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