net/mlx4: add port parameter
[dpdk.git] / drivers / net / mlx4 / mlx4.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright 2012-2017 6WIND S.A.
5  *   Copyright 2012-2017 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/ethtool.h>
58 #include <linux/sockios.h>
59 #include <fcntl.h>
60
61 #include <rte_ether.h>
62 #include <rte_ethdev.h>
63 #include <rte_dev.h>
64 #include <rte_mbuf.h>
65 #include <rte_errno.h>
66 #include <rte_mempool.h>
67 #include <rte_prefetch.h>
68 #include <rte_malloc.h>
69 #include <rte_spinlock.h>
70 #include <rte_atomic.h>
71 #include <rte_version.h>
72 #include <rte_log.h>
73 #include <rte_alarm.h>
74 #include <rte_memory.h>
75 #include <rte_flow.h>
76 #include <rte_kvargs.h>
77
78 /* Generated configuration header. */
79 #include "mlx4_autoconf.h"
80
81 /* PMD headers. */
82 #include "mlx4.h"
83 #include "mlx4_flow.h"
84
85 /* Convenience macros for accessing mbuf fields. */
86 #define NEXT(m) ((m)->next)
87 #define DATA_LEN(m) ((m)->data_len)
88 #define PKT_LEN(m) ((m)->pkt_len)
89 #define DATA_OFF(m) ((m)->data_off)
90 #define SET_DATA_OFF(m, o) ((m)->data_off = (o))
91 #define NB_SEGS(m) ((m)->nb_segs)
92 #define PORT(m) ((m)->port)
93
94 /* Work Request ID data type (64 bit). */
95 typedef union {
96         struct {
97                 uint32_t id;
98                 uint16_t offset;
99         } data;
100         uint64_t raw;
101 } wr_id_t;
102
103 #define WR_ID(o) (((wr_id_t *)&(o))->data)
104
105 /* Transpose flags. Useful to convert IBV to DPDK flags. */
106 #define TRANSPOSE(val, from, to) \
107         (((from) >= (to)) ? \
108          (((val) & (from)) / ((from) / (to))) : \
109          (((val) & (from)) * ((to) / (from))))
110
111 /* Local storage for secondary process data. */
112 struct mlx4_secondary_data {
113         struct rte_eth_dev_data data; /* Local device data. */
114         struct priv *primary_priv; /* Private structure from primary. */
115         struct rte_eth_dev_data *shared_dev_data; /* Shared device data. */
116         rte_spinlock_t lock; /* Port configuration lock. */
117 } mlx4_secondary_data[RTE_MAX_ETHPORTS];
118
119 struct mlx4_conf {
120         uint8_t active_ports;
121 };
122
123 /* Available parameters list. */
124 const char *pmd_mlx4_init_params[] = {
125         MLX4_PMD_PORT_KVARG,
126         NULL,
127 };
128
129 /**
130  * Check if running as a secondary process.
131  *
132  * @return
133  *   Nonzero if running as a secondary process.
134  */
135 static inline int
136 mlx4_is_secondary(void)
137 {
138         return rte_eal_process_type() != RTE_PROC_PRIMARY;
139 }
140
141 /**
142  * Return private structure associated with an Ethernet device.
143  *
144  * @param dev
145  *   Pointer to Ethernet device structure.
146  *
147  * @return
148  *   Pointer to private structure.
149  */
150 static struct priv *
151 mlx4_get_priv(struct rte_eth_dev *dev)
152 {
153         struct mlx4_secondary_data *sd;
154
155         if (!mlx4_is_secondary())
156                 return dev->data->dev_private;
157         sd = &mlx4_secondary_data[dev->data->port_id];
158         return sd->data.dev_private;
159 }
160
161 /**
162  * Lock private structure to protect it from concurrent access in the
163  * control path.
164  *
165  * @param priv
166  *   Pointer to private structure.
167  */
168 void priv_lock(struct priv *priv)
169 {
170         rte_spinlock_lock(&priv->lock);
171 }
172
173 /**
174  * Unlock private structure.
175  *
176  * @param priv
177  *   Pointer to private structure.
178  */
179 void priv_unlock(struct priv *priv)
180 {
181         rte_spinlock_unlock(&priv->lock);
182 }
183
184 /* Allocate a buffer on the stack and fill it with a printf format string. */
185 #define MKSTR(name, ...) \
186         char name[snprintf(NULL, 0, __VA_ARGS__) + 1]; \
187         \
188         snprintf(name, sizeof(name), __VA_ARGS__)
189
190 /**
191  * Get interface name from private structure.
192  *
193  * @param[in] priv
194  *   Pointer to private structure.
195  * @param[out] ifname
196  *   Interface name output buffer.
197  *
198  * @return
199  *   0 on success, -1 on failure and errno is set.
200  */
201 static int
202 priv_get_ifname(const struct priv *priv, char (*ifname)[IF_NAMESIZE])
203 {
204         DIR *dir;
205         struct dirent *dent;
206         unsigned int dev_type = 0;
207         unsigned int dev_port_prev = ~0u;
208         char match[IF_NAMESIZE] = "";
209
210         {
211                 MKSTR(path, "%s/device/net", priv->ctx->device->ibdev_path);
212
213                 dir = opendir(path);
214                 if (dir == NULL)
215                         return -1;
216         }
217         while ((dent = readdir(dir)) != NULL) {
218                 char *name = dent->d_name;
219                 FILE *file;
220                 unsigned int dev_port;
221                 int r;
222
223                 if ((name[0] == '.') &&
224                     ((name[1] == '\0') ||
225                      ((name[1] == '.') && (name[2] == '\0'))))
226                         continue;
227
228                 MKSTR(path, "%s/device/net/%s/%s",
229                       priv->ctx->device->ibdev_path, name,
230                       (dev_type ? "dev_id" : "dev_port"));
231
232                 file = fopen(path, "rb");
233                 if (file == NULL) {
234                         if (errno != ENOENT)
235                                 continue;
236                         /*
237                          * Switch to dev_id when dev_port does not exist as
238                          * is the case with Linux kernel versions < 3.15.
239                          */
240 try_dev_id:
241                         match[0] = '\0';
242                         if (dev_type)
243                                 break;
244                         dev_type = 1;
245                         dev_port_prev = ~0u;
246                         rewinddir(dir);
247                         continue;
248                 }
249                 r = fscanf(file, (dev_type ? "%x" : "%u"), &dev_port);
250                 fclose(file);
251                 if (r != 1)
252                         continue;
253                 /*
254                  * Switch to dev_id when dev_port returns the same value for
255                  * all ports. May happen when using a MOFED release older than
256                  * 3.0 with a Linux kernel >= 3.15.
257                  */
258                 if (dev_port == dev_port_prev)
259                         goto try_dev_id;
260                 dev_port_prev = dev_port;
261                 if (dev_port == (priv->port - 1u))
262                         snprintf(match, sizeof(match), "%s", name);
263         }
264         closedir(dir);
265         if (match[0] == '\0')
266                 return -1;
267         strncpy(*ifname, match, sizeof(*ifname));
268         return 0;
269 }
270
271 /**
272  * Read from sysfs entry.
273  *
274  * @param[in] priv
275  *   Pointer to private structure.
276  * @param[in] entry
277  *   Entry name relative to sysfs path.
278  * @param[out] buf
279  *   Data output buffer.
280  * @param size
281  *   Buffer size.
282  *
283  * @return
284  *   0 on success, -1 on failure and errno is set.
285  */
286 static int
287 priv_sysfs_read(const struct priv *priv, const char *entry,
288                 char *buf, size_t size)
289 {
290         char ifname[IF_NAMESIZE];
291         FILE *file;
292         int ret;
293         int err;
294
295         if (priv_get_ifname(priv, &ifname))
296                 return -1;
297
298         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
299               ifname, entry);
300
301         file = fopen(path, "rb");
302         if (file == NULL)
303                 return -1;
304         ret = fread(buf, 1, size, file);
305         err = errno;
306         if (((size_t)ret < size) && (ferror(file)))
307                 ret = -1;
308         else
309                 ret = size;
310         fclose(file);
311         errno = err;
312         return ret;
313 }
314
315 /**
316  * Write to sysfs entry.
317  *
318  * @param[in] priv
319  *   Pointer to private structure.
320  * @param[in] entry
321  *   Entry name relative to sysfs path.
322  * @param[in] buf
323  *   Data buffer.
324  * @param size
325  *   Buffer size.
326  *
327  * @return
328  *   0 on success, -1 on failure and errno is set.
329  */
330 static int
331 priv_sysfs_write(const struct priv *priv, const char *entry,
332                  char *buf, size_t size)
333 {
334         char ifname[IF_NAMESIZE];
335         FILE *file;
336         int ret;
337         int err;
338
339         if (priv_get_ifname(priv, &ifname))
340                 return -1;
341
342         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
343               ifname, entry);
344
345         file = fopen(path, "wb");
346         if (file == NULL)
347                 return -1;
348         ret = fwrite(buf, 1, size, file);
349         err = errno;
350         if (((size_t)ret < size) || (ferror(file)))
351                 ret = -1;
352         else
353                 ret = size;
354         fclose(file);
355         errno = err;
356         return ret;
357 }
358
359 /**
360  * Get unsigned long sysfs property.
361  *
362  * @param priv
363  *   Pointer to private structure.
364  * @param[in] name
365  *   Entry name relative to sysfs path.
366  * @param[out] value
367  *   Value output buffer.
368  *
369  * @return
370  *   0 on success, -1 on failure and errno is set.
371  */
372 static int
373 priv_get_sysfs_ulong(struct priv *priv, const char *name, unsigned long *value)
374 {
375         int ret;
376         unsigned long value_ret;
377         char value_str[32];
378
379         ret = priv_sysfs_read(priv, name, value_str, (sizeof(value_str) - 1));
380         if (ret == -1) {
381                 DEBUG("cannot read %s value from sysfs: %s",
382                       name, strerror(errno));
383                 return -1;
384         }
385         value_str[ret] = '\0';
386         errno = 0;
387         value_ret = strtoul(value_str, NULL, 0);
388         if (errno) {
389                 DEBUG("invalid %s value `%s': %s", name, value_str,
390                       strerror(errno));
391                 return -1;
392         }
393         *value = value_ret;
394         return 0;
395 }
396
397 /**
398  * Set unsigned long sysfs property.
399  *
400  * @param priv
401  *   Pointer to private structure.
402  * @param[in] name
403  *   Entry name relative to sysfs path.
404  * @param value
405  *   Value to set.
406  *
407  * @return
408  *   0 on success, -1 on failure and errno is set.
409  */
410 static int
411 priv_set_sysfs_ulong(struct priv *priv, const char *name, unsigned long value)
412 {
413         int ret;
414         MKSTR(value_str, "%lu", value);
415
416         ret = priv_sysfs_write(priv, name, value_str, (sizeof(value_str) - 1));
417         if (ret == -1) {
418                 DEBUG("cannot write %s `%s' (%lu) to sysfs: %s",
419                       name, value_str, value, strerror(errno));
420                 return -1;
421         }
422         return 0;
423 }
424
425 /**
426  * Perform ifreq ioctl() on associated Ethernet device.
427  *
428  * @param[in] priv
429  *   Pointer to private structure.
430  * @param req
431  *   Request number to pass to ioctl().
432  * @param[out] ifr
433  *   Interface request structure output buffer.
434  *
435  * @return
436  *   0 on success, -1 on failure and errno is set.
437  */
438 static int
439 priv_ifreq(const struct priv *priv, int req, struct ifreq *ifr)
440 {
441         int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
442         int ret = -1;
443
444         if (sock == -1)
445                 return ret;
446         if (priv_get_ifname(priv, &ifr->ifr_name) == 0)
447                 ret = ioctl(sock, req, ifr);
448         close(sock);
449         return ret;
450 }
451
452 /**
453  * Get device MTU.
454  *
455  * @param priv
456  *   Pointer to private structure.
457  * @param[out] mtu
458  *   MTU value output buffer.
459  *
460  * @return
461  *   0 on success, -1 on failure and errno is set.
462  */
463 static int
464 priv_get_mtu(struct priv *priv, uint16_t *mtu)
465 {
466         unsigned long ulong_mtu;
467
468         if (priv_get_sysfs_ulong(priv, "mtu", &ulong_mtu) == -1)
469                 return -1;
470         *mtu = ulong_mtu;
471         return 0;
472 }
473
474 /**
475  * Set device MTU.
476  *
477  * @param priv
478  *   Pointer to private structure.
479  * @param mtu
480  *   MTU value to set.
481  *
482  * @return
483  *   0 on success, -1 on failure and errno is set.
484  */
485 static int
486 priv_set_mtu(struct priv *priv, uint16_t mtu)
487 {
488         uint16_t new_mtu;
489
490         if (priv_set_sysfs_ulong(priv, "mtu", mtu) ||
491             priv_get_mtu(priv, &new_mtu))
492                 return -1;
493         if (new_mtu == mtu)
494                 return 0;
495         errno = EINVAL;
496         return -1;
497 }
498
499 /**
500  * Set device flags.
501  *
502  * @param priv
503  *   Pointer to private structure.
504  * @param keep
505  *   Bitmask for flags that must remain untouched.
506  * @param flags
507  *   Bitmask for flags to modify.
508  *
509  * @return
510  *   0 on success, -1 on failure and errno is set.
511  */
512 static int
513 priv_set_flags(struct priv *priv, unsigned int keep, unsigned int flags)
514 {
515         unsigned long tmp;
516
517         if (priv_get_sysfs_ulong(priv, "flags", &tmp) == -1)
518                 return -1;
519         tmp &= keep;
520         tmp |= (flags & (~keep));
521         return priv_set_sysfs_ulong(priv, "flags", tmp);
522 }
523
524 /* Device configuration. */
525
526 static int
527 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
528           unsigned int socket, const struct rte_eth_txconf *conf);
529
530 static void
531 txq_cleanup(struct txq *txq);
532
533 static int
534 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
535           unsigned int socket, int inactive, const struct rte_eth_rxconf *conf,
536           struct rte_mempool *mp);
537
538 static void
539 rxq_cleanup(struct rxq *rxq);
540
541 /**
542  * Ethernet device configuration.
543  *
544  * Prepare the driver for a given number of TX and RX queues.
545  * Allocate parent RSS queue when several RX queues are requested.
546  *
547  * @param dev
548  *   Pointer to Ethernet device structure.
549  *
550  * @return
551  *   0 on success, errno value on failure.
552  */
553 static int
554 dev_configure(struct rte_eth_dev *dev)
555 {
556         struct priv *priv = dev->data->dev_private;
557         unsigned int rxqs_n = dev->data->nb_rx_queues;
558         unsigned int txqs_n = dev->data->nb_tx_queues;
559         unsigned int tmp;
560         int ret;
561
562         priv->rxqs = (void *)dev->data->rx_queues;
563         priv->txqs = (void *)dev->data->tx_queues;
564         if (txqs_n != priv->txqs_n) {
565                 INFO("%p: TX queues number update: %u -> %u",
566                      (void *)dev, priv->txqs_n, txqs_n);
567                 priv->txqs_n = txqs_n;
568         }
569         if (rxqs_n == priv->rxqs_n)
570                 return 0;
571         if (!rte_is_power_of_2(rxqs_n)) {
572                 unsigned n_active;
573
574                 n_active = rte_align32pow2(rxqs_n + 1) >> 1;
575                 WARN("%p: number of RX queues must be a power"
576                         " of 2: %u queues among %u will be active",
577                         (void *)dev, n_active, rxqs_n);
578         }
579
580         INFO("%p: RX queues number update: %u -> %u",
581              (void *)dev, priv->rxqs_n, rxqs_n);
582         /* If RSS is enabled, disable it first. */
583         if (priv->rss) {
584                 unsigned int i;
585
586                 /* Only if there are no remaining child RX queues. */
587                 for (i = 0; (i != priv->rxqs_n); ++i)
588                         if ((*priv->rxqs)[i] != NULL)
589                                 return EINVAL;
590                 rxq_cleanup(&priv->rxq_parent);
591                 priv->rss = 0;
592                 priv->rxqs_n = 0;
593         }
594         if (rxqs_n <= 1) {
595                 /* Nothing else to do. */
596                 priv->rxqs_n = rxqs_n;
597                 return 0;
598         }
599         /* Allocate a new RSS parent queue if supported by hardware. */
600         if (!priv->hw_rss) {
601                 ERROR("%p: only a single RX queue can be configured when"
602                       " hardware doesn't support RSS",
603                       (void *)dev);
604                 return EINVAL;
605         }
606         /* Fail if hardware doesn't support that many RSS queues. */
607         if (rxqs_n >= priv->max_rss_tbl_sz) {
608                 ERROR("%p: only %u RX queues can be configured for RSS",
609                       (void *)dev, priv->max_rss_tbl_sz);
610                 return EINVAL;
611         }
612         priv->rss = 1;
613         tmp = priv->rxqs_n;
614         priv->rxqs_n = rxqs_n;
615         ret = rxq_setup(dev, &priv->rxq_parent, 0, 0, 0, NULL, NULL);
616         if (!ret)
617                 return 0;
618         /* Failure, rollback. */
619         priv->rss = 0;
620         priv->rxqs_n = tmp;
621         assert(ret > 0);
622         return ret;
623 }
624
625 /**
626  * DPDK callback for Ethernet device configuration.
627  *
628  * @param dev
629  *   Pointer to Ethernet device structure.
630  *
631  * @return
632  *   0 on success, negative errno value on failure.
633  */
634 static int
635 mlx4_dev_configure(struct rte_eth_dev *dev)
636 {
637         struct priv *priv = dev->data->dev_private;
638         int ret;
639
640         if (mlx4_is_secondary())
641                 return -E_RTE_SECONDARY;
642         priv_lock(priv);
643         ret = dev_configure(dev);
644         assert(ret >= 0);
645         priv_unlock(priv);
646         return -ret;
647 }
648
649 static uint16_t mlx4_tx_burst(void *, struct rte_mbuf **, uint16_t);
650 static uint16_t removed_rx_burst(void *, struct rte_mbuf **, uint16_t);
651
652 /**
653  * Configure secondary process queues from a private data pointer (primary
654  * or secondary) and update burst callbacks. Can take place only once.
655  *
656  * All queues must have been previously created by the primary process to
657  * avoid undefined behavior.
658  *
659  * @param priv
660  *   Private data pointer from either primary or secondary process.
661  *
662  * @return
663  *   Private data pointer from secondary process, NULL in case of error.
664  */
665 static struct priv *
666 mlx4_secondary_data_setup(struct priv *priv)
667 {
668         unsigned int port_id = 0;
669         struct mlx4_secondary_data *sd;
670         void **tx_queues;
671         void **rx_queues;
672         unsigned int nb_tx_queues;
673         unsigned int nb_rx_queues;
674         unsigned int i;
675
676         /* priv must be valid at this point. */
677         assert(priv != NULL);
678         /* priv->dev must also be valid but may point to local memory from
679          * another process, possibly with the same address and must not
680          * be dereferenced yet. */
681         assert(priv->dev != NULL);
682         /* Determine port ID by finding out where priv comes from. */
683         while (1) {
684                 sd = &mlx4_secondary_data[port_id];
685                 rte_spinlock_lock(&sd->lock);
686                 /* Primary process? */
687                 if (sd->primary_priv == priv)
688                         break;
689                 /* Secondary process? */
690                 if (sd->data.dev_private == priv)
691                         break;
692                 rte_spinlock_unlock(&sd->lock);
693                 if (++port_id == RTE_DIM(mlx4_secondary_data))
694                         port_id = 0;
695         }
696         /* Switch to secondary private structure. If private data has already
697          * been updated by another thread, there is nothing else to do. */
698         priv = sd->data.dev_private;
699         if (priv->dev->data == &sd->data)
700                 goto end;
701         /* Sanity checks. Secondary private structure is supposed to point
702          * to local eth_dev, itself still pointing to the shared device data
703          * structure allocated by the primary process. */
704         assert(sd->shared_dev_data != &sd->data);
705         assert(sd->data.nb_tx_queues == 0);
706         assert(sd->data.tx_queues == NULL);
707         assert(sd->data.nb_rx_queues == 0);
708         assert(sd->data.rx_queues == NULL);
709         assert(priv != sd->primary_priv);
710         assert(priv->dev->data == sd->shared_dev_data);
711         assert(priv->txqs_n == 0);
712         assert(priv->txqs == NULL);
713         assert(priv->rxqs_n == 0);
714         assert(priv->rxqs == NULL);
715         nb_tx_queues = sd->shared_dev_data->nb_tx_queues;
716         nb_rx_queues = sd->shared_dev_data->nb_rx_queues;
717         /* Allocate local storage for queues. */
718         tx_queues = rte_zmalloc("secondary ethdev->tx_queues",
719                                 sizeof(sd->data.tx_queues[0]) * nb_tx_queues,
720                                 RTE_CACHE_LINE_SIZE);
721         rx_queues = rte_zmalloc("secondary ethdev->rx_queues",
722                                 sizeof(sd->data.rx_queues[0]) * nb_rx_queues,
723                                 RTE_CACHE_LINE_SIZE);
724         if (tx_queues == NULL || rx_queues == NULL)
725                 goto error;
726         /* Lock to prevent control operations during setup. */
727         priv_lock(priv);
728         /* TX queues. */
729         for (i = 0; i != nb_tx_queues; ++i) {
730                 struct txq *primary_txq = (*sd->primary_priv->txqs)[i];
731                 struct txq *txq;
732
733                 if (primary_txq == NULL)
734                         continue;
735                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0,
736                                         primary_txq->socket);
737                 if (txq != NULL) {
738                         if (txq_setup(priv->dev,
739                                       txq,
740                                       primary_txq->elts_n * MLX4_PMD_SGE_WR_N,
741                                       primary_txq->socket,
742                                       NULL) == 0) {
743                                 txq->stats.idx = primary_txq->stats.idx;
744                                 tx_queues[i] = txq;
745                                 continue;
746                         }
747                         rte_free(txq);
748                 }
749                 while (i) {
750                         txq = tx_queues[--i];
751                         txq_cleanup(txq);
752                         rte_free(txq);
753                 }
754                 goto error;
755         }
756         /* RX queues. */
757         for (i = 0; i != nb_rx_queues; ++i) {
758                 struct rxq *primary_rxq = (*sd->primary_priv->rxqs)[i];
759
760                 if (primary_rxq == NULL)
761                         continue;
762                 /* Not supported yet. */
763                 rx_queues[i] = NULL;
764         }
765         /* Update everything. */
766         priv->txqs = (void *)tx_queues;
767         priv->txqs_n = nb_tx_queues;
768         priv->rxqs = (void *)rx_queues;
769         priv->rxqs_n = nb_rx_queues;
770         sd->data.rx_queues = rx_queues;
771         sd->data.tx_queues = tx_queues;
772         sd->data.nb_rx_queues = nb_rx_queues;
773         sd->data.nb_tx_queues = nb_tx_queues;
774         sd->data.dev_link = sd->shared_dev_data->dev_link;
775         sd->data.mtu = sd->shared_dev_data->mtu;
776         memcpy(sd->data.rx_queue_state, sd->shared_dev_data->rx_queue_state,
777                sizeof(sd->data.rx_queue_state));
778         memcpy(sd->data.tx_queue_state, sd->shared_dev_data->tx_queue_state,
779                sizeof(sd->data.tx_queue_state));
780         sd->data.dev_flags = sd->shared_dev_data->dev_flags;
781         /* Use local data from now on. */
782         rte_mb();
783         priv->dev->data = &sd->data;
784         rte_mb();
785         priv->dev->tx_pkt_burst = mlx4_tx_burst;
786         priv->dev->rx_pkt_burst = removed_rx_burst;
787         priv_unlock(priv);
788 end:
789         /* More sanity checks. */
790         assert(priv->dev->tx_pkt_burst == mlx4_tx_burst);
791         assert(priv->dev->rx_pkt_burst == removed_rx_burst);
792         assert(priv->dev->data == &sd->data);
793         rte_spinlock_unlock(&sd->lock);
794         return priv;
795 error:
796         priv_unlock(priv);
797         rte_free(tx_queues);
798         rte_free(rx_queues);
799         rte_spinlock_unlock(&sd->lock);
800         return NULL;
801 }
802
803 /* TX queues handling. */
804
805 /**
806  * Allocate TX queue elements.
807  *
808  * @param txq
809  *   Pointer to TX queue structure.
810  * @param elts_n
811  *   Number of elements to allocate.
812  *
813  * @return
814  *   0 on success, errno value on failure.
815  */
816 static int
817 txq_alloc_elts(struct txq *txq, unsigned int elts_n)
818 {
819         unsigned int i;
820         struct txq_elt (*elts)[elts_n] =
821                 rte_calloc_socket("TXQ", 1, sizeof(*elts), 0, txq->socket);
822         linear_t (*elts_linear)[elts_n] =
823                 rte_calloc_socket("TXQ", 1, sizeof(*elts_linear), 0,
824                                   txq->socket);
825         struct ibv_mr *mr_linear = NULL;
826         int ret = 0;
827
828         if ((elts == NULL) || (elts_linear == NULL)) {
829                 ERROR("%p: can't allocate packets array", (void *)txq);
830                 ret = ENOMEM;
831                 goto error;
832         }
833         mr_linear =
834                 ibv_reg_mr(txq->priv->pd, elts_linear, sizeof(*elts_linear),
835                            IBV_ACCESS_LOCAL_WRITE);
836         if (mr_linear == NULL) {
837                 ERROR("%p: unable to configure MR, ibv_reg_mr() failed",
838                       (void *)txq);
839                 ret = EINVAL;
840                 goto error;
841         }
842         for (i = 0; (i != elts_n); ++i) {
843                 struct txq_elt *elt = &(*elts)[i];
844
845                 elt->buf = NULL;
846         }
847         DEBUG("%p: allocated and configured %u WRs", (void *)txq, elts_n);
848         txq->elts_n = elts_n;
849         txq->elts = elts;
850         txq->elts_head = 0;
851         txq->elts_tail = 0;
852         txq->elts_comp = 0;
853         /* Request send completion every MLX4_PMD_TX_PER_COMP_REQ packets or
854          * at least 4 times per ring. */
855         txq->elts_comp_cd_init =
856                 ((MLX4_PMD_TX_PER_COMP_REQ < (elts_n / 4)) ?
857                  MLX4_PMD_TX_PER_COMP_REQ : (elts_n / 4));
858         txq->elts_comp_cd = txq->elts_comp_cd_init;
859         txq->elts_linear = elts_linear;
860         txq->mr_linear = mr_linear;
861         assert(ret == 0);
862         return 0;
863 error:
864         if (mr_linear != NULL)
865                 claim_zero(ibv_dereg_mr(mr_linear));
866
867         rte_free(elts_linear);
868         rte_free(elts);
869
870         DEBUG("%p: failed, freed everything", (void *)txq);
871         assert(ret > 0);
872         return ret;
873 }
874
875 /**
876  * Free TX queue elements.
877  *
878  * @param txq
879  *   Pointer to TX queue structure.
880  */
881 static void
882 txq_free_elts(struct txq *txq)
883 {
884         unsigned int elts_n = txq->elts_n;
885         unsigned int elts_head = txq->elts_head;
886         unsigned int elts_tail = txq->elts_tail;
887         struct txq_elt (*elts)[elts_n] = txq->elts;
888         linear_t (*elts_linear)[elts_n] = txq->elts_linear;
889         struct ibv_mr *mr_linear = txq->mr_linear;
890
891         DEBUG("%p: freeing WRs", (void *)txq);
892         txq->elts_n = 0;
893         txq->elts_head = 0;
894         txq->elts_tail = 0;
895         txq->elts_comp = 0;
896         txq->elts_comp_cd = 0;
897         txq->elts_comp_cd_init = 0;
898         txq->elts = NULL;
899         txq->elts_linear = NULL;
900         txq->mr_linear = NULL;
901         if (mr_linear != NULL)
902                 claim_zero(ibv_dereg_mr(mr_linear));
903
904         rte_free(elts_linear);
905         if (elts == NULL)
906                 return;
907         while (elts_tail != elts_head) {
908                 struct txq_elt *elt = &(*elts)[elts_tail];
909
910                 assert(elt->buf != NULL);
911                 rte_pktmbuf_free(elt->buf);
912 #ifndef NDEBUG
913                 /* Poisoning. */
914                 memset(elt, 0x77, sizeof(*elt));
915 #endif
916                 if (++elts_tail == elts_n)
917                         elts_tail = 0;
918         }
919         rte_free(elts);
920 }
921
922
923 /**
924  * Clean up a TX queue.
925  *
926  * Destroy objects, free allocated memory and reset the structure for reuse.
927  *
928  * @param txq
929  *   Pointer to TX queue structure.
930  */
931 static void
932 txq_cleanup(struct txq *txq)
933 {
934         struct ibv_exp_release_intf_params params;
935         size_t i;
936
937         DEBUG("cleaning up %p", (void *)txq);
938         txq_free_elts(txq);
939         if (txq->if_qp != NULL) {
940                 assert(txq->priv != NULL);
941                 assert(txq->priv->ctx != NULL);
942                 assert(txq->qp != NULL);
943                 params = (struct ibv_exp_release_intf_params){
944                         .comp_mask = 0,
945                 };
946                 claim_zero(ibv_exp_release_intf(txq->priv->ctx,
947                                                 txq->if_qp,
948                                                 &params));
949         }
950         if (txq->if_cq != NULL) {
951                 assert(txq->priv != NULL);
952                 assert(txq->priv->ctx != NULL);
953                 assert(txq->cq != NULL);
954                 params = (struct ibv_exp_release_intf_params){
955                         .comp_mask = 0,
956                 };
957                 claim_zero(ibv_exp_release_intf(txq->priv->ctx,
958                                                 txq->if_cq,
959                                                 &params));
960         }
961         if (txq->qp != NULL)
962                 claim_zero(ibv_destroy_qp(txq->qp));
963         if (txq->cq != NULL)
964                 claim_zero(ibv_destroy_cq(txq->cq));
965         if (txq->rd != NULL) {
966                 struct ibv_exp_destroy_res_domain_attr attr = {
967                         .comp_mask = 0,
968                 };
969
970                 assert(txq->priv != NULL);
971                 assert(txq->priv->ctx != NULL);
972                 claim_zero(ibv_exp_destroy_res_domain(txq->priv->ctx,
973                                                       txq->rd,
974                                                       &attr));
975         }
976         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
977                 if (txq->mp2mr[i].mp == NULL)
978                         break;
979                 assert(txq->mp2mr[i].mr != NULL);
980                 claim_zero(ibv_dereg_mr(txq->mp2mr[i].mr));
981         }
982         memset(txq, 0, sizeof(*txq));
983 }
984
985 /**
986  * Manage TX completions.
987  *
988  * When sending a burst, mlx4_tx_burst() posts several WRs.
989  * To improve performance, a completion event is only required once every
990  * MLX4_PMD_TX_PER_COMP_REQ sends. Doing so discards completion information
991  * for other WRs, but this information would not be used anyway.
992  *
993  * @param txq
994  *   Pointer to TX queue structure.
995  *
996  * @return
997  *   0 on success, -1 on failure.
998  */
999 static int
1000 txq_complete(struct txq *txq)
1001 {
1002         unsigned int elts_comp = txq->elts_comp;
1003         unsigned int elts_tail = txq->elts_tail;
1004         const unsigned int elts_n = txq->elts_n;
1005         int wcs_n;
1006
1007         if (unlikely(elts_comp == 0))
1008                 return 0;
1009 #ifdef DEBUG_SEND
1010         DEBUG("%p: processing %u work requests completions",
1011               (void *)txq, elts_comp);
1012 #endif
1013         wcs_n = txq->if_cq->poll_cnt(txq->cq, elts_comp);
1014         if (unlikely(wcs_n == 0))
1015                 return 0;
1016         if (unlikely(wcs_n < 0)) {
1017                 DEBUG("%p: ibv_poll_cq() failed (wcs_n=%d)",
1018                       (void *)txq, wcs_n);
1019                 return -1;
1020         }
1021         elts_comp -= wcs_n;
1022         assert(elts_comp <= txq->elts_comp);
1023         /*
1024          * Assume WC status is successful as nothing can be done about it
1025          * anyway.
1026          */
1027         elts_tail += wcs_n * txq->elts_comp_cd_init;
1028         if (elts_tail >= elts_n)
1029                 elts_tail -= elts_n;
1030         txq->elts_tail = elts_tail;
1031         txq->elts_comp = elts_comp;
1032         return 0;
1033 }
1034
1035 struct mlx4_check_mempool_data {
1036         int ret;
1037         char *start;
1038         char *end;
1039 };
1040
1041 /* Called by mlx4_check_mempool() when iterating the memory chunks. */
1042 static void mlx4_check_mempool_cb(struct rte_mempool *mp,
1043         void *opaque, struct rte_mempool_memhdr *memhdr,
1044         unsigned mem_idx)
1045 {
1046         struct mlx4_check_mempool_data *data = opaque;
1047
1048         (void)mp;
1049         (void)mem_idx;
1050
1051         /* It already failed, skip the next chunks. */
1052         if (data->ret != 0)
1053                 return;
1054         /* It is the first chunk. */
1055         if (data->start == NULL && data->end == NULL) {
1056                 data->start = memhdr->addr;
1057                 data->end = data->start + memhdr->len;
1058                 return;
1059         }
1060         if (data->end == memhdr->addr) {
1061                 data->end += memhdr->len;
1062                 return;
1063         }
1064         if (data->start == (char *)memhdr->addr + memhdr->len) {
1065                 data->start -= memhdr->len;
1066                 return;
1067         }
1068         /* Error, mempool is not virtually contigous. */
1069         data->ret = -1;
1070 }
1071
1072 /**
1073  * Check if a mempool can be used: it must be virtually contiguous.
1074  *
1075  * @param[in] mp
1076  *   Pointer to memory pool.
1077  * @param[out] start
1078  *   Pointer to the start address of the mempool virtual memory area
1079  * @param[out] end
1080  *   Pointer to the end address of the mempool virtual memory area
1081  *
1082  * @return
1083  *   0 on success (mempool is virtually contiguous), -1 on error.
1084  */
1085 static int mlx4_check_mempool(struct rte_mempool *mp, uintptr_t *start,
1086         uintptr_t *end)
1087 {
1088         struct mlx4_check_mempool_data data;
1089
1090         memset(&data, 0, sizeof(data));
1091         rte_mempool_mem_iter(mp, mlx4_check_mempool_cb, &data);
1092         *start = (uintptr_t)data.start;
1093         *end = (uintptr_t)data.end;
1094
1095         return data.ret;
1096 }
1097
1098 /* For best performance, this function should not be inlined. */
1099 static struct ibv_mr *mlx4_mp2mr(struct ibv_pd *, struct rte_mempool *)
1100         __attribute__((noinline));
1101
1102 /**
1103  * Register mempool as a memory region.
1104  *
1105  * @param pd
1106  *   Pointer to protection domain.
1107  * @param mp
1108  *   Pointer to memory pool.
1109  *
1110  * @return
1111  *   Memory region pointer, NULL in case of error.
1112  */
1113 static struct ibv_mr *
1114 mlx4_mp2mr(struct ibv_pd *pd, struct rte_mempool *mp)
1115 {
1116         const struct rte_memseg *ms = rte_eal_get_physmem_layout();
1117         uintptr_t start;
1118         uintptr_t end;
1119         unsigned int i;
1120
1121         if (mlx4_check_mempool(mp, &start, &end) != 0) {
1122                 ERROR("mempool %p: not virtually contiguous",
1123                         (void *)mp);
1124                 return NULL;
1125         }
1126
1127         DEBUG("mempool %p area start=%p end=%p size=%zu",
1128               (void *)mp, (void *)start, (void *)end,
1129               (size_t)(end - start));
1130         /* Round start and end to page boundary if found in memory segments. */
1131         for (i = 0; (i < RTE_MAX_MEMSEG) && (ms[i].addr != NULL); ++i) {
1132                 uintptr_t addr = (uintptr_t)ms[i].addr;
1133                 size_t len = ms[i].len;
1134                 unsigned int align = ms[i].hugepage_sz;
1135
1136                 if ((start > addr) && (start < addr + len))
1137                         start = RTE_ALIGN_FLOOR(start, align);
1138                 if ((end > addr) && (end < addr + len))
1139                         end = RTE_ALIGN_CEIL(end, align);
1140         }
1141         DEBUG("mempool %p using start=%p end=%p size=%zu for MR",
1142               (void *)mp, (void *)start, (void *)end,
1143               (size_t)(end - start));
1144         return ibv_reg_mr(pd,
1145                           (void *)start,
1146                           end - start,
1147                           IBV_ACCESS_LOCAL_WRITE);
1148 }
1149
1150 /**
1151  * Get Memory Pool (MP) from mbuf. If mbuf is indirect, the pool from which
1152  * the cloned mbuf is allocated is returned instead.
1153  *
1154  * @param buf
1155  *   Pointer to mbuf.
1156  *
1157  * @return
1158  *   Memory pool where data is located for given mbuf.
1159  */
1160 static struct rte_mempool *
1161 txq_mb2mp(struct rte_mbuf *buf)
1162 {
1163         if (unlikely(RTE_MBUF_INDIRECT(buf)))
1164                 return rte_mbuf_from_indirect(buf)->pool;
1165         return buf->pool;
1166 }
1167
1168 /**
1169  * Get Memory Region (MR) <-> Memory Pool (MP) association from txq->mp2mr[].
1170  * Add MP to txq->mp2mr[] if it's not registered yet. If mp2mr[] is full,
1171  * remove an entry first.
1172  *
1173  * @param txq
1174  *   Pointer to TX queue structure.
1175  * @param[in] mp
1176  *   Memory Pool for which a Memory Region lkey must be returned.
1177  *
1178  * @return
1179  *   mr->lkey on success, (uint32_t)-1 on failure.
1180  */
1181 static uint32_t
1182 txq_mp2mr(struct txq *txq, struct rte_mempool *mp)
1183 {
1184         unsigned int i;
1185         struct ibv_mr *mr;
1186
1187         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
1188                 if (unlikely(txq->mp2mr[i].mp == NULL)) {
1189                         /* Unknown MP, add a new MR for it. */
1190                         break;
1191                 }
1192                 if (txq->mp2mr[i].mp == mp) {
1193                         assert(txq->mp2mr[i].lkey != (uint32_t)-1);
1194                         assert(txq->mp2mr[i].mr->lkey == txq->mp2mr[i].lkey);
1195                         return txq->mp2mr[i].lkey;
1196                 }
1197         }
1198         /* Add a new entry, register MR first. */
1199         DEBUG("%p: discovered new memory pool \"%s\" (%p)",
1200               (void *)txq, mp->name, (void *)mp);
1201         mr = mlx4_mp2mr(txq->priv->pd, mp);
1202         if (unlikely(mr == NULL)) {
1203                 DEBUG("%p: unable to configure MR, ibv_reg_mr() failed.",
1204                       (void *)txq);
1205                 return (uint32_t)-1;
1206         }
1207         if (unlikely(i == elemof(txq->mp2mr))) {
1208                 /* Table is full, remove oldest entry. */
1209                 DEBUG("%p: MR <-> MP table full, dropping oldest entry.",
1210                       (void *)txq);
1211                 --i;
1212                 claim_zero(ibv_dereg_mr(txq->mp2mr[0].mr));
1213                 memmove(&txq->mp2mr[0], &txq->mp2mr[1],
1214                         (sizeof(txq->mp2mr) - sizeof(txq->mp2mr[0])));
1215         }
1216         /* Store the new entry. */
1217         txq->mp2mr[i].mp = mp;
1218         txq->mp2mr[i].mr = mr;
1219         txq->mp2mr[i].lkey = mr->lkey;
1220         DEBUG("%p: new MR lkey for MP \"%s\" (%p): 0x%08" PRIu32,
1221               (void *)txq, mp->name, (void *)mp, txq->mp2mr[i].lkey);
1222         return txq->mp2mr[i].lkey;
1223 }
1224
1225 struct txq_mp2mr_mbuf_check_data {
1226         int ret;
1227 };
1228
1229 /**
1230  * Callback function for rte_mempool_obj_iter() to check whether a given
1231  * mempool object looks like a mbuf.
1232  *
1233  * @param[in] mp
1234  *   The mempool pointer
1235  * @param[in] arg
1236  *   Context data (struct txq_mp2mr_mbuf_check_data). Contains the
1237  *   return value.
1238  * @param[in] obj
1239  *   Object address.
1240  * @param index
1241  *   Object index, unused.
1242  */
1243 static void
1244 txq_mp2mr_mbuf_check(struct rte_mempool *mp, void *arg, void *obj,
1245         uint32_t index __rte_unused)
1246 {
1247         struct txq_mp2mr_mbuf_check_data *data = arg;
1248         struct rte_mbuf *buf = obj;
1249
1250         /* Check whether mbuf structure fits element size and whether mempool
1251          * pointer is valid. */
1252         if (sizeof(*buf) > mp->elt_size || buf->pool != mp)
1253                 data->ret = -1;
1254 }
1255
1256 /**
1257  * Iterator function for rte_mempool_walk() to register existing mempools and
1258  * fill the MP to MR cache of a TX queue.
1259  *
1260  * @param[in] mp
1261  *   Memory Pool to register.
1262  * @param *arg
1263  *   Pointer to TX queue structure.
1264  */
1265 static void
1266 txq_mp2mr_iter(struct rte_mempool *mp, void *arg)
1267 {
1268         struct txq *txq = arg;
1269         struct txq_mp2mr_mbuf_check_data data = {
1270                 .ret = 0,
1271         };
1272
1273         /* Register mempool only if the first element looks like a mbuf. */
1274         if (rte_mempool_obj_iter(mp, txq_mp2mr_mbuf_check, &data) == 0 ||
1275                         data.ret == -1)
1276                 return;
1277         txq_mp2mr(txq, mp);
1278 }
1279
1280 #if MLX4_PMD_SGE_WR_N > 1
1281
1282 /**
1283  * Copy scattered mbuf contents to a single linear buffer.
1284  *
1285  * @param[out] linear
1286  *   Linear output buffer.
1287  * @param[in] buf
1288  *   Scattered input buffer.
1289  *
1290  * @return
1291  *   Number of bytes copied to the output buffer or 0 if not large enough.
1292  */
1293 static unsigned int
1294 linearize_mbuf(linear_t *linear, struct rte_mbuf *buf)
1295 {
1296         unsigned int size = 0;
1297         unsigned int offset;
1298
1299         do {
1300                 unsigned int len = DATA_LEN(buf);
1301
1302                 offset = size;
1303                 size += len;
1304                 if (unlikely(size > sizeof(*linear)))
1305                         return 0;
1306                 memcpy(&(*linear)[offset],
1307                        rte_pktmbuf_mtod(buf, uint8_t *),
1308                        len);
1309                 buf = NEXT(buf);
1310         } while (buf != NULL);
1311         return size;
1312 }
1313
1314 /**
1315  * Handle scattered buffers for mlx4_tx_burst().
1316  *
1317  * @param txq
1318  *   TX queue structure.
1319  * @param segs
1320  *   Number of segments in buf.
1321  * @param elt
1322  *   TX queue element to fill.
1323  * @param[in] buf
1324  *   Buffer to process.
1325  * @param elts_head
1326  *   Index of the linear buffer to use if necessary (normally txq->elts_head).
1327  * @param[out] sges
1328  *   Array filled with SGEs on success.
1329  *
1330  * @return
1331  *   A structure containing the processed packet size in bytes and the
1332  *   number of SGEs. Both fields are set to (unsigned int)-1 in case of
1333  *   failure.
1334  */
1335 static struct tx_burst_sg_ret {
1336         unsigned int length;
1337         unsigned int num;
1338 }
1339 tx_burst_sg(struct txq *txq, unsigned int segs, struct txq_elt *elt,
1340             struct rte_mbuf *buf, unsigned int elts_head,
1341             struct ibv_sge (*sges)[MLX4_PMD_SGE_WR_N])
1342 {
1343         unsigned int sent_size = 0;
1344         unsigned int j;
1345         int linearize = 0;
1346
1347         /* When there are too many segments, extra segments are
1348          * linearized in the last SGE. */
1349         if (unlikely(segs > elemof(*sges))) {
1350                 segs = (elemof(*sges) - 1);
1351                 linearize = 1;
1352         }
1353         /* Update element. */
1354         elt->buf = buf;
1355         /* Register segments as SGEs. */
1356         for (j = 0; (j != segs); ++j) {
1357                 struct ibv_sge *sge = &(*sges)[j];
1358                 uint32_t lkey;
1359
1360                 /* Retrieve Memory Region key for this memory pool. */
1361                 lkey = txq_mp2mr(txq, txq_mb2mp(buf));
1362                 if (unlikely(lkey == (uint32_t)-1)) {
1363                         /* MR does not exist. */
1364                         DEBUG("%p: unable to get MP <-> MR association",
1365                               (void *)txq);
1366                         /* Clean up TX element. */
1367                         elt->buf = NULL;
1368                         goto stop;
1369                 }
1370                 /* Update SGE. */
1371                 sge->addr = rte_pktmbuf_mtod(buf, uintptr_t);
1372                 if (txq->priv->vf)
1373                         rte_prefetch0((volatile void *)
1374                                       (uintptr_t)sge->addr);
1375                 sge->length = DATA_LEN(buf);
1376                 sge->lkey = lkey;
1377                 sent_size += sge->length;
1378                 buf = NEXT(buf);
1379         }
1380         /* If buf is not NULL here and is not going to be linearized,
1381          * nb_segs is not valid. */
1382         assert(j == segs);
1383         assert((buf == NULL) || (linearize));
1384         /* Linearize extra segments. */
1385         if (linearize) {
1386                 struct ibv_sge *sge = &(*sges)[segs];
1387                 linear_t *linear = &(*txq->elts_linear)[elts_head];
1388                 unsigned int size = linearize_mbuf(linear, buf);
1389
1390                 assert(segs == (elemof(*sges) - 1));
1391                 if (size == 0) {
1392                         /* Invalid packet. */
1393                         DEBUG("%p: packet too large to be linearized.",
1394                               (void *)txq);
1395                         /* Clean up TX element. */
1396                         elt->buf = NULL;
1397                         goto stop;
1398                 }
1399                 /* If MLX4_PMD_SGE_WR_N is 1, free mbuf immediately. */
1400                 if (elemof(*sges) == 1) {
1401                         do {
1402                                 struct rte_mbuf *next = NEXT(buf);
1403
1404                                 rte_pktmbuf_free_seg(buf);
1405                                 buf = next;
1406                         } while (buf != NULL);
1407                         elt->buf = NULL;
1408                 }
1409                 /* Update SGE. */
1410                 sge->addr = (uintptr_t)&(*linear)[0];
1411                 sge->length = size;
1412                 sge->lkey = txq->mr_linear->lkey;
1413                 sent_size += size;
1414                 /* Include last segment. */
1415                 segs++;
1416         }
1417         return (struct tx_burst_sg_ret){
1418                 .length = sent_size,
1419                 .num = segs,
1420         };
1421 stop:
1422         return (struct tx_burst_sg_ret){
1423                 .length = -1,
1424                 .num = -1,
1425         };
1426 }
1427
1428 #endif /* MLX4_PMD_SGE_WR_N > 1 */
1429
1430 /**
1431  * DPDK callback for TX.
1432  *
1433  * @param dpdk_txq
1434  *   Generic pointer to TX queue structure.
1435  * @param[in] pkts
1436  *   Packets to transmit.
1437  * @param pkts_n
1438  *   Number of packets in array.
1439  *
1440  * @return
1441  *   Number of packets successfully transmitted (<= pkts_n).
1442  */
1443 static uint16_t
1444 mlx4_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
1445 {
1446         struct txq *txq = (struct txq *)dpdk_txq;
1447         unsigned int elts_head = txq->elts_head;
1448         const unsigned int elts_n = txq->elts_n;
1449         unsigned int elts_comp_cd = txq->elts_comp_cd;
1450         unsigned int elts_comp = 0;
1451         unsigned int i;
1452         unsigned int max;
1453         int err;
1454
1455         assert(elts_comp_cd != 0);
1456         txq_complete(txq);
1457         max = (elts_n - (elts_head - txq->elts_tail));
1458         if (max > elts_n)
1459                 max -= elts_n;
1460         assert(max >= 1);
1461         assert(max <= elts_n);
1462         /* Always leave one free entry in the ring. */
1463         --max;
1464         if (max == 0)
1465                 return 0;
1466         if (max > pkts_n)
1467                 max = pkts_n;
1468         for (i = 0; (i != max); ++i) {
1469                 struct rte_mbuf *buf = pkts[i];
1470                 unsigned int elts_head_next =
1471                         (((elts_head + 1) == elts_n) ? 0 : elts_head + 1);
1472                 struct txq_elt *elt_next = &(*txq->elts)[elts_head_next];
1473                 struct txq_elt *elt = &(*txq->elts)[elts_head];
1474                 unsigned int segs = NB_SEGS(buf);
1475 #ifdef MLX4_PMD_SOFT_COUNTERS
1476                 unsigned int sent_size = 0;
1477 #endif
1478                 uint32_t send_flags = 0;
1479
1480                 /* Clean up old buffer. */
1481                 if (likely(elt->buf != NULL)) {
1482                         struct rte_mbuf *tmp = elt->buf;
1483
1484 #ifndef NDEBUG
1485                         /* Poisoning. */
1486                         memset(elt, 0x66, sizeof(*elt));
1487 #endif
1488                         /* Faster than rte_pktmbuf_free(). */
1489                         do {
1490                                 struct rte_mbuf *next = NEXT(tmp);
1491
1492                                 rte_pktmbuf_free_seg(tmp);
1493                                 tmp = next;
1494                         } while (tmp != NULL);
1495                 }
1496                 /* Request TX completion. */
1497                 if (unlikely(--elts_comp_cd == 0)) {
1498                         elts_comp_cd = txq->elts_comp_cd_init;
1499                         ++elts_comp;
1500                         send_flags |= IBV_EXP_QP_BURST_SIGNALED;
1501                 }
1502                 /* Should we enable HW CKSUM offload */
1503                 if (buf->ol_flags &
1504                     (PKT_TX_IP_CKSUM | PKT_TX_TCP_CKSUM | PKT_TX_UDP_CKSUM)) {
1505                         send_flags |= IBV_EXP_QP_BURST_IP_CSUM;
1506                         /* HW does not support checksum offloads at arbitrary
1507                          * offsets but automatically recognizes the packet
1508                          * type. For inner L3/L4 checksums, only VXLAN (UDP)
1509                          * tunnels are currently supported. */
1510                         if (RTE_ETH_IS_TUNNEL_PKT(buf->packet_type))
1511                                 send_flags |= IBV_EXP_QP_BURST_TUNNEL;
1512                 }
1513                 if (likely(segs == 1)) {
1514                         uintptr_t addr;
1515                         uint32_t length;
1516                         uint32_t lkey;
1517
1518                         /* Retrieve buffer information. */
1519                         addr = rte_pktmbuf_mtod(buf, uintptr_t);
1520                         length = DATA_LEN(buf);
1521                         /* Retrieve Memory Region key for this memory pool. */
1522                         lkey = txq_mp2mr(txq, txq_mb2mp(buf));
1523                         if (unlikely(lkey == (uint32_t)-1)) {
1524                                 /* MR does not exist. */
1525                                 DEBUG("%p: unable to get MP <-> MR"
1526                                       " association", (void *)txq);
1527                                 /* Clean up TX element. */
1528                                 elt->buf = NULL;
1529                                 goto stop;
1530                         }
1531                         /* Update element. */
1532                         elt->buf = buf;
1533                         if (txq->priv->vf)
1534                                 rte_prefetch0((volatile void *)
1535                                               (uintptr_t)addr);
1536                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1537                         /* Put packet into send queue. */
1538 #if MLX4_PMD_MAX_INLINE > 0
1539                         if (length <= txq->max_inline)
1540                                 err = txq->if_qp->send_pending_inline
1541                                         (txq->qp,
1542                                          (void *)addr,
1543                                          length,
1544                                          send_flags);
1545                         else
1546 #endif
1547                                 err = txq->if_qp->send_pending
1548                                         (txq->qp,
1549                                          addr,
1550                                          length,
1551                                          lkey,
1552                                          send_flags);
1553                         if (unlikely(err))
1554                                 goto stop;
1555 #ifdef MLX4_PMD_SOFT_COUNTERS
1556                         sent_size += length;
1557 #endif
1558                 } else {
1559 #if MLX4_PMD_SGE_WR_N > 1
1560                         struct ibv_sge sges[MLX4_PMD_SGE_WR_N];
1561                         struct tx_burst_sg_ret ret;
1562
1563                         ret = tx_burst_sg(txq, segs, elt, buf, elts_head,
1564                                           &sges);
1565                         if (ret.length == (unsigned int)-1)
1566                                 goto stop;
1567                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1568                         /* Put SG list into send queue. */
1569                         err = txq->if_qp->send_pending_sg_list
1570                                 (txq->qp,
1571                                  sges,
1572                                  ret.num,
1573                                  send_flags);
1574                         if (unlikely(err))
1575                                 goto stop;
1576 #ifdef MLX4_PMD_SOFT_COUNTERS
1577                         sent_size += ret.length;
1578 #endif
1579 #else /* MLX4_PMD_SGE_WR_N > 1 */
1580                         DEBUG("%p: TX scattered buffers support not"
1581                               " compiled in", (void *)txq);
1582                         goto stop;
1583 #endif /* MLX4_PMD_SGE_WR_N > 1 */
1584                 }
1585                 elts_head = elts_head_next;
1586 #ifdef MLX4_PMD_SOFT_COUNTERS
1587                 /* Increment sent bytes counter. */
1588                 txq->stats.obytes += sent_size;
1589 #endif
1590         }
1591 stop:
1592         /* Take a shortcut if nothing must be sent. */
1593         if (unlikely(i == 0))
1594                 return 0;
1595 #ifdef MLX4_PMD_SOFT_COUNTERS
1596         /* Increment sent packets counter. */
1597         txq->stats.opackets += i;
1598 #endif
1599         /* Ring QP doorbell. */
1600         err = txq->if_qp->send_flush(txq->qp);
1601         if (unlikely(err)) {
1602                 /* A nonzero value is not supposed to be returned.
1603                  * Nothing can be done about it. */
1604                 DEBUG("%p: send_flush() failed with error %d",
1605                       (void *)txq, err);
1606         }
1607         txq->elts_head = elts_head;
1608         txq->elts_comp += elts_comp;
1609         txq->elts_comp_cd = elts_comp_cd;
1610         return i;
1611 }
1612
1613 /**
1614  * DPDK callback for TX in secondary processes.
1615  *
1616  * This function configures all queues from primary process information
1617  * if necessary before reverting to the normal TX burst callback.
1618  *
1619  * @param dpdk_txq
1620  *   Generic pointer to TX queue structure.
1621  * @param[in] pkts
1622  *   Packets to transmit.
1623  * @param pkts_n
1624  *   Number of packets in array.
1625  *
1626  * @return
1627  *   Number of packets successfully transmitted (<= pkts_n).
1628  */
1629 static uint16_t
1630 mlx4_tx_burst_secondary_setup(void *dpdk_txq, struct rte_mbuf **pkts,
1631                               uint16_t pkts_n)
1632 {
1633         struct txq *txq = dpdk_txq;
1634         struct priv *priv = mlx4_secondary_data_setup(txq->priv);
1635         struct priv *primary_priv;
1636         unsigned int index;
1637
1638         if (priv == NULL)
1639                 return 0;
1640         primary_priv =
1641                 mlx4_secondary_data[priv->dev->data->port_id].primary_priv;
1642         /* Look for queue index in both private structures. */
1643         for (index = 0; index != priv->txqs_n; ++index)
1644                 if (((*primary_priv->txqs)[index] == txq) ||
1645                     ((*priv->txqs)[index] == txq))
1646                         break;
1647         if (index == priv->txqs_n)
1648                 return 0;
1649         txq = (*priv->txqs)[index];
1650         return priv->dev->tx_pkt_burst(txq, pkts, pkts_n);
1651 }
1652
1653 /**
1654  * Configure a TX queue.
1655  *
1656  * @param dev
1657  *   Pointer to Ethernet device structure.
1658  * @param txq
1659  *   Pointer to TX queue structure.
1660  * @param desc
1661  *   Number of descriptors to configure in queue.
1662  * @param socket
1663  *   NUMA socket on which memory must be allocated.
1664  * @param[in] conf
1665  *   Thresholds parameters.
1666  *
1667  * @return
1668  *   0 on success, errno value on failure.
1669  */
1670 static int
1671 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
1672           unsigned int socket, const struct rte_eth_txconf *conf)
1673 {
1674         struct priv *priv = mlx4_get_priv(dev);
1675         struct txq tmpl = {
1676                 .priv = priv,
1677                 .socket = socket
1678         };
1679         union {
1680                 struct ibv_exp_query_intf_params params;
1681                 struct ibv_exp_qp_init_attr init;
1682                 struct ibv_exp_res_domain_init_attr rd;
1683                 struct ibv_exp_cq_init_attr cq;
1684                 struct ibv_exp_qp_attr mod;
1685         } attr;
1686         enum ibv_exp_query_intf_status status;
1687         int ret = 0;
1688
1689         (void)conf; /* Thresholds configuration (ignored). */
1690         if (priv == NULL)
1691                 return EINVAL;
1692         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
1693                 ERROR("%p: invalid number of TX descriptors (must be a"
1694                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
1695                 return EINVAL;
1696         }
1697         desc /= MLX4_PMD_SGE_WR_N;
1698         /* MRs will be registered in mp2mr[] later. */
1699         attr.rd = (struct ibv_exp_res_domain_init_attr){
1700                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
1701                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
1702                 .thread_model = IBV_EXP_THREAD_SINGLE,
1703                 .msg_model = IBV_EXP_MSG_HIGH_BW,
1704         };
1705         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
1706         if (tmpl.rd == NULL) {
1707                 ret = ENOMEM;
1708                 ERROR("%p: RD creation failure: %s",
1709                       (void *)dev, strerror(ret));
1710                 goto error;
1711         }
1712         attr.cq = (struct ibv_exp_cq_init_attr){
1713                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
1714                 .res_domain = tmpl.rd,
1715         };
1716         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
1717         if (tmpl.cq == NULL) {
1718                 ret = ENOMEM;
1719                 ERROR("%p: CQ creation failure: %s",
1720                       (void *)dev, strerror(ret));
1721                 goto error;
1722         }
1723         DEBUG("priv->device_attr.max_qp_wr is %d",
1724               priv->device_attr.max_qp_wr);
1725         DEBUG("priv->device_attr.max_sge is %d",
1726               priv->device_attr.max_sge);
1727         attr.init = (struct ibv_exp_qp_init_attr){
1728                 /* CQ to be associated with the send queue. */
1729                 .send_cq = tmpl.cq,
1730                 /* CQ to be associated with the receive queue. */
1731                 .recv_cq = tmpl.cq,
1732                 .cap = {
1733                         /* Max number of outstanding WRs. */
1734                         .max_send_wr = ((priv->device_attr.max_qp_wr < desc) ?
1735                                         priv->device_attr.max_qp_wr :
1736                                         desc),
1737                         /* Max number of scatter/gather elements in a WR. */
1738                         .max_send_sge = ((priv->device_attr.max_sge <
1739                                           MLX4_PMD_SGE_WR_N) ?
1740                                          priv->device_attr.max_sge :
1741                                          MLX4_PMD_SGE_WR_N),
1742 #if MLX4_PMD_MAX_INLINE > 0
1743                         .max_inline_data = MLX4_PMD_MAX_INLINE,
1744 #endif
1745                 },
1746                 .qp_type = IBV_QPT_RAW_PACKET,
1747                 /* Do *NOT* enable this, completions events are managed per
1748                  * TX burst. */
1749                 .sq_sig_all = 0,
1750                 .pd = priv->pd,
1751                 .res_domain = tmpl.rd,
1752                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
1753                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
1754         };
1755         tmpl.qp = ibv_exp_create_qp(priv->ctx, &attr.init);
1756         if (tmpl.qp == NULL) {
1757                 ret = (errno ? errno : EINVAL);
1758                 ERROR("%p: QP creation failure: %s",
1759                       (void *)dev, strerror(ret));
1760                 goto error;
1761         }
1762 #if MLX4_PMD_MAX_INLINE > 0
1763         /* ibv_create_qp() updates this value. */
1764         tmpl.max_inline = attr.init.cap.max_inline_data;
1765 #endif
1766         attr.mod = (struct ibv_exp_qp_attr){
1767                 /* Move the QP to this state. */
1768                 .qp_state = IBV_QPS_INIT,
1769                 /* Primary port number. */
1770                 .port_num = priv->port
1771         };
1772         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod,
1773                                 (IBV_EXP_QP_STATE | IBV_EXP_QP_PORT));
1774         if (ret) {
1775                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1776                       (void *)dev, strerror(ret));
1777                 goto error;
1778         }
1779         ret = txq_alloc_elts(&tmpl, desc);
1780         if (ret) {
1781                 ERROR("%p: TXQ allocation failed: %s",
1782                       (void *)dev, strerror(ret));
1783                 goto error;
1784         }
1785         attr.mod = (struct ibv_exp_qp_attr){
1786                 .qp_state = IBV_QPS_RTR
1787         };
1788         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1789         if (ret) {
1790                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1791                       (void *)dev, strerror(ret));
1792                 goto error;
1793         }
1794         attr.mod.qp_state = IBV_QPS_RTS;
1795         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1796         if (ret) {
1797                 ERROR("%p: QP state to IBV_QPS_RTS failed: %s",
1798                       (void *)dev, strerror(ret));
1799                 goto error;
1800         }
1801         attr.params = (struct ibv_exp_query_intf_params){
1802                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1803                 .intf = IBV_EXP_INTF_CQ,
1804                 .obj = tmpl.cq,
1805         };
1806         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1807         if (tmpl.if_cq == NULL) {
1808                 ERROR("%p: CQ interface family query failed with status %d",
1809                       (void *)dev, status);
1810                 goto error;
1811         }
1812         attr.params = (struct ibv_exp_query_intf_params){
1813                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1814                 .intf = IBV_EXP_INTF_QP_BURST,
1815                 .obj = tmpl.qp,
1816 #ifdef HAVE_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK
1817                 /* MC loopback must be disabled when not using a VF. */
1818                 .family_flags =
1819                         (!priv->vf ?
1820                          IBV_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK :
1821                          0),
1822 #endif
1823         };
1824         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1825         if (tmpl.if_qp == NULL) {
1826                 ERROR("%p: QP interface family query failed with status %d",
1827                       (void *)dev, status);
1828                 goto error;
1829         }
1830         /* Clean up txq in case we're reinitializing it. */
1831         DEBUG("%p: cleaning-up old txq just in case", (void *)txq);
1832         txq_cleanup(txq);
1833         *txq = tmpl;
1834         DEBUG("%p: txq updated with %p", (void *)txq, (void *)&tmpl);
1835         /* Pre-register known mempools. */
1836         rte_mempool_walk(txq_mp2mr_iter, txq);
1837         assert(ret == 0);
1838         return 0;
1839 error:
1840         txq_cleanup(&tmpl);
1841         assert(ret > 0);
1842         return ret;
1843 }
1844
1845 /**
1846  * DPDK callback to configure a TX queue.
1847  *
1848  * @param dev
1849  *   Pointer to Ethernet device structure.
1850  * @param idx
1851  *   TX queue index.
1852  * @param desc
1853  *   Number of descriptors to configure in queue.
1854  * @param socket
1855  *   NUMA socket on which memory must be allocated.
1856  * @param[in] conf
1857  *   Thresholds parameters.
1858  *
1859  * @return
1860  *   0 on success, negative errno value on failure.
1861  */
1862 static int
1863 mlx4_tx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1864                     unsigned int socket, const struct rte_eth_txconf *conf)
1865 {
1866         struct priv *priv = dev->data->dev_private;
1867         struct txq *txq = (*priv->txqs)[idx];
1868         int ret;
1869
1870         if (mlx4_is_secondary())
1871                 return -E_RTE_SECONDARY;
1872         priv_lock(priv);
1873         DEBUG("%p: configuring queue %u for %u descriptors",
1874               (void *)dev, idx, desc);
1875         if (idx >= priv->txqs_n) {
1876                 ERROR("%p: queue index out of range (%u >= %u)",
1877                       (void *)dev, idx, priv->txqs_n);
1878                 priv_unlock(priv);
1879                 return -EOVERFLOW;
1880         }
1881         if (txq != NULL) {
1882                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1883                       (void *)dev, idx, (void *)txq);
1884                 if (priv->started) {
1885                         priv_unlock(priv);
1886                         return -EEXIST;
1887                 }
1888                 (*priv->txqs)[idx] = NULL;
1889                 txq_cleanup(txq);
1890         } else {
1891                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0, socket);
1892                 if (txq == NULL) {
1893                         ERROR("%p: unable to allocate queue index %u",
1894                               (void *)dev, idx);
1895                         priv_unlock(priv);
1896                         return -ENOMEM;
1897                 }
1898         }
1899         ret = txq_setup(dev, txq, desc, socket, conf);
1900         if (ret)
1901                 rte_free(txq);
1902         else {
1903                 txq->stats.idx = idx;
1904                 DEBUG("%p: adding TX queue %p to list",
1905                       (void *)dev, (void *)txq);
1906                 (*priv->txqs)[idx] = txq;
1907                 /* Update send callback. */
1908                 dev->tx_pkt_burst = mlx4_tx_burst;
1909         }
1910         priv_unlock(priv);
1911         return -ret;
1912 }
1913
1914 /**
1915  * DPDK callback to release a TX queue.
1916  *
1917  * @param dpdk_txq
1918  *   Generic TX queue pointer.
1919  */
1920 static void
1921 mlx4_tx_queue_release(void *dpdk_txq)
1922 {
1923         struct txq *txq = (struct txq *)dpdk_txq;
1924         struct priv *priv;
1925         unsigned int i;
1926
1927         if (mlx4_is_secondary())
1928                 return;
1929         if (txq == NULL)
1930                 return;
1931         priv = txq->priv;
1932         priv_lock(priv);
1933         for (i = 0; (i != priv->txqs_n); ++i)
1934                 if ((*priv->txqs)[i] == txq) {
1935                         DEBUG("%p: removing TX queue %p from list",
1936                               (void *)priv->dev, (void *)txq);
1937                         (*priv->txqs)[i] = NULL;
1938                         break;
1939                 }
1940         txq_cleanup(txq);
1941         rte_free(txq);
1942         priv_unlock(priv);
1943 }
1944
1945 /* RX queues handling. */
1946
1947 /**
1948  * Allocate RX queue elements with scattered packets support.
1949  *
1950  * @param rxq
1951  *   Pointer to RX queue structure.
1952  * @param elts_n
1953  *   Number of elements to allocate.
1954  * @param[in] pool
1955  *   If not NULL, fetch buffers from this array instead of allocating them
1956  *   with rte_pktmbuf_alloc().
1957  *
1958  * @return
1959  *   0 on success, errno value on failure.
1960  */
1961 static int
1962 rxq_alloc_elts_sp(struct rxq *rxq, unsigned int elts_n,
1963                   struct rte_mbuf **pool)
1964 {
1965         unsigned int i;
1966         struct rxq_elt_sp (*elts)[elts_n] =
1967                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1968                                   rxq->socket);
1969         int ret = 0;
1970
1971         if (elts == NULL) {
1972                 ERROR("%p: can't allocate packets array", (void *)rxq);
1973                 ret = ENOMEM;
1974                 goto error;
1975         }
1976         /* For each WR (packet). */
1977         for (i = 0; (i != elts_n); ++i) {
1978                 unsigned int j;
1979                 struct rxq_elt_sp *elt = &(*elts)[i];
1980                 struct ibv_recv_wr *wr = &elt->wr;
1981                 struct ibv_sge (*sges)[(elemof(elt->sges))] = &elt->sges;
1982
1983                 /* These two arrays must have the same size. */
1984                 assert(elemof(elt->sges) == elemof(elt->bufs));
1985                 /* Configure WR. */
1986                 wr->wr_id = i;
1987                 wr->next = &(*elts)[(i + 1)].wr;
1988                 wr->sg_list = &(*sges)[0];
1989                 wr->num_sge = elemof(*sges);
1990                 /* For each SGE (segment). */
1991                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
1992                         struct ibv_sge *sge = &(*sges)[j];
1993                         struct rte_mbuf *buf;
1994
1995                         if (pool != NULL) {
1996                                 buf = *(pool++);
1997                                 assert(buf != NULL);
1998                                 rte_pktmbuf_reset(buf);
1999                         } else
2000                                 buf = rte_pktmbuf_alloc(rxq->mp);
2001                         if (buf == NULL) {
2002                                 assert(pool == NULL);
2003                                 ERROR("%p: empty mbuf pool", (void *)rxq);
2004                                 ret = ENOMEM;
2005                                 goto error;
2006                         }
2007                         elt->bufs[j] = buf;
2008                         /* Headroom is reserved by rte_pktmbuf_alloc(). */
2009                         assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
2010                         /* Buffer is supposed to be empty. */
2011                         assert(rte_pktmbuf_data_len(buf) == 0);
2012                         assert(rte_pktmbuf_pkt_len(buf) == 0);
2013                         /* sge->addr must be able to store a pointer. */
2014                         assert(sizeof(sge->addr) >= sizeof(uintptr_t));
2015                         if (j == 0) {
2016                                 /* The first SGE keeps its headroom. */
2017                                 sge->addr = rte_pktmbuf_mtod(buf, uintptr_t);
2018                                 sge->length = (buf->buf_len -
2019                                                RTE_PKTMBUF_HEADROOM);
2020                         } else {
2021                                 /* Subsequent SGEs lose theirs. */
2022                                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
2023                                 SET_DATA_OFF(buf, 0);
2024                                 sge->addr = (uintptr_t)buf->buf_addr;
2025                                 sge->length = buf->buf_len;
2026                         }
2027                         sge->lkey = rxq->mr->lkey;
2028                         /* Redundant check for tailroom. */
2029                         assert(sge->length == rte_pktmbuf_tailroom(buf));
2030                 }
2031         }
2032         /* The last WR pointer must be NULL. */
2033         (*elts)[(i - 1)].wr.next = NULL;
2034         DEBUG("%p: allocated and configured %u WRs (%zu segments)",
2035               (void *)rxq, elts_n, (elts_n * elemof((*elts)[0].sges)));
2036         rxq->elts_n = elts_n;
2037         rxq->elts_head = 0;
2038         rxq->elts.sp = elts;
2039         assert(ret == 0);
2040         return 0;
2041 error:
2042         if (elts != NULL) {
2043                 assert(pool == NULL);
2044                 for (i = 0; (i != elemof(*elts)); ++i) {
2045                         unsigned int j;
2046                         struct rxq_elt_sp *elt = &(*elts)[i];
2047
2048                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
2049                                 struct rte_mbuf *buf = elt->bufs[j];
2050
2051                                 if (buf != NULL)
2052                                         rte_pktmbuf_free_seg(buf);
2053                         }
2054                 }
2055                 rte_free(elts);
2056         }
2057         DEBUG("%p: failed, freed everything", (void *)rxq);
2058         assert(ret > 0);
2059         return ret;
2060 }
2061
2062 /**
2063  * Free RX queue elements with scattered packets support.
2064  *
2065  * @param rxq
2066  *   Pointer to RX queue structure.
2067  */
2068 static void
2069 rxq_free_elts_sp(struct rxq *rxq)
2070 {
2071         unsigned int i;
2072         unsigned int elts_n = rxq->elts_n;
2073         struct rxq_elt_sp (*elts)[elts_n] = rxq->elts.sp;
2074
2075         DEBUG("%p: freeing WRs", (void *)rxq);
2076         rxq->elts_n = 0;
2077         rxq->elts.sp = NULL;
2078         if (elts == NULL)
2079                 return;
2080         for (i = 0; (i != elemof(*elts)); ++i) {
2081                 unsigned int j;
2082                 struct rxq_elt_sp *elt = &(*elts)[i];
2083
2084                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
2085                         struct rte_mbuf *buf = elt->bufs[j];
2086
2087                         if (buf != NULL)
2088                                 rte_pktmbuf_free_seg(buf);
2089                 }
2090         }
2091         rte_free(elts);
2092 }
2093
2094 /**
2095  * Allocate RX queue elements.
2096  *
2097  * @param rxq
2098  *   Pointer to RX queue structure.
2099  * @param elts_n
2100  *   Number of elements to allocate.
2101  * @param[in] pool
2102  *   If not NULL, fetch buffers from this array instead of allocating them
2103  *   with rte_pktmbuf_alloc().
2104  *
2105  * @return
2106  *   0 on success, errno value on failure.
2107  */
2108 static int
2109 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n, struct rte_mbuf **pool)
2110 {
2111         unsigned int i;
2112         struct rxq_elt (*elts)[elts_n] =
2113                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
2114                                   rxq->socket);
2115         int ret = 0;
2116
2117         if (elts == NULL) {
2118                 ERROR("%p: can't allocate packets array", (void *)rxq);
2119                 ret = ENOMEM;
2120                 goto error;
2121         }
2122         /* For each WR (packet). */
2123         for (i = 0; (i != elts_n); ++i) {
2124                 struct rxq_elt *elt = &(*elts)[i];
2125                 struct ibv_recv_wr *wr = &elt->wr;
2126                 struct ibv_sge *sge = &(*elts)[i].sge;
2127                 struct rte_mbuf *buf;
2128
2129                 if (pool != NULL) {
2130                         buf = *(pool++);
2131                         assert(buf != NULL);
2132                         rte_pktmbuf_reset(buf);
2133                 } else
2134                         buf = rte_pktmbuf_alloc(rxq->mp);
2135                 if (buf == NULL) {
2136                         assert(pool == NULL);
2137                         ERROR("%p: empty mbuf pool", (void *)rxq);
2138                         ret = ENOMEM;
2139                         goto error;
2140                 }
2141                 /* Configure WR. Work request ID contains its own index in
2142                  * the elts array and the offset between SGE buffer header and
2143                  * its data. */
2144                 WR_ID(wr->wr_id).id = i;
2145                 WR_ID(wr->wr_id).offset =
2146                         (((uintptr_t)buf->buf_addr + RTE_PKTMBUF_HEADROOM) -
2147                          (uintptr_t)buf);
2148                 wr->next = &(*elts)[(i + 1)].wr;
2149                 wr->sg_list = sge;
2150                 wr->num_sge = 1;
2151                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
2152                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
2153                 /* Buffer is supposed to be empty. */
2154                 assert(rte_pktmbuf_data_len(buf) == 0);
2155                 assert(rte_pktmbuf_pkt_len(buf) == 0);
2156                 /* sge->addr must be able to store a pointer. */
2157                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
2158                 /* SGE keeps its headroom. */
2159                 sge->addr = (uintptr_t)
2160                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
2161                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
2162                 sge->lkey = rxq->mr->lkey;
2163                 /* Redundant check for tailroom. */
2164                 assert(sge->length == rte_pktmbuf_tailroom(buf));
2165                 /* Make sure elts index and SGE mbuf pointer can be deduced
2166                  * from WR ID. */
2167                 if ((WR_ID(wr->wr_id).id != i) ||
2168                     ((void *)((uintptr_t)sge->addr -
2169                         WR_ID(wr->wr_id).offset) != buf)) {
2170                         ERROR("%p: cannot store index and offset in WR ID",
2171                               (void *)rxq);
2172                         sge->addr = 0;
2173                         rte_pktmbuf_free(buf);
2174                         ret = EOVERFLOW;
2175                         goto error;
2176                 }
2177         }
2178         /* The last WR pointer must be NULL. */
2179         (*elts)[(i - 1)].wr.next = NULL;
2180         DEBUG("%p: allocated and configured %u single-segment WRs",
2181               (void *)rxq, elts_n);
2182         rxq->elts_n = elts_n;
2183         rxq->elts_head = 0;
2184         rxq->elts.no_sp = elts;
2185         assert(ret == 0);
2186         return 0;
2187 error:
2188         if (elts != NULL) {
2189                 assert(pool == NULL);
2190                 for (i = 0; (i != elemof(*elts)); ++i) {
2191                         struct rxq_elt *elt = &(*elts)[i];
2192                         struct rte_mbuf *buf;
2193
2194                         if (elt->sge.addr == 0)
2195                                 continue;
2196                         assert(WR_ID(elt->wr.wr_id).id == i);
2197                         buf = (void *)((uintptr_t)elt->sge.addr -
2198                                 WR_ID(elt->wr.wr_id).offset);
2199                         rte_pktmbuf_free_seg(buf);
2200                 }
2201                 rte_free(elts);
2202         }
2203         DEBUG("%p: failed, freed everything", (void *)rxq);
2204         assert(ret > 0);
2205         return ret;
2206 }
2207
2208 /**
2209  * Free RX queue elements.
2210  *
2211  * @param rxq
2212  *   Pointer to RX queue structure.
2213  */
2214 static void
2215 rxq_free_elts(struct rxq *rxq)
2216 {
2217         unsigned int i;
2218         unsigned int elts_n = rxq->elts_n;
2219         struct rxq_elt (*elts)[elts_n] = rxq->elts.no_sp;
2220
2221         DEBUG("%p: freeing WRs", (void *)rxq);
2222         rxq->elts_n = 0;
2223         rxq->elts.no_sp = NULL;
2224         if (elts == NULL)
2225                 return;
2226         for (i = 0; (i != elemof(*elts)); ++i) {
2227                 struct rxq_elt *elt = &(*elts)[i];
2228                 struct rte_mbuf *buf;
2229
2230                 if (elt->sge.addr == 0)
2231                         continue;
2232                 assert(WR_ID(elt->wr.wr_id).id == i);
2233                 buf = (void *)((uintptr_t)elt->sge.addr -
2234                         WR_ID(elt->wr.wr_id).offset);
2235                 rte_pktmbuf_free_seg(buf);
2236         }
2237         rte_free(elts);
2238 }
2239
2240 /**
2241  * Delete flow steering rule.
2242  *
2243  * @param rxq
2244  *   Pointer to RX queue structure.
2245  * @param mac_index
2246  *   MAC address index.
2247  * @param vlan_index
2248  *   VLAN index.
2249  */
2250 static void
2251 rxq_del_flow(struct rxq *rxq, unsigned int mac_index, unsigned int vlan_index)
2252 {
2253 #ifndef NDEBUG
2254         struct priv *priv = rxq->priv;
2255         const uint8_t (*mac)[ETHER_ADDR_LEN] =
2256                 (const uint8_t (*)[ETHER_ADDR_LEN])
2257                 priv->mac[mac_index].addr_bytes;
2258 #endif
2259         assert(rxq->mac_flow[mac_index][vlan_index] != NULL);
2260         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x index %u"
2261               " (VLAN ID %" PRIu16 ")",
2262               (void *)rxq,
2263               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
2264               mac_index, priv->vlan_filter[vlan_index].id);
2265         claim_zero(ibv_destroy_flow(rxq->mac_flow[mac_index][vlan_index]));
2266         rxq->mac_flow[mac_index][vlan_index] = NULL;
2267 }
2268
2269 /**
2270  * Unregister a MAC address from a RX queue.
2271  *
2272  * @param rxq
2273  *   Pointer to RX queue structure.
2274  * @param mac_index
2275  *   MAC address index.
2276  */
2277 static void
2278 rxq_mac_addr_del(struct rxq *rxq, unsigned int mac_index)
2279 {
2280         struct priv *priv = rxq->priv;
2281         unsigned int i;
2282         unsigned int vlans = 0;
2283
2284         assert(mac_index < elemof(priv->mac));
2285         if (!BITFIELD_ISSET(rxq->mac_configured, mac_index))
2286                 return;
2287         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
2288                 if (!priv->vlan_filter[i].enabled)
2289                         continue;
2290                 rxq_del_flow(rxq, mac_index, i);
2291                 vlans++;
2292         }
2293         if (!vlans) {
2294                 rxq_del_flow(rxq, mac_index, 0);
2295         }
2296         BITFIELD_RESET(rxq->mac_configured, mac_index);
2297 }
2298
2299 /**
2300  * Unregister all MAC addresses from a RX queue.
2301  *
2302  * @param rxq
2303  *   Pointer to RX queue structure.
2304  */
2305 static void
2306 rxq_mac_addrs_del(struct rxq *rxq)
2307 {
2308         struct priv *priv = rxq->priv;
2309         unsigned int i;
2310
2311         for (i = 0; (i != elemof(priv->mac)); ++i)
2312                 rxq_mac_addr_del(rxq, i);
2313 }
2314
2315 static int rxq_promiscuous_enable(struct rxq *);
2316 static void rxq_promiscuous_disable(struct rxq *);
2317
2318 /**
2319  * Add single flow steering rule.
2320  *
2321  * @param rxq
2322  *   Pointer to RX queue structure.
2323  * @param mac_index
2324  *   MAC address index to register.
2325  * @param vlan_index
2326  *   VLAN index. Use -1 for a flow without VLAN.
2327  *
2328  * @return
2329  *   0 on success, errno value on failure.
2330  */
2331 static int
2332 rxq_add_flow(struct rxq *rxq, unsigned int mac_index, unsigned int vlan_index)
2333 {
2334         struct ibv_flow *flow;
2335         struct priv *priv = rxq->priv;
2336         const uint8_t (*mac)[ETHER_ADDR_LEN] =
2337                         (const uint8_t (*)[ETHER_ADDR_LEN])
2338                         priv->mac[mac_index].addr_bytes;
2339
2340         /* Allocate flow specification on the stack. */
2341         struct __attribute__((packed)) {
2342                 struct ibv_flow_attr attr;
2343                 struct ibv_flow_spec_eth spec;
2344         } data;
2345         struct ibv_flow_attr *attr = &data.attr;
2346         struct ibv_flow_spec_eth *spec = &data.spec;
2347
2348         assert(mac_index < elemof(priv->mac));
2349         assert((vlan_index < elemof(priv->vlan_filter)) || (vlan_index == -1u));
2350         /*
2351          * No padding must be inserted by the compiler between attr and spec.
2352          * This layout is expected by libibverbs.
2353          */
2354         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
2355         *attr = (struct ibv_flow_attr){
2356                 .type = IBV_FLOW_ATTR_NORMAL,
2357                 .priority = 3,
2358                 .num_of_specs = 1,
2359                 .port = priv->port,
2360                 .flags = 0
2361         };
2362         *spec = (struct ibv_flow_spec_eth){
2363                 .type = IBV_FLOW_SPEC_ETH,
2364                 .size = sizeof(*spec),
2365                 .val = {
2366                         .dst_mac = {
2367                                 (*mac)[0], (*mac)[1], (*mac)[2],
2368                                 (*mac)[3], (*mac)[4], (*mac)[5]
2369                         },
2370                         .vlan_tag = ((vlan_index != -1u) ?
2371                                      htons(priv->vlan_filter[vlan_index].id) :
2372                                      0),
2373                 },
2374                 .mask = {
2375                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
2376                         .vlan_tag = ((vlan_index != -1u) ? htons(0xfff) : 0),
2377                 }
2378         };
2379         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x index %u"
2380               " (VLAN %s %" PRIu16 ")",
2381               (void *)rxq,
2382               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
2383               mac_index,
2384               ((vlan_index != -1u) ? "ID" : "index"),
2385               ((vlan_index != -1u) ? priv->vlan_filter[vlan_index].id : -1u));
2386         /* Create related flow. */
2387         errno = 0;
2388         flow = ibv_create_flow(rxq->qp, attr);
2389         if (flow == NULL) {
2390                 /* It's not clear whether errno is always set in this case. */
2391                 ERROR("%p: flow configuration failed, errno=%d: %s",
2392                       (void *)rxq, errno,
2393                       (errno ? strerror(errno) : "Unknown error"));
2394                 if (errno)
2395                         return errno;
2396                 return EINVAL;
2397         }
2398         if (vlan_index == -1u)
2399                 vlan_index = 0;
2400         assert(rxq->mac_flow[mac_index][vlan_index] == NULL);
2401         rxq->mac_flow[mac_index][vlan_index] = flow;
2402         return 0;
2403 }
2404
2405 /**
2406  * Register a MAC address in a RX queue.
2407  *
2408  * @param rxq
2409  *   Pointer to RX queue structure.
2410  * @param mac_index
2411  *   MAC address index to register.
2412  *
2413  * @return
2414  *   0 on success, errno value on failure.
2415  */
2416 static int
2417 rxq_mac_addr_add(struct rxq *rxq, unsigned int mac_index)
2418 {
2419         struct priv *priv = rxq->priv;
2420         unsigned int i;
2421         unsigned int vlans = 0;
2422         int ret;
2423
2424         assert(mac_index < elemof(priv->mac));
2425         if (BITFIELD_ISSET(rxq->mac_configured, mac_index))
2426                 rxq_mac_addr_del(rxq, mac_index);
2427         /* Fill VLAN specifications. */
2428         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
2429                 if (!priv->vlan_filter[i].enabled)
2430                         continue;
2431                 /* Create related flow. */
2432                 ret = rxq_add_flow(rxq, mac_index, i);
2433                 if (!ret) {
2434                         vlans++;
2435                         continue;
2436                 }
2437                 /* Failure, rollback. */
2438                 while (i != 0)
2439                         if (priv->vlan_filter[--i].enabled)
2440                                 rxq_del_flow(rxq, mac_index, i);
2441                 assert(ret > 0);
2442                 return ret;
2443         }
2444         /* In case there is no VLAN filter. */
2445         if (!vlans) {
2446                 ret = rxq_add_flow(rxq, mac_index, -1);
2447                 if (ret)
2448                         return ret;
2449         }
2450         BITFIELD_SET(rxq->mac_configured, mac_index);
2451         return 0;
2452 }
2453
2454 /**
2455  * Register all MAC addresses in a RX queue.
2456  *
2457  * @param rxq
2458  *   Pointer to RX queue structure.
2459  *
2460  * @return
2461  *   0 on success, errno value on failure.
2462  */
2463 static int
2464 rxq_mac_addrs_add(struct rxq *rxq)
2465 {
2466         struct priv *priv = rxq->priv;
2467         unsigned int i;
2468         int ret;
2469
2470         for (i = 0; (i != elemof(priv->mac)); ++i) {
2471                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2472                         continue;
2473                 ret = rxq_mac_addr_add(rxq, i);
2474                 if (!ret)
2475                         continue;
2476                 /* Failure, rollback. */
2477                 while (i != 0)
2478                         rxq_mac_addr_del(rxq, --i);
2479                 assert(ret > 0);
2480                 return ret;
2481         }
2482         return 0;
2483 }
2484
2485 /**
2486  * Unregister a MAC address.
2487  *
2488  * In RSS mode, the MAC address is unregistered from the parent queue,
2489  * otherwise it is unregistered from each queue directly.
2490  *
2491  * @param priv
2492  *   Pointer to private structure.
2493  * @param mac_index
2494  *   MAC address index.
2495  */
2496 static void
2497 priv_mac_addr_del(struct priv *priv, unsigned int mac_index)
2498 {
2499         unsigned int i;
2500
2501         assert(mac_index < elemof(priv->mac));
2502         if (!BITFIELD_ISSET(priv->mac_configured, mac_index))
2503                 return;
2504         if (priv->rss) {
2505                 rxq_mac_addr_del(&priv->rxq_parent, mac_index);
2506                 goto end;
2507         }
2508         for (i = 0; (i != priv->dev->data->nb_rx_queues); ++i)
2509                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2510 end:
2511         BITFIELD_RESET(priv->mac_configured, mac_index);
2512 }
2513
2514 /**
2515  * Register a MAC address.
2516  *
2517  * In RSS mode, the MAC address is registered in the parent queue,
2518  * otherwise it is registered in each queue directly.
2519  *
2520  * @param priv
2521  *   Pointer to private structure.
2522  * @param mac_index
2523  *   MAC address index to use.
2524  * @param mac
2525  *   MAC address to register.
2526  *
2527  * @return
2528  *   0 on success, errno value on failure.
2529  */
2530 static int
2531 priv_mac_addr_add(struct priv *priv, unsigned int mac_index,
2532                   const uint8_t (*mac)[ETHER_ADDR_LEN])
2533 {
2534         unsigned int i;
2535         int ret;
2536
2537         assert(mac_index < elemof(priv->mac));
2538         /* First, make sure this address isn't already configured. */
2539         for (i = 0; (i != elemof(priv->mac)); ++i) {
2540                 /* Skip this index, it's going to be reconfigured. */
2541                 if (i == mac_index)
2542                         continue;
2543                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2544                         continue;
2545                 if (memcmp(priv->mac[i].addr_bytes, *mac, sizeof(*mac)))
2546                         continue;
2547                 /* Address already configured elsewhere, return with error. */
2548                 return EADDRINUSE;
2549         }
2550         if (BITFIELD_ISSET(priv->mac_configured, mac_index))
2551                 priv_mac_addr_del(priv, mac_index);
2552         priv->mac[mac_index] = (struct ether_addr){
2553                 {
2554                         (*mac)[0], (*mac)[1], (*mac)[2],
2555                         (*mac)[3], (*mac)[4], (*mac)[5]
2556                 }
2557         };
2558         /* If device isn't started, this is all we need to do. */
2559         if (!priv->started) {
2560 #ifndef NDEBUG
2561                 /* Verify that all queues have this index disabled. */
2562                 for (i = 0; (i != priv->rxqs_n); ++i) {
2563                         if ((*priv->rxqs)[i] == NULL)
2564                                 continue;
2565                         assert(!BITFIELD_ISSET
2566                                ((*priv->rxqs)[i]->mac_configured, mac_index));
2567                 }
2568 #endif
2569                 goto end;
2570         }
2571         if (priv->rss) {
2572                 ret = rxq_mac_addr_add(&priv->rxq_parent, mac_index);
2573                 if (ret)
2574                         return ret;
2575                 goto end;
2576         }
2577         for (i = 0; (i != priv->rxqs_n); ++i) {
2578                 if ((*priv->rxqs)[i] == NULL)
2579                         continue;
2580                 ret = rxq_mac_addr_add((*priv->rxqs)[i], mac_index);
2581                 if (!ret)
2582                         continue;
2583                 /* Failure, rollback. */
2584                 while (i != 0)
2585                         if ((*priv->rxqs)[(--i)] != NULL)
2586                                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2587                 return ret;
2588         }
2589 end:
2590         BITFIELD_SET(priv->mac_configured, mac_index);
2591         return 0;
2592 }
2593
2594 /**
2595  * Enable allmulti mode in a RX queue.
2596  *
2597  * @param rxq
2598  *   Pointer to RX queue structure.
2599  *
2600  * @return
2601  *   0 on success, errno value on failure.
2602  */
2603 static int
2604 rxq_allmulticast_enable(struct rxq *rxq)
2605 {
2606         struct ibv_flow *flow;
2607         struct ibv_flow_attr attr = {
2608                 .type = IBV_FLOW_ATTR_MC_DEFAULT,
2609                 .num_of_specs = 0,
2610                 .port = rxq->priv->port,
2611                 .flags = 0
2612         };
2613
2614         DEBUG("%p: enabling allmulticast mode", (void *)rxq);
2615         if (rxq->allmulti_flow != NULL)
2616                 return EBUSY;
2617         errno = 0;
2618         flow = ibv_create_flow(rxq->qp, &attr);
2619         if (flow == NULL) {
2620                 /* It's not clear whether errno is always set in this case. */
2621                 ERROR("%p: flow configuration failed, errno=%d: %s",
2622                       (void *)rxq, errno,
2623                       (errno ? strerror(errno) : "Unknown error"));
2624                 if (errno)
2625                         return errno;
2626                 return EINVAL;
2627         }
2628         rxq->allmulti_flow = flow;
2629         DEBUG("%p: allmulticast mode enabled", (void *)rxq);
2630         return 0;
2631 }
2632
2633 /**
2634  * Disable allmulti mode in a RX queue.
2635  *
2636  * @param rxq
2637  *   Pointer to RX queue structure.
2638  */
2639 static void
2640 rxq_allmulticast_disable(struct rxq *rxq)
2641 {
2642         DEBUG("%p: disabling allmulticast mode", (void *)rxq);
2643         if (rxq->allmulti_flow == NULL)
2644                 return;
2645         claim_zero(ibv_destroy_flow(rxq->allmulti_flow));
2646         rxq->allmulti_flow = NULL;
2647         DEBUG("%p: allmulticast mode disabled", (void *)rxq);
2648 }
2649
2650 /**
2651  * Enable promiscuous mode in a RX queue.
2652  *
2653  * @param rxq
2654  *   Pointer to RX queue structure.
2655  *
2656  * @return
2657  *   0 on success, errno value on failure.
2658  */
2659 static int
2660 rxq_promiscuous_enable(struct rxq *rxq)
2661 {
2662         struct ibv_flow *flow;
2663         struct ibv_flow_attr attr = {
2664                 .type = IBV_FLOW_ATTR_ALL_DEFAULT,
2665                 .num_of_specs = 0,
2666                 .port = rxq->priv->port,
2667                 .flags = 0
2668         };
2669
2670         if (rxq->priv->vf)
2671                 return 0;
2672         DEBUG("%p: enabling promiscuous mode", (void *)rxq);
2673         if (rxq->promisc_flow != NULL)
2674                 return EBUSY;
2675         errno = 0;
2676         flow = ibv_create_flow(rxq->qp, &attr);
2677         if (flow == NULL) {
2678                 /* It's not clear whether errno is always set in this case. */
2679                 ERROR("%p: flow configuration failed, errno=%d: %s",
2680                       (void *)rxq, errno,
2681                       (errno ? strerror(errno) : "Unknown error"));
2682                 if (errno)
2683                         return errno;
2684                 return EINVAL;
2685         }
2686         rxq->promisc_flow = flow;
2687         DEBUG("%p: promiscuous mode enabled", (void *)rxq);
2688         return 0;
2689 }
2690
2691 /**
2692  * Disable promiscuous mode in a RX queue.
2693  *
2694  * @param rxq
2695  *   Pointer to RX queue structure.
2696  */
2697 static void
2698 rxq_promiscuous_disable(struct rxq *rxq)
2699 {
2700         if (rxq->priv->vf)
2701                 return;
2702         DEBUG("%p: disabling promiscuous mode", (void *)rxq);
2703         if (rxq->promisc_flow == NULL)
2704                 return;
2705         claim_zero(ibv_destroy_flow(rxq->promisc_flow));
2706         rxq->promisc_flow = NULL;
2707         DEBUG("%p: promiscuous mode disabled", (void *)rxq);
2708 }
2709
2710 /**
2711  * Clean up a RX queue.
2712  *
2713  * Destroy objects, free allocated memory and reset the structure for reuse.
2714  *
2715  * @param rxq
2716  *   Pointer to RX queue structure.
2717  */
2718 static void
2719 rxq_cleanup(struct rxq *rxq)
2720 {
2721         struct ibv_exp_release_intf_params params;
2722
2723         DEBUG("cleaning up %p", (void *)rxq);
2724         if (rxq->sp)
2725                 rxq_free_elts_sp(rxq);
2726         else
2727                 rxq_free_elts(rxq);
2728         if (rxq->if_qp != NULL) {
2729                 assert(rxq->priv != NULL);
2730                 assert(rxq->priv->ctx != NULL);
2731                 assert(rxq->qp != NULL);
2732                 params = (struct ibv_exp_release_intf_params){
2733                         .comp_mask = 0,
2734                 };
2735                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
2736                                                 rxq->if_qp,
2737                                                 &params));
2738         }
2739         if (rxq->if_cq != NULL) {
2740                 assert(rxq->priv != NULL);
2741                 assert(rxq->priv->ctx != NULL);
2742                 assert(rxq->cq != NULL);
2743                 params = (struct ibv_exp_release_intf_params){
2744                         .comp_mask = 0,
2745                 };
2746                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
2747                                                 rxq->if_cq,
2748                                                 &params));
2749         }
2750         if (rxq->qp != NULL) {
2751                 rxq_promiscuous_disable(rxq);
2752                 rxq_allmulticast_disable(rxq);
2753                 rxq_mac_addrs_del(rxq);
2754                 claim_zero(ibv_destroy_qp(rxq->qp));
2755         }
2756         if (rxq->cq != NULL)
2757                 claim_zero(ibv_destroy_cq(rxq->cq));
2758         if (rxq->rd != NULL) {
2759                 struct ibv_exp_destroy_res_domain_attr attr = {
2760                         .comp_mask = 0,
2761                 };
2762
2763                 assert(rxq->priv != NULL);
2764                 assert(rxq->priv->ctx != NULL);
2765                 claim_zero(ibv_exp_destroy_res_domain(rxq->priv->ctx,
2766                                                       rxq->rd,
2767                                                       &attr));
2768         }
2769         if (rxq->mr != NULL)
2770                 claim_zero(ibv_dereg_mr(rxq->mr));
2771         memset(rxq, 0, sizeof(*rxq));
2772 }
2773
2774 /**
2775  * Translate RX completion flags to packet type.
2776  *
2777  * @param flags
2778  *   RX completion flags returned by poll_length_flags().
2779  *
2780  * @note: fix mlx4_dev_supported_ptypes_get() if any change here.
2781  *
2782  * @return
2783  *   Packet type for struct rte_mbuf.
2784  */
2785 static inline uint32_t
2786 rxq_cq_to_pkt_type(uint32_t flags)
2787 {
2788         uint32_t pkt_type;
2789
2790         if (flags & IBV_EXP_CQ_RX_TUNNEL_PACKET)
2791                 pkt_type =
2792                         TRANSPOSE(flags,
2793                                   IBV_EXP_CQ_RX_OUTER_IPV4_PACKET,
2794                                   RTE_PTYPE_L3_IPV4_EXT_UNKNOWN) |
2795                         TRANSPOSE(flags,
2796                                   IBV_EXP_CQ_RX_OUTER_IPV6_PACKET,
2797                                   RTE_PTYPE_L3_IPV6_EXT_UNKNOWN) |
2798                         TRANSPOSE(flags,
2799                                   IBV_EXP_CQ_RX_IPV4_PACKET,
2800                                   RTE_PTYPE_INNER_L3_IPV4_EXT_UNKNOWN) |
2801                         TRANSPOSE(flags,
2802                                   IBV_EXP_CQ_RX_IPV6_PACKET,
2803                                   RTE_PTYPE_INNER_L3_IPV6_EXT_UNKNOWN);
2804         else
2805                 pkt_type =
2806                         TRANSPOSE(flags,
2807                                   IBV_EXP_CQ_RX_IPV4_PACKET,
2808                                   RTE_PTYPE_L3_IPV4_EXT_UNKNOWN) |
2809                         TRANSPOSE(flags,
2810                                   IBV_EXP_CQ_RX_IPV6_PACKET,
2811                                   RTE_PTYPE_L3_IPV6_EXT_UNKNOWN);
2812         return pkt_type;
2813 }
2814
2815 /**
2816  * Translate RX completion flags to offload flags.
2817  *
2818  * @param[in] rxq
2819  *   Pointer to RX queue structure.
2820  * @param flags
2821  *   RX completion flags returned by poll_length_flags().
2822  *
2823  * @return
2824  *   Offload flags (ol_flags) for struct rte_mbuf.
2825  */
2826 static inline uint32_t
2827 rxq_cq_to_ol_flags(const struct rxq *rxq, uint32_t flags)
2828 {
2829         uint32_t ol_flags = 0;
2830
2831         if (rxq->csum)
2832                 ol_flags |=
2833                         TRANSPOSE(flags,
2834                                   IBV_EXP_CQ_RX_IP_CSUM_OK,
2835                                   PKT_RX_IP_CKSUM_GOOD) |
2836                         TRANSPOSE(flags,
2837                                   IBV_EXP_CQ_RX_TCP_UDP_CSUM_OK,
2838                                   PKT_RX_L4_CKSUM_GOOD);
2839         if ((flags & IBV_EXP_CQ_RX_TUNNEL_PACKET) && (rxq->csum_l2tun))
2840                 ol_flags |=
2841                         TRANSPOSE(flags,
2842                                   IBV_EXP_CQ_RX_OUTER_IP_CSUM_OK,
2843                                   PKT_RX_IP_CKSUM_GOOD) |
2844                         TRANSPOSE(flags,
2845                                   IBV_EXP_CQ_RX_OUTER_TCP_UDP_CSUM_OK,
2846                                   PKT_RX_L4_CKSUM_GOOD);
2847         return ol_flags;
2848 }
2849
2850 static uint16_t
2851 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n);
2852
2853 /**
2854  * DPDK callback for RX with scattered packets support.
2855  *
2856  * @param dpdk_rxq
2857  *   Generic pointer to RX queue structure.
2858  * @param[out] pkts
2859  *   Array to store received packets.
2860  * @param pkts_n
2861  *   Maximum number of packets in array.
2862  *
2863  * @return
2864  *   Number of packets successfully received (<= pkts_n).
2865  */
2866 static uint16_t
2867 mlx4_rx_burst_sp(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2868 {
2869         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2870         struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2871         const unsigned int elts_n = rxq->elts_n;
2872         unsigned int elts_head = rxq->elts_head;
2873         struct ibv_recv_wr head;
2874         struct ibv_recv_wr **next = &head.next;
2875         struct ibv_recv_wr *bad_wr;
2876         unsigned int i;
2877         unsigned int pkts_ret = 0;
2878         int ret;
2879
2880         if (unlikely(!rxq->sp))
2881                 return mlx4_rx_burst(dpdk_rxq, pkts, pkts_n);
2882         if (unlikely(elts == NULL)) /* See RTE_DEV_CMD_SET_MTU. */
2883                 return 0;
2884         for (i = 0; (i != pkts_n); ++i) {
2885                 struct rxq_elt_sp *elt = &(*elts)[elts_head];
2886                 struct ibv_recv_wr *wr = &elt->wr;
2887                 uint64_t wr_id = wr->wr_id;
2888                 unsigned int len;
2889                 unsigned int pkt_buf_len;
2890                 struct rte_mbuf *pkt_buf = NULL; /* Buffer returned in pkts. */
2891                 struct rte_mbuf **pkt_buf_next = &pkt_buf;
2892                 unsigned int seg_headroom = RTE_PKTMBUF_HEADROOM;
2893                 unsigned int j = 0;
2894                 uint32_t flags;
2895
2896                 /* Sanity checks. */
2897 #ifdef NDEBUG
2898                 (void)wr_id;
2899 #endif
2900                 assert(wr_id < rxq->elts_n);
2901                 assert(wr->sg_list == elt->sges);
2902                 assert(wr->num_sge == elemof(elt->sges));
2903                 assert(elts_head < rxq->elts_n);
2904                 assert(rxq->elts_head < rxq->elts_n);
2905                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
2906                                                     &flags);
2907                 if (unlikely(ret < 0)) {
2908                         struct ibv_wc wc;
2909                         int wcs_n;
2910
2911                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
2912                               (void *)rxq, ret);
2913                         /* ibv_poll_cq() must be used in case of failure. */
2914                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
2915                         if (unlikely(wcs_n == 0))
2916                                 break;
2917                         if (unlikely(wcs_n < 0)) {
2918                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
2919                                       (void *)rxq, wcs_n);
2920                                 break;
2921                         }
2922                         assert(wcs_n == 1);
2923                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
2924                                 /* Whatever, just repost the offending WR. */
2925                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
2926                                       " completion status (%d): %s",
2927                                       (void *)rxq, wc.wr_id, wc.status,
2928                                       ibv_wc_status_str(wc.status));
2929 #ifdef MLX4_PMD_SOFT_COUNTERS
2930                                 /* Increment dropped packets counter. */
2931                                 ++rxq->stats.idropped;
2932 #endif
2933                                 /* Link completed WRs together for repost. */
2934                                 *next = wr;
2935                                 next = &wr->next;
2936                                 goto repost;
2937                         }
2938                         ret = wc.byte_len;
2939                 }
2940                 if (ret == 0)
2941                         break;
2942                 len = ret;
2943                 pkt_buf_len = len;
2944                 /* Link completed WRs together for repost. */
2945                 *next = wr;
2946                 next = &wr->next;
2947                 /*
2948                  * Replace spent segments with new ones, concatenate and
2949                  * return them as pkt_buf.
2950                  */
2951                 while (1) {
2952                         struct ibv_sge *sge = &elt->sges[j];
2953                         struct rte_mbuf *seg = elt->bufs[j];
2954                         struct rte_mbuf *rep;
2955                         unsigned int seg_tailroom;
2956
2957                         /*
2958                          * Fetch initial bytes of packet descriptor into a
2959                          * cacheline while allocating rep.
2960                          */
2961                         rte_prefetch0(seg);
2962                         rep = rte_mbuf_raw_alloc(rxq->mp);
2963                         if (unlikely(rep == NULL)) {
2964                                 /*
2965                                  * Unable to allocate a replacement mbuf,
2966                                  * repost WR.
2967                                  */
2968                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ":"
2969                                       " can't allocate a new mbuf",
2970                                       (void *)rxq, wr_id);
2971                                 if (pkt_buf != NULL) {
2972                                         *pkt_buf_next = NULL;
2973                                         rte_pktmbuf_free(pkt_buf);
2974                                 }
2975                                 /* Increase out of memory counters. */
2976                                 ++rxq->stats.rx_nombuf;
2977                                 ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2978                                 goto repost;
2979                         }
2980 #ifndef NDEBUG
2981                         /* Poison user-modifiable fields in rep. */
2982                         NEXT(rep) = (void *)((uintptr_t)-1);
2983                         SET_DATA_OFF(rep, 0xdead);
2984                         DATA_LEN(rep) = 0xd00d;
2985                         PKT_LEN(rep) = 0xdeadd00d;
2986                         NB_SEGS(rep) = 0x2a;
2987                         PORT(rep) = 0x2a;
2988                         rep->ol_flags = -1;
2989 #endif
2990                         assert(rep->buf_len == seg->buf_len);
2991                         /* Reconfigure sge to use rep instead of seg. */
2992                         assert(sge->lkey == rxq->mr->lkey);
2993                         sge->addr = ((uintptr_t)rep->buf_addr + seg_headroom);
2994                         elt->bufs[j] = rep;
2995                         ++j;
2996                         /* Update pkt_buf if it's the first segment, or link
2997                          * seg to the previous one and update pkt_buf_next. */
2998                         *pkt_buf_next = seg;
2999                         pkt_buf_next = &NEXT(seg);
3000                         /* Update seg information. */
3001                         seg_tailroom = (seg->buf_len - seg_headroom);
3002                         assert(sge->length == seg_tailroom);
3003                         SET_DATA_OFF(seg, seg_headroom);
3004                         if (likely(len <= seg_tailroom)) {
3005                                 /* Last segment. */
3006                                 DATA_LEN(seg) = len;
3007                                 PKT_LEN(seg) = len;
3008                                 /* Sanity check. */
3009                                 assert(rte_pktmbuf_headroom(seg) ==
3010                                        seg_headroom);
3011                                 assert(rte_pktmbuf_tailroom(seg) ==
3012                                        (seg_tailroom - len));
3013                                 break;
3014                         }
3015                         DATA_LEN(seg) = seg_tailroom;
3016                         PKT_LEN(seg) = seg_tailroom;
3017                         /* Sanity check. */
3018                         assert(rte_pktmbuf_headroom(seg) == seg_headroom);
3019                         assert(rte_pktmbuf_tailroom(seg) == 0);
3020                         /* Fix len and clear headroom for next segments. */
3021                         len -= seg_tailroom;
3022                         seg_headroom = 0;
3023                 }
3024                 /* Update head and tail segments. */
3025                 *pkt_buf_next = NULL;
3026                 assert(pkt_buf != NULL);
3027                 assert(j != 0);
3028                 NB_SEGS(pkt_buf) = j;
3029                 PORT(pkt_buf) = rxq->port_id;
3030                 PKT_LEN(pkt_buf) = pkt_buf_len;
3031                 pkt_buf->packet_type = rxq_cq_to_pkt_type(flags);
3032                 pkt_buf->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
3033
3034                 /* Return packet. */
3035                 *(pkts++) = pkt_buf;
3036                 ++pkts_ret;
3037 #ifdef MLX4_PMD_SOFT_COUNTERS
3038                 /* Increase bytes counter. */
3039                 rxq->stats.ibytes += pkt_buf_len;
3040 #endif
3041 repost:
3042                 if (++elts_head >= elts_n)
3043                         elts_head = 0;
3044                 continue;
3045         }
3046         if (unlikely(i == 0))
3047                 return 0;
3048         *next = NULL;
3049         /* Repost WRs. */
3050 #ifdef DEBUG_RECV
3051         DEBUG("%p: reposting %d WRs", (void *)rxq, i);
3052 #endif
3053         ret = ibv_post_recv(rxq->qp, head.next, &bad_wr);
3054         if (unlikely(ret)) {
3055                 /* Inability to repost WRs is fatal. */
3056                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
3057                       (void *)rxq->priv,
3058                       (void *)bad_wr,
3059                       strerror(ret));
3060                 abort();
3061         }
3062         rxq->elts_head = elts_head;
3063 #ifdef MLX4_PMD_SOFT_COUNTERS
3064         /* Increase packets counter. */
3065         rxq->stats.ipackets += pkts_ret;
3066 #endif
3067         return pkts_ret;
3068 }
3069
3070 /**
3071  * DPDK callback for RX.
3072  *
3073  * The following function is the same as mlx4_rx_burst_sp(), except it doesn't
3074  * manage scattered packets. Improves performance when MRU is lower than the
3075  * size of the first segment.
3076  *
3077  * @param dpdk_rxq
3078  *   Generic pointer to RX queue structure.
3079  * @param[out] pkts
3080  *   Array to store received packets.
3081  * @param pkts_n
3082  *   Maximum number of packets in array.
3083  *
3084  * @return
3085  *   Number of packets successfully received (<= pkts_n).
3086  */
3087 static uint16_t
3088 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
3089 {
3090         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3091         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
3092         const unsigned int elts_n = rxq->elts_n;
3093         unsigned int elts_head = rxq->elts_head;
3094         struct ibv_sge sges[pkts_n];
3095         unsigned int i;
3096         unsigned int pkts_ret = 0;
3097         int ret;
3098
3099         if (unlikely(rxq->sp))
3100                 return mlx4_rx_burst_sp(dpdk_rxq, pkts, pkts_n);
3101         for (i = 0; (i != pkts_n); ++i) {
3102                 struct rxq_elt *elt = &(*elts)[elts_head];
3103                 struct ibv_recv_wr *wr = &elt->wr;
3104                 uint64_t wr_id = wr->wr_id;
3105                 unsigned int len;
3106                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
3107                         WR_ID(wr_id).offset);
3108                 struct rte_mbuf *rep;
3109                 uint32_t flags;
3110
3111                 /* Sanity checks. */
3112                 assert(WR_ID(wr_id).id < rxq->elts_n);
3113                 assert(wr->sg_list == &elt->sge);
3114                 assert(wr->num_sge == 1);
3115                 assert(elts_head < rxq->elts_n);
3116                 assert(rxq->elts_head < rxq->elts_n);
3117                 /*
3118                  * Fetch initial bytes of packet descriptor into a
3119                  * cacheline while allocating rep.
3120                  */
3121                 rte_mbuf_prefetch_part1(seg);
3122                 rte_mbuf_prefetch_part2(seg);
3123                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
3124                                                     &flags);
3125                 if (unlikely(ret < 0)) {
3126                         struct ibv_wc wc;
3127                         int wcs_n;
3128
3129                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
3130                               (void *)rxq, ret);
3131                         /* ibv_poll_cq() must be used in case of failure. */
3132                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
3133                         if (unlikely(wcs_n == 0))
3134                                 break;
3135                         if (unlikely(wcs_n < 0)) {
3136                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
3137                                       (void *)rxq, wcs_n);
3138                                 break;
3139                         }
3140                         assert(wcs_n == 1);
3141                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
3142                                 /* Whatever, just repost the offending WR. */
3143                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
3144                                       " completion status (%d): %s",
3145                                       (void *)rxq, wc.wr_id, wc.status,
3146                                       ibv_wc_status_str(wc.status));
3147 #ifdef MLX4_PMD_SOFT_COUNTERS
3148                                 /* Increment dropped packets counter. */
3149                                 ++rxq->stats.idropped;
3150 #endif
3151                                 /* Add SGE to array for repost. */
3152                                 sges[i] = elt->sge;
3153                                 goto repost;
3154                         }
3155                         ret = wc.byte_len;
3156                 }
3157                 if (ret == 0)
3158                         break;
3159                 len = ret;
3160                 rep = rte_mbuf_raw_alloc(rxq->mp);
3161                 if (unlikely(rep == NULL)) {
3162                         /*
3163                          * Unable to allocate a replacement mbuf,
3164                          * repost WR.
3165                          */
3166                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
3167                               " can't allocate a new mbuf",
3168                               (void *)rxq, WR_ID(wr_id).id);
3169                         /* Increase out of memory counters. */
3170                         ++rxq->stats.rx_nombuf;
3171                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
3172                         goto repost;
3173                 }
3174
3175                 /* Reconfigure sge to use rep instead of seg. */
3176                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
3177                 assert(elt->sge.lkey == rxq->mr->lkey);
3178                 WR_ID(wr->wr_id).offset =
3179                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
3180                          (uintptr_t)rep);
3181                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
3182
3183                 /* Add SGE to array for repost. */
3184                 sges[i] = elt->sge;
3185
3186                 /* Update seg information. */
3187                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
3188                 NB_SEGS(seg) = 1;
3189                 PORT(seg) = rxq->port_id;
3190                 NEXT(seg) = NULL;
3191                 PKT_LEN(seg) = len;
3192                 DATA_LEN(seg) = len;
3193                 seg->packet_type = rxq_cq_to_pkt_type(flags);
3194                 seg->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
3195
3196                 /* Return packet. */
3197                 *(pkts++) = seg;
3198                 ++pkts_ret;
3199 #ifdef MLX4_PMD_SOFT_COUNTERS
3200                 /* Increase bytes counter. */
3201                 rxq->stats.ibytes += len;
3202 #endif
3203 repost:
3204                 if (++elts_head >= elts_n)
3205                         elts_head = 0;
3206                 continue;
3207         }
3208         if (unlikely(i == 0))
3209                 return 0;
3210         /* Repost WRs. */
3211 #ifdef DEBUG_RECV
3212         DEBUG("%p: reposting %u WRs", (void *)rxq, i);
3213 #endif
3214         ret = rxq->if_qp->recv_burst(rxq->qp, sges, i);
3215         if (unlikely(ret)) {
3216                 /* Inability to repost WRs is fatal. */
3217                 DEBUG("%p: recv_burst(): failed (ret=%d)",
3218                       (void *)rxq->priv,
3219                       ret);
3220                 abort();
3221         }
3222         rxq->elts_head = elts_head;
3223 #ifdef MLX4_PMD_SOFT_COUNTERS
3224         /* Increase packets counter. */
3225         rxq->stats.ipackets += pkts_ret;
3226 #endif
3227         return pkts_ret;
3228 }
3229
3230 /**
3231  * DPDK callback for RX in secondary processes.
3232  *
3233  * This function configures all queues from primary process information
3234  * if necessary before reverting to the normal RX burst callback.
3235  *
3236  * @param dpdk_rxq
3237  *   Generic pointer to RX queue structure.
3238  * @param[out] pkts
3239  *   Array to store received packets.
3240  * @param pkts_n
3241  *   Maximum number of packets in array.
3242  *
3243  * @return
3244  *   Number of packets successfully received (<= pkts_n).
3245  */
3246 static uint16_t
3247 mlx4_rx_burst_secondary_setup(void *dpdk_rxq, struct rte_mbuf **pkts,
3248                               uint16_t pkts_n)
3249 {
3250         struct rxq *rxq = dpdk_rxq;
3251         struct priv *priv = mlx4_secondary_data_setup(rxq->priv);
3252         struct priv *primary_priv;
3253         unsigned int index;
3254
3255         if (priv == NULL)
3256                 return 0;
3257         primary_priv =
3258                 mlx4_secondary_data[priv->dev->data->port_id].primary_priv;
3259         /* Look for queue index in both private structures. */
3260         for (index = 0; index != priv->rxqs_n; ++index)
3261                 if (((*primary_priv->rxqs)[index] == rxq) ||
3262                     ((*priv->rxqs)[index] == rxq))
3263                         break;
3264         if (index == priv->rxqs_n)
3265                 return 0;
3266         rxq = (*priv->rxqs)[index];
3267         return priv->dev->rx_pkt_burst(rxq, pkts, pkts_n);
3268 }
3269
3270 /**
3271  * Allocate a Queue Pair.
3272  * Optionally setup inline receive if supported.
3273  *
3274  * @param priv
3275  *   Pointer to private structure.
3276  * @param cq
3277  *   Completion queue to associate with QP.
3278  * @param desc
3279  *   Number of descriptors in QP (hint only).
3280  *
3281  * @return
3282  *   QP pointer or NULL in case of error.
3283  */
3284 static struct ibv_qp *
3285 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
3286              struct ibv_exp_res_domain *rd)
3287 {
3288         struct ibv_exp_qp_init_attr attr = {
3289                 /* CQ to be associated with the send queue. */
3290                 .send_cq = cq,
3291                 /* CQ to be associated with the receive queue. */
3292                 .recv_cq = cq,
3293                 .cap = {
3294                         /* Max number of outstanding WRs. */
3295                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
3296                                         priv->device_attr.max_qp_wr :
3297                                         desc),
3298                         /* Max number of scatter/gather elements in a WR. */
3299                         .max_recv_sge = ((priv->device_attr.max_sge <
3300                                           MLX4_PMD_SGE_WR_N) ?
3301                                          priv->device_attr.max_sge :
3302                                          MLX4_PMD_SGE_WR_N),
3303                 },
3304                 .qp_type = IBV_QPT_RAW_PACKET,
3305                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
3306                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
3307                 .pd = priv->pd,
3308                 .res_domain = rd,
3309         };
3310
3311 #ifdef INLINE_RECV
3312         attr.max_inl_recv = priv->inl_recv_size;
3313         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3314 #endif
3315         return ibv_exp_create_qp(priv->ctx, &attr);
3316 }
3317
3318 #ifdef RSS_SUPPORT
3319
3320 /**
3321  * Allocate a RSS Queue Pair.
3322  * Optionally setup inline receive if supported.
3323  *
3324  * @param priv
3325  *   Pointer to private structure.
3326  * @param cq
3327  *   Completion queue to associate with QP.
3328  * @param desc
3329  *   Number of descriptors in QP (hint only).
3330  * @param parent
3331  *   If nonzero, create a parent QP, otherwise a child.
3332  *
3333  * @return
3334  *   QP pointer or NULL in case of error.
3335  */
3336 static struct ibv_qp *
3337 rxq_setup_qp_rss(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
3338                  int parent, struct ibv_exp_res_domain *rd)
3339 {
3340         struct ibv_exp_qp_init_attr attr = {
3341                 /* CQ to be associated with the send queue. */
3342                 .send_cq = cq,
3343                 /* CQ to be associated with the receive queue. */
3344                 .recv_cq = cq,
3345                 .cap = {
3346                         /* Max number of outstanding WRs. */
3347                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
3348                                         priv->device_attr.max_qp_wr :
3349                                         desc),
3350                         /* Max number of scatter/gather elements in a WR. */
3351                         .max_recv_sge = ((priv->device_attr.max_sge <
3352                                           MLX4_PMD_SGE_WR_N) ?
3353                                          priv->device_attr.max_sge :
3354                                          MLX4_PMD_SGE_WR_N),
3355                 },
3356                 .qp_type = IBV_QPT_RAW_PACKET,
3357                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
3358                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN |
3359                               IBV_EXP_QP_INIT_ATTR_QPG),
3360                 .pd = priv->pd,
3361                 .res_domain = rd,
3362         };
3363
3364 #ifdef INLINE_RECV
3365         attr.max_inl_recv = priv->inl_recv_size,
3366         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3367 #endif
3368         if (parent) {
3369                 attr.qpg.qpg_type = IBV_EXP_QPG_PARENT;
3370                 /* TSS isn't necessary. */
3371                 attr.qpg.parent_attrib.tss_child_count = 0;
3372                 attr.qpg.parent_attrib.rss_child_count =
3373                         rte_align32pow2(priv->rxqs_n + 1) >> 1;
3374                 DEBUG("initializing parent RSS queue");
3375         } else {
3376                 attr.qpg.qpg_type = IBV_EXP_QPG_CHILD_RX;
3377                 attr.qpg.qpg_parent = priv->rxq_parent.qp;
3378                 DEBUG("initializing child RSS queue");
3379         }
3380         return ibv_exp_create_qp(priv->ctx, &attr);
3381 }
3382
3383 #endif /* RSS_SUPPORT */
3384
3385 /**
3386  * Reconfigure a RX queue with new parameters.
3387  *
3388  * rxq_rehash() does not allocate mbufs, which, if not done from the right
3389  * thread (such as a control thread), may corrupt the pool.
3390  * In case of failure, the queue is left untouched.
3391  *
3392  * @param dev
3393  *   Pointer to Ethernet device structure.
3394  * @param rxq
3395  *   RX queue pointer.
3396  *
3397  * @return
3398  *   0 on success, errno value on failure.
3399  */
3400 static int
3401 rxq_rehash(struct rte_eth_dev *dev, struct rxq *rxq)
3402 {
3403         struct priv *priv = rxq->priv;
3404         struct rxq tmpl = *rxq;
3405         unsigned int mbuf_n;
3406         unsigned int desc_n;
3407         struct rte_mbuf **pool;
3408         unsigned int i, k;
3409         struct ibv_exp_qp_attr mod;
3410         struct ibv_recv_wr *bad_wr;
3411         unsigned int mb_len;
3412         int err;
3413         int parent = (rxq == &priv->rxq_parent);
3414
3415         if (parent) {
3416                 ERROR("%p: cannot rehash parent queue %p",
3417                       (void *)dev, (void *)rxq);
3418                 return EINVAL;
3419         }
3420         mb_len = rte_pktmbuf_data_room_size(rxq->mp);
3421         DEBUG("%p: rehashing queue %p", (void *)dev, (void *)rxq);
3422         /* Number of descriptors and mbufs currently allocated. */
3423         desc_n = (tmpl.elts_n * (tmpl.sp ? MLX4_PMD_SGE_WR_N : 1));
3424         mbuf_n = desc_n;
3425         /* Toggle RX checksum offload if hardware supports it. */
3426         if (priv->hw_csum) {
3427                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3428                 rxq->csum = tmpl.csum;
3429         }
3430         if (priv->hw_csum_l2tun) {
3431                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3432                 rxq->csum_l2tun = tmpl.csum_l2tun;
3433         }
3434         /* Enable scattered packets support for this queue if necessary. */
3435         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
3436         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3437             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3438              (mb_len - RTE_PKTMBUF_HEADROOM))) {
3439                 tmpl.sp = 1;
3440                 desc_n /= MLX4_PMD_SGE_WR_N;
3441         } else
3442                 tmpl.sp = 0;
3443         DEBUG("%p: %s scattered packets support (%u WRs)",
3444               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc_n);
3445         /* If scatter mode is the same as before, nothing to do. */
3446         if (tmpl.sp == rxq->sp) {
3447                 DEBUG("%p: nothing to do", (void *)dev);
3448                 return 0;
3449         }
3450         /* Remove attached flows if RSS is disabled (no parent queue). */
3451         if (!priv->rss) {
3452                 rxq_allmulticast_disable(&tmpl);
3453                 rxq_promiscuous_disable(&tmpl);
3454                 rxq_mac_addrs_del(&tmpl);
3455                 /* Update original queue in case of failure. */
3456                 rxq->allmulti_flow = tmpl.allmulti_flow;
3457                 rxq->promisc_flow = tmpl.promisc_flow;
3458                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3459                        sizeof(rxq->mac_configured));
3460                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3461         }
3462         /* From now on, any failure will render the queue unusable.
3463          * Reinitialize QP. */
3464         mod = (struct ibv_exp_qp_attr){ .qp_state = IBV_QPS_RESET };
3465         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3466         if (err) {
3467                 ERROR("%p: cannot reset QP: %s", (void *)dev, strerror(err));
3468                 assert(err > 0);
3469                 return err;
3470         }
3471         err = ibv_resize_cq(tmpl.cq, desc_n);
3472         if (err) {
3473                 ERROR("%p: cannot resize CQ: %s", (void *)dev, strerror(err));
3474                 assert(err > 0);
3475                 return err;
3476         }
3477         mod = (struct ibv_exp_qp_attr){
3478                 /* Move the QP to this state. */
3479                 .qp_state = IBV_QPS_INIT,
3480                 /* Primary port number. */
3481                 .port_num = priv->port
3482         };
3483         err = ibv_exp_modify_qp(tmpl.qp, &mod,
3484                                 (IBV_EXP_QP_STATE |
3485 #ifdef RSS_SUPPORT
3486                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3487 #endif /* RSS_SUPPORT */
3488                                  IBV_EXP_QP_PORT));
3489         if (err) {
3490                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3491                       (void *)dev, strerror(err));
3492                 assert(err > 0);
3493                 return err;
3494         };
3495         /* Reconfigure flows. Do not care for errors. */
3496         if (!priv->rss) {
3497                 rxq_mac_addrs_add(&tmpl);
3498                 if (priv->promisc)
3499                         rxq_promiscuous_enable(&tmpl);
3500                 if (priv->allmulti)
3501                         rxq_allmulticast_enable(&tmpl);
3502                 /* Update original queue in case of failure. */
3503                 rxq->allmulti_flow = tmpl.allmulti_flow;
3504                 rxq->promisc_flow = tmpl.promisc_flow;
3505                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3506                        sizeof(rxq->mac_configured));
3507                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3508         }
3509         /* Allocate pool. */
3510         pool = rte_malloc(__func__, (mbuf_n * sizeof(*pool)), 0);
3511         if (pool == NULL) {
3512                 ERROR("%p: cannot allocate memory", (void *)dev);
3513                 return ENOBUFS;
3514         }
3515         /* Snatch mbufs from original queue. */
3516         k = 0;
3517         if (rxq->sp) {
3518                 struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
3519
3520                 for (i = 0; (i != elemof(*elts)); ++i) {
3521                         struct rxq_elt_sp *elt = &(*elts)[i];
3522                         unsigned int j;
3523
3524                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
3525                                 assert(elt->bufs[j] != NULL);
3526                                 pool[k++] = elt->bufs[j];
3527                         }
3528                 }
3529         } else {
3530                 struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
3531
3532                 for (i = 0; (i != elemof(*elts)); ++i) {
3533                         struct rxq_elt *elt = &(*elts)[i];
3534                         struct rte_mbuf *buf = (void *)
3535                                 ((uintptr_t)elt->sge.addr -
3536                                  WR_ID(elt->wr.wr_id).offset);
3537
3538                         assert(WR_ID(elt->wr.wr_id).id == i);
3539                         pool[k++] = buf;
3540                 }
3541         }
3542         assert(k == mbuf_n);
3543         tmpl.elts_n = 0;
3544         tmpl.elts.sp = NULL;
3545         assert((void *)&tmpl.elts.sp == (void *)&tmpl.elts.no_sp);
3546         err = ((tmpl.sp) ?
3547                rxq_alloc_elts_sp(&tmpl, desc_n, pool) :
3548                rxq_alloc_elts(&tmpl, desc_n, pool));
3549         if (err) {
3550                 ERROR("%p: cannot reallocate WRs, aborting", (void *)dev);
3551                 rte_free(pool);
3552                 assert(err > 0);
3553                 return err;
3554         }
3555         assert(tmpl.elts_n == desc_n);
3556         assert(tmpl.elts.sp != NULL);
3557         rte_free(pool);
3558         /* Clean up original data. */
3559         rxq->elts_n = 0;
3560         rte_free(rxq->elts.sp);
3561         rxq->elts.sp = NULL;
3562         /* Post WRs. */
3563         err = ibv_post_recv(tmpl.qp,
3564                             (tmpl.sp ?
3565                              &(*tmpl.elts.sp)[0].wr :
3566                              &(*tmpl.elts.no_sp)[0].wr),
3567                             &bad_wr);
3568         if (err) {
3569                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3570                       (void *)dev,
3571                       (void *)bad_wr,
3572                       strerror(err));
3573                 goto skip_rtr;
3574         }
3575         mod = (struct ibv_exp_qp_attr){
3576                 .qp_state = IBV_QPS_RTR
3577         };
3578         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3579         if (err)
3580                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3581                       (void *)dev, strerror(err));
3582 skip_rtr:
3583         *rxq = tmpl;
3584         assert(err >= 0);
3585         return err;
3586 }
3587
3588 /**
3589  * Configure a RX queue.
3590  *
3591  * @param dev
3592  *   Pointer to Ethernet device structure.
3593  * @param rxq
3594  *   Pointer to RX queue structure.
3595  * @param desc
3596  *   Number of descriptors to configure in queue.
3597  * @param socket
3598  *   NUMA socket on which memory must be allocated.
3599  * @param inactive
3600  *   If true, the queue is disabled because its index is higher or
3601  *   equal to the real number of queues, which must be a power of 2.
3602  * @param[in] conf
3603  *   Thresholds parameters.
3604  * @param mp
3605  *   Memory pool for buffer allocations.
3606  *
3607  * @return
3608  *   0 on success, errno value on failure.
3609  */
3610 static int
3611 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
3612           unsigned int socket, int inactive, const struct rte_eth_rxconf *conf,
3613           struct rte_mempool *mp)
3614 {
3615         struct priv *priv = dev->data->dev_private;
3616         struct rxq tmpl = {
3617                 .priv = priv,
3618                 .mp = mp,
3619                 .socket = socket
3620         };
3621         struct ibv_exp_qp_attr mod;
3622         union {
3623                 struct ibv_exp_query_intf_params params;
3624                 struct ibv_exp_cq_init_attr cq;
3625                 struct ibv_exp_res_domain_init_attr rd;
3626         } attr;
3627         enum ibv_exp_query_intf_status status;
3628         struct ibv_recv_wr *bad_wr;
3629         unsigned int mb_len;
3630         int ret = 0;
3631         int parent = (rxq == &priv->rxq_parent);
3632
3633         (void)conf; /* Thresholds configuration (ignored). */
3634         /*
3635          * If this is a parent queue, hardware must support RSS and
3636          * RSS must be enabled.
3637          */
3638         assert((!parent) || ((priv->hw_rss) && (priv->rss)));
3639         if (parent) {
3640                 /* Even if unused, ibv_create_cq() requires at least one
3641                  * descriptor. */
3642                 desc = 1;
3643                 goto skip_mr;
3644         }
3645         mb_len = rte_pktmbuf_data_room_size(mp);
3646         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
3647                 ERROR("%p: invalid number of RX descriptors (must be a"
3648                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
3649                 return EINVAL;
3650         }
3651         /* Toggle RX checksum offload if hardware supports it. */
3652         if (priv->hw_csum)
3653                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3654         if (priv->hw_csum_l2tun)
3655                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3656         /* Enable scattered packets support for this queue if necessary. */
3657         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
3658         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3659             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3660              (mb_len - RTE_PKTMBUF_HEADROOM))) {
3661                 tmpl.sp = 1;
3662                 desc /= MLX4_PMD_SGE_WR_N;
3663         }
3664         DEBUG("%p: %s scattered packets support (%u WRs)",
3665               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
3666         /* Use the entire RX mempool as the memory region. */
3667         tmpl.mr = mlx4_mp2mr(priv->pd, mp);
3668         if (tmpl.mr == NULL) {
3669                 ret = EINVAL;
3670                 ERROR("%p: MR creation failure: %s",
3671                       (void *)dev, strerror(ret));
3672                 goto error;
3673         }
3674 skip_mr:
3675         attr.rd = (struct ibv_exp_res_domain_init_attr){
3676                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
3677                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
3678                 .thread_model = IBV_EXP_THREAD_SINGLE,
3679                 .msg_model = IBV_EXP_MSG_HIGH_BW,
3680         };
3681         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
3682         if (tmpl.rd == NULL) {
3683                 ret = ENOMEM;
3684                 ERROR("%p: RD creation failure: %s",
3685                       (void *)dev, strerror(ret));
3686                 goto error;
3687         }
3688         attr.cq = (struct ibv_exp_cq_init_attr){
3689                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
3690                 .res_domain = tmpl.rd,
3691         };
3692         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
3693         if (tmpl.cq == NULL) {
3694                 ret = ENOMEM;
3695                 ERROR("%p: CQ creation failure: %s",
3696                       (void *)dev, strerror(ret));
3697                 goto error;
3698         }
3699         DEBUG("priv->device_attr.max_qp_wr is %d",
3700               priv->device_attr.max_qp_wr);
3701         DEBUG("priv->device_attr.max_sge is %d",
3702               priv->device_attr.max_sge);
3703 #ifdef RSS_SUPPORT
3704         if (priv->rss && !inactive)
3705                 tmpl.qp = rxq_setup_qp_rss(priv, tmpl.cq, desc, parent,
3706                                            tmpl.rd);
3707         else
3708 #endif /* RSS_SUPPORT */
3709                 tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc, tmpl.rd);
3710         if (tmpl.qp == NULL) {
3711                 ret = (errno ? errno : EINVAL);
3712                 ERROR("%p: QP creation failure: %s",
3713                       (void *)dev, strerror(ret));
3714                 goto error;
3715         }
3716         mod = (struct ibv_exp_qp_attr){
3717                 /* Move the QP to this state. */
3718                 .qp_state = IBV_QPS_INIT,
3719                 /* Primary port number. */
3720                 .port_num = priv->port
3721         };
3722         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
3723                                 (IBV_EXP_QP_STATE |
3724 #ifdef RSS_SUPPORT
3725                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3726 #endif /* RSS_SUPPORT */
3727                                  IBV_EXP_QP_PORT));
3728         if (ret) {
3729                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3730                       (void *)dev, strerror(ret));
3731                 goto error;
3732         }
3733         if ((parent) || (!priv->rss))  {
3734                 /* Configure MAC and broadcast addresses. */
3735                 ret = rxq_mac_addrs_add(&tmpl);
3736                 if (ret) {
3737                         ERROR("%p: QP flow attachment failed: %s",
3738                               (void *)dev, strerror(ret));
3739                         goto error;
3740                 }
3741         }
3742         /* Allocate descriptors for RX queues, except for the RSS parent. */
3743         if (parent)
3744                 goto skip_alloc;
3745         if (tmpl.sp)
3746                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
3747         else
3748                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
3749         if (ret) {
3750                 ERROR("%p: RXQ allocation failed: %s",
3751                       (void *)dev, strerror(ret));
3752                 goto error;
3753         }
3754         ret = ibv_post_recv(tmpl.qp,
3755                             (tmpl.sp ?
3756                              &(*tmpl.elts.sp)[0].wr :
3757                              &(*tmpl.elts.no_sp)[0].wr),
3758                             &bad_wr);
3759         if (ret) {
3760                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3761                       (void *)dev,
3762                       (void *)bad_wr,
3763                       strerror(ret));
3764                 goto error;
3765         }
3766 skip_alloc:
3767         mod = (struct ibv_exp_qp_attr){
3768                 .qp_state = IBV_QPS_RTR
3769         };
3770         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3771         if (ret) {
3772                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3773                       (void *)dev, strerror(ret));
3774                 goto error;
3775         }
3776         /* Save port ID. */
3777         tmpl.port_id = dev->data->port_id;
3778         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
3779         attr.params = (struct ibv_exp_query_intf_params){
3780                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3781                 .intf = IBV_EXP_INTF_CQ,
3782                 .obj = tmpl.cq,
3783         };
3784         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3785         if (tmpl.if_cq == NULL) {
3786                 ERROR("%p: CQ interface family query failed with status %d",
3787                       (void *)dev, status);
3788                 goto error;
3789         }
3790         attr.params = (struct ibv_exp_query_intf_params){
3791                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3792                 .intf = IBV_EXP_INTF_QP_BURST,
3793                 .obj = tmpl.qp,
3794         };
3795         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3796         if (tmpl.if_qp == NULL) {
3797                 ERROR("%p: QP interface family query failed with status %d",
3798                       (void *)dev, status);
3799                 goto error;
3800         }
3801         /* Clean up rxq in case we're reinitializing it. */
3802         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
3803         rxq_cleanup(rxq);
3804         *rxq = tmpl;
3805         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
3806         assert(ret == 0);
3807         return 0;
3808 error:
3809         rxq_cleanup(&tmpl);
3810         assert(ret > 0);
3811         return ret;
3812 }
3813
3814 /**
3815  * DPDK callback to configure a RX queue.
3816  *
3817  * @param dev
3818  *   Pointer to Ethernet device structure.
3819  * @param idx
3820  *   RX queue index.
3821  * @param desc
3822  *   Number of descriptors to configure in queue.
3823  * @param socket
3824  *   NUMA socket on which memory must be allocated.
3825  * @param[in] conf
3826  *   Thresholds parameters.
3827  * @param mp
3828  *   Memory pool for buffer allocations.
3829  *
3830  * @return
3831  *   0 on success, negative errno value on failure.
3832  */
3833 static int
3834 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
3835                     unsigned int socket, const struct rte_eth_rxconf *conf,
3836                     struct rte_mempool *mp)
3837 {
3838         struct priv *priv = dev->data->dev_private;
3839         struct rxq *rxq = (*priv->rxqs)[idx];
3840         int inactive = 0;
3841         int ret;
3842
3843         if (mlx4_is_secondary())
3844                 return -E_RTE_SECONDARY;
3845         priv_lock(priv);
3846         DEBUG("%p: configuring queue %u for %u descriptors",
3847               (void *)dev, idx, desc);
3848         if (idx >= priv->rxqs_n) {
3849                 ERROR("%p: queue index out of range (%u >= %u)",
3850                       (void *)dev, idx, priv->rxqs_n);
3851                 priv_unlock(priv);
3852                 return -EOVERFLOW;
3853         }
3854         if (rxq != NULL) {
3855                 DEBUG("%p: reusing already allocated queue index %u (%p)",
3856                       (void *)dev, idx, (void *)rxq);
3857                 if (priv->started) {
3858                         priv_unlock(priv);
3859                         return -EEXIST;
3860                 }
3861                 (*priv->rxqs)[idx] = NULL;
3862                 rxq_cleanup(rxq);
3863         } else {
3864                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
3865                 if (rxq == NULL) {
3866                         ERROR("%p: unable to allocate queue index %u",
3867                               (void *)dev, idx);
3868                         priv_unlock(priv);
3869                         return -ENOMEM;
3870                 }
3871         }
3872         if (idx >= rte_align32pow2(priv->rxqs_n + 1) >> 1)
3873                 inactive = 1;
3874         ret = rxq_setup(dev, rxq, desc, socket, inactive, conf, mp);
3875         if (ret)
3876                 rte_free(rxq);
3877         else {
3878                 rxq->stats.idx = idx;
3879                 DEBUG("%p: adding RX queue %p to list",
3880                       (void *)dev, (void *)rxq);
3881                 (*priv->rxqs)[idx] = rxq;
3882                 /* Update receive callback. */
3883                 if (rxq->sp)
3884                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3885                 else
3886                         dev->rx_pkt_burst = mlx4_rx_burst;
3887         }
3888         priv_unlock(priv);
3889         return -ret;
3890 }
3891
3892 /**
3893  * DPDK callback to release a RX queue.
3894  *
3895  * @param dpdk_rxq
3896  *   Generic RX queue pointer.
3897  */
3898 static void
3899 mlx4_rx_queue_release(void *dpdk_rxq)
3900 {
3901         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3902         struct priv *priv;
3903         unsigned int i;
3904
3905         if (mlx4_is_secondary())
3906                 return;
3907         if (rxq == NULL)
3908                 return;
3909         priv = rxq->priv;
3910         priv_lock(priv);
3911         assert(rxq != &priv->rxq_parent);
3912         for (i = 0; (i != priv->rxqs_n); ++i)
3913                 if ((*priv->rxqs)[i] == rxq) {
3914                         DEBUG("%p: removing RX queue %p from list",
3915                               (void *)priv->dev, (void *)rxq);
3916                         (*priv->rxqs)[i] = NULL;
3917                         break;
3918                 }
3919         rxq_cleanup(rxq);
3920         rte_free(rxq);
3921         priv_unlock(priv);
3922 }
3923
3924 static void
3925 priv_dev_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
3926
3927 /**
3928  * DPDK callback to start the device.
3929  *
3930  * Simulate device start by attaching all configured flows.
3931  *
3932  * @param dev
3933  *   Pointer to Ethernet device structure.
3934  *
3935  * @return
3936  *   0 on success, negative errno value on failure.
3937  */
3938 static int
3939 mlx4_dev_start(struct rte_eth_dev *dev)
3940 {
3941         struct priv *priv = dev->data->dev_private;
3942         unsigned int i = 0;
3943         unsigned int r;
3944         struct rxq *rxq;
3945         int ret;
3946
3947         if (mlx4_is_secondary())
3948                 return -E_RTE_SECONDARY;
3949         priv_lock(priv);
3950         if (priv->started) {
3951                 priv_unlock(priv);
3952                 return 0;
3953         }
3954         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
3955         priv->started = 1;
3956         if (priv->rss) {
3957                 rxq = &priv->rxq_parent;
3958                 r = 1;
3959         } else {
3960                 rxq = (*priv->rxqs)[0];
3961                 r = priv->rxqs_n;
3962         }
3963         /* Iterate only once when RSS is enabled. */
3964         do {
3965                 /* Ignore nonexistent RX queues. */
3966                 if (rxq == NULL)
3967                         continue;
3968                 ret = rxq_mac_addrs_add(rxq);
3969                 if (!ret && priv->promisc)
3970                         ret = rxq_promiscuous_enable(rxq);
3971                 if (!ret && priv->allmulti)
3972                         ret = rxq_allmulticast_enable(rxq);
3973                 if (!ret)
3974                         continue;
3975                 WARN("%p: QP flow attachment failed: %s",
3976                      (void *)dev, strerror(ret));
3977                 goto err;
3978         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3979         priv_dev_interrupt_handler_install(priv, dev);
3980         ret = mlx4_priv_flow_start(priv);
3981         if (ret) {
3982                 ERROR("%p: flow start failed: %s",
3983                       (void *)dev, strerror(ret));
3984                 goto err;
3985         }
3986         priv_unlock(priv);
3987         return 0;
3988 err:
3989         /* Rollback. */
3990         while (i != 0) {
3991                 rxq = (*priv->rxqs)[i--];
3992                 if (rxq != NULL) {
3993                         rxq_allmulticast_disable(rxq);
3994                         rxq_promiscuous_disable(rxq);
3995                         rxq_mac_addrs_del(rxq);
3996                 }
3997         }
3998         priv->started = 0;
3999         priv_unlock(priv);
4000         return -ret;
4001 }
4002
4003 /**
4004  * DPDK callback to stop the device.
4005  *
4006  * Simulate device stop by detaching all configured flows.
4007  *
4008  * @param dev
4009  *   Pointer to Ethernet device structure.
4010  */
4011 static void
4012 mlx4_dev_stop(struct rte_eth_dev *dev)
4013 {
4014         struct priv *priv = dev->data->dev_private;
4015         unsigned int i = 0;
4016         unsigned int r;
4017         struct rxq *rxq;
4018
4019         if (mlx4_is_secondary())
4020                 return;
4021         priv_lock(priv);
4022         if (!priv->started) {
4023                 priv_unlock(priv);
4024                 return;
4025         }
4026         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
4027         priv->started = 0;
4028         if (priv->rss) {
4029                 rxq = &priv->rxq_parent;
4030                 r = 1;
4031         } else {
4032                 rxq = (*priv->rxqs)[0];
4033                 r = priv->rxqs_n;
4034         }
4035         mlx4_priv_flow_stop(priv);
4036         /* Iterate only once when RSS is enabled. */
4037         do {
4038                 /* Ignore nonexistent RX queues. */
4039                 if (rxq == NULL)
4040                         continue;
4041                 rxq_allmulticast_disable(rxq);
4042                 rxq_promiscuous_disable(rxq);
4043                 rxq_mac_addrs_del(rxq);
4044         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
4045         priv_unlock(priv);
4046 }
4047
4048 /**
4049  * Dummy DPDK callback for TX.
4050  *
4051  * This function is used to temporarily replace the real callback during
4052  * unsafe control operations on the queue, or in case of error.
4053  *
4054  * @param dpdk_txq
4055  *   Generic pointer to TX queue structure.
4056  * @param[in] pkts
4057  *   Packets to transmit.
4058  * @param pkts_n
4059  *   Number of packets in array.
4060  *
4061  * @return
4062  *   Number of packets successfully transmitted (<= pkts_n).
4063  */
4064 static uint16_t
4065 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
4066 {
4067         (void)dpdk_txq;
4068         (void)pkts;
4069         (void)pkts_n;
4070         return 0;
4071 }
4072
4073 /**
4074  * Dummy DPDK callback for RX.
4075  *
4076  * This function is used to temporarily replace the real callback during
4077  * unsafe control operations on the queue, or in case of error.
4078  *
4079  * @param dpdk_rxq
4080  *   Generic pointer to RX queue structure.
4081  * @param[out] pkts
4082  *   Array to store received packets.
4083  * @param pkts_n
4084  *   Maximum number of packets in array.
4085  *
4086  * @return
4087  *   Number of packets successfully received (<= pkts_n).
4088  */
4089 static uint16_t
4090 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
4091 {
4092         (void)dpdk_rxq;
4093         (void)pkts;
4094         (void)pkts_n;
4095         return 0;
4096 }
4097
4098 static void
4099 priv_dev_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
4100
4101 /**
4102  * DPDK callback to close the device.
4103  *
4104  * Destroy all queues and objects, free memory.
4105  *
4106  * @param dev
4107  *   Pointer to Ethernet device structure.
4108  */
4109 static void
4110 mlx4_dev_close(struct rte_eth_dev *dev)
4111 {
4112         struct priv *priv = mlx4_get_priv(dev);
4113         void *tmp;
4114         unsigned int i;
4115
4116         if (priv == NULL)
4117                 return;
4118         priv_lock(priv);
4119         DEBUG("%p: closing device \"%s\"",
4120               (void *)dev,
4121               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
4122         /* Prevent crashes when queues are still in use. This is unfortunately
4123          * still required for DPDK 1.3 because some programs (such as testpmd)
4124          * never release them before closing the device. */
4125         dev->rx_pkt_burst = removed_rx_burst;
4126         dev->tx_pkt_burst = removed_tx_burst;
4127         if (priv->rxqs != NULL) {
4128                 /* XXX race condition if mlx4_rx_burst() is still running. */
4129                 usleep(1000);
4130                 for (i = 0; (i != priv->rxqs_n); ++i) {
4131                         tmp = (*priv->rxqs)[i];
4132                         if (tmp == NULL)
4133                                 continue;
4134                         (*priv->rxqs)[i] = NULL;
4135                         rxq_cleanup(tmp);
4136                         rte_free(tmp);
4137                 }
4138                 priv->rxqs_n = 0;
4139                 priv->rxqs = NULL;
4140         }
4141         if (priv->txqs != NULL) {
4142                 /* XXX race condition if mlx4_tx_burst() is still running. */
4143                 usleep(1000);
4144                 for (i = 0; (i != priv->txqs_n); ++i) {
4145                         tmp = (*priv->txqs)[i];
4146                         if (tmp == NULL)
4147                                 continue;
4148                         (*priv->txqs)[i] = NULL;
4149                         txq_cleanup(tmp);
4150                         rte_free(tmp);
4151                 }
4152                 priv->txqs_n = 0;
4153                 priv->txqs = NULL;
4154         }
4155         if (priv->rss)
4156                 rxq_cleanup(&priv->rxq_parent);
4157         if (priv->pd != NULL) {
4158                 assert(priv->ctx != NULL);
4159                 claim_zero(ibv_dealloc_pd(priv->pd));
4160                 claim_zero(ibv_close_device(priv->ctx));
4161         } else
4162                 assert(priv->ctx == NULL);
4163         priv_dev_interrupt_handler_uninstall(priv, dev);
4164         priv_unlock(priv);
4165         memset(priv, 0, sizeof(*priv));
4166 }
4167
4168 /**
4169  * Change the link state (UP / DOWN).
4170  *
4171  * @param priv
4172  *   Pointer to Ethernet device private data.
4173  * @param up
4174  *   Nonzero for link up, otherwise link down.
4175  *
4176  * @return
4177  *   0 on success, errno value on failure.
4178  */
4179 static int
4180 priv_set_link(struct priv *priv, int up)
4181 {
4182         struct rte_eth_dev *dev = priv->dev;
4183         int err;
4184         unsigned int i;
4185
4186         if (up) {
4187                 err = priv_set_flags(priv, ~IFF_UP, IFF_UP);
4188                 if (err)
4189                         return err;
4190                 for (i = 0; i < priv->rxqs_n; i++)
4191                         if ((*priv->rxqs)[i]->sp)
4192                                 break;
4193                 /* Check if an sp queue exists.
4194                  * Note: Some old frames might be received.
4195                  */
4196                 if (i == priv->rxqs_n)
4197                         dev->rx_pkt_burst = mlx4_rx_burst;
4198                 else
4199                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
4200                 dev->tx_pkt_burst = mlx4_tx_burst;
4201         } else {
4202                 err = priv_set_flags(priv, ~IFF_UP, ~IFF_UP);
4203                 if (err)
4204                         return err;
4205                 dev->rx_pkt_burst = removed_rx_burst;
4206                 dev->tx_pkt_burst = removed_tx_burst;
4207         }
4208         return 0;
4209 }
4210
4211 /**
4212  * DPDK callback to bring the link DOWN.
4213  *
4214  * @param dev
4215  *   Pointer to Ethernet device structure.
4216  *
4217  * @return
4218  *   0 on success, errno value on failure.
4219  */
4220 static int
4221 mlx4_set_link_down(struct rte_eth_dev *dev)
4222 {
4223         struct priv *priv = dev->data->dev_private;
4224         int err;
4225
4226         priv_lock(priv);
4227         err = priv_set_link(priv, 0);
4228         priv_unlock(priv);
4229         return err;
4230 }
4231
4232 /**
4233  * DPDK callback to bring the link UP.
4234  *
4235  * @param dev
4236  *   Pointer to Ethernet device structure.
4237  *
4238  * @return
4239  *   0 on success, errno value on failure.
4240  */
4241 static int
4242 mlx4_set_link_up(struct rte_eth_dev *dev)
4243 {
4244         struct priv *priv = dev->data->dev_private;
4245         int err;
4246
4247         priv_lock(priv);
4248         err = priv_set_link(priv, 1);
4249         priv_unlock(priv);
4250         return err;
4251 }
4252 /**
4253  * DPDK callback to get information about the device.
4254  *
4255  * @param dev
4256  *   Pointer to Ethernet device structure.
4257  * @param[out] info
4258  *   Info structure output buffer.
4259  */
4260 static void
4261 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
4262 {
4263         struct priv *priv = mlx4_get_priv(dev);
4264         unsigned int max;
4265         char ifname[IF_NAMESIZE];
4266
4267         info->pci_dev = RTE_DEV_TO_PCI(dev->device);
4268
4269         if (priv == NULL)
4270                 return;
4271         priv_lock(priv);
4272         /* FIXME: we should ask the device for these values. */
4273         info->min_rx_bufsize = 32;
4274         info->max_rx_pktlen = 65536;
4275         /*
4276          * Since we need one CQ per QP, the limit is the minimum number
4277          * between the two values.
4278          */
4279         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
4280                priv->device_attr.max_qp : priv->device_attr.max_cq);
4281         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
4282         if (max >= 65535)
4283                 max = 65535;
4284         info->max_rx_queues = max;
4285         info->max_tx_queues = max;
4286         /* Last array entry is reserved for broadcast. */
4287         info->max_mac_addrs = (elemof(priv->mac) - 1);
4288         info->rx_offload_capa =
4289                 (priv->hw_csum ?
4290                  (DEV_RX_OFFLOAD_IPV4_CKSUM |
4291                   DEV_RX_OFFLOAD_UDP_CKSUM |
4292                   DEV_RX_OFFLOAD_TCP_CKSUM) :
4293                  0);
4294         info->tx_offload_capa =
4295                 (priv->hw_csum ?
4296                  (DEV_TX_OFFLOAD_IPV4_CKSUM |
4297                   DEV_TX_OFFLOAD_UDP_CKSUM |
4298                   DEV_TX_OFFLOAD_TCP_CKSUM) :
4299                  0);
4300         if (priv_get_ifname(priv, &ifname) == 0)
4301                 info->if_index = if_nametoindex(ifname);
4302         info->speed_capa =
4303                         ETH_LINK_SPEED_1G |
4304                         ETH_LINK_SPEED_10G |
4305                         ETH_LINK_SPEED_20G |
4306                         ETH_LINK_SPEED_40G |
4307                         ETH_LINK_SPEED_56G;
4308         priv_unlock(priv);
4309 }
4310
4311 static const uint32_t *
4312 mlx4_dev_supported_ptypes_get(struct rte_eth_dev *dev)
4313 {
4314         static const uint32_t ptypes[] = {
4315                 /* refers to rxq_cq_to_pkt_type() */
4316                 RTE_PTYPE_L3_IPV4,
4317                 RTE_PTYPE_L3_IPV6,
4318                 RTE_PTYPE_INNER_L3_IPV4,
4319                 RTE_PTYPE_INNER_L3_IPV6,
4320                 RTE_PTYPE_UNKNOWN
4321         };
4322
4323         if (dev->rx_pkt_burst == mlx4_rx_burst ||
4324             dev->rx_pkt_burst == mlx4_rx_burst_sp)
4325                 return ptypes;
4326         return NULL;
4327 }
4328
4329 /**
4330  * DPDK callback to get device statistics.
4331  *
4332  * @param dev
4333  *   Pointer to Ethernet device structure.
4334  * @param[out] stats
4335  *   Stats structure output buffer.
4336  */
4337 static void
4338 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
4339 {
4340         struct priv *priv = mlx4_get_priv(dev);
4341         struct rte_eth_stats tmp = {0};
4342         unsigned int i;
4343         unsigned int idx;
4344
4345         if (priv == NULL)
4346                 return;
4347         priv_lock(priv);
4348         /* Add software counters. */
4349         for (i = 0; (i != priv->rxqs_n); ++i) {
4350                 struct rxq *rxq = (*priv->rxqs)[i];
4351
4352                 if (rxq == NULL)
4353                         continue;
4354                 idx = rxq->stats.idx;
4355                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
4356 #ifdef MLX4_PMD_SOFT_COUNTERS
4357                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
4358                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
4359 #endif
4360                         tmp.q_errors[idx] += (rxq->stats.idropped +
4361                                               rxq->stats.rx_nombuf);
4362                 }
4363 #ifdef MLX4_PMD_SOFT_COUNTERS
4364                 tmp.ipackets += rxq->stats.ipackets;
4365                 tmp.ibytes += rxq->stats.ibytes;
4366 #endif
4367                 tmp.ierrors += rxq->stats.idropped;
4368                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
4369         }
4370         for (i = 0; (i != priv->txqs_n); ++i) {
4371                 struct txq *txq = (*priv->txqs)[i];
4372
4373                 if (txq == NULL)
4374                         continue;
4375                 idx = txq->stats.idx;
4376                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
4377 #ifdef MLX4_PMD_SOFT_COUNTERS
4378                         tmp.q_opackets[idx] += txq->stats.opackets;
4379                         tmp.q_obytes[idx] += txq->stats.obytes;
4380 #endif
4381                         tmp.q_errors[idx] += txq->stats.odropped;
4382                 }
4383 #ifdef MLX4_PMD_SOFT_COUNTERS
4384                 tmp.opackets += txq->stats.opackets;
4385                 tmp.obytes += txq->stats.obytes;
4386 #endif
4387                 tmp.oerrors += txq->stats.odropped;
4388         }
4389 #ifndef MLX4_PMD_SOFT_COUNTERS
4390         /* FIXME: retrieve and add hardware counters. */
4391 #endif
4392         *stats = tmp;
4393         priv_unlock(priv);
4394 }
4395
4396 /**
4397  * DPDK callback to clear device statistics.
4398  *
4399  * @param dev
4400  *   Pointer to Ethernet device structure.
4401  */
4402 static void
4403 mlx4_stats_reset(struct rte_eth_dev *dev)
4404 {
4405         struct priv *priv = mlx4_get_priv(dev);
4406         unsigned int i;
4407         unsigned int idx;
4408
4409         if (priv == NULL)
4410                 return;
4411         priv_lock(priv);
4412         for (i = 0; (i != priv->rxqs_n); ++i) {
4413                 if ((*priv->rxqs)[i] == NULL)
4414                         continue;
4415                 idx = (*priv->rxqs)[i]->stats.idx;
4416                 (*priv->rxqs)[i]->stats =
4417                         (struct mlx4_rxq_stats){ .idx = idx };
4418         }
4419         for (i = 0; (i != priv->txqs_n); ++i) {
4420                 if ((*priv->txqs)[i] == NULL)
4421                         continue;
4422                 idx = (*priv->txqs)[i]->stats.idx;
4423                 (*priv->txqs)[i]->stats =
4424                         (struct mlx4_txq_stats){ .idx = idx };
4425         }
4426 #ifndef MLX4_PMD_SOFT_COUNTERS
4427         /* FIXME: reset hardware counters. */
4428 #endif
4429         priv_unlock(priv);
4430 }
4431
4432 /**
4433  * DPDK callback to remove a MAC address.
4434  *
4435  * @param dev
4436  *   Pointer to Ethernet device structure.
4437  * @param index
4438  *   MAC address index.
4439  */
4440 static void
4441 mlx4_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
4442 {
4443         struct priv *priv = dev->data->dev_private;
4444
4445         if (mlx4_is_secondary())
4446                 return;
4447         priv_lock(priv);
4448         DEBUG("%p: removing MAC address from index %" PRIu32,
4449               (void *)dev, index);
4450         /* Last array entry is reserved for broadcast. */
4451         if (index >= (elemof(priv->mac) - 1))
4452                 goto end;
4453         priv_mac_addr_del(priv, index);
4454 end:
4455         priv_unlock(priv);
4456 }
4457
4458 /**
4459  * DPDK callback to add a MAC address.
4460  *
4461  * @param dev
4462  *   Pointer to Ethernet device structure.
4463  * @param mac_addr
4464  *   MAC address to register.
4465  * @param index
4466  *   MAC address index.
4467  * @param vmdq
4468  *   VMDq pool index to associate address with (ignored).
4469  */
4470 static void
4471 mlx4_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
4472                   uint32_t index, uint32_t vmdq)
4473 {
4474         struct priv *priv = dev->data->dev_private;
4475
4476         if (mlx4_is_secondary())
4477                 return;
4478         (void)vmdq;
4479         priv_lock(priv);
4480         DEBUG("%p: adding MAC address at index %" PRIu32,
4481               (void *)dev, index);
4482         /* Last array entry is reserved for broadcast. */
4483         if (index >= (elemof(priv->mac) - 1))
4484                 goto end;
4485         priv_mac_addr_add(priv, index,
4486                           (const uint8_t (*)[ETHER_ADDR_LEN])
4487                           mac_addr->addr_bytes);
4488 end:
4489         priv_unlock(priv);
4490 }
4491
4492 /**
4493  * DPDK callback to set the primary MAC address.
4494  *
4495  * @param dev
4496  *   Pointer to Ethernet device structure.
4497  * @param mac_addr
4498  *   MAC address to register.
4499  */
4500 static void
4501 mlx4_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
4502 {
4503         DEBUG("%p: setting primary MAC address", (void *)dev);
4504         mlx4_mac_addr_remove(dev, 0);
4505         mlx4_mac_addr_add(dev, mac_addr, 0, 0);
4506 }
4507
4508 /**
4509  * DPDK callback to enable promiscuous mode.
4510  *
4511  * @param dev
4512  *   Pointer to Ethernet device structure.
4513  */
4514 static void
4515 mlx4_promiscuous_enable(struct rte_eth_dev *dev)
4516 {
4517         struct priv *priv = dev->data->dev_private;
4518         unsigned int i;
4519         int ret;
4520
4521         if (mlx4_is_secondary())
4522                 return;
4523         priv_lock(priv);
4524         if (priv->promisc) {
4525                 priv_unlock(priv);
4526                 return;
4527         }
4528         /* If device isn't started, this is all we need to do. */
4529         if (!priv->started)
4530                 goto end;
4531         if (priv->rss) {
4532                 ret = rxq_promiscuous_enable(&priv->rxq_parent);
4533                 if (ret) {
4534                         priv_unlock(priv);
4535                         return;
4536                 }
4537                 goto end;
4538         }
4539         for (i = 0; (i != priv->rxqs_n); ++i) {
4540                 if ((*priv->rxqs)[i] == NULL)
4541                         continue;
4542                 ret = rxq_promiscuous_enable((*priv->rxqs)[i]);
4543                 if (!ret)
4544                         continue;
4545                 /* Failure, rollback. */
4546                 while (i != 0)
4547                         if ((*priv->rxqs)[--i] != NULL)
4548                                 rxq_promiscuous_disable((*priv->rxqs)[i]);
4549                 priv_unlock(priv);
4550                 return;
4551         }
4552 end:
4553         priv->promisc = 1;
4554         priv_unlock(priv);
4555 }
4556
4557 /**
4558  * DPDK callback to disable promiscuous mode.
4559  *
4560  * @param dev
4561  *   Pointer to Ethernet device structure.
4562  */
4563 static void
4564 mlx4_promiscuous_disable(struct rte_eth_dev *dev)
4565 {
4566         struct priv *priv = dev->data->dev_private;
4567         unsigned int i;
4568
4569         if (mlx4_is_secondary())
4570                 return;
4571         priv_lock(priv);
4572         if (!priv->promisc) {
4573                 priv_unlock(priv);
4574                 return;
4575         }
4576         if (priv->rss) {
4577                 rxq_promiscuous_disable(&priv->rxq_parent);
4578                 goto end;
4579         }
4580         for (i = 0; (i != priv->rxqs_n); ++i)
4581                 if ((*priv->rxqs)[i] != NULL)
4582                         rxq_promiscuous_disable((*priv->rxqs)[i]);
4583 end:
4584         priv->promisc = 0;
4585         priv_unlock(priv);
4586 }
4587
4588 /**
4589  * DPDK callback to enable allmulti mode.
4590  *
4591  * @param dev
4592  *   Pointer to Ethernet device structure.
4593  */
4594 static void
4595 mlx4_allmulticast_enable(struct rte_eth_dev *dev)
4596 {
4597         struct priv *priv = dev->data->dev_private;
4598         unsigned int i;
4599         int ret;
4600
4601         if (mlx4_is_secondary())
4602                 return;
4603         priv_lock(priv);
4604         if (priv->allmulti) {
4605                 priv_unlock(priv);
4606                 return;
4607         }
4608         /* If device isn't started, this is all we need to do. */
4609         if (!priv->started)
4610                 goto end;
4611         if (priv->rss) {
4612                 ret = rxq_allmulticast_enable(&priv->rxq_parent);
4613                 if (ret) {
4614                         priv_unlock(priv);
4615                         return;
4616                 }
4617                 goto end;
4618         }
4619         for (i = 0; (i != priv->rxqs_n); ++i) {
4620                 if ((*priv->rxqs)[i] == NULL)
4621                         continue;
4622                 ret = rxq_allmulticast_enable((*priv->rxqs)[i]);
4623                 if (!ret)
4624                         continue;
4625                 /* Failure, rollback. */
4626                 while (i != 0)
4627                         if ((*priv->rxqs)[--i] != NULL)
4628                                 rxq_allmulticast_disable((*priv->rxqs)[i]);
4629                 priv_unlock(priv);
4630                 return;
4631         }
4632 end:
4633         priv->allmulti = 1;
4634         priv_unlock(priv);
4635 }
4636
4637 /**
4638  * DPDK callback to disable allmulti mode.
4639  *
4640  * @param dev
4641  *   Pointer to Ethernet device structure.
4642  */
4643 static void
4644 mlx4_allmulticast_disable(struct rte_eth_dev *dev)
4645 {
4646         struct priv *priv = dev->data->dev_private;
4647         unsigned int i;
4648
4649         if (mlx4_is_secondary())
4650                 return;
4651         priv_lock(priv);
4652         if (!priv->allmulti) {
4653                 priv_unlock(priv);
4654                 return;
4655         }
4656         if (priv->rss) {
4657                 rxq_allmulticast_disable(&priv->rxq_parent);
4658                 goto end;
4659         }
4660         for (i = 0; (i != priv->rxqs_n); ++i)
4661                 if ((*priv->rxqs)[i] != NULL)
4662                         rxq_allmulticast_disable((*priv->rxqs)[i]);
4663 end:
4664         priv->allmulti = 0;
4665         priv_unlock(priv);
4666 }
4667
4668 /**
4669  * DPDK callback to retrieve physical link information.
4670  *
4671  * @param dev
4672  *   Pointer to Ethernet device structure.
4673  * @param wait_to_complete
4674  *   Wait for request completion (ignored).
4675  */
4676 static int
4677 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
4678 {
4679         const struct priv *priv = mlx4_get_priv(dev);
4680         struct ethtool_cmd edata = {
4681                 .cmd = ETHTOOL_GSET
4682         };
4683         struct ifreq ifr;
4684         struct rte_eth_link dev_link;
4685         int link_speed = 0;
4686
4687         /* priv_lock() is not taken to allow concurrent calls. */
4688
4689         if (priv == NULL)
4690                 return -EINVAL;
4691         (void)wait_to_complete;
4692         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
4693                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(errno));
4694                 return -1;
4695         }
4696         memset(&dev_link, 0, sizeof(dev_link));
4697         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
4698                                 (ifr.ifr_flags & IFF_RUNNING));
4699         ifr.ifr_data = (void *)&edata;
4700         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4701                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
4702                      strerror(errno));
4703                 return -1;
4704         }
4705         link_speed = ethtool_cmd_speed(&edata);
4706         if (link_speed == -1)
4707                 dev_link.link_speed = 0;
4708         else
4709                 dev_link.link_speed = link_speed;
4710         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
4711                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
4712         dev_link.link_autoneg = !(dev->data->dev_conf.link_speeds &
4713                         ETH_LINK_SPEED_FIXED);
4714         if (memcmp(&dev_link, &dev->data->dev_link, sizeof(dev_link))) {
4715                 /* Link status changed. */
4716                 dev->data->dev_link = dev_link;
4717                 return 0;
4718         }
4719         /* Link status is still the same. */
4720         return -1;
4721 }
4722
4723 /**
4724  * DPDK callback to change the MTU.
4725  *
4726  * Setting the MTU affects hardware MRU (packets larger than the MTU cannot be
4727  * received). Use this as a hint to enable/disable scattered packets support
4728  * and improve performance when not needed.
4729  * Since failure is not an option, reconfiguring queues on the fly is not
4730  * recommended.
4731  *
4732  * @param dev
4733  *   Pointer to Ethernet device structure.
4734  * @param in_mtu
4735  *   New MTU.
4736  *
4737  * @return
4738  *   0 on success, negative errno value on failure.
4739  */
4740 static int
4741 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
4742 {
4743         struct priv *priv = dev->data->dev_private;
4744         int ret = 0;
4745         unsigned int i;
4746         uint16_t (*rx_func)(void *, struct rte_mbuf **, uint16_t) =
4747                 mlx4_rx_burst;
4748
4749         if (mlx4_is_secondary())
4750                 return -E_RTE_SECONDARY;
4751         priv_lock(priv);
4752         /* Set kernel interface MTU first. */
4753         if (priv_set_mtu(priv, mtu)) {
4754                 ret = errno;
4755                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
4756                      strerror(ret));
4757                 goto out;
4758         } else
4759                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
4760         priv->mtu = mtu;
4761         /* Temporarily replace RX handler with a fake one, assuming it has not
4762          * been copied elsewhere. */
4763         dev->rx_pkt_burst = removed_rx_burst;
4764         /* Make sure everyone has left mlx4_rx_burst() and uses
4765          * removed_rx_burst() instead. */
4766         rte_wmb();
4767         usleep(1000);
4768         /* Reconfigure each RX queue. */
4769         for (i = 0; (i != priv->rxqs_n); ++i) {
4770                 struct rxq *rxq = (*priv->rxqs)[i];
4771                 unsigned int mb_len;
4772                 unsigned int max_frame_len;
4773                 int sp;
4774
4775                 if (rxq == NULL)
4776                         continue;
4777                 /* Calculate new maximum frame length according to MTU and
4778                  * toggle scattered support (sp) if necessary. */
4779                 max_frame_len = (priv->mtu + ETHER_HDR_LEN +
4780                                  (ETHER_MAX_VLAN_FRAME_LEN - ETHER_MAX_LEN));
4781                 mb_len = rte_pktmbuf_data_room_size(rxq->mp);
4782                 assert(mb_len >= RTE_PKTMBUF_HEADROOM);
4783                 sp = (max_frame_len > (mb_len - RTE_PKTMBUF_HEADROOM));
4784                 /* Provide new values to rxq_setup(). */
4785                 dev->data->dev_conf.rxmode.jumbo_frame = sp;
4786                 dev->data->dev_conf.rxmode.max_rx_pkt_len = max_frame_len;
4787                 ret = rxq_rehash(dev, rxq);
4788                 if (ret) {
4789                         /* Force SP RX if that queue requires it and abort. */
4790                         if (rxq->sp)
4791                                 rx_func = mlx4_rx_burst_sp;
4792                         break;
4793                 }
4794                 /* Reenable non-RSS queue attributes. No need to check
4795                  * for errors at this stage. */
4796                 if (!priv->rss) {
4797                         rxq_mac_addrs_add(rxq);
4798                         if (priv->promisc)
4799                                 rxq_promiscuous_enable(rxq);
4800                         if (priv->allmulti)
4801                                 rxq_allmulticast_enable(rxq);
4802                 }
4803                 /* Scattered burst function takes priority. */
4804                 if (rxq->sp)
4805                         rx_func = mlx4_rx_burst_sp;
4806         }
4807         /* Burst functions can now be called again. */
4808         rte_wmb();
4809         dev->rx_pkt_burst = rx_func;
4810 out:
4811         priv_unlock(priv);
4812         assert(ret >= 0);
4813         return -ret;
4814 }
4815
4816 /**
4817  * DPDK callback to get flow control status.
4818  *
4819  * @param dev
4820  *   Pointer to Ethernet device structure.
4821  * @param[out] fc_conf
4822  *   Flow control output buffer.
4823  *
4824  * @return
4825  *   0 on success, negative errno value on failure.
4826  */
4827 static int
4828 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4829 {
4830         struct priv *priv = dev->data->dev_private;
4831         struct ifreq ifr;
4832         struct ethtool_pauseparam ethpause = {
4833                 .cmd = ETHTOOL_GPAUSEPARAM
4834         };
4835         int ret;
4836
4837         if (mlx4_is_secondary())
4838                 return -E_RTE_SECONDARY;
4839         ifr.ifr_data = (void *)&ethpause;
4840         priv_lock(priv);
4841         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4842                 ret = errno;
4843                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
4844                      " failed: %s",
4845                      strerror(ret));
4846                 goto out;
4847         }
4848
4849         fc_conf->autoneg = ethpause.autoneg;
4850         if (ethpause.rx_pause && ethpause.tx_pause)
4851                 fc_conf->mode = RTE_FC_FULL;
4852         else if (ethpause.rx_pause)
4853                 fc_conf->mode = RTE_FC_RX_PAUSE;
4854         else if (ethpause.tx_pause)
4855                 fc_conf->mode = RTE_FC_TX_PAUSE;
4856         else
4857                 fc_conf->mode = RTE_FC_NONE;
4858         ret = 0;
4859
4860 out:
4861         priv_unlock(priv);
4862         assert(ret >= 0);
4863         return -ret;
4864 }
4865
4866 /**
4867  * DPDK callback to modify flow control parameters.
4868  *
4869  * @param dev
4870  *   Pointer to Ethernet device structure.
4871  * @param[in] fc_conf
4872  *   Flow control parameters.
4873  *
4874  * @return
4875  *   0 on success, negative errno value on failure.
4876  */
4877 static int
4878 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4879 {
4880         struct priv *priv = dev->data->dev_private;
4881         struct ifreq ifr;
4882         struct ethtool_pauseparam ethpause = {
4883                 .cmd = ETHTOOL_SPAUSEPARAM
4884         };
4885         int ret;
4886
4887         if (mlx4_is_secondary())
4888                 return -E_RTE_SECONDARY;
4889         ifr.ifr_data = (void *)&ethpause;
4890         ethpause.autoneg = fc_conf->autoneg;
4891         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4892             (fc_conf->mode & RTE_FC_RX_PAUSE))
4893                 ethpause.rx_pause = 1;
4894         else
4895                 ethpause.rx_pause = 0;
4896
4897         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4898             (fc_conf->mode & RTE_FC_TX_PAUSE))
4899                 ethpause.tx_pause = 1;
4900         else
4901                 ethpause.tx_pause = 0;
4902
4903         priv_lock(priv);
4904         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4905                 ret = errno;
4906                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
4907                      " failed: %s",
4908                      strerror(ret));
4909                 goto out;
4910         }
4911         ret = 0;
4912
4913 out:
4914         priv_unlock(priv);
4915         assert(ret >= 0);
4916         return -ret;
4917 }
4918
4919 /**
4920  * Configure a VLAN filter.
4921  *
4922  * @param dev
4923  *   Pointer to Ethernet device structure.
4924  * @param vlan_id
4925  *   VLAN ID to filter.
4926  * @param on
4927  *   Toggle filter.
4928  *
4929  * @return
4930  *   0 on success, errno value on failure.
4931  */
4932 static int
4933 vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4934 {
4935         struct priv *priv = dev->data->dev_private;
4936         unsigned int i;
4937         unsigned int j = -1;
4938
4939         DEBUG("%p: %s VLAN filter ID %" PRIu16,
4940               (void *)dev, (on ? "enable" : "disable"), vlan_id);
4941         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
4942                 if (!priv->vlan_filter[i].enabled) {
4943                         /* Unused index, remember it. */
4944                         j = i;
4945                         continue;
4946                 }
4947                 if (priv->vlan_filter[i].id != vlan_id)
4948                         continue;
4949                 /* This VLAN ID is already known, use its index. */
4950                 j = i;
4951                 break;
4952         }
4953         /* Check if there's room for another VLAN filter. */
4954         if (j == (unsigned int)-1)
4955                 return ENOMEM;
4956         /*
4957          * VLAN filters apply to all configured MAC addresses, flow
4958          * specifications must be reconfigured accordingly.
4959          */
4960         priv->vlan_filter[j].id = vlan_id;
4961         if ((on) && (!priv->vlan_filter[j].enabled)) {
4962                 /*
4963                  * Filter is disabled, enable it.
4964                  * Rehashing flows in all RX queues is necessary.
4965                  */
4966                 if (priv->rss)
4967                         rxq_mac_addrs_del(&priv->rxq_parent);
4968                 else
4969                         for (i = 0; (i != priv->rxqs_n); ++i)
4970                                 if ((*priv->rxqs)[i] != NULL)
4971                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4972                 priv->vlan_filter[j].enabled = 1;
4973                 if (priv->started) {
4974                         if (priv->rss)
4975                                 rxq_mac_addrs_add(&priv->rxq_parent);
4976                         else
4977                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4978                                         if ((*priv->rxqs)[i] == NULL)
4979                                                 continue;
4980                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4981                                 }
4982                 }
4983         } else if ((!on) && (priv->vlan_filter[j].enabled)) {
4984                 /*
4985                  * Filter is enabled, disable it.
4986                  * Rehashing flows in all RX queues is necessary.
4987                  */
4988                 if (priv->rss)
4989                         rxq_mac_addrs_del(&priv->rxq_parent);
4990                 else
4991                         for (i = 0; (i != priv->rxqs_n); ++i)
4992                                 if ((*priv->rxqs)[i] != NULL)
4993                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4994                 priv->vlan_filter[j].enabled = 0;
4995                 if (priv->started) {
4996                         if (priv->rss)
4997                                 rxq_mac_addrs_add(&priv->rxq_parent);
4998                         else
4999                                 for (i = 0; (i != priv->rxqs_n); ++i) {
5000                                         if ((*priv->rxqs)[i] == NULL)
5001                                                 continue;
5002                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
5003                                 }
5004                 }
5005         }
5006         return 0;
5007 }
5008
5009 /**
5010  * DPDK callback to configure a VLAN filter.
5011  *
5012  * @param dev
5013  *   Pointer to Ethernet device structure.
5014  * @param vlan_id
5015  *   VLAN ID to filter.
5016  * @param on
5017  *   Toggle filter.
5018  *
5019  * @return
5020  *   0 on success, negative errno value on failure.
5021  */
5022 static int
5023 mlx4_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
5024 {
5025         struct priv *priv = dev->data->dev_private;
5026         int ret;
5027
5028         if (mlx4_is_secondary())
5029                 return -E_RTE_SECONDARY;
5030         priv_lock(priv);
5031         ret = vlan_filter_set(dev, vlan_id, on);
5032         priv_unlock(priv);
5033         assert(ret >= 0);
5034         return -ret;
5035 }
5036
5037 const struct rte_flow_ops mlx4_flow_ops = {
5038         .validate = mlx4_flow_validate,
5039         .create = mlx4_flow_create,
5040         .destroy = mlx4_flow_destroy,
5041         .flush = mlx4_flow_flush,
5042         .query = NULL,
5043 };
5044
5045 /**
5046  * Manage filter operations.
5047  *
5048  * @param dev
5049  *   Pointer to Ethernet device structure.
5050  * @param filter_type
5051  *   Filter type.
5052  * @param filter_op
5053  *   Operation to perform.
5054  * @param arg
5055  *   Pointer to operation-specific structure.
5056  *
5057  * @return
5058  *   0 on success, negative errno value on failure.
5059  */
5060 static int
5061 mlx4_dev_filter_ctrl(struct rte_eth_dev *dev,
5062                      enum rte_filter_type filter_type,
5063                      enum rte_filter_op filter_op,
5064                      void *arg)
5065 {
5066         int ret = EINVAL;
5067
5068         switch (filter_type) {
5069         case RTE_ETH_FILTER_GENERIC:
5070                 if (filter_op != RTE_ETH_FILTER_GET)
5071                         return -EINVAL;
5072                 *(const void **)arg = &mlx4_flow_ops;
5073                 return 0;
5074         case RTE_ETH_FILTER_FDIR:
5075                 DEBUG("%p: filter type FDIR is not supported by this PMD",
5076                       (void *)dev);
5077                 break;
5078         default:
5079                 ERROR("%p: filter type (%d) not supported",
5080                       (void *)dev, filter_type);
5081                 break;
5082         }
5083         return -ret;
5084 }
5085
5086 static const struct eth_dev_ops mlx4_dev_ops = {
5087         .dev_configure = mlx4_dev_configure,
5088         .dev_start = mlx4_dev_start,
5089         .dev_stop = mlx4_dev_stop,
5090         .dev_set_link_down = mlx4_set_link_down,
5091         .dev_set_link_up = mlx4_set_link_up,
5092         .dev_close = mlx4_dev_close,
5093         .promiscuous_enable = mlx4_promiscuous_enable,
5094         .promiscuous_disable = mlx4_promiscuous_disable,
5095         .allmulticast_enable = mlx4_allmulticast_enable,
5096         .allmulticast_disable = mlx4_allmulticast_disable,
5097         .link_update = mlx4_link_update,
5098         .stats_get = mlx4_stats_get,
5099         .stats_reset = mlx4_stats_reset,
5100         .queue_stats_mapping_set = NULL,
5101         .dev_infos_get = mlx4_dev_infos_get,
5102         .dev_supported_ptypes_get = mlx4_dev_supported_ptypes_get,
5103         .vlan_filter_set = mlx4_vlan_filter_set,
5104         .vlan_tpid_set = NULL,
5105         .vlan_strip_queue_set = NULL,
5106         .vlan_offload_set = NULL,
5107         .rx_queue_setup = mlx4_rx_queue_setup,
5108         .tx_queue_setup = mlx4_tx_queue_setup,
5109         .rx_queue_release = mlx4_rx_queue_release,
5110         .tx_queue_release = mlx4_tx_queue_release,
5111         .dev_led_on = NULL,
5112         .dev_led_off = NULL,
5113         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
5114         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
5115         .priority_flow_ctrl_set = NULL,
5116         .mac_addr_remove = mlx4_mac_addr_remove,
5117         .mac_addr_add = mlx4_mac_addr_add,
5118         .mac_addr_set = mlx4_mac_addr_set,
5119         .mtu_set = mlx4_dev_set_mtu,
5120         .filter_ctrl = mlx4_dev_filter_ctrl,
5121 };
5122
5123 /**
5124  * Get PCI information from struct ibv_device.
5125  *
5126  * @param device
5127  *   Pointer to Ethernet device structure.
5128  * @param[out] pci_addr
5129  *   PCI bus address output buffer.
5130  *
5131  * @return
5132  *   0 on success, -1 on failure and errno is set.
5133  */
5134 static int
5135 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
5136                             struct rte_pci_addr *pci_addr)
5137 {
5138         FILE *file;
5139         char line[32];
5140         MKSTR(path, "%s/device/uevent", device->ibdev_path);
5141
5142         file = fopen(path, "rb");
5143         if (file == NULL)
5144                 return -1;
5145         while (fgets(line, sizeof(line), file) == line) {
5146                 size_t len = strlen(line);
5147                 int ret;
5148
5149                 /* Truncate long lines. */
5150                 if (len == (sizeof(line) - 1))
5151                         while (line[(len - 1)] != '\n') {
5152                                 ret = fgetc(file);
5153                                 if (ret == EOF)
5154                                         break;
5155                                 line[(len - 1)] = ret;
5156                         }
5157                 /* Extract information. */
5158                 if (sscanf(line,
5159                            "PCI_SLOT_NAME="
5160                            "%" SCNx16 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
5161                            &pci_addr->domain,
5162                            &pci_addr->bus,
5163                            &pci_addr->devid,
5164                            &pci_addr->function) == 4) {
5165                         ret = 0;
5166                         break;
5167                 }
5168         }
5169         fclose(file);
5170         return 0;
5171 }
5172
5173 /**
5174  * Get MAC address by querying netdevice.
5175  *
5176  * @param[in] priv
5177  *   struct priv for the requested device.
5178  * @param[out] mac
5179  *   MAC address output buffer.
5180  *
5181  * @return
5182  *   0 on success, -1 on failure and errno is set.
5183  */
5184 static int
5185 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
5186 {
5187         struct ifreq request;
5188
5189         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
5190                 return -1;
5191         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
5192         return 0;
5193 }
5194
5195 /* Support up to 32 adapters. */
5196 static struct {
5197         struct rte_pci_addr pci_addr; /* associated PCI address */
5198         uint32_t ports; /* physical ports bitfield. */
5199 } mlx4_dev[32];
5200
5201 /**
5202  * Get device index in mlx4_dev[] from PCI bus address.
5203  *
5204  * @param[in] pci_addr
5205  *   PCI bus address to look for.
5206  *
5207  * @return
5208  *   mlx4_dev[] index on success, -1 on failure.
5209  */
5210 static int
5211 mlx4_dev_idx(struct rte_pci_addr *pci_addr)
5212 {
5213         unsigned int i;
5214         int ret = -1;
5215
5216         assert(pci_addr != NULL);
5217         for (i = 0; (i != elemof(mlx4_dev)); ++i) {
5218                 if ((mlx4_dev[i].pci_addr.domain == pci_addr->domain) &&
5219                     (mlx4_dev[i].pci_addr.bus == pci_addr->bus) &&
5220                     (mlx4_dev[i].pci_addr.devid == pci_addr->devid) &&
5221                     (mlx4_dev[i].pci_addr.function == pci_addr->function))
5222                         return i;
5223                 if ((mlx4_dev[i].ports == 0) && (ret == -1))
5224                         ret = i;
5225         }
5226         return ret;
5227 }
5228
5229 /**
5230  * Retrieve integer value from environment variable.
5231  *
5232  * @param[in] name
5233  *   Environment variable name.
5234  *
5235  * @return
5236  *   Integer value, 0 if the variable is not set.
5237  */
5238 static int
5239 mlx4_getenv_int(const char *name)
5240 {
5241         const char *val = getenv(name);
5242
5243         if (val == NULL)
5244                 return 0;
5245         return atoi(val);
5246 }
5247
5248 static void
5249 mlx4_dev_link_status_handler(void *);
5250 static void
5251 mlx4_dev_interrupt_handler(struct rte_intr_handle *, void *);
5252
5253 /**
5254  * Link status handler.
5255  *
5256  * @param priv
5257  *   Pointer to private structure.
5258  * @param dev
5259  *   Pointer to the rte_eth_dev structure.
5260  *
5261  * @return
5262  *   Nonzero if the callback process can be called immediately.
5263  */
5264 static int
5265 priv_dev_link_status_handler(struct priv *priv, struct rte_eth_dev *dev)
5266 {
5267         struct ibv_async_event event;
5268         int port_change = 0;
5269         int ret = 0;
5270
5271         /* Read all message and acknowledge them. */
5272         for (;;) {
5273                 if (ibv_get_async_event(priv->ctx, &event))
5274                         break;
5275
5276                 if (event.event_type == IBV_EVENT_PORT_ACTIVE ||
5277                     event.event_type == IBV_EVENT_PORT_ERR)
5278                         port_change = 1;
5279                 else
5280                         DEBUG("event type %d on port %d not handled",
5281                               event.event_type, event.element.port_num);
5282                 ibv_ack_async_event(&event);
5283         }
5284
5285         if (port_change ^ priv->pending_alarm) {
5286                 struct rte_eth_link *link = &dev->data->dev_link;
5287
5288                 priv->pending_alarm = 0;
5289                 mlx4_link_update(dev, 0);
5290                 if (((link->link_speed == 0) && link->link_status) ||
5291                     ((link->link_speed != 0) && !link->link_status)) {
5292                         /* Inconsistent status, check again later. */
5293                         priv->pending_alarm = 1;
5294                         rte_eal_alarm_set(MLX4_ALARM_TIMEOUT_US,
5295                                           mlx4_dev_link_status_handler,
5296                                           dev);
5297                 } else
5298                         ret = 1;
5299         }
5300         return ret;
5301 }
5302
5303 /**
5304  * Handle delayed link status event.
5305  *
5306  * @param arg
5307  *   Registered argument.
5308  */
5309 static void
5310 mlx4_dev_link_status_handler(void *arg)
5311 {
5312         struct rte_eth_dev *dev = arg;
5313         struct priv *priv = dev->data->dev_private;
5314         int ret;
5315
5316         priv_lock(priv);
5317         assert(priv->pending_alarm == 1);
5318         ret = priv_dev_link_status_handler(priv, dev);
5319         priv_unlock(priv);
5320         if (ret)
5321                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC, NULL);
5322 }
5323
5324 /**
5325  * Handle interrupts from the NIC.
5326  *
5327  * @param[in] intr_handle
5328  *   Interrupt handler.
5329  * @param cb_arg
5330  *   Callback argument.
5331  */
5332 static void
5333 mlx4_dev_interrupt_handler(struct rte_intr_handle *intr_handle, void *cb_arg)
5334 {
5335         struct rte_eth_dev *dev = cb_arg;
5336         struct priv *priv = dev->data->dev_private;
5337         int ret;
5338
5339         (void)intr_handle;
5340         priv_lock(priv);
5341         ret = priv_dev_link_status_handler(priv, dev);
5342         priv_unlock(priv);
5343         if (ret)
5344                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC, NULL);
5345 }
5346
5347 /**
5348  * Uninstall interrupt handler.
5349  *
5350  * @param priv
5351  *   Pointer to private structure.
5352  * @param dev
5353  *   Pointer to the rte_eth_dev structure.
5354  */
5355 static void
5356 priv_dev_interrupt_handler_uninstall(struct priv *priv, struct rte_eth_dev *dev)
5357 {
5358         if (!dev->data->dev_conf.intr_conf.lsc)
5359                 return;
5360         rte_intr_callback_unregister(&priv->intr_handle,
5361                                      mlx4_dev_interrupt_handler,
5362                                      dev);
5363         if (priv->pending_alarm)
5364                 rte_eal_alarm_cancel(mlx4_dev_link_status_handler, dev);
5365         priv->pending_alarm = 0;
5366         priv->intr_handle.fd = 0;
5367         priv->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
5368 }
5369
5370 /**
5371  * Install interrupt handler.
5372  *
5373  * @param priv
5374  *   Pointer to private structure.
5375  * @param dev
5376  *   Pointer to the rte_eth_dev structure.
5377  */
5378 static void
5379 priv_dev_interrupt_handler_install(struct priv *priv, struct rte_eth_dev *dev)
5380 {
5381         int rc, flags;
5382
5383         if (!dev->data->dev_conf.intr_conf.lsc)
5384                 return;
5385         assert(priv->ctx->async_fd > 0);
5386         flags = fcntl(priv->ctx->async_fd, F_GETFL);
5387         rc = fcntl(priv->ctx->async_fd, F_SETFL, flags | O_NONBLOCK);
5388         if (rc < 0) {
5389                 INFO("failed to change file descriptor async event queue");
5390                 dev->data->dev_conf.intr_conf.lsc = 0;
5391         } else {
5392                 priv->intr_handle.fd = priv->ctx->async_fd;
5393                 priv->intr_handle.type = RTE_INTR_HANDLE_EXT;
5394                 rte_intr_callback_register(&priv->intr_handle,
5395                                            mlx4_dev_interrupt_handler,
5396                                            dev);
5397         }
5398 }
5399
5400 /**
5401  * Verify and store value for device argument.
5402  *
5403  * @param[in] key
5404  *   Key argument to verify.
5405  * @param[in] val
5406  *   Value associated with key.
5407  * @param out
5408  *   User data.
5409  *
5410  * @return
5411  *   0 on success, negative errno value on failure.
5412  */
5413 static int
5414 mlx4_arg_parse(const char *key, const char *val, void *out)
5415 {
5416         struct mlx4_conf *conf = out;
5417         unsigned long tmp;
5418
5419         errno = 0;
5420         tmp = strtoul(val, NULL, 0);
5421         if (errno) {
5422                 WARN("%s: \"%s\" is not a valid integer", key, val);
5423                 return -errno;
5424         }
5425         if (strcmp(MLX4_PMD_PORT_KVARG, key) == 0) {
5426                 if (tmp >= MLX4_PMD_MAX_PHYS_PORTS) {
5427                         ERROR("invalid port index %lu (max: %u)",
5428                                 tmp, MLX4_PMD_MAX_PHYS_PORTS - 1);
5429                         return -EINVAL;
5430                 }
5431                 conf->active_ports |= 1 << tmp;
5432         } else {
5433                 WARN("%s: unknown parameter", key);
5434                 return -EINVAL;
5435         }
5436         return 0;
5437 }
5438
5439 /**
5440  * Parse device parameters.
5441  *
5442  * @param devargs
5443  *   Device arguments structure.
5444  *
5445  * @return
5446  *   0 on success, negative errno value on failure.
5447  */
5448 static int
5449 mlx4_args(struct rte_devargs *devargs, struct mlx4_conf *conf)
5450 {
5451         struct rte_kvargs *kvlist;
5452         unsigned int arg_count;
5453         int ret = 0;
5454         int i;
5455
5456         if (devargs == NULL)
5457                 return 0;
5458         kvlist = rte_kvargs_parse(devargs->args, pmd_mlx4_init_params);
5459         if (kvlist == NULL) {
5460                 ERROR("failed to parse kvargs");
5461                 return -EINVAL;
5462         }
5463         /* Process parameters. */
5464         for (i = 0; pmd_mlx4_init_params[i]; ++i) {
5465                 arg_count = rte_kvargs_count(kvlist, MLX4_PMD_PORT_KVARG);
5466                 while (arg_count-- > 0) {
5467                         ret = rte_kvargs_process(kvlist, MLX4_PMD_PORT_KVARG,
5468                                         mlx4_arg_parse, conf);
5469                         if (ret != 0)
5470                                 goto free_kvlist;
5471                 }
5472         }
5473 free_kvlist:
5474         rte_kvargs_free(kvlist);
5475         return ret;
5476 }
5477
5478 static struct eth_driver mlx4_driver;
5479
5480 /**
5481  * DPDK callback to register a PCI device.
5482  *
5483  * This function creates an Ethernet device for each port of a given
5484  * PCI device.
5485  *
5486  * @param[in] pci_drv
5487  *   PCI driver structure (mlx4_driver).
5488  * @param[in] pci_dev
5489  *   PCI device information.
5490  *
5491  * @return
5492  *   0 on success, negative errno value on failure.
5493  */
5494 static int
5495 mlx4_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
5496 {
5497         struct ibv_device **list;
5498         struct ibv_device *ibv_dev;
5499         int err = 0;
5500         struct ibv_context *attr_ctx = NULL;
5501         struct ibv_device_attr device_attr;
5502         struct mlx4_conf conf = {
5503                 .active_ports = 0,
5504         };
5505         unsigned int vf;
5506         int idx;
5507         int i;
5508
5509         (void)pci_drv;
5510         assert(pci_drv == &mlx4_driver.pci_drv);
5511         /* Get mlx4_dev[] index. */
5512         idx = mlx4_dev_idx(&pci_dev->addr);
5513         if (idx == -1) {
5514                 ERROR("this driver cannot support any more adapters");
5515                 return -ENOMEM;
5516         }
5517         DEBUG("using driver device index %d", idx);
5518
5519         /* Save PCI address. */
5520         mlx4_dev[idx].pci_addr = pci_dev->addr;
5521         list = ibv_get_device_list(&i);
5522         if (list == NULL) {
5523                 assert(errno);
5524                 if (errno == ENOSYS) {
5525                         WARN("cannot list devices, is ib_uverbs loaded?");
5526                         return 0;
5527                 }
5528                 return -errno;
5529         }
5530         assert(i >= 0);
5531         /*
5532          * For each listed device, check related sysfs entry against
5533          * the provided PCI ID.
5534          */
5535         while (i != 0) {
5536                 struct rte_pci_addr pci_addr;
5537
5538                 --i;
5539                 DEBUG("checking device \"%s\"", list[i]->name);
5540                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
5541                         continue;
5542                 if ((pci_dev->addr.domain != pci_addr.domain) ||
5543                     (pci_dev->addr.bus != pci_addr.bus) ||
5544                     (pci_dev->addr.devid != pci_addr.devid) ||
5545                     (pci_dev->addr.function != pci_addr.function))
5546                         continue;
5547                 vf = (pci_dev->id.device_id ==
5548                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
5549                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
5550                      list[i]->name, (vf ? "true" : "false"));
5551                 attr_ctx = ibv_open_device(list[i]);
5552                 err = errno;
5553                 break;
5554         }
5555         if (attr_ctx == NULL) {
5556                 ibv_free_device_list(list);
5557                 switch (err) {
5558                 case 0:
5559                         WARN("cannot access device, is mlx4_ib loaded?");
5560                         return 0;
5561                 case EINVAL:
5562                         WARN("cannot use device, are drivers up to date?");
5563                         return 0;
5564                 }
5565                 assert(err > 0);
5566                 return -err;
5567         }
5568         ibv_dev = list[i];
5569
5570         DEBUG("device opened");
5571         if (ibv_query_device(attr_ctx, &device_attr))
5572                 goto error;
5573         INFO("%u port(s) detected", device_attr.phys_port_cnt);
5574
5575         if (mlx4_args(pci_dev->device.devargs, &conf)) {
5576                 ERROR("failed to process device arguments");
5577                 goto error;
5578         }
5579         /* Use all ports when none are defined */
5580         if (conf.active_ports == 0) {
5581                 for (i = 0; i < MLX4_PMD_MAX_PHYS_PORTS; i++)
5582                         conf.active_ports |= 1 << i;
5583         }
5584         for (i = 0; i < device_attr.phys_port_cnt; i++) {
5585                 uint32_t port = i + 1; /* ports are indexed from one */
5586                 uint32_t test = (1 << i);
5587                 struct ibv_context *ctx = NULL;
5588                 struct ibv_port_attr port_attr;
5589                 struct ibv_pd *pd = NULL;
5590                 struct priv *priv = NULL;
5591                 struct rte_eth_dev *eth_dev = NULL;
5592 #ifdef HAVE_EXP_QUERY_DEVICE
5593                 struct ibv_exp_device_attr exp_device_attr;
5594 #endif /* HAVE_EXP_QUERY_DEVICE */
5595                 struct ether_addr mac;
5596
5597                 /* If port is not active, skip. */
5598                 if (!(conf.active_ports & (1 << i)))
5599                         continue;
5600 #ifdef HAVE_EXP_QUERY_DEVICE
5601                 exp_device_attr.comp_mask = IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS;
5602 #ifdef RSS_SUPPORT
5603                 exp_device_attr.comp_mask |= IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ;
5604 #endif /* RSS_SUPPORT */
5605 #endif /* HAVE_EXP_QUERY_DEVICE */
5606
5607                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
5608
5609                 ctx = ibv_open_device(ibv_dev);
5610                 if (ctx == NULL)
5611                         goto port_error;
5612
5613                 /* Check port status. */
5614                 err = ibv_query_port(ctx, port, &port_attr);
5615                 if (err) {
5616                         ERROR("port query failed: %s", strerror(err));
5617                         goto port_error;
5618                 }
5619
5620                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
5621                         ERROR("port %d is not configured in Ethernet mode",
5622                               port);
5623                         goto port_error;
5624                 }
5625
5626                 if (port_attr.state != IBV_PORT_ACTIVE)
5627                         DEBUG("port %d is not active: \"%s\" (%d)",
5628                               port, ibv_port_state_str(port_attr.state),
5629                               port_attr.state);
5630
5631                 /* Allocate protection domain. */
5632                 pd = ibv_alloc_pd(ctx);
5633                 if (pd == NULL) {
5634                         ERROR("PD allocation failure");
5635                         err = ENOMEM;
5636                         goto port_error;
5637                 }
5638
5639                 mlx4_dev[idx].ports |= test;
5640
5641                 /* from rte_ethdev.c */
5642                 priv = rte_zmalloc("ethdev private structure",
5643                                    sizeof(*priv),
5644                                    RTE_CACHE_LINE_SIZE);
5645                 if (priv == NULL) {
5646                         ERROR("priv allocation failure");
5647                         err = ENOMEM;
5648                         goto port_error;
5649                 }
5650
5651                 priv->ctx = ctx;
5652                 priv->device_attr = device_attr;
5653                 priv->port = port;
5654                 priv->pd = pd;
5655                 priv->mtu = ETHER_MTU;
5656 #ifdef HAVE_EXP_QUERY_DEVICE
5657                 if (ibv_exp_query_device(ctx, &exp_device_attr)) {
5658                         ERROR("ibv_exp_query_device() failed");
5659                         goto port_error;
5660                 }
5661 #ifdef RSS_SUPPORT
5662                 if ((exp_device_attr.exp_device_cap_flags &
5663                      IBV_EXP_DEVICE_QPG) &&
5664                     (exp_device_attr.exp_device_cap_flags &
5665                      IBV_EXP_DEVICE_UD_RSS) &&
5666                     (exp_device_attr.comp_mask &
5667                      IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ) &&
5668                     (exp_device_attr.max_rss_tbl_sz > 0)) {
5669                         priv->hw_qpg = 1;
5670                         priv->hw_rss = 1;
5671                         priv->max_rss_tbl_sz = exp_device_attr.max_rss_tbl_sz;
5672                 } else {
5673                         priv->hw_qpg = 0;
5674                         priv->hw_rss = 0;
5675                         priv->max_rss_tbl_sz = 0;
5676                 }
5677                 priv->hw_tss = !!(exp_device_attr.exp_device_cap_flags &
5678                                   IBV_EXP_DEVICE_UD_TSS);
5679                 DEBUG("device flags: %s%s%s",
5680                       (priv->hw_qpg ? "IBV_DEVICE_QPG " : ""),
5681                       (priv->hw_tss ? "IBV_DEVICE_TSS " : ""),
5682                       (priv->hw_rss ? "IBV_DEVICE_RSS " : ""));
5683                 if (priv->hw_rss)
5684                         DEBUG("maximum RSS indirection table size: %u",
5685                               exp_device_attr.max_rss_tbl_sz);
5686 #endif /* RSS_SUPPORT */
5687
5688                 priv->hw_csum =
5689                         ((exp_device_attr.exp_device_cap_flags &
5690                           IBV_EXP_DEVICE_RX_CSUM_TCP_UDP_PKT) &&
5691                          (exp_device_attr.exp_device_cap_flags &
5692                           IBV_EXP_DEVICE_RX_CSUM_IP_PKT));
5693                 DEBUG("checksum offloading is %ssupported",
5694                       (priv->hw_csum ? "" : "not "));
5695
5696                 priv->hw_csum_l2tun = !!(exp_device_attr.exp_device_cap_flags &
5697                                          IBV_EXP_DEVICE_VXLAN_SUPPORT);
5698                 DEBUG("L2 tunnel checksum offloads are %ssupported",
5699                       (priv->hw_csum_l2tun ? "" : "not "));
5700
5701 #ifdef INLINE_RECV
5702                 priv->inl_recv_size = mlx4_getenv_int("MLX4_INLINE_RECV_SIZE");
5703
5704                 if (priv->inl_recv_size) {
5705                         exp_device_attr.comp_mask =
5706                                 IBV_EXP_DEVICE_ATTR_INLINE_RECV_SZ;
5707                         if (ibv_exp_query_device(ctx, &exp_device_attr)) {
5708                                 INFO("Couldn't query device for inline-receive"
5709                                      " capabilities.");
5710                                 priv->inl_recv_size = 0;
5711                         } else {
5712                                 if ((unsigned)exp_device_attr.inline_recv_sz <
5713                                     priv->inl_recv_size) {
5714                                         INFO("Max inline-receive (%d) <"
5715                                              " requested inline-receive (%u)",
5716                                              exp_device_attr.inline_recv_sz,
5717                                              priv->inl_recv_size);
5718                                         priv->inl_recv_size =
5719                                                 exp_device_attr.inline_recv_sz;
5720                                 }
5721                         }
5722                         INFO("Set inline receive size to %u",
5723                              priv->inl_recv_size);
5724                 }
5725 #endif /* INLINE_RECV */
5726 #endif /* HAVE_EXP_QUERY_DEVICE */
5727
5728                 (void)mlx4_getenv_int;
5729                 priv->vf = vf;
5730                 /* Configure the first MAC address by default. */
5731                 if (priv_get_mac(priv, &mac.addr_bytes)) {
5732                         ERROR("cannot get MAC address, is mlx4_en loaded?"
5733                               " (errno: %s)", strerror(errno));
5734                         goto port_error;
5735                 }
5736                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
5737                      priv->port,
5738                      mac.addr_bytes[0], mac.addr_bytes[1],
5739                      mac.addr_bytes[2], mac.addr_bytes[3],
5740                      mac.addr_bytes[4], mac.addr_bytes[5]);
5741                 /* Register MAC and broadcast addresses. */
5742                 claim_zero(priv_mac_addr_add(priv, 0,
5743                                              (const uint8_t (*)[ETHER_ADDR_LEN])
5744                                              mac.addr_bytes));
5745                 claim_zero(priv_mac_addr_add(priv, (elemof(priv->mac) - 1),
5746                                              &(const uint8_t [ETHER_ADDR_LEN])
5747                                              { "\xff\xff\xff\xff\xff\xff" }));
5748 #ifndef NDEBUG
5749                 {
5750                         char ifname[IF_NAMESIZE];
5751
5752                         if (priv_get_ifname(priv, &ifname) == 0)
5753                                 DEBUG("port %u ifname is \"%s\"",
5754                                       priv->port, ifname);
5755                         else
5756                                 DEBUG("port %u ifname is unknown", priv->port);
5757                 }
5758 #endif
5759                 /* Get actual MTU if possible. */
5760                 priv_get_mtu(priv, &priv->mtu);
5761                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
5762
5763                 /* from rte_ethdev.c */
5764                 {
5765                         char name[RTE_ETH_NAME_MAX_LEN];
5766
5767                         snprintf(name, sizeof(name), "%s port %u",
5768                                  ibv_get_device_name(ibv_dev), port);
5769                         eth_dev = rte_eth_dev_allocate(name);
5770                 }
5771                 if (eth_dev == NULL) {
5772                         ERROR("can not allocate rte ethdev");
5773                         err = ENOMEM;
5774                         goto port_error;
5775                 }
5776
5777                 /* Secondary processes have to use local storage for their
5778                  * private data as well as a copy of eth_dev->data, but this
5779                  * pointer must not be modified before burst functions are
5780                  * actually called. */
5781                 if (mlx4_is_secondary()) {
5782                         struct mlx4_secondary_data *sd =
5783                                 &mlx4_secondary_data[eth_dev->data->port_id];
5784
5785                         sd->primary_priv = eth_dev->data->dev_private;
5786                         if (sd->primary_priv == NULL) {
5787                                 ERROR("no private data for port %u",
5788                                       eth_dev->data->port_id);
5789                                 err = EINVAL;
5790                                 goto port_error;
5791                         }
5792                         sd->shared_dev_data = eth_dev->data;
5793                         rte_spinlock_init(&sd->lock);
5794                         memcpy(sd->data.name, sd->shared_dev_data->name,
5795                                sizeof(sd->data.name));
5796                         sd->data.dev_private = priv;
5797                         sd->data.rx_mbuf_alloc_failed = 0;
5798                         sd->data.mtu = ETHER_MTU;
5799                         sd->data.port_id = sd->shared_dev_data->port_id;
5800                         sd->data.mac_addrs = priv->mac;
5801                         eth_dev->tx_pkt_burst = mlx4_tx_burst_secondary_setup;
5802                         eth_dev->rx_pkt_burst = mlx4_rx_burst_secondary_setup;
5803                 } else {
5804                         eth_dev->data->dev_private = priv;
5805                         eth_dev->data->mac_addrs = priv->mac;
5806                 }
5807                 eth_dev->device = &pci_dev->device;
5808
5809                 rte_eth_copy_pci_info(eth_dev, pci_dev);
5810
5811                 eth_dev->driver = &mlx4_driver;
5812
5813                 priv->dev = eth_dev;
5814                 eth_dev->dev_ops = &mlx4_dev_ops;
5815
5816                 /* Bring Ethernet device up. */
5817                 DEBUG("forcing Ethernet interface up");
5818                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
5819                 /* Update link status once if waiting for LSC. */
5820                 if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
5821                         mlx4_link_update(eth_dev, 0);
5822                 continue;
5823
5824 port_error:
5825                 rte_free(priv);
5826                 if (pd)
5827                         claim_zero(ibv_dealloc_pd(pd));
5828                 if (ctx)
5829                         claim_zero(ibv_close_device(ctx));
5830                 if (eth_dev)
5831                         rte_eth_dev_release_port(eth_dev);
5832                 break;
5833         }
5834
5835         /*
5836          * XXX if something went wrong in the loop above, there is a resource
5837          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
5838          * long as the dpdk does not provide a way to deallocate a ethdev and a
5839          * way to enumerate the registered ethdevs to free the previous ones.
5840          */
5841
5842         /* no port found, complain */
5843         if (!mlx4_dev[idx].ports) {
5844                 err = ENODEV;
5845                 goto error;
5846         }
5847
5848 error:
5849         if (attr_ctx)
5850                 claim_zero(ibv_close_device(attr_ctx));
5851         if (list)
5852                 ibv_free_device_list(list);
5853         assert(err >= 0);
5854         return -err;
5855 }
5856
5857 static const struct rte_pci_id mlx4_pci_id_map[] = {
5858         {
5859                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
5860                                PCI_DEVICE_ID_MELLANOX_CONNECTX3)
5861         },
5862         {
5863                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
5864                                PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO)
5865         },
5866         {
5867                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
5868                                PCI_DEVICE_ID_MELLANOX_CONNECTX3VF)
5869         },
5870         {
5871                 .vendor_id = 0
5872         }
5873 };
5874
5875 static struct eth_driver mlx4_driver = {
5876         .pci_drv = {
5877                 .driver = {
5878                         .name = MLX4_DRIVER_NAME
5879                 },
5880                 .id_table = mlx4_pci_id_map,
5881                 .probe = mlx4_pci_probe,
5882                 .drv_flags = RTE_PCI_DRV_INTR_LSC,
5883         },
5884         .dev_private_size = sizeof(struct priv)
5885 };
5886
5887 /**
5888  * Driver initialization routine.
5889  */
5890 RTE_INIT(rte_mlx4_pmd_init);
5891 static void
5892 rte_mlx4_pmd_init(void)
5893 {
5894         RTE_BUILD_BUG_ON(sizeof(wr_id_t) != sizeof(uint64_t));
5895         /*
5896          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
5897          * huge pages. Calling ibv_fork_init() during init allows
5898          * applications to use fork() safely for purposes other than
5899          * using this PMD, which is not supported in forked processes.
5900          */
5901         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
5902         ibv_fork_init();
5903         rte_eal_pci_register(&mlx4_driver.pci_drv);
5904 }
5905
5906 RTE_PMD_EXPORT_NAME(net_mlx4, __COUNTER__);
5907 RTE_PMD_REGISTER_PCI_TABLE(net_mlx4, mlx4_pci_id_map);
5908 RTE_PMD_REGISTER_KMOD_DEP(net_mlx4,
5909         "* ib_uverbs & mlx4_en & mlx4_core & mlx4_ib");