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