mlx4: replace some offload flags with packet type
[dpdk.git] / drivers / net / mlx4 / mlx4.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright 2012-2015 6WIND S.A.
5  *   Copyright 2012 Mellanox.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of 6WIND S.A. nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 /*
35  * Known limitations:
36  * - RSS hash key and options cannot be modified.
37  * - Hardware counters aren't implemented.
38  */
39
40 /* System headers. */
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <stdint.h>
45 #include <inttypes.h>
46 #include <string.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <limits.h>
50 #include <assert.h>
51 #include <arpa/inet.h>
52 #include <net/if.h>
53 #include <dirent.h>
54 #include <sys/ioctl.h>
55 #include <sys/socket.h>
56 #include <netinet/in.h>
57 #include <linux/if.h>
58 #include <linux/ethtool.h>
59 #include <linux/sockios.h>
60
61 /* Verbs header. */
62 /* ISO C doesn't support unnamed structs/unions, disabling -pedantic. */
63 #ifdef PEDANTIC
64 #pragma GCC diagnostic ignored "-pedantic"
65 #endif
66 #include <infiniband/verbs.h>
67 #ifdef PEDANTIC
68 #pragma GCC diagnostic error "-pedantic"
69 #endif
70
71 /* DPDK headers don't like -pedantic. */
72 #ifdef PEDANTIC
73 #pragma GCC diagnostic ignored "-pedantic"
74 #endif
75 #include <rte_config.h>
76 #include <rte_ether.h>
77 #include <rte_ethdev.h>
78 #include <rte_dev.h>
79 #include <rte_mbuf.h>
80 #include <rte_errno.h>
81 #include <rte_mempool.h>
82 #include <rte_prefetch.h>
83 #include <rte_malloc.h>
84 #include <rte_spinlock.h>
85 #include <rte_atomic.h>
86 #include <rte_version.h>
87 #include <rte_log.h>
88 #ifdef PEDANTIC
89 #pragma GCC diagnostic error "-pedantic"
90 #endif
91
92 /* Generated configuration header. */
93 #include "mlx4_autoconf.h"
94
95 /* PMD header. */
96 #include "mlx4.h"
97
98 /* Runtime logging through RTE_LOG() is enabled when not in debugging mode.
99  * Intermediate LOG_*() macros add the required end-of-line characters. */
100 #ifndef NDEBUG
101 #define INFO(...) DEBUG(__VA_ARGS__)
102 #define WARN(...) DEBUG(__VA_ARGS__)
103 #define ERROR(...) DEBUG(__VA_ARGS__)
104 #else
105 #define LOG__(level, m, ...) \
106         RTE_LOG(level, PMD, MLX4_DRIVER_NAME ": " m "%c", __VA_ARGS__)
107 #define LOG_(level, ...) LOG__(level, __VA_ARGS__, '\n')
108 #define INFO(...) LOG_(INFO, __VA_ARGS__)
109 #define WARN(...) LOG_(WARNING, __VA_ARGS__)
110 #define ERROR(...) LOG_(ERR, __VA_ARGS__)
111 #endif
112
113 /* Convenience macros for accessing mbuf fields. */
114 #define NEXT(m) ((m)->next)
115 #define DATA_LEN(m) ((m)->data_len)
116 #define PKT_LEN(m) ((m)->pkt_len)
117 #define DATA_OFF(m) ((m)->data_off)
118 #define SET_DATA_OFF(m, o) ((m)->data_off = (o))
119 #define NB_SEGS(m) ((m)->nb_segs)
120 #define PORT(m) ((m)->port)
121
122 /* Work Request ID data type (64 bit). */
123 typedef union {
124         struct {
125                 uint32_t id;
126                 uint16_t offset;
127         } data;
128         uint64_t raw;
129 } wr_id_t;
130
131 #define WR_ID(o) (((wr_id_t *)&(o))->data)
132
133 /* Compile-time check. */
134 static inline void wr_id_t_check(void)
135 {
136         wr_id_t check[1 + (2 * -!(sizeof(wr_id_t) == sizeof(uint64_t)))];
137
138         (void)check;
139         (void)wr_id_t_check;
140 }
141
142 /* Transpose flags. Useful to convert IBV to DPDK flags. */
143 #define TRANSPOSE(val, from, to) \
144         (((from) >= (to)) ? \
145          (((val) & (from)) / ((from) / (to))) : \
146          (((val) & (from)) * ((to) / (from))))
147
148 struct mlx4_rxq_stats {
149         unsigned int idx; /**< Mapping index. */
150 #ifdef MLX4_PMD_SOFT_COUNTERS
151         uint64_t ipackets;  /**< Total of successfully received packets. */
152         uint64_t ibytes;    /**< Total of successfully received bytes. */
153 #endif
154         uint64_t idropped;  /**< Total of packets dropped when RX ring full. */
155         uint64_t rx_nombuf; /**< Total of RX mbuf allocation failures. */
156 };
157
158 struct mlx4_txq_stats {
159         unsigned int idx; /**< Mapping index. */
160 #ifdef MLX4_PMD_SOFT_COUNTERS
161         uint64_t opackets; /**< Total of successfully sent packets. */
162         uint64_t obytes;   /**< Total of successfully sent bytes. */
163 #endif
164         uint64_t odropped; /**< Total of packets not sent when TX ring full. */
165 };
166
167 /* RX element (scattered packets). */
168 struct rxq_elt_sp {
169         struct ibv_recv_wr wr; /* Work Request. */
170         struct ibv_sge sges[MLX4_PMD_SGE_WR_N]; /* Scatter/Gather Elements. */
171         struct rte_mbuf *bufs[MLX4_PMD_SGE_WR_N]; /* SGEs buffers. */
172 };
173
174 /* RX element. */
175 struct rxq_elt {
176         struct ibv_recv_wr wr; /* Work Request. */
177         struct ibv_sge sge; /* Scatter/Gather Element. */
178         /* mbuf pointer is derived from WR_ID(wr.wr_id).offset. */
179 };
180
181 /* RX queue descriptor. */
182 struct rxq {
183         struct priv *priv; /* Back pointer to private data. */
184         struct rte_mempool *mp; /* Memory Pool for allocations. */
185         struct ibv_mr *mr; /* Memory Region (for mp). */
186         struct ibv_cq *cq; /* Completion Queue. */
187         struct ibv_qp *qp; /* Queue Pair. */
188         struct ibv_exp_qp_burst_family *if_qp; /* QP burst interface. */
189         struct ibv_exp_cq_family *if_cq; /* CQ interface. */
190         /*
191          * Each VLAN ID requires a separate flow steering rule.
192          */
193         BITFIELD_DECLARE(mac_configured, uint32_t, MLX4_MAX_MAC_ADDRESSES);
194         struct ibv_flow *mac_flow[MLX4_MAX_MAC_ADDRESSES][MLX4_MAX_VLAN_IDS];
195         struct ibv_flow *promisc_flow; /* Promiscuous flow. */
196         struct ibv_flow *allmulti_flow; /* Multicast flow. */
197         unsigned int port_id; /* Port ID for incoming packets. */
198         unsigned int elts_n; /* (*elts)[] length. */
199         unsigned int elts_head; /* Current index in (*elts)[]. */
200         union {
201                 struct rxq_elt_sp (*sp)[]; /* Scattered RX elements. */
202                 struct rxq_elt (*no_sp)[]; /* RX elements. */
203         } elts;
204         unsigned int sp:1; /* Use scattered RX elements. */
205         unsigned int csum:1; /* Enable checksum offloading. */
206         unsigned int csum_l2tun:1; /* Same for L2 tunnels. */
207         uint32_t mb_len; /* Length of a mp-issued mbuf. */
208         struct mlx4_rxq_stats stats; /* RX queue counters. */
209         unsigned int socket; /* CPU socket ID for allocations. */
210         struct ibv_exp_res_domain *rd; /* Resource Domain. */
211 };
212
213 /* TX element. */
214 struct txq_elt {
215         struct rte_mbuf *buf;
216 };
217
218 /* Linear buffer type. It is used when transmitting buffers with too many
219  * segments that do not fit the hardware queue (see max_send_sge).
220  * Extra segments are copied (linearized) in such buffers, replacing the
221  * last SGE during TX.
222  * The size is arbitrary but large enough to hold a jumbo frame with
223  * 8 segments considering mbuf.buf_len is about 2048 bytes. */
224 typedef uint8_t linear_t[16384];
225
226 /* TX queue descriptor. */
227 struct txq {
228         struct priv *priv; /* Back pointer to private data. */
229         struct {
230                 struct rte_mempool *mp; /* Cached Memory Pool. */
231                 struct ibv_mr *mr; /* Memory Region (for mp). */
232                 uint32_t lkey; /* mr->lkey */
233         } mp2mr[MLX4_PMD_TX_MP_CACHE]; /* MP to MR translation table. */
234         struct ibv_cq *cq; /* Completion Queue. */
235         struct ibv_qp *qp; /* Queue Pair. */
236         struct ibv_exp_qp_burst_family *if_qp; /* QP burst interface. */
237         struct ibv_exp_cq_family *if_cq; /* CQ interface. */
238 #if MLX4_PMD_MAX_INLINE > 0
239         uint32_t max_inline; /* Max inline send size <= MLX4_PMD_MAX_INLINE. */
240 #endif
241         unsigned int elts_n; /* (*elts)[] length. */
242         struct txq_elt (*elts)[]; /* TX elements. */
243         unsigned int elts_head; /* Current index in (*elts)[]. */
244         unsigned int elts_tail; /* First element awaiting completion. */
245         unsigned int elts_comp; /* Number of completion requests. */
246         unsigned int elts_comp_cd; /* Countdown for next completion request. */
247         unsigned int elts_comp_cd_init; /* Initial value for countdown. */
248         struct mlx4_txq_stats stats; /* TX queue counters. */
249         linear_t (*elts_linear)[]; /* Linearized buffers. */
250         struct ibv_mr *mr_linear; /* Memory Region for linearized buffers. */
251         unsigned int socket; /* CPU socket ID for allocations. */
252         struct ibv_exp_res_domain *rd; /* Resource Domain. */
253 };
254
255 struct priv {
256         struct rte_eth_dev *dev; /* Ethernet device. */
257         struct ibv_context *ctx; /* Verbs context. */
258         struct ibv_device_attr device_attr; /* Device properties. */
259         struct ibv_pd *pd; /* Protection Domain. */
260         /*
261          * MAC addresses array and configuration bit-field.
262          * An extra entry that cannot be modified by the DPDK is reserved
263          * for broadcast frames (destination MAC address ff:ff:ff:ff:ff:ff).
264          */
265         struct ether_addr mac[MLX4_MAX_MAC_ADDRESSES];
266         BITFIELD_DECLARE(mac_configured, uint32_t, MLX4_MAX_MAC_ADDRESSES);
267         /* VLAN filters. */
268         struct {
269                 unsigned int enabled:1; /* If enabled. */
270                 unsigned int id:12; /* VLAN ID (0-4095). */
271         } vlan_filter[MLX4_MAX_VLAN_IDS]; /* VLAN filters table. */
272         /* Device properties. */
273         uint16_t mtu; /* Configured MTU. */
274         uint8_t port; /* Physical port number. */
275         unsigned int started:1; /* Device started, flows enabled. */
276         unsigned int promisc:1; /* Device in promiscuous mode. */
277         unsigned int allmulti:1; /* Device receives all multicast packets. */
278         unsigned int hw_qpg:1; /* QP groups are supported. */
279         unsigned int hw_tss:1; /* TSS is supported. */
280         unsigned int hw_rss:1; /* RSS is supported. */
281         unsigned int hw_csum:1; /* Checksum offload is supported. */
282         unsigned int hw_csum_l2tun:1; /* Same for L2 tunnels. */
283         unsigned int rss:1; /* RSS is enabled. */
284         unsigned int vf:1; /* This is a VF device. */
285 #ifdef INLINE_RECV
286         unsigned int inl_recv_size; /* Inline recv size */
287 #endif
288         unsigned int max_rss_tbl_sz; /* Maximum number of RSS queues. */
289         /* RX/TX queues. */
290         struct rxq rxq_parent; /* Parent queue when RSS is enabled. */
291         unsigned int rxqs_n; /* RX queues array size. */
292         unsigned int txqs_n; /* TX queues array size. */
293         struct rxq *(*rxqs)[]; /* RX queues. */
294         struct txq *(*txqs)[]; /* TX queues. */
295         rte_spinlock_t lock; /* Lock for control functions. */
296 };
297
298 /**
299  * Lock private structure to protect it from concurrent access in the
300  * control path.
301  *
302  * @param priv
303  *   Pointer to private structure.
304  */
305 static void
306 priv_lock(struct priv *priv)
307 {
308         rte_spinlock_lock(&priv->lock);
309 }
310
311 /**
312  * Unlock private structure.
313  *
314  * @param priv
315  *   Pointer to private structure.
316  */
317 static void
318 priv_unlock(struct priv *priv)
319 {
320         rte_spinlock_unlock(&priv->lock);
321 }
322
323 /* Allocate a buffer on the stack and fill it with a printf format string. */
324 #define MKSTR(name, ...) \
325         char name[snprintf(NULL, 0, __VA_ARGS__) + 1]; \
326         \
327         snprintf(name, sizeof(name), __VA_ARGS__)
328
329 /**
330  * Get interface name from private structure.
331  *
332  * @param[in] priv
333  *   Pointer to private structure.
334  * @param[out] ifname
335  *   Interface name output buffer.
336  *
337  * @return
338  *   0 on success, -1 on failure and errno is set.
339  */
340 static int
341 priv_get_ifname(const struct priv *priv, char (*ifname)[IF_NAMESIZE])
342 {
343         DIR *dir;
344         struct dirent *dent;
345         unsigned int dev_type = 0;
346         unsigned int dev_port_prev = ~0u;
347         char match[IF_NAMESIZE] = "";
348
349         {
350                 MKSTR(path, "%s/device/net", priv->ctx->device->ibdev_path);
351
352                 dir = opendir(path);
353                 if (dir == NULL)
354                         return -1;
355         }
356         while ((dent = readdir(dir)) != NULL) {
357                 char *name = dent->d_name;
358                 FILE *file;
359                 unsigned int dev_port;
360                 int r;
361
362                 if ((name[0] == '.') &&
363                     ((name[1] == '\0') ||
364                      ((name[1] == '.') && (name[2] == '\0'))))
365                         continue;
366
367                 MKSTR(path, "%s/device/net/%s/%s",
368                       priv->ctx->device->ibdev_path, name,
369                       (dev_type ? "dev_id" : "dev_port"));
370
371                 file = fopen(path, "rb");
372                 if (file == NULL) {
373                         if (errno != ENOENT)
374                                 continue;
375                         /*
376                          * Switch to dev_id when dev_port does not exist as
377                          * is the case with Linux kernel versions < 3.15.
378                          */
379 try_dev_id:
380                         match[0] = '\0';
381                         if (dev_type)
382                                 break;
383                         dev_type = 1;
384                         dev_port_prev = ~0u;
385                         rewinddir(dir);
386                         continue;
387                 }
388                 r = fscanf(file, (dev_type ? "%x" : "%u"), &dev_port);
389                 fclose(file);
390                 if (r != 1)
391                         continue;
392                 /*
393                  * Switch to dev_id when dev_port returns the same value for
394                  * all ports. May happen when using a MOFED release older than
395                  * 3.0 with a Linux kernel >= 3.15.
396                  */
397                 if (dev_port == dev_port_prev)
398                         goto try_dev_id;
399                 dev_port_prev = dev_port;
400                 if (dev_port == (priv->port - 1u))
401                         snprintf(match, sizeof(match), "%s", name);
402         }
403         closedir(dir);
404         if (match[0] == '\0')
405                 return -1;
406         strncpy(*ifname, match, sizeof(*ifname));
407         return 0;
408 }
409
410 /**
411  * Read from sysfs entry.
412  *
413  * @param[in] priv
414  *   Pointer to private structure.
415  * @param[in] entry
416  *   Entry name relative to sysfs path.
417  * @param[out] buf
418  *   Data output buffer.
419  * @param size
420  *   Buffer size.
421  *
422  * @return
423  *   0 on success, -1 on failure and errno is set.
424  */
425 static int
426 priv_sysfs_read(const struct priv *priv, const char *entry,
427                 char *buf, size_t size)
428 {
429         char ifname[IF_NAMESIZE];
430         FILE *file;
431         int ret;
432         int err;
433
434         if (priv_get_ifname(priv, &ifname))
435                 return -1;
436
437         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
438               ifname, entry);
439
440         file = fopen(path, "rb");
441         if (file == NULL)
442                 return -1;
443         ret = fread(buf, 1, size, file);
444         err = errno;
445         if (((size_t)ret < size) && (ferror(file)))
446                 ret = -1;
447         else
448                 ret = size;
449         fclose(file);
450         errno = err;
451         return ret;
452 }
453
454 /**
455  * Write to sysfs entry.
456  *
457  * @param[in] priv
458  *   Pointer to private structure.
459  * @param[in] entry
460  *   Entry name relative to sysfs path.
461  * @param[in] buf
462  *   Data buffer.
463  * @param size
464  *   Buffer size.
465  *
466  * @return
467  *   0 on success, -1 on failure and errno is set.
468  */
469 static int
470 priv_sysfs_write(const struct priv *priv, const char *entry,
471                  char *buf, size_t size)
472 {
473         char ifname[IF_NAMESIZE];
474         FILE *file;
475         int ret;
476         int err;
477
478         if (priv_get_ifname(priv, &ifname))
479                 return -1;
480
481         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
482               ifname, entry);
483
484         file = fopen(path, "wb");
485         if (file == NULL)
486                 return -1;
487         ret = fwrite(buf, 1, size, file);
488         err = errno;
489         if (((size_t)ret < size) || (ferror(file)))
490                 ret = -1;
491         else
492                 ret = size;
493         fclose(file);
494         errno = err;
495         return ret;
496 }
497
498 /**
499  * Get unsigned long sysfs property.
500  *
501  * @param priv
502  *   Pointer to private structure.
503  * @param[in] name
504  *   Entry name relative to sysfs path.
505  * @param[out] value
506  *   Value output buffer.
507  *
508  * @return
509  *   0 on success, -1 on failure and errno is set.
510  */
511 static int
512 priv_get_sysfs_ulong(struct priv *priv, const char *name, unsigned long *value)
513 {
514         int ret;
515         unsigned long value_ret;
516         char value_str[32];
517
518         ret = priv_sysfs_read(priv, name, value_str, (sizeof(value_str) - 1));
519         if (ret == -1) {
520                 DEBUG("cannot read %s value from sysfs: %s",
521                       name, strerror(errno));
522                 return -1;
523         }
524         value_str[ret] = '\0';
525         errno = 0;
526         value_ret = strtoul(value_str, NULL, 0);
527         if (errno) {
528                 DEBUG("invalid %s value `%s': %s", name, value_str,
529                       strerror(errno));
530                 return -1;
531         }
532         *value = value_ret;
533         return 0;
534 }
535
536 /**
537  * Set unsigned long sysfs property.
538  *
539  * @param priv
540  *   Pointer to private structure.
541  * @param[in] name
542  *   Entry name relative to sysfs path.
543  * @param value
544  *   Value to set.
545  *
546  * @return
547  *   0 on success, -1 on failure and errno is set.
548  */
549 static int
550 priv_set_sysfs_ulong(struct priv *priv, const char *name, unsigned long value)
551 {
552         int ret;
553         MKSTR(value_str, "%lu", value);
554
555         ret = priv_sysfs_write(priv, name, value_str, (sizeof(value_str) - 1));
556         if (ret == -1) {
557                 DEBUG("cannot write %s `%s' (%lu) to sysfs: %s",
558                       name, value_str, value, strerror(errno));
559                 return -1;
560         }
561         return 0;
562 }
563
564 /**
565  * Perform ifreq ioctl() on associated Ethernet device.
566  *
567  * @param[in] priv
568  *   Pointer to private structure.
569  * @param req
570  *   Request number to pass to ioctl().
571  * @param[out] ifr
572  *   Interface request structure output buffer.
573  *
574  * @return
575  *   0 on success, -1 on failure and errno is set.
576  */
577 static int
578 priv_ifreq(const struct priv *priv, int req, struct ifreq *ifr)
579 {
580         int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
581         int ret = -1;
582
583         if (sock == -1)
584                 return ret;
585         if (priv_get_ifname(priv, &ifr->ifr_name) == 0)
586                 ret = ioctl(sock, req, ifr);
587         close(sock);
588         return ret;
589 }
590
591 /**
592  * Get device MTU.
593  *
594  * @param priv
595  *   Pointer to private structure.
596  * @param[out] mtu
597  *   MTU value output buffer.
598  *
599  * @return
600  *   0 on success, -1 on failure and errno is set.
601  */
602 static int
603 priv_get_mtu(struct priv *priv, uint16_t *mtu)
604 {
605         unsigned long ulong_mtu;
606
607         if (priv_get_sysfs_ulong(priv, "mtu", &ulong_mtu) == -1)
608                 return -1;
609         *mtu = ulong_mtu;
610         return 0;
611 }
612
613 /**
614  * Set device MTU.
615  *
616  * @param priv
617  *   Pointer to private structure.
618  * @param mtu
619  *   MTU value to set.
620  *
621  * @return
622  *   0 on success, -1 on failure and errno is set.
623  */
624 static int
625 priv_set_mtu(struct priv *priv, uint16_t mtu)
626 {
627         return priv_set_sysfs_ulong(priv, "mtu", mtu);
628 }
629
630 /**
631  * Set device flags.
632  *
633  * @param priv
634  *   Pointer to private structure.
635  * @param keep
636  *   Bitmask for flags that must remain untouched.
637  * @param flags
638  *   Bitmask for flags to modify.
639  *
640  * @return
641  *   0 on success, -1 on failure and errno is set.
642  */
643 static int
644 priv_set_flags(struct priv *priv, unsigned int keep, unsigned int flags)
645 {
646         unsigned long tmp;
647
648         if (priv_get_sysfs_ulong(priv, "flags", &tmp) == -1)
649                 return -1;
650         tmp &= keep;
651         tmp |= flags;
652         return priv_set_sysfs_ulong(priv, "flags", tmp);
653 }
654
655 /* Device configuration. */
656
657 static int
658 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
659           unsigned int socket, const struct rte_eth_rxconf *conf,
660           struct rte_mempool *mp);
661
662 static void
663 rxq_cleanup(struct rxq *rxq);
664
665 /**
666  * Ethernet device configuration.
667  *
668  * Prepare the driver for a given number of TX and RX queues.
669  * Allocate parent RSS queue when several RX queues are requested.
670  *
671  * @param dev
672  *   Pointer to Ethernet device structure.
673  *
674  * @return
675  *   0 on success, errno value on failure.
676  */
677 static int
678 dev_configure(struct rte_eth_dev *dev)
679 {
680         struct priv *priv = dev->data->dev_private;
681         unsigned int rxqs_n = dev->data->nb_rx_queues;
682         unsigned int txqs_n = dev->data->nb_tx_queues;
683         unsigned int tmp;
684         int ret;
685
686         priv->rxqs = (void *)dev->data->rx_queues;
687         priv->txqs = (void *)dev->data->tx_queues;
688         if (txqs_n != priv->txqs_n) {
689                 INFO("%p: TX queues number update: %u -> %u",
690                      (void *)dev, priv->txqs_n, txqs_n);
691                 priv->txqs_n = txqs_n;
692         }
693         if (rxqs_n == priv->rxqs_n)
694                 return 0;
695         INFO("%p: RX queues number update: %u -> %u",
696              (void *)dev, priv->rxqs_n, rxqs_n);
697         /* If RSS is enabled, disable it first. */
698         if (priv->rss) {
699                 unsigned int i;
700
701                 /* Only if there are no remaining child RX queues. */
702                 for (i = 0; (i != priv->rxqs_n); ++i)
703                         if ((*priv->rxqs)[i] != NULL)
704                                 return EINVAL;
705                 rxq_cleanup(&priv->rxq_parent);
706                 priv->rss = 0;
707                 priv->rxqs_n = 0;
708         }
709         if (rxqs_n <= 1) {
710                 /* Nothing else to do. */
711                 priv->rxqs_n = rxqs_n;
712                 return 0;
713         }
714         /* Allocate a new RSS parent queue if supported by hardware. */
715         if (!priv->hw_rss) {
716                 ERROR("%p: only a single RX queue can be configured when"
717                       " hardware doesn't support RSS",
718                       (void *)dev);
719                 return EINVAL;
720         }
721         /* Fail if hardware doesn't support that many RSS queues. */
722         if (rxqs_n >= priv->max_rss_tbl_sz) {
723                 ERROR("%p: only %u RX queues can be configured for RSS",
724                       (void *)dev, priv->max_rss_tbl_sz);
725                 return EINVAL;
726         }
727         priv->rss = 1;
728         tmp = priv->rxqs_n;
729         priv->rxqs_n = rxqs_n;
730         ret = rxq_setup(dev, &priv->rxq_parent, 0, 0, NULL, NULL);
731         if (!ret)
732                 return 0;
733         /* Failure, rollback. */
734         priv->rss = 0;
735         priv->rxqs_n = tmp;
736         assert(ret > 0);
737         return ret;
738 }
739
740 /**
741  * DPDK callback for Ethernet device configuration.
742  *
743  * @param dev
744  *   Pointer to Ethernet device structure.
745  *
746  * @return
747  *   0 on success, negative errno value on failure.
748  */
749 static int
750 mlx4_dev_configure(struct rte_eth_dev *dev)
751 {
752         struct priv *priv = dev->data->dev_private;
753         int ret;
754
755         priv_lock(priv);
756         ret = dev_configure(dev);
757         assert(ret >= 0);
758         priv_unlock(priv);
759         return -ret;
760 }
761
762 /* TX queues handling. */
763
764 /**
765  * Allocate TX queue elements.
766  *
767  * @param txq
768  *   Pointer to TX queue structure.
769  * @param elts_n
770  *   Number of elements to allocate.
771  *
772  * @return
773  *   0 on success, errno value on failure.
774  */
775 static int
776 txq_alloc_elts(struct txq *txq, unsigned int elts_n)
777 {
778         unsigned int i;
779         struct txq_elt (*elts)[elts_n] =
780                 rte_calloc_socket("TXQ", 1, sizeof(*elts), 0, txq->socket);
781         linear_t (*elts_linear)[elts_n] =
782                 rte_calloc_socket("TXQ", 1, sizeof(*elts_linear), 0,
783                                   txq->socket);
784         struct ibv_mr *mr_linear = NULL;
785         int ret = 0;
786
787         if ((elts == NULL) || (elts_linear == NULL)) {
788                 ERROR("%p: can't allocate packets array", (void *)txq);
789                 ret = ENOMEM;
790                 goto error;
791         }
792         mr_linear =
793                 ibv_reg_mr(txq->priv->pd, elts_linear, sizeof(*elts_linear),
794                            (IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE));
795         if (mr_linear == NULL) {
796                 ERROR("%p: unable to configure MR, ibv_reg_mr() failed",
797                       (void *)txq);
798                 ret = EINVAL;
799                 goto error;
800         }
801         for (i = 0; (i != elts_n); ++i) {
802                 struct txq_elt *elt = &(*elts)[i];
803
804                 elt->buf = NULL;
805         }
806         DEBUG("%p: allocated and configured %u WRs", (void *)txq, elts_n);
807         txq->elts_n = elts_n;
808         txq->elts = elts;
809         txq->elts_head = 0;
810         txq->elts_tail = 0;
811         txq->elts_comp = 0;
812         /* Request send completion every MLX4_PMD_TX_PER_COMP_REQ packets or
813          * at least 4 times per ring. */
814         txq->elts_comp_cd_init =
815                 ((MLX4_PMD_TX_PER_COMP_REQ < (elts_n / 4)) ?
816                  MLX4_PMD_TX_PER_COMP_REQ : (elts_n / 4));
817         txq->elts_comp_cd = txq->elts_comp_cd_init;
818         txq->elts_linear = elts_linear;
819         txq->mr_linear = mr_linear;
820         assert(ret == 0);
821         return 0;
822 error:
823         if (mr_linear != NULL)
824                 claim_zero(ibv_dereg_mr(mr_linear));
825
826         rte_free(elts_linear);
827         rte_free(elts);
828
829         DEBUG("%p: failed, freed everything", (void *)txq);
830         assert(ret > 0);
831         return ret;
832 }
833
834 /**
835  * Free TX queue elements.
836  *
837  * @param txq
838  *   Pointer to TX queue structure.
839  */
840 static void
841 txq_free_elts(struct txq *txq)
842 {
843         unsigned int i;
844         unsigned int elts_n = txq->elts_n;
845         struct txq_elt (*elts)[elts_n] = txq->elts;
846         linear_t (*elts_linear)[elts_n] = txq->elts_linear;
847         struct ibv_mr *mr_linear = txq->mr_linear;
848
849         DEBUG("%p: freeing WRs", (void *)txq);
850         txq->elts_n = 0;
851         txq->elts = NULL;
852         txq->elts_linear = NULL;
853         txq->mr_linear = NULL;
854         if (mr_linear != NULL)
855                 claim_zero(ibv_dereg_mr(mr_linear));
856
857         rte_free(elts_linear);
858         if (elts == NULL)
859                 return;
860         for (i = 0; (i != elemof(*elts)); ++i) {
861                 struct txq_elt *elt = &(*elts)[i];
862
863                 if (elt->buf == NULL)
864                         continue;
865                 rte_pktmbuf_free(elt->buf);
866         }
867         rte_free(elts);
868 }
869
870
871 /**
872  * Clean up a TX queue.
873  *
874  * Destroy objects, free allocated memory and reset the structure for reuse.
875  *
876  * @param txq
877  *   Pointer to TX queue structure.
878  */
879 static void
880 txq_cleanup(struct txq *txq)
881 {
882         struct ibv_exp_release_intf_params params;
883         size_t i;
884
885         DEBUG("cleaning up %p", (void *)txq);
886         txq_free_elts(txq);
887         if (txq->if_qp != NULL) {
888                 assert(txq->priv != NULL);
889                 assert(txq->priv->ctx != NULL);
890                 assert(txq->qp != NULL);
891                 params = (struct ibv_exp_release_intf_params){
892                         .comp_mask = 0,
893                 };
894                 claim_zero(ibv_exp_release_intf(txq->priv->ctx,
895                                                 txq->if_qp,
896                                                 &params));
897         }
898         if (txq->if_cq != NULL) {
899                 assert(txq->priv != NULL);
900                 assert(txq->priv->ctx != NULL);
901                 assert(txq->cq != NULL);
902                 params = (struct ibv_exp_release_intf_params){
903                         .comp_mask = 0,
904                 };
905                 claim_zero(ibv_exp_release_intf(txq->priv->ctx,
906                                                 txq->if_cq,
907                                                 &params));
908         }
909         if (txq->qp != NULL)
910                 claim_zero(ibv_destroy_qp(txq->qp));
911         if (txq->cq != NULL)
912                 claim_zero(ibv_destroy_cq(txq->cq));
913         if (txq->rd != NULL) {
914                 struct ibv_exp_destroy_res_domain_attr attr = {
915                         .comp_mask = 0,
916                 };
917
918                 assert(txq->priv != NULL);
919                 assert(txq->priv->ctx != NULL);
920                 claim_zero(ibv_exp_destroy_res_domain(txq->priv->ctx,
921                                                       txq->rd,
922                                                       &attr));
923         }
924         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
925                 if (txq->mp2mr[i].mp == NULL)
926                         break;
927                 assert(txq->mp2mr[i].mr != NULL);
928                 claim_zero(ibv_dereg_mr(txq->mp2mr[i].mr));
929         }
930         memset(txq, 0, sizeof(*txq));
931 }
932
933 /**
934  * Manage TX completions.
935  *
936  * When sending a burst, mlx4_tx_burst() posts several WRs.
937  * To improve performance, a completion event is only required once every
938  * MLX4_PMD_TX_PER_COMP_REQ sends. Doing so discards completion information
939  * for other WRs, but this information would not be used anyway.
940  *
941  * @param txq
942  *   Pointer to TX queue structure.
943  *
944  * @return
945  *   0 on success, -1 on failure.
946  */
947 static int
948 txq_complete(struct txq *txq)
949 {
950         unsigned int elts_comp = txq->elts_comp;
951         unsigned int elts_tail = txq->elts_tail;
952         const unsigned int elts_n = txq->elts_n;
953         int wcs_n;
954
955         if (unlikely(elts_comp == 0))
956                 return 0;
957 #ifdef DEBUG_SEND
958         DEBUG("%p: processing %u work requests completions",
959               (void *)txq, elts_comp);
960 #endif
961         wcs_n = txq->if_cq->poll_cnt(txq->cq, elts_comp);
962         if (unlikely(wcs_n == 0))
963                 return 0;
964         if (unlikely(wcs_n < 0)) {
965                 DEBUG("%p: ibv_poll_cq() failed (wcs_n=%d)",
966                       (void *)txq, wcs_n);
967                 return -1;
968         }
969         elts_comp -= wcs_n;
970         assert(elts_comp <= txq->elts_comp);
971         /*
972          * Assume WC status is successful as nothing can be done about it
973          * anyway.
974          */
975         elts_tail += wcs_n * txq->elts_comp_cd_init;
976         if (elts_tail >= elts_n)
977                 elts_tail -= elts_n;
978         txq->elts_tail = elts_tail;
979         txq->elts_comp = elts_comp;
980         return 0;
981 }
982
983 /**
984  * Get Memory Region (MR) <-> Memory Pool (MP) association from txq->mp2mr[].
985  * Add MP to txq->mp2mr[] if it's not registered yet. If mp2mr[] is full,
986  * remove an entry first.
987  *
988  * @param txq
989  *   Pointer to TX queue structure.
990  * @param[in] mp
991  *   Memory Pool for which a Memory Region lkey must be returned.
992  *
993  * @return
994  *   mr->lkey on success, (uint32_t)-1 on failure.
995  */
996 static uint32_t
997 txq_mp2mr(struct txq *txq, struct rte_mempool *mp)
998 {
999         unsigned int i;
1000         struct ibv_mr *mr;
1001
1002         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
1003                 if (unlikely(txq->mp2mr[i].mp == NULL)) {
1004                         /* Unknown MP, add a new MR for it. */
1005                         break;
1006                 }
1007                 if (txq->mp2mr[i].mp == mp) {
1008                         assert(txq->mp2mr[i].lkey != (uint32_t)-1);
1009                         assert(txq->mp2mr[i].mr->lkey == txq->mp2mr[i].lkey);
1010                         return txq->mp2mr[i].lkey;
1011                 }
1012         }
1013         /* Add a new entry, register MR first. */
1014         DEBUG("%p: discovered new memory pool %p", (void *)txq, (void *)mp);
1015         mr = ibv_reg_mr(txq->priv->pd,
1016                         (void *)mp->elt_va_start,
1017                         (mp->elt_va_end - mp->elt_va_start),
1018                         (IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE));
1019         if (unlikely(mr == NULL)) {
1020                 DEBUG("%p: unable to configure MR, ibv_reg_mr() failed.",
1021                       (void *)txq);
1022                 return (uint32_t)-1;
1023         }
1024         if (unlikely(i == elemof(txq->mp2mr))) {
1025                 /* Table is full, remove oldest entry. */
1026                 DEBUG("%p: MR <-> MP table full, dropping oldest entry.",
1027                       (void *)txq);
1028                 --i;
1029                 claim_zero(ibv_dereg_mr(txq->mp2mr[i].mr));
1030                 memmove(&txq->mp2mr[0], &txq->mp2mr[1],
1031                         (sizeof(txq->mp2mr) - sizeof(txq->mp2mr[0])));
1032         }
1033         /* Store the new entry. */
1034         txq->mp2mr[i].mp = mp;
1035         txq->mp2mr[i].mr = mr;
1036         txq->mp2mr[i].lkey = mr->lkey;
1037         DEBUG("%p: new MR lkey for MP %p: 0x%08" PRIu32,
1038               (void *)txq, (void *)mp, txq->mp2mr[i].lkey);
1039         return txq->mp2mr[i].lkey;
1040 }
1041
1042 #if MLX4_PMD_SGE_WR_N > 1
1043
1044 /**
1045  * Copy scattered mbuf contents to a single linear buffer.
1046  *
1047  * @param[out] linear
1048  *   Linear output buffer.
1049  * @param[in] buf
1050  *   Scattered input buffer.
1051  *
1052  * @return
1053  *   Number of bytes copied to the output buffer or 0 if not large enough.
1054  */
1055 static unsigned int
1056 linearize_mbuf(linear_t *linear, struct rte_mbuf *buf)
1057 {
1058         unsigned int size = 0;
1059         unsigned int offset;
1060
1061         do {
1062                 unsigned int len = DATA_LEN(buf);
1063
1064                 offset = size;
1065                 size += len;
1066                 if (unlikely(size > sizeof(*linear)))
1067                         return 0;
1068                 memcpy(&(*linear)[offset],
1069                        rte_pktmbuf_mtod(buf, uint8_t *),
1070                        len);
1071                 buf = NEXT(buf);
1072         } while (buf != NULL);
1073         return size;
1074 }
1075
1076 /**
1077  * Handle scattered buffers for mlx4_tx_burst().
1078  *
1079  * @param txq
1080  *   TX queue structure.
1081  * @param segs
1082  *   Number of segments in buf.
1083  * @param elt
1084  *   TX queue element to fill.
1085  * @param[in] buf
1086  *   Buffer to process.
1087  * @param elts_head
1088  *   Index of the linear buffer to use if necessary (normally txq->elts_head).
1089  * @param[out] sges
1090  *   Array filled with SGEs on success.
1091  *
1092  * @return
1093  *   A structure containing the processed packet size in bytes and the
1094  *   number of SGEs. Both fields are set to (unsigned int)-1 in case of
1095  *   failure.
1096  */
1097 static struct tx_burst_sg_ret {
1098         unsigned int length;
1099         unsigned int num;
1100 }
1101 tx_burst_sg(struct txq *txq, unsigned int segs, struct txq_elt *elt,
1102             struct rte_mbuf *buf, unsigned int elts_head,
1103             struct ibv_sge (*sges)[MLX4_PMD_SGE_WR_N])
1104 {
1105         unsigned int sent_size = 0;
1106         unsigned int j;
1107         int linearize = 0;
1108
1109         /* When there are too many segments, extra segments are
1110          * linearized in the last SGE. */
1111         if (unlikely(segs > elemof(*sges))) {
1112                 segs = (elemof(*sges) - 1);
1113                 linearize = 1;
1114         }
1115         /* Update element. */
1116         elt->buf = buf;
1117         /* Register segments as SGEs. */
1118         for (j = 0; (j != segs); ++j) {
1119                 struct ibv_sge *sge = &(*sges)[j];
1120                 uint32_t lkey;
1121
1122                 /* Retrieve Memory Region key for this memory pool. */
1123                 lkey = txq_mp2mr(txq, buf->pool);
1124                 if (unlikely(lkey == (uint32_t)-1)) {
1125                         /* MR does not exist. */
1126                         DEBUG("%p: unable to get MP <-> MR association",
1127                               (void *)txq);
1128                         /* Clean up TX element. */
1129                         elt->buf = NULL;
1130                         goto stop;
1131                 }
1132                 /* Update SGE. */
1133                 sge->addr = rte_pktmbuf_mtod(buf, uintptr_t);
1134                 if (txq->priv->vf)
1135                         rte_prefetch0((volatile void *)
1136                                       (uintptr_t)sge->addr);
1137                 sge->length = DATA_LEN(buf);
1138                 sge->lkey = lkey;
1139                 sent_size += sge->length;
1140                 buf = NEXT(buf);
1141         }
1142         /* If buf is not NULL here and is not going to be linearized,
1143          * nb_segs is not valid. */
1144         assert(j == segs);
1145         assert((buf == NULL) || (linearize));
1146         /* Linearize extra segments. */
1147         if (linearize) {
1148                 struct ibv_sge *sge = &(*sges)[segs];
1149                 linear_t *linear = &(*txq->elts_linear)[elts_head];
1150                 unsigned int size = linearize_mbuf(linear, buf);
1151
1152                 assert(segs == (elemof(*sges) - 1));
1153                 if (size == 0) {
1154                         /* Invalid packet. */
1155                         DEBUG("%p: packet too large to be linearized.",
1156                               (void *)txq);
1157                         /* Clean up TX element. */
1158                         elt->buf = NULL;
1159                         goto stop;
1160                 }
1161                 /* If MLX4_PMD_SGE_WR_N is 1, free mbuf immediately. */
1162                 if (elemof(*sges) == 1) {
1163                         do {
1164                                 struct rte_mbuf *next = NEXT(buf);
1165
1166                                 rte_pktmbuf_free_seg(buf);
1167                                 buf = next;
1168                         } while (buf != NULL);
1169                         elt->buf = NULL;
1170                 }
1171                 /* Update SGE. */
1172                 sge->addr = (uintptr_t)&(*linear)[0];
1173                 sge->length = size;
1174                 sge->lkey = txq->mr_linear->lkey;
1175                 sent_size += size;
1176         }
1177         return (struct tx_burst_sg_ret){
1178                 .length = sent_size,
1179                 .num = segs,
1180         };
1181 stop:
1182         return (struct tx_burst_sg_ret){
1183                 .length = -1,
1184                 .num = -1,
1185         };
1186 }
1187
1188 #endif /* MLX4_PMD_SGE_WR_N > 1 */
1189
1190 /**
1191  * DPDK callback for TX.
1192  *
1193  * @param dpdk_txq
1194  *   Generic pointer to TX queue structure.
1195  * @param[in] pkts
1196  *   Packets to transmit.
1197  * @param pkts_n
1198  *   Number of packets in array.
1199  *
1200  * @return
1201  *   Number of packets successfully transmitted (<= pkts_n).
1202  */
1203 static uint16_t
1204 mlx4_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
1205 {
1206         struct txq *txq = (struct txq *)dpdk_txq;
1207         unsigned int elts_head = txq->elts_head;
1208         const unsigned int elts_tail = txq->elts_tail;
1209         const unsigned int elts_n = txq->elts_n;
1210         unsigned int elts_comp_cd = txq->elts_comp_cd;
1211         unsigned int elts_comp = 0;
1212         unsigned int i;
1213         unsigned int max;
1214         int err;
1215
1216         assert(elts_comp_cd != 0);
1217         txq_complete(txq);
1218         max = (elts_n - (elts_head - elts_tail));
1219         if (max > elts_n)
1220                 max -= elts_n;
1221         assert(max >= 1);
1222         assert(max <= elts_n);
1223         /* Always leave one free entry in the ring. */
1224         --max;
1225         if (max == 0)
1226                 return 0;
1227         if (max > pkts_n)
1228                 max = pkts_n;
1229         for (i = 0; (i != max); ++i) {
1230                 struct rte_mbuf *buf = pkts[i];
1231                 unsigned int elts_head_next =
1232                         (((elts_head + 1) == elts_n) ? 0 : elts_head + 1);
1233                 struct txq_elt *elt_next = &(*txq->elts)[elts_head_next];
1234                 struct txq_elt *elt = &(*txq->elts)[elts_head];
1235                 unsigned int segs = NB_SEGS(buf);
1236 #ifdef MLX4_PMD_SOFT_COUNTERS
1237                 unsigned int sent_size = 0;
1238 #endif
1239                 uint32_t send_flags = 0;
1240
1241                 /* Clean up old buffer. */
1242                 if (likely(elt->buf != NULL)) {
1243                         struct rte_mbuf *tmp = elt->buf;
1244
1245                         /* Faster than rte_pktmbuf_free(). */
1246                         do {
1247                                 struct rte_mbuf *next = NEXT(tmp);
1248
1249                                 rte_pktmbuf_free_seg(tmp);
1250                                 tmp = next;
1251                         } while (tmp != NULL);
1252                 }
1253                 /* Request TX completion. */
1254                 if (unlikely(--elts_comp_cd == 0)) {
1255                         elts_comp_cd = txq->elts_comp_cd_init;
1256                         ++elts_comp;
1257                         send_flags |= IBV_EXP_QP_BURST_SIGNALED;
1258                 }
1259                 /* Should we enable HW CKSUM offload */
1260                 if (buf->ol_flags &
1261                     (PKT_TX_IP_CKSUM | PKT_TX_TCP_CKSUM | PKT_TX_UDP_CKSUM)) {
1262                         send_flags |= IBV_EXP_QP_BURST_IP_CSUM;
1263                         /* HW does not support checksum offloads at arbitrary
1264                          * offsets but automatically recognizes the packet
1265                          * type. For inner L3/L4 checksums, only VXLAN (UDP)
1266                          * tunnels are currently supported. */
1267 #ifdef RTE_NEXT_ABI
1268                         if (RTE_ETH_IS_TUNNEL_PKT(buf->packet_type))
1269 #else
1270                         /* FIXME: since PKT_TX_UDP_TUNNEL_PKT has been removed,
1271                          * the outer packet type is unknown. All we know is
1272                          * that the L2 header is of unusual length (not
1273                          * ETHER_HDR_LEN with or without 802.1Q header). */
1274                         if ((buf->l2_len != ETHER_HDR_LEN) &&
1275                             (buf->l2_len != (ETHER_HDR_LEN + 4)))
1276 #endif
1277                                 send_flags |= IBV_EXP_QP_BURST_TUNNEL;
1278                 }
1279                 if (likely(segs == 1)) {
1280                         uintptr_t addr;
1281                         uint32_t length;
1282                         uint32_t lkey;
1283
1284                         /* Retrieve buffer information. */
1285                         addr = rte_pktmbuf_mtod(buf, uintptr_t);
1286                         length = DATA_LEN(buf);
1287                         /* Retrieve Memory Region key for this memory pool. */
1288                         lkey = txq_mp2mr(txq, buf->pool);
1289                         if (unlikely(lkey == (uint32_t)-1)) {
1290                                 /* MR does not exist. */
1291                                 DEBUG("%p: unable to get MP <-> MR"
1292                                       " association", (void *)txq);
1293                                 /* Clean up TX element. */
1294                                 elt->buf = NULL;
1295                                 goto stop;
1296                         }
1297                         /* Update element. */
1298                         elt->buf = buf;
1299                         if (txq->priv->vf)
1300                                 rte_prefetch0((volatile void *)
1301                                               (uintptr_t)addr);
1302                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1303                         /* Put packet into send queue. */
1304 #if MLX4_PMD_MAX_INLINE > 0
1305                         if (length <= txq->max_inline)
1306                                 err = txq->if_qp->send_pending_inline
1307                                         (txq->qp,
1308                                          (void *)addr,
1309                                          length,
1310                                          send_flags);
1311                         else
1312 #endif
1313                                 err = txq->if_qp->send_pending
1314                                         (txq->qp,
1315                                          addr,
1316                                          length,
1317                                          lkey,
1318                                          send_flags);
1319                         if (unlikely(err))
1320                                 goto stop;
1321 #ifdef MLX4_PMD_SOFT_COUNTERS
1322                         sent_size += length;
1323 #endif
1324                 } else {
1325 #if MLX4_PMD_SGE_WR_N > 1
1326                         struct ibv_sge sges[MLX4_PMD_SGE_WR_N];
1327                         struct tx_burst_sg_ret ret;
1328
1329                         ret = tx_burst_sg(txq, segs, elt, buf, elts_head,
1330                                           &sges);
1331                         if (ret.length == (unsigned int)-1)
1332                                 goto stop;
1333                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1334                         /* Put SG list into send queue. */
1335                         err = txq->if_qp->send_pending_sg_list
1336                                 (txq->qp,
1337                                  sges,
1338                                  ret.num,
1339                                  send_flags);
1340                         if (unlikely(err))
1341                                 goto stop;
1342 #ifdef MLX4_PMD_SOFT_COUNTERS
1343                         sent_size += ret.length;
1344 #endif
1345 #else /* MLX4_PMD_SGE_WR_N > 1 */
1346                         DEBUG("%p: TX scattered buffers support not"
1347                               " compiled in", (void *)txq);
1348                         goto stop;
1349 #endif /* MLX4_PMD_SGE_WR_N > 1 */
1350                 }
1351                 elts_head = elts_head_next;
1352 #ifdef MLX4_PMD_SOFT_COUNTERS
1353                 /* Increment sent bytes counter. */
1354                 txq->stats.obytes += sent_size;
1355 #endif
1356         }
1357 stop:
1358         /* Take a shortcut if nothing must be sent. */
1359         if (unlikely(i == 0))
1360                 return 0;
1361 #ifdef MLX4_PMD_SOFT_COUNTERS
1362         /* Increment sent packets counter. */
1363         txq->stats.opackets += i;
1364 #endif
1365         /* Ring QP doorbell. */
1366         err = txq->if_qp->send_flush(txq->qp);
1367         if (unlikely(err)) {
1368                 /* A nonzero value is not supposed to be returned.
1369                  * Nothing can be done about it. */
1370                 DEBUG("%p: send_flush() failed with error %d",
1371                       (void *)txq, err);
1372         }
1373         txq->elts_head = elts_head;
1374         txq->elts_comp += elts_comp;
1375         txq->elts_comp_cd = elts_comp_cd;
1376         return i;
1377 }
1378
1379 /**
1380  * Configure a TX queue.
1381  *
1382  * @param dev
1383  *   Pointer to Ethernet device structure.
1384  * @param txq
1385  *   Pointer to TX queue structure.
1386  * @param desc
1387  *   Number of descriptors to configure in queue.
1388  * @param socket
1389  *   NUMA socket on which memory must be allocated.
1390  * @param[in] conf
1391  *   Thresholds parameters.
1392  *
1393  * @return
1394  *   0 on success, errno value on failure.
1395  */
1396 static int
1397 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
1398           unsigned int socket, const struct rte_eth_txconf *conf)
1399 {
1400         struct priv *priv = dev->data->dev_private;
1401         struct txq tmpl = {
1402                 .priv = priv,
1403                 .socket = socket
1404         };
1405         union {
1406                 struct ibv_exp_query_intf_params params;
1407                 struct ibv_exp_qp_init_attr init;
1408                 struct ibv_exp_res_domain_init_attr rd;
1409                 struct ibv_exp_cq_init_attr cq;
1410                 struct ibv_exp_qp_attr mod;
1411         } attr;
1412         enum ibv_exp_query_intf_status status;
1413         int ret = 0;
1414
1415         (void)conf; /* Thresholds configuration (ignored). */
1416         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
1417                 ERROR("%p: invalid number of TX descriptors (must be a"
1418                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
1419                 return EINVAL;
1420         }
1421         desc /= MLX4_PMD_SGE_WR_N;
1422         /* MRs will be registered in mp2mr[] later. */
1423         attr.rd = (struct ibv_exp_res_domain_init_attr){
1424                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
1425                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
1426                 .thread_model = IBV_EXP_THREAD_SINGLE,
1427                 .msg_model = IBV_EXP_MSG_HIGH_BW,
1428         };
1429         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
1430         if (tmpl.rd == NULL) {
1431                 ret = ENOMEM;
1432                 ERROR("%p: RD creation failure: %s",
1433                       (void *)dev, strerror(ret));
1434                 goto error;
1435         }
1436         attr.cq = (struct ibv_exp_cq_init_attr){
1437                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
1438                 .res_domain = tmpl.rd,
1439         };
1440         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
1441         if (tmpl.cq == NULL) {
1442                 ret = ENOMEM;
1443                 ERROR("%p: CQ creation failure: %s",
1444                       (void *)dev, strerror(ret));
1445                 goto error;
1446         }
1447         DEBUG("priv->device_attr.max_qp_wr is %d",
1448               priv->device_attr.max_qp_wr);
1449         DEBUG("priv->device_attr.max_sge is %d",
1450               priv->device_attr.max_sge);
1451         attr.init = (struct ibv_exp_qp_init_attr){
1452                 /* CQ to be associated with the send queue. */
1453                 .send_cq = tmpl.cq,
1454                 /* CQ to be associated with the receive queue. */
1455                 .recv_cq = tmpl.cq,
1456                 .cap = {
1457                         /* Max number of outstanding WRs. */
1458                         .max_send_wr = ((priv->device_attr.max_qp_wr < desc) ?
1459                                         priv->device_attr.max_qp_wr :
1460                                         desc),
1461                         /* Max number of scatter/gather elements in a WR. */
1462                         .max_send_sge = ((priv->device_attr.max_sge <
1463                                           MLX4_PMD_SGE_WR_N) ?
1464                                          priv->device_attr.max_sge :
1465                                          MLX4_PMD_SGE_WR_N),
1466 #if MLX4_PMD_MAX_INLINE > 0
1467                         .max_inline_data = MLX4_PMD_MAX_INLINE,
1468 #endif
1469                 },
1470                 .qp_type = IBV_QPT_RAW_PACKET,
1471                 /* Do *NOT* enable this, completions events are managed per
1472                  * TX burst. */
1473                 .sq_sig_all = 0,
1474                 .pd = priv->pd,
1475                 .res_domain = tmpl.rd,
1476                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
1477                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
1478         };
1479         tmpl.qp = ibv_exp_create_qp(priv->ctx, &attr.init);
1480         if (tmpl.qp == NULL) {
1481                 ret = (errno ? errno : EINVAL);
1482                 ERROR("%p: QP creation failure: %s",
1483                       (void *)dev, strerror(ret));
1484                 goto error;
1485         }
1486 #if MLX4_PMD_MAX_INLINE > 0
1487         /* ibv_create_qp() updates this value. */
1488         tmpl.max_inline = attr.init.cap.max_inline_data;
1489 #endif
1490         attr.mod = (struct ibv_exp_qp_attr){
1491                 /* Move the QP to this state. */
1492                 .qp_state = IBV_QPS_INIT,
1493                 /* Primary port number. */
1494                 .port_num = priv->port
1495         };
1496         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod,
1497                                 (IBV_EXP_QP_STATE | IBV_EXP_QP_PORT));
1498         if (ret) {
1499                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1500                       (void *)dev, strerror(ret));
1501                 goto error;
1502         }
1503         ret = txq_alloc_elts(&tmpl, desc);
1504         if (ret) {
1505                 ERROR("%p: TXQ allocation failed: %s",
1506                       (void *)dev, strerror(ret));
1507                 goto error;
1508         }
1509         attr.mod = (struct ibv_exp_qp_attr){
1510                 .qp_state = IBV_QPS_RTR
1511         };
1512         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1513         if (ret) {
1514                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1515                       (void *)dev, strerror(ret));
1516                 goto error;
1517         }
1518         attr.mod.qp_state = IBV_QPS_RTS;
1519         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1520         if (ret) {
1521                 ERROR("%p: QP state to IBV_QPS_RTS failed: %s",
1522                       (void *)dev, strerror(ret));
1523                 goto error;
1524         }
1525         attr.params = (struct ibv_exp_query_intf_params){
1526                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1527                 .intf = IBV_EXP_INTF_CQ,
1528                 .obj = tmpl.cq,
1529         };
1530         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1531         if (tmpl.if_cq == NULL) {
1532                 ERROR("%p: CQ interface family query failed with status %d",
1533                       (void *)dev, status);
1534                 goto error;
1535         }
1536         attr.params = (struct ibv_exp_query_intf_params){
1537                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1538                 .intf = IBV_EXP_INTF_QP_BURST,
1539                 .obj = tmpl.qp,
1540 #ifdef HAVE_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK
1541                 /* MC loopback must be disabled when not using a VF. */
1542                 .family_flags =
1543                         (!priv->vf ?
1544                          IBV_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK :
1545                          0),
1546 #endif
1547         };
1548         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1549         if (tmpl.if_qp == NULL) {
1550                 ERROR("%p: QP interface family query failed with status %d",
1551                       (void *)dev, status);
1552                 goto error;
1553         }
1554         /* Clean up txq in case we're reinitializing it. */
1555         DEBUG("%p: cleaning-up old txq just in case", (void *)txq);
1556         txq_cleanup(txq);
1557         *txq = tmpl;
1558         DEBUG("%p: txq updated with %p", (void *)txq, (void *)&tmpl);
1559         assert(ret == 0);
1560         return 0;
1561 error:
1562         txq_cleanup(&tmpl);
1563         assert(ret > 0);
1564         return ret;
1565 }
1566
1567 /**
1568  * DPDK callback to configure a TX queue.
1569  *
1570  * @param dev
1571  *   Pointer to Ethernet device structure.
1572  * @param idx
1573  *   TX queue index.
1574  * @param desc
1575  *   Number of descriptors to configure in queue.
1576  * @param socket
1577  *   NUMA socket on which memory must be allocated.
1578  * @param[in] conf
1579  *   Thresholds parameters.
1580  *
1581  * @return
1582  *   0 on success, negative errno value on failure.
1583  */
1584 static int
1585 mlx4_tx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1586                     unsigned int socket, const struct rte_eth_txconf *conf)
1587 {
1588         struct priv *priv = dev->data->dev_private;
1589         struct txq *txq = (*priv->txqs)[idx];
1590         int ret;
1591
1592         priv_lock(priv);
1593         DEBUG("%p: configuring queue %u for %u descriptors",
1594               (void *)dev, idx, desc);
1595         if (idx >= priv->txqs_n) {
1596                 ERROR("%p: queue index out of range (%u >= %u)",
1597                       (void *)dev, idx, priv->txqs_n);
1598                 priv_unlock(priv);
1599                 return -EOVERFLOW;
1600         }
1601         if (txq != NULL) {
1602                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1603                       (void *)dev, idx, (void *)txq);
1604                 if (priv->started) {
1605                         priv_unlock(priv);
1606                         return -EEXIST;
1607                 }
1608                 (*priv->txqs)[idx] = NULL;
1609                 txq_cleanup(txq);
1610         } else {
1611                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0, socket);
1612                 if (txq == NULL) {
1613                         ERROR("%p: unable to allocate queue index %u",
1614                               (void *)dev, idx);
1615                         priv_unlock(priv);
1616                         return -ENOMEM;
1617                 }
1618         }
1619         ret = txq_setup(dev, txq, desc, socket, conf);
1620         if (ret)
1621                 rte_free(txq);
1622         else {
1623                 txq->stats.idx = idx;
1624                 DEBUG("%p: adding TX queue %p to list",
1625                       (void *)dev, (void *)txq);
1626                 (*priv->txqs)[idx] = txq;
1627                 /* Update send callback. */
1628                 dev->tx_pkt_burst = mlx4_tx_burst;
1629         }
1630         priv_unlock(priv);
1631         return -ret;
1632 }
1633
1634 /**
1635  * DPDK callback to release a TX queue.
1636  *
1637  * @param dpdk_txq
1638  *   Generic TX queue pointer.
1639  */
1640 static void
1641 mlx4_tx_queue_release(void *dpdk_txq)
1642 {
1643         struct txq *txq = (struct txq *)dpdk_txq;
1644         struct priv *priv;
1645         unsigned int i;
1646
1647         if (txq == NULL)
1648                 return;
1649         priv = txq->priv;
1650         priv_lock(priv);
1651         for (i = 0; (i != priv->txqs_n); ++i)
1652                 if ((*priv->txqs)[i] == txq) {
1653                         DEBUG("%p: removing TX queue %p from list",
1654                               (void *)priv->dev, (void *)txq);
1655                         (*priv->txqs)[i] = NULL;
1656                         break;
1657                 }
1658         txq_cleanup(txq);
1659         rte_free(txq);
1660         priv_unlock(priv);
1661 }
1662
1663 /* RX queues handling. */
1664
1665 /**
1666  * Allocate RX queue elements with scattered packets support.
1667  *
1668  * @param rxq
1669  *   Pointer to RX queue structure.
1670  * @param elts_n
1671  *   Number of elements to allocate.
1672  * @param[in] pool
1673  *   If not NULL, fetch buffers from this array instead of allocating them
1674  *   with rte_pktmbuf_alloc().
1675  *
1676  * @return
1677  *   0 on success, errno value on failure.
1678  */
1679 static int
1680 rxq_alloc_elts_sp(struct rxq *rxq, unsigned int elts_n,
1681                   struct rte_mbuf **pool)
1682 {
1683         unsigned int i;
1684         struct rxq_elt_sp (*elts)[elts_n] =
1685                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1686                                   rxq->socket);
1687         int ret = 0;
1688
1689         if (elts == NULL) {
1690                 ERROR("%p: can't allocate packets array", (void *)rxq);
1691                 ret = ENOMEM;
1692                 goto error;
1693         }
1694         /* For each WR (packet). */
1695         for (i = 0; (i != elts_n); ++i) {
1696                 unsigned int j;
1697                 struct rxq_elt_sp *elt = &(*elts)[i];
1698                 struct ibv_recv_wr *wr = &elt->wr;
1699                 struct ibv_sge (*sges)[(elemof(elt->sges))] = &elt->sges;
1700
1701                 /* These two arrays must have the same size. */
1702                 assert(elemof(elt->sges) == elemof(elt->bufs));
1703                 /* Configure WR. */
1704                 wr->wr_id = i;
1705                 wr->next = &(*elts)[(i + 1)].wr;
1706                 wr->sg_list = &(*sges)[0];
1707                 wr->num_sge = elemof(*sges);
1708                 /* For each SGE (segment). */
1709                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
1710                         struct ibv_sge *sge = &(*sges)[j];
1711                         struct rte_mbuf *buf;
1712
1713                         if (pool != NULL) {
1714                                 buf = *(pool++);
1715                                 assert(buf != NULL);
1716                                 rte_pktmbuf_reset(buf);
1717                         } else
1718                                 buf = rte_pktmbuf_alloc(rxq->mp);
1719                         if (buf == NULL) {
1720                                 assert(pool == NULL);
1721                                 ERROR("%p: empty mbuf pool", (void *)rxq);
1722                                 ret = ENOMEM;
1723                                 goto error;
1724                         }
1725                         elt->bufs[j] = buf;
1726                         /* Headroom is reserved by rte_pktmbuf_alloc(). */
1727                         assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1728                         /* Buffer is supposed to be empty. */
1729                         assert(rte_pktmbuf_data_len(buf) == 0);
1730                         assert(rte_pktmbuf_pkt_len(buf) == 0);
1731                         /* sge->addr must be able to store a pointer. */
1732                         assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1733                         if (j == 0) {
1734                                 /* The first SGE keeps its headroom. */
1735                                 sge->addr = rte_pktmbuf_mtod(buf, uintptr_t);
1736                                 sge->length = (buf->buf_len -
1737                                                RTE_PKTMBUF_HEADROOM);
1738                         } else {
1739                                 /* Subsequent SGEs lose theirs. */
1740                                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1741                                 SET_DATA_OFF(buf, 0);
1742                                 sge->addr = (uintptr_t)buf->buf_addr;
1743                                 sge->length = buf->buf_len;
1744                         }
1745                         sge->lkey = rxq->mr->lkey;
1746                         /* Redundant check for tailroom. */
1747                         assert(sge->length == rte_pktmbuf_tailroom(buf));
1748                 }
1749         }
1750         /* The last WR pointer must be NULL. */
1751         (*elts)[(i - 1)].wr.next = NULL;
1752         DEBUG("%p: allocated and configured %u WRs (%zu segments)",
1753               (void *)rxq, elts_n, (elts_n * elemof((*elts)[0].sges)));
1754         rxq->elts_n = elts_n;
1755         rxq->elts_head = 0;
1756         rxq->elts.sp = elts;
1757         assert(ret == 0);
1758         return 0;
1759 error:
1760         if (elts != NULL) {
1761                 assert(pool == NULL);
1762                 for (i = 0; (i != elemof(*elts)); ++i) {
1763                         unsigned int j;
1764                         struct rxq_elt_sp *elt = &(*elts)[i];
1765
1766                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
1767                                 struct rte_mbuf *buf = elt->bufs[j];
1768
1769                                 if (buf != NULL)
1770                                         rte_pktmbuf_free_seg(buf);
1771                         }
1772                 }
1773                 rte_free(elts);
1774         }
1775         DEBUG("%p: failed, freed everything", (void *)rxq);
1776         assert(ret > 0);
1777         return ret;
1778 }
1779
1780 /**
1781  * Free RX queue elements with scattered packets support.
1782  *
1783  * @param rxq
1784  *   Pointer to RX queue structure.
1785  */
1786 static void
1787 rxq_free_elts_sp(struct rxq *rxq)
1788 {
1789         unsigned int i;
1790         unsigned int elts_n = rxq->elts_n;
1791         struct rxq_elt_sp (*elts)[elts_n] = rxq->elts.sp;
1792
1793         DEBUG("%p: freeing WRs", (void *)rxq);
1794         rxq->elts_n = 0;
1795         rxq->elts.sp = NULL;
1796         if (elts == NULL)
1797                 return;
1798         for (i = 0; (i != elemof(*elts)); ++i) {
1799                 unsigned int j;
1800                 struct rxq_elt_sp *elt = &(*elts)[i];
1801
1802                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
1803                         struct rte_mbuf *buf = elt->bufs[j];
1804
1805                         if (buf != NULL)
1806                                 rte_pktmbuf_free_seg(buf);
1807                 }
1808         }
1809         rte_free(elts);
1810 }
1811
1812 /**
1813  * Allocate RX queue elements.
1814  *
1815  * @param rxq
1816  *   Pointer to RX queue structure.
1817  * @param elts_n
1818  *   Number of elements to allocate.
1819  * @param[in] pool
1820  *   If not NULL, fetch buffers from this array instead of allocating them
1821  *   with rte_pktmbuf_alloc().
1822  *
1823  * @return
1824  *   0 on success, errno value on failure.
1825  */
1826 static int
1827 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n, struct rte_mbuf **pool)
1828 {
1829         unsigned int i;
1830         struct rxq_elt (*elts)[elts_n] =
1831                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1832                                   rxq->socket);
1833         int ret = 0;
1834
1835         if (elts == NULL) {
1836                 ERROR("%p: can't allocate packets array", (void *)rxq);
1837                 ret = ENOMEM;
1838                 goto error;
1839         }
1840         /* For each WR (packet). */
1841         for (i = 0; (i != elts_n); ++i) {
1842                 struct rxq_elt *elt = &(*elts)[i];
1843                 struct ibv_recv_wr *wr = &elt->wr;
1844                 struct ibv_sge *sge = &(*elts)[i].sge;
1845                 struct rte_mbuf *buf;
1846
1847                 if (pool != NULL) {
1848                         buf = *(pool++);
1849                         assert(buf != NULL);
1850                         rte_pktmbuf_reset(buf);
1851                 } else
1852                         buf = rte_pktmbuf_alloc(rxq->mp);
1853                 if (buf == NULL) {
1854                         assert(pool == NULL);
1855                         ERROR("%p: empty mbuf pool", (void *)rxq);
1856                         ret = ENOMEM;
1857                         goto error;
1858                 }
1859                 /* Configure WR. Work request ID contains its own index in
1860                  * the elts array and the offset between SGE buffer header and
1861                  * its data. */
1862                 WR_ID(wr->wr_id).id = i;
1863                 WR_ID(wr->wr_id).offset =
1864                         (((uintptr_t)buf->buf_addr + RTE_PKTMBUF_HEADROOM) -
1865                          (uintptr_t)buf);
1866                 wr->next = &(*elts)[(i + 1)].wr;
1867                 wr->sg_list = sge;
1868                 wr->num_sge = 1;
1869                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
1870                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1871                 /* Buffer is supposed to be empty. */
1872                 assert(rte_pktmbuf_data_len(buf) == 0);
1873                 assert(rte_pktmbuf_pkt_len(buf) == 0);
1874                 /* sge->addr must be able to store a pointer. */
1875                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1876                 /* SGE keeps its headroom. */
1877                 sge->addr = (uintptr_t)
1878                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
1879                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
1880                 sge->lkey = rxq->mr->lkey;
1881                 /* Redundant check for tailroom. */
1882                 assert(sge->length == rte_pktmbuf_tailroom(buf));
1883                 /* Make sure elts index and SGE mbuf pointer can be deduced
1884                  * from WR ID. */
1885                 if ((WR_ID(wr->wr_id).id != i) ||
1886                     ((void *)((uintptr_t)sge->addr -
1887                         WR_ID(wr->wr_id).offset) != buf)) {
1888                         ERROR("%p: cannot store index and offset in WR ID",
1889                               (void *)rxq);
1890                         sge->addr = 0;
1891                         rte_pktmbuf_free(buf);
1892                         ret = EOVERFLOW;
1893                         goto error;
1894                 }
1895         }
1896         /* The last WR pointer must be NULL. */
1897         (*elts)[(i - 1)].wr.next = NULL;
1898         DEBUG("%p: allocated and configured %u single-segment WRs",
1899               (void *)rxq, elts_n);
1900         rxq->elts_n = elts_n;
1901         rxq->elts_head = 0;
1902         rxq->elts.no_sp = elts;
1903         assert(ret == 0);
1904         return 0;
1905 error:
1906         if (elts != NULL) {
1907                 assert(pool == NULL);
1908                 for (i = 0; (i != elemof(*elts)); ++i) {
1909                         struct rxq_elt *elt = &(*elts)[i];
1910                         struct rte_mbuf *buf;
1911
1912                         if (elt->sge.addr == 0)
1913                                 continue;
1914                         assert(WR_ID(elt->wr.wr_id).id == i);
1915                         buf = (void *)((uintptr_t)elt->sge.addr -
1916                                 WR_ID(elt->wr.wr_id).offset);
1917                         rte_pktmbuf_free_seg(buf);
1918                 }
1919                 rte_free(elts);
1920         }
1921         DEBUG("%p: failed, freed everything", (void *)rxq);
1922         assert(ret > 0);
1923         return ret;
1924 }
1925
1926 /**
1927  * Free RX queue elements.
1928  *
1929  * @param rxq
1930  *   Pointer to RX queue structure.
1931  */
1932 static void
1933 rxq_free_elts(struct rxq *rxq)
1934 {
1935         unsigned int i;
1936         unsigned int elts_n = rxq->elts_n;
1937         struct rxq_elt (*elts)[elts_n] = rxq->elts.no_sp;
1938
1939         DEBUG("%p: freeing WRs", (void *)rxq);
1940         rxq->elts_n = 0;
1941         rxq->elts.no_sp = NULL;
1942         if (elts == NULL)
1943                 return;
1944         for (i = 0; (i != elemof(*elts)); ++i) {
1945                 struct rxq_elt *elt = &(*elts)[i];
1946                 struct rte_mbuf *buf;
1947
1948                 if (elt->sge.addr == 0)
1949                         continue;
1950                 assert(WR_ID(elt->wr.wr_id).id == i);
1951                 buf = (void *)((uintptr_t)elt->sge.addr -
1952                         WR_ID(elt->wr.wr_id).offset);
1953                 rte_pktmbuf_free_seg(buf);
1954         }
1955         rte_free(elts);
1956 }
1957
1958 /**
1959  * Delete flow steering rule.
1960  *
1961  * @param rxq
1962  *   Pointer to RX queue structure.
1963  * @param mac_index
1964  *   MAC address index.
1965  * @param vlan_index
1966  *   VLAN index.
1967  */
1968 static void
1969 rxq_del_flow(struct rxq *rxq, unsigned int mac_index, unsigned int vlan_index)
1970 {
1971 #ifndef NDEBUG
1972         struct priv *priv = rxq->priv;
1973         const uint8_t (*mac)[ETHER_ADDR_LEN] =
1974                 (const uint8_t (*)[ETHER_ADDR_LEN])
1975                 priv->mac[mac_index].addr_bytes;
1976 #endif
1977         assert(rxq->mac_flow[mac_index][vlan_index] != NULL);
1978         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x index %u"
1979               " (VLAN ID %" PRIu16 ")",
1980               (void *)rxq,
1981               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
1982               mac_index, priv->vlan_filter[vlan_index].id);
1983         claim_zero(ibv_destroy_flow(rxq->mac_flow[mac_index][vlan_index]));
1984         rxq->mac_flow[mac_index][vlan_index] = NULL;
1985 }
1986
1987 /**
1988  * Unregister a MAC address from a RX queue.
1989  *
1990  * @param rxq
1991  *   Pointer to RX queue structure.
1992  * @param mac_index
1993  *   MAC address index.
1994  */
1995 static void
1996 rxq_mac_addr_del(struct rxq *rxq, unsigned int mac_index)
1997 {
1998         struct priv *priv = rxq->priv;
1999         unsigned int i;
2000         unsigned int vlans = 0;
2001
2002         assert(mac_index < elemof(priv->mac));
2003         if (!BITFIELD_ISSET(rxq->mac_configured, mac_index))
2004                 return;
2005         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
2006                 if (!priv->vlan_filter[i].enabled)
2007                         continue;
2008                 rxq_del_flow(rxq, mac_index, i);
2009                 vlans++;
2010         }
2011         if (!vlans) {
2012                 rxq_del_flow(rxq, mac_index, 0);
2013         }
2014         BITFIELD_RESET(rxq->mac_configured, mac_index);
2015 }
2016
2017 /**
2018  * Unregister all MAC addresses from a RX queue.
2019  *
2020  * @param rxq
2021  *   Pointer to RX queue structure.
2022  */
2023 static void
2024 rxq_mac_addrs_del(struct rxq *rxq)
2025 {
2026         struct priv *priv = rxq->priv;
2027         unsigned int i;
2028
2029         for (i = 0; (i != elemof(priv->mac)); ++i)
2030                 rxq_mac_addr_del(rxq, i);
2031 }
2032
2033 static int rxq_promiscuous_enable(struct rxq *);
2034 static void rxq_promiscuous_disable(struct rxq *);
2035
2036 /**
2037  * Add single flow steering rule.
2038  *
2039  * @param rxq
2040  *   Pointer to RX queue structure.
2041  * @param mac_index
2042  *   MAC address index to register.
2043  * @param vlan_index
2044  *   VLAN index. Use -1 for a flow without VLAN.
2045  *
2046  * @return
2047  *   0 on success, errno value on failure.
2048  */
2049 static int
2050 rxq_add_flow(struct rxq *rxq, unsigned int mac_index, unsigned int vlan_index)
2051 {
2052         struct ibv_flow *flow;
2053         struct priv *priv = rxq->priv;
2054         const uint8_t (*mac)[ETHER_ADDR_LEN] =
2055                         (const uint8_t (*)[ETHER_ADDR_LEN])
2056                         priv->mac[mac_index].addr_bytes;
2057
2058         /* Allocate flow specification on the stack. */
2059         struct __attribute__((packed)) {
2060                 struct ibv_flow_attr attr;
2061                 struct ibv_flow_spec_eth spec;
2062         } data;
2063         struct ibv_flow_attr *attr = &data.attr;
2064         struct ibv_flow_spec_eth *spec = &data.spec;
2065
2066         assert(mac_index < elemof(priv->mac));
2067         assert((vlan_index < elemof(priv->vlan_filter)) || (vlan_index == -1u));
2068         /*
2069          * No padding must be inserted by the compiler between attr and spec.
2070          * This layout is expected by libibverbs.
2071          */
2072         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
2073         *attr = (struct ibv_flow_attr){
2074                 .type = IBV_FLOW_ATTR_NORMAL,
2075                 .num_of_specs = 1,
2076                 .port = priv->port,
2077                 .flags = 0
2078         };
2079         *spec = (struct ibv_flow_spec_eth){
2080                 .type = IBV_FLOW_SPEC_ETH,
2081                 .size = sizeof(*spec),
2082                 .val = {
2083                         .dst_mac = {
2084                                 (*mac)[0], (*mac)[1], (*mac)[2],
2085                                 (*mac)[3], (*mac)[4], (*mac)[5]
2086                         },
2087                         .vlan_tag = ((vlan_index != -1u) ?
2088                                      htons(priv->vlan_filter[vlan_index].id) :
2089                                      0),
2090                 },
2091                 .mask = {
2092                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
2093                         .vlan_tag = ((vlan_index != -1u) ? htons(0xfff) : 0),
2094                 }
2095         };
2096         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x index %u"
2097               " (VLAN %s %" PRIu16 ")",
2098               (void *)rxq,
2099               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
2100               mac_index,
2101               ((vlan_index != -1u) ? "ID" : "index"),
2102               ((vlan_index != -1u) ? priv->vlan_filter[vlan_index].id : -1u));
2103         /* Create related flow. */
2104         errno = 0;
2105         flow = ibv_create_flow(rxq->qp, attr);
2106         if (flow == NULL) {
2107                 /* It's not clear whether errno is always set in this case. */
2108                 ERROR("%p: flow configuration failed, errno=%d: %s",
2109                       (void *)rxq, errno,
2110                       (errno ? strerror(errno) : "Unknown error"));
2111                 if (errno)
2112                         return errno;
2113                 return EINVAL;
2114         }
2115         if (vlan_index == -1u)
2116                 vlan_index = 0;
2117         assert(rxq->mac_flow[mac_index][vlan_index] == NULL);
2118         rxq->mac_flow[mac_index][vlan_index] = flow;
2119         return 0;
2120 }
2121
2122 /**
2123  * Register a MAC address in a RX queue.
2124  *
2125  * @param rxq
2126  *   Pointer to RX queue structure.
2127  * @param mac_index
2128  *   MAC address index to register.
2129  *
2130  * @return
2131  *   0 on success, errno value on failure.
2132  */
2133 static int
2134 rxq_mac_addr_add(struct rxq *rxq, unsigned int mac_index)
2135 {
2136         struct priv *priv = rxq->priv;
2137         unsigned int i;
2138         unsigned int vlans = 0;
2139         int ret;
2140
2141         assert(mac_index < elemof(priv->mac));
2142         if (BITFIELD_ISSET(rxq->mac_configured, mac_index))
2143                 rxq_mac_addr_del(rxq, mac_index);
2144         /* Fill VLAN specifications. */
2145         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
2146                 if (!priv->vlan_filter[i].enabled)
2147                         continue;
2148                 /* Create related flow. */
2149                 ret = rxq_add_flow(rxq, mac_index, i);
2150                 if (!ret) {
2151                         vlans++;
2152                         continue;
2153                 }
2154                 /* Failure, rollback. */
2155                 while (i != 0)
2156                         if (priv->vlan_filter[--i].enabled)
2157                                 rxq_del_flow(rxq, mac_index, i);
2158                 assert(ret > 0);
2159                 return ret;
2160         }
2161         /* In case there is no VLAN filter. */
2162         if (!vlans) {
2163                 ret = rxq_add_flow(rxq, mac_index, -1);
2164                 if (ret)
2165                         return ret;
2166         }
2167         BITFIELD_SET(rxq->mac_configured, mac_index);
2168         return 0;
2169 }
2170
2171 /**
2172  * Register all MAC addresses in a RX queue.
2173  *
2174  * @param rxq
2175  *   Pointer to RX queue structure.
2176  *
2177  * @return
2178  *   0 on success, errno value on failure.
2179  */
2180 static int
2181 rxq_mac_addrs_add(struct rxq *rxq)
2182 {
2183         struct priv *priv = rxq->priv;
2184         unsigned int i;
2185         int ret;
2186
2187         for (i = 0; (i != elemof(priv->mac)); ++i) {
2188                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2189                         continue;
2190                 ret = rxq_mac_addr_add(rxq, i);
2191                 if (!ret)
2192                         continue;
2193                 /* Failure, rollback. */
2194                 while (i != 0)
2195                         rxq_mac_addr_del(rxq, --i);
2196                 assert(ret > 0);
2197                 return ret;
2198         }
2199         return 0;
2200 }
2201
2202 /**
2203  * Unregister a MAC address.
2204  *
2205  * In RSS mode, the MAC address is unregistered from the parent queue,
2206  * otherwise it is unregistered from each queue directly.
2207  *
2208  * @param priv
2209  *   Pointer to private structure.
2210  * @param mac_index
2211  *   MAC address index.
2212  */
2213 static void
2214 priv_mac_addr_del(struct priv *priv, unsigned int mac_index)
2215 {
2216         unsigned int i;
2217
2218         assert(mac_index < elemof(priv->mac));
2219         if (!BITFIELD_ISSET(priv->mac_configured, mac_index))
2220                 return;
2221         if (priv->rss) {
2222                 rxq_mac_addr_del(&priv->rxq_parent, mac_index);
2223                 goto end;
2224         }
2225         for (i = 0; (i != priv->dev->data->nb_rx_queues); ++i)
2226                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2227 end:
2228         BITFIELD_RESET(priv->mac_configured, mac_index);
2229 }
2230
2231 /**
2232  * Register a MAC address.
2233  *
2234  * In RSS mode, the MAC address is registered in the parent queue,
2235  * otherwise it is registered in each queue directly.
2236  *
2237  * @param priv
2238  *   Pointer to private structure.
2239  * @param mac_index
2240  *   MAC address index to use.
2241  * @param mac
2242  *   MAC address to register.
2243  *
2244  * @return
2245  *   0 on success, errno value on failure.
2246  */
2247 static int
2248 priv_mac_addr_add(struct priv *priv, unsigned int mac_index,
2249                   const uint8_t (*mac)[ETHER_ADDR_LEN])
2250 {
2251         unsigned int i;
2252         int ret;
2253
2254         assert(mac_index < elemof(priv->mac));
2255         /* First, make sure this address isn't already configured. */
2256         for (i = 0; (i != elemof(priv->mac)); ++i) {
2257                 /* Skip this index, it's going to be reconfigured. */
2258                 if (i == mac_index)
2259                         continue;
2260                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2261                         continue;
2262                 if (memcmp(priv->mac[i].addr_bytes, *mac, sizeof(*mac)))
2263                         continue;
2264                 /* Address already configured elsewhere, return with error. */
2265                 return EADDRINUSE;
2266         }
2267         if (BITFIELD_ISSET(priv->mac_configured, mac_index))
2268                 priv_mac_addr_del(priv, mac_index);
2269         priv->mac[mac_index] = (struct ether_addr){
2270                 {
2271                         (*mac)[0], (*mac)[1], (*mac)[2],
2272                         (*mac)[3], (*mac)[4], (*mac)[5]
2273                 }
2274         };
2275         /* If device isn't started, this is all we need to do. */
2276         if (!priv->started) {
2277 #ifndef NDEBUG
2278                 /* Verify that all queues have this index disabled. */
2279                 for (i = 0; (i != priv->rxqs_n); ++i) {
2280                         if ((*priv->rxqs)[i] == NULL)
2281                                 continue;
2282                         assert(!BITFIELD_ISSET
2283                                ((*priv->rxqs)[i]->mac_configured, mac_index));
2284                 }
2285 #endif
2286                 goto end;
2287         }
2288         if (priv->rss) {
2289                 ret = rxq_mac_addr_add(&priv->rxq_parent, mac_index);
2290                 if (ret)
2291                         return ret;
2292                 goto end;
2293         }
2294         for (i = 0; (i != priv->rxqs_n); ++i) {
2295                 if ((*priv->rxqs)[i] == NULL)
2296                         continue;
2297                 ret = rxq_mac_addr_add((*priv->rxqs)[i], mac_index);
2298                 if (!ret)
2299                         continue;
2300                 /* Failure, rollback. */
2301                 while (i != 0)
2302                         if ((*priv->rxqs)[(--i)] != NULL)
2303                                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2304                 return ret;
2305         }
2306 end:
2307         BITFIELD_SET(priv->mac_configured, mac_index);
2308         return 0;
2309 }
2310
2311 /**
2312  * Enable allmulti mode in a RX queue.
2313  *
2314  * @param rxq
2315  *   Pointer to RX queue structure.
2316  *
2317  * @return
2318  *   0 on success, errno value on failure.
2319  */
2320 static int
2321 rxq_allmulticast_enable(struct rxq *rxq)
2322 {
2323         struct ibv_flow *flow;
2324         struct ibv_flow_attr attr = {
2325                 .type = IBV_FLOW_ATTR_MC_DEFAULT,
2326                 .num_of_specs = 0,
2327                 .port = rxq->priv->port,
2328                 .flags = 0
2329         };
2330
2331         DEBUG("%p: enabling allmulticast mode", (void *)rxq);
2332         if (rxq->allmulti_flow != NULL)
2333                 return EBUSY;
2334         errno = 0;
2335         flow = ibv_create_flow(rxq->qp, &attr);
2336         if (flow == NULL) {
2337                 /* It's not clear whether errno is always set in this case. */
2338                 ERROR("%p: flow configuration failed, errno=%d: %s",
2339                       (void *)rxq, errno,
2340                       (errno ? strerror(errno) : "Unknown error"));
2341                 if (errno)
2342                         return errno;
2343                 return EINVAL;
2344         }
2345         rxq->allmulti_flow = flow;
2346         DEBUG("%p: allmulticast mode enabled", (void *)rxq);
2347         return 0;
2348 }
2349
2350 /**
2351  * Disable allmulti mode in a RX queue.
2352  *
2353  * @param rxq
2354  *   Pointer to RX queue structure.
2355  */
2356 static void
2357 rxq_allmulticast_disable(struct rxq *rxq)
2358 {
2359         DEBUG("%p: disabling allmulticast mode", (void *)rxq);
2360         if (rxq->allmulti_flow == NULL)
2361                 return;
2362         claim_zero(ibv_destroy_flow(rxq->allmulti_flow));
2363         rxq->allmulti_flow = NULL;
2364         DEBUG("%p: allmulticast mode disabled", (void *)rxq);
2365 }
2366
2367 /**
2368  * Enable promiscuous mode in a RX queue.
2369  *
2370  * @param rxq
2371  *   Pointer to RX queue structure.
2372  *
2373  * @return
2374  *   0 on success, errno value on failure.
2375  */
2376 static int
2377 rxq_promiscuous_enable(struct rxq *rxq)
2378 {
2379         struct ibv_flow *flow;
2380         struct ibv_flow_attr attr = {
2381                 .type = IBV_FLOW_ATTR_ALL_DEFAULT,
2382                 .num_of_specs = 0,
2383                 .port = rxq->priv->port,
2384                 .flags = 0
2385         };
2386
2387         if (rxq->priv->vf)
2388                 return 0;
2389         DEBUG("%p: enabling promiscuous mode", (void *)rxq);
2390         if (rxq->promisc_flow != NULL)
2391                 return EBUSY;
2392         errno = 0;
2393         flow = ibv_create_flow(rxq->qp, &attr);
2394         if (flow == NULL) {
2395                 /* It's not clear whether errno is always set in this case. */
2396                 ERROR("%p: flow configuration failed, errno=%d: %s",
2397                       (void *)rxq, errno,
2398                       (errno ? strerror(errno) : "Unknown error"));
2399                 if (errno)
2400                         return errno;
2401                 return EINVAL;
2402         }
2403         rxq->promisc_flow = flow;
2404         DEBUG("%p: promiscuous mode enabled", (void *)rxq);
2405         return 0;
2406 }
2407
2408 /**
2409  * Disable promiscuous mode in a RX queue.
2410  *
2411  * @param rxq
2412  *   Pointer to RX queue structure.
2413  */
2414 static void
2415 rxq_promiscuous_disable(struct rxq *rxq)
2416 {
2417         if (rxq->priv->vf)
2418                 return;
2419         DEBUG("%p: disabling promiscuous mode", (void *)rxq);
2420         if (rxq->promisc_flow == NULL)
2421                 return;
2422         claim_zero(ibv_destroy_flow(rxq->promisc_flow));
2423         rxq->promisc_flow = NULL;
2424         DEBUG("%p: promiscuous mode disabled", (void *)rxq);
2425 }
2426
2427 /**
2428  * Clean up a RX queue.
2429  *
2430  * Destroy objects, free allocated memory and reset the structure for reuse.
2431  *
2432  * @param rxq
2433  *   Pointer to RX queue structure.
2434  */
2435 static void
2436 rxq_cleanup(struct rxq *rxq)
2437 {
2438         struct ibv_exp_release_intf_params params;
2439
2440         DEBUG("cleaning up %p", (void *)rxq);
2441         if (rxq->sp)
2442                 rxq_free_elts_sp(rxq);
2443         else
2444                 rxq_free_elts(rxq);
2445         if (rxq->if_qp != NULL) {
2446                 assert(rxq->priv != NULL);
2447                 assert(rxq->priv->ctx != NULL);
2448                 assert(rxq->qp != NULL);
2449                 params = (struct ibv_exp_release_intf_params){
2450                         .comp_mask = 0,
2451                 };
2452                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
2453                                                 rxq->if_qp,
2454                                                 &params));
2455         }
2456         if (rxq->if_cq != NULL) {
2457                 assert(rxq->priv != NULL);
2458                 assert(rxq->priv->ctx != NULL);
2459                 assert(rxq->cq != NULL);
2460                 params = (struct ibv_exp_release_intf_params){
2461                         .comp_mask = 0,
2462                 };
2463                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
2464                                                 rxq->if_cq,
2465                                                 &params));
2466         }
2467         if (rxq->qp != NULL) {
2468                 rxq_promiscuous_disable(rxq);
2469                 rxq_allmulticast_disable(rxq);
2470                 rxq_mac_addrs_del(rxq);
2471                 claim_zero(ibv_destroy_qp(rxq->qp));
2472         }
2473         if (rxq->cq != NULL)
2474                 claim_zero(ibv_destroy_cq(rxq->cq));
2475         if (rxq->rd != NULL) {
2476                 struct ibv_exp_destroy_res_domain_attr attr = {
2477                         .comp_mask = 0,
2478                 };
2479
2480                 assert(rxq->priv != NULL);
2481                 assert(rxq->priv->ctx != NULL);
2482                 claim_zero(ibv_exp_destroy_res_domain(rxq->priv->ctx,
2483                                                       rxq->rd,
2484                                                       &attr));
2485         }
2486         if (rxq->mr != NULL)
2487                 claim_zero(ibv_dereg_mr(rxq->mr));
2488         memset(rxq, 0, sizeof(*rxq));
2489 }
2490
2491 #ifdef RTE_NEXT_ABI
2492 /**
2493  * Translate RX completion flags to packet type.
2494  *
2495  * @param flags
2496  *   RX completion flags returned by poll_length_flags().
2497  *
2498  * @return
2499  *   Packet type for struct rte_mbuf.
2500  */
2501 static inline uint32_t
2502 rxq_cq_to_pkt_type(uint32_t flags)
2503 {
2504         uint32_t pkt_type;
2505
2506         if (flags & IBV_EXP_CQ_RX_TUNNEL_PACKET)
2507                 pkt_type =
2508                         TRANSPOSE(flags,
2509                                   IBV_EXP_CQ_RX_OUTER_IPV4_PACKET, RTE_PTYPE_L3_IPV4) |
2510                         TRANSPOSE(flags,
2511                                   IBV_EXP_CQ_RX_OUTER_IPV6_PACKET, RTE_PTYPE_L3_IPV6) |
2512                         TRANSPOSE(flags,
2513                                   IBV_EXP_CQ_RX_IPV4_PACKET, RTE_PTYPE_INNER_L3_IPV4) |
2514                         TRANSPOSE(flags,
2515                                   IBV_EXP_CQ_RX_IPV6_PACKET, RTE_PTYPE_INNER_L3_IPV6);
2516         else
2517                 pkt_type =
2518                         TRANSPOSE(flags,
2519                                   IBV_EXP_CQ_RX_IPV4_PACKET, RTE_PTYPE_L3_IPV4) |
2520                         TRANSPOSE(flags,
2521                                   IBV_EXP_CQ_RX_IPV6_PACKET, RTE_PTYPE_L3_IPV6);
2522         return pkt_type;
2523 }
2524 #endif /* RTE_NEXT_ABI */
2525
2526 /**
2527  * Translate RX completion flags to offload flags.
2528  *
2529  * @param[in] rxq
2530  *   Pointer to RX queue structure.
2531  * @param flags
2532  *   RX completion flags returned by poll_length_flags().
2533  *
2534  * @return
2535  *   Offload flags (ol_flags) for struct rte_mbuf.
2536  */
2537 static inline uint32_t
2538 rxq_cq_to_ol_flags(const struct rxq *rxq, uint32_t flags)
2539 {
2540         uint32_t ol_flags = 0;
2541
2542 #ifndef RTE_NEXT_ABI
2543         ol_flags =
2544                 TRANSPOSE(flags, IBV_EXP_CQ_RX_IPV4_PACKET, PKT_RX_IPV4_HDR) |
2545                 TRANSPOSE(flags, IBV_EXP_CQ_RX_IPV6_PACKET, PKT_RX_IPV6_HDR);
2546 #endif
2547         if (rxq->csum)
2548                 ol_flags |=
2549                         TRANSPOSE(~flags,
2550                                   IBV_EXP_CQ_RX_IP_CSUM_OK,
2551                                   PKT_RX_IP_CKSUM_BAD) |
2552                         TRANSPOSE(~flags,
2553                                   IBV_EXP_CQ_RX_TCP_UDP_CSUM_OK,
2554                                   PKT_RX_L4_CKSUM_BAD);
2555         /*
2556          * PKT_RX_IP_CKSUM_BAD and PKT_RX_L4_CKSUM_BAD are used in place
2557          * of PKT_RX_EIP_CKSUM_BAD because the latter is not functional
2558          * (its value is 0).
2559          */
2560         if ((flags & IBV_EXP_CQ_RX_TUNNEL_PACKET) && (rxq->csum_l2tun))
2561                 ol_flags |=
2562 #ifndef RTE_NEXT_ABI
2563                         TRANSPOSE(flags,
2564                                   IBV_EXP_CQ_RX_OUTER_IPV4_PACKET,
2565                                   PKT_RX_TUNNEL_IPV4_HDR) |
2566                         TRANSPOSE(flags,
2567                                   IBV_EXP_CQ_RX_OUTER_IPV6_PACKET,
2568                                   PKT_RX_TUNNEL_IPV6_HDR) |
2569 #endif
2570                         TRANSPOSE(~flags,
2571                                   IBV_EXP_CQ_RX_OUTER_IP_CSUM_OK,
2572                                   PKT_RX_IP_CKSUM_BAD) |
2573                         TRANSPOSE(~flags,
2574                                   IBV_EXP_CQ_RX_OUTER_TCP_UDP_CSUM_OK,
2575                                   PKT_RX_L4_CKSUM_BAD);
2576         return ol_flags;
2577 }
2578
2579 static uint16_t
2580 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n);
2581
2582 /**
2583  * DPDK callback for RX with scattered packets support.
2584  *
2585  * @param dpdk_rxq
2586  *   Generic pointer to RX queue structure.
2587  * @param[out] pkts
2588  *   Array to store received packets.
2589  * @param pkts_n
2590  *   Maximum number of packets in array.
2591  *
2592  * @return
2593  *   Number of packets successfully received (<= pkts_n).
2594  */
2595 static uint16_t
2596 mlx4_rx_burst_sp(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2597 {
2598         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2599         struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2600         const unsigned int elts_n = rxq->elts_n;
2601         unsigned int elts_head = rxq->elts_head;
2602         struct ibv_recv_wr head;
2603         struct ibv_recv_wr **next = &head.next;
2604         struct ibv_recv_wr *bad_wr;
2605         unsigned int i;
2606         unsigned int pkts_ret = 0;
2607         int ret;
2608
2609         if (unlikely(!rxq->sp))
2610                 return mlx4_rx_burst(dpdk_rxq, pkts, pkts_n);
2611         if (unlikely(elts == NULL)) /* See RTE_DEV_CMD_SET_MTU. */
2612                 return 0;
2613         for (i = 0; (i != pkts_n); ++i) {
2614                 struct rxq_elt_sp *elt = &(*elts)[elts_head];
2615                 struct ibv_recv_wr *wr = &elt->wr;
2616                 uint64_t wr_id = wr->wr_id;
2617                 unsigned int len;
2618                 unsigned int pkt_buf_len;
2619                 struct rte_mbuf *pkt_buf = NULL; /* Buffer returned in pkts. */
2620                 struct rte_mbuf **pkt_buf_next = &pkt_buf;
2621                 unsigned int seg_headroom = RTE_PKTMBUF_HEADROOM;
2622                 unsigned int j = 0;
2623                 uint32_t flags;
2624
2625                 /* Sanity checks. */
2626 #ifdef NDEBUG
2627                 (void)wr_id;
2628 #endif
2629                 assert(wr_id < rxq->elts_n);
2630                 assert(wr->sg_list == elt->sges);
2631                 assert(wr->num_sge == elemof(elt->sges));
2632                 assert(elts_head < rxq->elts_n);
2633                 assert(rxq->elts_head < rxq->elts_n);
2634                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
2635                                                     &flags);
2636                 if (unlikely(ret < 0)) {
2637                         struct ibv_wc wc;
2638                         int wcs_n;
2639
2640                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
2641                               (void *)rxq, ret);
2642                         /* ibv_poll_cq() must be used in case of failure. */
2643                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
2644                         if (unlikely(wcs_n == 0))
2645                                 break;
2646                         if (unlikely(wcs_n < 0)) {
2647                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
2648                                       (void *)rxq, wcs_n);
2649                                 break;
2650                         }
2651                         assert(wcs_n == 1);
2652                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
2653                                 /* Whatever, just repost the offending WR. */
2654                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
2655                                       " completion status (%d): %s",
2656                                       (void *)rxq, wc.wr_id, wc.status,
2657                                       ibv_wc_status_str(wc.status));
2658 #ifdef MLX4_PMD_SOFT_COUNTERS
2659                                 /* Increment dropped packets counter. */
2660                                 ++rxq->stats.idropped;
2661 #endif
2662                                 /* Link completed WRs together for repost. */
2663                                 *next = wr;
2664                                 next = &wr->next;
2665                                 goto repost;
2666                         }
2667                         ret = wc.byte_len;
2668                 }
2669                 if (ret == 0)
2670                         break;
2671                 len = ret;
2672                 pkt_buf_len = len;
2673                 /* Link completed WRs together for repost. */
2674                 *next = wr;
2675                 next = &wr->next;
2676                 /*
2677                  * Replace spent segments with new ones, concatenate and
2678                  * return them as pkt_buf.
2679                  */
2680                 while (1) {
2681                         struct ibv_sge *sge = &elt->sges[j];
2682                         struct rte_mbuf *seg = elt->bufs[j];
2683                         struct rte_mbuf *rep;
2684                         unsigned int seg_tailroom;
2685
2686                         /*
2687                          * Fetch initial bytes of packet descriptor into a
2688                          * cacheline while allocating rep.
2689                          */
2690                         rte_prefetch0(seg);
2691                         rep = __rte_mbuf_raw_alloc(rxq->mp);
2692                         if (unlikely(rep == NULL)) {
2693                                 /*
2694                                  * Unable to allocate a replacement mbuf,
2695                                  * repost WR.
2696                                  */
2697                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ":"
2698                                       " can't allocate a new mbuf",
2699                                       (void *)rxq, wr_id);
2700                                 if (pkt_buf != NULL) {
2701                                         *pkt_buf_next = NULL;
2702                                         rte_pktmbuf_free(pkt_buf);
2703                                 }
2704                                 /* Increase out of memory counters. */
2705                                 ++rxq->stats.rx_nombuf;
2706                                 ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2707                                 goto repost;
2708                         }
2709 #ifndef NDEBUG
2710                         /* Poison user-modifiable fields in rep. */
2711                         NEXT(rep) = (void *)((uintptr_t)-1);
2712                         SET_DATA_OFF(rep, 0xdead);
2713                         DATA_LEN(rep) = 0xd00d;
2714                         PKT_LEN(rep) = 0xdeadd00d;
2715                         NB_SEGS(rep) = 0x2a;
2716                         PORT(rep) = 0x2a;
2717                         rep->ol_flags = -1;
2718 #endif
2719                         assert(rep->buf_len == seg->buf_len);
2720                         assert(rep->buf_len == rxq->mb_len);
2721                         /* Reconfigure sge to use rep instead of seg. */
2722                         assert(sge->lkey == rxq->mr->lkey);
2723                         sge->addr = ((uintptr_t)rep->buf_addr + seg_headroom);
2724                         elt->bufs[j] = rep;
2725                         ++j;
2726                         /* Update pkt_buf if it's the first segment, or link
2727                          * seg to the previous one and update pkt_buf_next. */
2728                         *pkt_buf_next = seg;
2729                         pkt_buf_next = &NEXT(seg);
2730                         /* Update seg information. */
2731                         seg_tailroom = (seg->buf_len - seg_headroom);
2732                         assert(sge->length == seg_tailroom);
2733                         SET_DATA_OFF(seg, seg_headroom);
2734                         if (likely(len <= seg_tailroom)) {
2735                                 /* Last segment. */
2736                                 DATA_LEN(seg) = len;
2737                                 PKT_LEN(seg) = len;
2738                                 /* Sanity check. */
2739                                 assert(rte_pktmbuf_headroom(seg) ==
2740                                        seg_headroom);
2741                                 assert(rte_pktmbuf_tailroom(seg) ==
2742                                        (seg_tailroom - len));
2743                                 break;
2744                         }
2745                         DATA_LEN(seg) = seg_tailroom;
2746                         PKT_LEN(seg) = seg_tailroom;
2747                         /* Sanity check. */
2748                         assert(rte_pktmbuf_headroom(seg) == seg_headroom);
2749                         assert(rte_pktmbuf_tailroom(seg) == 0);
2750                         /* Fix len and clear headroom for next segments. */
2751                         len -= seg_tailroom;
2752                         seg_headroom = 0;
2753                 }
2754                 /* Update head and tail segments. */
2755                 *pkt_buf_next = NULL;
2756                 assert(pkt_buf != NULL);
2757                 assert(j != 0);
2758                 NB_SEGS(pkt_buf) = j;
2759                 PORT(pkt_buf) = rxq->port_id;
2760                 PKT_LEN(pkt_buf) = pkt_buf_len;
2761 #ifdef RTE_NEXT_ABI
2762                 pkt_buf->packet_type = rxq_cq_to_pkt_type(flags);
2763 #endif
2764                 pkt_buf->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
2765
2766                 /* Return packet. */
2767                 *(pkts++) = pkt_buf;
2768                 ++pkts_ret;
2769 #ifdef MLX4_PMD_SOFT_COUNTERS
2770                 /* Increase bytes counter. */
2771                 rxq->stats.ibytes += pkt_buf_len;
2772 #endif
2773 repost:
2774                 if (++elts_head >= elts_n)
2775                         elts_head = 0;
2776                 continue;
2777         }
2778         if (unlikely(i == 0))
2779                 return 0;
2780         *next = NULL;
2781         /* Repost WRs. */
2782 #ifdef DEBUG_RECV
2783         DEBUG("%p: reposting %d WRs", (void *)rxq, i);
2784 #endif
2785         ret = ibv_post_recv(rxq->qp, head.next, &bad_wr);
2786         if (unlikely(ret)) {
2787                 /* Inability to repost WRs is fatal. */
2788                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
2789                       (void *)rxq->priv,
2790                       (void *)bad_wr,
2791                       strerror(ret));
2792                 abort();
2793         }
2794         rxq->elts_head = elts_head;
2795 #ifdef MLX4_PMD_SOFT_COUNTERS
2796         /* Increase packets counter. */
2797         rxq->stats.ipackets += pkts_ret;
2798 #endif
2799         return pkts_ret;
2800 }
2801
2802 /**
2803  * DPDK callback for RX.
2804  *
2805  * The following function is the same as mlx4_rx_burst_sp(), except it doesn't
2806  * manage scattered packets. Improves performance when MRU is lower than the
2807  * size of the first segment.
2808  *
2809  * @param dpdk_rxq
2810  *   Generic pointer to RX queue structure.
2811  * @param[out] pkts
2812  *   Array to store received packets.
2813  * @param pkts_n
2814  *   Maximum number of packets in array.
2815  *
2816  * @return
2817  *   Number of packets successfully received (<= pkts_n).
2818  */
2819 static uint16_t
2820 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2821 {
2822         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2823         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
2824         const unsigned int elts_n = rxq->elts_n;
2825         unsigned int elts_head = rxq->elts_head;
2826         struct ibv_sge sges[pkts_n];
2827         unsigned int i;
2828         unsigned int pkts_ret = 0;
2829         int ret;
2830
2831         if (unlikely(rxq->sp))
2832                 return mlx4_rx_burst_sp(dpdk_rxq, pkts, pkts_n);
2833         for (i = 0; (i != pkts_n); ++i) {
2834                 struct rxq_elt *elt = &(*elts)[elts_head];
2835                 struct ibv_recv_wr *wr = &elt->wr;
2836                 uint64_t wr_id = wr->wr_id;
2837                 unsigned int len;
2838                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
2839                         WR_ID(wr_id).offset);
2840                 struct rte_mbuf *rep;
2841                 uint32_t flags;
2842
2843                 /* Sanity checks. */
2844                 assert(WR_ID(wr_id).id < rxq->elts_n);
2845                 assert(wr->sg_list == &elt->sge);
2846                 assert(wr->num_sge == 1);
2847                 assert(elts_head < rxq->elts_n);
2848                 assert(rxq->elts_head < rxq->elts_n);
2849                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
2850                                                     &flags);
2851                 if (unlikely(ret < 0)) {
2852                         struct ibv_wc wc;
2853                         int wcs_n;
2854
2855                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
2856                               (void *)rxq, ret);
2857                         /* ibv_poll_cq() must be used in case of failure. */
2858                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
2859                         if (unlikely(wcs_n == 0))
2860                                 break;
2861                         if (unlikely(wcs_n < 0)) {
2862                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
2863                                       (void *)rxq, wcs_n);
2864                                 break;
2865                         }
2866                         assert(wcs_n == 1);
2867                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
2868                                 /* Whatever, just repost the offending WR. */
2869                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
2870                                       " completion status (%d): %s",
2871                                       (void *)rxq, wc.wr_id, wc.status,
2872                                       ibv_wc_status_str(wc.status));
2873 #ifdef MLX4_PMD_SOFT_COUNTERS
2874                                 /* Increment dropped packets counter. */
2875                                 ++rxq->stats.idropped;
2876 #endif
2877                                 /* Add SGE to array for repost. */
2878                                 sges[i] = elt->sge;
2879                                 goto repost;
2880                         }
2881                         ret = wc.byte_len;
2882                 }
2883                 if (ret == 0)
2884                         break;
2885                 len = ret;
2886                 /*
2887                  * Fetch initial bytes of packet descriptor into a
2888                  * cacheline while allocating rep.
2889                  */
2890                 rte_prefetch0(seg);
2891                 rep = __rte_mbuf_raw_alloc(rxq->mp);
2892                 if (unlikely(rep == NULL)) {
2893                         /*
2894                          * Unable to allocate a replacement mbuf,
2895                          * repost WR.
2896                          */
2897                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
2898                               " can't allocate a new mbuf",
2899                               (void *)rxq, WR_ID(wr_id).id);
2900                         /* Increase out of memory counters. */
2901                         ++rxq->stats.rx_nombuf;
2902                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2903                         goto repost;
2904                 }
2905
2906                 /* Reconfigure sge to use rep instead of seg. */
2907                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
2908                 assert(elt->sge.lkey == rxq->mr->lkey);
2909                 WR_ID(wr->wr_id).offset =
2910                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
2911                          (uintptr_t)rep);
2912                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
2913
2914                 /* Add SGE to array for repost. */
2915                 sges[i] = elt->sge;
2916
2917                 /* Update seg information. */
2918                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
2919                 NB_SEGS(seg) = 1;
2920                 PORT(seg) = rxq->port_id;
2921                 NEXT(seg) = NULL;
2922                 PKT_LEN(seg) = len;
2923                 DATA_LEN(seg) = len;
2924 #ifdef RTE_NEXT_ABI
2925                 seg->packet_type = rxq_cq_to_pkt_type(flags);
2926 #endif
2927                 seg->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
2928
2929                 /* Return packet. */
2930                 *(pkts++) = seg;
2931                 ++pkts_ret;
2932 #ifdef MLX4_PMD_SOFT_COUNTERS
2933                 /* Increase bytes counter. */
2934                 rxq->stats.ibytes += len;
2935 #endif
2936 repost:
2937                 if (++elts_head >= elts_n)
2938                         elts_head = 0;
2939                 continue;
2940         }
2941         if (unlikely(i == 0))
2942                 return 0;
2943         /* Repost WRs. */
2944 #ifdef DEBUG_RECV
2945         DEBUG("%p: reposting %u WRs", (void *)rxq, i);
2946 #endif
2947         ret = rxq->if_qp->recv_burst(rxq->qp, sges, i);
2948         if (unlikely(ret)) {
2949                 /* Inability to repost WRs is fatal. */
2950                 DEBUG("%p: recv_burst(): failed (ret=%d)",
2951                       (void *)rxq->priv,
2952                       ret);
2953                 abort();
2954         }
2955         rxq->elts_head = elts_head;
2956 #ifdef MLX4_PMD_SOFT_COUNTERS
2957         /* Increase packets counter. */
2958         rxq->stats.ipackets += pkts_ret;
2959 #endif
2960         return pkts_ret;
2961 }
2962
2963 /**
2964  * Allocate a Queue Pair.
2965  * Optionally setup inline receive if supported.
2966  *
2967  * @param priv
2968  *   Pointer to private structure.
2969  * @param cq
2970  *   Completion queue to associate with QP.
2971  * @param desc
2972  *   Number of descriptors in QP (hint only).
2973  *
2974  * @return
2975  *   QP pointer or NULL in case of error.
2976  */
2977 static struct ibv_qp *
2978 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
2979              struct ibv_exp_res_domain *rd)
2980 {
2981         struct ibv_exp_qp_init_attr attr = {
2982                 /* CQ to be associated with the send queue. */
2983                 .send_cq = cq,
2984                 /* CQ to be associated with the receive queue. */
2985                 .recv_cq = cq,
2986                 .cap = {
2987                         /* Max number of outstanding WRs. */
2988                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2989                                         priv->device_attr.max_qp_wr :
2990                                         desc),
2991                         /* Max number of scatter/gather elements in a WR. */
2992                         .max_recv_sge = ((priv->device_attr.max_sge <
2993                                           MLX4_PMD_SGE_WR_N) ?
2994                                          priv->device_attr.max_sge :
2995                                          MLX4_PMD_SGE_WR_N),
2996                 },
2997                 .qp_type = IBV_QPT_RAW_PACKET,
2998                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
2999                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
3000                 .pd = priv->pd,
3001                 .res_domain = rd,
3002         };
3003
3004 #ifdef INLINE_RECV
3005         attr.max_inl_recv = priv->inl_recv_size;
3006         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3007 #endif
3008         return ibv_exp_create_qp(priv->ctx, &attr);
3009 }
3010
3011 #ifdef RSS_SUPPORT
3012
3013 /**
3014  * Allocate a RSS Queue Pair.
3015  * Optionally setup inline receive if supported.
3016  *
3017  * @param priv
3018  *   Pointer to private structure.
3019  * @param cq
3020  *   Completion queue to associate with QP.
3021  * @param desc
3022  *   Number of descriptors in QP (hint only).
3023  * @param parent
3024  *   If nonzero, create a parent QP, otherwise a child.
3025  *
3026  * @return
3027  *   QP pointer or NULL in case of error.
3028  */
3029 static struct ibv_qp *
3030 rxq_setup_qp_rss(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
3031                  int parent, struct ibv_exp_res_domain *rd)
3032 {
3033         struct ibv_exp_qp_init_attr attr = {
3034                 /* CQ to be associated with the send queue. */
3035                 .send_cq = cq,
3036                 /* CQ to be associated with the receive queue. */
3037                 .recv_cq = cq,
3038                 .cap = {
3039                         /* Max number of outstanding WRs. */
3040                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
3041                                         priv->device_attr.max_qp_wr :
3042                                         desc),
3043                         /* Max number of scatter/gather elements in a WR. */
3044                         .max_recv_sge = ((priv->device_attr.max_sge <
3045                                           MLX4_PMD_SGE_WR_N) ?
3046                                          priv->device_attr.max_sge :
3047                                          MLX4_PMD_SGE_WR_N),
3048                 },
3049                 .qp_type = IBV_QPT_RAW_PACKET,
3050                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
3051                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN |
3052                               IBV_EXP_QP_INIT_ATTR_QPG),
3053                 .pd = priv->pd,
3054                 .res_domain = rd,
3055         };
3056
3057 #ifdef INLINE_RECV
3058         attr.max_inl_recv = priv->inl_recv_size,
3059         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3060 #endif
3061         if (parent) {
3062                 attr.qpg.qpg_type = IBV_EXP_QPG_PARENT;
3063                 /* TSS isn't necessary. */
3064                 attr.qpg.parent_attrib.tss_child_count = 0;
3065                 attr.qpg.parent_attrib.rss_child_count = priv->rxqs_n;
3066                 DEBUG("initializing parent RSS queue");
3067         } else {
3068                 attr.qpg.qpg_type = IBV_EXP_QPG_CHILD_RX;
3069                 attr.qpg.qpg_parent = priv->rxq_parent.qp;
3070                 DEBUG("initializing child RSS queue");
3071         }
3072         return ibv_exp_create_qp(priv->ctx, &attr);
3073 }
3074
3075 #endif /* RSS_SUPPORT */
3076
3077 /**
3078  * Reconfigure a RX queue with new parameters.
3079  *
3080  * rxq_rehash() does not allocate mbufs, which, if not done from the right
3081  * thread (such as a control thread), may corrupt the pool.
3082  * In case of failure, the queue is left untouched.
3083  *
3084  * @param dev
3085  *   Pointer to Ethernet device structure.
3086  * @param rxq
3087  *   RX queue pointer.
3088  *
3089  * @return
3090  *   0 on success, errno value on failure.
3091  */
3092 static int
3093 rxq_rehash(struct rte_eth_dev *dev, struct rxq *rxq)
3094 {
3095         struct priv *priv = rxq->priv;
3096         struct rxq tmpl = *rxq;
3097         unsigned int mbuf_n;
3098         unsigned int desc_n;
3099         struct rte_mbuf **pool;
3100         unsigned int i, k;
3101         struct ibv_exp_qp_attr mod;
3102         struct ibv_recv_wr *bad_wr;
3103         int err;
3104         int parent = (rxq == &priv->rxq_parent);
3105
3106         if (parent) {
3107                 ERROR("%p: cannot rehash parent queue %p",
3108                       (void *)dev, (void *)rxq);
3109                 return EINVAL;
3110         }
3111         DEBUG("%p: rehashing queue %p", (void *)dev, (void *)rxq);
3112         /* Number of descriptors and mbufs currently allocated. */
3113         desc_n = (tmpl.elts_n * (tmpl.sp ? MLX4_PMD_SGE_WR_N : 1));
3114         mbuf_n = desc_n;
3115         /* Toggle RX checksum offload if hardware supports it. */
3116         if (priv->hw_csum) {
3117                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3118                 rxq->csum = tmpl.csum;
3119         }
3120         if (priv->hw_csum_l2tun) {
3121                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3122                 rxq->csum_l2tun = tmpl.csum_l2tun;
3123         }
3124         /* Enable scattered packets support for this queue if necessary. */
3125         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3126             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3127              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
3128                 tmpl.sp = 1;
3129                 desc_n /= MLX4_PMD_SGE_WR_N;
3130         } else
3131                 tmpl.sp = 0;
3132         DEBUG("%p: %s scattered packets support (%u WRs)",
3133               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc_n);
3134         /* If scatter mode is the same as before, nothing to do. */
3135         if (tmpl.sp == rxq->sp) {
3136                 DEBUG("%p: nothing to do", (void *)dev);
3137                 return 0;
3138         }
3139         /* Remove attached flows if RSS is disabled (no parent queue). */
3140         if (!priv->rss) {
3141                 rxq_allmulticast_disable(&tmpl);
3142                 rxq_promiscuous_disable(&tmpl);
3143                 rxq_mac_addrs_del(&tmpl);
3144                 /* Update original queue in case of failure. */
3145                 rxq->allmulti_flow = tmpl.allmulti_flow;
3146                 rxq->promisc_flow = tmpl.promisc_flow;
3147                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3148                        sizeof(rxq->mac_configured));
3149                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3150         }
3151         /* From now on, any failure will render the queue unusable.
3152          * Reinitialize QP. */
3153         mod = (struct ibv_exp_qp_attr){ .qp_state = IBV_QPS_RESET };
3154         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3155         if (err) {
3156                 ERROR("%p: cannot reset QP: %s", (void *)dev, strerror(err));
3157                 assert(err > 0);
3158                 return err;
3159         }
3160         err = ibv_resize_cq(tmpl.cq, desc_n);
3161         if (err) {
3162                 ERROR("%p: cannot resize CQ: %s", (void *)dev, strerror(err));
3163                 assert(err > 0);
3164                 return err;
3165         }
3166         mod = (struct ibv_exp_qp_attr){
3167                 /* Move the QP to this state. */
3168                 .qp_state = IBV_QPS_INIT,
3169                 /* Primary port number. */
3170                 .port_num = priv->port
3171         };
3172         err = ibv_exp_modify_qp(tmpl.qp, &mod,
3173                                 (IBV_EXP_QP_STATE |
3174 #ifdef RSS_SUPPORT
3175                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3176 #endif /* RSS_SUPPORT */
3177                                  IBV_EXP_QP_PORT));
3178         if (err) {
3179                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3180                       (void *)dev, strerror(err));
3181                 assert(err > 0);
3182                 return err;
3183         };
3184         /* Reconfigure flows. Do not care for errors. */
3185         if (!priv->rss) {
3186                 rxq_mac_addrs_add(&tmpl);
3187                 if (priv->promisc)
3188                         rxq_promiscuous_enable(&tmpl);
3189                 if (priv->allmulti)
3190                         rxq_allmulticast_enable(&tmpl);
3191                 /* Update original queue in case of failure. */
3192                 rxq->allmulti_flow = tmpl.allmulti_flow;
3193                 rxq->promisc_flow = tmpl.promisc_flow;
3194                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3195                        sizeof(rxq->mac_configured));
3196                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3197         }
3198         /* Allocate pool. */
3199         pool = rte_malloc(__func__, (mbuf_n * sizeof(*pool)), 0);
3200         if (pool == NULL) {
3201                 ERROR("%p: cannot allocate memory", (void *)dev);
3202                 return ENOBUFS;
3203         }
3204         /* Snatch mbufs from original queue. */
3205         k = 0;
3206         if (rxq->sp) {
3207                 struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
3208
3209                 for (i = 0; (i != elemof(*elts)); ++i) {
3210                         struct rxq_elt_sp *elt = &(*elts)[i];
3211                         unsigned int j;
3212
3213                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
3214                                 assert(elt->bufs[j] != NULL);
3215                                 pool[k++] = elt->bufs[j];
3216                         }
3217                 }
3218         } else {
3219                 struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
3220
3221                 for (i = 0; (i != elemof(*elts)); ++i) {
3222                         struct rxq_elt *elt = &(*elts)[i];
3223                         struct rte_mbuf *buf = (void *)
3224                                 ((uintptr_t)elt->sge.addr -
3225                                  WR_ID(elt->wr.wr_id).offset);
3226
3227                         assert(WR_ID(elt->wr.wr_id).id == i);
3228                         pool[k++] = buf;
3229                 }
3230         }
3231         assert(k == mbuf_n);
3232         tmpl.elts_n = 0;
3233         tmpl.elts.sp = NULL;
3234         assert((void *)&tmpl.elts.sp == (void *)&tmpl.elts.no_sp);
3235         err = ((tmpl.sp) ?
3236                rxq_alloc_elts_sp(&tmpl, desc_n, pool) :
3237                rxq_alloc_elts(&tmpl, desc_n, pool));
3238         if (err) {
3239                 ERROR("%p: cannot reallocate WRs, aborting", (void *)dev);
3240                 rte_free(pool);
3241                 assert(err > 0);
3242                 return err;
3243         }
3244         assert(tmpl.elts_n == desc_n);
3245         assert(tmpl.elts.sp != NULL);
3246         rte_free(pool);
3247         /* Clean up original data. */
3248         rxq->elts_n = 0;
3249         rte_free(rxq->elts.sp);
3250         rxq->elts.sp = NULL;
3251         /* Post WRs. */
3252         err = ibv_post_recv(tmpl.qp,
3253                             (tmpl.sp ?
3254                              &(*tmpl.elts.sp)[0].wr :
3255                              &(*tmpl.elts.no_sp)[0].wr),
3256                             &bad_wr);
3257         if (err) {
3258                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3259                       (void *)dev,
3260                       (void *)bad_wr,
3261                       strerror(err));
3262                 goto skip_rtr;
3263         }
3264         mod = (struct ibv_exp_qp_attr){
3265                 .qp_state = IBV_QPS_RTR
3266         };
3267         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3268         if (err)
3269                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3270                       (void *)dev, strerror(err));
3271 skip_rtr:
3272         *rxq = tmpl;
3273         assert(err >= 0);
3274         return err;
3275 }
3276
3277 /**
3278  * Configure a RX queue.
3279  *
3280  * @param dev
3281  *   Pointer to Ethernet device structure.
3282  * @param rxq
3283  *   Pointer to RX queue structure.
3284  * @param desc
3285  *   Number of descriptors to configure in queue.
3286  * @param socket
3287  *   NUMA socket on which memory must be allocated.
3288  * @param[in] conf
3289  *   Thresholds parameters.
3290  * @param mp
3291  *   Memory pool for buffer allocations.
3292  *
3293  * @return
3294  *   0 on success, errno value on failure.
3295  */
3296 static int
3297 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
3298           unsigned int socket, const struct rte_eth_rxconf *conf,
3299           struct rte_mempool *mp)
3300 {
3301         struct priv *priv = dev->data->dev_private;
3302         struct rxq tmpl = {
3303                 .priv = priv,
3304                 .mp = mp,
3305                 .socket = socket
3306         };
3307         struct ibv_exp_qp_attr mod;
3308         union {
3309                 struct ibv_exp_query_intf_params params;
3310                 struct ibv_exp_cq_init_attr cq;
3311                 struct ibv_exp_res_domain_init_attr rd;
3312         } attr;
3313         enum ibv_exp_query_intf_status status;
3314         struct ibv_recv_wr *bad_wr;
3315         struct rte_mbuf *buf;
3316         int ret = 0;
3317         int parent = (rxq == &priv->rxq_parent);
3318
3319         (void)conf; /* Thresholds configuration (ignored). */
3320         /*
3321          * If this is a parent queue, hardware must support RSS and
3322          * RSS must be enabled.
3323          */
3324         assert((!parent) || ((priv->hw_rss) && (priv->rss)));
3325         if (parent) {
3326                 /* Even if unused, ibv_create_cq() requires at least one
3327                  * descriptor. */
3328                 desc = 1;
3329                 goto skip_mr;
3330         }
3331         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
3332                 ERROR("%p: invalid number of RX descriptors (must be a"
3333                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
3334                 return EINVAL;
3335         }
3336         /* Get mbuf length. */
3337         buf = rte_pktmbuf_alloc(mp);
3338         if (buf == NULL) {
3339                 ERROR("%p: unable to allocate mbuf", (void *)dev);
3340                 return ENOMEM;
3341         }
3342         tmpl.mb_len = buf->buf_len;
3343         assert((rte_pktmbuf_headroom(buf) +
3344                 rte_pktmbuf_tailroom(buf)) == tmpl.mb_len);
3345         assert(rte_pktmbuf_headroom(buf) == RTE_PKTMBUF_HEADROOM);
3346         rte_pktmbuf_free(buf);
3347         /* Toggle RX checksum offload if hardware supports it. */
3348         if (priv->hw_csum)
3349                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3350         if (priv->hw_csum_l2tun)
3351                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3352         /* Enable scattered packets support for this queue if necessary. */
3353         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3354             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3355              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
3356                 tmpl.sp = 1;
3357                 desc /= MLX4_PMD_SGE_WR_N;
3358         }
3359         DEBUG("%p: %s scattered packets support (%u WRs)",
3360               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
3361         /* Use the entire RX mempool as the memory region. */
3362         tmpl.mr = ibv_reg_mr(priv->pd,
3363                              (void *)mp->elt_va_start,
3364                              (mp->elt_va_end - mp->elt_va_start),
3365                              (IBV_ACCESS_LOCAL_WRITE |
3366                               IBV_ACCESS_REMOTE_WRITE));
3367         if (tmpl.mr == NULL) {
3368                 ret = EINVAL;
3369                 ERROR("%p: MR creation failure: %s",
3370                       (void *)dev, strerror(ret));
3371                 goto error;
3372         }
3373 skip_mr:
3374         attr.rd = (struct ibv_exp_res_domain_init_attr){
3375                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
3376                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
3377                 .thread_model = IBV_EXP_THREAD_SINGLE,
3378                 .msg_model = IBV_EXP_MSG_HIGH_BW,
3379         };
3380         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
3381         if (tmpl.rd == NULL) {
3382                 ret = ENOMEM;
3383                 ERROR("%p: RD creation failure: %s",
3384                       (void *)dev, strerror(ret));
3385                 goto error;
3386         }
3387         attr.cq = (struct ibv_exp_cq_init_attr){
3388                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
3389                 .res_domain = tmpl.rd,
3390         };
3391         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
3392         if (tmpl.cq == NULL) {
3393                 ret = ENOMEM;
3394                 ERROR("%p: CQ creation failure: %s",
3395                       (void *)dev, strerror(ret));
3396                 goto error;
3397         }
3398         DEBUG("priv->device_attr.max_qp_wr is %d",
3399               priv->device_attr.max_qp_wr);
3400         DEBUG("priv->device_attr.max_sge is %d",
3401               priv->device_attr.max_sge);
3402 #ifdef RSS_SUPPORT
3403         if (priv->rss)
3404                 tmpl.qp = rxq_setup_qp_rss(priv, tmpl.cq, desc, parent,
3405                                            tmpl.rd);
3406         else
3407 #endif /* RSS_SUPPORT */
3408                 tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc, tmpl.rd);
3409         if (tmpl.qp == NULL) {
3410                 ret = (errno ? errno : EINVAL);
3411                 ERROR("%p: QP creation failure: %s",
3412                       (void *)dev, strerror(ret));
3413                 goto error;
3414         }
3415         mod = (struct ibv_exp_qp_attr){
3416                 /* Move the QP to this state. */
3417                 .qp_state = IBV_QPS_INIT,
3418                 /* Primary port number. */
3419                 .port_num = priv->port
3420         };
3421         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
3422                                 (IBV_EXP_QP_STATE |
3423 #ifdef RSS_SUPPORT
3424                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3425 #endif /* RSS_SUPPORT */
3426                                  IBV_EXP_QP_PORT));
3427         if (ret) {
3428                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3429                       (void *)dev, strerror(ret));
3430                 goto error;
3431         }
3432         if ((parent) || (!priv->rss))  {
3433                 /* Configure MAC and broadcast addresses. */
3434                 ret = rxq_mac_addrs_add(&tmpl);
3435                 if (ret) {
3436                         ERROR("%p: QP flow attachment failed: %s",
3437                               (void *)dev, strerror(ret));
3438                         goto error;
3439                 }
3440         }
3441         /* Allocate descriptors for RX queues, except for the RSS parent. */
3442         if (parent)
3443                 goto skip_alloc;
3444         if (tmpl.sp)
3445                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
3446         else
3447                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
3448         if (ret) {
3449                 ERROR("%p: RXQ allocation failed: %s",
3450                       (void *)dev, strerror(ret));
3451                 goto error;
3452         }
3453         ret = ibv_post_recv(tmpl.qp,
3454                             (tmpl.sp ?
3455                              &(*tmpl.elts.sp)[0].wr :
3456                              &(*tmpl.elts.no_sp)[0].wr),
3457                             &bad_wr);
3458         if (ret) {
3459                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3460                       (void *)dev,
3461                       (void *)bad_wr,
3462                       strerror(ret));
3463                 goto error;
3464         }
3465 skip_alloc:
3466         mod = (struct ibv_exp_qp_attr){
3467                 .qp_state = IBV_QPS_RTR
3468         };
3469         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3470         if (ret) {
3471                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3472                       (void *)dev, strerror(ret));
3473                 goto error;
3474         }
3475         /* Save port ID. */
3476         tmpl.port_id = dev->data->port_id;
3477         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
3478         attr.params = (struct ibv_exp_query_intf_params){
3479                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3480                 .intf = IBV_EXP_INTF_CQ,
3481                 .obj = tmpl.cq,
3482         };
3483         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3484         if (tmpl.if_cq == NULL) {
3485                 ERROR("%p: CQ interface family query failed with status %d",
3486                       (void *)dev, status);
3487                 goto error;
3488         }
3489         attr.params = (struct ibv_exp_query_intf_params){
3490                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3491                 .intf = IBV_EXP_INTF_QP_BURST,
3492                 .obj = tmpl.qp,
3493         };
3494         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3495         if (tmpl.if_qp == NULL) {
3496                 ERROR("%p: QP interface family query failed with status %d",
3497                       (void *)dev, status);
3498                 goto error;
3499         }
3500         /* Clean up rxq in case we're reinitializing it. */
3501         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
3502         rxq_cleanup(rxq);
3503         *rxq = tmpl;
3504         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
3505         assert(ret == 0);
3506         return 0;
3507 error:
3508         rxq_cleanup(&tmpl);
3509         assert(ret > 0);
3510         return ret;
3511 }
3512
3513 /**
3514  * DPDK callback to configure a RX queue.
3515  *
3516  * @param dev
3517  *   Pointer to Ethernet device structure.
3518  * @param idx
3519  *   RX queue index.
3520  * @param desc
3521  *   Number of descriptors to configure in queue.
3522  * @param socket
3523  *   NUMA socket on which memory must be allocated.
3524  * @param[in] conf
3525  *   Thresholds parameters.
3526  * @param mp
3527  *   Memory pool for buffer allocations.
3528  *
3529  * @return
3530  *   0 on success, negative errno value on failure.
3531  */
3532 static int
3533 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
3534                     unsigned int socket, const struct rte_eth_rxconf *conf,
3535                     struct rte_mempool *mp)
3536 {
3537         struct priv *priv = dev->data->dev_private;
3538         struct rxq *rxq = (*priv->rxqs)[idx];
3539         int ret;
3540
3541         priv_lock(priv);
3542         DEBUG("%p: configuring queue %u for %u descriptors",
3543               (void *)dev, idx, desc);
3544         if (idx >= priv->rxqs_n) {
3545                 ERROR("%p: queue index out of range (%u >= %u)",
3546                       (void *)dev, idx, priv->rxqs_n);
3547                 priv_unlock(priv);
3548                 return -EOVERFLOW;
3549         }
3550         if (rxq != NULL) {
3551                 DEBUG("%p: reusing already allocated queue index %u (%p)",
3552                       (void *)dev, idx, (void *)rxq);
3553                 if (priv->started) {
3554                         priv_unlock(priv);
3555                         return -EEXIST;
3556                 }
3557                 (*priv->rxqs)[idx] = NULL;
3558                 rxq_cleanup(rxq);
3559         } else {
3560                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
3561                 if (rxq == NULL) {
3562                         ERROR("%p: unable to allocate queue index %u",
3563                               (void *)dev, idx);
3564                         priv_unlock(priv);
3565                         return -ENOMEM;
3566                 }
3567         }
3568         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
3569         if (ret)
3570                 rte_free(rxq);
3571         else {
3572                 rxq->stats.idx = idx;
3573                 DEBUG("%p: adding RX queue %p to list",
3574                       (void *)dev, (void *)rxq);
3575                 (*priv->rxqs)[idx] = rxq;
3576                 /* Update receive callback. */
3577                 if (rxq->sp)
3578                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3579                 else
3580                         dev->rx_pkt_burst = mlx4_rx_burst;
3581         }
3582         priv_unlock(priv);
3583         return -ret;
3584 }
3585
3586 /**
3587  * DPDK callback to release a RX queue.
3588  *
3589  * @param dpdk_rxq
3590  *   Generic RX queue pointer.
3591  */
3592 static void
3593 mlx4_rx_queue_release(void *dpdk_rxq)
3594 {
3595         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3596         struct priv *priv;
3597         unsigned int i;
3598
3599         if (rxq == NULL)
3600                 return;
3601         priv = rxq->priv;
3602         priv_lock(priv);
3603         assert(rxq != &priv->rxq_parent);
3604         for (i = 0; (i != priv->rxqs_n); ++i)
3605                 if ((*priv->rxqs)[i] == rxq) {
3606                         DEBUG("%p: removing RX queue %p from list",
3607                               (void *)priv->dev, (void *)rxq);
3608                         (*priv->rxqs)[i] = NULL;
3609                         break;
3610                 }
3611         rxq_cleanup(rxq);
3612         rte_free(rxq);
3613         priv_unlock(priv);
3614 }
3615
3616 /**
3617  * DPDK callback to start the device.
3618  *
3619  * Simulate device start by attaching all configured flows.
3620  *
3621  * @param dev
3622  *   Pointer to Ethernet device structure.
3623  *
3624  * @return
3625  *   0 on success, negative errno value on failure.
3626  */
3627 static int
3628 mlx4_dev_start(struct rte_eth_dev *dev)
3629 {
3630         struct priv *priv = dev->data->dev_private;
3631         unsigned int i = 0;
3632         unsigned int r;
3633         struct rxq *rxq;
3634
3635         priv_lock(priv);
3636         if (priv->started) {
3637                 priv_unlock(priv);
3638                 return 0;
3639         }
3640         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
3641         priv->started = 1;
3642         if (priv->rss) {
3643                 rxq = &priv->rxq_parent;
3644                 r = 1;
3645         } else {
3646                 rxq = (*priv->rxqs)[0];
3647                 r = priv->rxqs_n;
3648         }
3649         /* Iterate only once when RSS is enabled. */
3650         do {
3651                 int ret;
3652
3653                 /* Ignore nonexistent RX queues. */
3654                 if (rxq == NULL)
3655                         continue;
3656                 ret = rxq_mac_addrs_add(rxq);
3657                 if (!ret && priv->promisc)
3658                         ret = rxq_promiscuous_enable(rxq);
3659                 if (!ret && priv->allmulti)
3660                         ret = rxq_allmulticast_enable(rxq);
3661                 if (!ret)
3662                         continue;
3663                 WARN("%p: QP flow attachment failed: %s",
3664                      (void *)dev, strerror(ret));
3665                 /* Rollback. */
3666                 while (i != 0) {
3667                         rxq = (*priv->rxqs)[--i];
3668                         if (rxq != NULL) {
3669                                 rxq_allmulticast_disable(rxq);
3670                                 rxq_promiscuous_disable(rxq);
3671                                 rxq_mac_addrs_del(rxq);
3672                         }
3673                 }
3674                 priv->started = 0;
3675                 return -ret;
3676         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3677         priv_unlock(priv);
3678         return 0;
3679 }
3680
3681 /**
3682  * DPDK callback to stop the device.
3683  *
3684  * Simulate device stop by detaching all configured flows.
3685  *
3686  * @param dev
3687  *   Pointer to Ethernet device structure.
3688  */
3689 static void
3690 mlx4_dev_stop(struct rte_eth_dev *dev)
3691 {
3692         struct priv *priv = dev->data->dev_private;
3693         unsigned int i = 0;
3694         unsigned int r;
3695         struct rxq *rxq;
3696
3697         priv_lock(priv);
3698         if (!priv->started) {
3699                 priv_unlock(priv);
3700                 return;
3701         }
3702         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
3703         priv->started = 0;
3704         if (priv->rss) {
3705                 rxq = &priv->rxq_parent;
3706                 r = 1;
3707         } else {
3708                 rxq = (*priv->rxqs)[0];
3709                 r = priv->rxqs_n;
3710         }
3711         /* Iterate only once when RSS is enabled. */
3712         do {
3713                 /* Ignore nonexistent RX queues. */
3714                 if (rxq == NULL)
3715                         continue;
3716                 rxq_allmulticast_disable(rxq);
3717                 rxq_promiscuous_disable(rxq);
3718                 rxq_mac_addrs_del(rxq);
3719         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3720         priv_unlock(priv);
3721 }
3722
3723 /**
3724  * Dummy DPDK callback for TX.
3725  *
3726  * This function is used to temporarily replace the real callback during
3727  * unsafe control operations on the queue, or in case of error.
3728  *
3729  * @param dpdk_txq
3730  *   Generic pointer to TX queue structure.
3731  * @param[in] pkts
3732  *   Packets to transmit.
3733  * @param pkts_n
3734  *   Number of packets in array.
3735  *
3736  * @return
3737  *   Number of packets successfully transmitted (<= pkts_n).
3738  */
3739 static uint16_t
3740 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
3741 {
3742         (void)dpdk_txq;
3743         (void)pkts;
3744         (void)pkts_n;
3745         return 0;
3746 }
3747
3748 /**
3749  * Dummy DPDK callback for RX.
3750  *
3751  * This function is used to temporarily replace the real callback during
3752  * unsafe control operations on the queue, or in case of error.
3753  *
3754  * @param dpdk_rxq
3755  *   Generic pointer to RX queue structure.
3756  * @param[out] pkts
3757  *   Array to store received packets.
3758  * @param pkts_n
3759  *   Maximum number of packets in array.
3760  *
3761  * @return
3762  *   Number of packets successfully received (<= pkts_n).
3763  */
3764 static uint16_t
3765 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
3766 {
3767         (void)dpdk_rxq;
3768         (void)pkts;
3769         (void)pkts_n;
3770         return 0;
3771 }
3772
3773 /**
3774  * DPDK callback to close the device.
3775  *
3776  * Destroy all queues and objects, free memory.
3777  *
3778  * @param dev
3779  *   Pointer to Ethernet device structure.
3780  */
3781 static void
3782 mlx4_dev_close(struct rte_eth_dev *dev)
3783 {
3784         struct priv *priv = dev->data->dev_private;
3785         void *tmp;
3786         unsigned int i;
3787
3788         priv_lock(priv);
3789         DEBUG("%p: closing device \"%s\"",
3790               (void *)dev,
3791               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
3792         /* Prevent crashes when queues are still in use. This is unfortunately
3793          * still required for DPDK 1.3 because some programs (such as testpmd)
3794          * never release them before closing the device. */
3795         dev->rx_pkt_burst = removed_rx_burst;
3796         dev->tx_pkt_burst = removed_tx_burst;
3797         if (priv->rxqs != NULL) {
3798                 /* XXX race condition if mlx4_rx_burst() is still running. */
3799                 usleep(1000);
3800                 for (i = 0; (i != priv->rxqs_n); ++i) {
3801                         tmp = (*priv->rxqs)[i];
3802                         if (tmp == NULL)
3803                                 continue;
3804                         (*priv->rxqs)[i] = NULL;
3805                         rxq_cleanup(tmp);
3806                         rte_free(tmp);
3807                 }
3808                 priv->rxqs_n = 0;
3809                 priv->rxqs = NULL;
3810         }
3811         if (priv->txqs != NULL) {
3812                 /* XXX race condition if mlx4_tx_burst() is still running. */
3813                 usleep(1000);
3814                 for (i = 0; (i != priv->txqs_n); ++i) {
3815                         tmp = (*priv->txqs)[i];
3816                         if (tmp == NULL)
3817                                 continue;
3818                         (*priv->txqs)[i] = NULL;
3819                         txq_cleanup(tmp);
3820                         rte_free(tmp);
3821                 }
3822                 priv->txqs_n = 0;
3823                 priv->txqs = NULL;
3824         }
3825         if (priv->rss)
3826                 rxq_cleanup(&priv->rxq_parent);
3827         if (priv->pd != NULL) {
3828                 assert(priv->ctx != NULL);
3829                 claim_zero(ibv_dealloc_pd(priv->pd));
3830                 claim_zero(ibv_close_device(priv->ctx));
3831         } else
3832                 assert(priv->ctx == NULL);
3833         priv_unlock(priv);
3834         memset(priv, 0, sizeof(*priv));
3835 }
3836
3837 /**
3838  * DPDK callback to get information about the device.
3839  *
3840  * @param dev
3841  *   Pointer to Ethernet device structure.
3842  * @param[out] info
3843  *   Info structure output buffer.
3844  */
3845 static void
3846 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
3847 {
3848         struct priv *priv = dev->data->dev_private;
3849         unsigned int max;
3850
3851         priv_lock(priv);
3852         /* FIXME: we should ask the device for these values. */
3853         info->min_rx_bufsize = 32;
3854         info->max_rx_pktlen = 65536;
3855         /*
3856          * Since we need one CQ per QP, the limit is the minimum number
3857          * between the two values.
3858          */
3859         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
3860                priv->device_attr.max_qp : priv->device_attr.max_cq);
3861         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
3862         if (max >= 65535)
3863                 max = 65535;
3864         info->max_rx_queues = max;
3865         info->max_tx_queues = max;
3866         info->max_mac_addrs = elemof(priv->mac);
3867         info->rx_offload_capa =
3868                 (priv->hw_csum ?
3869                  (DEV_RX_OFFLOAD_IPV4_CKSUM |
3870                   DEV_RX_OFFLOAD_UDP_CKSUM |
3871                   DEV_RX_OFFLOAD_TCP_CKSUM) :
3872                  0);
3873         info->tx_offload_capa =
3874                 (priv->hw_csum ?
3875                  (DEV_TX_OFFLOAD_IPV4_CKSUM |
3876                   DEV_TX_OFFLOAD_UDP_CKSUM |
3877                   DEV_TX_OFFLOAD_TCP_CKSUM) :
3878                  0);
3879         priv_unlock(priv);
3880 }
3881
3882 /**
3883  * DPDK callback to get device statistics.
3884  *
3885  * @param dev
3886  *   Pointer to Ethernet device structure.
3887  * @param[out] stats
3888  *   Stats structure output buffer.
3889  */
3890 static void
3891 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
3892 {
3893         struct priv *priv = dev->data->dev_private;
3894         struct rte_eth_stats tmp = {0};
3895         unsigned int i;
3896         unsigned int idx;
3897
3898         priv_lock(priv);
3899         /* Add software counters. */
3900         for (i = 0; (i != priv->rxqs_n); ++i) {
3901                 struct rxq *rxq = (*priv->rxqs)[i];
3902
3903                 if (rxq == NULL)
3904                         continue;
3905                 idx = rxq->stats.idx;
3906                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3907 #ifdef MLX4_PMD_SOFT_COUNTERS
3908                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
3909                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
3910 #endif
3911                         tmp.q_errors[idx] += (rxq->stats.idropped +
3912                                               rxq->stats.rx_nombuf);
3913                 }
3914 #ifdef MLX4_PMD_SOFT_COUNTERS
3915                 tmp.ipackets += rxq->stats.ipackets;
3916                 tmp.ibytes += rxq->stats.ibytes;
3917 #endif
3918                 tmp.ierrors += rxq->stats.idropped;
3919                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
3920         }
3921         for (i = 0; (i != priv->txqs_n); ++i) {
3922                 struct txq *txq = (*priv->txqs)[i];
3923
3924                 if (txq == NULL)
3925                         continue;
3926                 idx = txq->stats.idx;
3927                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3928 #ifdef MLX4_PMD_SOFT_COUNTERS
3929                         tmp.q_opackets[idx] += txq->stats.opackets;
3930                         tmp.q_obytes[idx] += txq->stats.obytes;
3931 #endif
3932                         tmp.q_errors[idx] += txq->stats.odropped;
3933                 }
3934 #ifdef MLX4_PMD_SOFT_COUNTERS
3935                 tmp.opackets += txq->stats.opackets;
3936                 tmp.obytes += txq->stats.obytes;
3937 #endif
3938                 tmp.oerrors += txq->stats.odropped;
3939         }
3940 #ifndef MLX4_PMD_SOFT_COUNTERS
3941         /* FIXME: retrieve and add hardware counters. */
3942 #endif
3943         *stats = tmp;
3944         priv_unlock(priv);
3945 }
3946
3947 /**
3948  * DPDK callback to clear device statistics.
3949  *
3950  * @param dev
3951  *   Pointer to Ethernet device structure.
3952  */
3953 static void
3954 mlx4_stats_reset(struct rte_eth_dev *dev)
3955 {
3956         struct priv *priv = dev->data->dev_private;
3957         unsigned int i;
3958         unsigned int idx;
3959
3960         priv_lock(priv);
3961         for (i = 0; (i != priv->rxqs_n); ++i) {
3962                 if ((*priv->rxqs)[i] == NULL)
3963                         continue;
3964                 idx = (*priv->rxqs)[i]->stats.idx;
3965                 (*priv->rxqs)[i]->stats =
3966                         (struct mlx4_rxq_stats){ .idx = idx };
3967         }
3968         for (i = 0; (i != priv->txqs_n); ++i) {
3969                 if ((*priv->txqs)[i] == NULL)
3970                         continue;
3971                 idx = (*priv->rxqs)[i]->stats.idx;
3972                 (*priv->txqs)[i]->stats =
3973                         (struct mlx4_txq_stats){ .idx = idx };
3974         }
3975 #ifndef MLX4_PMD_SOFT_COUNTERS
3976         /* FIXME: reset hardware counters. */
3977 #endif
3978         priv_unlock(priv);
3979 }
3980
3981 /**
3982  * DPDK callback to remove a MAC address.
3983  *
3984  * @param dev
3985  *   Pointer to Ethernet device structure.
3986  * @param index
3987  *   MAC address index.
3988  */
3989 static void
3990 mlx4_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
3991 {
3992         struct priv *priv = dev->data->dev_private;
3993
3994         priv_lock(priv);
3995         DEBUG("%p: removing MAC address from index %" PRIu32,
3996               (void *)dev, index);
3997         if (index >= MLX4_MAX_MAC_ADDRESSES)
3998                 goto end;
3999         /* Refuse to remove the broadcast address, this one is special. */
4000         if (!memcmp(priv->mac[index].addr_bytes, "\xff\xff\xff\xff\xff\xff",
4001                     ETHER_ADDR_LEN))
4002                 goto end;
4003         priv_mac_addr_del(priv, index);
4004 end:
4005         priv_unlock(priv);
4006 }
4007
4008 /**
4009  * DPDK callback to add a MAC address.
4010  *
4011  * @param dev
4012  *   Pointer to Ethernet device structure.
4013  * @param mac_addr
4014  *   MAC address to register.
4015  * @param index
4016  *   MAC address index.
4017  * @param vmdq
4018  *   VMDq pool index to associate address with (ignored).
4019  */
4020 static void
4021 mlx4_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
4022                   uint32_t index, uint32_t vmdq)
4023 {
4024         struct priv *priv = dev->data->dev_private;
4025
4026         (void)vmdq;
4027         priv_lock(priv);
4028         DEBUG("%p: adding MAC address at index %" PRIu32,
4029               (void *)dev, index);
4030         if (index >= MLX4_MAX_MAC_ADDRESSES)
4031                 goto end;
4032         /* Refuse to add the broadcast address, this one is special. */
4033         if (!memcmp(mac_addr->addr_bytes, "\xff\xff\xff\xff\xff\xff",
4034                     ETHER_ADDR_LEN))
4035                 goto end;
4036         priv_mac_addr_add(priv, index,
4037                           (const uint8_t (*)[ETHER_ADDR_LEN])
4038                           mac_addr->addr_bytes);
4039 end:
4040         priv_unlock(priv);
4041 }
4042
4043 /**
4044  * DPDK callback to enable promiscuous mode.
4045  *
4046  * @param dev
4047  *   Pointer to Ethernet device structure.
4048  */
4049 static void
4050 mlx4_promiscuous_enable(struct rte_eth_dev *dev)
4051 {
4052         struct priv *priv = dev->data->dev_private;
4053         unsigned int i;
4054         int ret;
4055
4056         priv_lock(priv);
4057         if (priv->promisc) {
4058                 priv_unlock(priv);
4059                 return;
4060         }
4061         /* If device isn't started, this is all we need to do. */
4062         if (!priv->started)
4063                 goto end;
4064         if (priv->rss) {
4065                 ret = rxq_promiscuous_enable(&priv->rxq_parent);
4066                 if (ret) {
4067                         priv_unlock(priv);
4068                         return;
4069                 }
4070                 goto end;
4071         }
4072         for (i = 0; (i != priv->rxqs_n); ++i) {
4073                 if ((*priv->rxqs)[i] == NULL)
4074                         continue;
4075                 ret = rxq_promiscuous_enable((*priv->rxqs)[i]);
4076                 if (!ret)
4077                         continue;
4078                 /* Failure, rollback. */
4079                 while (i != 0)
4080                         if ((*priv->rxqs)[--i] != NULL)
4081                                 rxq_promiscuous_disable((*priv->rxqs)[i]);
4082                 priv_unlock(priv);
4083                 return;
4084         }
4085 end:
4086         priv->promisc = 1;
4087         priv_unlock(priv);
4088 }
4089
4090 /**
4091  * DPDK callback to disable promiscuous mode.
4092  *
4093  * @param dev
4094  *   Pointer to Ethernet device structure.
4095  */
4096 static void
4097 mlx4_promiscuous_disable(struct rte_eth_dev *dev)
4098 {
4099         struct priv *priv = dev->data->dev_private;
4100         unsigned int i;
4101
4102         priv_lock(priv);
4103         if (!priv->promisc) {
4104                 priv_unlock(priv);
4105                 return;
4106         }
4107         if (priv->rss) {
4108                 rxq_promiscuous_disable(&priv->rxq_parent);
4109                 goto end;
4110         }
4111         for (i = 0; (i != priv->rxqs_n); ++i)
4112                 if ((*priv->rxqs)[i] != NULL)
4113                         rxq_promiscuous_disable((*priv->rxqs)[i]);
4114 end:
4115         priv->promisc = 0;
4116         priv_unlock(priv);
4117 }
4118
4119 /**
4120  * DPDK callback to enable allmulti mode.
4121  *
4122  * @param dev
4123  *   Pointer to Ethernet device structure.
4124  */
4125 static void
4126 mlx4_allmulticast_enable(struct rte_eth_dev *dev)
4127 {
4128         struct priv *priv = dev->data->dev_private;
4129         unsigned int i;
4130         int ret;
4131
4132         priv_lock(priv);
4133         if (priv->allmulti) {
4134                 priv_unlock(priv);
4135                 return;
4136         }
4137         /* If device isn't started, this is all we need to do. */
4138         if (!priv->started)
4139                 goto end;
4140         if (priv->rss) {
4141                 ret = rxq_allmulticast_enable(&priv->rxq_parent);
4142                 if (ret) {
4143                         priv_unlock(priv);
4144                         return;
4145                 }
4146                 goto end;
4147         }
4148         for (i = 0; (i != priv->rxqs_n); ++i) {
4149                 if ((*priv->rxqs)[i] == NULL)
4150                         continue;
4151                 ret = rxq_allmulticast_enable((*priv->rxqs)[i]);
4152                 if (!ret)
4153                         continue;
4154                 /* Failure, rollback. */
4155                 while (i != 0)
4156                         if ((*priv->rxqs)[--i] != NULL)
4157                                 rxq_allmulticast_disable((*priv->rxqs)[i]);
4158                 priv_unlock(priv);
4159                 return;
4160         }
4161 end:
4162         priv->allmulti = 1;
4163         priv_unlock(priv);
4164 }
4165
4166 /**
4167  * DPDK callback to disable allmulti mode.
4168  *
4169  * @param dev
4170  *   Pointer to Ethernet device structure.
4171  */
4172 static void
4173 mlx4_allmulticast_disable(struct rte_eth_dev *dev)
4174 {
4175         struct priv *priv = dev->data->dev_private;
4176         unsigned int i;
4177
4178         priv_lock(priv);
4179         if (!priv->allmulti) {
4180                 priv_unlock(priv);
4181                 return;
4182         }
4183         if (priv->rss) {
4184                 rxq_allmulticast_disable(&priv->rxq_parent);
4185                 goto end;
4186         }
4187         for (i = 0; (i != priv->rxqs_n); ++i)
4188                 if ((*priv->rxqs)[i] != NULL)
4189                         rxq_allmulticast_disable((*priv->rxqs)[i]);
4190 end:
4191         priv->allmulti = 0;
4192         priv_unlock(priv);
4193 }
4194
4195 /**
4196  * DPDK callback to retrieve physical link information (unlocked version).
4197  *
4198  * @param dev
4199  *   Pointer to Ethernet device structure.
4200  * @param wait_to_complete
4201  *   Wait for request completion (ignored).
4202  */
4203 static int
4204 mlx4_link_update_unlocked(struct rte_eth_dev *dev, int wait_to_complete)
4205 {
4206         struct priv *priv = dev->data->dev_private;
4207         struct ethtool_cmd edata = {
4208                 .cmd = ETHTOOL_GSET
4209         };
4210         struct ifreq ifr;
4211         struct rte_eth_link dev_link;
4212         int link_speed = 0;
4213
4214         (void)wait_to_complete;
4215         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
4216                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(errno));
4217                 return -1;
4218         }
4219         memset(&dev_link, 0, sizeof(dev_link));
4220         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
4221                                 (ifr.ifr_flags & IFF_RUNNING));
4222         ifr.ifr_data = &edata;
4223         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4224                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
4225                      strerror(errno));
4226                 return -1;
4227         }
4228         link_speed = ethtool_cmd_speed(&edata);
4229         if (link_speed == -1)
4230                 dev_link.link_speed = 0;
4231         else
4232                 dev_link.link_speed = link_speed;
4233         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
4234                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
4235         if (memcmp(&dev_link, &dev->data->dev_link, sizeof(dev_link))) {
4236                 /* Link status changed. */
4237                 dev->data->dev_link = dev_link;
4238                 return 0;
4239         }
4240         /* Link status is still the same. */
4241         return -1;
4242 }
4243
4244 /**
4245  * DPDK callback to retrieve physical link information.
4246  *
4247  * @param dev
4248  *   Pointer to Ethernet device structure.
4249  * @param wait_to_complete
4250  *   Wait for request completion (ignored).
4251  */
4252 static int
4253 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
4254 {
4255         struct priv *priv = dev->data->dev_private;
4256         int ret;
4257
4258         priv_lock(priv);
4259         ret = mlx4_link_update_unlocked(dev, wait_to_complete);
4260         priv_unlock(priv);
4261         return ret;
4262 }
4263
4264 /**
4265  * DPDK callback to change the MTU.
4266  *
4267  * Setting the MTU affects hardware MRU (packets larger than the MTU cannot be
4268  * received). Use this as a hint to enable/disable scattered packets support
4269  * and improve performance when not needed.
4270  * Since failure is not an option, reconfiguring queues on the fly is not
4271  * recommended.
4272  *
4273  * @param dev
4274  *   Pointer to Ethernet device structure.
4275  * @param in_mtu
4276  *   New MTU.
4277  *
4278  * @return
4279  *   0 on success, negative errno value on failure.
4280  */
4281 static int
4282 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
4283 {
4284         struct priv *priv = dev->data->dev_private;
4285         int ret = 0;
4286         unsigned int i;
4287         uint16_t (*rx_func)(void *, struct rte_mbuf **, uint16_t) =
4288                 mlx4_rx_burst;
4289
4290         priv_lock(priv);
4291         /* Set kernel interface MTU first. */
4292         if (priv_set_mtu(priv, mtu)) {
4293                 ret = errno;
4294                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
4295                      strerror(ret));
4296                 goto out;
4297         } else
4298                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
4299         priv->mtu = mtu;
4300         /* Temporarily replace RX handler with a fake one, assuming it has not
4301          * been copied elsewhere. */
4302         dev->rx_pkt_burst = removed_rx_burst;
4303         /* Make sure everyone has left mlx4_rx_burst() and uses
4304          * removed_rx_burst() instead. */
4305         rte_wmb();
4306         usleep(1000);
4307         /* Reconfigure each RX queue. */
4308         for (i = 0; (i != priv->rxqs_n); ++i) {
4309                 struct rxq *rxq = (*priv->rxqs)[i];
4310                 unsigned int max_frame_len;
4311                 int sp;
4312
4313                 if (rxq == NULL)
4314                         continue;
4315                 /* Calculate new maximum frame length according to MTU and
4316                  * toggle scattered support (sp) if necessary. */
4317                 max_frame_len = (priv->mtu + ETHER_HDR_LEN +
4318                                  (ETHER_MAX_VLAN_FRAME_LEN - ETHER_MAX_LEN));
4319                 sp = (max_frame_len > (rxq->mb_len - RTE_PKTMBUF_HEADROOM));
4320                 /* Provide new values to rxq_setup(). */
4321                 dev->data->dev_conf.rxmode.jumbo_frame = sp;
4322                 dev->data->dev_conf.rxmode.max_rx_pkt_len = max_frame_len;
4323                 ret = rxq_rehash(dev, rxq);
4324                 if (ret) {
4325                         /* Force SP RX if that queue requires it and abort. */
4326                         if (rxq->sp)
4327                                 rx_func = mlx4_rx_burst_sp;
4328                         break;
4329                 }
4330                 /* Reenable non-RSS queue attributes. No need to check
4331                  * for errors at this stage. */
4332                 if (!priv->rss) {
4333                         rxq_mac_addrs_add(rxq);
4334                         if (priv->promisc)
4335                                 rxq_promiscuous_enable(rxq);
4336                         if (priv->allmulti)
4337                                 rxq_allmulticast_enable(rxq);
4338                 }
4339                 /* Scattered burst function takes priority. */
4340                 if (rxq->sp)
4341                         rx_func = mlx4_rx_burst_sp;
4342         }
4343         /* Burst functions can now be called again. */
4344         rte_wmb();
4345         dev->rx_pkt_burst = rx_func;
4346 out:
4347         priv_unlock(priv);
4348         assert(ret >= 0);
4349         return -ret;
4350 }
4351
4352 /**
4353  * DPDK callback to get flow control status.
4354  *
4355  * @param dev
4356  *   Pointer to Ethernet device structure.
4357  * @param[out] fc_conf
4358  *   Flow control output buffer.
4359  *
4360  * @return
4361  *   0 on success, negative errno value on failure.
4362  */
4363 static int
4364 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4365 {
4366         struct priv *priv = dev->data->dev_private;
4367         struct ifreq ifr;
4368         struct ethtool_pauseparam ethpause = {
4369                 .cmd = ETHTOOL_GPAUSEPARAM
4370         };
4371         int ret;
4372
4373         ifr.ifr_data = &ethpause;
4374         priv_lock(priv);
4375         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4376                 ret = errno;
4377                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
4378                      " failed: %s",
4379                      strerror(ret));
4380                 goto out;
4381         }
4382
4383         fc_conf->autoneg = ethpause.autoneg;
4384         if (ethpause.rx_pause && ethpause.tx_pause)
4385                 fc_conf->mode = RTE_FC_FULL;
4386         else if (ethpause.rx_pause)
4387                 fc_conf->mode = RTE_FC_RX_PAUSE;
4388         else if (ethpause.tx_pause)
4389                 fc_conf->mode = RTE_FC_TX_PAUSE;
4390         else
4391                 fc_conf->mode = RTE_FC_NONE;
4392         ret = 0;
4393
4394 out:
4395         priv_unlock(priv);
4396         assert(ret >= 0);
4397         return -ret;
4398 }
4399
4400 /**
4401  * DPDK callback to modify flow control parameters.
4402  *
4403  * @param dev
4404  *   Pointer to Ethernet device structure.
4405  * @param[in] fc_conf
4406  *   Flow control parameters.
4407  *
4408  * @return
4409  *   0 on success, negative errno value on failure.
4410  */
4411 static int
4412 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4413 {
4414         struct priv *priv = dev->data->dev_private;
4415         struct ifreq ifr;
4416         struct ethtool_pauseparam ethpause = {
4417                 .cmd = ETHTOOL_SPAUSEPARAM
4418         };
4419         int ret;
4420
4421         ifr.ifr_data = &ethpause;
4422         ethpause.autoneg = fc_conf->autoneg;
4423         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4424             (fc_conf->mode & RTE_FC_RX_PAUSE))
4425                 ethpause.rx_pause = 1;
4426         else
4427                 ethpause.rx_pause = 0;
4428
4429         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4430             (fc_conf->mode & RTE_FC_TX_PAUSE))
4431                 ethpause.tx_pause = 1;
4432         else
4433                 ethpause.tx_pause = 0;
4434
4435         priv_lock(priv);
4436         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4437                 ret = errno;
4438                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
4439                      " failed: %s",
4440                      strerror(ret));
4441                 goto out;
4442         }
4443         ret = 0;
4444
4445 out:
4446         priv_unlock(priv);
4447         assert(ret >= 0);
4448         return -ret;
4449 }
4450
4451 /**
4452  * Configure a VLAN filter.
4453  *
4454  * @param dev
4455  *   Pointer to Ethernet device structure.
4456  * @param vlan_id
4457  *   VLAN ID to filter.
4458  * @param on
4459  *   Toggle filter.
4460  *
4461  * @return
4462  *   0 on success, errno value on failure.
4463  */
4464 static int
4465 vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4466 {
4467         struct priv *priv = dev->data->dev_private;
4468         unsigned int i;
4469         unsigned int j = -1;
4470
4471         DEBUG("%p: %s VLAN filter ID %" PRIu16,
4472               (void *)dev, (on ? "enable" : "disable"), vlan_id);
4473         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
4474                 if (!priv->vlan_filter[i].enabled) {
4475                         /* Unused index, remember it. */
4476                         j = i;
4477                         continue;
4478                 }
4479                 if (priv->vlan_filter[i].id != vlan_id)
4480                         continue;
4481                 /* This VLAN ID is already known, use its index. */
4482                 j = i;
4483                 break;
4484         }
4485         /* Check if there's room for another VLAN filter. */
4486         if (j == (unsigned int)-1)
4487                 return ENOMEM;
4488         /*
4489          * VLAN filters apply to all configured MAC addresses, flow
4490          * specifications must be reconfigured accordingly.
4491          */
4492         priv->vlan_filter[j].id = vlan_id;
4493         if ((on) && (!priv->vlan_filter[j].enabled)) {
4494                 /*
4495                  * Filter is disabled, enable it.
4496                  * Rehashing flows in all RX queues is necessary.
4497                  */
4498                 if (priv->rss)
4499                         rxq_mac_addrs_del(&priv->rxq_parent);
4500                 else
4501                         for (i = 0; (i != priv->rxqs_n); ++i)
4502                                 if ((*priv->rxqs)[i] != NULL)
4503                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4504                 priv->vlan_filter[j].enabled = 1;
4505                 if (priv->started) {
4506                         if (priv->rss)
4507                                 rxq_mac_addrs_add(&priv->rxq_parent);
4508                         else
4509                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4510                                         if ((*priv->rxqs)[i] == NULL)
4511                                                 continue;
4512                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4513                                 }
4514                 }
4515         } else if ((!on) && (priv->vlan_filter[j].enabled)) {
4516                 /*
4517                  * Filter is enabled, disable it.
4518                  * Rehashing flows in all RX queues is necessary.
4519                  */
4520                 if (priv->rss)
4521                         rxq_mac_addrs_del(&priv->rxq_parent);
4522                 else
4523                         for (i = 0; (i != priv->rxqs_n); ++i)
4524                                 if ((*priv->rxqs)[i] != NULL)
4525                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4526                 priv->vlan_filter[j].enabled = 0;
4527                 if (priv->started) {
4528                         if (priv->rss)
4529                                 rxq_mac_addrs_add(&priv->rxq_parent);
4530                         else
4531                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4532                                         if ((*priv->rxqs)[i] == NULL)
4533                                                 continue;
4534                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4535                                 }
4536                 }
4537         }
4538         return 0;
4539 }
4540
4541 /**
4542  * DPDK callback to configure a VLAN filter.
4543  *
4544  * @param dev
4545  *   Pointer to Ethernet device structure.
4546  * @param vlan_id
4547  *   VLAN ID to filter.
4548  * @param on
4549  *   Toggle filter.
4550  *
4551  * @return
4552  *   0 on success, negative errno value on failure.
4553  */
4554 static int
4555 mlx4_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4556 {
4557         struct priv *priv = dev->data->dev_private;
4558         int ret;
4559
4560         priv_lock(priv);
4561         ret = vlan_filter_set(dev, vlan_id, on);
4562         priv_unlock(priv);
4563         assert(ret >= 0);
4564         return -ret;
4565 }
4566
4567 static const struct eth_dev_ops mlx4_dev_ops = {
4568         .dev_configure = mlx4_dev_configure,
4569         .dev_start = mlx4_dev_start,
4570         .dev_stop = mlx4_dev_stop,
4571         .dev_close = mlx4_dev_close,
4572         .promiscuous_enable = mlx4_promiscuous_enable,
4573         .promiscuous_disable = mlx4_promiscuous_disable,
4574         .allmulticast_enable = mlx4_allmulticast_enable,
4575         .allmulticast_disable = mlx4_allmulticast_disable,
4576         .link_update = mlx4_link_update,
4577         .stats_get = mlx4_stats_get,
4578         .stats_reset = mlx4_stats_reset,
4579         .queue_stats_mapping_set = NULL,
4580         .dev_infos_get = mlx4_dev_infos_get,
4581         .vlan_filter_set = mlx4_vlan_filter_set,
4582         .vlan_tpid_set = NULL,
4583         .vlan_strip_queue_set = NULL,
4584         .vlan_offload_set = NULL,
4585         .rx_queue_setup = mlx4_rx_queue_setup,
4586         .tx_queue_setup = mlx4_tx_queue_setup,
4587         .rx_queue_release = mlx4_rx_queue_release,
4588         .tx_queue_release = mlx4_tx_queue_release,
4589         .dev_led_on = NULL,
4590         .dev_led_off = NULL,
4591         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
4592         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
4593         .priority_flow_ctrl_set = NULL,
4594         .mac_addr_remove = mlx4_mac_addr_remove,
4595         .mac_addr_add = mlx4_mac_addr_add,
4596         .mtu_set = mlx4_dev_set_mtu,
4597         .udp_tunnel_add = NULL,
4598         .udp_tunnel_del = NULL,
4599         .fdir_add_signature_filter = NULL,
4600         .fdir_update_signature_filter = NULL,
4601         .fdir_remove_signature_filter = NULL,
4602         .fdir_add_perfect_filter = NULL,
4603         .fdir_update_perfect_filter = NULL,
4604         .fdir_remove_perfect_filter = NULL,
4605         .fdir_set_masks = NULL
4606 };
4607
4608 /**
4609  * Get PCI information from struct ibv_device.
4610  *
4611  * @param device
4612  *   Pointer to Ethernet device structure.
4613  * @param[out] pci_addr
4614  *   PCI bus address output buffer.
4615  *
4616  * @return
4617  *   0 on success, -1 on failure and errno is set.
4618  */
4619 static int
4620 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
4621                             struct rte_pci_addr *pci_addr)
4622 {
4623         FILE *file;
4624         char line[32];
4625         MKSTR(path, "%s/device/uevent", device->ibdev_path);
4626
4627         file = fopen(path, "rb");
4628         if (file == NULL)
4629                 return -1;
4630         while (fgets(line, sizeof(line), file) == line) {
4631                 size_t len = strlen(line);
4632                 int ret;
4633
4634                 /* Truncate long lines. */
4635                 if (len == (sizeof(line) - 1))
4636                         while (line[(len - 1)] != '\n') {
4637                                 ret = fgetc(file);
4638                                 if (ret == EOF)
4639                                         break;
4640                                 line[(len - 1)] = ret;
4641                         }
4642                 /* Extract information. */
4643                 if (sscanf(line,
4644                            "PCI_SLOT_NAME="
4645                            "%" SCNx16 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
4646                            &pci_addr->domain,
4647                            &pci_addr->bus,
4648                            &pci_addr->devid,
4649                            &pci_addr->function) == 4) {
4650                         ret = 0;
4651                         break;
4652                 }
4653         }
4654         fclose(file);
4655         return 0;
4656 }
4657
4658 /**
4659  * Get MAC address by querying netdevice.
4660  *
4661  * @param[in] priv
4662  *   struct priv for the requested device.
4663  * @param[out] mac
4664  *   MAC address output buffer.
4665  *
4666  * @return
4667  *   0 on success, -1 on failure and errno is set.
4668  */
4669 static int
4670 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
4671 {
4672         struct ifreq request;
4673
4674         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
4675                 return -1;
4676         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
4677         return 0;
4678 }
4679
4680 /* Support up to 32 adapters. */
4681 static struct {
4682         struct rte_pci_addr pci_addr; /* associated PCI address */
4683         uint32_t ports; /* physical ports bitfield. */
4684 } mlx4_dev[32];
4685
4686 /**
4687  * Get device index in mlx4_dev[] from PCI bus address.
4688  *
4689  * @param[in] pci_addr
4690  *   PCI bus address to look for.
4691  *
4692  * @return
4693  *   mlx4_dev[] index on success, -1 on failure.
4694  */
4695 static int
4696 mlx4_dev_idx(struct rte_pci_addr *pci_addr)
4697 {
4698         unsigned int i;
4699         int ret = -1;
4700
4701         assert(pci_addr != NULL);
4702         for (i = 0; (i != elemof(mlx4_dev)); ++i) {
4703                 if ((mlx4_dev[i].pci_addr.domain == pci_addr->domain) &&
4704                     (mlx4_dev[i].pci_addr.bus == pci_addr->bus) &&
4705                     (mlx4_dev[i].pci_addr.devid == pci_addr->devid) &&
4706                     (mlx4_dev[i].pci_addr.function == pci_addr->function))
4707                         return i;
4708                 if ((mlx4_dev[i].ports == 0) && (ret == -1))
4709                         ret = i;
4710         }
4711         return ret;
4712 }
4713
4714 /**
4715  * Retrieve integer value from environment variable.
4716  *
4717  * @param[in] name
4718  *   Environment variable name.
4719  *
4720  * @return
4721  *   Integer value, 0 if the variable is not set.
4722  */
4723 static int
4724 mlx4_getenv_int(const char *name)
4725 {
4726         const char *val = getenv(name);
4727
4728         if (val == NULL)
4729                 return 0;
4730         return atoi(val);
4731 }
4732
4733 static struct eth_driver mlx4_driver;
4734
4735 /**
4736  * DPDK callback to register a PCI device.
4737  *
4738  * This function creates an Ethernet device for each port of a given
4739  * PCI device.
4740  *
4741  * @param[in] pci_drv
4742  *   PCI driver structure (mlx4_driver).
4743  * @param[in] pci_dev
4744  *   PCI device information.
4745  *
4746  * @return
4747  *   0 on success, negative errno value on failure.
4748  */
4749 static int
4750 mlx4_pci_devinit(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
4751 {
4752         struct ibv_device **list;
4753         struct ibv_device *ibv_dev;
4754         int err = 0;
4755         struct ibv_context *attr_ctx = NULL;
4756         struct ibv_device_attr device_attr;
4757         unsigned int vf;
4758         int idx;
4759         int i;
4760
4761         (void)pci_drv;
4762         assert(pci_drv == &mlx4_driver.pci_drv);
4763         /* Get mlx4_dev[] index. */
4764         idx = mlx4_dev_idx(&pci_dev->addr);
4765         if (idx == -1) {
4766                 ERROR("this driver cannot support any more adapters");
4767                 return -ENOMEM;
4768         }
4769         DEBUG("using driver device index %d", idx);
4770
4771         /* Save PCI address. */
4772         mlx4_dev[idx].pci_addr = pci_dev->addr;
4773         list = ibv_get_device_list(&i);
4774         if (list == NULL) {
4775                 assert(errno);
4776                 if (errno == ENOSYS) {
4777                         WARN("cannot list devices, is ib_uverbs loaded?");
4778                         return 0;
4779                 }
4780                 return -errno;
4781         }
4782         assert(i >= 0);
4783         /*
4784          * For each listed device, check related sysfs entry against
4785          * the provided PCI ID.
4786          */
4787         while (i != 0) {
4788                 struct rte_pci_addr pci_addr;
4789
4790                 --i;
4791                 DEBUG("checking device \"%s\"", list[i]->name);
4792                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
4793                         continue;
4794                 if ((pci_dev->addr.domain != pci_addr.domain) ||
4795                     (pci_dev->addr.bus != pci_addr.bus) ||
4796                     (pci_dev->addr.devid != pci_addr.devid) ||
4797                     (pci_dev->addr.function != pci_addr.function))
4798                         continue;
4799                 vf = (pci_dev->id.device_id ==
4800                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
4801                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
4802                      list[i]->name, (vf ? "true" : "false"));
4803                 attr_ctx = ibv_open_device(list[i]);
4804                 err = errno;
4805                 break;
4806         }
4807         if (attr_ctx == NULL) {
4808                 ibv_free_device_list(list);
4809                 switch (err) {
4810                 case 0:
4811                         WARN("cannot access device, is mlx4_ib loaded?");
4812                         return 0;
4813                 case EINVAL:
4814                         WARN("cannot use device, are drivers up to date?");
4815                         return 0;
4816                 }
4817                 assert(err > 0);
4818                 return -err;
4819         }
4820         ibv_dev = list[i];
4821
4822         DEBUG("device opened");
4823         if (ibv_query_device(attr_ctx, &device_attr))
4824                 goto error;
4825         INFO("%u port(s) detected", device_attr.phys_port_cnt);
4826
4827         for (i = 0; i < device_attr.phys_port_cnt; i++) {
4828                 uint32_t port = i + 1; /* ports are indexed from one */
4829                 uint32_t test = (1 << i);
4830                 struct ibv_context *ctx = NULL;
4831                 struct ibv_port_attr port_attr;
4832                 struct ibv_pd *pd = NULL;
4833                 struct priv *priv = NULL;
4834                 struct rte_eth_dev *eth_dev;
4835 #ifdef HAVE_EXP_QUERY_DEVICE
4836                 struct ibv_exp_device_attr exp_device_attr;
4837 #endif /* HAVE_EXP_QUERY_DEVICE */
4838                 struct ether_addr mac;
4839
4840 #ifdef HAVE_EXP_QUERY_DEVICE
4841                 exp_device_attr.comp_mask = IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS;
4842 #ifdef RSS_SUPPORT
4843                 exp_device_attr.comp_mask |= IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ;
4844 #endif /* RSS_SUPPORT */
4845 #endif /* HAVE_EXP_QUERY_DEVICE */
4846
4847                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
4848
4849                 ctx = ibv_open_device(ibv_dev);
4850                 if (ctx == NULL)
4851                         goto port_error;
4852
4853                 /* Check port status. */
4854                 err = ibv_query_port(ctx, port, &port_attr);
4855                 if (err) {
4856                         ERROR("port query failed: %s", strerror(err));
4857                         goto port_error;
4858                 }
4859                 if (port_attr.state != IBV_PORT_ACTIVE)
4860                         WARN("bad state for port %d: \"%s\" (%d)",
4861                              port, ibv_port_state_str(port_attr.state),
4862                              port_attr.state);
4863
4864                 /* Allocate protection domain. */
4865                 pd = ibv_alloc_pd(ctx);
4866                 if (pd == NULL) {
4867                         ERROR("PD allocation failure");
4868                         err = ENOMEM;
4869                         goto port_error;
4870                 }
4871
4872                 mlx4_dev[idx].ports |= test;
4873
4874                 /* from rte_ethdev.c */
4875                 priv = rte_zmalloc("ethdev private structure",
4876                                    sizeof(*priv),
4877                                    RTE_CACHE_LINE_SIZE);
4878                 if (priv == NULL) {
4879                         ERROR("priv allocation failure");
4880                         err = ENOMEM;
4881                         goto port_error;
4882                 }
4883
4884                 priv->ctx = ctx;
4885                 priv->device_attr = device_attr;
4886                 priv->port = port;
4887                 priv->pd = pd;
4888                 priv->mtu = ETHER_MTU;
4889 #ifdef HAVE_EXP_QUERY_DEVICE
4890                 if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4891                         ERROR("ibv_exp_query_device() failed");
4892                         goto port_error;
4893                 }
4894 #ifdef RSS_SUPPORT
4895                 if ((exp_device_attr.exp_device_cap_flags &
4896                      IBV_EXP_DEVICE_QPG) &&
4897                     (exp_device_attr.exp_device_cap_flags &
4898                      IBV_EXP_DEVICE_UD_RSS) &&
4899                     (exp_device_attr.comp_mask &
4900                      IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ) &&
4901                     (exp_device_attr.max_rss_tbl_sz > 0)) {
4902                         priv->hw_qpg = 1;
4903                         priv->hw_rss = 1;
4904                         priv->max_rss_tbl_sz = exp_device_attr.max_rss_tbl_sz;
4905                 } else {
4906                         priv->hw_qpg = 0;
4907                         priv->hw_rss = 0;
4908                         priv->max_rss_tbl_sz = 0;
4909                 }
4910                 priv->hw_tss = !!(exp_device_attr.exp_device_cap_flags &
4911                                   IBV_EXP_DEVICE_UD_TSS);
4912                 DEBUG("device flags: %s%s%s",
4913                       (priv->hw_qpg ? "IBV_DEVICE_QPG " : ""),
4914                       (priv->hw_tss ? "IBV_DEVICE_TSS " : ""),
4915                       (priv->hw_rss ? "IBV_DEVICE_RSS " : ""));
4916                 if (priv->hw_rss)
4917                         DEBUG("maximum RSS indirection table size: %u",
4918                               exp_device_attr.max_rss_tbl_sz);
4919 #endif /* RSS_SUPPORT */
4920
4921                 priv->hw_csum =
4922                         ((exp_device_attr.exp_device_cap_flags &
4923                           IBV_EXP_DEVICE_RX_CSUM_TCP_UDP_PKT) &&
4924                          (exp_device_attr.exp_device_cap_flags &
4925                           IBV_EXP_DEVICE_RX_CSUM_IP_PKT));
4926                 DEBUG("checksum offloading is %ssupported",
4927                       (priv->hw_csum ? "" : "not "));
4928
4929                 priv->hw_csum_l2tun = !!(exp_device_attr.exp_device_cap_flags &
4930                                          IBV_EXP_DEVICE_VXLAN_SUPPORT);
4931                 DEBUG("L2 tunnel checksum offloads are %ssupported",
4932                       (priv->hw_csum_l2tun ? "" : "not "));
4933
4934 #ifdef INLINE_RECV
4935                 priv->inl_recv_size = mlx4_getenv_int("MLX4_INLINE_RECV_SIZE");
4936
4937                 if (priv->inl_recv_size) {
4938                         exp_device_attr.comp_mask =
4939                                 IBV_EXP_DEVICE_ATTR_INLINE_RECV_SZ;
4940                         if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4941                                 INFO("Couldn't query device for inline-receive"
4942                                      " capabilities.");
4943                                 priv->inl_recv_size = 0;
4944                         } else {
4945                                 if ((unsigned)exp_device_attr.inline_recv_sz <
4946                                     priv->inl_recv_size) {
4947                                         INFO("Max inline-receive (%d) <"
4948                                              " requested inline-receive (%u)",
4949                                              exp_device_attr.inline_recv_sz,
4950                                              priv->inl_recv_size);
4951                                         priv->inl_recv_size =
4952                                                 exp_device_attr.inline_recv_sz;
4953                                 }
4954                         }
4955                         INFO("Set inline receive size to %u",
4956                              priv->inl_recv_size);
4957                 }
4958 #endif /* INLINE_RECV */
4959 #endif /* HAVE_EXP_QUERY_DEVICE */
4960
4961                 (void)mlx4_getenv_int;
4962                 priv->vf = vf;
4963                 /* Configure the first MAC address by default. */
4964                 if (priv_get_mac(priv, &mac.addr_bytes)) {
4965                         ERROR("cannot get MAC address, is mlx4_en loaded?"
4966                               " (errno: %s)", strerror(errno));
4967                         goto port_error;
4968                 }
4969                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
4970                      priv->port,
4971                      mac.addr_bytes[0], mac.addr_bytes[1],
4972                      mac.addr_bytes[2], mac.addr_bytes[3],
4973                      mac.addr_bytes[4], mac.addr_bytes[5]);
4974                 /* Register MAC and broadcast addresses. */
4975                 claim_zero(priv_mac_addr_add(priv, 0,
4976                                              (const uint8_t (*)[ETHER_ADDR_LEN])
4977                                              mac.addr_bytes));
4978                 claim_zero(priv_mac_addr_add(priv, 1,
4979                                              &(const uint8_t [ETHER_ADDR_LEN])
4980                                              { "\xff\xff\xff\xff\xff\xff" }));
4981 #ifndef NDEBUG
4982                 {
4983                         char ifname[IF_NAMESIZE];
4984
4985                         if (priv_get_ifname(priv, &ifname) == 0)
4986                                 DEBUG("port %u ifname is \"%s\"",
4987                                       priv->port, ifname);
4988                         else
4989                                 DEBUG("port %u ifname is unknown", priv->port);
4990                 }
4991 #endif
4992                 /* Get actual MTU if possible. */
4993                 priv_get_mtu(priv, &priv->mtu);
4994                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
4995
4996                 /* from rte_ethdev.c */
4997                 {
4998                         char name[RTE_ETH_NAME_MAX_LEN];
4999
5000                         snprintf(name, sizeof(name), "%s port %u",
5001                                  ibv_get_device_name(ibv_dev), port);
5002                         eth_dev = rte_eth_dev_allocate(name, RTE_ETH_DEV_PCI);
5003                 }
5004                 if (eth_dev == NULL) {
5005                         ERROR("can not allocate rte ethdev");
5006                         err = ENOMEM;
5007                         goto port_error;
5008                 }
5009
5010                 eth_dev->data->dev_private = priv;
5011                 eth_dev->pci_dev = pci_dev;
5012                 eth_dev->driver = &mlx4_driver;
5013                 eth_dev->data->rx_mbuf_alloc_failed = 0;
5014                 eth_dev->data->mtu = ETHER_MTU;
5015
5016                 priv->dev = eth_dev;
5017                 eth_dev->dev_ops = &mlx4_dev_ops;
5018                 eth_dev->data->mac_addrs = priv->mac;
5019
5020                 /* Bring Ethernet device up. */
5021                 DEBUG("forcing Ethernet interface up");
5022                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
5023                 continue;
5024
5025 port_error:
5026                 rte_free(priv);
5027                 if (pd)
5028                         claim_zero(ibv_dealloc_pd(pd));
5029                 if (ctx)
5030                         claim_zero(ibv_close_device(ctx));
5031                 break;
5032         }
5033
5034         /*
5035          * XXX if something went wrong in the loop above, there is a resource
5036          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
5037          * long as the dpdk does not provide a way to deallocate a ethdev and a
5038          * way to enumerate the registered ethdevs to free the previous ones.
5039          */
5040
5041         /* no port found, complain */
5042         if (!mlx4_dev[idx].ports) {
5043                 err = ENODEV;
5044                 goto error;
5045         }
5046
5047 error:
5048         if (attr_ctx)
5049                 claim_zero(ibv_close_device(attr_ctx));
5050         if (list)
5051                 ibv_free_device_list(list);
5052         assert(err >= 0);
5053         return -err;
5054 }
5055
5056 static const struct rte_pci_id mlx4_pci_id_map[] = {
5057         {
5058                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5059                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3,
5060                 .subsystem_vendor_id = PCI_ANY_ID,
5061                 .subsystem_device_id = PCI_ANY_ID
5062         },
5063         {
5064                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5065                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO,
5066                 .subsystem_vendor_id = PCI_ANY_ID,
5067                 .subsystem_device_id = PCI_ANY_ID
5068         },
5069         {
5070                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5071                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3VF,
5072                 .subsystem_vendor_id = PCI_ANY_ID,
5073                 .subsystem_device_id = PCI_ANY_ID
5074         },
5075         {
5076                 .vendor_id = 0
5077         }
5078 };
5079
5080 static struct eth_driver mlx4_driver = {
5081         .pci_drv = {
5082                 .name = MLX4_DRIVER_NAME,
5083                 .id_table = mlx4_pci_id_map,
5084                 .devinit = mlx4_pci_devinit,
5085         },
5086         .dev_private_size = sizeof(struct priv)
5087 };
5088
5089 /**
5090  * Driver initialization routine.
5091  */
5092 static int
5093 rte_mlx4_pmd_init(const char *name, const char *args)
5094 {
5095         (void)name;
5096         (void)args;
5097         /*
5098          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
5099          * huge pages. Calling ibv_fork_init() during init allows
5100          * applications to use fork() safely for purposes other than
5101          * using this PMD, which is not supported in forked processes.
5102          */
5103         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
5104         ibv_fork_init();
5105         rte_eal_pci_register(&mlx4_driver.pci_drv);
5106         return 0;
5107 }
5108
5109 static struct rte_driver rte_mlx4_driver = {
5110         .type = PMD_PDEV,
5111         .name = MLX4_DRIVER_NAME,
5112         .init = rte_mlx4_pmd_init,
5113 };
5114
5115 PMD_REGISTER_DRIVER(rte_mlx4_driver)