mlx4: improve Rx performance with better prefetching
[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                 pkt_buf->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
2739
2740                 /* Return packet. */
2741                 *(pkts++) = pkt_buf;
2742                 ++pkts_ret;
2743 #ifdef MLX4_PMD_SOFT_COUNTERS
2744                 /* Increase bytes counter. */
2745                 rxq->stats.ibytes += pkt_buf_len;
2746 #endif
2747 repost:
2748                 if (++elts_head >= elts_n)
2749                         elts_head = 0;
2750                 continue;
2751         }
2752         if (unlikely(i == 0))
2753                 return 0;
2754         *next = NULL;
2755         /* Repost WRs. */
2756 #ifdef DEBUG_RECV
2757         DEBUG("%p: reposting %d WRs", (void *)rxq, i);
2758 #endif
2759         ret = ibv_post_recv(rxq->qp, head.next, &bad_wr);
2760         if (unlikely(ret)) {
2761                 /* Inability to repost WRs is fatal. */
2762                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
2763                       (void *)rxq->priv,
2764                       (void *)bad_wr,
2765                       strerror(ret));
2766                 abort();
2767         }
2768         rxq->elts_head = elts_head;
2769 #ifdef MLX4_PMD_SOFT_COUNTERS
2770         /* Increase packets counter. */
2771         rxq->stats.ipackets += pkts_ret;
2772 #endif
2773         return pkts_ret;
2774 }
2775
2776 /**
2777  * DPDK callback for RX.
2778  *
2779  * The following function is the same as mlx4_rx_burst_sp(), except it doesn't
2780  * manage scattered packets. Improves performance when MRU is lower than the
2781  * size of the first segment.
2782  *
2783  * @param dpdk_rxq
2784  *   Generic pointer to RX queue structure.
2785  * @param[out] pkts
2786  *   Array to store received packets.
2787  * @param pkts_n
2788  *   Maximum number of packets in array.
2789  *
2790  * @return
2791  *   Number of packets successfully received (<= pkts_n).
2792  */
2793 static uint16_t
2794 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2795 {
2796         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2797         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
2798         const unsigned int elts_n = rxq->elts_n;
2799         unsigned int elts_head = rxq->elts_head;
2800         struct ibv_sge sges[pkts_n];
2801         unsigned int i;
2802         unsigned int pkts_ret = 0;
2803         int ret;
2804
2805         if (unlikely(rxq->sp))
2806                 return mlx4_rx_burst_sp(dpdk_rxq, pkts, pkts_n);
2807         for (i = 0; (i != pkts_n); ++i) {
2808                 struct rxq_elt *elt = &(*elts)[elts_head];
2809                 struct ibv_recv_wr *wr = &elt->wr;
2810                 uint64_t wr_id = wr->wr_id;
2811                 unsigned int len;
2812                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
2813                         WR_ID(wr_id).offset);
2814                 struct rte_mbuf *rep;
2815                 uint32_t flags;
2816
2817                 /* Sanity checks. */
2818                 assert(WR_ID(wr_id).id < rxq->elts_n);
2819                 assert(wr->sg_list == &elt->sge);
2820                 assert(wr->num_sge == 1);
2821                 assert(elts_head < rxq->elts_n);
2822                 assert(rxq->elts_head < rxq->elts_n);
2823                 /*
2824                  * Fetch initial bytes of packet descriptor into a
2825                  * cacheline while allocating rep.
2826                  */
2827                 rte_prefetch0(seg);
2828                 rte_prefetch0(&seg->cacheline1);
2829                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
2830                                                     &flags);
2831                 if (unlikely(ret < 0)) {
2832                         struct ibv_wc wc;
2833                         int wcs_n;
2834
2835                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
2836                               (void *)rxq, ret);
2837                         /* ibv_poll_cq() must be used in case of failure. */
2838                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
2839                         if (unlikely(wcs_n == 0))
2840                                 break;
2841                         if (unlikely(wcs_n < 0)) {
2842                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
2843                                       (void *)rxq, wcs_n);
2844                                 break;
2845                         }
2846                         assert(wcs_n == 1);
2847                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
2848                                 /* Whatever, just repost the offending WR. */
2849                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
2850                                       " completion status (%d): %s",
2851                                       (void *)rxq, wc.wr_id, wc.status,
2852                                       ibv_wc_status_str(wc.status));
2853 #ifdef MLX4_PMD_SOFT_COUNTERS
2854                                 /* Increment dropped packets counter. */
2855                                 ++rxq->stats.idropped;
2856 #endif
2857                                 /* Add SGE to array for repost. */
2858                                 sges[i] = elt->sge;
2859                                 goto repost;
2860                         }
2861                         ret = wc.byte_len;
2862                 }
2863                 if (ret == 0)
2864                         break;
2865                 len = ret;
2866                 rep = __rte_mbuf_raw_alloc(rxq->mp);
2867                 if (unlikely(rep == NULL)) {
2868                         /*
2869                          * Unable to allocate a replacement mbuf,
2870                          * repost WR.
2871                          */
2872                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
2873                               " can't allocate a new mbuf",
2874                               (void *)rxq, WR_ID(wr_id).id);
2875                         /* Increase out of memory counters. */
2876                         ++rxq->stats.rx_nombuf;
2877                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2878                         goto repost;
2879                 }
2880
2881                 /* Reconfigure sge to use rep instead of seg. */
2882                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
2883                 assert(elt->sge.lkey == rxq->mr->lkey);
2884                 WR_ID(wr->wr_id).offset =
2885                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
2886                          (uintptr_t)rep);
2887                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
2888
2889                 /* Add SGE to array for repost. */
2890                 sges[i] = elt->sge;
2891
2892                 /* Update seg information. */
2893                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
2894                 NB_SEGS(seg) = 1;
2895                 PORT(seg) = rxq->port_id;
2896                 NEXT(seg) = NULL;
2897                 PKT_LEN(seg) = len;
2898                 DATA_LEN(seg) = len;
2899                 seg->packet_type = rxq_cq_to_pkt_type(flags);
2900                 seg->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
2901
2902                 /* Return packet. */
2903                 *(pkts++) = seg;
2904                 ++pkts_ret;
2905 #ifdef MLX4_PMD_SOFT_COUNTERS
2906                 /* Increase bytes counter. */
2907                 rxq->stats.ibytes += len;
2908 #endif
2909 repost:
2910                 if (++elts_head >= elts_n)
2911                         elts_head = 0;
2912                 continue;
2913         }
2914         if (unlikely(i == 0))
2915                 return 0;
2916         /* Repost WRs. */
2917 #ifdef DEBUG_RECV
2918         DEBUG("%p: reposting %u WRs", (void *)rxq, i);
2919 #endif
2920         ret = rxq->if_qp->recv_burst(rxq->qp, sges, i);
2921         if (unlikely(ret)) {
2922                 /* Inability to repost WRs is fatal. */
2923                 DEBUG("%p: recv_burst(): failed (ret=%d)",
2924                       (void *)rxq->priv,
2925                       ret);
2926                 abort();
2927         }
2928         rxq->elts_head = elts_head;
2929 #ifdef MLX4_PMD_SOFT_COUNTERS
2930         /* Increase packets counter. */
2931         rxq->stats.ipackets += pkts_ret;
2932 #endif
2933         return pkts_ret;
2934 }
2935
2936 /**
2937  * Allocate a Queue Pair.
2938  * Optionally setup inline receive if supported.
2939  *
2940  * @param priv
2941  *   Pointer to private structure.
2942  * @param cq
2943  *   Completion queue to associate with QP.
2944  * @param desc
2945  *   Number of descriptors in QP (hint only).
2946  *
2947  * @return
2948  *   QP pointer or NULL in case of error.
2949  */
2950 static struct ibv_qp *
2951 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
2952              struct ibv_exp_res_domain *rd)
2953 {
2954         struct ibv_exp_qp_init_attr attr = {
2955                 /* CQ to be associated with the send queue. */
2956                 .send_cq = cq,
2957                 /* CQ to be associated with the receive queue. */
2958                 .recv_cq = cq,
2959                 .cap = {
2960                         /* Max number of outstanding WRs. */
2961                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2962                                         priv->device_attr.max_qp_wr :
2963                                         desc),
2964                         /* Max number of scatter/gather elements in a WR. */
2965                         .max_recv_sge = ((priv->device_attr.max_sge <
2966                                           MLX4_PMD_SGE_WR_N) ?
2967                                          priv->device_attr.max_sge :
2968                                          MLX4_PMD_SGE_WR_N),
2969                 },
2970                 .qp_type = IBV_QPT_RAW_PACKET,
2971                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
2972                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
2973                 .pd = priv->pd,
2974                 .res_domain = rd,
2975         };
2976
2977 #ifdef INLINE_RECV
2978         attr.max_inl_recv = priv->inl_recv_size;
2979         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
2980 #endif
2981         return ibv_exp_create_qp(priv->ctx, &attr);
2982 }
2983
2984 #ifdef RSS_SUPPORT
2985
2986 /**
2987  * Allocate a RSS Queue Pair.
2988  * Optionally setup inline receive if supported.
2989  *
2990  * @param priv
2991  *   Pointer to private structure.
2992  * @param cq
2993  *   Completion queue to associate with QP.
2994  * @param desc
2995  *   Number of descriptors in QP (hint only).
2996  * @param parent
2997  *   If nonzero, create a parent QP, otherwise a child.
2998  *
2999  * @return
3000  *   QP pointer or NULL in case of error.
3001  */
3002 static struct ibv_qp *
3003 rxq_setup_qp_rss(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
3004                  int parent, struct ibv_exp_res_domain *rd)
3005 {
3006         struct ibv_exp_qp_init_attr attr = {
3007                 /* CQ to be associated with the send queue. */
3008                 .send_cq = cq,
3009                 /* CQ to be associated with the receive queue. */
3010                 .recv_cq = cq,
3011                 .cap = {
3012                         /* Max number of outstanding WRs. */
3013                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
3014                                         priv->device_attr.max_qp_wr :
3015                                         desc),
3016                         /* Max number of scatter/gather elements in a WR. */
3017                         .max_recv_sge = ((priv->device_attr.max_sge <
3018                                           MLX4_PMD_SGE_WR_N) ?
3019                                          priv->device_attr.max_sge :
3020                                          MLX4_PMD_SGE_WR_N),
3021                 },
3022                 .qp_type = IBV_QPT_RAW_PACKET,
3023                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
3024                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN |
3025                               IBV_EXP_QP_INIT_ATTR_QPG),
3026                 .pd = priv->pd,
3027                 .res_domain = rd,
3028         };
3029
3030 #ifdef INLINE_RECV
3031         attr.max_inl_recv = priv->inl_recv_size,
3032         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3033 #endif
3034         if (parent) {
3035                 attr.qpg.qpg_type = IBV_EXP_QPG_PARENT;
3036                 /* TSS isn't necessary. */
3037                 attr.qpg.parent_attrib.tss_child_count = 0;
3038                 attr.qpg.parent_attrib.rss_child_count = priv->rxqs_n;
3039                 DEBUG("initializing parent RSS queue");
3040         } else {
3041                 attr.qpg.qpg_type = IBV_EXP_QPG_CHILD_RX;
3042                 attr.qpg.qpg_parent = priv->rxq_parent.qp;
3043                 DEBUG("initializing child RSS queue");
3044         }
3045         return ibv_exp_create_qp(priv->ctx, &attr);
3046 }
3047
3048 #endif /* RSS_SUPPORT */
3049
3050 /**
3051  * Reconfigure a RX queue with new parameters.
3052  *
3053  * rxq_rehash() does not allocate mbufs, which, if not done from the right
3054  * thread (such as a control thread), may corrupt the pool.
3055  * In case of failure, the queue is left untouched.
3056  *
3057  * @param dev
3058  *   Pointer to Ethernet device structure.
3059  * @param rxq
3060  *   RX queue pointer.
3061  *
3062  * @return
3063  *   0 on success, errno value on failure.
3064  */
3065 static int
3066 rxq_rehash(struct rte_eth_dev *dev, struct rxq *rxq)
3067 {
3068         struct priv *priv = rxq->priv;
3069         struct rxq tmpl = *rxq;
3070         unsigned int mbuf_n;
3071         unsigned int desc_n;
3072         struct rte_mbuf **pool;
3073         unsigned int i, k;
3074         struct ibv_exp_qp_attr mod;
3075         struct ibv_recv_wr *bad_wr;
3076         int err;
3077         int parent = (rxq == &priv->rxq_parent);
3078
3079         if (parent) {
3080                 ERROR("%p: cannot rehash parent queue %p",
3081                       (void *)dev, (void *)rxq);
3082                 return EINVAL;
3083         }
3084         DEBUG("%p: rehashing queue %p", (void *)dev, (void *)rxq);
3085         /* Number of descriptors and mbufs currently allocated. */
3086         desc_n = (tmpl.elts_n * (tmpl.sp ? MLX4_PMD_SGE_WR_N : 1));
3087         mbuf_n = desc_n;
3088         /* Toggle RX checksum offload if hardware supports it. */
3089         if (priv->hw_csum) {
3090                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3091                 rxq->csum = tmpl.csum;
3092         }
3093         if (priv->hw_csum_l2tun) {
3094                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3095                 rxq->csum_l2tun = tmpl.csum_l2tun;
3096         }
3097         /* Enable scattered packets support for this queue if necessary. */
3098         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3099             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3100              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
3101                 tmpl.sp = 1;
3102                 desc_n /= MLX4_PMD_SGE_WR_N;
3103         } else
3104                 tmpl.sp = 0;
3105         DEBUG("%p: %s scattered packets support (%u WRs)",
3106               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc_n);
3107         /* If scatter mode is the same as before, nothing to do. */
3108         if (tmpl.sp == rxq->sp) {
3109                 DEBUG("%p: nothing to do", (void *)dev);
3110                 return 0;
3111         }
3112         /* Remove attached flows if RSS is disabled (no parent queue). */
3113         if (!priv->rss) {
3114                 rxq_allmulticast_disable(&tmpl);
3115                 rxq_promiscuous_disable(&tmpl);
3116                 rxq_mac_addrs_del(&tmpl);
3117                 /* Update original queue in case of failure. */
3118                 rxq->allmulti_flow = tmpl.allmulti_flow;
3119                 rxq->promisc_flow = tmpl.promisc_flow;
3120                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3121                        sizeof(rxq->mac_configured));
3122                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3123         }
3124         /* From now on, any failure will render the queue unusable.
3125          * Reinitialize QP. */
3126         mod = (struct ibv_exp_qp_attr){ .qp_state = IBV_QPS_RESET };
3127         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3128         if (err) {
3129                 ERROR("%p: cannot reset QP: %s", (void *)dev, strerror(err));
3130                 assert(err > 0);
3131                 return err;
3132         }
3133         err = ibv_resize_cq(tmpl.cq, desc_n);
3134         if (err) {
3135                 ERROR("%p: cannot resize CQ: %s", (void *)dev, strerror(err));
3136                 assert(err > 0);
3137                 return err;
3138         }
3139         mod = (struct ibv_exp_qp_attr){
3140                 /* Move the QP to this state. */
3141                 .qp_state = IBV_QPS_INIT,
3142                 /* Primary port number. */
3143                 .port_num = priv->port
3144         };
3145         err = ibv_exp_modify_qp(tmpl.qp, &mod,
3146                                 (IBV_EXP_QP_STATE |
3147 #ifdef RSS_SUPPORT
3148                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3149 #endif /* RSS_SUPPORT */
3150                                  IBV_EXP_QP_PORT));
3151         if (err) {
3152                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3153                       (void *)dev, strerror(err));
3154                 assert(err > 0);
3155                 return err;
3156         };
3157         /* Reconfigure flows. Do not care for errors. */
3158         if (!priv->rss) {
3159                 rxq_mac_addrs_add(&tmpl);
3160                 if (priv->promisc)
3161                         rxq_promiscuous_enable(&tmpl);
3162                 if (priv->allmulti)
3163                         rxq_allmulticast_enable(&tmpl);
3164                 /* Update original queue in case of failure. */
3165                 rxq->allmulti_flow = tmpl.allmulti_flow;
3166                 rxq->promisc_flow = tmpl.promisc_flow;
3167                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3168                        sizeof(rxq->mac_configured));
3169                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3170         }
3171         /* Allocate pool. */
3172         pool = rte_malloc(__func__, (mbuf_n * sizeof(*pool)), 0);
3173         if (pool == NULL) {
3174                 ERROR("%p: cannot allocate memory", (void *)dev);
3175                 return ENOBUFS;
3176         }
3177         /* Snatch mbufs from original queue. */
3178         k = 0;
3179         if (rxq->sp) {
3180                 struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
3181
3182                 for (i = 0; (i != elemof(*elts)); ++i) {
3183                         struct rxq_elt_sp *elt = &(*elts)[i];
3184                         unsigned int j;
3185
3186                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
3187                                 assert(elt->bufs[j] != NULL);
3188                                 pool[k++] = elt->bufs[j];
3189                         }
3190                 }
3191         } else {
3192                 struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
3193
3194                 for (i = 0; (i != elemof(*elts)); ++i) {
3195                         struct rxq_elt *elt = &(*elts)[i];
3196                         struct rte_mbuf *buf = (void *)
3197                                 ((uintptr_t)elt->sge.addr -
3198                                  WR_ID(elt->wr.wr_id).offset);
3199
3200                         assert(WR_ID(elt->wr.wr_id).id == i);
3201                         pool[k++] = buf;
3202                 }
3203         }
3204         assert(k == mbuf_n);
3205         tmpl.elts_n = 0;
3206         tmpl.elts.sp = NULL;
3207         assert((void *)&tmpl.elts.sp == (void *)&tmpl.elts.no_sp);
3208         err = ((tmpl.sp) ?
3209                rxq_alloc_elts_sp(&tmpl, desc_n, pool) :
3210                rxq_alloc_elts(&tmpl, desc_n, pool));
3211         if (err) {
3212                 ERROR("%p: cannot reallocate WRs, aborting", (void *)dev);
3213                 rte_free(pool);
3214                 assert(err > 0);
3215                 return err;
3216         }
3217         assert(tmpl.elts_n == desc_n);
3218         assert(tmpl.elts.sp != NULL);
3219         rte_free(pool);
3220         /* Clean up original data. */
3221         rxq->elts_n = 0;
3222         rte_free(rxq->elts.sp);
3223         rxq->elts.sp = NULL;
3224         /* Post WRs. */
3225         err = ibv_post_recv(tmpl.qp,
3226                             (tmpl.sp ?
3227                              &(*tmpl.elts.sp)[0].wr :
3228                              &(*tmpl.elts.no_sp)[0].wr),
3229                             &bad_wr);
3230         if (err) {
3231                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3232                       (void *)dev,
3233                       (void *)bad_wr,
3234                       strerror(err));
3235                 goto skip_rtr;
3236         }
3237         mod = (struct ibv_exp_qp_attr){
3238                 .qp_state = IBV_QPS_RTR
3239         };
3240         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3241         if (err)
3242                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3243                       (void *)dev, strerror(err));
3244 skip_rtr:
3245         *rxq = tmpl;
3246         assert(err >= 0);
3247         return err;
3248 }
3249
3250 /**
3251  * Configure a RX queue.
3252  *
3253  * @param dev
3254  *   Pointer to Ethernet device structure.
3255  * @param rxq
3256  *   Pointer to RX queue structure.
3257  * @param desc
3258  *   Number of descriptors to configure in queue.
3259  * @param socket
3260  *   NUMA socket on which memory must be allocated.
3261  * @param[in] conf
3262  *   Thresholds parameters.
3263  * @param mp
3264  *   Memory pool for buffer allocations.
3265  *
3266  * @return
3267  *   0 on success, errno value on failure.
3268  */
3269 static int
3270 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
3271           unsigned int socket, const struct rte_eth_rxconf *conf,
3272           struct rte_mempool *mp)
3273 {
3274         struct priv *priv = dev->data->dev_private;
3275         struct rxq tmpl = {
3276                 .priv = priv,
3277                 .mp = mp,
3278                 .socket = socket
3279         };
3280         struct ibv_exp_qp_attr mod;
3281         union {
3282                 struct ibv_exp_query_intf_params params;
3283                 struct ibv_exp_cq_init_attr cq;
3284                 struct ibv_exp_res_domain_init_attr rd;
3285         } attr;
3286         enum ibv_exp_query_intf_status status;
3287         struct ibv_recv_wr *bad_wr;
3288         struct rte_mbuf *buf;
3289         int ret = 0;
3290         int parent = (rxq == &priv->rxq_parent);
3291
3292         (void)conf; /* Thresholds configuration (ignored). */
3293         /*
3294          * If this is a parent queue, hardware must support RSS and
3295          * RSS must be enabled.
3296          */
3297         assert((!parent) || ((priv->hw_rss) && (priv->rss)));
3298         if (parent) {
3299                 /* Even if unused, ibv_create_cq() requires at least one
3300                  * descriptor. */
3301                 desc = 1;
3302                 goto skip_mr;
3303         }
3304         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
3305                 ERROR("%p: invalid number of RX descriptors (must be a"
3306                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
3307                 return EINVAL;
3308         }
3309         /* Get mbuf length. */
3310         buf = rte_pktmbuf_alloc(mp);
3311         if (buf == NULL) {
3312                 ERROR("%p: unable to allocate mbuf", (void *)dev);
3313                 return ENOMEM;
3314         }
3315         tmpl.mb_len = buf->buf_len;
3316         assert((rte_pktmbuf_headroom(buf) +
3317                 rte_pktmbuf_tailroom(buf)) == tmpl.mb_len);
3318         assert(rte_pktmbuf_headroom(buf) == RTE_PKTMBUF_HEADROOM);
3319         rte_pktmbuf_free(buf);
3320         /* Toggle RX checksum offload if hardware supports it. */
3321         if (priv->hw_csum)
3322                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3323         if (priv->hw_csum_l2tun)
3324                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3325         /* Enable scattered packets support for this queue if necessary. */
3326         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3327             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3328              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
3329                 tmpl.sp = 1;
3330                 desc /= MLX4_PMD_SGE_WR_N;
3331         }
3332         DEBUG("%p: %s scattered packets support (%u WRs)",
3333               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
3334         /* Use the entire RX mempool as the memory region. */
3335         tmpl.mr = ibv_reg_mr(priv->pd,
3336                              (void *)mp->elt_va_start,
3337                              (mp->elt_va_end - mp->elt_va_start),
3338                              (IBV_ACCESS_LOCAL_WRITE |
3339                               IBV_ACCESS_REMOTE_WRITE));
3340         if (tmpl.mr == NULL) {
3341                 ret = EINVAL;
3342                 ERROR("%p: MR creation failure: %s",
3343                       (void *)dev, strerror(ret));
3344                 goto error;
3345         }
3346 skip_mr:
3347         attr.rd = (struct ibv_exp_res_domain_init_attr){
3348                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
3349                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
3350                 .thread_model = IBV_EXP_THREAD_SINGLE,
3351                 .msg_model = IBV_EXP_MSG_HIGH_BW,
3352         };
3353         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
3354         if (tmpl.rd == NULL) {
3355                 ret = ENOMEM;
3356                 ERROR("%p: RD creation failure: %s",
3357                       (void *)dev, strerror(ret));
3358                 goto error;
3359         }
3360         attr.cq = (struct ibv_exp_cq_init_attr){
3361                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
3362                 .res_domain = tmpl.rd,
3363         };
3364         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
3365         if (tmpl.cq == NULL) {
3366                 ret = ENOMEM;
3367                 ERROR("%p: CQ creation failure: %s",
3368                       (void *)dev, strerror(ret));
3369                 goto error;
3370         }
3371         DEBUG("priv->device_attr.max_qp_wr is %d",
3372               priv->device_attr.max_qp_wr);
3373         DEBUG("priv->device_attr.max_sge is %d",
3374               priv->device_attr.max_sge);
3375 #ifdef RSS_SUPPORT
3376         if (priv->rss)
3377                 tmpl.qp = rxq_setup_qp_rss(priv, tmpl.cq, desc, parent,
3378                                            tmpl.rd);
3379         else
3380 #endif /* RSS_SUPPORT */
3381                 tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc, tmpl.rd);
3382         if (tmpl.qp == NULL) {
3383                 ret = (errno ? errno : EINVAL);
3384                 ERROR("%p: QP creation failure: %s",
3385                       (void *)dev, strerror(ret));
3386                 goto error;
3387         }
3388         mod = (struct ibv_exp_qp_attr){
3389                 /* Move the QP to this state. */
3390                 .qp_state = IBV_QPS_INIT,
3391                 /* Primary port number. */
3392                 .port_num = priv->port
3393         };
3394         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
3395                                 (IBV_EXP_QP_STATE |
3396 #ifdef RSS_SUPPORT
3397                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3398 #endif /* RSS_SUPPORT */
3399                                  IBV_EXP_QP_PORT));
3400         if (ret) {
3401                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3402                       (void *)dev, strerror(ret));
3403                 goto error;
3404         }
3405         if ((parent) || (!priv->rss))  {
3406                 /* Configure MAC and broadcast addresses. */
3407                 ret = rxq_mac_addrs_add(&tmpl);
3408                 if (ret) {
3409                         ERROR("%p: QP flow attachment failed: %s",
3410                               (void *)dev, strerror(ret));
3411                         goto error;
3412                 }
3413         }
3414         /* Allocate descriptors for RX queues, except for the RSS parent. */
3415         if (parent)
3416                 goto skip_alloc;
3417         if (tmpl.sp)
3418                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
3419         else
3420                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
3421         if (ret) {
3422                 ERROR("%p: RXQ allocation failed: %s",
3423                       (void *)dev, strerror(ret));
3424                 goto error;
3425         }
3426         ret = ibv_post_recv(tmpl.qp,
3427                             (tmpl.sp ?
3428                              &(*tmpl.elts.sp)[0].wr :
3429                              &(*tmpl.elts.no_sp)[0].wr),
3430                             &bad_wr);
3431         if (ret) {
3432                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3433                       (void *)dev,
3434                       (void *)bad_wr,
3435                       strerror(ret));
3436                 goto error;
3437         }
3438 skip_alloc:
3439         mod = (struct ibv_exp_qp_attr){
3440                 .qp_state = IBV_QPS_RTR
3441         };
3442         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3443         if (ret) {
3444                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3445                       (void *)dev, strerror(ret));
3446                 goto error;
3447         }
3448         /* Save port ID. */
3449         tmpl.port_id = dev->data->port_id;
3450         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
3451         attr.params = (struct ibv_exp_query_intf_params){
3452                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3453                 .intf = IBV_EXP_INTF_CQ,
3454                 .obj = tmpl.cq,
3455         };
3456         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3457         if (tmpl.if_cq == NULL) {
3458                 ERROR("%p: CQ interface family query failed with status %d",
3459                       (void *)dev, status);
3460                 goto error;
3461         }
3462         attr.params = (struct ibv_exp_query_intf_params){
3463                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3464                 .intf = IBV_EXP_INTF_QP_BURST,
3465                 .obj = tmpl.qp,
3466         };
3467         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3468         if (tmpl.if_qp == NULL) {
3469                 ERROR("%p: QP interface family query failed with status %d",
3470                       (void *)dev, status);
3471                 goto error;
3472         }
3473         /* Clean up rxq in case we're reinitializing it. */
3474         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
3475         rxq_cleanup(rxq);
3476         *rxq = tmpl;
3477         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
3478         assert(ret == 0);
3479         return 0;
3480 error:
3481         rxq_cleanup(&tmpl);
3482         assert(ret > 0);
3483         return ret;
3484 }
3485
3486 /**
3487  * DPDK callback to configure a RX queue.
3488  *
3489  * @param dev
3490  *   Pointer to Ethernet device structure.
3491  * @param idx
3492  *   RX queue index.
3493  * @param desc
3494  *   Number of descriptors to configure in queue.
3495  * @param socket
3496  *   NUMA socket on which memory must be allocated.
3497  * @param[in] conf
3498  *   Thresholds parameters.
3499  * @param mp
3500  *   Memory pool for buffer allocations.
3501  *
3502  * @return
3503  *   0 on success, negative errno value on failure.
3504  */
3505 static int
3506 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
3507                     unsigned int socket, const struct rte_eth_rxconf *conf,
3508                     struct rte_mempool *mp)
3509 {
3510         struct priv *priv = dev->data->dev_private;
3511         struct rxq *rxq = (*priv->rxqs)[idx];
3512         int ret;
3513
3514         priv_lock(priv);
3515         DEBUG("%p: configuring queue %u for %u descriptors",
3516               (void *)dev, idx, desc);
3517         if (idx >= priv->rxqs_n) {
3518                 ERROR("%p: queue index out of range (%u >= %u)",
3519                       (void *)dev, idx, priv->rxqs_n);
3520                 priv_unlock(priv);
3521                 return -EOVERFLOW;
3522         }
3523         if (rxq != NULL) {
3524                 DEBUG("%p: reusing already allocated queue index %u (%p)",
3525                       (void *)dev, idx, (void *)rxq);
3526                 if (priv->started) {
3527                         priv_unlock(priv);
3528                         return -EEXIST;
3529                 }
3530                 (*priv->rxqs)[idx] = NULL;
3531                 rxq_cleanup(rxq);
3532         } else {
3533                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
3534                 if (rxq == NULL) {
3535                         ERROR("%p: unable to allocate queue index %u",
3536                               (void *)dev, idx);
3537                         priv_unlock(priv);
3538                         return -ENOMEM;
3539                 }
3540         }
3541         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
3542         if (ret)
3543                 rte_free(rxq);
3544         else {
3545                 rxq->stats.idx = idx;
3546                 DEBUG("%p: adding RX queue %p to list",
3547                       (void *)dev, (void *)rxq);
3548                 (*priv->rxqs)[idx] = rxq;
3549                 /* Update receive callback. */
3550                 if (rxq->sp)
3551                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3552                 else
3553                         dev->rx_pkt_burst = mlx4_rx_burst;
3554         }
3555         priv_unlock(priv);
3556         return -ret;
3557 }
3558
3559 /**
3560  * DPDK callback to release a RX queue.
3561  *
3562  * @param dpdk_rxq
3563  *   Generic RX queue pointer.
3564  */
3565 static void
3566 mlx4_rx_queue_release(void *dpdk_rxq)
3567 {
3568         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3569         struct priv *priv;
3570         unsigned int i;
3571
3572         if (rxq == NULL)
3573                 return;
3574         priv = rxq->priv;
3575         priv_lock(priv);
3576         assert(rxq != &priv->rxq_parent);
3577         for (i = 0; (i != priv->rxqs_n); ++i)
3578                 if ((*priv->rxqs)[i] == rxq) {
3579                         DEBUG("%p: removing RX queue %p from list",
3580                               (void *)priv->dev, (void *)rxq);
3581                         (*priv->rxqs)[i] = NULL;
3582                         break;
3583                 }
3584         rxq_cleanup(rxq);
3585         rte_free(rxq);
3586         priv_unlock(priv);
3587 }
3588
3589 /**
3590  * DPDK callback to start the device.
3591  *
3592  * Simulate device start by attaching all configured flows.
3593  *
3594  * @param dev
3595  *   Pointer to Ethernet device structure.
3596  *
3597  * @return
3598  *   0 on success, negative errno value on failure.
3599  */
3600 static int
3601 mlx4_dev_start(struct rte_eth_dev *dev)
3602 {
3603         struct priv *priv = dev->data->dev_private;
3604         unsigned int i = 0;
3605         unsigned int r;
3606         struct rxq *rxq;
3607
3608         priv_lock(priv);
3609         if (priv->started) {
3610                 priv_unlock(priv);
3611                 return 0;
3612         }
3613         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
3614         priv->started = 1;
3615         if (priv->rss) {
3616                 rxq = &priv->rxq_parent;
3617                 r = 1;
3618         } else {
3619                 rxq = (*priv->rxqs)[0];
3620                 r = priv->rxqs_n;
3621         }
3622         /* Iterate only once when RSS is enabled. */
3623         do {
3624                 int ret;
3625
3626                 /* Ignore nonexistent RX queues. */
3627                 if (rxq == NULL)
3628                         continue;
3629                 ret = rxq_mac_addrs_add(rxq);
3630                 if (!ret && priv->promisc)
3631                         ret = rxq_promiscuous_enable(rxq);
3632                 if (!ret && priv->allmulti)
3633                         ret = rxq_allmulticast_enable(rxq);
3634                 if (!ret)
3635                         continue;
3636                 WARN("%p: QP flow attachment failed: %s",
3637                      (void *)dev, strerror(ret));
3638                 /* Rollback. */
3639                 while (i != 0) {
3640                         rxq = (*priv->rxqs)[--i];
3641                         if (rxq != NULL) {
3642                                 rxq_allmulticast_disable(rxq);
3643                                 rxq_promiscuous_disable(rxq);
3644                                 rxq_mac_addrs_del(rxq);
3645                         }
3646                 }
3647                 priv->started = 0;
3648                 return -ret;
3649         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3650         priv_unlock(priv);
3651         return 0;
3652 }
3653
3654 /**
3655  * DPDK callback to stop the device.
3656  *
3657  * Simulate device stop by detaching all configured flows.
3658  *
3659  * @param dev
3660  *   Pointer to Ethernet device structure.
3661  */
3662 static void
3663 mlx4_dev_stop(struct rte_eth_dev *dev)
3664 {
3665         struct priv *priv = dev->data->dev_private;
3666         unsigned int i = 0;
3667         unsigned int r;
3668         struct rxq *rxq;
3669
3670         priv_lock(priv);
3671         if (!priv->started) {
3672                 priv_unlock(priv);
3673                 return;
3674         }
3675         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
3676         priv->started = 0;
3677         if (priv->rss) {
3678                 rxq = &priv->rxq_parent;
3679                 r = 1;
3680         } else {
3681                 rxq = (*priv->rxqs)[0];
3682                 r = priv->rxqs_n;
3683         }
3684         /* Iterate only once when RSS is enabled. */
3685         do {
3686                 /* Ignore nonexistent RX queues. */
3687                 if (rxq == NULL)
3688                         continue;
3689                 rxq_allmulticast_disable(rxq);
3690                 rxq_promiscuous_disable(rxq);
3691                 rxq_mac_addrs_del(rxq);
3692         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3693         priv_unlock(priv);
3694 }
3695
3696 /**
3697  * Dummy DPDK callback for TX.
3698  *
3699  * This function is used to temporarily replace the real callback during
3700  * unsafe control operations on the queue, or in case of error.
3701  *
3702  * @param dpdk_txq
3703  *   Generic pointer to TX queue structure.
3704  * @param[in] pkts
3705  *   Packets to transmit.
3706  * @param pkts_n
3707  *   Number of packets in array.
3708  *
3709  * @return
3710  *   Number of packets successfully transmitted (<= pkts_n).
3711  */
3712 static uint16_t
3713 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
3714 {
3715         (void)dpdk_txq;
3716         (void)pkts;
3717         (void)pkts_n;
3718         return 0;
3719 }
3720
3721 /**
3722  * Dummy DPDK callback for RX.
3723  *
3724  * This function is used to temporarily replace the real callback during
3725  * unsafe control operations on the queue, or in case of error.
3726  *
3727  * @param dpdk_rxq
3728  *   Generic pointer to RX queue structure.
3729  * @param[out] pkts
3730  *   Array to store received packets.
3731  * @param pkts_n
3732  *   Maximum number of packets in array.
3733  *
3734  * @return
3735  *   Number of packets successfully received (<= pkts_n).
3736  */
3737 static uint16_t
3738 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
3739 {
3740         (void)dpdk_rxq;
3741         (void)pkts;
3742         (void)pkts_n;
3743         return 0;
3744 }
3745
3746 /**
3747  * DPDK callback to close the device.
3748  *
3749  * Destroy all queues and objects, free memory.
3750  *
3751  * @param dev
3752  *   Pointer to Ethernet device structure.
3753  */
3754 static void
3755 mlx4_dev_close(struct rte_eth_dev *dev)
3756 {
3757         struct priv *priv = dev->data->dev_private;
3758         void *tmp;
3759         unsigned int i;
3760
3761         priv_lock(priv);
3762         DEBUG("%p: closing device \"%s\"",
3763               (void *)dev,
3764               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
3765         /* Prevent crashes when queues are still in use. This is unfortunately
3766          * still required for DPDK 1.3 because some programs (such as testpmd)
3767          * never release them before closing the device. */
3768         dev->rx_pkt_burst = removed_rx_burst;
3769         dev->tx_pkt_burst = removed_tx_burst;
3770         if (priv->rxqs != NULL) {
3771                 /* XXX race condition if mlx4_rx_burst() is still running. */
3772                 usleep(1000);
3773                 for (i = 0; (i != priv->rxqs_n); ++i) {
3774                         tmp = (*priv->rxqs)[i];
3775                         if (tmp == NULL)
3776                                 continue;
3777                         (*priv->rxqs)[i] = NULL;
3778                         rxq_cleanup(tmp);
3779                         rte_free(tmp);
3780                 }
3781                 priv->rxqs_n = 0;
3782                 priv->rxqs = NULL;
3783         }
3784         if (priv->txqs != NULL) {
3785                 /* XXX race condition if mlx4_tx_burst() is still running. */
3786                 usleep(1000);
3787                 for (i = 0; (i != priv->txqs_n); ++i) {
3788                         tmp = (*priv->txqs)[i];
3789                         if (tmp == NULL)
3790                                 continue;
3791                         (*priv->txqs)[i] = NULL;
3792                         txq_cleanup(tmp);
3793                         rte_free(tmp);
3794                 }
3795                 priv->txqs_n = 0;
3796                 priv->txqs = NULL;
3797         }
3798         if (priv->rss)
3799                 rxq_cleanup(&priv->rxq_parent);
3800         if (priv->pd != NULL) {
3801                 assert(priv->ctx != NULL);
3802                 claim_zero(ibv_dealloc_pd(priv->pd));
3803                 claim_zero(ibv_close_device(priv->ctx));
3804         } else
3805                 assert(priv->ctx == NULL);
3806         priv_unlock(priv);
3807         memset(priv, 0, sizeof(*priv));
3808 }
3809
3810 /**
3811  * DPDK callback to get information about the device.
3812  *
3813  * @param dev
3814  *   Pointer to Ethernet device structure.
3815  * @param[out] info
3816  *   Info structure output buffer.
3817  */
3818 static void
3819 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
3820 {
3821         struct priv *priv = dev->data->dev_private;
3822         unsigned int max;
3823         char ifname[IF_NAMESIZE];
3824
3825         priv_lock(priv);
3826         /* FIXME: we should ask the device for these values. */
3827         info->min_rx_bufsize = 32;
3828         info->max_rx_pktlen = 65536;
3829         /*
3830          * Since we need one CQ per QP, the limit is the minimum number
3831          * between the two values.
3832          */
3833         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
3834                priv->device_attr.max_qp : priv->device_attr.max_cq);
3835         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
3836         if (max >= 65535)
3837                 max = 65535;
3838         info->max_rx_queues = max;
3839         info->max_tx_queues = max;
3840         /* Last array entry is reserved for broadcast. */
3841         info->max_mac_addrs = (elemof(priv->mac) - 1);
3842         info->rx_offload_capa =
3843                 (priv->hw_csum ?
3844                  (DEV_RX_OFFLOAD_IPV4_CKSUM |
3845                   DEV_RX_OFFLOAD_UDP_CKSUM |
3846                   DEV_RX_OFFLOAD_TCP_CKSUM) :
3847                  0);
3848         info->tx_offload_capa =
3849                 (priv->hw_csum ?
3850                  (DEV_TX_OFFLOAD_IPV4_CKSUM |
3851                   DEV_TX_OFFLOAD_UDP_CKSUM |
3852                   DEV_TX_OFFLOAD_TCP_CKSUM) :
3853                  0);
3854         if (priv_get_ifname(priv, &ifname) == 0)
3855                 info->if_index = if_nametoindex(ifname);
3856         priv_unlock(priv);
3857 }
3858
3859 /**
3860  * DPDK callback to get device statistics.
3861  *
3862  * @param dev
3863  *   Pointer to Ethernet device structure.
3864  * @param[out] stats
3865  *   Stats structure output buffer.
3866  */
3867 static void
3868 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
3869 {
3870         struct priv *priv = dev->data->dev_private;
3871         struct rte_eth_stats tmp = {0};
3872         unsigned int i;
3873         unsigned int idx;
3874
3875         priv_lock(priv);
3876         /* Add software counters. */
3877         for (i = 0; (i != priv->rxqs_n); ++i) {
3878                 struct rxq *rxq = (*priv->rxqs)[i];
3879
3880                 if (rxq == NULL)
3881                         continue;
3882                 idx = rxq->stats.idx;
3883                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3884 #ifdef MLX4_PMD_SOFT_COUNTERS
3885                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
3886                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
3887 #endif
3888                         tmp.q_errors[idx] += (rxq->stats.idropped +
3889                                               rxq->stats.rx_nombuf);
3890                 }
3891 #ifdef MLX4_PMD_SOFT_COUNTERS
3892                 tmp.ipackets += rxq->stats.ipackets;
3893                 tmp.ibytes += rxq->stats.ibytes;
3894 #endif
3895                 tmp.ierrors += rxq->stats.idropped;
3896                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
3897         }
3898         for (i = 0; (i != priv->txqs_n); ++i) {
3899                 struct txq *txq = (*priv->txqs)[i];
3900
3901                 if (txq == NULL)
3902                         continue;
3903                 idx = txq->stats.idx;
3904                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3905 #ifdef MLX4_PMD_SOFT_COUNTERS
3906                         tmp.q_opackets[idx] += txq->stats.opackets;
3907                         tmp.q_obytes[idx] += txq->stats.obytes;
3908 #endif
3909                         tmp.q_errors[idx] += txq->stats.odropped;
3910                 }
3911 #ifdef MLX4_PMD_SOFT_COUNTERS
3912                 tmp.opackets += txq->stats.opackets;
3913                 tmp.obytes += txq->stats.obytes;
3914 #endif
3915                 tmp.oerrors += txq->stats.odropped;
3916         }
3917 #ifndef MLX4_PMD_SOFT_COUNTERS
3918         /* FIXME: retrieve and add hardware counters. */
3919 #endif
3920         *stats = tmp;
3921         priv_unlock(priv);
3922 }
3923
3924 /**
3925  * DPDK callback to clear device statistics.
3926  *
3927  * @param dev
3928  *   Pointer to Ethernet device structure.
3929  */
3930 static void
3931 mlx4_stats_reset(struct rte_eth_dev *dev)
3932 {
3933         struct priv *priv = dev->data->dev_private;
3934         unsigned int i;
3935         unsigned int idx;
3936
3937         priv_lock(priv);
3938         for (i = 0; (i != priv->rxqs_n); ++i) {
3939                 if ((*priv->rxqs)[i] == NULL)
3940                         continue;
3941                 idx = (*priv->rxqs)[i]->stats.idx;
3942                 (*priv->rxqs)[i]->stats =
3943                         (struct mlx4_rxq_stats){ .idx = idx };
3944         }
3945         for (i = 0; (i != priv->txqs_n); ++i) {
3946                 if ((*priv->txqs)[i] == NULL)
3947                         continue;
3948                 idx = (*priv->rxqs)[i]->stats.idx;
3949                 (*priv->txqs)[i]->stats =
3950                         (struct mlx4_txq_stats){ .idx = idx };
3951         }
3952 #ifndef MLX4_PMD_SOFT_COUNTERS
3953         /* FIXME: reset hardware counters. */
3954 #endif
3955         priv_unlock(priv);
3956 }
3957
3958 /**
3959  * DPDK callback to remove a MAC address.
3960  *
3961  * @param dev
3962  *   Pointer to Ethernet device structure.
3963  * @param index
3964  *   MAC address index.
3965  */
3966 static void
3967 mlx4_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
3968 {
3969         struct priv *priv = dev->data->dev_private;
3970
3971         priv_lock(priv);
3972         DEBUG("%p: removing MAC address from index %" PRIu32,
3973               (void *)dev, index);
3974         /* Last array entry is reserved for broadcast. */
3975         if (index >= (elemof(priv->mac) - 1))
3976                 goto end;
3977         priv_mac_addr_del(priv, index);
3978 end:
3979         priv_unlock(priv);
3980 }
3981
3982 /**
3983  * DPDK callback to add a MAC address.
3984  *
3985  * @param dev
3986  *   Pointer to Ethernet device structure.
3987  * @param mac_addr
3988  *   MAC address to register.
3989  * @param index
3990  *   MAC address index.
3991  * @param vmdq
3992  *   VMDq pool index to associate address with (ignored).
3993  */
3994 static void
3995 mlx4_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
3996                   uint32_t index, uint32_t vmdq)
3997 {
3998         struct priv *priv = dev->data->dev_private;
3999
4000         (void)vmdq;
4001         priv_lock(priv);
4002         DEBUG("%p: adding MAC address at index %" PRIu32,
4003               (void *)dev, index);
4004         /* Last array entry is reserved for broadcast. */
4005         if (index >= (elemof(priv->mac) - 1))
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 };
4571
4572 /**
4573  * Get PCI information from struct ibv_device.
4574  *
4575  * @param device
4576  *   Pointer to Ethernet device structure.
4577  * @param[out] pci_addr
4578  *   PCI bus address output buffer.
4579  *
4580  * @return
4581  *   0 on success, -1 on failure and errno is set.
4582  */
4583 static int
4584 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
4585                             struct rte_pci_addr *pci_addr)
4586 {
4587         FILE *file;
4588         char line[32];
4589         MKSTR(path, "%s/device/uevent", device->ibdev_path);
4590
4591         file = fopen(path, "rb");
4592         if (file == NULL)
4593                 return -1;
4594         while (fgets(line, sizeof(line), file) == line) {
4595                 size_t len = strlen(line);
4596                 int ret;
4597
4598                 /* Truncate long lines. */
4599                 if (len == (sizeof(line) - 1))
4600                         while (line[(len - 1)] != '\n') {
4601                                 ret = fgetc(file);
4602                                 if (ret == EOF)
4603                                         break;
4604                                 line[(len - 1)] = ret;
4605                         }
4606                 /* Extract information. */
4607                 if (sscanf(line,
4608                            "PCI_SLOT_NAME="
4609                            "%" SCNx16 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
4610                            &pci_addr->domain,
4611                            &pci_addr->bus,
4612                            &pci_addr->devid,
4613                            &pci_addr->function) == 4) {
4614                         ret = 0;
4615                         break;
4616                 }
4617         }
4618         fclose(file);
4619         return 0;
4620 }
4621
4622 /**
4623  * Get MAC address by querying netdevice.
4624  *
4625  * @param[in] priv
4626  *   struct priv for the requested device.
4627  * @param[out] mac
4628  *   MAC address output buffer.
4629  *
4630  * @return
4631  *   0 on success, -1 on failure and errno is set.
4632  */
4633 static int
4634 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
4635 {
4636         struct ifreq request;
4637
4638         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
4639                 return -1;
4640         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
4641         return 0;
4642 }
4643
4644 /* Support up to 32 adapters. */
4645 static struct {
4646         struct rte_pci_addr pci_addr; /* associated PCI address */
4647         uint32_t ports; /* physical ports bitfield. */
4648 } mlx4_dev[32];
4649
4650 /**
4651  * Get device index in mlx4_dev[] from PCI bus address.
4652  *
4653  * @param[in] pci_addr
4654  *   PCI bus address to look for.
4655  *
4656  * @return
4657  *   mlx4_dev[] index on success, -1 on failure.
4658  */
4659 static int
4660 mlx4_dev_idx(struct rte_pci_addr *pci_addr)
4661 {
4662         unsigned int i;
4663         int ret = -1;
4664
4665         assert(pci_addr != NULL);
4666         for (i = 0; (i != elemof(mlx4_dev)); ++i) {
4667                 if ((mlx4_dev[i].pci_addr.domain == pci_addr->domain) &&
4668                     (mlx4_dev[i].pci_addr.bus == pci_addr->bus) &&
4669                     (mlx4_dev[i].pci_addr.devid == pci_addr->devid) &&
4670                     (mlx4_dev[i].pci_addr.function == pci_addr->function))
4671                         return i;
4672                 if ((mlx4_dev[i].ports == 0) && (ret == -1))
4673                         ret = i;
4674         }
4675         return ret;
4676 }
4677
4678 /**
4679  * Retrieve integer value from environment variable.
4680  *
4681  * @param[in] name
4682  *   Environment variable name.
4683  *
4684  * @return
4685  *   Integer value, 0 if the variable is not set.
4686  */
4687 static int
4688 mlx4_getenv_int(const char *name)
4689 {
4690         const char *val = getenv(name);
4691
4692         if (val == NULL)
4693                 return 0;
4694         return atoi(val);
4695 }
4696
4697 static struct eth_driver mlx4_driver;
4698
4699 /**
4700  * DPDK callback to register a PCI device.
4701  *
4702  * This function creates an Ethernet device for each port of a given
4703  * PCI device.
4704  *
4705  * @param[in] pci_drv
4706  *   PCI driver structure (mlx4_driver).
4707  * @param[in] pci_dev
4708  *   PCI device information.
4709  *
4710  * @return
4711  *   0 on success, negative errno value on failure.
4712  */
4713 static int
4714 mlx4_pci_devinit(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
4715 {
4716         struct ibv_device **list;
4717         struct ibv_device *ibv_dev;
4718         int err = 0;
4719         struct ibv_context *attr_ctx = NULL;
4720         struct ibv_device_attr device_attr;
4721         unsigned int vf;
4722         int idx;
4723         int i;
4724
4725         (void)pci_drv;
4726         assert(pci_drv == &mlx4_driver.pci_drv);
4727         /* Get mlx4_dev[] index. */
4728         idx = mlx4_dev_idx(&pci_dev->addr);
4729         if (idx == -1) {
4730                 ERROR("this driver cannot support any more adapters");
4731                 return -ENOMEM;
4732         }
4733         DEBUG("using driver device index %d", idx);
4734
4735         /* Save PCI address. */
4736         mlx4_dev[idx].pci_addr = pci_dev->addr;
4737         list = ibv_get_device_list(&i);
4738         if (list == NULL) {
4739                 assert(errno);
4740                 if (errno == ENOSYS) {
4741                         WARN("cannot list devices, is ib_uverbs loaded?");
4742                         return 0;
4743                 }
4744                 return -errno;
4745         }
4746         assert(i >= 0);
4747         /*
4748          * For each listed device, check related sysfs entry against
4749          * the provided PCI ID.
4750          */
4751         while (i != 0) {
4752                 struct rte_pci_addr pci_addr;
4753
4754                 --i;
4755                 DEBUG("checking device \"%s\"", list[i]->name);
4756                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
4757                         continue;
4758                 if ((pci_dev->addr.domain != pci_addr.domain) ||
4759                     (pci_dev->addr.bus != pci_addr.bus) ||
4760                     (pci_dev->addr.devid != pci_addr.devid) ||
4761                     (pci_dev->addr.function != pci_addr.function))
4762                         continue;
4763                 vf = (pci_dev->id.device_id ==
4764                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
4765                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
4766                      list[i]->name, (vf ? "true" : "false"));
4767                 attr_ctx = ibv_open_device(list[i]);
4768                 err = errno;
4769                 break;
4770         }
4771         if (attr_ctx == NULL) {
4772                 ibv_free_device_list(list);
4773                 switch (err) {
4774                 case 0:
4775                         WARN("cannot access device, is mlx4_ib loaded?");
4776                         return 0;
4777                 case EINVAL:
4778                         WARN("cannot use device, are drivers up to date?");
4779                         return 0;
4780                 }
4781                 assert(err > 0);
4782                 return -err;
4783         }
4784         ibv_dev = list[i];
4785
4786         DEBUG("device opened");
4787         if (ibv_query_device(attr_ctx, &device_attr))
4788                 goto error;
4789         INFO("%u port(s) detected", device_attr.phys_port_cnt);
4790
4791         for (i = 0; i < device_attr.phys_port_cnt; i++) {
4792                 uint32_t port = i + 1; /* ports are indexed from one */
4793                 uint32_t test = (1 << i);
4794                 struct ibv_context *ctx = NULL;
4795                 struct ibv_port_attr port_attr;
4796                 struct ibv_pd *pd = NULL;
4797                 struct priv *priv = NULL;
4798                 struct rte_eth_dev *eth_dev;
4799 #ifdef HAVE_EXP_QUERY_DEVICE
4800                 struct ibv_exp_device_attr exp_device_attr;
4801 #endif /* HAVE_EXP_QUERY_DEVICE */
4802                 struct ether_addr mac;
4803
4804 #ifdef HAVE_EXP_QUERY_DEVICE
4805                 exp_device_attr.comp_mask = IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS;
4806 #ifdef RSS_SUPPORT
4807                 exp_device_attr.comp_mask |= IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ;
4808 #endif /* RSS_SUPPORT */
4809 #endif /* HAVE_EXP_QUERY_DEVICE */
4810
4811                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
4812
4813                 ctx = ibv_open_device(ibv_dev);
4814                 if (ctx == NULL)
4815                         goto port_error;
4816
4817                 /* Check port status. */
4818                 err = ibv_query_port(ctx, port, &port_attr);
4819                 if (err) {
4820                         ERROR("port query failed: %s", strerror(err));
4821                         goto port_error;
4822                 }
4823                 if (port_attr.state != IBV_PORT_ACTIVE)
4824                         WARN("bad state for port %d: \"%s\" (%d)",
4825                              port, ibv_port_state_str(port_attr.state),
4826                              port_attr.state);
4827
4828                 /* Allocate protection domain. */
4829                 pd = ibv_alloc_pd(ctx);
4830                 if (pd == NULL) {
4831                         ERROR("PD allocation failure");
4832                         err = ENOMEM;
4833                         goto port_error;
4834                 }
4835
4836                 mlx4_dev[idx].ports |= test;
4837
4838                 /* from rte_ethdev.c */
4839                 priv = rte_zmalloc("ethdev private structure",
4840                                    sizeof(*priv),
4841                                    RTE_CACHE_LINE_SIZE);
4842                 if (priv == NULL) {
4843                         ERROR("priv allocation failure");
4844                         err = ENOMEM;
4845                         goto port_error;
4846                 }
4847
4848                 priv->ctx = ctx;
4849                 priv->device_attr = device_attr;
4850                 priv->port = port;
4851                 priv->pd = pd;
4852                 priv->mtu = ETHER_MTU;
4853 #ifdef HAVE_EXP_QUERY_DEVICE
4854                 if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4855                         ERROR("ibv_exp_query_device() failed");
4856                         goto port_error;
4857                 }
4858 #ifdef RSS_SUPPORT
4859                 if ((exp_device_attr.exp_device_cap_flags &
4860                      IBV_EXP_DEVICE_QPG) &&
4861                     (exp_device_attr.exp_device_cap_flags &
4862                      IBV_EXP_DEVICE_UD_RSS) &&
4863                     (exp_device_attr.comp_mask &
4864                      IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ) &&
4865                     (exp_device_attr.max_rss_tbl_sz > 0)) {
4866                         priv->hw_qpg = 1;
4867                         priv->hw_rss = 1;
4868                         priv->max_rss_tbl_sz = exp_device_attr.max_rss_tbl_sz;
4869                 } else {
4870                         priv->hw_qpg = 0;
4871                         priv->hw_rss = 0;
4872                         priv->max_rss_tbl_sz = 0;
4873                 }
4874                 priv->hw_tss = !!(exp_device_attr.exp_device_cap_flags &
4875                                   IBV_EXP_DEVICE_UD_TSS);
4876                 DEBUG("device flags: %s%s%s",
4877                       (priv->hw_qpg ? "IBV_DEVICE_QPG " : ""),
4878                       (priv->hw_tss ? "IBV_DEVICE_TSS " : ""),
4879                       (priv->hw_rss ? "IBV_DEVICE_RSS " : ""));
4880                 if (priv->hw_rss)
4881                         DEBUG("maximum RSS indirection table size: %u",
4882                               exp_device_attr.max_rss_tbl_sz);
4883 #endif /* RSS_SUPPORT */
4884
4885                 priv->hw_csum =
4886                         ((exp_device_attr.exp_device_cap_flags &
4887                           IBV_EXP_DEVICE_RX_CSUM_TCP_UDP_PKT) &&
4888                          (exp_device_attr.exp_device_cap_flags &
4889                           IBV_EXP_DEVICE_RX_CSUM_IP_PKT));
4890                 DEBUG("checksum offloading is %ssupported",
4891                       (priv->hw_csum ? "" : "not "));
4892
4893                 priv->hw_csum_l2tun = !!(exp_device_attr.exp_device_cap_flags &
4894                                          IBV_EXP_DEVICE_VXLAN_SUPPORT);
4895                 DEBUG("L2 tunnel checksum offloads are %ssupported",
4896                       (priv->hw_csum_l2tun ? "" : "not "));
4897
4898 #ifdef INLINE_RECV
4899                 priv->inl_recv_size = mlx4_getenv_int("MLX4_INLINE_RECV_SIZE");
4900
4901                 if (priv->inl_recv_size) {
4902                         exp_device_attr.comp_mask =
4903                                 IBV_EXP_DEVICE_ATTR_INLINE_RECV_SZ;
4904                         if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4905                                 INFO("Couldn't query device for inline-receive"
4906                                      " capabilities.");
4907                                 priv->inl_recv_size = 0;
4908                         } else {
4909                                 if ((unsigned)exp_device_attr.inline_recv_sz <
4910                                     priv->inl_recv_size) {
4911                                         INFO("Max inline-receive (%d) <"
4912                                              " requested inline-receive (%u)",
4913                                              exp_device_attr.inline_recv_sz,
4914                                              priv->inl_recv_size);
4915                                         priv->inl_recv_size =
4916                                                 exp_device_attr.inline_recv_sz;
4917                                 }
4918                         }
4919                         INFO("Set inline receive size to %u",
4920                              priv->inl_recv_size);
4921                 }
4922 #endif /* INLINE_RECV */
4923 #endif /* HAVE_EXP_QUERY_DEVICE */
4924
4925                 (void)mlx4_getenv_int;
4926                 priv->vf = vf;
4927                 /* Configure the first MAC address by default. */
4928                 if (priv_get_mac(priv, &mac.addr_bytes)) {
4929                         ERROR("cannot get MAC address, is mlx4_en loaded?"
4930                               " (errno: %s)", strerror(errno));
4931                         goto port_error;
4932                 }
4933                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
4934                      priv->port,
4935                      mac.addr_bytes[0], mac.addr_bytes[1],
4936                      mac.addr_bytes[2], mac.addr_bytes[3],
4937                      mac.addr_bytes[4], mac.addr_bytes[5]);
4938                 /* Register MAC and broadcast addresses. */
4939                 claim_zero(priv_mac_addr_add(priv, 0,
4940                                              (const uint8_t (*)[ETHER_ADDR_LEN])
4941                                              mac.addr_bytes));
4942                 claim_zero(priv_mac_addr_add(priv, (elemof(priv->mac) - 1),
4943                                              &(const uint8_t [ETHER_ADDR_LEN])
4944                                              { "\xff\xff\xff\xff\xff\xff" }));
4945 #ifndef NDEBUG
4946                 {
4947                         char ifname[IF_NAMESIZE];
4948
4949                         if (priv_get_ifname(priv, &ifname) == 0)
4950                                 DEBUG("port %u ifname is \"%s\"",
4951                                       priv->port, ifname);
4952                         else
4953                                 DEBUG("port %u ifname is unknown", priv->port);
4954                 }
4955 #endif
4956                 /* Get actual MTU if possible. */
4957                 priv_get_mtu(priv, &priv->mtu);
4958                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
4959
4960                 /* from rte_ethdev.c */
4961                 {
4962                         char name[RTE_ETH_NAME_MAX_LEN];
4963
4964                         snprintf(name, sizeof(name), "%s port %u",
4965                                  ibv_get_device_name(ibv_dev), port);
4966                         eth_dev = rte_eth_dev_allocate(name, RTE_ETH_DEV_PCI);
4967                 }
4968                 if (eth_dev == NULL) {
4969                         ERROR("can not allocate rte ethdev");
4970                         err = ENOMEM;
4971                         goto port_error;
4972                 }
4973
4974                 eth_dev->data->dev_private = priv;
4975                 eth_dev->pci_dev = pci_dev;
4976                 eth_dev->driver = &mlx4_driver;
4977                 eth_dev->data->rx_mbuf_alloc_failed = 0;
4978                 eth_dev->data->mtu = ETHER_MTU;
4979
4980                 priv->dev = eth_dev;
4981                 eth_dev->dev_ops = &mlx4_dev_ops;
4982                 eth_dev->data->mac_addrs = priv->mac;
4983
4984                 /* Bring Ethernet device up. */
4985                 DEBUG("forcing Ethernet interface up");
4986                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
4987                 continue;
4988
4989 port_error:
4990                 rte_free(priv);
4991                 if (pd)
4992                         claim_zero(ibv_dealloc_pd(pd));
4993                 if (ctx)
4994                         claim_zero(ibv_close_device(ctx));
4995                 break;
4996         }
4997
4998         /*
4999          * XXX if something went wrong in the loop above, there is a resource
5000          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
5001          * long as the dpdk does not provide a way to deallocate a ethdev and a
5002          * way to enumerate the registered ethdevs to free the previous ones.
5003          */
5004
5005         /* no port found, complain */
5006         if (!mlx4_dev[idx].ports) {
5007                 err = ENODEV;
5008                 goto error;
5009         }
5010
5011 error:
5012         if (attr_ctx)
5013                 claim_zero(ibv_close_device(attr_ctx));
5014         if (list)
5015                 ibv_free_device_list(list);
5016         assert(err >= 0);
5017         return -err;
5018 }
5019
5020 static const struct rte_pci_id mlx4_pci_id_map[] = {
5021         {
5022                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5023                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3,
5024                 .subsystem_vendor_id = PCI_ANY_ID,
5025                 .subsystem_device_id = PCI_ANY_ID
5026         },
5027         {
5028                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5029                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO,
5030                 .subsystem_vendor_id = PCI_ANY_ID,
5031                 .subsystem_device_id = PCI_ANY_ID
5032         },
5033         {
5034                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5035                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3VF,
5036                 .subsystem_vendor_id = PCI_ANY_ID,
5037                 .subsystem_device_id = PCI_ANY_ID
5038         },
5039         {
5040                 .vendor_id = 0
5041         }
5042 };
5043
5044 static struct eth_driver mlx4_driver = {
5045         .pci_drv = {
5046                 .name = MLX4_DRIVER_NAME,
5047                 .id_table = mlx4_pci_id_map,
5048                 .devinit = mlx4_pci_devinit,
5049         },
5050         .dev_private_size = sizeof(struct priv)
5051 };
5052
5053 /**
5054  * Driver initialization routine.
5055  */
5056 static int
5057 rte_mlx4_pmd_init(const char *name, const char *args)
5058 {
5059         (void)name;
5060         (void)args;
5061         /*
5062          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
5063          * huge pages. Calling ibv_fork_init() during init allows
5064          * applications to use fork() safely for purposes other than
5065          * using this PMD, which is not supported in forked processes.
5066          */
5067         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
5068         ibv_fork_init();
5069         rte_eal_pci_register(&mlx4_driver.pci_drv);
5070         return 0;
5071 }
5072
5073 static struct rte_driver rte_mlx4_driver = {
5074         .type = PMD_PDEV,
5075         .name = MLX4_DRIVER_NAME,
5076         .init = rte_mlx4_pmd_init,
5077 };
5078
5079 PMD_REGISTER_DRIVER(rte_mlx4_driver)