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