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