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