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