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