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