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