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