eal: clean up interrupt handle
[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.enable_scatter &&
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.max_rx_pkt_len <=
3659             (mb_len - RTE_PKTMBUF_HEADROOM)) {
3660                 tmpl.sp = 0;
3661         } else if (dev->data->dev_conf.rxmode.enable_scatter) {
3662                 tmpl.sp = 1;
3663                 desc /= MLX4_PMD_SGE_WR_N;
3664         } else {
3665                 WARN("%p: the requested maximum Rx packet size (%u) is"
3666                      " larger than a single mbuf (%u) and scattered"
3667                      " mode has not been requested",
3668                      (void *)dev,
3669                      dev->data->dev_conf.rxmode.max_rx_pkt_len,
3670                      mb_len - RTE_PKTMBUF_HEADROOM);
3671         }
3672         DEBUG("%p: %s scattered packets support (%u WRs)",
3673               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
3674         /* Use the entire RX mempool as the memory region. */
3675         tmpl.mr = mlx4_mp2mr(priv->pd, mp);
3676         if (tmpl.mr == NULL) {
3677                 ret = EINVAL;
3678                 ERROR("%p: MR creation failure: %s",
3679                       (void *)dev, strerror(ret));
3680                 goto error;
3681         }
3682 skip_mr:
3683         attr.rd = (struct ibv_exp_res_domain_init_attr){
3684                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
3685                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
3686                 .thread_model = IBV_EXP_THREAD_SINGLE,
3687                 .msg_model = IBV_EXP_MSG_HIGH_BW,
3688         };
3689         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
3690         if (tmpl.rd == NULL) {
3691                 ret = ENOMEM;
3692                 ERROR("%p: RD creation failure: %s",
3693                       (void *)dev, strerror(ret));
3694                 goto error;
3695         }
3696         attr.cq = (struct ibv_exp_cq_init_attr){
3697                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
3698                 .res_domain = tmpl.rd,
3699         };
3700         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
3701         if (tmpl.cq == NULL) {
3702                 ret = ENOMEM;
3703                 ERROR("%p: CQ creation failure: %s",
3704                       (void *)dev, strerror(ret));
3705                 goto error;
3706         }
3707         DEBUG("priv->device_attr.max_qp_wr is %d",
3708               priv->device_attr.max_qp_wr);
3709         DEBUG("priv->device_attr.max_sge is %d",
3710               priv->device_attr.max_sge);
3711 #ifdef RSS_SUPPORT
3712         if (priv->rss && !inactive)
3713                 tmpl.qp = rxq_setup_qp_rss(priv, tmpl.cq, desc, parent,
3714                                            tmpl.rd);
3715         else
3716 #endif /* RSS_SUPPORT */
3717                 tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc, tmpl.rd);
3718         if (tmpl.qp == NULL) {
3719                 ret = (errno ? errno : EINVAL);
3720                 ERROR("%p: QP creation failure: %s",
3721                       (void *)dev, strerror(ret));
3722                 goto error;
3723         }
3724         mod = (struct ibv_exp_qp_attr){
3725                 /* Move the QP to this state. */
3726                 .qp_state = IBV_QPS_INIT,
3727                 /* Primary port number. */
3728                 .port_num = priv->port
3729         };
3730         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
3731                                 (IBV_EXP_QP_STATE |
3732 #ifdef RSS_SUPPORT
3733                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3734 #endif /* RSS_SUPPORT */
3735                                  IBV_EXP_QP_PORT));
3736         if (ret) {
3737                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3738                       (void *)dev, strerror(ret));
3739                 goto error;
3740         }
3741         if ((parent) || (!priv->rss))  {
3742                 /* Configure MAC and broadcast addresses. */
3743                 ret = rxq_mac_addrs_add(&tmpl);
3744                 if (ret) {
3745                         ERROR("%p: QP flow attachment failed: %s",
3746                               (void *)dev, strerror(ret));
3747                         goto error;
3748                 }
3749         }
3750         /* Allocate descriptors for RX queues, except for the RSS parent. */
3751         if (parent)
3752                 goto skip_alloc;
3753         if (tmpl.sp)
3754                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
3755         else
3756                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
3757         if (ret) {
3758                 ERROR("%p: RXQ allocation failed: %s",
3759                       (void *)dev, strerror(ret));
3760                 goto error;
3761         }
3762         ret = ibv_post_recv(tmpl.qp,
3763                             (tmpl.sp ?
3764                              &(*tmpl.elts.sp)[0].wr :
3765                              &(*tmpl.elts.no_sp)[0].wr),
3766                             &bad_wr);
3767         if (ret) {
3768                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3769                       (void *)dev,
3770                       (void *)bad_wr,
3771                       strerror(ret));
3772                 goto error;
3773         }
3774 skip_alloc:
3775         mod = (struct ibv_exp_qp_attr){
3776                 .qp_state = IBV_QPS_RTR
3777         };
3778         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3779         if (ret) {
3780                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3781                       (void *)dev, strerror(ret));
3782                 goto error;
3783         }
3784         /* Save port ID. */
3785         tmpl.port_id = dev->data->port_id;
3786         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
3787         attr.params = (struct ibv_exp_query_intf_params){
3788                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3789                 .intf = IBV_EXP_INTF_CQ,
3790                 .obj = tmpl.cq,
3791         };
3792         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3793         if (tmpl.if_cq == NULL) {
3794                 ERROR("%p: CQ interface family query failed with status %d",
3795                       (void *)dev, status);
3796                 goto error;
3797         }
3798         attr.params = (struct ibv_exp_query_intf_params){
3799                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3800                 .intf = IBV_EXP_INTF_QP_BURST,
3801                 .obj = tmpl.qp,
3802         };
3803         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3804         if (tmpl.if_qp == NULL) {
3805                 ERROR("%p: QP interface family query failed with status %d",
3806                       (void *)dev, status);
3807                 goto error;
3808         }
3809         /* Clean up rxq in case we're reinitializing it. */
3810         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
3811         rxq_cleanup(rxq);
3812         *rxq = tmpl;
3813         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
3814         assert(ret == 0);
3815         return 0;
3816 error:
3817         rxq_cleanup(&tmpl);
3818         assert(ret > 0);
3819         return ret;
3820 }
3821
3822 /**
3823  * DPDK callback to configure a RX queue.
3824  *
3825  * @param dev
3826  *   Pointer to Ethernet device structure.
3827  * @param idx
3828  *   RX queue index.
3829  * @param desc
3830  *   Number of descriptors to configure in queue.
3831  * @param socket
3832  *   NUMA socket on which memory must be allocated.
3833  * @param[in] conf
3834  *   Thresholds parameters.
3835  * @param mp
3836  *   Memory pool for buffer allocations.
3837  *
3838  * @return
3839  *   0 on success, negative errno value on failure.
3840  */
3841 static int
3842 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
3843                     unsigned int socket, const struct rte_eth_rxconf *conf,
3844                     struct rte_mempool *mp)
3845 {
3846         struct priv *priv = dev->data->dev_private;
3847         struct rxq *rxq = (*priv->rxqs)[idx];
3848         int inactive = 0;
3849         int ret;
3850
3851         if (mlx4_is_secondary())
3852                 return -E_RTE_SECONDARY;
3853         priv_lock(priv);
3854         DEBUG("%p: configuring queue %u for %u descriptors",
3855               (void *)dev, idx, desc);
3856         if (idx >= priv->rxqs_n) {
3857                 ERROR("%p: queue index out of range (%u >= %u)",
3858                       (void *)dev, idx, priv->rxqs_n);
3859                 priv_unlock(priv);
3860                 return -EOVERFLOW;
3861         }
3862         if (rxq != NULL) {
3863                 DEBUG("%p: reusing already allocated queue index %u (%p)",
3864                       (void *)dev, idx, (void *)rxq);
3865                 if (priv->started) {
3866                         priv_unlock(priv);
3867                         return -EEXIST;
3868                 }
3869                 (*priv->rxqs)[idx] = NULL;
3870                 rxq_cleanup(rxq);
3871         } else {
3872                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
3873                 if (rxq == NULL) {
3874                         ERROR("%p: unable to allocate queue index %u",
3875                               (void *)dev, idx);
3876                         priv_unlock(priv);
3877                         return -ENOMEM;
3878                 }
3879         }
3880         if (idx >= rte_align32pow2(priv->rxqs_n + 1) >> 1)
3881                 inactive = 1;
3882         ret = rxq_setup(dev, rxq, desc, socket, inactive, conf, mp);
3883         if (ret)
3884                 rte_free(rxq);
3885         else {
3886                 rxq->stats.idx = idx;
3887                 DEBUG("%p: adding RX queue %p to list",
3888                       (void *)dev, (void *)rxq);
3889                 (*priv->rxqs)[idx] = rxq;
3890                 /* Update receive callback. */
3891                 if (rxq->sp)
3892                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3893                 else
3894                         dev->rx_pkt_burst = mlx4_rx_burst;
3895         }
3896         priv_unlock(priv);
3897         return -ret;
3898 }
3899
3900 /**
3901  * DPDK callback to release a RX queue.
3902  *
3903  * @param dpdk_rxq
3904  *   Generic RX queue pointer.
3905  */
3906 static void
3907 mlx4_rx_queue_release(void *dpdk_rxq)
3908 {
3909         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3910         struct priv *priv;
3911         unsigned int i;
3912
3913         if (mlx4_is_secondary())
3914                 return;
3915         if (rxq == NULL)
3916                 return;
3917         priv = rxq->priv;
3918         priv_lock(priv);
3919         assert(rxq != &priv->rxq_parent);
3920         for (i = 0; (i != priv->rxqs_n); ++i)
3921                 if ((*priv->rxqs)[i] == rxq) {
3922                         DEBUG("%p: removing RX queue %p from list",
3923                               (void *)priv->dev, (void *)rxq);
3924                         (*priv->rxqs)[i] = NULL;
3925                         break;
3926                 }
3927         rxq_cleanup(rxq);
3928         rte_free(rxq);
3929         priv_unlock(priv);
3930 }
3931
3932 static void
3933 priv_dev_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
3934
3935 /**
3936  * DPDK callback to start the device.
3937  *
3938  * Simulate device start by attaching all configured flows.
3939  *
3940  * @param dev
3941  *   Pointer to Ethernet device structure.
3942  *
3943  * @return
3944  *   0 on success, negative errno value on failure.
3945  */
3946 static int
3947 mlx4_dev_start(struct rte_eth_dev *dev)
3948 {
3949         struct priv *priv = dev->data->dev_private;
3950         unsigned int i = 0;
3951         unsigned int r;
3952         struct rxq *rxq;
3953         int ret;
3954
3955         if (mlx4_is_secondary())
3956                 return -E_RTE_SECONDARY;
3957         priv_lock(priv);
3958         if (priv->started) {
3959                 priv_unlock(priv);
3960                 return 0;
3961         }
3962         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
3963         priv->started = 1;
3964         if (priv->rss) {
3965                 rxq = &priv->rxq_parent;
3966                 r = 1;
3967         } else {
3968                 rxq = (*priv->rxqs)[0];
3969                 r = priv->rxqs_n;
3970         }
3971         /* Iterate only once when RSS is enabled. */
3972         do {
3973                 /* Ignore nonexistent RX queues. */
3974                 if (rxq == NULL)
3975                         continue;
3976                 ret = rxq_mac_addrs_add(rxq);
3977                 if (!ret && priv->promisc)
3978                         ret = rxq_promiscuous_enable(rxq);
3979                 if (!ret && priv->allmulti)
3980                         ret = rxq_allmulticast_enable(rxq);
3981                 if (!ret)
3982                         continue;
3983                 WARN("%p: QP flow attachment failed: %s",
3984                      (void *)dev, strerror(ret));
3985                 goto err;
3986         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3987         priv_dev_interrupt_handler_install(priv, dev);
3988         ret = mlx4_priv_flow_start(priv);
3989         if (ret) {
3990                 ERROR("%p: flow start failed: %s",
3991                       (void *)dev, strerror(ret));
3992                 goto err;
3993         }
3994         priv_unlock(priv);
3995         return 0;
3996 err:
3997         /* Rollback. */
3998         while (i != 0) {
3999                 rxq = (*priv->rxqs)[i--];
4000                 if (rxq != NULL) {
4001                         rxq_allmulticast_disable(rxq);
4002                         rxq_promiscuous_disable(rxq);
4003                         rxq_mac_addrs_del(rxq);
4004                 }
4005         }
4006         priv->started = 0;
4007         priv_unlock(priv);
4008         return -ret;
4009 }
4010
4011 /**
4012  * DPDK callback to stop the device.
4013  *
4014  * Simulate device stop by detaching all configured flows.
4015  *
4016  * @param dev
4017  *   Pointer to Ethernet device structure.
4018  */
4019 static void
4020 mlx4_dev_stop(struct rte_eth_dev *dev)
4021 {
4022         struct priv *priv = dev->data->dev_private;
4023         unsigned int i = 0;
4024         unsigned int r;
4025         struct rxq *rxq;
4026
4027         if (mlx4_is_secondary())
4028                 return;
4029         priv_lock(priv);
4030         if (!priv->started) {
4031                 priv_unlock(priv);
4032                 return;
4033         }
4034         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
4035         priv->started = 0;
4036         if (priv->rss) {
4037                 rxq = &priv->rxq_parent;
4038                 r = 1;
4039         } else {
4040                 rxq = (*priv->rxqs)[0];
4041                 r = priv->rxqs_n;
4042         }
4043         mlx4_priv_flow_stop(priv);
4044         /* Iterate only once when RSS is enabled. */
4045         do {
4046                 /* Ignore nonexistent RX queues. */
4047                 if (rxq == NULL)
4048                         continue;
4049                 rxq_allmulticast_disable(rxq);
4050                 rxq_promiscuous_disable(rxq);
4051                 rxq_mac_addrs_del(rxq);
4052         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
4053         priv_unlock(priv);
4054 }
4055
4056 /**
4057  * Dummy DPDK callback for TX.
4058  *
4059  * This function is used to temporarily replace the real callback during
4060  * unsafe control operations on the queue, or in case of error.
4061  *
4062  * @param dpdk_txq
4063  *   Generic pointer to TX queue structure.
4064  * @param[in] pkts
4065  *   Packets to transmit.
4066  * @param pkts_n
4067  *   Number of packets in array.
4068  *
4069  * @return
4070  *   Number of packets successfully transmitted (<= pkts_n).
4071  */
4072 static uint16_t
4073 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
4074 {
4075         (void)dpdk_txq;
4076         (void)pkts;
4077         (void)pkts_n;
4078         return 0;
4079 }
4080
4081 /**
4082  * Dummy DPDK callback for RX.
4083  *
4084  * This function is used to temporarily replace the real callback during
4085  * unsafe control operations on the queue, or in case of error.
4086  *
4087  * @param dpdk_rxq
4088  *   Generic pointer to RX queue structure.
4089  * @param[out] pkts
4090  *   Array to store received packets.
4091  * @param pkts_n
4092  *   Maximum number of packets in array.
4093  *
4094  * @return
4095  *   Number of packets successfully received (<= pkts_n).
4096  */
4097 static uint16_t
4098 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
4099 {
4100         (void)dpdk_rxq;
4101         (void)pkts;
4102         (void)pkts_n;
4103         return 0;
4104 }
4105
4106 static void
4107 priv_dev_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
4108
4109 /**
4110  * DPDK callback to close the device.
4111  *
4112  * Destroy all queues and objects, free memory.
4113  *
4114  * @param dev
4115  *   Pointer to Ethernet device structure.
4116  */
4117 static void
4118 mlx4_dev_close(struct rte_eth_dev *dev)
4119 {
4120         struct priv *priv = mlx4_get_priv(dev);
4121         void *tmp;
4122         unsigned int i;
4123
4124         if (priv == NULL)
4125                 return;
4126         priv_lock(priv);
4127         DEBUG("%p: closing device \"%s\"",
4128               (void *)dev,
4129               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
4130         /* Prevent crashes when queues are still in use. This is unfortunately
4131          * still required for DPDK 1.3 because some programs (such as testpmd)
4132          * never release them before closing the device. */
4133         dev->rx_pkt_burst = removed_rx_burst;
4134         dev->tx_pkt_burst = removed_tx_burst;
4135         if (priv->rxqs != NULL) {
4136                 /* XXX race condition if mlx4_rx_burst() is still running. */
4137                 usleep(1000);
4138                 for (i = 0; (i != priv->rxqs_n); ++i) {
4139                         tmp = (*priv->rxqs)[i];
4140                         if (tmp == NULL)
4141                                 continue;
4142                         (*priv->rxqs)[i] = NULL;
4143                         rxq_cleanup(tmp);
4144                         rte_free(tmp);
4145                 }
4146                 priv->rxqs_n = 0;
4147                 priv->rxqs = NULL;
4148         }
4149         if (priv->txqs != NULL) {
4150                 /* XXX race condition if mlx4_tx_burst() is still running. */
4151                 usleep(1000);
4152                 for (i = 0; (i != priv->txqs_n); ++i) {
4153                         tmp = (*priv->txqs)[i];
4154                         if (tmp == NULL)
4155                                 continue;
4156                         (*priv->txqs)[i] = NULL;
4157                         txq_cleanup(tmp);
4158                         rte_free(tmp);
4159                 }
4160                 priv->txqs_n = 0;
4161                 priv->txqs = NULL;
4162         }
4163         if (priv->rss)
4164                 rxq_cleanup(&priv->rxq_parent);
4165         if (priv->pd != NULL) {
4166                 assert(priv->ctx != NULL);
4167                 claim_zero(ibv_dealloc_pd(priv->pd));
4168                 claim_zero(ibv_close_device(priv->ctx));
4169         } else
4170                 assert(priv->ctx == NULL);
4171         priv_dev_interrupt_handler_uninstall(priv, dev);
4172         priv_unlock(priv);
4173         memset(priv, 0, sizeof(*priv));
4174 }
4175
4176 /**
4177  * Change the link state (UP / DOWN).
4178  *
4179  * @param priv
4180  *   Pointer to Ethernet device private data.
4181  * @param up
4182  *   Nonzero for link up, otherwise link down.
4183  *
4184  * @return
4185  *   0 on success, errno value on failure.
4186  */
4187 static int
4188 priv_set_link(struct priv *priv, int up)
4189 {
4190         struct rte_eth_dev *dev = priv->dev;
4191         int err;
4192         unsigned int i;
4193
4194         if (up) {
4195                 err = priv_set_flags(priv, ~IFF_UP, IFF_UP);
4196                 if (err)
4197                         return err;
4198                 for (i = 0; i < priv->rxqs_n; i++)
4199                         if ((*priv->rxqs)[i]->sp)
4200                                 break;
4201                 /* Check if an sp queue exists.
4202                  * Note: Some old frames might be received.
4203                  */
4204                 if (i == priv->rxqs_n)
4205                         dev->rx_pkt_burst = mlx4_rx_burst;
4206                 else
4207                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
4208                 dev->tx_pkt_burst = mlx4_tx_burst;
4209         } else {
4210                 err = priv_set_flags(priv, ~IFF_UP, ~IFF_UP);
4211                 if (err)
4212                         return err;
4213                 dev->rx_pkt_burst = removed_rx_burst;
4214                 dev->tx_pkt_burst = removed_tx_burst;
4215         }
4216         return 0;
4217 }
4218
4219 /**
4220  * DPDK callback to bring the link DOWN.
4221  *
4222  * @param dev
4223  *   Pointer to Ethernet device structure.
4224  *
4225  * @return
4226  *   0 on success, errno value on failure.
4227  */
4228 static int
4229 mlx4_set_link_down(struct rte_eth_dev *dev)
4230 {
4231         struct priv *priv = dev->data->dev_private;
4232         int err;
4233
4234         priv_lock(priv);
4235         err = priv_set_link(priv, 0);
4236         priv_unlock(priv);
4237         return err;
4238 }
4239
4240 /**
4241  * DPDK callback to bring the link UP.
4242  *
4243  * @param dev
4244  *   Pointer to Ethernet device structure.
4245  *
4246  * @return
4247  *   0 on success, errno value on failure.
4248  */
4249 static int
4250 mlx4_set_link_up(struct rte_eth_dev *dev)
4251 {
4252         struct priv *priv = dev->data->dev_private;
4253         int err;
4254
4255         priv_lock(priv);
4256         err = priv_set_link(priv, 1);
4257         priv_unlock(priv);
4258         return err;
4259 }
4260 /**
4261  * DPDK callback to get information about the device.
4262  *
4263  * @param dev
4264  *   Pointer to Ethernet device structure.
4265  * @param[out] info
4266  *   Info structure output buffer.
4267  */
4268 static void
4269 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
4270 {
4271         struct priv *priv = mlx4_get_priv(dev);
4272         unsigned int max;
4273         char ifname[IF_NAMESIZE];
4274
4275         info->pci_dev = RTE_DEV_TO_PCI(dev->device);
4276
4277         if (priv == NULL)
4278                 return;
4279         priv_lock(priv);
4280         /* FIXME: we should ask the device for these values. */
4281         info->min_rx_bufsize = 32;
4282         info->max_rx_pktlen = 65536;
4283         /*
4284          * Since we need one CQ per QP, the limit is the minimum number
4285          * between the two values.
4286          */
4287         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
4288                priv->device_attr.max_qp : priv->device_attr.max_cq);
4289         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
4290         if (max >= 65535)
4291                 max = 65535;
4292         info->max_rx_queues = max;
4293         info->max_tx_queues = max;
4294         /* Last array entry is reserved for broadcast. */
4295         info->max_mac_addrs = (elemof(priv->mac) - 1);
4296         info->rx_offload_capa =
4297                 (priv->hw_csum ?
4298                  (DEV_RX_OFFLOAD_IPV4_CKSUM |
4299                   DEV_RX_OFFLOAD_UDP_CKSUM |
4300                   DEV_RX_OFFLOAD_TCP_CKSUM) :
4301                  0);
4302         info->tx_offload_capa =
4303                 (priv->hw_csum ?
4304                  (DEV_TX_OFFLOAD_IPV4_CKSUM |
4305                   DEV_TX_OFFLOAD_UDP_CKSUM |
4306                   DEV_TX_OFFLOAD_TCP_CKSUM) :
4307                  0);
4308         if (priv_get_ifname(priv, &ifname) == 0)
4309                 info->if_index = if_nametoindex(ifname);
4310         info->speed_capa =
4311                         ETH_LINK_SPEED_1G |
4312                         ETH_LINK_SPEED_10G |
4313                         ETH_LINK_SPEED_20G |
4314                         ETH_LINK_SPEED_40G |
4315                         ETH_LINK_SPEED_56G;
4316         priv_unlock(priv);
4317 }
4318
4319 static const uint32_t *
4320 mlx4_dev_supported_ptypes_get(struct rte_eth_dev *dev)
4321 {
4322         static const uint32_t ptypes[] = {
4323                 /* refers to rxq_cq_to_pkt_type() */
4324                 RTE_PTYPE_L3_IPV4,
4325                 RTE_PTYPE_L3_IPV6,
4326                 RTE_PTYPE_INNER_L3_IPV4,
4327                 RTE_PTYPE_INNER_L3_IPV6,
4328                 RTE_PTYPE_UNKNOWN
4329         };
4330
4331         if (dev->rx_pkt_burst == mlx4_rx_burst ||
4332             dev->rx_pkt_burst == mlx4_rx_burst_sp)
4333                 return ptypes;
4334         return NULL;
4335 }
4336
4337 /**
4338  * DPDK callback to get device statistics.
4339  *
4340  * @param dev
4341  *   Pointer to Ethernet device structure.
4342  * @param[out] stats
4343  *   Stats structure output buffer.
4344  */
4345 static void
4346 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
4347 {
4348         struct priv *priv = mlx4_get_priv(dev);
4349         struct rte_eth_stats tmp = {0};
4350         unsigned int i;
4351         unsigned int idx;
4352
4353         if (priv == NULL)
4354                 return;
4355         priv_lock(priv);
4356         /* Add software counters. */
4357         for (i = 0; (i != priv->rxqs_n); ++i) {
4358                 struct rxq *rxq = (*priv->rxqs)[i];
4359
4360                 if (rxq == NULL)
4361                         continue;
4362                 idx = rxq->stats.idx;
4363                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
4364 #ifdef MLX4_PMD_SOFT_COUNTERS
4365                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
4366                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
4367 #endif
4368                         tmp.q_errors[idx] += (rxq->stats.idropped +
4369                                               rxq->stats.rx_nombuf);
4370                 }
4371 #ifdef MLX4_PMD_SOFT_COUNTERS
4372                 tmp.ipackets += rxq->stats.ipackets;
4373                 tmp.ibytes += rxq->stats.ibytes;
4374 #endif
4375                 tmp.ierrors += rxq->stats.idropped;
4376                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
4377         }
4378         for (i = 0; (i != priv->txqs_n); ++i) {
4379                 struct txq *txq = (*priv->txqs)[i];
4380
4381                 if (txq == NULL)
4382                         continue;
4383                 idx = txq->stats.idx;
4384                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
4385 #ifdef MLX4_PMD_SOFT_COUNTERS
4386                         tmp.q_opackets[idx] += txq->stats.opackets;
4387                         tmp.q_obytes[idx] += txq->stats.obytes;
4388 #endif
4389                         tmp.q_errors[idx] += txq->stats.odropped;
4390                 }
4391 #ifdef MLX4_PMD_SOFT_COUNTERS
4392                 tmp.opackets += txq->stats.opackets;
4393                 tmp.obytes += txq->stats.obytes;
4394 #endif
4395                 tmp.oerrors += txq->stats.odropped;
4396         }
4397 #ifndef MLX4_PMD_SOFT_COUNTERS
4398         /* FIXME: retrieve and add hardware counters. */
4399 #endif
4400         *stats = tmp;
4401         priv_unlock(priv);
4402 }
4403
4404 /**
4405  * DPDK callback to clear device statistics.
4406  *
4407  * @param dev
4408  *   Pointer to Ethernet device structure.
4409  */
4410 static void
4411 mlx4_stats_reset(struct rte_eth_dev *dev)
4412 {
4413         struct priv *priv = mlx4_get_priv(dev);
4414         unsigned int i;
4415         unsigned int idx;
4416
4417         if (priv == NULL)
4418                 return;
4419         priv_lock(priv);
4420         for (i = 0; (i != priv->rxqs_n); ++i) {
4421                 if ((*priv->rxqs)[i] == NULL)
4422                         continue;
4423                 idx = (*priv->rxqs)[i]->stats.idx;
4424                 (*priv->rxqs)[i]->stats =
4425                         (struct mlx4_rxq_stats){ .idx = idx };
4426         }
4427         for (i = 0; (i != priv->txqs_n); ++i) {
4428                 if ((*priv->txqs)[i] == NULL)
4429                         continue;
4430                 idx = (*priv->txqs)[i]->stats.idx;
4431                 (*priv->txqs)[i]->stats =
4432                         (struct mlx4_txq_stats){ .idx = idx };
4433         }
4434 #ifndef MLX4_PMD_SOFT_COUNTERS
4435         /* FIXME: reset hardware counters. */
4436 #endif
4437         priv_unlock(priv);
4438 }
4439
4440 /**
4441  * DPDK callback to remove a MAC address.
4442  *
4443  * @param dev
4444  *   Pointer to Ethernet device structure.
4445  * @param index
4446  *   MAC address index.
4447  */
4448 static void
4449 mlx4_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
4450 {
4451         struct priv *priv = dev->data->dev_private;
4452
4453         if (mlx4_is_secondary())
4454                 return;
4455         priv_lock(priv);
4456         DEBUG("%p: removing MAC address from index %" PRIu32,
4457               (void *)dev, index);
4458         /* Last array entry is reserved for broadcast. */
4459         if (index >= (elemof(priv->mac) - 1))
4460                 goto end;
4461         priv_mac_addr_del(priv, index);
4462 end:
4463         priv_unlock(priv);
4464 }
4465
4466 /**
4467  * DPDK callback to add a MAC address.
4468  *
4469  * @param dev
4470  *   Pointer to Ethernet device structure.
4471  * @param mac_addr
4472  *   MAC address to register.
4473  * @param index
4474  *   MAC address index.
4475  * @param vmdq
4476  *   VMDq pool index to associate address with (ignored).
4477  */
4478 static void
4479 mlx4_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
4480                   uint32_t index, uint32_t vmdq)
4481 {
4482         struct priv *priv = dev->data->dev_private;
4483
4484         if (mlx4_is_secondary())
4485                 return;
4486         (void)vmdq;
4487         priv_lock(priv);
4488         DEBUG("%p: adding MAC address at index %" PRIu32,
4489               (void *)dev, index);
4490         /* Last array entry is reserved for broadcast. */
4491         if (index >= (elemof(priv->mac) - 1))
4492                 goto end;
4493         priv_mac_addr_add(priv, index,
4494                           (const uint8_t (*)[ETHER_ADDR_LEN])
4495                           mac_addr->addr_bytes);
4496 end:
4497         priv_unlock(priv);
4498 }
4499
4500 /**
4501  * DPDK callback to set the primary MAC address.
4502  *
4503  * @param dev
4504  *   Pointer to Ethernet device structure.
4505  * @param mac_addr
4506  *   MAC address to register.
4507  */
4508 static void
4509 mlx4_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
4510 {
4511         DEBUG("%p: setting primary MAC address", (void *)dev);
4512         mlx4_mac_addr_remove(dev, 0);
4513         mlx4_mac_addr_add(dev, mac_addr, 0, 0);
4514 }
4515
4516 /**
4517  * DPDK callback to enable promiscuous mode.
4518  *
4519  * @param dev
4520  *   Pointer to Ethernet device structure.
4521  */
4522 static void
4523 mlx4_promiscuous_enable(struct rte_eth_dev *dev)
4524 {
4525         struct priv *priv = dev->data->dev_private;
4526         unsigned int i;
4527         int ret;
4528
4529         if (mlx4_is_secondary())
4530                 return;
4531         priv_lock(priv);
4532         if (priv->promisc) {
4533                 priv_unlock(priv);
4534                 return;
4535         }
4536         /* If device isn't started, this is all we need to do. */
4537         if (!priv->started)
4538                 goto end;
4539         if (priv->rss) {
4540                 ret = rxq_promiscuous_enable(&priv->rxq_parent);
4541                 if (ret) {
4542                         priv_unlock(priv);
4543                         return;
4544                 }
4545                 goto end;
4546         }
4547         for (i = 0; (i != priv->rxqs_n); ++i) {
4548                 if ((*priv->rxqs)[i] == NULL)
4549                         continue;
4550                 ret = rxq_promiscuous_enable((*priv->rxqs)[i]);
4551                 if (!ret)
4552                         continue;
4553                 /* Failure, rollback. */
4554                 while (i != 0)
4555                         if ((*priv->rxqs)[--i] != NULL)
4556                                 rxq_promiscuous_disable((*priv->rxqs)[i]);
4557                 priv_unlock(priv);
4558                 return;
4559         }
4560 end:
4561         priv->promisc = 1;
4562         priv_unlock(priv);
4563 }
4564
4565 /**
4566  * DPDK callback to disable promiscuous mode.
4567  *
4568  * @param dev
4569  *   Pointer to Ethernet device structure.
4570  */
4571 static void
4572 mlx4_promiscuous_disable(struct rte_eth_dev *dev)
4573 {
4574         struct priv *priv = dev->data->dev_private;
4575         unsigned int i;
4576
4577         if (mlx4_is_secondary())
4578                 return;
4579         priv_lock(priv);
4580         if (!priv->promisc) {
4581                 priv_unlock(priv);
4582                 return;
4583         }
4584         if (priv->rss) {
4585                 rxq_promiscuous_disable(&priv->rxq_parent);
4586                 goto end;
4587         }
4588         for (i = 0; (i != priv->rxqs_n); ++i)
4589                 if ((*priv->rxqs)[i] != NULL)
4590                         rxq_promiscuous_disable((*priv->rxqs)[i]);
4591 end:
4592         priv->promisc = 0;
4593         priv_unlock(priv);
4594 }
4595
4596 /**
4597  * DPDK callback to enable allmulti mode.
4598  *
4599  * @param dev
4600  *   Pointer to Ethernet device structure.
4601  */
4602 static void
4603 mlx4_allmulticast_enable(struct rte_eth_dev *dev)
4604 {
4605         struct priv *priv = dev->data->dev_private;
4606         unsigned int i;
4607         int ret;
4608
4609         if (mlx4_is_secondary())
4610                 return;
4611         priv_lock(priv);
4612         if (priv->allmulti) {
4613                 priv_unlock(priv);
4614                 return;
4615         }
4616         /* If device isn't started, this is all we need to do. */
4617         if (!priv->started)
4618                 goto end;
4619         if (priv->rss) {
4620                 ret = rxq_allmulticast_enable(&priv->rxq_parent);
4621                 if (ret) {
4622                         priv_unlock(priv);
4623                         return;
4624                 }
4625                 goto end;
4626         }
4627         for (i = 0; (i != priv->rxqs_n); ++i) {
4628                 if ((*priv->rxqs)[i] == NULL)
4629                         continue;
4630                 ret = rxq_allmulticast_enable((*priv->rxqs)[i]);
4631                 if (!ret)
4632                         continue;
4633                 /* Failure, rollback. */
4634                 while (i != 0)
4635                         if ((*priv->rxqs)[--i] != NULL)
4636                                 rxq_allmulticast_disable((*priv->rxqs)[i]);
4637                 priv_unlock(priv);
4638                 return;
4639         }
4640 end:
4641         priv->allmulti = 1;
4642         priv_unlock(priv);
4643 }
4644
4645 /**
4646  * DPDK callback to disable allmulti mode.
4647  *
4648  * @param dev
4649  *   Pointer to Ethernet device structure.
4650  */
4651 static void
4652 mlx4_allmulticast_disable(struct rte_eth_dev *dev)
4653 {
4654         struct priv *priv = dev->data->dev_private;
4655         unsigned int i;
4656
4657         if (mlx4_is_secondary())
4658                 return;
4659         priv_lock(priv);
4660         if (!priv->allmulti) {
4661                 priv_unlock(priv);
4662                 return;
4663         }
4664         if (priv->rss) {
4665                 rxq_allmulticast_disable(&priv->rxq_parent);
4666                 goto end;
4667         }
4668         for (i = 0; (i != priv->rxqs_n); ++i)
4669                 if ((*priv->rxqs)[i] != NULL)
4670                         rxq_allmulticast_disable((*priv->rxqs)[i]);
4671 end:
4672         priv->allmulti = 0;
4673         priv_unlock(priv);
4674 }
4675
4676 /**
4677  * DPDK callback to retrieve physical link information.
4678  *
4679  * @param dev
4680  *   Pointer to Ethernet device structure.
4681  * @param wait_to_complete
4682  *   Wait for request completion (ignored).
4683  */
4684 static int
4685 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
4686 {
4687         const struct priv *priv = mlx4_get_priv(dev);
4688         struct ethtool_cmd edata = {
4689                 .cmd = ETHTOOL_GSET
4690         };
4691         struct ifreq ifr;
4692         struct rte_eth_link dev_link;
4693         int link_speed = 0;
4694
4695         /* priv_lock() is not taken to allow concurrent calls. */
4696
4697         if (priv == NULL)
4698                 return -EINVAL;
4699         (void)wait_to_complete;
4700         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
4701                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(errno));
4702                 return -1;
4703         }
4704         memset(&dev_link, 0, sizeof(dev_link));
4705         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
4706                                 (ifr.ifr_flags & IFF_RUNNING));
4707         ifr.ifr_data = (void *)&edata;
4708         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4709                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
4710                      strerror(errno));
4711                 return -1;
4712         }
4713         link_speed = ethtool_cmd_speed(&edata);
4714         if (link_speed == -1)
4715                 dev_link.link_speed = 0;
4716         else
4717                 dev_link.link_speed = link_speed;
4718         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
4719                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
4720         dev_link.link_autoneg = !(dev->data->dev_conf.link_speeds &
4721                         ETH_LINK_SPEED_FIXED);
4722         if (memcmp(&dev_link, &dev->data->dev_link, sizeof(dev_link))) {
4723                 /* Link status changed. */
4724                 dev->data->dev_link = dev_link;
4725                 return 0;
4726         }
4727         /* Link status is still the same. */
4728         return -1;
4729 }
4730
4731 /**
4732  * DPDK callback to change the MTU.
4733  *
4734  * Setting the MTU affects hardware MRU (packets larger than the MTU cannot be
4735  * received). Use this as a hint to enable/disable scattered packets support
4736  * and improve performance when not needed.
4737  * Since failure is not an option, reconfiguring queues on the fly is not
4738  * recommended.
4739  *
4740  * @param dev
4741  *   Pointer to Ethernet device structure.
4742  * @param in_mtu
4743  *   New MTU.
4744  *
4745  * @return
4746  *   0 on success, negative errno value on failure.
4747  */
4748 static int
4749 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
4750 {
4751         struct priv *priv = dev->data->dev_private;
4752         int ret = 0;
4753         unsigned int i;
4754         uint16_t (*rx_func)(void *, struct rte_mbuf **, uint16_t) =
4755                 mlx4_rx_burst;
4756
4757         if (mlx4_is_secondary())
4758                 return -E_RTE_SECONDARY;
4759         priv_lock(priv);
4760         /* Set kernel interface MTU first. */
4761         if (priv_set_mtu(priv, mtu)) {
4762                 ret = errno;
4763                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
4764                      strerror(ret));
4765                 goto out;
4766         } else
4767                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
4768         priv->mtu = mtu;
4769         /* Temporarily replace RX handler with a fake one, assuming it has not
4770          * been copied elsewhere. */
4771         dev->rx_pkt_burst = removed_rx_burst;
4772         /* Make sure everyone has left mlx4_rx_burst() and uses
4773          * removed_rx_burst() instead. */
4774         rte_wmb();
4775         usleep(1000);
4776         /* Reconfigure each RX queue. */
4777         for (i = 0; (i != priv->rxqs_n); ++i) {
4778                 struct rxq *rxq = (*priv->rxqs)[i];
4779                 unsigned int max_frame_len;
4780
4781                 if (rxq == NULL)
4782                         continue;
4783                 /* Calculate new maximum frame length according to MTU. */
4784                 max_frame_len = (priv->mtu + ETHER_HDR_LEN +
4785                                  (ETHER_MAX_VLAN_FRAME_LEN - ETHER_MAX_LEN));
4786                 /* Provide new values to rxq_setup(). */
4787                 dev->data->dev_conf.rxmode.jumbo_frame =
4788                         (max_frame_len > ETHER_MAX_LEN);
4789                 dev->data->dev_conf.rxmode.max_rx_pkt_len = max_frame_len;
4790                 ret = rxq_rehash(dev, rxq);
4791                 if (ret) {
4792                         /* Force SP RX if that queue requires it and abort. */
4793                         if (rxq->sp)
4794                                 rx_func = mlx4_rx_burst_sp;
4795                         break;
4796                 }
4797                 /* Reenable non-RSS queue attributes. No need to check
4798                  * for errors at this stage. */
4799                 if (!priv->rss) {
4800                         rxq_mac_addrs_add(rxq);
4801                         if (priv->promisc)
4802                                 rxq_promiscuous_enable(rxq);
4803                         if (priv->allmulti)
4804                                 rxq_allmulticast_enable(rxq);
4805                 }
4806                 /* Scattered burst function takes priority. */
4807                 if (rxq->sp)
4808                         rx_func = mlx4_rx_burst_sp;
4809         }
4810         /* Burst functions can now be called again. */
4811         rte_wmb();
4812         dev->rx_pkt_burst = rx_func;
4813 out:
4814         priv_unlock(priv);
4815         assert(ret >= 0);
4816         return -ret;
4817 }
4818
4819 /**
4820  * DPDK callback to get flow control status.
4821  *
4822  * @param dev
4823  *   Pointer to Ethernet device structure.
4824  * @param[out] fc_conf
4825  *   Flow control output buffer.
4826  *
4827  * @return
4828  *   0 on success, negative errno value on failure.
4829  */
4830 static int
4831 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4832 {
4833         struct priv *priv = dev->data->dev_private;
4834         struct ifreq ifr;
4835         struct ethtool_pauseparam ethpause = {
4836                 .cmd = ETHTOOL_GPAUSEPARAM
4837         };
4838         int ret;
4839
4840         if (mlx4_is_secondary())
4841                 return -E_RTE_SECONDARY;
4842         ifr.ifr_data = (void *)&ethpause;
4843         priv_lock(priv);
4844         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4845                 ret = errno;
4846                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
4847                      " failed: %s",
4848                      strerror(ret));
4849                 goto out;
4850         }
4851
4852         fc_conf->autoneg = ethpause.autoneg;
4853         if (ethpause.rx_pause && ethpause.tx_pause)
4854                 fc_conf->mode = RTE_FC_FULL;
4855         else if (ethpause.rx_pause)
4856                 fc_conf->mode = RTE_FC_RX_PAUSE;
4857         else if (ethpause.tx_pause)
4858                 fc_conf->mode = RTE_FC_TX_PAUSE;
4859         else
4860                 fc_conf->mode = RTE_FC_NONE;
4861         ret = 0;
4862
4863 out:
4864         priv_unlock(priv);
4865         assert(ret >= 0);
4866         return -ret;
4867 }
4868
4869 /**
4870  * DPDK callback to modify flow control parameters.
4871  *
4872  * @param dev
4873  *   Pointer to Ethernet device structure.
4874  * @param[in] fc_conf
4875  *   Flow control parameters.
4876  *
4877  * @return
4878  *   0 on success, negative errno value on failure.
4879  */
4880 static int
4881 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4882 {
4883         struct priv *priv = dev->data->dev_private;
4884         struct ifreq ifr;
4885         struct ethtool_pauseparam ethpause = {
4886                 .cmd = ETHTOOL_SPAUSEPARAM
4887         };
4888         int ret;
4889
4890         if (mlx4_is_secondary())
4891                 return -E_RTE_SECONDARY;
4892         ifr.ifr_data = (void *)&ethpause;
4893         ethpause.autoneg = fc_conf->autoneg;
4894         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4895             (fc_conf->mode & RTE_FC_RX_PAUSE))
4896                 ethpause.rx_pause = 1;
4897         else
4898                 ethpause.rx_pause = 0;
4899
4900         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4901             (fc_conf->mode & RTE_FC_TX_PAUSE))
4902                 ethpause.tx_pause = 1;
4903         else
4904                 ethpause.tx_pause = 0;
4905
4906         priv_lock(priv);
4907         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4908                 ret = errno;
4909                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
4910                      " failed: %s",
4911                      strerror(ret));
4912                 goto out;
4913         }
4914         ret = 0;
4915
4916 out:
4917         priv_unlock(priv);
4918         assert(ret >= 0);
4919         return -ret;
4920 }
4921
4922 /**
4923  * Configure a VLAN filter.
4924  *
4925  * @param dev
4926  *   Pointer to Ethernet device structure.
4927  * @param vlan_id
4928  *   VLAN ID to filter.
4929  * @param on
4930  *   Toggle filter.
4931  *
4932  * @return
4933  *   0 on success, errno value on failure.
4934  */
4935 static int
4936 vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4937 {
4938         struct priv *priv = dev->data->dev_private;
4939         unsigned int i;
4940         unsigned int j = -1;
4941
4942         DEBUG("%p: %s VLAN filter ID %" PRIu16,
4943               (void *)dev, (on ? "enable" : "disable"), vlan_id);
4944         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
4945                 if (!priv->vlan_filter[i].enabled) {
4946                         /* Unused index, remember it. */
4947                         j = i;
4948                         continue;
4949                 }
4950                 if (priv->vlan_filter[i].id != vlan_id)
4951                         continue;
4952                 /* This VLAN ID is already known, use its index. */
4953                 j = i;
4954                 break;
4955         }
4956         /* Check if there's room for another VLAN filter. */
4957         if (j == (unsigned int)-1)
4958                 return ENOMEM;
4959         /*
4960          * VLAN filters apply to all configured MAC addresses, flow
4961          * specifications must be reconfigured accordingly.
4962          */
4963         priv->vlan_filter[j].id = vlan_id;
4964         if ((on) && (!priv->vlan_filter[j].enabled)) {
4965                 /*
4966                  * Filter is disabled, enable it.
4967                  * Rehashing flows in all RX queues is necessary.
4968                  */
4969                 if (priv->rss)
4970                         rxq_mac_addrs_del(&priv->rxq_parent);
4971                 else
4972                         for (i = 0; (i != priv->rxqs_n); ++i)
4973                                 if ((*priv->rxqs)[i] != NULL)
4974                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4975                 priv->vlan_filter[j].enabled = 1;
4976                 if (priv->started) {
4977                         if (priv->rss)
4978                                 rxq_mac_addrs_add(&priv->rxq_parent);
4979                         else
4980                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4981                                         if ((*priv->rxqs)[i] == NULL)
4982                                                 continue;
4983                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4984                                 }
4985                 }
4986         } else if ((!on) && (priv->vlan_filter[j].enabled)) {
4987                 /*
4988                  * Filter is enabled, disable it.
4989                  * Rehashing flows in all RX queues is necessary.
4990                  */
4991                 if (priv->rss)
4992                         rxq_mac_addrs_del(&priv->rxq_parent);
4993                 else
4994                         for (i = 0; (i != priv->rxqs_n); ++i)
4995                                 if ((*priv->rxqs)[i] != NULL)
4996                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4997                 priv->vlan_filter[j].enabled = 0;
4998                 if (priv->started) {
4999                         if (priv->rss)
5000                                 rxq_mac_addrs_add(&priv->rxq_parent);
5001                         else
5002                                 for (i = 0; (i != priv->rxqs_n); ++i) {
5003                                         if ((*priv->rxqs)[i] == NULL)
5004                                                 continue;
5005                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
5006                                 }
5007                 }
5008         }
5009         return 0;
5010 }
5011
5012 /**
5013  * DPDK callback to configure a VLAN filter.
5014  *
5015  * @param dev
5016  *   Pointer to Ethernet device structure.
5017  * @param vlan_id
5018  *   VLAN ID to filter.
5019  * @param on
5020  *   Toggle filter.
5021  *
5022  * @return
5023  *   0 on success, negative errno value on failure.
5024  */
5025 static int
5026 mlx4_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
5027 {
5028         struct priv *priv = dev->data->dev_private;
5029         int ret;
5030
5031         if (mlx4_is_secondary())
5032                 return -E_RTE_SECONDARY;
5033         priv_lock(priv);
5034         ret = vlan_filter_set(dev, vlan_id, on);
5035         priv_unlock(priv);
5036         assert(ret >= 0);
5037         return -ret;
5038 }
5039
5040 const struct rte_flow_ops mlx4_flow_ops = {
5041         .validate = mlx4_flow_validate,
5042         .create = mlx4_flow_create,
5043         .destroy = mlx4_flow_destroy,
5044         .flush = mlx4_flow_flush,
5045         .query = NULL,
5046 };
5047
5048 /**
5049  * Manage filter operations.
5050  *
5051  * @param dev
5052  *   Pointer to Ethernet device structure.
5053  * @param filter_type
5054  *   Filter type.
5055  * @param filter_op
5056  *   Operation to perform.
5057  * @param arg
5058  *   Pointer to operation-specific structure.
5059  *
5060  * @return
5061  *   0 on success, negative errno value on failure.
5062  */
5063 static int
5064 mlx4_dev_filter_ctrl(struct rte_eth_dev *dev,
5065                      enum rte_filter_type filter_type,
5066                      enum rte_filter_op filter_op,
5067                      void *arg)
5068 {
5069         int ret = EINVAL;
5070
5071         switch (filter_type) {
5072         case RTE_ETH_FILTER_GENERIC:
5073                 if (filter_op != RTE_ETH_FILTER_GET)
5074                         return -EINVAL;
5075                 *(const void **)arg = &mlx4_flow_ops;
5076                 return 0;
5077         case RTE_ETH_FILTER_FDIR:
5078                 DEBUG("%p: filter type FDIR is not supported by this PMD",
5079                       (void *)dev);
5080                 break;
5081         default:
5082                 ERROR("%p: filter type (%d) not supported",
5083                       (void *)dev, filter_type);
5084                 break;
5085         }
5086         return -ret;
5087 }
5088
5089 static const struct eth_dev_ops mlx4_dev_ops = {
5090         .dev_configure = mlx4_dev_configure,
5091         .dev_start = mlx4_dev_start,
5092         .dev_stop = mlx4_dev_stop,
5093         .dev_set_link_down = mlx4_set_link_down,
5094         .dev_set_link_up = mlx4_set_link_up,
5095         .dev_close = mlx4_dev_close,
5096         .promiscuous_enable = mlx4_promiscuous_enable,
5097         .promiscuous_disable = mlx4_promiscuous_disable,
5098         .allmulticast_enable = mlx4_allmulticast_enable,
5099         .allmulticast_disable = mlx4_allmulticast_disable,
5100         .link_update = mlx4_link_update,
5101         .stats_get = mlx4_stats_get,
5102         .stats_reset = mlx4_stats_reset,
5103         .queue_stats_mapping_set = NULL,
5104         .dev_infos_get = mlx4_dev_infos_get,
5105         .dev_supported_ptypes_get = mlx4_dev_supported_ptypes_get,
5106         .vlan_filter_set = mlx4_vlan_filter_set,
5107         .vlan_tpid_set = NULL,
5108         .vlan_strip_queue_set = NULL,
5109         .vlan_offload_set = NULL,
5110         .rx_queue_setup = mlx4_rx_queue_setup,
5111         .tx_queue_setup = mlx4_tx_queue_setup,
5112         .rx_queue_release = mlx4_rx_queue_release,
5113         .tx_queue_release = mlx4_tx_queue_release,
5114         .dev_led_on = NULL,
5115         .dev_led_off = NULL,
5116         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
5117         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
5118         .priority_flow_ctrl_set = NULL,
5119         .mac_addr_remove = mlx4_mac_addr_remove,
5120         .mac_addr_add = mlx4_mac_addr_add,
5121         .mac_addr_set = mlx4_mac_addr_set,
5122         .mtu_set = mlx4_dev_set_mtu,
5123         .filter_ctrl = mlx4_dev_filter_ctrl,
5124 };
5125
5126 /**
5127  * Get PCI information from struct ibv_device.
5128  *
5129  * @param device
5130  *   Pointer to Ethernet device structure.
5131  * @param[out] pci_addr
5132  *   PCI bus address output buffer.
5133  *
5134  * @return
5135  *   0 on success, -1 on failure and errno is set.
5136  */
5137 static int
5138 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
5139                             struct rte_pci_addr *pci_addr)
5140 {
5141         FILE *file;
5142         char line[32];
5143         MKSTR(path, "%s/device/uevent", device->ibdev_path);
5144
5145         file = fopen(path, "rb");
5146         if (file == NULL)
5147                 return -1;
5148         while (fgets(line, sizeof(line), file) == line) {
5149                 size_t len = strlen(line);
5150                 int ret;
5151
5152                 /* Truncate long lines. */
5153                 if (len == (sizeof(line) - 1))
5154                         while (line[(len - 1)] != '\n') {
5155                                 ret = fgetc(file);
5156                                 if (ret == EOF)
5157                                         break;
5158                                 line[(len - 1)] = ret;
5159                         }
5160                 /* Extract information. */
5161                 if (sscanf(line,
5162                            "PCI_SLOT_NAME="
5163                            "%" SCNx16 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
5164                            &pci_addr->domain,
5165                            &pci_addr->bus,
5166                            &pci_addr->devid,
5167                            &pci_addr->function) == 4) {
5168                         ret = 0;
5169                         break;
5170                 }
5171         }
5172         fclose(file);
5173         return 0;
5174 }
5175
5176 /**
5177  * Get MAC address by querying netdevice.
5178  *
5179  * @param[in] priv
5180  *   struct priv for the requested device.
5181  * @param[out] mac
5182  *   MAC address output buffer.
5183  *
5184  * @return
5185  *   0 on success, -1 on failure and errno is set.
5186  */
5187 static int
5188 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
5189 {
5190         struct ifreq request;
5191
5192         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
5193                 return -1;
5194         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
5195         return 0;
5196 }
5197
5198 /* Support up to 32 adapters. */
5199 static struct {
5200         struct rte_pci_addr pci_addr; /* associated PCI address */
5201         uint32_t ports; /* physical ports bitfield. */
5202 } mlx4_dev[32];
5203
5204 /**
5205  * Get device index in mlx4_dev[] from PCI bus address.
5206  *
5207  * @param[in] pci_addr
5208  *   PCI bus address to look for.
5209  *
5210  * @return
5211  *   mlx4_dev[] index on success, -1 on failure.
5212  */
5213 static int
5214 mlx4_dev_idx(struct rte_pci_addr *pci_addr)
5215 {
5216         unsigned int i;
5217         int ret = -1;
5218
5219         assert(pci_addr != NULL);
5220         for (i = 0; (i != elemof(mlx4_dev)); ++i) {
5221                 if ((mlx4_dev[i].pci_addr.domain == pci_addr->domain) &&
5222                     (mlx4_dev[i].pci_addr.bus == pci_addr->bus) &&
5223                     (mlx4_dev[i].pci_addr.devid == pci_addr->devid) &&
5224                     (mlx4_dev[i].pci_addr.function == pci_addr->function))
5225                         return i;
5226                 if ((mlx4_dev[i].ports == 0) && (ret == -1))
5227                         ret = i;
5228         }
5229         return ret;
5230 }
5231
5232 /**
5233  * Retrieve integer value from environment variable.
5234  *
5235  * @param[in] name
5236  *   Environment variable name.
5237  *
5238  * @return
5239  *   Integer value, 0 if the variable is not set.
5240  */
5241 static int
5242 mlx4_getenv_int(const char *name)
5243 {
5244         const char *val = getenv(name);
5245
5246         if (val == NULL)
5247                 return 0;
5248         return atoi(val);
5249 }
5250
5251 static void
5252 mlx4_dev_link_status_handler(void *);
5253 static void
5254 mlx4_dev_interrupt_handler(void *);
5255
5256 /**
5257  * Link status handler.
5258  *
5259  * @param priv
5260  *   Pointer to private structure.
5261  * @param dev
5262  *   Pointer to the rte_eth_dev structure.
5263  *
5264  * @return
5265  *   Nonzero if the callback process can be called immediately.
5266  */
5267 static int
5268 priv_dev_link_status_handler(struct priv *priv, struct rte_eth_dev *dev)
5269 {
5270         struct ibv_async_event event;
5271         int port_change = 0;
5272         int ret = 0;
5273
5274         /* Read all message and acknowledge them. */
5275         for (;;) {
5276                 if (ibv_get_async_event(priv->ctx, &event))
5277                         break;
5278
5279                 if (event.event_type == IBV_EVENT_PORT_ACTIVE ||
5280                     event.event_type == IBV_EVENT_PORT_ERR)
5281                         port_change = 1;
5282                 else
5283                         DEBUG("event type %d on port %d not handled",
5284                               event.event_type, event.element.port_num);
5285                 ibv_ack_async_event(&event);
5286         }
5287
5288         if (port_change ^ priv->pending_alarm) {
5289                 struct rte_eth_link *link = &dev->data->dev_link;
5290
5291                 priv->pending_alarm = 0;
5292                 mlx4_link_update(dev, 0);
5293                 if (((link->link_speed == 0) && link->link_status) ||
5294                     ((link->link_speed != 0) && !link->link_status)) {
5295                         /* Inconsistent status, check again later. */
5296                         priv->pending_alarm = 1;
5297                         rte_eal_alarm_set(MLX4_ALARM_TIMEOUT_US,
5298                                           mlx4_dev_link_status_handler,
5299                                           dev);
5300                 } else
5301                         ret = 1;
5302         }
5303         return ret;
5304 }
5305
5306 /**
5307  * Handle delayed link status event.
5308  *
5309  * @param arg
5310  *   Registered argument.
5311  */
5312 static void
5313 mlx4_dev_link_status_handler(void *arg)
5314 {
5315         struct rte_eth_dev *dev = arg;
5316         struct priv *priv = dev->data->dev_private;
5317         int ret;
5318
5319         priv_lock(priv);
5320         assert(priv->pending_alarm == 1);
5321         ret = priv_dev_link_status_handler(priv, dev);
5322         priv_unlock(priv);
5323         if (ret)
5324                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC, NULL);
5325 }
5326
5327 /**
5328  * Handle interrupts from the NIC.
5329  *
5330  * @param[in] intr_handle
5331  *   Interrupt handler.
5332  * @param cb_arg
5333  *   Callback argument.
5334  */
5335 static void
5336 mlx4_dev_interrupt_handler(void *cb_arg)
5337 {
5338         struct rte_eth_dev *dev = cb_arg;
5339         struct priv *priv = dev->data->dev_private;
5340         int ret;
5341
5342         priv_lock(priv);
5343         ret = priv_dev_link_status_handler(priv, dev);
5344         priv_unlock(priv);
5345         if (ret)
5346                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC, NULL);
5347 }
5348
5349 /**
5350  * Uninstall interrupt handler.
5351  *
5352  * @param priv
5353  *   Pointer to private structure.
5354  * @param dev
5355  *   Pointer to the rte_eth_dev structure.
5356  */
5357 static void
5358 priv_dev_interrupt_handler_uninstall(struct priv *priv, struct rte_eth_dev *dev)
5359 {
5360         if (!dev->data->dev_conf.intr_conf.lsc)
5361                 return;
5362         rte_intr_callback_unregister(&priv->intr_handle,
5363                                      mlx4_dev_interrupt_handler,
5364                                      dev);
5365         if (priv->pending_alarm)
5366                 rte_eal_alarm_cancel(mlx4_dev_link_status_handler, dev);
5367         priv->pending_alarm = 0;
5368         priv->intr_handle.fd = 0;
5369         priv->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
5370 }
5371
5372 /**
5373  * Install interrupt handler.
5374  *
5375  * @param priv
5376  *   Pointer to private structure.
5377  * @param dev
5378  *   Pointer to the rte_eth_dev structure.
5379  */
5380 static void
5381 priv_dev_interrupt_handler_install(struct priv *priv, struct rte_eth_dev *dev)
5382 {
5383         int rc, flags;
5384
5385         if (!dev->data->dev_conf.intr_conf.lsc)
5386                 return;
5387         assert(priv->ctx->async_fd > 0);
5388         flags = fcntl(priv->ctx->async_fd, F_GETFL);
5389         rc = fcntl(priv->ctx->async_fd, F_SETFL, flags | O_NONBLOCK);
5390         if (rc < 0) {
5391                 INFO("failed to change file descriptor async event queue");
5392                 dev->data->dev_conf.intr_conf.lsc = 0;
5393         } else {
5394                 priv->intr_handle.fd = priv->ctx->async_fd;
5395                 priv->intr_handle.type = RTE_INTR_HANDLE_EXT;
5396                 rte_intr_callback_register(&priv->intr_handle,
5397                                            mlx4_dev_interrupt_handler,
5398                                            dev);
5399         }
5400 }
5401
5402 /**
5403  * Verify and store value for device argument.
5404  *
5405  * @param[in] key
5406  *   Key argument to verify.
5407  * @param[in] val
5408  *   Value associated with key.
5409  * @param out
5410  *   User data.
5411  *
5412  * @return
5413  *   0 on success, negative errno value on failure.
5414  */
5415 static int
5416 mlx4_arg_parse(const char *key, const char *val, void *out)
5417 {
5418         struct mlx4_conf *conf = out;
5419         unsigned long tmp;
5420
5421         errno = 0;
5422         tmp = strtoul(val, NULL, 0);
5423         if (errno) {
5424                 WARN("%s: \"%s\" is not a valid integer", key, val);
5425                 return -errno;
5426         }
5427         if (strcmp(MLX4_PMD_PORT_KVARG, key) == 0) {
5428                 if (tmp >= MLX4_PMD_MAX_PHYS_PORTS) {
5429                         ERROR("invalid port index %lu (max: %u)",
5430                                 tmp, MLX4_PMD_MAX_PHYS_PORTS - 1);
5431                         return -EINVAL;
5432                 }
5433                 conf->active_ports |= 1 << tmp;
5434         } else {
5435                 WARN("%s: unknown parameter", key);
5436                 return -EINVAL;
5437         }
5438         return 0;
5439 }
5440
5441 /**
5442  * Parse device parameters.
5443  *
5444  * @param devargs
5445  *   Device arguments structure.
5446  *
5447  * @return
5448  *   0 on success, negative errno value on failure.
5449  */
5450 static int
5451 mlx4_args(struct rte_devargs *devargs, struct mlx4_conf *conf)
5452 {
5453         struct rte_kvargs *kvlist;
5454         unsigned int arg_count;
5455         int ret = 0;
5456         int i;
5457
5458         if (devargs == NULL)
5459                 return 0;
5460         kvlist = rte_kvargs_parse(devargs->args, pmd_mlx4_init_params);
5461         if (kvlist == NULL) {
5462                 ERROR("failed to parse kvargs");
5463                 return -EINVAL;
5464         }
5465         /* Process parameters. */
5466         for (i = 0; pmd_mlx4_init_params[i]; ++i) {
5467                 arg_count = rte_kvargs_count(kvlist, MLX4_PMD_PORT_KVARG);
5468                 while (arg_count-- > 0) {
5469                         ret = rte_kvargs_process(kvlist, MLX4_PMD_PORT_KVARG,
5470                                         mlx4_arg_parse, conf);
5471                         if (ret != 0)
5472                                 goto free_kvlist;
5473                 }
5474         }
5475 free_kvlist:
5476         rte_kvargs_free(kvlist);
5477         return ret;
5478 }
5479
5480 static struct eth_driver mlx4_driver;
5481
5482 /**
5483  * DPDK callback to register a PCI device.
5484  *
5485  * This function creates an Ethernet device for each port of a given
5486  * PCI device.
5487  *
5488  * @param[in] pci_drv
5489  *   PCI driver structure (mlx4_driver).
5490  * @param[in] pci_dev
5491  *   PCI device information.
5492  *
5493  * @return
5494  *   0 on success, negative errno value on failure.
5495  */
5496 static int
5497 mlx4_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
5498 {
5499         struct ibv_device **list;
5500         struct ibv_device *ibv_dev;
5501         int err = 0;
5502         struct ibv_context *attr_ctx = NULL;
5503         struct ibv_device_attr device_attr;
5504         struct mlx4_conf conf = {
5505                 .active_ports = 0,
5506         };
5507         unsigned int vf;
5508         int idx;
5509         int i;
5510
5511         (void)pci_drv;
5512         assert(pci_drv == &mlx4_driver.pci_drv);
5513         /* Get mlx4_dev[] index. */
5514         idx = mlx4_dev_idx(&pci_dev->addr);
5515         if (idx == -1) {
5516                 ERROR("this driver cannot support any more adapters");
5517                 return -ENOMEM;
5518         }
5519         DEBUG("using driver device index %d", idx);
5520
5521         /* Save PCI address. */
5522         mlx4_dev[idx].pci_addr = pci_dev->addr;
5523         list = ibv_get_device_list(&i);
5524         if (list == NULL) {
5525                 assert(errno);
5526                 if (errno == ENOSYS)
5527                         ERROR("cannot list devices, is ib_uverbs loaded?");
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                         ERROR("cannot access device, is mlx4_ib loaded?");
5560                         return -ENODEV;
5561                 case EINVAL:
5562                         ERROR("cannot use device, are drivers up to date?");
5563                         return -EINVAL;
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");