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