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