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