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