mlx4: fix 32-bit build
[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(((uintptr_t)rte_pktmbuf_mtod(buf, char *) -
1108                         (uintptr_t)buf) <= 0xffff);
1109                 WR_ID(wr->wr_id).offset =
1110                         ((uintptr_t)rte_pktmbuf_mtod(buf, char *) -
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 = (uintptr_t)rte_pktmbuf_mtod(buf, char *);
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 = (uintptr_t)rte_pktmbuf_mtod(buf,
1597                                                                         char *);
1598                                 sge->length = (buf->buf_len -
1599                                                RTE_PKTMBUF_HEADROOM);
1600                         } else {
1601                                 /* Subsequent SGEs lose theirs. */
1602                                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1603                                 SET_DATA_OFF(buf, 0);
1604                                 sge->addr = (uintptr_t)buf->buf_addr;
1605                                 sge->length = buf->buf_len;
1606                         }
1607                         sge->lkey = rxq->mr->lkey;
1608                         /* Redundant check for tailroom. */
1609                         assert(sge->length == rte_pktmbuf_tailroom(buf));
1610                 }
1611         }
1612         /* The last WR pointer must be NULL. */
1613         (*elts)[(i - 1)].wr.next = NULL;
1614         DEBUG("%p: allocated and configured %u WRs (%zu segments)",
1615               (void *)rxq, elts_n, (elts_n * elemof((*elts)[0].sges)));
1616         rxq->elts_n = elts_n;
1617         rxq->elts.sp = elts;
1618         assert(ret == 0);
1619         return 0;
1620 error:
1621         if (elts != NULL) {
1622                 assert(pool == NULL);
1623                 for (i = 0; (i != elemof(*elts)); ++i) {
1624                         unsigned int j;
1625                         struct rxq_elt_sp *elt = &(*elts)[i];
1626
1627                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
1628                                 struct rte_mbuf *buf = elt->bufs[j];
1629
1630                                 if (buf != NULL)
1631                                         rte_pktmbuf_free_seg(buf);
1632                         }
1633                 }
1634                 rte_free(elts);
1635         }
1636         DEBUG("%p: failed, freed everything", (void *)rxq);
1637         assert(ret > 0);
1638         return ret;
1639 }
1640
1641 /**
1642  * Free RX queue elements with scattered packets support.
1643  *
1644  * @param rxq
1645  *   Pointer to RX queue structure.
1646  */
1647 static void
1648 rxq_free_elts_sp(struct rxq *rxq)
1649 {
1650         unsigned int i;
1651         unsigned int elts_n = rxq->elts_n;
1652         struct rxq_elt_sp (*elts)[elts_n] = rxq->elts.sp;
1653
1654         DEBUG("%p: freeing WRs", (void *)rxq);
1655         rxq->elts_n = 0;
1656         rxq->elts.sp = NULL;
1657         if (elts == NULL)
1658                 return;
1659         for (i = 0; (i != elemof(*elts)); ++i) {
1660                 unsigned int j;
1661                 struct rxq_elt_sp *elt = &(*elts)[i];
1662
1663                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
1664                         struct rte_mbuf *buf = elt->bufs[j];
1665
1666                         if (buf != NULL)
1667                                 rte_pktmbuf_free_seg(buf);
1668                 }
1669         }
1670         rte_free(elts);
1671 }
1672
1673 /**
1674  * Allocate RX queue elements.
1675  *
1676  * @param rxq
1677  *   Pointer to RX queue structure.
1678  * @param elts_n
1679  *   Number of elements to allocate.
1680  * @param[in] pool
1681  *   If not NULL, fetch buffers from this array instead of allocating them
1682  *   with rte_pktmbuf_alloc().
1683  *
1684  * @return
1685  *   0 on success, errno value on failure.
1686  */
1687 static int
1688 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n, struct rte_mbuf **pool)
1689 {
1690         unsigned int i;
1691         struct rxq_elt (*elts)[elts_n] =
1692                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1693                                   rxq->socket);
1694         int ret = 0;
1695
1696         if (elts == NULL) {
1697                 ERROR("%p: can't allocate packets array", (void *)rxq);
1698                 ret = ENOMEM;
1699                 goto error;
1700         }
1701         /* For each WR (packet). */
1702         for (i = 0; (i != elts_n); ++i) {
1703                 struct rxq_elt *elt = &(*elts)[i];
1704                 struct ibv_recv_wr *wr = &elt->wr;
1705                 struct ibv_sge *sge = &(*elts)[i].sge;
1706                 struct rte_mbuf *buf;
1707
1708                 if (pool != NULL) {
1709                         buf = *(pool++);
1710                         assert(buf != NULL);
1711                         rte_pktmbuf_reset(buf);
1712                 } else
1713                         buf = rte_pktmbuf_alloc(rxq->mp);
1714                 if (buf == NULL) {
1715                         assert(pool == NULL);
1716                         ERROR("%p: empty mbuf pool", (void *)rxq);
1717                         ret = ENOMEM;
1718                         goto error;
1719                 }
1720                 /* Configure WR. Work request ID contains its own index in
1721                  * the elts array and the offset between SGE buffer header and
1722                  * its data. */
1723                 WR_ID(wr->wr_id).id = i;
1724                 WR_ID(wr->wr_id).offset =
1725                         (((uintptr_t)buf->buf_addr + RTE_PKTMBUF_HEADROOM) -
1726                          (uintptr_t)buf);
1727                 wr->next = &(*elts)[(i + 1)].wr;
1728                 wr->sg_list = sge;
1729                 wr->num_sge = 1;
1730                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
1731                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1732                 /* Buffer is supposed to be empty. */
1733                 assert(rte_pktmbuf_data_len(buf) == 0);
1734                 assert(rte_pktmbuf_pkt_len(buf) == 0);
1735                 /* sge->addr must be able to store a pointer. */
1736                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1737                 /* SGE keeps its headroom. */
1738                 sge->addr = (uintptr_t)
1739                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
1740                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
1741                 sge->lkey = rxq->mr->lkey;
1742                 /* Redundant check for tailroom. */
1743                 assert(sge->length == rte_pktmbuf_tailroom(buf));
1744                 /* Make sure elts index and SGE mbuf pointer can be deduced
1745                  * from WR ID. */
1746                 if ((WR_ID(wr->wr_id).id != i) ||
1747                     ((void *)((uintptr_t)sge->addr -
1748                         WR_ID(wr->wr_id).offset) != buf)) {
1749                         ERROR("%p: cannot store index and offset in WR ID",
1750                               (void *)rxq);
1751                         sge->addr = 0;
1752                         rte_pktmbuf_free(buf);
1753                         ret = EOVERFLOW;
1754                         goto error;
1755                 }
1756         }
1757         /* The last WR pointer must be NULL. */
1758         (*elts)[(i - 1)].wr.next = NULL;
1759         DEBUG("%p: allocated and configured %u single-segment WRs",
1760               (void *)rxq, elts_n);
1761         rxq->elts_n = elts_n;
1762         rxq->elts.no_sp = elts;
1763         assert(ret == 0);
1764         return 0;
1765 error:
1766         if (elts != NULL) {
1767                 assert(pool == NULL);
1768                 for (i = 0; (i != elemof(*elts)); ++i) {
1769                         struct rxq_elt *elt = &(*elts)[i];
1770                         struct rte_mbuf *buf;
1771
1772                         if (elt->sge.addr == 0)
1773                                 continue;
1774                         assert(WR_ID(elt->wr.wr_id).id == i);
1775                         buf = (void *)((uintptr_t)elt->sge.addr -
1776                                 WR_ID(elt->wr.wr_id).offset);
1777                         rte_pktmbuf_free_seg(buf);
1778                 }
1779                 rte_free(elts);
1780         }
1781         DEBUG("%p: failed, freed everything", (void *)rxq);
1782         assert(ret > 0);
1783         return ret;
1784 }
1785
1786 /**
1787  * Free RX queue elements.
1788  *
1789  * @param rxq
1790  *   Pointer to RX queue structure.
1791  */
1792 static void
1793 rxq_free_elts(struct rxq *rxq)
1794 {
1795         unsigned int i;
1796         unsigned int elts_n = rxq->elts_n;
1797         struct rxq_elt (*elts)[elts_n] = rxq->elts.no_sp;
1798
1799         DEBUG("%p: freeing WRs", (void *)rxq);
1800         rxq->elts_n = 0;
1801         rxq->elts.no_sp = NULL;
1802         if (elts == NULL)
1803                 return;
1804         for (i = 0; (i != elemof(*elts)); ++i) {
1805                 struct rxq_elt *elt = &(*elts)[i];
1806                 struct rte_mbuf *buf;
1807
1808                 if (elt->sge.addr == 0)
1809                         continue;
1810                 assert(WR_ID(elt->wr.wr_id).id == i);
1811                 buf = (void *)((uintptr_t)elt->sge.addr -
1812                         WR_ID(elt->wr.wr_id).offset);
1813                 rte_pktmbuf_free_seg(buf);
1814         }
1815         rte_free(elts);
1816 }
1817
1818 /**
1819  * Unregister a MAC address from a RX queue.
1820  *
1821  * @param rxq
1822  *   Pointer to RX queue structure.
1823  * @param mac_index
1824  *   MAC address index.
1825  */
1826 static void
1827 rxq_mac_addr_del(struct rxq *rxq, unsigned int mac_index)
1828 {
1829 #ifndef NDEBUG
1830         struct priv *priv = rxq->priv;
1831         const uint8_t (*mac)[ETHER_ADDR_LEN] =
1832                 (const uint8_t (*)[ETHER_ADDR_LEN])
1833                 priv->mac[mac_index].addr_bytes;
1834 #endif
1835
1836         assert(mac_index < elemof(priv->mac));
1837         if (!BITFIELD_ISSET(rxq->mac_configured, mac_index)) {
1838                 assert(rxq->mac_flow[mac_index] == NULL);
1839                 return;
1840         }
1841         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x"
1842               " index %u",
1843               (void *)rxq,
1844               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
1845               mac_index);
1846         assert(rxq->mac_flow[mac_index] != NULL);
1847         claim_zero(ibv_exp_destroy_flow(rxq->mac_flow[mac_index]));
1848         rxq->mac_flow[mac_index] = NULL;
1849         BITFIELD_RESET(rxq->mac_configured, mac_index);
1850 }
1851
1852 /**
1853  * Unregister all MAC addresses from a RX queue.
1854  *
1855  * @param rxq
1856  *   Pointer to RX queue structure.
1857  */
1858 static void
1859 rxq_mac_addrs_del(struct rxq *rxq)
1860 {
1861         struct priv *priv = rxq->priv;
1862         unsigned int i;
1863
1864         for (i = 0; (i != elemof(priv->mac)); ++i)
1865                 rxq_mac_addr_del(rxq, i);
1866 }
1867
1868 static int rxq_promiscuous_enable(struct rxq *);
1869 static void rxq_promiscuous_disable(struct rxq *);
1870
1871 /**
1872  * Register a MAC address in a RX queue.
1873  *
1874  * @param rxq
1875  *   Pointer to RX queue structure.
1876  * @param mac_index
1877  *   MAC address index to register.
1878  *
1879  * @return
1880  *   0 on success, errno value on failure.
1881  */
1882 static int
1883 rxq_mac_addr_add(struct rxq *rxq, unsigned int mac_index)
1884 {
1885         struct priv *priv = rxq->priv;
1886         const uint8_t (*mac)[ETHER_ADDR_LEN] =
1887                 (const uint8_t (*)[ETHER_ADDR_LEN])
1888                 priv->mac[mac_index].addr_bytes;
1889         unsigned int vlans = 0;
1890         unsigned int specs = 0;
1891         unsigned int i, j;
1892         struct ibv_exp_flow *flow;
1893
1894         assert(mac_index < elemof(priv->mac));
1895         if (BITFIELD_ISSET(rxq->mac_configured, mac_index))
1896                 rxq_mac_addr_del(rxq, mac_index);
1897         /* Number of configured VLANs. */
1898         for (i = 0; (i != elemof(priv->vlan_filter)); ++i)
1899                 if (priv->vlan_filter[i].enabled)
1900                         ++vlans;
1901         specs = (vlans ? vlans : 1);
1902
1903         /* Allocate flow specification on the stack. */
1904         struct ibv_exp_flow_attr data
1905                 [1 +
1906                  (sizeof(struct ibv_exp_flow_spec_eth[specs]) /
1907                   sizeof(struct ibv_exp_flow_attr)) +
1908                  !!(sizeof(struct ibv_exp_flow_spec_eth[specs]) %
1909                     sizeof(struct ibv_exp_flow_attr))];
1910         struct ibv_exp_flow_attr *attr = (void *)&data[0];
1911         struct ibv_exp_flow_spec_eth *spec = (void *)&data[1];
1912
1913         /*
1914          * No padding must be inserted by the compiler between attr and spec.
1915          * This layout is expected by libibverbs.
1916          */
1917         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
1918         *attr = (struct ibv_exp_flow_attr){
1919                 .type = IBV_EXP_FLOW_ATTR_NORMAL,
1920                 .num_of_specs = specs,
1921                 .port = priv->port,
1922                 .flags = 0
1923         };
1924         *spec = (struct ibv_exp_flow_spec_eth){
1925                 .type = IBV_EXP_FLOW_SPEC_ETH,
1926                 .size = sizeof(*spec),
1927                 .val = {
1928                         .dst_mac = {
1929                                 (*mac)[0], (*mac)[1], (*mac)[2],
1930                                 (*mac)[3], (*mac)[4], (*mac)[5]
1931                         }
1932                 },
1933                 .mask = {
1934                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
1935                         .vlan_tag = (vlans ? htons(0xfff) : 0)
1936                 }
1937         };
1938         /* Fill VLAN specifications. */
1939         for (i = 0, j = 0; (i != elemof(priv->vlan_filter)); ++i) {
1940                 if (!priv->vlan_filter[i].enabled)
1941                         continue;
1942                 assert(j != vlans);
1943                 if (j)
1944                         spec[j] = spec[0];
1945                 spec[j].val.vlan_tag = htons(priv->vlan_filter[i].id);
1946                 ++j;
1947         }
1948         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x index %u"
1949               " (%u VLAN(s) configured)",
1950               (void *)rxq,
1951               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
1952               mac_index,
1953               vlans);
1954         /* Create related flow. */
1955         errno = 0;
1956         flow = ibv_exp_create_flow(rxq->qp, attr);
1957         if (flow == NULL) {
1958                 int err = errno;
1959
1960                 /* Flow creation failure is not fatal when in DMFS A0 mode.
1961                  * Ignore error if promiscuity is already enabled or can be
1962                  * enabled. */
1963                 if (priv->promisc_ok)
1964                         return 0;
1965                 if ((rxq->promisc_flow != NULL) ||
1966                     (rxq_promiscuous_enable(rxq) == 0)) {
1967                         if (rxq->promisc_flow != NULL)
1968                                 rxq_promiscuous_disable(rxq);
1969                         WARN("cannot configure normal flow but promiscuous"
1970                              " mode is fine, assuming promiscuous optimization"
1971                              " is enabled"
1972                              " (options mlx4_core log_num_mgm_entry_size=-7)");
1973                         priv->promisc_ok = 1;
1974                         return 0;
1975                 }
1976                 errno = err;
1977                 /* It's not clear whether errno is always set in this case. */
1978                 ERROR("%p: flow configuration failed, errno=%d: %s",
1979                       (void *)rxq, errno,
1980                       (errno ? strerror(errno) : "Unknown error"));
1981                 if (errno)
1982                         return errno;
1983                 return EINVAL;
1984         }
1985         assert(rxq->mac_flow[mac_index] == NULL);
1986         rxq->mac_flow[mac_index] = flow;
1987         BITFIELD_SET(rxq->mac_configured, mac_index);
1988         return 0;
1989 }
1990
1991 /**
1992  * Register all MAC addresses in a RX queue.
1993  *
1994  * @param rxq
1995  *   Pointer to RX queue structure.
1996  *
1997  * @return
1998  *   0 on success, errno value on failure.
1999  */
2000 static int
2001 rxq_mac_addrs_add(struct rxq *rxq)
2002 {
2003         struct priv *priv = rxq->priv;
2004         unsigned int i;
2005         int ret;
2006
2007         for (i = 0; (i != elemof(priv->mac)); ++i) {
2008                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2009                         continue;
2010                 ret = rxq_mac_addr_add(rxq, i);
2011                 if (!ret)
2012                         continue;
2013                 /* Failure, rollback. */
2014                 while (i != 0)
2015                         rxq_mac_addr_del(rxq, --i);
2016                 assert(ret > 0);
2017                 return ret;
2018         }
2019         return 0;
2020 }
2021
2022 /**
2023  * Unregister a MAC address.
2024  *
2025  * In RSS mode, the MAC address is unregistered from the parent queue,
2026  * otherwise it is unregistered from each queue directly.
2027  *
2028  * @param priv
2029  *   Pointer to private structure.
2030  * @param mac_index
2031  *   MAC address index.
2032  */
2033 static void
2034 priv_mac_addr_del(struct priv *priv, unsigned int mac_index)
2035 {
2036         unsigned int i;
2037
2038         assert(mac_index < elemof(priv->mac));
2039         if (!BITFIELD_ISSET(priv->mac_configured, mac_index))
2040                 return;
2041         if (priv->rss) {
2042                 rxq_mac_addr_del(&priv->rxq_parent, mac_index);
2043                 goto end;
2044         }
2045         for (i = 0; (i != priv->dev->data->nb_rx_queues); ++i)
2046                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2047 end:
2048         BITFIELD_RESET(priv->mac_configured, mac_index);
2049 }
2050
2051 /**
2052  * Register a MAC address.
2053  *
2054  * In RSS mode, the MAC address is registered in the parent queue,
2055  * otherwise it is registered in each queue directly.
2056  *
2057  * @param priv
2058  *   Pointer to private structure.
2059  * @param mac_index
2060  *   MAC address index to use.
2061  * @param mac
2062  *   MAC address to register.
2063  *
2064  * @return
2065  *   0 on success, errno value on failure.
2066  */
2067 static int
2068 priv_mac_addr_add(struct priv *priv, unsigned int mac_index,
2069                   const uint8_t (*mac)[ETHER_ADDR_LEN])
2070 {
2071         unsigned int i;
2072         int ret;
2073
2074         assert(mac_index < elemof(priv->mac));
2075         /* First, make sure this address isn't already configured. */
2076         for (i = 0; (i != elemof(priv->mac)); ++i) {
2077                 /* Skip this index, it's going to be reconfigured. */
2078                 if (i == mac_index)
2079                         continue;
2080                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2081                         continue;
2082                 if (memcmp(priv->mac[i].addr_bytes, *mac, sizeof(*mac)))
2083                         continue;
2084                 /* Address already configured elsewhere, return with error. */
2085                 return EADDRINUSE;
2086         }
2087         if (BITFIELD_ISSET(priv->mac_configured, mac_index))
2088                 priv_mac_addr_del(priv, mac_index);
2089         priv->mac[mac_index] = (struct ether_addr){
2090                 {
2091                         (*mac)[0], (*mac)[1], (*mac)[2],
2092                         (*mac)[3], (*mac)[4], (*mac)[5]
2093                 }
2094         };
2095         /* If device isn't started, this is all we need to do. */
2096         if (!priv->started) {
2097 #ifndef NDEBUG
2098                 /* Verify that all queues have this index disabled. */
2099                 for (i = 0; (i != priv->rxqs_n); ++i) {
2100                         if ((*priv->rxqs)[i] == NULL)
2101                                 continue;
2102                         assert(!BITFIELD_ISSET
2103                                ((*priv->rxqs)[i]->mac_configured, mac_index));
2104                 }
2105 #endif
2106                 goto end;
2107         }
2108         if (priv->rss) {
2109                 ret = rxq_mac_addr_add(&priv->rxq_parent, mac_index);
2110                 if (ret)
2111                         return ret;
2112                 goto end;
2113         }
2114         for (i = 0; (i != priv->rxqs_n); ++i) {
2115                 if ((*priv->rxqs)[i] == NULL)
2116                         continue;
2117                 ret = rxq_mac_addr_add((*priv->rxqs)[i], mac_index);
2118                 if (!ret)
2119                         continue;
2120                 /* Failure, rollback. */
2121                 while (i != 0)
2122                         if ((*priv->rxqs)[(--i)] != NULL)
2123                                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2124                 return ret;
2125         }
2126 end:
2127         BITFIELD_SET(priv->mac_configured, mac_index);
2128         return 0;
2129 }
2130
2131 /**
2132  * Enable allmulti mode in a RX queue.
2133  *
2134  * @param rxq
2135  *   Pointer to RX queue structure.
2136  *
2137  * @return
2138  *   0 on success, errno value on failure.
2139  */
2140 static int
2141 rxq_allmulticast_enable(struct rxq *rxq)
2142 {
2143         struct ibv_exp_flow *flow;
2144         struct ibv_exp_flow_attr attr = {
2145                 .type = IBV_EXP_FLOW_ATTR_MC_DEFAULT,
2146                 .num_of_specs = 0,
2147                 .port = rxq->priv->port,
2148                 .flags = 0
2149         };
2150
2151         DEBUG("%p: enabling allmulticast mode", (void *)rxq);
2152         if (rxq->allmulti_flow != NULL)
2153                 return EBUSY;
2154         errno = 0;
2155         flow = ibv_exp_create_flow(rxq->qp, &attr);
2156         if (flow == NULL) {
2157                 /* It's not clear whether errno is always set in this case. */
2158                 ERROR("%p: flow configuration failed, errno=%d: %s",
2159                       (void *)rxq, errno,
2160                       (errno ? strerror(errno) : "Unknown error"));
2161                 if (errno)
2162                         return errno;
2163                 return EINVAL;
2164         }
2165         rxq->allmulti_flow = flow;
2166         DEBUG("%p: allmulticast mode enabled", (void *)rxq);
2167         return 0;
2168 }
2169
2170 /**
2171  * Disable allmulti mode in a RX queue.
2172  *
2173  * @param rxq
2174  *   Pointer to RX queue structure.
2175  */
2176 static void
2177 rxq_allmulticast_disable(struct rxq *rxq)
2178 {
2179         DEBUG("%p: disabling allmulticast mode", (void *)rxq);
2180         if (rxq->allmulti_flow == NULL)
2181                 return;
2182         claim_zero(ibv_exp_destroy_flow(rxq->allmulti_flow));
2183         rxq->allmulti_flow = NULL;
2184         DEBUG("%p: allmulticast mode disabled", (void *)rxq);
2185 }
2186
2187 /**
2188  * Enable promiscuous mode in a RX queue.
2189  *
2190  * @param rxq
2191  *   Pointer to RX queue structure.
2192  *
2193  * @return
2194  *   0 on success, errno value on failure.
2195  */
2196 static int
2197 rxq_promiscuous_enable(struct rxq *rxq)
2198 {
2199         struct ibv_exp_flow *flow;
2200         struct ibv_exp_flow_attr attr = {
2201                 .type = IBV_EXP_FLOW_ATTR_ALL_DEFAULT,
2202                 .num_of_specs = 0,
2203                 .port = rxq->priv->port,
2204                 .flags = 0
2205         };
2206
2207         if (rxq->priv->vf)
2208                 return 0;
2209         DEBUG("%p: enabling promiscuous mode", (void *)rxq);
2210         if (rxq->promisc_flow != NULL)
2211                 return EBUSY;
2212         errno = 0;
2213         flow = ibv_exp_create_flow(rxq->qp, &attr);
2214         if (flow == NULL) {
2215                 /* It's not clear whether errno is always set in this case. */
2216                 ERROR("%p: flow configuration failed, errno=%d: %s",
2217                       (void *)rxq, errno,
2218                       (errno ? strerror(errno) : "Unknown error"));
2219                 if (errno)
2220                         return errno;
2221                 return EINVAL;
2222         }
2223         rxq->promisc_flow = flow;
2224         DEBUG("%p: promiscuous mode enabled", (void *)rxq);
2225         return 0;
2226 }
2227
2228 /**
2229  * Disable promiscuous mode in a RX queue.
2230  *
2231  * @param rxq
2232  *   Pointer to RX queue structure.
2233  */
2234 static void
2235 rxq_promiscuous_disable(struct rxq *rxq)
2236 {
2237         if (rxq->priv->vf)
2238                 return;
2239         DEBUG("%p: disabling promiscuous mode", (void *)rxq);
2240         if (rxq->promisc_flow == NULL)
2241                 return;
2242         claim_zero(ibv_exp_destroy_flow(rxq->promisc_flow));
2243         rxq->promisc_flow = NULL;
2244         DEBUG("%p: promiscuous mode disabled", (void *)rxq);
2245 }
2246
2247 /**
2248  * Clean up a RX queue.
2249  *
2250  * Destroy objects, free allocated memory and reset the structure for reuse.
2251  *
2252  * @param rxq
2253  *   Pointer to RX queue structure.
2254  */
2255 static void
2256 rxq_cleanup(struct rxq *rxq)
2257 {
2258         DEBUG("cleaning up %p", (void *)rxq);
2259         if (rxq->sp)
2260                 rxq_free_elts_sp(rxq);
2261         else
2262                 rxq_free_elts(rxq);
2263         if (rxq->qp != NULL) {
2264                 rxq_promiscuous_disable(rxq);
2265                 rxq_allmulticast_disable(rxq);
2266                 rxq_mac_addrs_del(rxq);
2267                 claim_zero(ibv_destroy_qp(rxq->qp));
2268         }
2269         if (rxq->cq != NULL)
2270                 claim_zero(ibv_destroy_cq(rxq->cq));
2271         if (rxq->mr != NULL)
2272                 claim_zero(ibv_dereg_mr(rxq->mr));
2273         memset(rxq, 0, sizeof(*rxq));
2274 }
2275
2276 static uint16_t
2277 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n);
2278
2279 /**
2280  * DPDK callback for RX with scattered packets support.
2281  *
2282  * @param dpdk_rxq
2283  *   Generic pointer to RX queue structure.
2284  * @param[out] pkts
2285  *   Array to store received packets.
2286  * @param pkts_n
2287  *   Maximum number of packets in array.
2288  *
2289  * @return
2290  *   Number of packets successfully received (<= pkts_n).
2291  */
2292 static uint16_t
2293 mlx4_rx_burst_sp(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2294 {
2295         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2296         struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2297         struct ibv_wc wcs[pkts_n];
2298         struct ibv_recv_wr head;
2299         struct ibv_recv_wr **next = &head.next;
2300         struct ibv_recv_wr *bad_wr;
2301         int ret = 0;
2302         int wcs_n;
2303         int i;
2304
2305         if (unlikely(!rxq->sp))
2306                 return mlx4_rx_burst(dpdk_rxq, pkts, pkts_n);
2307         if (unlikely(elts == NULL)) /* See RTE_DEV_CMD_SET_MTU. */
2308                 return 0;
2309         wcs_n = ibv_poll_cq(rxq->cq, pkts_n, wcs);
2310         if (unlikely(wcs_n == 0))
2311                 return 0;
2312         if (unlikely(wcs_n < 0)) {
2313                 DEBUG("rxq=%p, ibv_poll_cq() failed (wc_n=%d)",
2314                       (void *)rxq, wcs_n);
2315                 return 0;
2316         }
2317         assert(wcs_n <= (int)pkts_n);
2318         /* For each work completion. */
2319         for (i = 0; (i != wcs_n); ++i) {
2320                 struct ibv_wc *wc = &wcs[i];
2321                 uint64_t wr_id = wc->wr_id;
2322                 uint32_t len = wc->byte_len;
2323                 struct rxq_elt_sp *elt = &(*elts)[wr_id];
2324                 struct ibv_recv_wr *wr = &elt->wr;
2325                 struct rte_mbuf *pkt_buf = NULL; /* Buffer returned in pkts. */
2326                 struct rte_mbuf **pkt_buf_next = &pkt_buf;
2327                 unsigned int seg_headroom = RTE_PKTMBUF_HEADROOM;
2328                 unsigned int j = 0;
2329
2330                 /* Sanity checks. */
2331                 assert(wr_id < rxq->elts_n);
2332                 assert(wr_id == wr->wr_id);
2333                 assert(wr->sg_list == elt->sges);
2334                 assert(wr->num_sge == elemof(elt->sges));
2335                 /* Link completed WRs together for repost. */
2336                 *next = wr;
2337                 next = &wr->next;
2338                 if (unlikely(wc->status != IBV_WC_SUCCESS)) {
2339                         /* Whatever, just repost the offending WR. */
2340                         DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work completion"
2341                               " status (%d): %s",
2342                               (void *)rxq, wc->wr_id, wc->status,
2343                               ibv_wc_status_str(wc->status));
2344 #ifdef MLX4_PMD_SOFT_COUNTERS
2345                         /* Increase dropped packets counter. */
2346                         ++rxq->stats.idropped;
2347 #endif
2348                         goto repost;
2349                 }
2350                 /*
2351                  * Replace spent segments with new ones, concatenate and
2352                  * return them as pkt_buf.
2353                  */
2354                 while (1) {
2355                         struct ibv_sge *sge = &elt->sges[j];
2356                         struct rte_mbuf *seg = elt->bufs[j];
2357                         struct rte_mbuf *rep;
2358                         unsigned int seg_tailroom;
2359
2360                         /*
2361                          * Fetch initial bytes of packet descriptor into a
2362                          * cacheline while allocating rep.
2363                          */
2364                         rte_prefetch0(seg);
2365                         rep = __rte_mbuf_raw_alloc(rxq->mp);
2366                         if (unlikely(rep == NULL)) {
2367                                 /*
2368                                  * Unable to allocate a replacement mbuf,
2369                                  * repost WR.
2370                                  */
2371                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ":"
2372                                       " can't allocate a new mbuf",
2373                                       (void *)rxq, wr_id);
2374                                 if (pkt_buf != NULL)
2375                                         rte_pktmbuf_free(pkt_buf);
2376                                 /* Increase out of memory counters. */
2377                                 ++rxq->stats.rx_nombuf;
2378                                 ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2379                                 goto repost;
2380                         }
2381 #ifndef NDEBUG
2382                         /* Poison user-modifiable fields in rep. */
2383                         NEXT(rep) = (void *)((uintptr_t)-1);
2384                         SET_DATA_OFF(rep, 0xdead);
2385                         DATA_LEN(rep) = 0xd00d;
2386                         PKT_LEN(rep) = 0xdeadd00d;
2387                         NB_SEGS(rep) = 0x2a;
2388                         PORT(rep) = 0x2a;
2389                         rep->ol_flags = -1;
2390 #endif
2391                         assert(rep->buf_len == seg->buf_len);
2392                         assert(rep->buf_len == rxq->mb_len);
2393                         /* Reconfigure sge to use rep instead of seg. */
2394                         assert(sge->lkey == rxq->mr->lkey);
2395                         sge->addr = ((uintptr_t)rep->buf_addr + seg_headroom);
2396                         elt->bufs[j] = rep;
2397                         ++j;
2398                         /* Update pkt_buf if it's the first segment, or link
2399                          * seg to the previous one and update pkt_buf_next. */
2400                         *pkt_buf_next = seg;
2401                         pkt_buf_next = &NEXT(seg);
2402                         /* Update seg information. */
2403                         seg_tailroom = (seg->buf_len - seg_headroom);
2404                         assert(sge->length == seg_tailroom);
2405                         SET_DATA_OFF(seg, seg_headroom);
2406                         if (likely(len <= seg_tailroom)) {
2407                                 /* Last segment. */
2408                                 DATA_LEN(seg) = len;
2409                                 PKT_LEN(seg) = len;
2410                                 /* Sanity check. */
2411                                 assert(rte_pktmbuf_headroom(seg) ==
2412                                        seg_headroom);
2413                                 assert(rte_pktmbuf_tailroom(seg) ==
2414                                        (seg_tailroom - len));
2415                                 break;
2416                         }
2417                         DATA_LEN(seg) = seg_tailroom;
2418                         PKT_LEN(seg) = seg_tailroom;
2419                         /* Sanity check. */
2420                         assert(rte_pktmbuf_headroom(seg) == seg_headroom);
2421                         assert(rte_pktmbuf_tailroom(seg) == 0);
2422                         /* Fix len and clear headroom for next segments. */
2423                         len -= seg_tailroom;
2424                         seg_headroom = 0;
2425                 }
2426                 /* Update head and tail segments. */
2427                 *pkt_buf_next = NULL;
2428                 assert(pkt_buf != NULL);
2429                 assert(j != 0);
2430                 NB_SEGS(pkt_buf) = j;
2431                 PORT(pkt_buf) = rxq->port_id;
2432                 PKT_LEN(pkt_buf) = wc->byte_len;
2433                 pkt_buf->ol_flags = 0;
2434
2435                 /* Return packet. */
2436                 *(pkts++) = pkt_buf;
2437                 ++ret;
2438 #ifdef MLX4_PMD_SOFT_COUNTERS
2439                 /* Increase bytes counter. */
2440                 rxq->stats.ibytes += wc->byte_len;
2441 #endif
2442 repost:
2443                 continue;
2444         }
2445         *next = NULL;
2446         /* Repost WRs. */
2447 #ifdef DEBUG_RECV
2448         DEBUG("%p: reposting %d WRs starting from %" PRIu64 " (%p)",
2449               (void *)rxq, wcs_n, wcs[0].wr_id, (void *)head.next);
2450 #endif
2451         i = ibv_post_recv(rxq->qp, head.next, &bad_wr);
2452         if (unlikely(i)) {
2453                 /* Inability to repost WRs is fatal. */
2454                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
2455                       (void *)rxq->priv,
2456                       (void *)bad_wr,
2457                       strerror(i));
2458                 abort();
2459         }
2460 #ifdef MLX4_PMD_SOFT_COUNTERS
2461         /* Increase packets counter. */
2462         rxq->stats.ipackets += ret;
2463 #endif
2464         return ret;
2465 }
2466
2467 /**
2468  * DPDK callback for RX.
2469  *
2470  * The following function is the same as mlx4_rx_burst_sp(), except it doesn't
2471  * manage scattered packets. Improves performance when MRU is lower than the
2472  * size of the first segment.
2473  *
2474  * @param dpdk_rxq
2475  *   Generic pointer to RX queue structure.
2476  * @param[out] pkts
2477  *   Array to store received packets.
2478  * @param pkts_n
2479  *   Maximum number of packets in array.
2480  *
2481  * @return
2482  *   Number of packets successfully received (<= pkts_n).
2483  */
2484 static uint16_t
2485 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2486 {
2487         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2488         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
2489         struct ibv_wc wcs[pkts_n];
2490         struct ibv_recv_wr head;
2491         struct ibv_recv_wr **next = &head.next;
2492         struct ibv_recv_wr *bad_wr;
2493         int ret = 0;
2494         int wcs_n;
2495         int i;
2496
2497         if (unlikely(rxq->sp))
2498                 return mlx4_rx_burst_sp(dpdk_rxq, pkts, pkts_n);
2499         wcs_n = ibv_poll_cq(rxq->cq, pkts_n, wcs);
2500         if (unlikely(wcs_n == 0))
2501                 return 0;
2502         if (unlikely(wcs_n < 0)) {
2503                 DEBUG("rxq=%p, ibv_poll_cq() failed (wc_n=%d)",
2504                       (void *)rxq, wcs_n);
2505                 return 0;
2506         }
2507         assert(wcs_n <= (int)pkts_n);
2508         /* For each work completion. */
2509         for (i = 0; (i != wcs_n); ++i) {
2510                 struct ibv_wc *wc = &wcs[i];
2511                 uint64_t wr_id = wc->wr_id;
2512                 uint32_t len = wc->byte_len;
2513                 struct rxq_elt *elt = &(*elts)[WR_ID(wr_id).id];
2514                 struct ibv_recv_wr *wr = &elt->wr;
2515                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
2516                         WR_ID(wr_id).offset);
2517                 struct rte_mbuf *rep;
2518
2519                 /* Sanity checks. */
2520                 assert(WR_ID(wr_id).id < rxq->elts_n);
2521                 assert(wr_id == wr->wr_id);
2522                 assert(wr->sg_list == &elt->sge);
2523                 assert(wr->num_sge == 1);
2524                 /* Link completed WRs together for repost. */
2525                 *next = wr;
2526                 next = &wr->next;
2527                 if (unlikely(wc->status != IBV_WC_SUCCESS)) {
2528                         /* Whatever, just repost the offending WR. */
2529                         DEBUG("rxq=%p, wr_id=%" PRIu32 ": bad work completion"
2530                               " status (%d): %s",
2531                               (void *)rxq, WR_ID(wr_id).id, wc->status,
2532                               ibv_wc_status_str(wc->status));
2533 #ifdef MLX4_PMD_SOFT_COUNTERS
2534                         /* Increase dropped packets counter. */
2535                         ++rxq->stats.idropped;
2536 #endif
2537                         goto repost;
2538                 }
2539                 /*
2540                  * Fetch initial bytes of packet descriptor into a
2541                  * cacheline while allocating rep.
2542                  */
2543                 rte_prefetch0(seg);
2544                 rep = __rte_mbuf_raw_alloc(rxq->mp);
2545                 if (unlikely(rep == NULL)) {
2546                         /*
2547                          * Unable to allocate a replacement mbuf,
2548                          * repost WR.
2549                          */
2550                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
2551                               " can't allocate a new mbuf",
2552                               (void *)rxq, WR_ID(wr_id).id);
2553                         /* Increase out of memory counters. */
2554                         ++rxq->stats.rx_nombuf;
2555                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2556                         goto repost;
2557                 }
2558
2559                 /* Reconfigure sge to use rep instead of seg. */
2560                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
2561                 assert(elt->sge.lkey == rxq->mr->lkey);
2562                 WR_ID(wr->wr_id).offset =
2563                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
2564                          (uintptr_t)rep);
2565                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
2566
2567                 /* Update seg information. */
2568                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
2569                 NB_SEGS(seg) = 1;
2570                 PORT(seg) = rxq->port_id;
2571                 NEXT(seg) = NULL;
2572                 PKT_LEN(seg) = len;
2573                 DATA_LEN(seg) = len;
2574                 seg->ol_flags = 0;
2575
2576                 /* Return packet. */
2577                 *(pkts++) = seg;
2578                 ++ret;
2579 #ifdef MLX4_PMD_SOFT_COUNTERS
2580                 /* Increase bytes counter. */
2581                 rxq->stats.ibytes += wc->byte_len;
2582 #endif
2583 repost:
2584                 continue;
2585         }
2586         *next = NULL;
2587         /* Repost WRs. */
2588 #ifdef DEBUG_RECV
2589         DEBUG("%p: reposting %d WRs starting from %" PRIu32 " (%p)",
2590               (void *)rxq, wcs_n, WR_ID(wcs[0].wr_id).id, (void *)head.next);
2591 #endif
2592         i = ibv_post_recv(rxq->qp, head.next, &bad_wr);
2593         if (unlikely(i)) {
2594                 /* Inability to repost WRs is fatal. */
2595                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
2596                       (void *)rxq->priv,
2597                       (void *)bad_wr,
2598                       strerror(i));
2599                 abort();
2600         }
2601 #ifdef MLX4_PMD_SOFT_COUNTERS
2602         /* Increase packets counter. */
2603         rxq->stats.ipackets += ret;
2604 #endif
2605         return ret;
2606 }
2607
2608 #ifdef INLINE_RECV
2609
2610 /**
2611  * Allocate a Queue Pair in case inline receive is supported.
2612  *
2613  * @param priv
2614  *   Pointer to private structure.
2615  * @param cq
2616  *   Completion queue to associate with QP.
2617  * @param desc
2618  *   Number of descriptors in QP (hint only).
2619  *
2620  * @return
2621  *   QP pointer or NULL in case of error.
2622  */
2623 static struct ibv_qp *
2624 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc)
2625 {
2626         struct ibv_exp_qp_init_attr attr = {
2627                 /* CQ to be associated with the send queue. */
2628                 .send_cq = cq,
2629                 /* CQ to be associated with the receive queue. */
2630                 .recv_cq = cq,
2631                 .max_inl_recv = priv->inl_recv_size,
2632                 .cap = {
2633                         /* Max number of outstanding WRs. */
2634                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2635                                         priv->device_attr.max_qp_wr :
2636                                         desc),
2637                         /* Max number of scatter/gather elements in a WR. */
2638                         .max_recv_sge = ((priv->device_attr.max_sge <
2639                                           MLX4_PMD_SGE_WR_N) ?
2640                                          priv->device_attr.max_sge :
2641                                          MLX4_PMD_SGE_WR_N),
2642                 },
2643                 .qp_type = IBV_QPT_RAW_PACKET,
2644                 .pd = priv->pd
2645         };
2646
2647         attr.comp_mask = IBV_EXP_QP_INIT_ATTR_PD;
2648         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
2649
2650         return ibv_exp_create_qp(priv->ctx, &attr);
2651 }
2652
2653 #else /* INLINE_RECV */
2654
2655 /**
2656  * Allocate a Queue Pair.
2657  *
2658  * @param priv
2659  *   Pointer to private structure.
2660  * @param cq
2661  *   Completion queue to associate with QP.
2662  * @param desc
2663  *   Number of descriptors in QP (hint only).
2664  *
2665  * @return
2666  *   QP pointer or NULL in case of error.
2667  */
2668 static struct ibv_qp *
2669 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc)
2670 {
2671         struct ibv_qp_init_attr attr = {
2672                 /* CQ to be associated with the send queue. */
2673                 .send_cq = cq,
2674                 /* CQ to be associated with the receive queue. */
2675                 .recv_cq = cq,
2676                 .cap = {
2677                         /* Max number of outstanding WRs. */
2678                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2679                                         priv->device_attr.max_qp_wr :
2680                                         desc),
2681                         /* Max number of scatter/gather elements in a WR. */
2682                         .max_recv_sge = ((priv->device_attr.max_sge <
2683                                           MLX4_PMD_SGE_WR_N) ?
2684                                          priv->device_attr.max_sge :
2685                                          MLX4_PMD_SGE_WR_N),
2686                 },
2687                 .qp_type = IBV_QPT_RAW_PACKET
2688         };
2689
2690         return ibv_create_qp(priv->pd, &attr);
2691 }
2692
2693 #endif /* INLINE_RECV */
2694
2695 #ifdef RSS_SUPPORT
2696
2697 /**
2698  * Allocate a RSS Queue Pair.
2699  *
2700  * @param priv
2701  *   Pointer to private structure.
2702  * @param cq
2703  *   Completion queue to associate with QP.
2704  * @param desc
2705  *   Number of descriptors in QP (hint only).
2706  * @param parent
2707  *   If nonzero, create a parent QP, otherwise a child.
2708  *
2709  * @return
2710  *   QP pointer or NULL in case of error.
2711  */
2712 static struct ibv_qp *
2713 rxq_setup_qp_rss(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
2714                  int parent)
2715 {
2716         struct ibv_exp_qp_init_attr attr = {
2717                 /* CQ to be associated with the send queue. */
2718                 .send_cq = cq,
2719                 /* CQ to be associated with the receive queue. */
2720                 .recv_cq = cq,
2721 #ifdef INLINE_RECV
2722                 .max_inl_recv = priv->inl_recv_size,
2723 #endif
2724                 .cap = {
2725                         /* Max number of outstanding WRs. */
2726                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2727                                         priv->device_attr.max_qp_wr :
2728                                         desc),
2729                         /* Max number of scatter/gather elements in a WR. */
2730                         .max_recv_sge = ((priv->device_attr.max_sge <
2731                                           MLX4_PMD_SGE_WR_N) ?
2732                                          priv->device_attr.max_sge :
2733                                          MLX4_PMD_SGE_WR_N),
2734                 },
2735                 .qp_type = IBV_QPT_RAW_PACKET,
2736                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
2737                               IBV_EXP_QP_INIT_ATTR_QPG),
2738                 .pd = priv->pd
2739         };
2740
2741 #ifdef INLINE_RECV
2742         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
2743 #endif
2744         if (parent) {
2745                 attr.qpg.qpg_type = IBV_EXP_QPG_PARENT;
2746                 /* TSS isn't necessary. */
2747                 attr.qpg.parent_attrib.tss_child_count = 0;
2748                 attr.qpg.parent_attrib.rss_child_count = priv->rxqs_n;
2749                 DEBUG("initializing parent RSS queue");
2750         } else {
2751                 attr.qpg.qpg_type = IBV_EXP_QPG_CHILD_RX;
2752                 attr.qpg.qpg_parent = priv->rxq_parent.qp;
2753                 DEBUG("initializing child RSS queue");
2754         }
2755         return ibv_exp_create_qp(priv->ctx, &attr);
2756 }
2757
2758 #endif /* RSS_SUPPORT */
2759
2760 /**
2761  * Reconfigure a RX queue with new parameters.
2762  *
2763  * rxq_rehash() does not allocate mbufs, which, if not done from the right
2764  * thread (such as a control thread), may corrupt the pool.
2765  * In case of failure, the queue is left untouched.
2766  *
2767  * @param dev
2768  *   Pointer to Ethernet device structure.
2769  * @param rxq
2770  *   RX queue pointer.
2771  *
2772  * @return
2773  *   0 on success, errno value on failure.
2774  */
2775 static int
2776 rxq_rehash(struct rte_eth_dev *dev, struct rxq *rxq)
2777 {
2778         struct priv *priv = rxq->priv;
2779         struct rxq tmpl = *rxq;
2780         unsigned int mbuf_n;
2781         unsigned int desc_n;
2782         struct rte_mbuf **pool;
2783         unsigned int i, k;
2784         struct ibv_exp_qp_attr mod;
2785         struct ibv_recv_wr *bad_wr;
2786         int err;
2787         int parent = (rxq == &priv->rxq_parent);
2788
2789         if (parent) {
2790                 ERROR("%p: cannot rehash parent queue %p",
2791                       (void *)dev, (void *)rxq);
2792                 return EINVAL;
2793         }
2794         DEBUG("%p: rehashing queue %p", (void *)dev, (void *)rxq);
2795         /* Number of descriptors and mbufs currently allocated. */
2796         desc_n = (tmpl.elts_n * (tmpl.sp ? MLX4_PMD_SGE_WR_N : 1));
2797         mbuf_n = desc_n;
2798         /* Enable scattered packets support for this queue if necessary. */
2799         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
2800             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
2801              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
2802                 tmpl.sp = 1;
2803                 desc_n /= MLX4_PMD_SGE_WR_N;
2804         } else
2805                 tmpl.sp = 0;
2806         DEBUG("%p: %s scattered packets support (%u WRs)",
2807               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc_n);
2808         /* If scatter mode is the same as before, nothing to do. */
2809         if (tmpl.sp == rxq->sp) {
2810                 DEBUG("%p: nothing to do", (void *)dev);
2811                 return 0;
2812         }
2813         /* Remove attached flows if RSS is disabled (no parent queue). */
2814         if (!priv->rss) {
2815                 rxq_allmulticast_disable(&tmpl);
2816                 rxq_promiscuous_disable(&tmpl);
2817                 rxq_mac_addrs_del(&tmpl);
2818                 /* Update original queue in case of failure. */
2819                 rxq->allmulti_flow = tmpl.allmulti_flow;
2820                 rxq->promisc_flow = tmpl.promisc_flow;
2821                 memcpy(rxq->mac_configured, tmpl.mac_configured,
2822                        sizeof(rxq->mac_configured));
2823                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
2824         }
2825         /* From now on, any failure will render the queue unusable.
2826          * Reinitialize QP. */
2827         mod = (struct ibv_exp_qp_attr){ .qp_state = IBV_QPS_RESET };
2828         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
2829         if (err) {
2830                 ERROR("%p: cannot reset QP: %s", (void *)dev, strerror(err));
2831                 assert(err > 0);
2832                 return err;
2833         }
2834         err = ibv_resize_cq(tmpl.cq, desc_n);
2835         if (err) {
2836                 ERROR("%p: cannot resize CQ: %s", (void *)dev, strerror(err));
2837                 assert(err > 0);
2838                 return err;
2839         }
2840         mod = (struct ibv_exp_qp_attr){
2841                 /* Move the QP to this state. */
2842                 .qp_state = IBV_QPS_INIT,
2843                 /* Primary port number. */
2844                 .port_num = priv->port
2845         };
2846         err = ibv_exp_modify_qp(tmpl.qp, &mod,
2847                                 (IBV_EXP_QP_STATE |
2848 #ifdef RSS_SUPPORT
2849                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
2850 #endif /* RSS_SUPPORT */
2851                                  IBV_EXP_QP_PORT));
2852         if (err) {
2853                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
2854                       (void *)dev, strerror(err));
2855                 assert(err > 0);
2856                 return err;
2857         };
2858         /* Reconfigure flows. Do not care for errors. */
2859         if (!priv->rss) {
2860                 rxq_mac_addrs_add(&tmpl);
2861                 if (priv->promisc)
2862                         rxq_promiscuous_enable(&tmpl);
2863                 if (priv->allmulti)
2864                         rxq_allmulticast_enable(&tmpl);
2865                 /* Update original queue in case of failure. */
2866                 rxq->allmulti_flow = tmpl.allmulti_flow;
2867                 rxq->promisc_flow = tmpl.promisc_flow;
2868                 memcpy(rxq->mac_configured, tmpl.mac_configured,
2869                        sizeof(rxq->mac_configured));
2870                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
2871         }
2872         /* Allocate pool. */
2873         pool = rte_malloc(__func__, (mbuf_n * sizeof(*pool)), 0);
2874         if (pool == NULL) {
2875                 ERROR("%p: cannot allocate memory", (void *)dev);
2876                 return ENOBUFS;
2877         }
2878         /* Snatch mbufs from original queue. */
2879         k = 0;
2880         if (rxq->sp) {
2881                 struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2882
2883                 for (i = 0; (i != elemof(*elts)); ++i) {
2884                         struct rxq_elt_sp *elt = &(*elts)[i];
2885                         unsigned int j;
2886
2887                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
2888                                 assert(elt->bufs[j] != NULL);
2889                                 pool[k++] = elt->bufs[j];
2890                         }
2891                 }
2892         } else {
2893                 struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
2894
2895                 for (i = 0; (i != elemof(*elts)); ++i) {
2896                         struct rxq_elt *elt = &(*elts)[i];
2897                         struct rte_mbuf *buf = (void *)
2898                                 ((uintptr_t)elt->sge.addr -
2899                                  WR_ID(elt->wr.wr_id).offset);
2900
2901                         assert(WR_ID(elt->wr.wr_id).id == i);
2902                         pool[k++] = buf;
2903                 }
2904         }
2905         assert(k == mbuf_n);
2906         tmpl.elts_n = 0;
2907         tmpl.elts.sp = NULL;
2908         assert((void *)&tmpl.elts.sp == (void *)&tmpl.elts.no_sp);
2909         err = ((tmpl.sp) ?
2910                rxq_alloc_elts_sp(&tmpl, desc_n, pool) :
2911                rxq_alloc_elts(&tmpl, desc_n, pool));
2912         if (err) {
2913                 ERROR("%p: cannot reallocate WRs, aborting", (void *)dev);
2914                 rte_free(pool);
2915                 assert(err > 0);
2916                 return err;
2917         }
2918         assert(tmpl.elts_n == desc_n);
2919         assert(tmpl.elts.sp != NULL);
2920         rte_free(pool);
2921         /* Clean up original data. */
2922         rxq->elts_n = 0;
2923         rte_free(rxq->elts.sp);
2924         rxq->elts.sp = NULL;
2925         /* Post WRs. */
2926         err = ibv_post_recv(tmpl.qp,
2927                             (tmpl.sp ?
2928                              &(*tmpl.elts.sp)[0].wr :
2929                              &(*tmpl.elts.no_sp)[0].wr),
2930                             &bad_wr);
2931         if (err) {
2932                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
2933                       (void *)dev,
2934                       (void *)bad_wr,
2935                       strerror(err));
2936                 goto skip_rtr;
2937         }
2938         mod = (struct ibv_exp_qp_attr){
2939                 .qp_state = IBV_QPS_RTR
2940         };
2941         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
2942         if (err)
2943                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
2944                       (void *)dev, strerror(err));
2945 skip_rtr:
2946         *rxq = tmpl;
2947         assert(err >= 0);
2948         return err;
2949 }
2950
2951 /**
2952  * Configure a RX queue.
2953  *
2954  * @param dev
2955  *   Pointer to Ethernet device structure.
2956  * @param rxq
2957  *   Pointer to RX queue structure.
2958  * @param desc
2959  *   Number of descriptors to configure in queue.
2960  * @param socket
2961  *   NUMA socket on which memory must be allocated.
2962  * @param[in] conf
2963  *   Thresholds parameters.
2964  * @param mp
2965  *   Memory pool for buffer allocations.
2966  *
2967  * @return
2968  *   0 on success, errno value on failure.
2969  */
2970 static int
2971 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
2972           unsigned int socket, const struct rte_eth_rxconf *conf,
2973           struct rte_mempool *mp)
2974 {
2975         struct priv *priv = dev->data->dev_private;
2976         struct rxq tmpl = {
2977                 .priv = priv,
2978                 .mp = mp,
2979                 .socket = socket
2980         };
2981         struct ibv_exp_qp_attr mod;
2982         struct ibv_recv_wr *bad_wr;
2983         struct rte_mbuf *buf;
2984         int ret = 0;
2985         int parent = (rxq == &priv->rxq_parent);
2986
2987         (void)conf; /* Thresholds configuration (ignored). */
2988         /*
2989          * If this is a parent queue, hardware must support RSS and
2990          * RSS must be enabled.
2991          */
2992         assert((!parent) || ((priv->hw_rss) && (priv->rss)));
2993         if (parent) {
2994                 /* Even if unused, ibv_create_cq() requires at least one
2995                  * descriptor. */
2996                 desc = 1;
2997                 goto skip_mr;
2998         }
2999         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
3000                 ERROR("%p: invalid number of RX descriptors (must be a"
3001                       " multiple of %d)", (void *)dev, desc);
3002                 return EINVAL;
3003         }
3004         /* Get mbuf length. */
3005         buf = rte_pktmbuf_alloc(mp);
3006         if (buf == NULL) {
3007                 ERROR("%p: unable to allocate mbuf", (void *)dev);
3008                 return ENOMEM;
3009         }
3010         tmpl.mb_len = buf->buf_len;
3011         assert((rte_pktmbuf_headroom(buf) +
3012                 rte_pktmbuf_tailroom(buf)) == tmpl.mb_len);
3013         assert(rte_pktmbuf_headroom(buf) == RTE_PKTMBUF_HEADROOM);
3014         rte_pktmbuf_free(buf);
3015         /* Enable scattered packets support for this queue if necessary. */
3016         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3017             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3018              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
3019                 tmpl.sp = 1;
3020                 desc /= MLX4_PMD_SGE_WR_N;
3021         }
3022         DEBUG("%p: %s scattered packets support (%u WRs)",
3023               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
3024         /* Use the entire RX mempool as the memory region. */
3025         tmpl.mr = ibv_reg_mr(priv->pd,
3026                              (void *)mp->elt_va_start,
3027                              (mp->elt_va_end - mp->elt_va_start),
3028                              (IBV_ACCESS_LOCAL_WRITE |
3029                               IBV_ACCESS_REMOTE_WRITE));
3030         if (tmpl.mr == NULL) {
3031                 ret = EINVAL;
3032                 ERROR("%p: MR creation failure: %s",
3033                       (void *)dev, strerror(ret));
3034                 goto error;
3035         }
3036 skip_mr:
3037         tmpl.cq = ibv_create_cq(priv->ctx, desc, NULL, NULL, 0);
3038         if (tmpl.cq == NULL) {
3039                 ret = ENOMEM;
3040                 ERROR("%p: CQ creation failure: %s",
3041                       (void *)dev, strerror(ret));
3042                 goto error;
3043         }
3044         DEBUG("priv->device_attr.max_qp_wr is %d",
3045               priv->device_attr.max_qp_wr);
3046         DEBUG("priv->device_attr.max_sge is %d",
3047               priv->device_attr.max_sge);
3048 #ifdef RSS_SUPPORT
3049         if (priv->rss)
3050                 tmpl.qp = rxq_setup_qp_rss(priv, tmpl.cq, desc, parent);
3051         else
3052 #endif /* RSS_SUPPORT */
3053                 tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc);
3054         if (tmpl.qp == NULL) {
3055                 ret = (errno ? errno : EINVAL);
3056                 ERROR("%p: QP creation failure: %s",
3057                       (void *)dev, strerror(ret));
3058                 goto error;
3059         }
3060         mod = (struct ibv_exp_qp_attr){
3061                 /* Move the QP to this state. */
3062                 .qp_state = IBV_QPS_INIT,
3063                 /* Primary port number. */
3064                 .port_num = priv->port
3065         };
3066         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
3067                                 (IBV_EXP_QP_STATE |
3068 #ifdef RSS_SUPPORT
3069                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3070 #endif /* RSS_SUPPORT */
3071                                  IBV_EXP_QP_PORT));
3072         if (ret) {
3073                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3074                       (void *)dev, strerror(ret));
3075                 goto error;
3076         }
3077         if ((parent) || (!priv->rss))  {
3078                 /* Configure MAC and broadcast addresses. */
3079                 ret = rxq_mac_addrs_add(&tmpl);
3080                 if (ret) {
3081                         ERROR("%p: QP flow attachment failed: %s",
3082                               (void *)dev, strerror(ret));
3083                         goto error;
3084                 }
3085         }
3086         /* Allocate descriptors for RX queues, except for the RSS parent. */
3087         if (parent)
3088                 goto skip_alloc;
3089         if (tmpl.sp)
3090                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
3091         else
3092                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
3093         if (ret) {
3094                 ERROR("%p: RXQ allocation failed: %s",
3095                       (void *)dev, strerror(ret));
3096                 goto error;
3097         }
3098         ret = ibv_post_recv(tmpl.qp,
3099                             (tmpl.sp ?
3100                              &(*tmpl.elts.sp)[0].wr :
3101                              &(*tmpl.elts.no_sp)[0].wr),
3102                             &bad_wr);
3103         if (ret) {
3104                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3105                       (void *)dev,
3106                       (void *)bad_wr,
3107                       strerror(ret));
3108                 goto error;
3109         }
3110 skip_alloc:
3111         mod = (struct ibv_exp_qp_attr){
3112                 .qp_state = IBV_QPS_RTR
3113         };
3114         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3115         if (ret) {
3116                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3117                       (void *)dev, strerror(ret));
3118                 goto error;
3119         }
3120         /* Save port ID. */
3121         tmpl.port_id = dev->data->port_id;
3122         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
3123         /* Clean up rxq in case we're reinitializing it. */
3124         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
3125         rxq_cleanup(rxq);
3126         *rxq = tmpl;
3127         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
3128         assert(ret == 0);
3129         return 0;
3130 error:
3131         rxq_cleanup(&tmpl);
3132         assert(ret > 0);
3133         return ret;
3134 }
3135
3136 /**
3137  * DPDK callback to configure a RX queue.
3138  *
3139  * @param dev
3140  *   Pointer to Ethernet device structure.
3141  * @param idx
3142  *   RX queue index.
3143  * @param desc
3144  *   Number of descriptors to configure in queue.
3145  * @param socket
3146  *   NUMA socket on which memory must be allocated.
3147  * @param[in] conf
3148  *   Thresholds parameters.
3149  * @param mp
3150  *   Memory pool for buffer allocations.
3151  *
3152  * @return
3153  *   0 on success, negative errno value on failure.
3154  */
3155 static int
3156 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
3157                     unsigned int socket, const struct rte_eth_rxconf *conf,
3158                     struct rte_mempool *mp)
3159 {
3160         struct priv *priv = dev->data->dev_private;
3161         struct rxq *rxq = (*priv->rxqs)[idx];
3162         int ret;
3163
3164         priv_lock(priv);
3165         DEBUG("%p: configuring queue %u for %u descriptors",
3166               (void *)dev, idx, desc);
3167         if (idx >= priv->rxqs_n) {
3168                 ERROR("%p: queue index out of range (%u >= %u)",
3169                       (void *)dev, idx, priv->rxqs_n);
3170                 priv_unlock(priv);
3171                 return -EOVERFLOW;
3172         }
3173         if (rxq != NULL) {
3174                 DEBUG("%p: reusing already allocated queue index %u (%p)",
3175                       (void *)dev, idx, (void *)rxq);
3176                 if (priv->started) {
3177                         priv_unlock(priv);
3178                         return -EEXIST;
3179                 }
3180                 (*priv->rxqs)[idx] = NULL;
3181                 rxq_cleanup(rxq);
3182         } else {
3183                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
3184                 if (rxq == NULL) {
3185                         ERROR("%p: unable to allocate queue index %u",
3186                               (void *)dev, idx);
3187                         priv_unlock(priv);
3188                         return -ENOMEM;
3189                 }
3190         }
3191         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
3192         if (ret)
3193                 rte_free(rxq);
3194         else {
3195                 rxq->stats.idx = idx;
3196                 DEBUG("%p: adding RX queue %p to list",
3197                       (void *)dev, (void *)rxq);
3198                 (*priv->rxqs)[idx] = rxq;
3199                 /* Update receive callback. */
3200                 if (rxq->sp)
3201                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3202                 else
3203                         dev->rx_pkt_burst = mlx4_rx_burst;
3204         }
3205         priv_unlock(priv);
3206         return -ret;
3207 }
3208
3209 /**
3210  * DPDK callback to release a RX queue.
3211  *
3212  * @param dpdk_rxq
3213  *   Generic RX queue pointer.
3214  */
3215 static void
3216 mlx4_rx_queue_release(void *dpdk_rxq)
3217 {
3218         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3219         struct priv *priv;
3220         unsigned int i;
3221
3222         if (rxq == NULL)
3223                 return;
3224         priv = rxq->priv;
3225         priv_lock(priv);
3226         assert(rxq != &priv->rxq_parent);
3227         for (i = 0; (i != priv->rxqs_n); ++i)
3228                 if ((*priv->rxqs)[i] == rxq) {
3229                         DEBUG("%p: removing RX queue %p from list",
3230                               (void *)priv->dev, (void *)rxq);
3231                         (*priv->rxqs)[i] = NULL;
3232                         break;
3233                 }
3234         rxq_cleanup(rxq);
3235         rte_free(rxq);
3236         priv_unlock(priv);
3237 }
3238
3239 /**
3240  * DPDK callback to start the device.
3241  *
3242  * Simulate device start by attaching all configured flows.
3243  *
3244  * @param dev
3245  *   Pointer to Ethernet device structure.
3246  *
3247  * @return
3248  *   0 on success, negative errno value on failure.
3249  */
3250 static int
3251 mlx4_dev_start(struct rte_eth_dev *dev)
3252 {
3253         struct priv *priv = dev->data->dev_private;
3254         unsigned int i = 0;
3255         unsigned int r;
3256         struct rxq *rxq;
3257
3258         priv_lock(priv);
3259         if (priv->started) {
3260                 priv_unlock(priv);
3261                 return 0;
3262         }
3263         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
3264         priv->started = 1;
3265         if (priv->rss) {
3266                 rxq = &priv->rxq_parent;
3267                 r = 1;
3268         } else {
3269                 rxq = (*priv->rxqs)[0];
3270                 r = priv->rxqs_n;
3271         }
3272         /* Iterate only once when RSS is enabled. */
3273         do {
3274                 int ret;
3275
3276                 /* Ignore nonexistent RX queues. */
3277                 if (rxq == NULL)
3278                         continue;
3279                 ret = rxq_mac_addrs_add(rxq);
3280                 if (!ret && priv->promisc)
3281                         ret = rxq_promiscuous_enable(rxq);
3282                 if (!ret && priv->allmulti)
3283                         ret = rxq_allmulticast_enable(rxq);
3284                 if (!ret)
3285                         continue;
3286                 WARN("%p: QP flow attachment failed: %s",
3287                      (void *)dev, strerror(ret));
3288                 /* Rollback. */
3289                 while (i != 0) {
3290                         rxq = (*priv->rxqs)[--i];
3291                         if (rxq != NULL) {
3292                                 rxq_allmulticast_disable(rxq);
3293                                 rxq_promiscuous_disable(rxq);
3294                                 rxq_mac_addrs_del(rxq);
3295                         }
3296                 }
3297                 priv->started = 0;
3298                 return -ret;
3299         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3300         priv_unlock(priv);
3301         return 0;
3302 }
3303
3304 /**
3305  * DPDK callback to stop the device.
3306  *
3307  * Simulate device stop by detaching all configured flows.
3308  *
3309  * @param dev
3310  *   Pointer to Ethernet device structure.
3311  */
3312 static void
3313 mlx4_dev_stop(struct rte_eth_dev *dev)
3314 {
3315         struct priv *priv = dev->data->dev_private;
3316         unsigned int i = 0;
3317         unsigned int r;
3318         struct rxq *rxq;
3319
3320         priv_lock(priv);
3321         if (!priv->started) {
3322                 priv_unlock(priv);
3323                 return;
3324         }
3325         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
3326         priv->started = 0;
3327         if (priv->rss) {
3328                 rxq = &priv->rxq_parent;
3329                 r = 1;
3330         } else {
3331                 rxq = (*priv->rxqs)[0];
3332                 r = priv->rxqs_n;
3333         }
3334         /* Iterate only once when RSS is enabled. */
3335         do {
3336                 /* Ignore nonexistent RX queues. */
3337                 if (rxq == NULL)
3338                         continue;
3339                 rxq_allmulticast_disable(rxq);
3340                 rxq_promiscuous_disable(rxq);
3341                 rxq_mac_addrs_del(rxq);
3342         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3343         priv_unlock(priv);
3344 }
3345
3346 /**
3347  * Dummy DPDK callback for TX.
3348  *
3349  * This function is used to temporarily replace the real callback during
3350  * unsafe control operations on the queue, or in case of error.
3351  *
3352  * @param dpdk_txq
3353  *   Generic pointer to TX queue structure.
3354  * @param[in] pkts
3355  *   Packets to transmit.
3356  * @param pkts_n
3357  *   Number of packets in array.
3358  *
3359  * @return
3360  *   Number of packets successfully transmitted (<= pkts_n).
3361  */
3362 static uint16_t
3363 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
3364 {
3365         (void)dpdk_txq;
3366         (void)pkts;
3367         (void)pkts_n;
3368         return 0;
3369 }
3370
3371 /**
3372  * Dummy DPDK callback for RX.
3373  *
3374  * This function is used to temporarily replace the real callback during
3375  * unsafe control operations on the queue, or in case of error.
3376  *
3377  * @param dpdk_rxq
3378  *   Generic pointer to RX queue structure.
3379  * @param[out] pkts
3380  *   Array to store received packets.
3381  * @param pkts_n
3382  *   Maximum number of packets in array.
3383  *
3384  * @return
3385  *   Number of packets successfully received (<= pkts_n).
3386  */
3387 static uint16_t
3388 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
3389 {
3390         (void)dpdk_rxq;
3391         (void)pkts;
3392         (void)pkts_n;
3393         return 0;
3394 }
3395
3396 /**
3397  * DPDK callback to close the device.
3398  *
3399  * Destroy all queues and objects, free memory.
3400  *
3401  * @param dev
3402  *   Pointer to Ethernet device structure.
3403  */
3404 static void
3405 mlx4_dev_close(struct rte_eth_dev *dev)
3406 {
3407         struct priv *priv = dev->data->dev_private;
3408         void *tmp;
3409         unsigned int i;
3410
3411         priv_lock(priv);
3412         DEBUG("%p: closing device \"%s\"",
3413               (void *)dev,
3414               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
3415         /* Prevent crashes when queues are still in use. This is unfortunately
3416          * still required for DPDK 1.3 because some programs (such as testpmd)
3417          * never release them before closing the device. */
3418         dev->rx_pkt_burst = removed_rx_burst;
3419         dev->tx_pkt_burst = removed_tx_burst;
3420         if (priv->rxqs != NULL) {
3421                 /* XXX race condition if mlx4_rx_burst() is still running. */
3422                 usleep(1000);
3423                 for (i = 0; (i != priv->rxqs_n); ++i) {
3424                         tmp = (*priv->rxqs)[i];
3425                         if (tmp == NULL)
3426                                 continue;
3427                         (*priv->rxqs)[i] = NULL;
3428                         rxq_cleanup(tmp);
3429                         rte_free(tmp);
3430                 }
3431                 priv->rxqs_n = 0;
3432                 priv->rxqs = NULL;
3433         }
3434         if (priv->txqs != NULL) {
3435                 /* XXX race condition if mlx4_tx_burst() is still running. */
3436                 usleep(1000);
3437                 for (i = 0; (i != priv->txqs_n); ++i) {
3438                         tmp = (*priv->txqs)[i];
3439                         if (tmp == NULL)
3440                                 continue;
3441                         (*priv->txqs)[i] = NULL;
3442                         txq_cleanup(tmp);
3443                         rte_free(tmp);
3444                 }
3445                 priv->txqs_n = 0;
3446                 priv->txqs = NULL;
3447         }
3448         if (priv->rss)
3449                 rxq_cleanup(&priv->rxq_parent);
3450         if (priv->pd != NULL) {
3451                 assert(priv->ctx != NULL);
3452                 claim_zero(ibv_dealloc_pd(priv->pd));
3453                 claim_zero(ibv_close_device(priv->ctx));
3454         } else
3455                 assert(priv->ctx == NULL);
3456         priv_unlock(priv);
3457         memset(priv, 0, sizeof(*priv));
3458 }
3459
3460 /**
3461  * DPDK callback to get information about the device.
3462  *
3463  * @param dev
3464  *   Pointer to Ethernet device structure.
3465  * @param[out] info
3466  *   Info structure output buffer.
3467  */
3468 static void
3469 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
3470 {
3471         struct priv *priv = dev->data->dev_private;
3472         unsigned int max;
3473
3474         priv_lock(priv);
3475         /* FIXME: we should ask the device for these values. */
3476         info->min_rx_bufsize = 32;
3477         info->max_rx_pktlen = 65536;
3478         /*
3479          * Since we need one CQ per QP, the limit is the minimum number
3480          * between the two values.
3481          */
3482         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
3483                priv->device_attr.max_qp : priv->device_attr.max_cq);
3484         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
3485         if (max >= 65535)
3486                 max = 65535;
3487         info->max_rx_queues = max;
3488         info->max_tx_queues = max;
3489         info->max_mac_addrs = elemof(priv->mac);
3490         priv_unlock(priv);
3491 }
3492
3493 /**
3494  * DPDK callback to get device statistics.
3495  *
3496  * @param dev
3497  *   Pointer to Ethernet device structure.
3498  * @param[out] stats
3499  *   Stats structure output buffer.
3500  */
3501 static void
3502 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
3503 {
3504         struct priv *priv = dev->data->dev_private;
3505         struct rte_eth_stats tmp = {0};
3506         unsigned int i;
3507         unsigned int idx;
3508
3509         priv_lock(priv);
3510         /* Add software counters. */
3511         for (i = 0; (i != priv->rxqs_n); ++i) {
3512                 struct rxq *rxq = (*priv->rxqs)[i];
3513
3514                 if (rxq == NULL)
3515                         continue;
3516                 idx = rxq->stats.idx;
3517                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3518 #ifdef MLX4_PMD_SOFT_COUNTERS
3519                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
3520                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
3521 #endif
3522                         tmp.q_errors[idx] += (rxq->stats.idropped +
3523                                               rxq->stats.rx_nombuf);
3524                 }
3525 #ifdef MLX4_PMD_SOFT_COUNTERS
3526                 tmp.ipackets += rxq->stats.ipackets;
3527                 tmp.ibytes += rxq->stats.ibytes;
3528 #endif
3529                 tmp.ierrors += rxq->stats.idropped;
3530                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
3531         }
3532         for (i = 0; (i != priv->txqs_n); ++i) {
3533                 struct txq *txq = (*priv->txqs)[i];
3534
3535                 if (txq == NULL)
3536                         continue;
3537                 idx = txq->stats.idx;
3538                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3539 #ifdef MLX4_PMD_SOFT_COUNTERS
3540                         tmp.q_opackets[idx] += txq->stats.opackets;
3541                         tmp.q_obytes[idx] += txq->stats.obytes;
3542 #endif
3543                         tmp.q_errors[idx] += txq->stats.odropped;
3544                 }
3545 #ifdef MLX4_PMD_SOFT_COUNTERS
3546                 tmp.opackets += txq->stats.opackets;
3547                 tmp.obytes += txq->stats.obytes;
3548 #endif
3549                 tmp.oerrors += txq->stats.odropped;
3550         }
3551 #ifndef MLX4_PMD_SOFT_COUNTERS
3552         /* FIXME: retrieve and add hardware counters. */
3553 #endif
3554         *stats = tmp;
3555         priv_unlock(priv);
3556 }
3557
3558 /**
3559  * DPDK callback to clear device statistics.
3560  *
3561  * @param dev
3562  *   Pointer to Ethernet device structure.
3563  */
3564 static void
3565 mlx4_stats_reset(struct rte_eth_dev *dev)
3566 {
3567         struct priv *priv = dev->data->dev_private;
3568         unsigned int i;
3569         unsigned int idx;
3570
3571         priv_lock(priv);
3572         for (i = 0; (i != priv->rxqs_n); ++i) {
3573                 if ((*priv->rxqs)[i] == NULL)
3574                         continue;
3575                 idx = (*priv->rxqs)[i]->stats.idx;
3576                 (*priv->rxqs)[i]->stats =
3577                         (struct mlx4_rxq_stats){ .idx = idx };
3578         }
3579         for (i = 0; (i != priv->txqs_n); ++i) {
3580                 if ((*priv->txqs)[i] == NULL)
3581                         continue;
3582                 idx = (*priv->rxqs)[i]->stats.idx;
3583                 (*priv->txqs)[i]->stats =
3584                         (struct mlx4_txq_stats){ .idx = idx };
3585         }
3586 #ifndef MLX4_PMD_SOFT_COUNTERS
3587         /* FIXME: reset hardware counters. */
3588 #endif
3589         priv_unlock(priv);
3590 }
3591
3592 /**
3593  * DPDK callback to remove a MAC address.
3594  *
3595  * @param dev
3596  *   Pointer to Ethernet device structure.
3597  * @param index
3598  *   MAC address index.
3599  */
3600 static void
3601 mlx4_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
3602 {
3603         struct priv *priv = dev->data->dev_private;
3604
3605         priv_lock(priv);
3606         DEBUG("%p: removing MAC address from index %" PRIu32,
3607               (void *)dev, index);
3608         if (index >= MLX4_MAX_MAC_ADDRESSES)
3609                 goto end;
3610         /* Refuse to remove the broadcast address, this one is special. */
3611         if (!memcmp(priv->mac[index].addr_bytes, "\xff\xff\xff\xff\xff\xff",
3612                     ETHER_ADDR_LEN))
3613                 goto end;
3614         priv_mac_addr_del(priv, index);
3615 end:
3616         priv_unlock(priv);
3617 }
3618
3619 /**
3620  * DPDK callback to add a MAC address.
3621  *
3622  * @param dev
3623  *   Pointer to Ethernet device structure.
3624  * @param mac_addr
3625  *   MAC address to register.
3626  * @param index
3627  *   MAC address index.
3628  * @param vmdq
3629  *   VMDq pool index to associate address with (ignored).
3630  */
3631 static void
3632 mlx4_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
3633                   uint32_t index, uint32_t vmdq)
3634 {
3635         struct priv *priv = dev->data->dev_private;
3636
3637         (void)vmdq;
3638         priv_lock(priv);
3639         DEBUG("%p: adding MAC address at index %" PRIu32,
3640               (void *)dev, index);
3641         if (index >= MLX4_MAX_MAC_ADDRESSES)
3642                 goto end;
3643         /* Refuse to add the broadcast address, this one is special. */
3644         if (!memcmp(mac_addr->addr_bytes, "\xff\xff\xff\xff\xff\xff",
3645                     ETHER_ADDR_LEN))
3646                 goto end;
3647         priv_mac_addr_add(priv, index,
3648                           (const uint8_t (*)[ETHER_ADDR_LEN])
3649                           mac_addr->addr_bytes);
3650 end:
3651         priv_unlock(priv);
3652 }
3653
3654 /**
3655  * DPDK callback to enable promiscuous mode.
3656  *
3657  * @param dev
3658  *   Pointer to Ethernet device structure.
3659  */
3660 static void
3661 mlx4_promiscuous_enable(struct rte_eth_dev *dev)
3662 {
3663         struct priv *priv = dev->data->dev_private;
3664         unsigned int i;
3665         int ret;
3666
3667         priv_lock(priv);
3668         if (priv->promisc) {
3669                 priv_unlock(priv);
3670                 return;
3671         }
3672         /* If device isn't started, this is all we need to do. */
3673         if (!priv->started)
3674                 goto end;
3675         if (priv->rss) {
3676                 ret = rxq_promiscuous_enable(&priv->rxq_parent);
3677                 if (ret) {
3678                         priv_unlock(priv);
3679                         return;
3680                 }
3681                 goto end;
3682         }
3683         for (i = 0; (i != priv->rxqs_n); ++i) {
3684                 if ((*priv->rxqs)[i] == NULL)
3685                         continue;
3686                 ret = rxq_promiscuous_enable((*priv->rxqs)[i]);
3687                 if (!ret)
3688                         continue;
3689                 /* Failure, rollback. */
3690                 while (i != 0)
3691                         if ((*priv->rxqs)[--i] != NULL)
3692                                 rxq_promiscuous_disable((*priv->rxqs)[i]);
3693                 priv_unlock(priv);
3694                 return;
3695         }
3696 end:
3697         priv->promisc = 1;
3698         priv_unlock(priv);
3699 }
3700
3701 /**
3702  * DPDK callback to disable promiscuous mode.
3703  *
3704  * @param dev
3705  *   Pointer to Ethernet device structure.
3706  */
3707 static void
3708 mlx4_promiscuous_disable(struct rte_eth_dev *dev)
3709 {
3710         struct priv *priv = dev->data->dev_private;
3711         unsigned int i;
3712
3713         priv_lock(priv);
3714         if (!priv->promisc) {
3715                 priv_unlock(priv);
3716                 return;
3717         }
3718         if (priv->rss) {
3719                 rxq_promiscuous_disable(&priv->rxq_parent);
3720                 goto end;
3721         }
3722         for (i = 0; (i != priv->rxqs_n); ++i)
3723                 if ((*priv->rxqs)[i] != NULL)
3724                         rxq_promiscuous_disable((*priv->rxqs)[i]);
3725 end:
3726         priv->promisc = 0;
3727         priv_unlock(priv);
3728 }
3729
3730 /**
3731  * DPDK callback to enable allmulti mode.
3732  *
3733  * @param dev
3734  *   Pointer to Ethernet device structure.
3735  */
3736 static void
3737 mlx4_allmulticast_enable(struct rte_eth_dev *dev)
3738 {
3739         struct priv *priv = dev->data->dev_private;
3740         unsigned int i;
3741         int ret;
3742
3743         priv_lock(priv);
3744         if (priv->allmulti) {
3745                 priv_unlock(priv);
3746                 return;
3747         }
3748         /* If device isn't started, this is all we need to do. */
3749         if (!priv->started)
3750                 goto end;
3751         if (priv->rss) {
3752                 ret = rxq_allmulticast_enable(&priv->rxq_parent);
3753                 if (ret) {
3754                         priv_unlock(priv);
3755                         return;
3756                 }
3757                 goto end;
3758         }
3759         for (i = 0; (i != priv->rxqs_n); ++i) {
3760                 if ((*priv->rxqs)[i] == NULL)
3761                         continue;
3762                 ret = rxq_allmulticast_enable((*priv->rxqs)[i]);
3763                 if (!ret)
3764                         continue;
3765                 /* Failure, rollback. */
3766                 while (i != 0)
3767                         if ((*priv->rxqs)[--i] != NULL)
3768                                 rxq_allmulticast_disable((*priv->rxqs)[i]);
3769                 priv_unlock(priv);
3770                 return;
3771         }
3772 end:
3773         priv->allmulti = 1;
3774         priv_unlock(priv);
3775 }
3776
3777 /**
3778  * DPDK callback to disable allmulti mode.
3779  *
3780  * @param dev
3781  *   Pointer to Ethernet device structure.
3782  */
3783 static void
3784 mlx4_allmulticast_disable(struct rte_eth_dev *dev)
3785 {
3786         struct priv *priv = dev->data->dev_private;
3787         unsigned int i;
3788
3789         priv_lock(priv);
3790         if (!priv->allmulti) {
3791                 priv_unlock(priv);
3792                 return;
3793         }
3794         if (priv->rss) {
3795                 rxq_allmulticast_disable(&priv->rxq_parent);
3796                 goto end;
3797         }
3798         for (i = 0; (i != priv->rxqs_n); ++i)
3799                 if ((*priv->rxqs)[i] != NULL)
3800                         rxq_allmulticast_disable((*priv->rxqs)[i]);
3801 end:
3802         priv->allmulti = 0;
3803         priv_unlock(priv);
3804 }
3805
3806 /**
3807  * DPDK callback to retrieve physical link information (unlocked version).
3808  *
3809  * @param dev
3810  *   Pointer to Ethernet device structure.
3811  * @param wait_to_complete
3812  *   Wait for request completion (ignored).
3813  */
3814 static int
3815 mlx4_link_update_unlocked(struct rte_eth_dev *dev, int wait_to_complete)
3816 {
3817         struct priv *priv = dev->data->dev_private;
3818         struct ibv_port_attr port_attr;
3819         static const uint8_t width_mult[] = {
3820                 /* Multiplier values taken from devinfo.c in libibverbs. */
3821                 0, 1, 4, 0, 8, 0, 0, 0, 12, 0
3822         };
3823
3824         (void)wait_to_complete;
3825         errno = ibv_query_port(priv->ctx, priv->port, &port_attr);
3826         if (errno) {
3827                 WARN("port query failed: %s", strerror(errno));
3828                 return -1;
3829         }
3830         dev->data->dev_link = (struct rte_eth_link){
3831                 .link_speed = (ibv_rate_to_mbps(mult_to_ibv_rate
3832                                                 (port_attr.active_speed)) *
3833                                width_mult[(port_attr.active_width %
3834                                            sizeof(width_mult))]),
3835                 .link_duplex = ETH_LINK_FULL_DUPLEX,
3836                 .link_status = (port_attr.state == IBV_PORT_ACTIVE)
3837         };
3838         if (memcmp(&port_attr, &priv->port_attr, sizeof(port_attr))) {
3839                 /* Link status changed. */
3840                 priv->port_attr = port_attr;
3841                 return 0;
3842         }
3843         /* Link status is still the same. */
3844         return -1;
3845 }
3846
3847 /**
3848  * DPDK callback to retrieve physical link information.
3849  *
3850  * @param dev
3851  *   Pointer to Ethernet device structure.
3852  * @param wait_to_complete
3853  *   Wait for request completion (ignored).
3854  */
3855 static int
3856 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
3857 {
3858         struct priv *priv = dev->data->dev_private;
3859         int ret;
3860
3861         priv_lock(priv);
3862         ret = mlx4_link_update_unlocked(dev, wait_to_complete);
3863         priv_unlock(priv);
3864         return ret;
3865 }
3866
3867 /**
3868  * DPDK callback to change the MTU.
3869  *
3870  * Setting the MTU affects hardware MRU (packets larger than the MTU cannot be
3871  * received). Use this as a hint to enable/disable scattered packets support
3872  * and improve performance when not needed.
3873  * Since failure is not an option, reconfiguring queues on the fly is not
3874  * recommended.
3875  *
3876  * @param dev
3877  *   Pointer to Ethernet device structure.
3878  * @param in_mtu
3879  *   New MTU.
3880  *
3881  * @return
3882  *   0 on success, negative errno value on failure.
3883  */
3884 static int
3885 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
3886 {
3887         struct priv *priv = dev->data->dev_private;
3888         int ret = 0;
3889         unsigned int i;
3890         uint16_t (*rx_func)(void *, struct rte_mbuf **, uint16_t) =
3891                 mlx4_rx_burst;
3892
3893         priv_lock(priv);
3894         /* Set kernel interface MTU first. */
3895         if (priv_set_mtu(priv, mtu)) {
3896                 ret = errno;
3897                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
3898                      strerror(ret));
3899                 goto out;
3900         } else
3901                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
3902         priv->mtu = mtu;
3903         /* Temporarily replace RX handler with a fake one, assuming it has not
3904          * been copied elsewhere. */
3905         dev->rx_pkt_burst = removed_rx_burst;
3906         /* Make sure everyone has left mlx4_rx_burst() and uses
3907          * removed_rx_burst() instead. */
3908         rte_wmb();
3909         usleep(1000);
3910         /* Reconfigure each RX queue. */
3911         for (i = 0; (i != priv->rxqs_n); ++i) {
3912                 struct rxq *rxq = (*priv->rxqs)[i];
3913                 unsigned int max_frame_len;
3914                 int sp;
3915
3916                 if (rxq == NULL)
3917                         continue;
3918                 /* Calculate new maximum frame length according to MTU and
3919                  * toggle scattered support (sp) if necessary. */
3920                 max_frame_len = (priv->mtu + ETHER_HDR_LEN +
3921                                  (ETHER_MAX_VLAN_FRAME_LEN - ETHER_MAX_LEN));
3922                 sp = (max_frame_len > (rxq->mb_len - RTE_PKTMBUF_HEADROOM));
3923                 /* Provide new values to rxq_setup(). */
3924                 dev->data->dev_conf.rxmode.jumbo_frame = sp;
3925                 dev->data->dev_conf.rxmode.max_rx_pkt_len = max_frame_len;
3926                 ret = rxq_rehash(dev, rxq);
3927                 if (ret) {
3928                         /* Force SP RX if that queue requires it and abort. */
3929                         if (rxq->sp)
3930                                 rx_func = mlx4_rx_burst_sp;
3931                         break;
3932                 }
3933                 /* Reenable non-RSS queue attributes. No need to check
3934                  * for errors at this stage. */
3935                 if (!priv->rss) {
3936                         rxq_mac_addrs_add(rxq);
3937                         if (priv->promisc)
3938                                 rxq_promiscuous_enable(rxq);
3939                         if (priv->allmulti)
3940                                 rxq_allmulticast_enable(rxq);
3941                 }
3942                 /* Scattered burst function takes priority. */
3943                 if (rxq->sp)
3944                         rx_func = mlx4_rx_burst_sp;
3945         }
3946         /* Burst functions can now be called again. */
3947         rte_wmb();
3948         dev->rx_pkt_burst = rx_func;
3949 out:
3950         priv_unlock(priv);
3951         assert(ret >= 0);
3952         return -ret;
3953 }
3954
3955 /**
3956  * DPDK callback to get flow control status.
3957  *
3958  * @param dev
3959  *   Pointer to Ethernet device structure.
3960  * @param[out] fc_conf
3961  *   Flow control output buffer.
3962  *
3963  * @return
3964  *   0 on success, negative errno value on failure.
3965  */
3966 static int
3967 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
3968 {
3969         struct priv *priv = dev->data->dev_private;
3970         struct ifreq ifr;
3971         struct ethtool_pauseparam ethpause = {
3972                 .cmd = ETHTOOL_GPAUSEPARAM
3973         };
3974         int ret;
3975
3976         ifr.ifr_data = &ethpause;
3977         priv_lock(priv);
3978         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
3979                 ret = errno;
3980                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
3981                      " failed: %s",
3982                      strerror(ret));
3983                 goto out;
3984         }
3985
3986         fc_conf->autoneg = ethpause.autoneg;
3987         if (ethpause.rx_pause && ethpause.tx_pause)
3988                 fc_conf->mode = RTE_FC_FULL;
3989         else if (ethpause.rx_pause)
3990                 fc_conf->mode = RTE_FC_RX_PAUSE;
3991         else if (ethpause.tx_pause)
3992                 fc_conf->mode = RTE_FC_TX_PAUSE;
3993         else
3994                 fc_conf->mode = RTE_FC_NONE;
3995         ret = 0;
3996
3997 out:
3998         priv_unlock(priv);
3999         assert(ret >= 0);
4000         return -ret;
4001 }
4002
4003 /**
4004  * DPDK callback to modify flow control parameters.
4005  *
4006  * @param dev
4007  *   Pointer to Ethernet device structure.
4008  * @param[in] fc_conf
4009  *   Flow control parameters.
4010  *
4011  * @return
4012  *   0 on success, negative errno value on failure.
4013  */
4014 static int
4015 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4016 {
4017         struct priv *priv = dev->data->dev_private;
4018         struct ifreq ifr;
4019         struct ethtool_pauseparam ethpause = {
4020                 .cmd = ETHTOOL_SPAUSEPARAM
4021         };
4022         int ret;
4023
4024         ifr.ifr_data = &ethpause;
4025         ethpause.autoneg = fc_conf->autoneg;
4026         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4027             (fc_conf->mode & RTE_FC_RX_PAUSE))
4028                 ethpause.rx_pause = 1;
4029         else
4030                 ethpause.rx_pause = 0;
4031
4032         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4033             (fc_conf->mode & RTE_FC_TX_PAUSE))
4034                 ethpause.tx_pause = 1;
4035         else
4036                 ethpause.tx_pause = 0;
4037
4038         priv_lock(priv);
4039         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4040                 ret = errno;
4041                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
4042                      " failed: %s",
4043                      strerror(ret));
4044                 goto out;
4045         }
4046         ret = 0;
4047
4048 out:
4049         priv_unlock(priv);
4050         assert(ret >= 0);
4051         return -ret;
4052 }
4053
4054 /**
4055  * Configure a VLAN filter.
4056  *
4057  * @param dev
4058  *   Pointer to Ethernet device structure.
4059  * @param vlan_id
4060  *   VLAN ID to filter.
4061  * @param on
4062  *   Toggle filter.
4063  *
4064  * @return
4065  *   0 on success, errno value on failure.
4066  */
4067 static int
4068 vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4069 {
4070         struct priv *priv = dev->data->dev_private;
4071         unsigned int i;
4072         unsigned int j = -1;
4073
4074         DEBUG("%p: %s VLAN filter ID %" PRIu16,
4075               (void *)dev, (on ? "enable" : "disable"), vlan_id);
4076         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
4077                 if (!priv->vlan_filter[i].enabled) {
4078                         /* Unused index, remember it. */
4079                         j = i;
4080                         continue;
4081                 }
4082                 if (priv->vlan_filter[i].id != vlan_id)
4083                         continue;
4084                 /* This VLAN ID is already known, use its index. */
4085                 j = i;
4086                 break;
4087         }
4088         /* Check if there's room for another VLAN filter. */
4089         if (j == (unsigned int)-1)
4090                 return ENOMEM;
4091         /*
4092          * VLAN filters apply to all configured MAC addresses, flow
4093          * specifications must be reconfigured accordingly.
4094          */
4095         priv->vlan_filter[j].id = vlan_id;
4096         if ((on) && (!priv->vlan_filter[j].enabled)) {
4097                 /*
4098                  * Filter is disabled, enable it.
4099                  * Rehashing flows in all RX queues is necessary.
4100                  */
4101                 if (priv->rss)
4102                         rxq_mac_addrs_del(&priv->rxq_parent);
4103                 else
4104                         for (i = 0; (i != priv->rxqs_n); ++i)
4105                                 if ((*priv->rxqs)[i] != NULL)
4106                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4107                 priv->vlan_filter[j].enabled = 1;
4108                 if (priv->started) {
4109                         if (priv->rss)
4110                                 rxq_mac_addrs_add(&priv->rxq_parent);
4111                         else
4112                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4113                                         if ((*priv->rxqs)[i] == NULL)
4114                                                 continue;
4115                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4116                                 }
4117                 }
4118         } else if ((!on) && (priv->vlan_filter[j].enabled)) {
4119                 /*
4120                  * Filter is enabled, disable it.
4121                  * Rehashing flows in all RX queues is necessary.
4122                  */
4123                 if (priv->rss)
4124                         rxq_mac_addrs_del(&priv->rxq_parent);
4125                 else
4126                         for (i = 0; (i != priv->rxqs_n); ++i)
4127                                 if ((*priv->rxqs)[i] != NULL)
4128                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4129                 priv->vlan_filter[j].enabled = 0;
4130                 if (priv->started) {
4131                         if (priv->rss)
4132                                 rxq_mac_addrs_add(&priv->rxq_parent);
4133                         else
4134                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4135                                         if ((*priv->rxqs)[i] == NULL)
4136                                                 continue;
4137                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4138                                 }
4139                 }
4140         }
4141         return 0;
4142 }
4143
4144 /**
4145  * DPDK callback to configure a VLAN filter.
4146  *
4147  * @param dev
4148  *   Pointer to Ethernet device structure.
4149  * @param vlan_id
4150  *   VLAN ID to filter.
4151  * @param on
4152  *   Toggle filter.
4153  *
4154  * @return
4155  *   0 on success, negative errno value on failure.
4156  */
4157 static int
4158 mlx4_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4159 {
4160         struct priv *priv = dev->data->dev_private;
4161         int ret;
4162
4163         priv_lock(priv);
4164         ret = vlan_filter_set(dev, vlan_id, on);
4165         priv_unlock(priv);
4166         assert(ret >= 0);
4167         return -ret;
4168 }
4169
4170 static const struct eth_dev_ops mlx4_dev_ops = {
4171         .dev_configure = mlx4_dev_configure,
4172         .dev_start = mlx4_dev_start,
4173         .dev_stop = mlx4_dev_stop,
4174         .dev_close = mlx4_dev_close,
4175         .promiscuous_enable = mlx4_promiscuous_enable,
4176         .promiscuous_disable = mlx4_promiscuous_disable,
4177         .allmulticast_enable = mlx4_allmulticast_enable,
4178         .allmulticast_disable = mlx4_allmulticast_disable,
4179         .link_update = mlx4_link_update,
4180         .stats_get = mlx4_stats_get,
4181         .stats_reset = mlx4_stats_reset,
4182         .queue_stats_mapping_set = NULL,
4183         .dev_infos_get = mlx4_dev_infos_get,
4184         .vlan_filter_set = mlx4_vlan_filter_set,
4185         .vlan_tpid_set = NULL,
4186         .vlan_strip_queue_set = NULL,
4187         .vlan_offload_set = NULL,
4188         .rx_queue_setup = mlx4_rx_queue_setup,
4189         .tx_queue_setup = mlx4_tx_queue_setup,
4190         .rx_queue_release = mlx4_rx_queue_release,
4191         .tx_queue_release = mlx4_tx_queue_release,
4192         .dev_led_on = NULL,
4193         .dev_led_off = NULL,
4194         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
4195         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
4196         .priority_flow_ctrl_set = NULL,
4197         .mac_addr_remove = mlx4_mac_addr_remove,
4198         .mac_addr_add = mlx4_mac_addr_add,
4199         .mtu_set = mlx4_dev_set_mtu,
4200         .fdir_add_signature_filter = NULL,
4201         .fdir_update_signature_filter = NULL,
4202         .fdir_remove_signature_filter = NULL,
4203         .fdir_add_perfect_filter = NULL,
4204         .fdir_update_perfect_filter = NULL,
4205         .fdir_remove_perfect_filter = NULL,
4206         .fdir_set_masks = NULL
4207 };
4208
4209 /**
4210  * Get PCI information from struct ibv_device.
4211  *
4212  * @param device
4213  *   Pointer to Ethernet device structure.
4214  * @param[out] pci_addr
4215  *   PCI bus address output buffer.
4216  *
4217  * @return
4218  *   0 on success, -1 on failure and errno is set.
4219  */
4220 static int
4221 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
4222                             struct rte_pci_addr *pci_addr)
4223 {
4224         FILE *file;
4225         char line[32];
4226         MKSTR(path, "%s/device/uevent", device->ibdev_path);
4227
4228         file = fopen(path, "rb");
4229         if (file == NULL)
4230                 return -1;
4231         while (fgets(line, sizeof(line), file) == line) {
4232                 size_t len = strlen(line);
4233                 int ret;
4234
4235                 /* Truncate long lines. */
4236                 if (len == (sizeof(line) - 1))
4237                         while (line[(len - 1)] != '\n') {
4238                                 ret = fgetc(file);
4239                                 if (ret == EOF)
4240                                         break;
4241                                 line[(len - 1)] = ret;
4242                         }
4243                 /* Extract information. */
4244                 if (sscanf(line,
4245                            "PCI_SLOT_NAME="
4246                            "%" SCNx16 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
4247                            &pci_addr->domain,
4248                            &pci_addr->bus,
4249                            &pci_addr->devid,
4250                            &pci_addr->function) == 4) {
4251                         ret = 0;
4252                         break;
4253                 }
4254         }
4255         fclose(file);
4256         return 0;
4257 }
4258
4259 /**
4260  * Derive MAC address from port GID.
4261  *
4262  * @param[out] mac
4263  *   MAC address output buffer.
4264  * @param port
4265  *   Physical port number.
4266  * @param[in] gid
4267  *   Port GID.
4268  */
4269 static void
4270 mac_from_gid(uint8_t (*mac)[ETHER_ADDR_LEN], uint32_t port, uint8_t *gid)
4271 {
4272         memcpy(&(*mac)[0], gid + 8, 3);
4273         memcpy(&(*mac)[3], gid + 13, 3);
4274         if (port == 1)
4275                 (*mac)[0] ^= 2;
4276 }
4277
4278 /* Support up to 32 adapters. */
4279 static struct {
4280         struct rte_pci_addr pci_addr; /* associated PCI address */
4281         uint32_t ports; /* physical ports bitfield. */
4282 } mlx4_dev[32];
4283
4284 /**
4285  * Get device index in mlx4_dev[] from PCI bus address.
4286  *
4287  * @param[in] pci_addr
4288  *   PCI bus address to look for.
4289  *
4290  * @return
4291  *   mlx4_dev[] index on success, -1 on failure.
4292  */
4293 static int
4294 mlx4_dev_idx(struct rte_pci_addr *pci_addr)
4295 {
4296         unsigned int i;
4297         int ret = -1;
4298
4299         assert(pci_addr != NULL);
4300         for (i = 0; (i != elemof(mlx4_dev)); ++i) {
4301                 if ((mlx4_dev[i].pci_addr.domain == pci_addr->domain) &&
4302                     (mlx4_dev[i].pci_addr.bus == pci_addr->bus) &&
4303                     (mlx4_dev[i].pci_addr.devid == pci_addr->devid) &&
4304                     (mlx4_dev[i].pci_addr.function == pci_addr->function))
4305                         return i;
4306                 if ((mlx4_dev[i].ports == 0) && (ret == -1))
4307                         ret = i;
4308         }
4309         return ret;
4310 }
4311
4312 /**
4313  * Retrieve integer value from environment variable.
4314  *
4315  * @param[in] name
4316  *   Environment variable name.
4317  *
4318  * @return
4319  *   Integer value, 0 if the variable is not set.
4320  */
4321 static int
4322 mlx4_getenv_int(const char *name)
4323 {
4324         const char *val = getenv(name);
4325
4326         if (val == NULL)
4327                 return 0;
4328         return atoi(val);
4329 }
4330
4331 static struct eth_driver mlx4_driver;
4332
4333 /**
4334  * DPDK callback to register a PCI device.
4335  *
4336  * This function creates an Ethernet device for each port of a given
4337  * PCI device.
4338  *
4339  * @param[in] pci_drv
4340  *   PCI driver structure (mlx4_driver).
4341  * @param[in] pci_dev
4342  *   PCI device information.
4343  *
4344  * @return
4345  *   0 on success, negative errno value on failure.
4346  */
4347 static int
4348 mlx4_pci_devinit(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
4349 {
4350         struct ibv_device **list;
4351         struct ibv_device *ibv_dev;
4352         int err = 0;
4353         struct ibv_context *attr_ctx = NULL;
4354         struct ibv_device_attr device_attr;
4355         unsigned int vf;
4356         int idx;
4357         int i;
4358
4359         (void)pci_drv;
4360         assert(pci_drv == &mlx4_driver.pci_drv);
4361         /* Get mlx4_dev[] index. */
4362         idx = mlx4_dev_idx(&pci_dev->addr);
4363         if (idx == -1) {
4364                 ERROR("this driver cannot support any more adapters");
4365                 return -ENOMEM;
4366         }
4367         DEBUG("using driver device index %d", idx);
4368
4369         /* Save PCI address. */
4370         mlx4_dev[idx].pci_addr = pci_dev->addr;
4371         list = ibv_get_device_list(&i);
4372         if (list == NULL) {
4373                 assert(errno);
4374                 if (errno == ENOSYS) {
4375                         WARN("cannot list devices, is ib_uverbs loaded?");
4376                         return 0;
4377                 }
4378                 return -errno;
4379         }
4380         assert(i >= 0);
4381         /*
4382          * For each listed device, check related sysfs entry against
4383          * the provided PCI ID.
4384          */
4385         while (i != 0) {
4386                 struct rte_pci_addr pci_addr;
4387
4388                 --i;
4389                 DEBUG("checking device \"%s\"", list[i]->name);
4390                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
4391                         continue;
4392                 if ((pci_dev->addr.domain != pci_addr.domain) ||
4393                     (pci_dev->addr.bus != pci_addr.bus) ||
4394                     (pci_dev->addr.devid != pci_addr.devid) ||
4395                     (pci_dev->addr.function != pci_addr.function))
4396                         continue;
4397                 vf = (pci_dev->id.device_id ==
4398                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
4399                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
4400                      list[i]->name, (vf ? "true" : "false"));
4401                 attr_ctx = ibv_open_device(list[i]);
4402                 err = errno;
4403                 break;
4404         }
4405         if (attr_ctx == NULL) {
4406                 ibv_free_device_list(list);
4407                 switch (err) {
4408                 case 0:
4409                         WARN("cannot access device, is mlx4_ib loaded?");
4410                         return 0;
4411                 case EINVAL:
4412                         WARN("cannot use device, are drivers up to date?");
4413                         return 0;
4414                 }
4415                 assert(err > 0);
4416                 return -err;
4417         }
4418         ibv_dev = list[i];
4419
4420         DEBUG("device opened");
4421         if (ibv_query_device(attr_ctx, &device_attr))
4422                 goto error;
4423         INFO("%u port(s) detected", device_attr.phys_port_cnt);
4424
4425         for (i = 0; i < device_attr.phys_port_cnt; i++) {
4426                 uint32_t port = i + 1; /* ports are indexed from one */
4427                 uint32_t test = (1 << i);
4428                 struct ibv_context *ctx = NULL;
4429                 struct ibv_port_attr port_attr;
4430                 struct ibv_pd *pd = NULL;
4431                 struct priv *priv = NULL;
4432                 struct rte_eth_dev *eth_dev;
4433 #if defined(INLINE_RECV) || defined(RSS_SUPPORT)
4434                 struct ibv_exp_device_attr exp_device_attr;
4435 #endif
4436                 struct ether_addr mac;
4437                 union ibv_gid temp_gid;
4438
4439 #ifdef RSS_SUPPORT
4440                 exp_device_attr.comp_mask =
4441                         (IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS |
4442                          IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ);
4443 #endif /* RSS_SUPPORT */
4444
4445                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
4446
4447                 ctx = ibv_open_device(ibv_dev);
4448                 if (ctx == NULL)
4449                         goto port_error;
4450
4451                 /* Check port status. */
4452                 err = ibv_query_port(ctx, port, &port_attr);
4453                 if (err) {
4454                         ERROR("port query failed: %s", strerror(err));
4455                         goto port_error;
4456                 }
4457                 if (port_attr.state != IBV_PORT_ACTIVE)
4458                         WARN("bad state for port %d: \"%s\" (%d)",
4459                              port, ibv_port_state_str(port_attr.state),
4460                              port_attr.state);
4461
4462                 /* Allocate protection domain. */
4463                 pd = ibv_alloc_pd(ctx);
4464                 if (pd == NULL) {
4465                         ERROR("PD allocation failure");
4466                         err = ENOMEM;
4467                         goto port_error;
4468                 }
4469
4470                 mlx4_dev[idx].ports |= test;
4471
4472                 /* from rte_ethdev.c */
4473                 priv = rte_zmalloc("ethdev private structure",
4474                                    sizeof(*priv),
4475                                    RTE_CACHE_LINE_SIZE);
4476                 if (priv == NULL) {
4477                         ERROR("priv allocation failure");
4478                         err = ENOMEM;
4479                         goto port_error;
4480                 }
4481
4482                 priv->ctx = ctx;
4483                 priv->device_attr = device_attr;
4484                 priv->port_attr = port_attr;
4485                 priv->port = port;
4486                 priv->pd = pd;
4487                 priv->mtu = ETHER_MTU;
4488 #ifdef RSS_SUPPORT
4489                 if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4490                         INFO("experimental ibv_exp_query_device");
4491                         goto port_error;
4492                 }
4493                 if ((exp_device_attr.exp_device_cap_flags &
4494                      IBV_EXP_DEVICE_QPG) &&
4495                     (exp_device_attr.exp_device_cap_flags &
4496                      IBV_EXP_DEVICE_UD_RSS) &&
4497                     (exp_device_attr.comp_mask &
4498                      IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ) &&
4499                     (exp_device_attr.max_rss_tbl_sz > 0)) {
4500                         priv->hw_qpg = 1;
4501                         priv->hw_rss = 1;
4502                         priv->max_rss_tbl_sz = exp_device_attr.max_rss_tbl_sz;
4503                 } else {
4504                         priv->hw_qpg = 0;
4505                         priv->hw_rss = 0;
4506                         priv->max_rss_tbl_sz = 0;
4507                 }
4508                 priv->hw_tss = !!(exp_device_attr.exp_device_cap_flags &
4509                                   IBV_EXP_DEVICE_UD_TSS);
4510                 DEBUG("device flags: %s%s%s",
4511                       (priv->hw_qpg ? "IBV_DEVICE_QPG " : ""),
4512                       (priv->hw_tss ? "IBV_DEVICE_TSS " : ""),
4513                       (priv->hw_rss ? "IBV_DEVICE_RSS " : ""));
4514                 if (priv->hw_rss)
4515                         DEBUG("maximum RSS indirection table size: %u",
4516                               exp_device_attr.max_rss_tbl_sz);
4517 #endif /* RSS_SUPPORT */
4518
4519 #ifdef INLINE_RECV
4520                 priv->inl_recv_size = mlx4_getenv_int("MLX4_INLINE_RECV_SIZE");
4521
4522                 if (priv->inl_recv_size) {
4523                         exp_device_attr.comp_mask =
4524                                 IBV_EXP_DEVICE_ATTR_INLINE_RECV_SZ;
4525                         if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4526                                 INFO("Couldn't query device for inline-receive"
4527                                      " capabilities.");
4528                                 priv->inl_recv_size = 0;
4529                         } else {
4530                                 if ((unsigned)exp_device_attr.inline_recv_sz <
4531                                     priv->inl_recv_size) {
4532                                         INFO("Max inline-receive (%d) <"
4533                                              " requested inline-receive (%u)",
4534                                              exp_device_attr.inline_recv_sz,
4535                                              priv->inl_recv_size);
4536                                         priv->inl_recv_size =
4537                                                 exp_device_attr.inline_recv_sz;
4538                                 }
4539                         }
4540                         INFO("Set inline receive size to %u",
4541                              priv->inl_recv_size);
4542                 }
4543 #endif /* INLINE_RECV */
4544
4545                 (void)mlx4_getenv_int;
4546                 priv->vf = vf;
4547                 if (ibv_query_gid(ctx, port, 0, &temp_gid)) {
4548                         ERROR("ibv_query_gid() failure");
4549                         goto port_error;
4550                 }
4551                 /* Configure the first MAC address by default. */
4552                 mac_from_gid(&mac.addr_bytes, port, temp_gid.raw);
4553                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
4554                      priv->port,
4555                      mac.addr_bytes[0], mac.addr_bytes[1],
4556                      mac.addr_bytes[2], mac.addr_bytes[3],
4557                      mac.addr_bytes[4], mac.addr_bytes[5]);
4558                 /* Register MAC and broadcast addresses. */
4559                 claim_zero(priv_mac_addr_add(priv, 0,
4560                                              (const uint8_t (*)[ETHER_ADDR_LEN])
4561                                              mac.addr_bytes));
4562                 claim_zero(priv_mac_addr_add(priv, 1,
4563                                              &(const uint8_t [ETHER_ADDR_LEN])
4564                                              { "\xff\xff\xff\xff\xff\xff" }));
4565 #ifndef NDEBUG
4566                 {
4567                         char ifname[IF_NAMESIZE];
4568
4569                         if (priv_get_ifname(priv, &ifname) == 0)
4570                                 DEBUG("port %u ifname is \"%s\"",
4571                                       priv->port, ifname);
4572                         else
4573                                 DEBUG("port %u ifname is unknown", priv->port);
4574                 }
4575 #endif
4576                 /* Get actual MTU if possible. */
4577                 priv_get_mtu(priv, &priv->mtu);
4578                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
4579
4580                 /* from rte_ethdev.c */
4581                 {
4582                         char name[RTE_ETH_NAME_MAX_LEN];
4583
4584                         snprintf(name, sizeof(name), "%s port %u",
4585                                  ibv_get_device_name(ibv_dev), port);
4586                         eth_dev = rte_eth_dev_allocate(name, RTE_ETH_DEV_PCI);
4587                 }
4588                 if (eth_dev == NULL) {
4589                         ERROR("can not allocate rte ethdev");
4590                         err = ENOMEM;
4591                         goto port_error;
4592                 }
4593
4594                 eth_dev->data->dev_private = priv;
4595                 eth_dev->pci_dev = pci_dev;
4596                 eth_dev->driver = &mlx4_driver;
4597                 eth_dev->data->rx_mbuf_alloc_failed = 0;
4598                 eth_dev->data->mtu = ETHER_MTU;
4599
4600                 priv->dev = eth_dev;
4601                 eth_dev->dev_ops = &mlx4_dev_ops;
4602                 eth_dev->data->mac_addrs = priv->mac;
4603
4604                 /* Bring Ethernet device up. */
4605                 DEBUG("forcing Ethernet interface up");
4606                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
4607                 continue;
4608
4609 port_error:
4610                 rte_free(priv);
4611                 if (pd)
4612                         claim_zero(ibv_dealloc_pd(pd));
4613                 if (ctx)
4614                         claim_zero(ibv_close_device(ctx));
4615                 break;
4616         }
4617
4618         /*
4619          * XXX if something went wrong in the loop above, there is a resource
4620          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
4621          * long as the dpdk does not provide a way to deallocate a ethdev and a
4622          * way to enumerate the registered ethdevs to free the previous ones.
4623          */
4624
4625         /* no port found, complain */
4626         if (!mlx4_dev[idx].ports) {
4627                 err = ENODEV;
4628                 goto error;
4629         }
4630
4631 error:
4632         if (attr_ctx)
4633                 claim_zero(ibv_close_device(attr_ctx));
4634         if (list)
4635                 ibv_free_device_list(list);
4636         assert(err >= 0);
4637         return -err;
4638 }
4639
4640 static const struct rte_pci_id mlx4_pci_id_map[] = {
4641         {
4642                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
4643                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3,
4644                 .subsystem_vendor_id = PCI_ANY_ID,
4645                 .subsystem_device_id = PCI_ANY_ID
4646         },
4647         {
4648                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
4649                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO,
4650                 .subsystem_vendor_id = PCI_ANY_ID,
4651                 .subsystem_device_id = PCI_ANY_ID
4652         },
4653         {
4654                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
4655                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3VF,
4656                 .subsystem_vendor_id = PCI_ANY_ID,
4657                 .subsystem_device_id = PCI_ANY_ID
4658         },
4659         {
4660                 .vendor_id = 0
4661         }
4662 };
4663
4664 static struct eth_driver mlx4_driver = {
4665         .pci_drv = {
4666                 .name = MLX4_DRIVER_NAME,
4667                 .id_table = mlx4_pci_id_map,
4668                 .devinit = mlx4_pci_devinit,
4669         },
4670         .dev_private_size = sizeof(struct priv)
4671 };
4672
4673 /**
4674  * Driver initialization routine.
4675  */
4676 static int
4677 rte_mlx4_pmd_init(const char *name, const char *args)
4678 {
4679         (void)name;
4680         (void)args;
4681         rte_eal_pci_register(&mlx4_driver.pci_drv);
4682         return 0;
4683 }
4684
4685 static struct rte_driver rte_mlx4_driver = {
4686         .type = PMD_PDEV,
4687         .name = MLX4_DRIVER_NAME,
4688         .init = rte_mlx4_pmd_init,
4689 };
4690
4691 PMD_REGISTER_DRIVER(rte_mlx4_driver)