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