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