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