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