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