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