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