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