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