net/mlx4: fix Rx interrupts management
[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 #endif
3006                         assert(rep->buf_len == seg->buf_len);
3007                         /* Reconfigure sge to use rep instead of seg. */
3008                         assert(sge->lkey == rxq->mr->lkey);
3009                         sge->addr = ((uintptr_t)rep->buf_addr + seg_headroom);
3010                         elt->bufs[j] = rep;
3011                         ++j;
3012                         /* Update pkt_buf if it's the first segment, or link
3013                          * seg to the previous one and update pkt_buf_next. */
3014                         *pkt_buf_next = seg;
3015                         pkt_buf_next = &NEXT(seg);
3016                         /* Update seg information. */
3017                         seg_tailroom = (seg->buf_len - seg_headroom);
3018                         assert(sge->length == seg_tailroom);
3019                         SET_DATA_OFF(seg, seg_headroom);
3020                         if (likely(len <= seg_tailroom)) {
3021                                 /* Last segment. */
3022                                 DATA_LEN(seg) = len;
3023                                 PKT_LEN(seg) = len;
3024                                 /* Sanity check. */
3025                                 assert(rte_pktmbuf_headroom(seg) ==
3026                                        seg_headroom);
3027                                 assert(rte_pktmbuf_tailroom(seg) ==
3028                                        (seg_tailroom - len));
3029                                 break;
3030                         }
3031                         DATA_LEN(seg) = seg_tailroom;
3032                         PKT_LEN(seg) = seg_tailroom;
3033                         /* Sanity check. */
3034                         assert(rte_pktmbuf_headroom(seg) == seg_headroom);
3035                         assert(rte_pktmbuf_tailroom(seg) == 0);
3036                         /* Fix len and clear headroom for next segments. */
3037                         len -= seg_tailroom;
3038                         seg_headroom = 0;
3039                 }
3040                 /* Update head and tail segments. */
3041                 *pkt_buf_next = NULL;
3042                 assert(pkt_buf != NULL);
3043                 assert(j != 0);
3044                 NB_SEGS(pkt_buf) = j;
3045                 PORT(pkt_buf) = rxq->port_id;
3046                 PKT_LEN(pkt_buf) = pkt_buf_len;
3047                 pkt_buf->packet_type = rxq_cq_to_pkt_type(flags);
3048                 pkt_buf->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
3049
3050                 /* Return packet. */
3051                 *(pkts++) = pkt_buf;
3052                 ++pkts_ret;
3053 #ifdef MLX4_PMD_SOFT_COUNTERS
3054                 /* Increase bytes counter. */
3055                 rxq->stats.ibytes += pkt_buf_len;
3056 #endif
3057 repost:
3058                 if (++elts_head >= elts_n)
3059                         elts_head = 0;
3060                 continue;
3061         }
3062         if (unlikely(i == 0))
3063                 return 0;
3064         *next = NULL;
3065         /* Repost WRs. */
3066 #ifdef DEBUG_RECV
3067         DEBUG("%p: reposting %d WRs", (void *)rxq, i);
3068 #endif
3069         ret = ibv_post_recv(rxq->qp, head.next, &bad_wr);
3070         if (unlikely(ret)) {
3071                 /* Inability to repost WRs is fatal. */
3072                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
3073                       (void *)rxq->priv,
3074                       (void *)bad_wr,
3075                       strerror(ret));
3076                 abort();
3077         }
3078         rxq->elts_head = elts_head;
3079 #ifdef MLX4_PMD_SOFT_COUNTERS
3080         /* Increase packets counter. */
3081         rxq->stats.ipackets += pkts_ret;
3082 #endif
3083         return pkts_ret;
3084 }
3085
3086 /**
3087  * DPDK callback for RX.
3088  *
3089  * The following function is the same as mlx4_rx_burst_sp(), except it doesn't
3090  * manage scattered packets. Improves performance when MRU is lower than the
3091  * size of the first segment.
3092  *
3093  * @param dpdk_rxq
3094  *   Generic pointer to RX queue structure.
3095  * @param[out] pkts
3096  *   Array to store received packets.
3097  * @param pkts_n
3098  *   Maximum number of packets in array.
3099  *
3100  * @return
3101  *   Number of packets successfully received (<= pkts_n).
3102  */
3103 static uint16_t
3104 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
3105 {
3106         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3107         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
3108         const unsigned int elts_n = rxq->elts_n;
3109         unsigned int elts_head = rxq->elts_head;
3110         struct ibv_sge sges[pkts_n];
3111         unsigned int i;
3112         unsigned int pkts_ret = 0;
3113         int ret;
3114
3115         if (unlikely(rxq->sp))
3116                 return mlx4_rx_burst_sp(dpdk_rxq, pkts, pkts_n);
3117         for (i = 0; (i != pkts_n); ++i) {
3118                 struct rxq_elt *elt = &(*elts)[elts_head];
3119                 struct ibv_recv_wr *wr = &elt->wr;
3120                 uint64_t wr_id = wr->wr_id;
3121                 unsigned int len;
3122                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
3123                         WR_ID(wr_id).offset);
3124                 struct rte_mbuf *rep;
3125                 uint32_t flags;
3126
3127                 /* Sanity checks. */
3128                 assert(WR_ID(wr_id).id < rxq->elts_n);
3129                 assert(wr->sg_list == &elt->sge);
3130                 assert(wr->num_sge == 1);
3131                 assert(elts_head < rxq->elts_n);
3132                 assert(rxq->elts_head < rxq->elts_n);
3133                 /*
3134                  * Fetch initial bytes of packet descriptor into a
3135                  * cacheline while allocating rep.
3136                  */
3137                 rte_mbuf_prefetch_part1(seg);
3138                 rte_mbuf_prefetch_part2(seg);
3139                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
3140                                                     &flags);
3141                 if (unlikely(ret < 0)) {
3142                         struct ibv_wc wc;
3143                         int wcs_n;
3144
3145                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
3146                               (void *)rxq, ret);
3147                         /* ibv_poll_cq() must be used in case of failure. */
3148                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
3149                         if (unlikely(wcs_n == 0))
3150                                 break;
3151                         if (unlikely(wcs_n < 0)) {
3152                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
3153                                       (void *)rxq, wcs_n);
3154                                 break;
3155                         }
3156                         assert(wcs_n == 1);
3157                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
3158                                 /* Whatever, just repost the offending WR. */
3159                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
3160                                       " completion status (%d): %s",
3161                                       (void *)rxq, wc.wr_id, wc.status,
3162                                       ibv_wc_status_str(wc.status));
3163 #ifdef MLX4_PMD_SOFT_COUNTERS
3164                                 /* Increment dropped packets counter. */
3165                                 ++rxq->stats.idropped;
3166 #endif
3167                                 /* Add SGE to array for repost. */
3168                                 sges[i] = elt->sge;
3169                                 goto repost;
3170                         }
3171                         ret = wc.byte_len;
3172                 }
3173                 if (ret == 0)
3174                         break;
3175                 len = ret;
3176                 rep = rte_mbuf_raw_alloc(rxq->mp);
3177                 if (unlikely(rep == NULL)) {
3178                         /*
3179                          * Unable to allocate a replacement mbuf,
3180                          * repost WR.
3181                          */
3182                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
3183                               " can't allocate a new mbuf",
3184                               (void *)rxq, WR_ID(wr_id).id);
3185                         /* Increase out of memory counters. */
3186                         ++rxq->stats.rx_nombuf;
3187                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
3188                         /* Add SGE to array for repost. */
3189                         sges[i] = elt->sge;
3190                         goto repost;
3191                 }
3192
3193                 /* Reconfigure sge to use rep instead of seg. */
3194                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
3195                 assert(elt->sge.lkey == rxq->mr->lkey);
3196                 WR_ID(wr->wr_id).offset =
3197                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
3198                          (uintptr_t)rep);
3199                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
3200
3201                 /* Add SGE to array for repost. */
3202                 sges[i] = elt->sge;
3203
3204                 /* Update seg information. */
3205                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
3206                 NB_SEGS(seg) = 1;
3207                 PORT(seg) = rxq->port_id;
3208                 NEXT(seg) = NULL;
3209                 PKT_LEN(seg) = len;
3210                 DATA_LEN(seg) = len;
3211                 seg->packet_type = rxq_cq_to_pkt_type(flags);
3212                 seg->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
3213
3214                 /* Return packet. */
3215                 *(pkts++) = seg;
3216                 ++pkts_ret;
3217 #ifdef MLX4_PMD_SOFT_COUNTERS
3218                 /* Increase bytes counter. */
3219                 rxq->stats.ibytes += len;
3220 #endif
3221 repost:
3222                 if (++elts_head >= elts_n)
3223                         elts_head = 0;
3224                 continue;
3225         }
3226         if (unlikely(i == 0))
3227                 return 0;
3228         /* Repost WRs. */
3229 #ifdef DEBUG_RECV
3230         DEBUG("%p: reposting %u WRs", (void *)rxq, i);
3231 #endif
3232         ret = rxq->if_qp->recv_burst(rxq->qp, sges, i);
3233         if (unlikely(ret)) {
3234                 /* Inability to repost WRs is fatal. */
3235                 DEBUG("%p: recv_burst(): failed (ret=%d)",
3236                       (void *)rxq->priv,
3237                       ret);
3238                 abort();
3239         }
3240         rxq->elts_head = elts_head;
3241 #ifdef MLX4_PMD_SOFT_COUNTERS
3242         /* Increase packets counter. */
3243         rxq->stats.ipackets += pkts_ret;
3244 #endif
3245         return pkts_ret;
3246 }
3247
3248 /**
3249  * DPDK callback for RX in secondary processes.
3250  *
3251  * This function configures all queues from primary process information
3252  * if necessary before reverting to the normal RX burst callback.
3253  *
3254  * @param dpdk_rxq
3255  *   Generic pointer to RX queue structure.
3256  * @param[out] pkts
3257  *   Array to store received packets.
3258  * @param pkts_n
3259  *   Maximum number of packets in array.
3260  *
3261  * @return
3262  *   Number of packets successfully received (<= pkts_n).
3263  */
3264 static uint16_t
3265 mlx4_rx_burst_secondary_setup(void *dpdk_rxq, struct rte_mbuf **pkts,
3266                               uint16_t pkts_n)
3267 {
3268         struct rxq *rxq = dpdk_rxq;
3269         struct priv *priv = mlx4_secondary_data_setup(rxq->priv);
3270         struct priv *primary_priv;
3271         unsigned int index;
3272
3273         if (priv == NULL)
3274                 return 0;
3275         primary_priv =
3276                 mlx4_secondary_data[priv->dev->data->port_id].primary_priv;
3277         /* Look for queue index in both private structures. */
3278         for (index = 0; index != priv->rxqs_n; ++index)
3279                 if (((*primary_priv->rxqs)[index] == rxq) ||
3280                     ((*priv->rxqs)[index] == rxq))
3281                         break;
3282         if (index == priv->rxqs_n)
3283                 return 0;
3284         rxq = (*priv->rxqs)[index];
3285         return priv->dev->rx_pkt_burst(rxq, pkts, pkts_n);
3286 }
3287
3288 /**
3289  * Allocate a Queue Pair.
3290  * Optionally setup inline receive if supported.
3291  *
3292  * @param priv
3293  *   Pointer to private structure.
3294  * @param cq
3295  *   Completion queue to associate with QP.
3296  * @param desc
3297  *   Number of descriptors in QP (hint only).
3298  *
3299  * @return
3300  *   QP pointer or NULL in case of error.
3301  */
3302 static struct ibv_qp *
3303 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
3304              struct ibv_exp_res_domain *rd)
3305 {
3306         struct ibv_exp_qp_init_attr attr = {
3307                 /* CQ to be associated with the send queue. */
3308                 .send_cq = cq,
3309                 /* CQ to be associated with the receive queue. */
3310                 .recv_cq = cq,
3311                 .cap = {
3312                         /* Max number of outstanding WRs. */
3313                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
3314                                         priv->device_attr.max_qp_wr :
3315                                         desc),
3316                         /* Max number of scatter/gather elements in a WR. */
3317                         .max_recv_sge = ((priv->device_attr.max_sge <
3318                                           MLX4_PMD_SGE_WR_N) ?
3319                                          priv->device_attr.max_sge :
3320                                          MLX4_PMD_SGE_WR_N),
3321                 },
3322                 .qp_type = IBV_QPT_RAW_PACKET,
3323                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
3324                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
3325                 .pd = priv->pd,
3326                 .res_domain = rd,
3327         };
3328
3329 #ifdef INLINE_RECV
3330         attr.max_inl_recv = priv->inl_recv_size;
3331         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3332 #endif
3333         return ibv_exp_create_qp(priv->ctx, &attr);
3334 }
3335
3336 #ifdef RSS_SUPPORT
3337
3338 /**
3339  * Allocate a RSS Queue Pair.
3340  * Optionally setup inline receive if supported.
3341  *
3342  * @param priv
3343  *   Pointer to private structure.
3344  * @param cq
3345  *   Completion queue to associate with QP.
3346  * @param desc
3347  *   Number of descriptors in QP (hint only).
3348  * @param parent
3349  *   If nonzero, create a parent QP, otherwise a child.
3350  *
3351  * @return
3352  *   QP pointer or NULL in case of error.
3353  */
3354 static struct ibv_qp *
3355 rxq_setup_qp_rss(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
3356                  int parent, struct ibv_exp_res_domain *rd)
3357 {
3358         struct ibv_exp_qp_init_attr attr = {
3359                 /* CQ to be associated with the send queue. */
3360                 .send_cq = cq,
3361                 /* CQ to be associated with the receive queue. */
3362                 .recv_cq = cq,
3363                 .cap = {
3364                         /* Max number of outstanding WRs. */
3365                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
3366                                         priv->device_attr.max_qp_wr :
3367                                         desc),
3368                         /* Max number of scatter/gather elements in a WR. */
3369                         .max_recv_sge = ((priv->device_attr.max_sge <
3370                                           MLX4_PMD_SGE_WR_N) ?
3371                                          priv->device_attr.max_sge :
3372                                          MLX4_PMD_SGE_WR_N),
3373                 },
3374                 .qp_type = IBV_QPT_RAW_PACKET,
3375                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
3376                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN |
3377                               IBV_EXP_QP_INIT_ATTR_QPG),
3378                 .pd = priv->pd,
3379                 .res_domain = rd,
3380         };
3381
3382 #ifdef INLINE_RECV
3383         attr.max_inl_recv = priv->inl_recv_size,
3384         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3385 #endif
3386         if (parent) {
3387                 attr.qpg.qpg_type = IBV_EXP_QPG_PARENT;
3388                 /* TSS isn't necessary. */
3389                 attr.qpg.parent_attrib.tss_child_count = 0;
3390                 attr.qpg.parent_attrib.rss_child_count =
3391                         rte_align32pow2(priv->rxqs_n + 1) >> 1;
3392                 DEBUG("initializing parent RSS queue");
3393         } else {
3394                 attr.qpg.qpg_type = IBV_EXP_QPG_CHILD_RX;
3395                 attr.qpg.qpg_parent = priv->rxq_parent.qp;
3396                 DEBUG("initializing child RSS queue");
3397         }
3398         return ibv_exp_create_qp(priv->ctx, &attr);
3399 }
3400
3401 #endif /* RSS_SUPPORT */
3402
3403 /**
3404  * Reconfigure a RX queue with new parameters.
3405  *
3406  * rxq_rehash() does not allocate mbufs, which, if not done from the right
3407  * thread (such as a control thread), may corrupt the pool.
3408  * In case of failure, the queue is left untouched.
3409  *
3410  * @param dev
3411  *   Pointer to Ethernet device structure.
3412  * @param rxq
3413  *   RX queue pointer.
3414  *
3415  * @return
3416  *   0 on success, errno value on failure.
3417  */
3418 static int
3419 rxq_rehash(struct rte_eth_dev *dev, struct rxq *rxq)
3420 {
3421         struct priv *priv = rxq->priv;
3422         struct rxq tmpl = *rxq;
3423         unsigned int mbuf_n;
3424         unsigned int desc_n;
3425         struct rte_mbuf **pool;
3426         unsigned int i, k;
3427         struct ibv_exp_qp_attr mod;
3428         struct ibv_recv_wr *bad_wr;
3429         unsigned int mb_len;
3430         int err;
3431         int parent = (rxq == &priv->rxq_parent);
3432
3433         if (parent) {
3434                 ERROR("%p: cannot rehash parent queue %p",
3435                       (void *)dev, (void *)rxq);
3436                 return EINVAL;
3437         }
3438         mb_len = rte_pktmbuf_data_room_size(rxq->mp);
3439         DEBUG("%p: rehashing queue %p", (void *)dev, (void *)rxq);
3440         /* Number of descriptors and mbufs currently allocated. */
3441         desc_n = (tmpl.elts_n * (tmpl.sp ? MLX4_PMD_SGE_WR_N : 1));
3442         mbuf_n = desc_n;
3443         /* Toggle RX checksum offload if hardware supports it. */
3444         if (priv->hw_csum) {
3445                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3446                 rxq->csum = tmpl.csum;
3447         }
3448         if (priv->hw_csum_l2tun) {
3449                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3450                 rxq->csum_l2tun = tmpl.csum_l2tun;
3451         }
3452         /* Enable scattered packets support for this queue if necessary. */
3453         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
3454         if (dev->data->dev_conf.rxmode.enable_scatter &&
3455             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3456              (mb_len - RTE_PKTMBUF_HEADROOM))) {
3457                 tmpl.sp = 1;
3458                 desc_n /= MLX4_PMD_SGE_WR_N;
3459         } else
3460                 tmpl.sp = 0;
3461         DEBUG("%p: %s scattered packets support (%u WRs)",
3462               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc_n);
3463         /* If scatter mode is the same as before, nothing to do. */
3464         if (tmpl.sp == rxq->sp) {
3465                 DEBUG("%p: nothing to do", (void *)dev);
3466                 return 0;
3467         }
3468         /* Remove attached flows if RSS is disabled (no parent queue). */
3469         if (!priv->rss) {
3470                 rxq_allmulticast_disable(&tmpl);
3471                 rxq_promiscuous_disable(&tmpl);
3472                 rxq_mac_addrs_del(&tmpl);
3473                 /* Update original queue in case of failure. */
3474                 rxq->allmulti_flow = tmpl.allmulti_flow;
3475                 rxq->promisc_flow = tmpl.promisc_flow;
3476                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3477                        sizeof(rxq->mac_configured));
3478                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3479         }
3480         /* From now on, any failure will render the queue unusable.
3481          * Reinitialize QP. */
3482         mod = (struct ibv_exp_qp_attr){ .qp_state = IBV_QPS_RESET };
3483         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3484         if (err) {
3485                 ERROR("%p: cannot reset QP: %s", (void *)dev, strerror(err));
3486                 assert(err > 0);
3487                 return err;
3488         }
3489         err = ibv_resize_cq(tmpl.cq, desc_n);
3490         if (err) {
3491                 ERROR("%p: cannot resize CQ: %s", (void *)dev, strerror(err));
3492                 assert(err > 0);
3493                 return err;
3494         }
3495         mod = (struct ibv_exp_qp_attr){
3496                 /* Move the QP to this state. */
3497                 .qp_state = IBV_QPS_INIT,
3498                 /* Primary port number. */
3499                 .port_num = priv->port
3500         };
3501         err = ibv_exp_modify_qp(tmpl.qp, &mod,
3502                                 (IBV_EXP_QP_STATE |
3503 #ifdef RSS_SUPPORT
3504                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3505 #endif /* RSS_SUPPORT */
3506                                  IBV_EXP_QP_PORT));
3507         if (err) {
3508                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3509                       (void *)dev, strerror(err));
3510                 assert(err > 0);
3511                 return err;
3512         };
3513         /* Reconfigure flows. Do not care for errors. */
3514         if (!priv->rss) {
3515                 rxq_mac_addrs_add(&tmpl);
3516                 if (priv->promisc)
3517                         rxq_promiscuous_enable(&tmpl);
3518                 if (priv->allmulti)
3519                         rxq_allmulticast_enable(&tmpl);
3520                 /* Update original queue in case of failure. */
3521                 rxq->allmulti_flow = tmpl.allmulti_flow;
3522                 rxq->promisc_flow = tmpl.promisc_flow;
3523                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3524                        sizeof(rxq->mac_configured));
3525                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3526         }
3527         /* Allocate pool. */
3528         pool = rte_malloc(__func__, (mbuf_n * sizeof(*pool)), 0);
3529         if (pool == NULL) {
3530                 ERROR("%p: cannot allocate memory", (void *)dev);
3531                 return ENOBUFS;
3532         }
3533         /* Snatch mbufs from original queue. */
3534         k = 0;
3535         if (rxq->sp) {
3536                 struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
3537
3538                 for (i = 0; (i != elemof(*elts)); ++i) {
3539                         struct rxq_elt_sp *elt = &(*elts)[i];
3540                         unsigned int j;
3541
3542                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
3543                                 assert(elt->bufs[j] != NULL);
3544                                 pool[k++] = elt->bufs[j];
3545                         }
3546                 }
3547         } else {
3548                 struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
3549
3550                 for (i = 0; (i != elemof(*elts)); ++i) {
3551                         struct rxq_elt *elt = &(*elts)[i];
3552                         struct rte_mbuf *buf = (void *)
3553                                 ((uintptr_t)elt->sge.addr -
3554                                  WR_ID(elt->wr.wr_id).offset);
3555
3556                         assert(WR_ID(elt->wr.wr_id).id == i);
3557                         pool[k++] = buf;
3558                 }
3559         }
3560         assert(k == mbuf_n);
3561         tmpl.elts_n = 0;
3562         tmpl.elts.sp = NULL;
3563         assert((void *)&tmpl.elts.sp == (void *)&tmpl.elts.no_sp);
3564         err = ((tmpl.sp) ?
3565                rxq_alloc_elts_sp(&tmpl, desc_n, pool) :
3566                rxq_alloc_elts(&tmpl, desc_n, pool));
3567         if (err) {
3568                 ERROR("%p: cannot reallocate WRs, aborting", (void *)dev);
3569                 rte_free(pool);
3570                 assert(err > 0);
3571                 return err;
3572         }
3573         assert(tmpl.elts_n == desc_n);
3574         assert(tmpl.elts.sp != NULL);
3575         rte_free(pool);
3576         /* Clean up original data. */
3577         rxq->elts_n = 0;
3578         rte_free(rxq->elts.sp);
3579         rxq->elts.sp = NULL;
3580         /* Post WRs. */
3581         err = ibv_post_recv(tmpl.qp,
3582                             (tmpl.sp ?
3583                              &(*tmpl.elts.sp)[0].wr :
3584                              &(*tmpl.elts.no_sp)[0].wr),
3585                             &bad_wr);
3586         if (err) {
3587                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3588                       (void *)dev,
3589                       (void *)bad_wr,
3590                       strerror(err));
3591                 goto skip_rtr;
3592         }
3593         mod = (struct ibv_exp_qp_attr){
3594                 .qp_state = IBV_QPS_RTR
3595         };
3596         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3597         if (err)
3598                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3599                       (void *)dev, strerror(err));
3600 skip_rtr:
3601         *rxq = tmpl;
3602         assert(err >= 0);
3603         return err;
3604 }
3605
3606 /**
3607  * Configure a RX queue.
3608  *
3609  * @param dev
3610  *   Pointer to Ethernet device structure.
3611  * @param rxq
3612  *   Pointer to RX queue structure.
3613  * @param desc
3614  *   Number of descriptors to configure in queue.
3615  * @param socket
3616  *   NUMA socket on which memory must be allocated.
3617  * @param inactive
3618  *   If true, the queue is disabled because its index is higher or
3619  *   equal to the real number of queues, which must be a power of 2.
3620  * @param[in] conf
3621  *   Thresholds parameters.
3622  * @param mp
3623  *   Memory pool for buffer allocations.
3624  *
3625  * @return
3626  *   0 on success, errno value on failure.
3627  */
3628 static int
3629 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
3630           unsigned int socket, int inactive, const struct rte_eth_rxconf *conf,
3631           struct rte_mempool *mp)
3632 {
3633         struct priv *priv = dev->data->dev_private;
3634         struct rxq tmpl = {
3635                 .priv = priv,
3636                 .mp = mp,
3637                 .socket = socket
3638         };
3639         struct ibv_exp_qp_attr mod;
3640         union {
3641                 struct ibv_exp_query_intf_params params;
3642                 struct ibv_exp_cq_init_attr cq;
3643                 struct ibv_exp_res_domain_init_attr rd;
3644         } attr;
3645         enum ibv_exp_query_intf_status status;
3646         struct ibv_recv_wr *bad_wr;
3647         unsigned int mb_len;
3648         int ret = 0;
3649         int parent = (rxq == &priv->rxq_parent);
3650
3651         (void)conf; /* Thresholds configuration (ignored). */
3652         /*
3653          * If this is a parent queue, hardware must support RSS and
3654          * RSS must be enabled.
3655          */
3656         assert((!parent) || ((priv->hw_rss) && (priv->rss)));
3657         if (parent) {
3658                 /* Even if unused, ibv_create_cq() requires at least one
3659                  * descriptor. */
3660                 desc = 1;
3661                 goto skip_mr;
3662         }
3663         mb_len = rte_pktmbuf_data_room_size(mp);
3664         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
3665                 ERROR("%p: invalid number of RX descriptors (must be a"
3666                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
3667                 return EINVAL;
3668         }
3669         /* Toggle RX checksum offload if hardware supports it. */
3670         if (priv->hw_csum)
3671                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3672         if (priv->hw_csum_l2tun)
3673                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3674         /* Enable scattered packets support for this queue if necessary. */
3675         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
3676         if (dev->data->dev_conf.rxmode.max_rx_pkt_len <=
3677             (mb_len - RTE_PKTMBUF_HEADROOM)) {
3678                 tmpl.sp = 0;
3679         } else if (dev->data->dev_conf.rxmode.enable_scatter) {
3680                 tmpl.sp = 1;
3681                 desc /= MLX4_PMD_SGE_WR_N;
3682         } else {
3683                 WARN("%p: the requested maximum Rx packet size (%u) is"
3684                      " larger than a single mbuf (%u) and scattered"
3685                      " mode has not been requested",
3686                      (void *)dev,
3687                      dev->data->dev_conf.rxmode.max_rx_pkt_len,
3688                      mb_len - RTE_PKTMBUF_HEADROOM);
3689         }
3690         DEBUG("%p: %s scattered packets support (%u WRs)",
3691               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
3692         /* Use the entire RX mempool as the memory region. */
3693         tmpl.mr = mlx4_mp2mr(priv->pd, mp);
3694         if (tmpl.mr == NULL) {
3695                 ret = EINVAL;
3696                 ERROR("%p: MR creation failure: %s",
3697                       (void *)dev, strerror(ret));
3698                 goto error;
3699         }
3700 skip_mr:
3701         attr.rd = (struct ibv_exp_res_domain_init_attr){
3702                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
3703                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
3704                 .thread_model = IBV_EXP_THREAD_SINGLE,
3705                 .msg_model = IBV_EXP_MSG_HIGH_BW,
3706         };
3707         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
3708         if (tmpl.rd == NULL) {
3709                 ret = ENOMEM;
3710                 ERROR("%p: RD creation failure: %s",
3711                       (void *)dev, strerror(ret));
3712                 goto error;
3713         }
3714         if (dev->data->dev_conf.intr_conf.rxq) {
3715                 tmpl.channel = ibv_create_comp_channel(priv->ctx);
3716                 if (tmpl.channel == NULL) {
3717                         ret = ENOMEM;
3718                         ERROR("%p: Rx interrupt completion channel creation"
3719                               " failure: %s",
3720                               (void *)dev, strerror(ret));
3721                         goto error;
3722                 }
3723         }
3724         attr.cq = (struct ibv_exp_cq_init_attr){
3725                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
3726                 .res_domain = tmpl.rd,
3727         };
3728         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, tmpl.channel, 0,
3729                                     &attr.cq);
3730         if (tmpl.cq == NULL) {
3731                 ret = ENOMEM;
3732                 ERROR("%p: CQ creation failure: %s",
3733                       (void *)dev, strerror(ret));
3734                 goto error;
3735         }
3736         DEBUG("priv->device_attr.max_qp_wr is %d",
3737               priv->device_attr.max_qp_wr);
3738         DEBUG("priv->device_attr.max_sge is %d",
3739               priv->device_attr.max_sge);
3740 #ifdef RSS_SUPPORT
3741         if (priv->rss && !inactive)
3742                 tmpl.qp = rxq_setup_qp_rss(priv, tmpl.cq, desc, parent,
3743                                            tmpl.rd);
3744         else
3745 #endif /* RSS_SUPPORT */
3746                 tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc, tmpl.rd);
3747         if (tmpl.qp == NULL) {
3748                 ret = (errno ? errno : EINVAL);
3749                 ERROR("%p: QP creation failure: %s",
3750                       (void *)dev, strerror(ret));
3751                 goto error;
3752         }
3753         mod = (struct ibv_exp_qp_attr){
3754                 /* Move the QP to this state. */
3755                 .qp_state = IBV_QPS_INIT,
3756                 /* Primary port number. */
3757                 .port_num = priv->port
3758         };
3759         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
3760                                 (IBV_EXP_QP_STATE |
3761 #ifdef RSS_SUPPORT
3762                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3763 #endif /* RSS_SUPPORT */
3764                                  IBV_EXP_QP_PORT));
3765         if (ret) {
3766                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3767                       (void *)dev, strerror(ret));
3768                 goto error;
3769         }
3770         if ((parent) || (!priv->rss))  {
3771                 /* Configure MAC and broadcast addresses. */
3772                 ret = rxq_mac_addrs_add(&tmpl);
3773                 if (ret) {
3774                         ERROR("%p: QP flow attachment failed: %s",
3775                               (void *)dev, strerror(ret));
3776                         goto error;
3777                 }
3778         }
3779         /* Allocate descriptors for RX queues, except for the RSS parent. */
3780         if (parent)
3781                 goto skip_alloc;
3782         if (tmpl.sp)
3783                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
3784         else
3785                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
3786         if (ret) {
3787                 ERROR("%p: RXQ allocation failed: %s",
3788                       (void *)dev, strerror(ret));
3789                 goto error;
3790         }
3791         ret = ibv_post_recv(tmpl.qp,
3792                             (tmpl.sp ?
3793                              &(*tmpl.elts.sp)[0].wr :
3794                              &(*tmpl.elts.no_sp)[0].wr),
3795                             &bad_wr);
3796         if (ret) {
3797                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3798                       (void *)dev,
3799                       (void *)bad_wr,
3800                       strerror(ret));
3801                 goto error;
3802         }
3803 skip_alloc:
3804         mod = (struct ibv_exp_qp_attr){
3805                 .qp_state = IBV_QPS_RTR
3806         };
3807         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3808         if (ret) {
3809                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3810                       (void *)dev, strerror(ret));
3811                 goto error;
3812         }
3813         /* Save port ID. */
3814         tmpl.port_id = dev->data->port_id;
3815         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
3816         attr.params = (struct ibv_exp_query_intf_params){
3817                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3818                 .intf = IBV_EXP_INTF_CQ,
3819                 .obj = tmpl.cq,
3820         };
3821         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3822         if (tmpl.if_cq == NULL) {
3823                 ERROR("%p: CQ interface family query failed with status %d",
3824                       (void *)dev, status);
3825                 goto error;
3826         }
3827         attr.params = (struct ibv_exp_query_intf_params){
3828                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3829                 .intf = IBV_EXP_INTF_QP_BURST,
3830                 .obj = tmpl.qp,
3831         };
3832         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3833         if (tmpl.if_qp == NULL) {
3834                 ERROR("%p: QP interface family query failed with status %d",
3835                       (void *)dev, status);
3836                 goto error;
3837         }
3838         /* Clean up rxq in case we're reinitializing it. */
3839         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
3840         rxq_cleanup(rxq);
3841         *rxq = tmpl;
3842         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
3843         assert(ret == 0);
3844         return 0;
3845 error:
3846         rxq_cleanup(&tmpl);
3847         assert(ret > 0);
3848         return ret;
3849 }
3850
3851 /**
3852  * DPDK callback to configure a RX queue.
3853  *
3854  * @param dev
3855  *   Pointer to Ethernet device structure.
3856  * @param idx
3857  *   RX queue index.
3858  * @param desc
3859  *   Number of descriptors to configure in queue.
3860  * @param socket
3861  *   NUMA socket on which memory must be allocated.
3862  * @param[in] conf
3863  *   Thresholds parameters.
3864  * @param mp
3865  *   Memory pool for buffer allocations.
3866  *
3867  * @return
3868  *   0 on success, negative errno value on failure.
3869  */
3870 static int
3871 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
3872                     unsigned int socket, const struct rte_eth_rxconf *conf,
3873                     struct rte_mempool *mp)
3874 {
3875         struct priv *priv = dev->data->dev_private;
3876         struct rxq *rxq = (*priv->rxqs)[idx];
3877         int inactive = 0;
3878         int ret;
3879
3880         if (mlx4_is_secondary())
3881                 return -E_RTE_SECONDARY;
3882         priv_lock(priv);
3883         DEBUG("%p: configuring queue %u for %u descriptors",
3884               (void *)dev, idx, desc);
3885         if (idx >= priv->rxqs_n) {
3886                 ERROR("%p: queue index out of range (%u >= %u)",
3887                       (void *)dev, idx, priv->rxqs_n);
3888                 priv_unlock(priv);
3889                 return -EOVERFLOW;
3890         }
3891         if (rxq != NULL) {
3892                 DEBUG("%p: reusing already allocated queue index %u (%p)",
3893                       (void *)dev, idx, (void *)rxq);
3894                 if (priv->started) {
3895                         priv_unlock(priv);
3896                         return -EEXIST;
3897                 }
3898                 (*priv->rxqs)[idx] = NULL;
3899                 rxq_cleanup(rxq);
3900         } else {
3901                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
3902                 if (rxq == NULL) {
3903                         ERROR("%p: unable to allocate queue index %u",
3904                               (void *)dev, idx);
3905                         priv_unlock(priv);
3906                         return -ENOMEM;
3907                 }
3908         }
3909         if (idx >= rte_align32pow2(priv->rxqs_n + 1) >> 1)
3910                 inactive = 1;
3911         ret = rxq_setup(dev, rxq, desc, socket, inactive, conf, mp);
3912         if (ret)
3913                 rte_free(rxq);
3914         else {
3915                 rxq->stats.idx = idx;
3916                 DEBUG("%p: adding RX queue %p to list",
3917                       (void *)dev, (void *)rxq);
3918                 (*priv->rxqs)[idx] = rxq;
3919                 /* Update receive callback. */
3920                 if (rxq->sp)
3921                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3922                 else
3923                         dev->rx_pkt_burst = mlx4_rx_burst;
3924         }
3925         priv_unlock(priv);
3926         return -ret;
3927 }
3928
3929 /**
3930  * DPDK callback to release a RX queue.
3931  *
3932  * @param dpdk_rxq
3933  *   Generic RX queue pointer.
3934  */
3935 static void
3936 mlx4_rx_queue_release(void *dpdk_rxq)
3937 {
3938         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3939         struct priv *priv;
3940         unsigned int i;
3941
3942         if (mlx4_is_secondary())
3943                 return;
3944         if (rxq == NULL)
3945                 return;
3946         priv = rxq->priv;
3947         priv_lock(priv);
3948         assert(rxq != &priv->rxq_parent);
3949         for (i = 0; (i != priv->rxqs_n); ++i)
3950                 if ((*priv->rxqs)[i] == rxq) {
3951                         DEBUG("%p: removing RX queue %p from list",
3952                               (void *)priv->dev, (void *)rxq);
3953                         (*priv->rxqs)[i] = NULL;
3954                         break;
3955                 }
3956         rxq_cleanup(rxq);
3957         rte_free(rxq);
3958         priv_unlock(priv);
3959 }
3960
3961 static int
3962 priv_dev_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
3963
3964 static int
3965 priv_dev_removal_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
3966
3967 static int
3968 priv_dev_link_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
3969
3970 /**
3971  * DPDK callback to start the device.
3972  *
3973  * Simulate device start by attaching all configured flows.
3974  *
3975  * @param dev
3976  *   Pointer to Ethernet device structure.
3977  *
3978  * @return
3979  *   0 on success, negative errno value on failure.
3980  */
3981 static int
3982 mlx4_dev_start(struct rte_eth_dev *dev)
3983 {
3984         struct priv *priv = dev->data->dev_private;
3985         unsigned int i = 0;
3986         unsigned int r;
3987         struct rxq *rxq;
3988         int ret;
3989
3990         if (mlx4_is_secondary())
3991                 return -E_RTE_SECONDARY;
3992         priv_lock(priv);
3993         if (priv->started) {
3994                 priv_unlock(priv);
3995                 return 0;
3996         }
3997         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
3998         priv->started = 1;
3999         if (priv->rss) {
4000                 rxq = &priv->rxq_parent;
4001                 r = 1;
4002         } else {
4003                 rxq = (*priv->rxqs)[0];
4004                 r = priv->rxqs_n;
4005         }
4006         /* Iterate only once when RSS is enabled. */
4007         do {
4008                 /* Ignore nonexistent RX queues. */
4009                 if (rxq == NULL)
4010                         continue;
4011                 ret = rxq_mac_addrs_add(rxq);
4012                 if (!ret && priv->promisc)
4013                         ret = rxq_promiscuous_enable(rxq);
4014                 if (!ret && priv->allmulti)
4015                         ret = rxq_allmulticast_enable(rxq);
4016                 if (!ret)
4017                         continue;
4018                 WARN("%p: QP flow attachment failed: %s",
4019                      (void *)dev, strerror(ret));
4020                 goto err;
4021         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
4022         ret = priv_dev_link_interrupt_handler_install(priv, dev);
4023         if (ret) {
4024                 ERROR("%p: LSC handler install failed",
4025                      (void *)dev);
4026                 goto err;
4027         }
4028         ret = priv_dev_removal_interrupt_handler_install(priv, dev);
4029         if (ret) {
4030                 ERROR("%p: RMV handler install failed",
4031                      (void *)dev);
4032                 goto err;
4033         }
4034         ret = priv_rx_intr_vec_enable(priv);
4035         if (ret) {
4036                 ERROR("%p: Rx interrupt vector creation failed",
4037                       (void *)dev);
4038                 goto err;
4039         }
4040         ret = mlx4_priv_flow_start(priv);
4041         if (ret) {
4042                 ERROR("%p: flow start failed: %s",
4043                       (void *)dev, strerror(ret));
4044                 goto err;
4045         }
4046         priv_unlock(priv);
4047         return 0;
4048 err:
4049         /* Rollback. */
4050         while (i != 0) {
4051                 rxq = (*priv->rxqs)[i--];
4052                 if (rxq != NULL) {
4053                         rxq_allmulticast_disable(rxq);
4054                         rxq_promiscuous_disable(rxq);
4055                         rxq_mac_addrs_del(rxq);
4056                 }
4057         }
4058         priv->started = 0;
4059         priv_unlock(priv);
4060         return -ret;
4061 }
4062
4063 /**
4064  * DPDK callback to stop the device.
4065  *
4066  * Simulate device stop by detaching all configured flows.
4067  *
4068  * @param dev
4069  *   Pointer to Ethernet device structure.
4070  */
4071 static void
4072 mlx4_dev_stop(struct rte_eth_dev *dev)
4073 {
4074         struct priv *priv = dev->data->dev_private;
4075         unsigned int i = 0;
4076         unsigned int r;
4077         struct rxq *rxq;
4078
4079         if (mlx4_is_secondary())
4080                 return;
4081         priv_lock(priv);
4082         if (!priv->started) {
4083                 priv_unlock(priv);
4084                 return;
4085         }
4086         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
4087         priv->started = 0;
4088         if (priv->rss) {
4089                 rxq = &priv->rxq_parent;
4090                 r = 1;
4091         } else {
4092                 rxq = (*priv->rxqs)[0];
4093                 r = priv->rxqs_n;
4094         }
4095         mlx4_priv_flow_stop(priv);
4096         /* Iterate only once when RSS is enabled. */
4097         do {
4098                 /* Ignore nonexistent RX queues. */
4099                 if (rxq == NULL)
4100                         continue;
4101                 rxq_allmulticast_disable(rxq);
4102                 rxq_promiscuous_disable(rxq);
4103                 rxq_mac_addrs_del(rxq);
4104         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
4105         priv_unlock(priv);
4106 }
4107
4108 /**
4109  * Dummy DPDK callback for TX.
4110  *
4111  * This function is used to temporarily replace the real callback during
4112  * unsafe control operations on the queue, or in case of error.
4113  *
4114  * @param dpdk_txq
4115  *   Generic pointer to TX queue structure.
4116  * @param[in] pkts
4117  *   Packets to transmit.
4118  * @param pkts_n
4119  *   Number of packets in array.
4120  *
4121  * @return
4122  *   Number of packets successfully transmitted (<= pkts_n).
4123  */
4124 static uint16_t
4125 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
4126 {
4127         (void)dpdk_txq;
4128         (void)pkts;
4129         (void)pkts_n;
4130         return 0;
4131 }
4132
4133 /**
4134  * Dummy DPDK callback for RX.
4135  *
4136  * This function is used to temporarily replace the real callback during
4137  * unsafe control operations on the queue, or in case of error.
4138  *
4139  * @param dpdk_rxq
4140  *   Generic pointer to RX queue structure.
4141  * @param[out] pkts
4142  *   Array to store received packets.
4143  * @param pkts_n
4144  *   Maximum number of packets in array.
4145  *
4146  * @return
4147  *   Number of packets successfully received (<= pkts_n).
4148  */
4149 static uint16_t
4150 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
4151 {
4152         (void)dpdk_rxq;
4153         (void)pkts;
4154         (void)pkts_n;
4155         return 0;
4156 }
4157
4158 static int
4159 priv_dev_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
4160
4161 static int
4162 priv_dev_removal_interrupt_handler_uninstall(struct priv *,
4163                                              struct rte_eth_dev *);
4164
4165 static int
4166 priv_dev_link_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
4167
4168 /**
4169  * DPDK callback to close the device.
4170  *
4171  * Destroy all queues and objects, free memory.
4172  *
4173  * @param dev
4174  *   Pointer to Ethernet device structure.
4175  */
4176 static void
4177 mlx4_dev_close(struct rte_eth_dev *dev)
4178 {
4179         struct priv *priv = mlx4_get_priv(dev);
4180         void *tmp;
4181         unsigned int i;
4182
4183         if (priv == NULL)
4184                 return;
4185         priv_lock(priv);
4186         DEBUG("%p: closing device \"%s\"",
4187               (void *)dev,
4188               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
4189         /* Prevent crashes when queues are still in use. This is unfortunately
4190          * still required for DPDK 1.3 because some programs (such as testpmd)
4191          * never release them before closing the device. */
4192         dev->rx_pkt_burst = removed_rx_burst;
4193         dev->tx_pkt_burst = removed_tx_burst;
4194         if (priv->rxqs != NULL) {
4195                 /* XXX race condition if mlx4_rx_burst() is still running. */
4196                 usleep(1000);
4197                 for (i = 0; (i != priv->rxqs_n); ++i) {
4198                         tmp = (*priv->rxqs)[i];
4199                         if (tmp == NULL)
4200                                 continue;
4201                         (*priv->rxqs)[i] = NULL;
4202                         rxq_cleanup(tmp);
4203                         rte_free(tmp);
4204                 }
4205                 priv->rxqs_n = 0;
4206                 priv->rxqs = NULL;
4207         }
4208         if (priv->txqs != NULL) {
4209                 /* XXX race condition if mlx4_tx_burst() is still running. */
4210                 usleep(1000);
4211                 for (i = 0; (i != priv->txqs_n); ++i) {
4212                         tmp = (*priv->txqs)[i];
4213                         if (tmp == NULL)
4214                                 continue;
4215                         (*priv->txqs)[i] = NULL;
4216                         txq_cleanup(tmp);
4217                         rte_free(tmp);
4218                 }
4219                 priv->txqs_n = 0;
4220                 priv->txqs = NULL;
4221         }
4222         if (priv->rss)
4223                 rxq_cleanup(&priv->rxq_parent);
4224         if (priv->pd != NULL) {
4225                 assert(priv->ctx != NULL);
4226                 claim_zero(ibv_dealloc_pd(priv->pd));
4227                 claim_zero(ibv_close_device(priv->ctx));
4228         } else
4229                 assert(priv->ctx == NULL);
4230         priv_dev_removal_interrupt_handler_uninstall(priv, dev);
4231         priv_dev_link_interrupt_handler_uninstall(priv, dev);
4232         priv_rx_intr_vec_disable(priv);
4233         priv_unlock(priv);
4234         memset(priv, 0, sizeof(*priv));
4235 }
4236
4237 /**
4238  * Change the link state (UP / DOWN).
4239  *
4240  * @param priv
4241  *   Pointer to Ethernet device private data.
4242  * @param up
4243  *   Nonzero for link up, otherwise link down.
4244  *
4245  * @return
4246  *   0 on success, errno value on failure.
4247  */
4248 static int
4249 priv_set_link(struct priv *priv, int up)
4250 {
4251         struct rte_eth_dev *dev = priv->dev;
4252         int err;
4253         unsigned int i;
4254
4255         if (up) {
4256                 err = priv_set_flags(priv, ~IFF_UP, IFF_UP);
4257                 if (err)
4258                         return err;
4259                 for (i = 0; i < priv->rxqs_n; i++)
4260                         if ((*priv->rxqs)[i]->sp)
4261                                 break;
4262                 /* Check if an sp queue exists.
4263                  * Note: Some old frames might be received.
4264                  */
4265                 if (i == priv->rxqs_n)
4266                         dev->rx_pkt_burst = mlx4_rx_burst;
4267                 else
4268                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
4269                 dev->tx_pkt_burst = mlx4_tx_burst;
4270         } else {
4271                 err = priv_set_flags(priv, ~IFF_UP, ~IFF_UP);
4272                 if (err)
4273                         return err;
4274                 dev->rx_pkt_burst = removed_rx_burst;
4275                 dev->tx_pkt_burst = removed_tx_burst;
4276         }
4277         return 0;
4278 }
4279
4280 /**
4281  * DPDK callback to bring the link DOWN.
4282  *
4283  * @param dev
4284  *   Pointer to Ethernet device structure.
4285  *
4286  * @return
4287  *   0 on success, errno value on failure.
4288  */
4289 static int
4290 mlx4_set_link_down(struct rte_eth_dev *dev)
4291 {
4292         struct priv *priv = dev->data->dev_private;
4293         int err;
4294
4295         priv_lock(priv);
4296         err = priv_set_link(priv, 0);
4297         priv_unlock(priv);
4298         return err;
4299 }
4300
4301 /**
4302  * DPDK callback to bring the link UP.
4303  *
4304  * @param dev
4305  *   Pointer to Ethernet device structure.
4306  *
4307  * @return
4308  *   0 on success, errno value on failure.
4309  */
4310 static int
4311 mlx4_set_link_up(struct rte_eth_dev *dev)
4312 {
4313         struct priv *priv = dev->data->dev_private;
4314         int err;
4315
4316         priv_lock(priv);
4317         err = priv_set_link(priv, 1);
4318         priv_unlock(priv);
4319         return err;
4320 }
4321 /**
4322  * DPDK callback to get information about the device.
4323  *
4324  * @param dev
4325  *   Pointer to Ethernet device structure.
4326  * @param[out] info
4327  *   Info structure output buffer.
4328  */
4329 static void
4330 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
4331 {
4332         struct priv *priv = mlx4_get_priv(dev);
4333         unsigned int max;
4334         char ifname[IF_NAMESIZE];
4335
4336         info->pci_dev = RTE_ETH_DEV_TO_PCI(dev);
4337
4338         if (priv == NULL)
4339                 return;
4340         priv_lock(priv);
4341         /* FIXME: we should ask the device for these values. */
4342         info->min_rx_bufsize = 32;
4343         info->max_rx_pktlen = 65536;
4344         /*
4345          * Since we need one CQ per QP, the limit is the minimum number
4346          * between the two values.
4347          */
4348         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
4349                priv->device_attr.max_qp : priv->device_attr.max_cq);
4350         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
4351         if (max >= 65535)
4352                 max = 65535;
4353         info->max_rx_queues = max;
4354         info->max_tx_queues = max;
4355         /* Last array entry is reserved for broadcast. */
4356         info->max_mac_addrs = (elemof(priv->mac) - 1);
4357         info->rx_offload_capa =
4358                 (priv->hw_csum ?
4359                  (DEV_RX_OFFLOAD_IPV4_CKSUM |
4360                   DEV_RX_OFFLOAD_UDP_CKSUM |
4361                   DEV_RX_OFFLOAD_TCP_CKSUM) :
4362                  0);
4363         info->tx_offload_capa =
4364                 (priv->hw_csum ?
4365                  (DEV_TX_OFFLOAD_IPV4_CKSUM |
4366                   DEV_TX_OFFLOAD_UDP_CKSUM |
4367                   DEV_TX_OFFLOAD_TCP_CKSUM) :
4368                  0);
4369         if (priv_get_ifname(priv, &ifname) == 0)
4370                 info->if_index = if_nametoindex(ifname);
4371         info->speed_capa =
4372                         ETH_LINK_SPEED_1G |
4373                         ETH_LINK_SPEED_10G |
4374                         ETH_LINK_SPEED_20G |
4375                         ETH_LINK_SPEED_40G |
4376                         ETH_LINK_SPEED_56G;
4377         priv_unlock(priv);
4378 }
4379
4380 static const uint32_t *
4381 mlx4_dev_supported_ptypes_get(struct rte_eth_dev *dev)
4382 {
4383         static const uint32_t ptypes[] = {
4384                 /* refers to rxq_cq_to_pkt_type() */
4385                 RTE_PTYPE_L3_IPV4,
4386                 RTE_PTYPE_L3_IPV6,
4387                 RTE_PTYPE_INNER_L3_IPV4,
4388                 RTE_PTYPE_INNER_L3_IPV6,
4389                 RTE_PTYPE_UNKNOWN
4390         };
4391
4392         if (dev->rx_pkt_burst == mlx4_rx_burst ||
4393             dev->rx_pkt_burst == mlx4_rx_burst_sp)
4394                 return ptypes;
4395         return NULL;
4396 }
4397
4398 /**
4399  * DPDK callback to get device statistics.
4400  *
4401  * @param dev
4402  *   Pointer to Ethernet device structure.
4403  * @param[out] stats
4404  *   Stats structure output buffer.
4405  */
4406 static void
4407 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
4408 {
4409         struct priv *priv = mlx4_get_priv(dev);
4410         struct rte_eth_stats tmp = {0};
4411         unsigned int i;
4412         unsigned int idx;
4413
4414         if (priv == NULL)
4415                 return;
4416         priv_lock(priv);
4417         /* Add software counters. */
4418         for (i = 0; (i != priv->rxqs_n); ++i) {
4419                 struct rxq *rxq = (*priv->rxqs)[i];
4420
4421                 if (rxq == NULL)
4422                         continue;
4423                 idx = rxq->stats.idx;
4424                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
4425 #ifdef MLX4_PMD_SOFT_COUNTERS
4426                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
4427                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
4428 #endif
4429                         tmp.q_errors[idx] += (rxq->stats.idropped +
4430                                               rxq->stats.rx_nombuf);
4431                 }
4432 #ifdef MLX4_PMD_SOFT_COUNTERS
4433                 tmp.ipackets += rxq->stats.ipackets;
4434                 tmp.ibytes += rxq->stats.ibytes;
4435 #endif
4436                 tmp.ierrors += rxq->stats.idropped;
4437                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
4438         }
4439         for (i = 0; (i != priv->txqs_n); ++i) {
4440                 struct txq *txq = (*priv->txqs)[i];
4441
4442                 if (txq == NULL)
4443                         continue;
4444                 idx = txq->stats.idx;
4445                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
4446 #ifdef MLX4_PMD_SOFT_COUNTERS
4447                         tmp.q_opackets[idx] += txq->stats.opackets;
4448                         tmp.q_obytes[idx] += txq->stats.obytes;
4449 #endif
4450                         tmp.q_errors[idx] += txq->stats.odropped;
4451                 }
4452 #ifdef MLX4_PMD_SOFT_COUNTERS
4453                 tmp.opackets += txq->stats.opackets;
4454                 tmp.obytes += txq->stats.obytes;
4455 #endif
4456                 tmp.oerrors += txq->stats.odropped;
4457         }
4458 #ifndef MLX4_PMD_SOFT_COUNTERS
4459         /* FIXME: retrieve and add hardware counters. */
4460 #endif
4461         *stats = tmp;
4462         priv_unlock(priv);
4463 }
4464
4465 /**
4466  * DPDK callback to clear device statistics.
4467  *
4468  * @param dev
4469  *   Pointer to Ethernet device structure.
4470  */
4471 static void
4472 mlx4_stats_reset(struct rte_eth_dev *dev)
4473 {
4474         struct priv *priv = mlx4_get_priv(dev);
4475         unsigned int i;
4476         unsigned int idx;
4477
4478         if (priv == NULL)
4479                 return;
4480         priv_lock(priv);
4481         for (i = 0; (i != priv->rxqs_n); ++i) {
4482                 if ((*priv->rxqs)[i] == NULL)
4483                         continue;
4484                 idx = (*priv->rxqs)[i]->stats.idx;
4485                 (*priv->rxqs)[i]->stats =
4486                         (struct mlx4_rxq_stats){ .idx = idx };
4487         }
4488         for (i = 0; (i != priv->txqs_n); ++i) {
4489                 if ((*priv->txqs)[i] == NULL)
4490                         continue;
4491                 idx = (*priv->txqs)[i]->stats.idx;
4492                 (*priv->txqs)[i]->stats =
4493                         (struct mlx4_txq_stats){ .idx = idx };
4494         }
4495 #ifndef MLX4_PMD_SOFT_COUNTERS
4496         /* FIXME: reset hardware counters. */
4497 #endif
4498         priv_unlock(priv);
4499 }
4500
4501 /**
4502  * DPDK callback to remove a MAC address.
4503  *
4504  * @param dev
4505  *   Pointer to Ethernet device structure.
4506  * @param index
4507  *   MAC address index.
4508  */
4509 static void
4510 mlx4_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
4511 {
4512         struct priv *priv = dev->data->dev_private;
4513
4514         if (mlx4_is_secondary())
4515                 return;
4516         priv_lock(priv);
4517         DEBUG("%p: removing MAC address from index %" PRIu32,
4518               (void *)dev, index);
4519         /* Last array entry is reserved for broadcast. */
4520         if (index >= (elemof(priv->mac) - 1))
4521                 goto end;
4522         priv_mac_addr_del(priv, index);
4523 end:
4524         priv_unlock(priv);
4525 }
4526
4527 /**
4528  * DPDK callback to add a MAC address.
4529  *
4530  * @param dev
4531  *   Pointer to Ethernet device structure.
4532  * @param mac_addr
4533  *   MAC address to register.
4534  * @param index
4535  *   MAC address index.
4536  * @param vmdq
4537  *   VMDq pool index to associate address with (ignored).
4538  */
4539 static int
4540 mlx4_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
4541                   uint32_t index, uint32_t vmdq)
4542 {
4543         struct priv *priv = dev->data->dev_private;
4544         int re;
4545
4546         if (mlx4_is_secondary())
4547                 return -ENOTSUP;
4548         (void)vmdq;
4549         priv_lock(priv);
4550         DEBUG("%p: adding MAC address at index %" PRIu32,
4551               (void *)dev, index);
4552         /* Last array entry is reserved for broadcast. */
4553         if (index >= (elemof(priv->mac) - 1)) {
4554                 re = EINVAL;
4555                 goto end;
4556         }
4557         re = priv_mac_addr_add(priv, index,
4558                                (const uint8_t (*)[ETHER_ADDR_LEN])
4559                                mac_addr->addr_bytes);
4560 end:
4561         priv_unlock(priv);
4562         return -re;
4563 }
4564
4565 /**
4566  * DPDK callback to set the primary MAC address.
4567  *
4568  * @param dev
4569  *   Pointer to Ethernet device structure.
4570  * @param mac_addr
4571  *   MAC address to register.
4572  */
4573 static void
4574 mlx4_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
4575 {
4576         DEBUG("%p: setting primary MAC address", (void *)dev);
4577         mlx4_mac_addr_remove(dev, 0);
4578         mlx4_mac_addr_add(dev, mac_addr, 0, 0);
4579 }
4580
4581 /**
4582  * DPDK callback to enable promiscuous mode.
4583  *
4584  * @param dev
4585  *   Pointer to Ethernet device structure.
4586  */
4587 static void
4588 mlx4_promiscuous_enable(struct rte_eth_dev *dev)
4589 {
4590         struct priv *priv = dev->data->dev_private;
4591         unsigned int i;
4592         int ret;
4593
4594         if (mlx4_is_secondary())
4595                 return;
4596         priv_lock(priv);
4597         if (priv->promisc) {
4598                 priv_unlock(priv);
4599                 return;
4600         }
4601         /* If device isn't started, this is all we need to do. */
4602         if (!priv->started)
4603                 goto end;
4604         if (priv->rss) {
4605                 ret = rxq_promiscuous_enable(&priv->rxq_parent);
4606                 if (ret) {
4607                         priv_unlock(priv);
4608                         return;
4609                 }
4610                 goto end;
4611         }
4612         for (i = 0; (i != priv->rxqs_n); ++i) {
4613                 if ((*priv->rxqs)[i] == NULL)
4614                         continue;
4615                 ret = rxq_promiscuous_enable((*priv->rxqs)[i]);
4616                 if (!ret)
4617                         continue;
4618                 /* Failure, rollback. */
4619                 while (i != 0)
4620                         if ((*priv->rxqs)[--i] != NULL)
4621                                 rxq_promiscuous_disable((*priv->rxqs)[i]);
4622                 priv_unlock(priv);
4623                 return;
4624         }
4625 end:
4626         priv->promisc = 1;
4627         priv_unlock(priv);
4628 }
4629
4630 /**
4631  * DPDK callback to disable promiscuous mode.
4632  *
4633  * @param dev
4634  *   Pointer to Ethernet device structure.
4635  */
4636 static void
4637 mlx4_promiscuous_disable(struct rte_eth_dev *dev)
4638 {
4639         struct priv *priv = dev->data->dev_private;
4640         unsigned int i;
4641
4642         if (mlx4_is_secondary())
4643                 return;
4644         priv_lock(priv);
4645         if (!priv->promisc) {
4646                 priv_unlock(priv);
4647                 return;
4648         }
4649         if (priv->rss) {
4650                 rxq_promiscuous_disable(&priv->rxq_parent);
4651                 goto end;
4652         }
4653         for (i = 0; (i != priv->rxqs_n); ++i)
4654                 if ((*priv->rxqs)[i] != NULL)
4655                         rxq_promiscuous_disable((*priv->rxqs)[i]);
4656 end:
4657         priv->promisc = 0;
4658         priv_unlock(priv);
4659 }
4660
4661 /**
4662  * DPDK callback to enable allmulti mode.
4663  *
4664  * @param dev
4665  *   Pointer to Ethernet device structure.
4666  */
4667 static void
4668 mlx4_allmulticast_enable(struct rte_eth_dev *dev)
4669 {
4670         struct priv *priv = dev->data->dev_private;
4671         unsigned int i;
4672         int ret;
4673
4674         if (mlx4_is_secondary())
4675                 return;
4676         priv_lock(priv);
4677         if (priv->allmulti) {
4678                 priv_unlock(priv);
4679                 return;
4680         }
4681         /* If device isn't started, this is all we need to do. */
4682         if (!priv->started)
4683                 goto end;
4684         if (priv->rss) {
4685                 ret = rxq_allmulticast_enable(&priv->rxq_parent);
4686                 if (ret) {
4687                         priv_unlock(priv);
4688                         return;
4689                 }
4690                 goto end;
4691         }
4692         for (i = 0; (i != priv->rxqs_n); ++i) {
4693                 if ((*priv->rxqs)[i] == NULL)
4694                         continue;
4695                 ret = rxq_allmulticast_enable((*priv->rxqs)[i]);
4696                 if (!ret)
4697                         continue;
4698                 /* Failure, rollback. */
4699                 while (i != 0)
4700                         if ((*priv->rxqs)[--i] != NULL)
4701                                 rxq_allmulticast_disable((*priv->rxqs)[i]);
4702                 priv_unlock(priv);
4703                 return;
4704         }
4705 end:
4706         priv->allmulti = 1;
4707         priv_unlock(priv);
4708 }
4709
4710 /**
4711  * DPDK callback to disable allmulti mode.
4712  *
4713  * @param dev
4714  *   Pointer to Ethernet device structure.
4715  */
4716 static void
4717 mlx4_allmulticast_disable(struct rte_eth_dev *dev)
4718 {
4719         struct priv *priv = dev->data->dev_private;
4720         unsigned int i;
4721
4722         if (mlx4_is_secondary())
4723                 return;
4724         priv_lock(priv);
4725         if (!priv->allmulti) {
4726                 priv_unlock(priv);
4727                 return;
4728         }
4729         if (priv->rss) {
4730                 rxq_allmulticast_disable(&priv->rxq_parent);
4731                 goto end;
4732         }
4733         for (i = 0; (i != priv->rxqs_n); ++i)
4734                 if ((*priv->rxqs)[i] != NULL)
4735                         rxq_allmulticast_disable((*priv->rxqs)[i]);
4736 end:
4737         priv->allmulti = 0;
4738         priv_unlock(priv);
4739 }
4740
4741 /**
4742  * DPDK callback to retrieve physical link information.
4743  *
4744  * @param dev
4745  *   Pointer to Ethernet device structure.
4746  * @param wait_to_complete
4747  *   Wait for request completion (ignored).
4748  */
4749 static int
4750 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
4751 {
4752         const struct priv *priv = mlx4_get_priv(dev);
4753         struct ethtool_cmd edata = {
4754                 .cmd = ETHTOOL_GSET
4755         };
4756         struct ifreq ifr;
4757         struct rte_eth_link dev_link;
4758         int link_speed = 0;
4759
4760         /* priv_lock() is not taken to allow concurrent calls. */
4761
4762         if (priv == NULL)
4763                 return -EINVAL;
4764         (void)wait_to_complete;
4765         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
4766                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(errno));
4767                 return -1;
4768         }
4769         memset(&dev_link, 0, sizeof(dev_link));
4770         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
4771                                 (ifr.ifr_flags & IFF_RUNNING));
4772         ifr.ifr_data = (void *)&edata;
4773         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4774                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
4775                      strerror(errno));
4776                 return -1;
4777         }
4778         link_speed = ethtool_cmd_speed(&edata);
4779         if (link_speed == -1)
4780                 dev_link.link_speed = 0;
4781         else
4782                 dev_link.link_speed = link_speed;
4783         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
4784                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
4785         dev_link.link_autoneg = !(dev->data->dev_conf.link_speeds &
4786                         ETH_LINK_SPEED_FIXED);
4787         if (memcmp(&dev_link, &dev->data->dev_link, sizeof(dev_link))) {
4788                 /* Link status changed. */
4789                 dev->data->dev_link = dev_link;
4790                 return 0;
4791         }
4792         /* Link status is still the same. */
4793         return -1;
4794 }
4795
4796 static int
4797 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
4798                             struct rte_pci_addr *pci_addr);
4799
4800 /**
4801  * DPDK callback to change the MTU.
4802  *
4803  * Setting the MTU affects hardware MRU (packets larger than the MTU cannot be
4804  * received). Use this as a hint to enable/disable scattered packets support
4805  * and improve performance when not needed.
4806  * Since failure is not an option, reconfiguring queues on the fly is not
4807  * recommended.
4808  *
4809  * @param dev
4810  *   Pointer to Ethernet device structure.
4811  * @param in_mtu
4812  *   New MTU.
4813  *
4814  * @return
4815  *   0 on success, negative errno value on failure.
4816  */
4817 static int
4818 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
4819 {
4820         struct priv *priv = dev->data->dev_private;
4821         int ret = 0;
4822         unsigned int i;
4823         uint16_t (*rx_func)(void *, struct rte_mbuf **, uint16_t) =
4824                 mlx4_rx_burst;
4825
4826         if (mlx4_is_secondary())
4827                 return -E_RTE_SECONDARY;
4828         priv_lock(priv);
4829         /* Set kernel interface MTU first. */
4830         if (priv_set_mtu(priv, mtu)) {
4831                 ret = errno;
4832                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
4833                      strerror(ret));
4834                 goto out;
4835         } else
4836                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
4837         priv->mtu = mtu;
4838         /* Temporarily replace RX handler with a fake one, assuming it has not
4839          * been copied elsewhere. */
4840         dev->rx_pkt_burst = removed_rx_burst;
4841         /* Make sure everyone has left mlx4_rx_burst() and uses
4842          * removed_rx_burst() instead. */
4843         rte_wmb();
4844         usleep(1000);
4845         /* Reconfigure each RX queue. */
4846         for (i = 0; (i != priv->rxqs_n); ++i) {
4847                 struct rxq *rxq = (*priv->rxqs)[i];
4848                 unsigned int max_frame_len;
4849
4850                 if (rxq == NULL)
4851                         continue;
4852                 /* Calculate new maximum frame length according to MTU. */
4853                 max_frame_len = (priv->mtu + ETHER_HDR_LEN +
4854                                  (ETHER_MAX_VLAN_FRAME_LEN - ETHER_MAX_LEN));
4855                 /* Provide new values to rxq_setup(). */
4856                 dev->data->dev_conf.rxmode.jumbo_frame =
4857                         (max_frame_len > ETHER_MAX_LEN);
4858                 dev->data->dev_conf.rxmode.max_rx_pkt_len = max_frame_len;
4859                 ret = rxq_rehash(dev, rxq);
4860                 if (ret) {
4861                         /* Force SP RX if that queue requires it and abort. */
4862                         if (rxq->sp)
4863                                 rx_func = mlx4_rx_burst_sp;
4864                         break;
4865                 }
4866                 /* Reenable non-RSS queue attributes. No need to check
4867                  * for errors at this stage. */
4868                 if (!priv->rss) {
4869                         rxq_mac_addrs_add(rxq);
4870                         if (priv->promisc)
4871                                 rxq_promiscuous_enable(rxq);
4872                         if (priv->allmulti)
4873                                 rxq_allmulticast_enable(rxq);
4874                 }
4875                 /* Scattered burst function takes priority. */
4876                 if (rxq->sp)
4877                         rx_func = mlx4_rx_burst_sp;
4878         }
4879         /* Burst functions can now be called again. */
4880         rte_wmb();
4881         dev->rx_pkt_burst = rx_func;
4882 out:
4883         priv_unlock(priv);
4884         assert(ret >= 0);
4885         return -ret;
4886 }
4887
4888 /**
4889  * DPDK callback to get flow control status.
4890  *
4891  * @param dev
4892  *   Pointer to Ethernet device structure.
4893  * @param[out] fc_conf
4894  *   Flow control output buffer.
4895  *
4896  * @return
4897  *   0 on success, negative errno value on failure.
4898  */
4899 static int
4900 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4901 {
4902         struct priv *priv = dev->data->dev_private;
4903         struct ifreq ifr;
4904         struct ethtool_pauseparam ethpause = {
4905                 .cmd = ETHTOOL_GPAUSEPARAM
4906         };
4907         int ret;
4908
4909         if (mlx4_is_secondary())
4910                 return -E_RTE_SECONDARY;
4911         ifr.ifr_data = (void *)&ethpause;
4912         priv_lock(priv);
4913         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4914                 ret = errno;
4915                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
4916                      " failed: %s",
4917                      strerror(ret));
4918                 goto out;
4919         }
4920
4921         fc_conf->autoneg = ethpause.autoneg;
4922         if (ethpause.rx_pause && ethpause.tx_pause)
4923                 fc_conf->mode = RTE_FC_FULL;
4924         else if (ethpause.rx_pause)
4925                 fc_conf->mode = RTE_FC_RX_PAUSE;
4926         else if (ethpause.tx_pause)
4927                 fc_conf->mode = RTE_FC_TX_PAUSE;
4928         else
4929                 fc_conf->mode = RTE_FC_NONE;
4930         ret = 0;
4931
4932 out:
4933         priv_unlock(priv);
4934         assert(ret >= 0);
4935         return -ret;
4936 }
4937
4938 /**
4939  * DPDK callback to modify flow control parameters.
4940  *
4941  * @param dev
4942  *   Pointer to Ethernet device structure.
4943  * @param[in] fc_conf
4944  *   Flow control parameters.
4945  *
4946  * @return
4947  *   0 on success, negative errno value on failure.
4948  */
4949 static int
4950 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4951 {
4952         struct priv *priv = dev->data->dev_private;
4953         struct ifreq ifr;
4954         struct ethtool_pauseparam ethpause = {
4955                 .cmd = ETHTOOL_SPAUSEPARAM
4956         };
4957         int ret;
4958
4959         if (mlx4_is_secondary())
4960                 return -E_RTE_SECONDARY;
4961         ifr.ifr_data = (void *)&ethpause;
4962         ethpause.autoneg = fc_conf->autoneg;
4963         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4964             (fc_conf->mode & RTE_FC_RX_PAUSE))
4965                 ethpause.rx_pause = 1;
4966         else
4967                 ethpause.rx_pause = 0;
4968
4969         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4970             (fc_conf->mode & RTE_FC_TX_PAUSE))
4971                 ethpause.tx_pause = 1;
4972         else
4973                 ethpause.tx_pause = 0;
4974
4975         priv_lock(priv);
4976         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4977                 ret = errno;
4978                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
4979                      " failed: %s",
4980                      strerror(ret));
4981                 goto out;
4982         }
4983         ret = 0;
4984
4985 out:
4986         priv_unlock(priv);
4987         assert(ret >= 0);
4988         return -ret;
4989 }
4990
4991 /**
4992  * Configure a VLAN filter.
4993  *
4994  * @param dev
4995  *   Pointer to Ethernet device structure.
4996  * @param vlan_id
4997  *   VLAN ID to filter.
4998  * @param on
4999  *   Toggle filter.
5000  *
5001  * @return
5002  *   0 on success, errno value on failure.
5003  */
5004 static int
5005 vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
5006 {
5007         struct priv *priv = dev->data->dev_private;
5008         unsigned int i;
5009         unsigned int j = -1;
5010
5011         DEBUG("%p: %s VLAN filter ID %" PRIu16,
5012               (void *)dev, (on ? "enable" : "disable"), vlan_id);
5013         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
5014                 if (!priv->vlan_filter[i].enabled) {
5015                         /* Unused index, remember it. */
5016                         j = i;
5017                         continue;
5018                 }
5019                 if (priv->vlan_filter[i].id != vlan_id)
5020                         continue;
5021                 /* This VLAN ID is already known, use its index. */
5022                 j = i;
5023                 break;
5024         }
5025         /* Check if there's room for another VLAN filter. */
5026         if (j == (unsigned int)-1)
5027                 return ENOMEM;
5028         /*
5029          * VLAN filters apply to all configured MAC addresses, flow
5030          * specifications must be reconfigured accordingly.
5031          */
5032         priv->vlan_filter[j].id = vlan_id;
5033         if ((on) && (!priv->vlan_filter[j].enabled)) {
5034                 /*
5035                  * Filter is disabled, enable it.
5036                  * Rehashing flows in all RX queues is necessary.
5037                  */
5038                 if (priv->rss)
5039                         rxq_mac_addrs_del(&priv->rxq_parent);
5040                 else
5041                         for (i = 0; (i != priv->rxqs_n); ++i)
5042                                 if ((*priv->rxqs)[i] != NULL)
5043                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
5044                 priv->vlan_filter[j].enabled = 1;
5045                 if (priv->started) {
5046                         if (priv->rss)
5047                                 rxq_mac_addrs_add(&priv->rxq_parent);
5048                         else
5049                                 for (i = 0; (i != priv->rxqs_n); ++i) {
5050                                         if ((*priv->rxqs)[i] == NULL)
5051                                                 continue;
5052                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
5053                                 }
5054                 }
5055         } else if ((!on) && (priv->vlan_filter[j].enabled)) {
5056                 /*
5057                  * Filter is enabled, disable it.
5058                  * Rehashing flows in all RX queues is necessary.
5059                  */
5060                 if (priv->rss)
5061                         rxq_mac_addrs_del(&priv->rxq_parent);
5062                 else
5063                         for (i = 0; (i != priv->rxqs_n); ++i)
5064                                 if ((*priv->rxqs)[i] != NULL)
5065                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
5066                 priv->vlan_filter[j].enabled = 0;
5067                 if (priv->started) {
5068                         if (priv->rss)
5069                                 rxq_mac_addrs_add(&priv->rxq_parent);
5070                         else
5071                                 for (i = 0; (i != priv->rxqs_n); ++i) {
5072                                         if ((*priv->rxqs)[i] == NULL)
5073                                                 continue;
5074                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
5075                                 }
5076                 }
5077         }
5078         return 0;
5079 }
5080
5081 /**
5082  * DPDK callback to configure a VLAN filter.
5083  *
5084  * @param dev
5085  *   Pointer to Ethernet device structure.
5086  * @param vlan_id
5087  *   VLAN ID to filter.
5088  * @param on
5089  *   Toggle filter.
5090  *
5091  * @return
5092  *   0 on success, negative errno value on failure.
5093  */
5094 static int
5095 mlx4_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
5096 {
5097         struct priv *priv = dev->data->dev_private;
5098         int ret;
5099
5100         if (mlx4_is_secondary())
5101                 return -E_RTE_SECONDARY;
5102         priv_lock(priv);
5103         ret = vlan_filter_set(dev, vlan_id, on);
5104         priv_unlock(priv);
5105         assert(ret >= 0);
5106         return -ret;
5107 }
5108
5109 const struct rte_flow_ops mlx4_flow_ops = {
5110         .validate = mlx4_flow_validate,
5111         .create = mlx4_flow_create,
5112         .destroy = mlx4_flow_destroy,
5113         .flush = mlx4_flow_flush,
5114         .query = NULL,
5115 };
5116
5117 /**
5118  * Manage filter operations.
5119  *
5120  * @param dev
5121  *   Pointer to Ethernet device structure.
5122  * @param filter_type
5123  *   Filter type.
5124  * @param filter_op
5125  *   Operation to perform.
5126  * @param arg
5127  *   Pointer to operation-specific structure.
5128  *
5129  * @return
5130  *   0 on success, negative errno value on failure.
5131  */
5132 static int
5133 mlx4_dev_filter_ctrl(struct rte_eth_dev *dev,
5134                      enum rte_filter_type filter_type,
5135                      enum rte_filter_op filter_op,
5136                      void *arg)
5137 {
5138         int ret = EINVAL;
5139
5140         switch (filter_type) {
5141         case RTE_ETH_FILTER_GENERIC:
5142                 if (filter_op != RTE_ETH_FILTER_GET)
5143                         return -EINVAL;
5144                 *(const void **)arg = &mlx4_flow_ops;
5145                 return 0;
5146         case RTE_ETH_FILTER_FDIR:
5147                 DEBUG("%p: filter type FDIR is not supported by this PMD",
5148                       (void *)dev);
5149                 break;
5150         default:
5151                 ERROR("%p: filter type (%d) not supported",
5152                       (void *)dev, filter_type);
5153                 break;
5154         }
5155         return -ret;
5156 }
5157
5158 static const struct eth_dev_ops mlx4_dev_ops = {
5159         .dev_configure = mlx4_dev_configure,
5160         .dev_start = mlx4_dev_start,
5161         .dev_stop = mlx4_dev_stop,
5162         .dev_set_link_down = mlx4_set_link_down,
5163         .dev_set_link_up = mlx4_set_link_up,
5164         .dev_close = mlx4_dev_close,
5165         .promiscuous_enable = mlx4_promiscuous_enable,
5166         .promiscuous_disable = mlx4_promiscuous_disable,
5167         .allmulticast_enable = mlx4_allmulticast_enable,
5168         .allmulticast_disable = mlx4_allmulticast_disable,
5169         .link_update = mlx4_link_update,
5170         .stats_get = mlx4_stats_get,
5171         .stats_reset = mlx4_stats_reset,
5172         .queue_stats_mapping_set = NULL,
5173         .dev_infos_get = mlx4_dev_infos_get,
5174         .dev_supported_ptypes_get = mlx4_dev_supported_ptypes_get,
5175         .vlan_filter_set = mlx4_vlan_filter_set,
5176         .vlan_tpid_set = NULL,
5177         .vlan_strip_queue_set = NULL,
5178         .vlan_offload_set = NULL,
5179         .rx_queue_setup = mlx4_rx_queue_setup,
5180         .tx_queue_setup = mlx4_tx_queue_setup,
5181         .rx_queue_release = mlx4_rx_queue_release,
5182         .tx_queue_release = mlx4_tx_queue_release,
5183         .dev_led_on = NULL,
5184         .dev_led_off = NULL,
5185         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
5186         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
5187         .priority_flow_ctrl_set = NULL,
5188         .mac_addr_remove = mlx4_mac_addr_remove,
5189         .mac_addr_add = mlx4_mac_addr_add,
5190         .mac_addr_set = mlx4_mac_addr_set,
5191         .mtu_set = mlx4_dev_set_mtu,
5192         .filter_ctrl = mlx4_dev_filter_ctrl,
5193         .rx_queue_intr_enable = mlx4_rx_intr_enable,
5194         .rx_queue_intr_disable = mlx4_rx_intr_disable,
5195 };
5196
5197 /**
5198  * Get PCI information from struct ibv_device.
5199  *
5200  * @param device
5201  *   Pointer to Ethernet device structure.
5202  * @param[out] pci_addr
5203  *   PCI bus address output buffer.
5204  *
5205  * @return
5206  *   0 on success, -1 on failure and errno is set.
5207  */
5208 static int
5209 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
5210                             struct rte_pci_addr *pci_addr)
5211 {
5212         FILE *file;
5213         char line[32];
5214         MKSTR(path, "%s/device/uevent", device->ibdev_path);
5215
5216         file = fopen(path, "rb");
5217         if (file == NULL)
5218                 return -1;
5219         while (fgets(line, sizeof(line), file) == line) {
5220                 size_t len = strlen(line);
5221                 int ret;
5222
5223                 /* Truncate long lines. */
5224                 if (len == (sizeof(line) - 1))
5225                         while (line[(len - 1)] != '\n') {
5226                                 ret = fgetc(file);
5227                                 if (ret == EOF)
5228                                         break;
5229                                 line[(len - 1)] = ret;
5230                         }
5231                 /* Extract information. */
5232                 if (sscanf(line,
5233                            "PCI_SLOT_NAME="
5234                            "%" SCNx32 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
5235                            &pci_addr->domain,
5236                            &pci_addr->bus,
5237                            &pci_addr->devid,
5238                            &pci_addr->function) == 4) {
5239                         ret = 0;
5240                         break;
5241                 }
5242         }
5243         fclose(file);
5244         return 0;
5245 }
5246
5247 /**
5248  * Get MAC address by querying netdevice.
5249  *
5250  * @param[in] priv
5251  *   struct priv for the requested device.
5252  * @param[out] mac
5253  *   MAC address output buffer.
5254  *
5255  * @return
5256  *   0 on success, -1 on failure and errno is set.
5257  */
5258 static int
5259 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
5260 {
5261         struct ifreq request;
5262
5263         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
5264                 return -1;
5265         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
5266         return 0;
5267 }
5268
5269 /* Support up to 32 adapters. */
5270 static struct {
5271         struct rte_pci_addr pci_addr; /* associated PCI address */
5272         uint32_t ports; /* physical ports bitfield. */
5273 } mlx4_dev[32];
5274
5275 /**
5276  * Get device index in mlx4_dev[] from PCI bus address.
5277  *
5278  * @param[in] pci_addr
5279  *   PCI bus address to look for.
5280  *
5281  * @return
5282  *   mlx4_dev[] index on success, -1 on failure.
5283  */
5284 static int
5285 mlx4_dev_idx(struct rte_pci_addr *pci_addr)
5286 {
5287         unsigned int i;
5288         int ret = -1;
5289
5290         assert(pci_addr != NULL);
5291         for (i = 0; (i != elemof(mlx4_dev)); ++i) {
5292                 if ((mlx4_dev[i].pci_addr.domain == pci_addr->domain) &&
5293                     (mlx4_dev[i].pci_addr.bus == pci_addr->bus) &&
5294                     (mlx4_dev[i].pci_addr.devid == pci_addr->devid) &&
5295                     (mlx4_dev[i].pci_addr.function == pci_addr->function))
5296                         return i;
5297                 if ((mlx4_dev[i].ports == 0) && (ret == -1))
5298                         ret = i;
5299         }
5300         return ret;
5301 }
5302
5303 /**
5304  * Retrieve integer value from environment variable.
5305  *
5306  * @param[in] name
5307  *   Environment variable name.
5308  *
5309  * @return
5310  *   Integer value, 0 if the variable is not set.
5311  */
5312 static int
5313 mlx4_getenv_int(const char *name)
5314 {
5315         const char *val = getenv(name);
5316
5317         if (val == NULL)
5318                 return 0;
5319         return atoi(val);
5320 }
5321
5322 static void
5323 mlx4_dev_link_status_handler(void *);
5324 static void
5325 mlx4_dev_interrupt_handler(void *);
5326
5327 /**
5328  * Link/device status handler.
5329  *
5330  * @param priv
5331  *   Pointer to private structure.
5332  * @param dev
5333  *   Pointer to the rte_eth_dev structure.
5334  * @param events
5335  *   Pointer to event flags holder.
5336  *
5337  * @return
5338  *   Number of events
5339  */
5340 static int
5341 priv_dev_status_handler(struct priv *priv, struct rte_eth_dev *dev,
5342                         uint32_t *events)
5343 {
5344         struct ibv_async_event event;
5345         int port_change = 0;
5346         int ret = 0;
5347
5348         *events = 0;
5349         /* Read all message and acknowledge them. */
5350         for (;;) {
5351                 if (ibv_get_async_event(priv->ctx, &event))
5352                         break;
5353                 if ((event.event_type == IBV_EVENT_PORT_ACTIVE ||
5354                      event.event_type == IBV_EVENT_PORT_ERR) &&
5355                     (priv->intr_conf.lsc == 1)) {
5356                         port_change = 1;
5357                         ret++;
5358                 } else if (event.event_type == IBV_EVENT_DEVICE_FATAL &&
5359                            priv->intr_conf.rmv == 1) {
5360                         *events |= (1 << RTE_ETH_EVENT_INTR_RMV);
5361                         ret++;
5362                 } else
5363                         DEBUG("event type %d on port %d not handled",
5364                               event.event_type, event.element.port_num);
5365                 ibv_ack_async_event(&event);
5366         }
5367
5368         if (port_change ^ priv->pending_alarm) {
5369                 struct rte_eth_link *link = &dev->data->dev_link;
5370
5371                 priv->pending_alarm = 0;
5372                 mlx4_link_update(dev, 0);
5373                 if (((link->link_speed == 0) && link->link_status) ||
5374                     ((link->link_speed != 0) && !link->link_status)) {
5375                         /* Inconsistent status, check again later. */
5376                         priv->pending_alarm = 1;
5377                         rte_eal_alarm_set(MLX4_ALARM_TIMEOUT_US,
5378                                           mlx4_dev_link_status_handler,
5379                                           dev);
5380                 } else {
5381                         *events |= (1 << RTE_ETH_EVENT_INTR_LSC);
5382                 }
5383         }
5384         return ret;
5385 }
5386
5387 /**
5388  * Handle delayed link status event.
5389  *
5390  * @param arg
5391  *   Registered argument.
5392  */
5393 static void
5394 mlx4_dev_link_status_handler(void *arg)
5395 {
5396         struct rte_eth_dev *dev = arg;
5397         struct priv *priv = dev->data->dev_private;
5398         uint32_t events;
5399         int ret;
5400
5401         priv_lock(priv);
5402         assert(priv->pending_alarm == 1);
5403         ret = priv_dev_status_handler(priv, dev, &events);
5404         priv_unlock(priv);
5405         if (ret > 0 && events & (1 << RTE_ETH_EVENT_INTR_LSC))
5406                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC, NULL,
5407                                               NULL);
5408 }
5409
5410 /**
5411  * Handle interrupts from the NIC.
5412  *
5413  * @param[in] intr_handle
5414  *   Interrupt handler.
5415  * @param cb_arg
5416  *   Callback argument.
5417  */
5418 static void
5419 mlx4_dev_interrupt_handler(void *cb_arg)
5420 {
5421         struct rte_eth_dev *dev = cb_arg;
5422         struct priv *priv = dev->data->dev_private;
5423         int ret;
5424         uint32_t ev;
5425         int i;
5426
5427         priv_lock(priv);
5428         ret = priv_dev_status_handler(priv, dev, &ev);
5429         priv_unlock(priv);
5430         if (ret > 0) {
5431                 for (i = RTE_ETH_EVENT_UNKNOWN;
5432                      i < RTE_ETH_EVENT_MAX;
5433                      i++) {
5434                         if (ev & (1 << i)) {
5435                                 ev &= ~(1 << i);
5436                                 _rte_eth_dev_callback_process(dev, i, NULL,
5437                                                               NULL);
5438                                 ret--;
5439                         }
5440                 }
5441                 if (ret)
5442                         WARN("%d event%s not processed", ret,
5443                              (ret > 1 ? "s were" : " was"));
5444         }
5445 }
5446
5447 /**
5448  * Uninstall interrupt handler.
5449  *
5450  * @param priv
5451  *   Pointer to private structure.
5452  * @param dev
5453  *   Pointer to the rte_eth_dev structure.
5454  * @return
5455  *   0 on success, negative errno value on failure.
5456  */
5457 static int
5458 priv_dev_interrupt_handler_uninstall(struct priv *priv, struct rte_eth_dev *dev)
5459 {
5460         int ret;
5461
5462         if (priv->intr_conf.lsc ||
5463             priv->intr_conf.rmv)
5464                 return 0;
5465         ret = rte_intr_callback_unregister(&priv->intr_handle,
5466                                            mlx4_dev_interrupt_handler,
5467                                            dev);
5468         if (ret < 0) {
5469                 ERROR("rte_intr_callback_unregister failed with %d"
5470                       "%s%s%s", ret,
5471                       (errno ? " (errno: " : ""),
5472                       (errno ? strerror(errno) : ""),
5473                       (errno ? ")" : ""));
5474         }
5475         priv->intr_handle.fd = 0;
5476         priv->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
5477         return ret;
5478 }
5479
5480 /**
5481  * Install interrupt handler.
5482  *
5483  * @param priv
5484  *   Pointer to private structure.
5485  * @param dev
5486  *   Pointer to the rte_eth_dev structure.
5487  * @return
5488  *   0 on success, negative errno value on failure.
5489  */
5490 static int
5491 priv_dev_interrupt_handler_install(struct priv *priv,
5492                                    struct rte_eth_dev *dev)
5493 {
5494         int flags;
5495         int rc;
5496
5497         /* Check whether the interrupt handler has already been installed
5498          * for either type of interrupt
5499          */
5500         if (priv->intr_conf.lsc &&
5501             priv->intr_conf.rmv &&
5502             priv->intr_handle.fd)
5503                 return 0;
5504         assert(priv->ctx->async_fd > 0);
5505         flags = fcntl(priv->ctx->async_fd, F_GETFL);
5506         rc = fcntl(priv->ctx->async_fd, F_SETFL, flags | O_NONBLOCK);
5507         if (rc < 0) {
5508                 INFO("failed to change file descriptor async event queue");
5509                 dev->data->dev_conf.intr_conf.lsc = 0;
5510                 dev->data->dev_conf.intr_conf.rmv = 0;
5511                 return -errno;
5512         } else {
5513                 priv->intr_handle.fd = priv->ctx->async_fd;
5514                 priv->intr_handle.type = RTE_INTR_HANDLE_EXT;
5515                 rc = rte_intr_callback_register(&priv->intr_handle,
5516                                                  mlx4_dev_interrupt_handler,
5517                                                  dev);
5518                 if (rc) {
5519                         ERROR("rte_intr_callback_register failed "
5520                               " (errno: %s)", strerror(errno));
5521                         return rc;
5522                 }
5523         }
5524         return 0;
5525 }
5526
5527 /**
5528  * Uninstall interrupt handler.
5529  *
5530  * @param priv
5531  *   Pointer to private structure.
5532  * @param dev
5533  *   Pointer to the rte_eth_dev structure.
5534  * @return
5535  *   0 on success, negative value on error.
5536  */
5537 static int
5538 priv_dev_removal_interrupt_handler_uninstall(struct priv *priv,
5539                                             struct rte_eth_dev *dev)
5540 {
5541         if (dev->data->dev_conf.intr_conf.rmv) {
5542                 priv->intr_conf.rmv = 0;
5543                 return priv_dev_interrupt_handler_uninstall(priv, dev);
5544         }
5545         return 0;
5546 }
5547
5548 /**
5549  * Uninstall interrupt handler.
5550  *
5551  * @param priv
5552  *   Pointer to private structure.
5553  * @param dev
5554  *   Pointer to the rte_eth_dev structure.
5555  * @return
5556  *   0 on success, negative value on error,
5557  */
5558 static int
5559 priv_dev_link_interrupt_handler_uninstall(struct priv *priv,
5560                                           struct rte_eth_dev *dev)
5561 {
5562         int ret = 0;
5563
5564         if (dev->data->dev_conf.intr_conf.lsc) {
5565                 priv->intr_conf.lsc = 0;
5566                 ret = priv_dev_interrupt_handler_uninstall(priv, dev);
5567                 if (ret)
5568                         return ret;
5569         }
5570         if (priv->pending_alarm)
5571                 if (rte_eal_alarm_cancel(mlx4_dev_link_status_handler,
5572                                          dev)) {
5573                         ERROR("rte_eal_alarm_cancel failed "
5574                               " (errno: %s)", strerror(rte_errno));
5575                         return -rte_errno;
5576                 }
5577         priv->pending_alarm = 0;
5578         return 0;
5579 }
5580
5581 /**
5582  * Install link interrupt handler.
5583  *
5584  * @param priv
5585  *   Pointer to private structure.
5586  * @param dev
5587  *   Pointer to the rte_eth_dev structure.
5588  * @return
5589  *   0 on success, negative value on error.
5590  */
5591 static int
5592 priv_dev_link_interrupt_handler_install(struct priv *priv,
5593                                         struct rte_eth_dev *dev)
5594 {
5595         int ret;
5596
5597         if (dev->data->dev_conf.intr_conf.lsc) {
5598                 ret = priv_dev_interrupt_handler_install(priv, dev);
5599                 if (ret)
5600                         return ret;
5601                 priv->intr_conf.lsc = 1;
5602         }
5603         return 0;
5604 }
5605
5606 /**
5607  * Install removal interrupt handler.
5608  *
5609  * @param priv
5610  *   Pointer to private structure.
5611  * @param dev
5612  *   Pointer to the rte_eth_dev structure.
5613  * @return
5614  *   0 on success, negative value on error.
5615  */
5616 static int
5617 priv_dev_removal_interrupt_handler_install(struct priv *priv,
5618                                            struct rte_eth_dev *dev)
5619 {
5620         int ret;
5621
5622         if (dev->data->dev_conf.intr_conf.rmv) {
5623                 ret = priv_dev_interrupt_handler_install(priv, dev);
5624                 if (ret)
5625                         return ret;
5626                 priv->intr_conf.rmv = 1;
5627         }
5628         return 0;
5629 }
5630
5631 /**
5632  * Allocate queue vector and fill epoll fd list for Rx interrupts.
5633  *
5634  * @param priv
5635  *   Pointer to private structure.
5636  *
5637  * @return
5638  *   0 on success, negative on failure.
5639  */
5640 static int
5641 priv_rx_intr_vec_enable(struct priv *priv)
5642 {
5643         unsigned int i;
5644         unsigned int rxqs_n = priv->rxqs_n;
5645         unsigned int n = RTE_MIN(rxqs_n, (uint32_t)RTE_MAX_RXTX_INTR_VEC_ID);
5646         unsigned int count = 0;
5647         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
5648
5649         if (!priv->dev->data->dev_conf.intr_conf.rxq)
5650                 return 0;
5651         priv_rx_intr_vec_disable(priv);
5652         intr_handle->intr_vec = malloc(sizeof(intr_handle->intr_vec[rxqs_n]));
5653         if (intr_handle->intr_vec == NULL) {
5654                 ERROR("failed to allocate memory for interrupt vector,"
5655                       " Rx interrupts will not be supported");
5656                 return -ENOMEM;
5657         }
5658         intr_handle->type = RTE_INTR_HANDLE_EXT;
5659         for (i = 0; i != n; ++i) {
5660                 struct rxq *rxq = (*priv->rxqs)[i];
5661                 int fd;
5662                 int flags;
5663                 int rc;
5664
5665                 /* Skip queues that cannot request interrupts. */
5666                 if (!rxq || !rxq->channel) {
5667                         /* Use invalid intr_vec[] index to disable entry. */
5668                         intr_handle->intr_vec[i] =
5669                                 RTE_INTR_VEC_RXTX_OFFSET +
5670                                 RTE_MAX_RXTX_INTR_VEC_ID;
5671                         continue;
5672                 }
5673                 if (count >= RTE_MAX_RXTX_INTR_VEC_ID) {
5674                         ERROR("too many Rx queues for interrupt vector size"
5675                               " (%d), Rx interrupts cannot be enabled",
5676                               RTE_MAX_RXTX_INTR_VEC_ID);
5677                         priv_rx_intr_vec_disable(priv);
5678                         return -1;
5679                 }
5680                 fd = rxq->channel->fd;
5681                 flags = fcntl(fd, F_GETFL);
5682                 rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
5683                 if (rc < 0) {
5684                         ERROR("failed to make Rx interrupt file descriptor"
5685                               " %d non-blocking for queue index %d", fd, i);
5686                         priv_rx_intr_vec_disable(priv);
5687                         return rc;
5688                 }
5689                 intr_handle->intr_vec[i] = RTE_INTR_VEC_RXTX_OFFSET + count;
5690                 intr_handle->efds[count] = fd;
5691                 count++;
5692         }
5693         if (!count)
5694                 priv_rx_intr_vec_disable(priv);
5695         else
5696                 intr_handle->nb_efd = count;
5697         return 0;
5698 }
5699
5700 /**
5701  * Clean up Rx interrupts handler.
5702  *
5703  * @param priv
5704  *   Pointer to private structure.
5705  */
5706 static void
5707 priv_rx_intr_vec_disable(struct priv *priv)
5708 {
5709         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
5710
5711         rte_intr_free_epoll_fd(intr_handle);
5712         free(intr_handle->intr_vec);
5713         intr_handle->nb_efd = 0;
5714         intr_handle->intr_vec = NULL;
5715 }
5716
5717 /**
5718  * DPDK callback for Rx queue interrupt enable.
5719  *
5720  * @param dev
5721  *   Pointer to Ethernet device structure.
5722  * @param idx
5723  *   Rx queue index.
5724  *
5725  * @return
5726  *   0 on success, negative on failure.
5727  */
5728 static int
5729 mlx4_rx_intr_enable(struct rte_eth_dev *dev, uint16_t idx)
5730 {
5731         struct priv *priv = dev->data->dev_private;
5732         struct rxq *rxq = (*priv->rxqs)[idx];
5733         int ret;
5734
5735         if (!rxq || !rxq->channel)
5736                 ret = EINVAL;
5737         else
5738                 ret = ibv_req_notify_cq(rxq->cq, 0);
5739         if (ret)
5740                 WARN("unable to arm interrupt on rx queue %d", idx);
5741         return -ret;
5742 }
5743
5744 /**
5745  * DPDK callback for Rx queue interrupt disable.
5746  *
5747  * @param dev
5748  *   Pointer to Ethernet device structure.
5749  * @param idx
5750  *   Rx queue index.
5751  *
5752  * @return
5753  *   0 on success, negative on failure.
5754  */
5755 static int
5756 mlx4_rx_intr_disable(struct rte_eth_dev *dev, uint16_t idx)
5757 {
5758         struct priv *priv = dev->data->dev_private;
5759         struct rxq *rxq = (*priv->rxqs)[idx];
5760         struct ibv_cq *ev_cq;
5761         void *ev_ctx;
5762         int ret;
5763
5764         if (!rxq || !rxq->channel) {
5765                 ret = EINVAL;
5766         } else {
5767                 ret = ibv_get_cq_event(rxq->cq->channel, &ev_cq, &ev_ctx);
5768                 if (ret || ev_cq != rxq->cq)
5769                         ret = EINVAL;
5770         }
5771         if (ret)
5772                 WARN("unable to disable interrupt on rx queue %d",
5773                      idx);
5774         else
5775                 ibv_ack_cq_events(rxq->cq, 1);
5776         return -ret;
5777 }
5778
5779 /**
5780  * Verify and store value for device argument.
5781  *
5782  * @param[in] key
5783  *   Key argument to verify.
5784  * @param[in] val
5785  *   Value associated with key.
5786  * @param out
5787  *   User data.
5788  *
5789  * @return
5790  *   0 on success, negative errno value on failure.
5791  */
5792 static int
5793 mlx4_arg_parse(const char *key, const char *val, void *out)
5794 {
5795         struct mlx4_conf *conf = out;
5796         unsigned long tmp;
5797
5798         errno = 0;
5799         tmp = strtoul(val, NULL, 0);
5800         if (errno) {
5801                 WARN("%s: \"%s\" is not a valid integer", key, val);
5802                 return -errno;
5803         }
5804         if (strcmp(MLX4_PMD_PORT_KVARG, key) == 0) {
5805                 if (tmp >= MLX4_PMD_MAX_PHYS_PORTS) {
5806                         ERROR("invalid port index %lu (max: %u)",
5807                                 tmp, MLX4_PMD_MAX_PHYS_PORTS - 1);
5808                         return -EINVAL;
5809                 }
5810                 conf->active_ports |= 1 << tmp;
5811         } else {
5812                 WARN("%s: unknown parameter", key);
5813                 return -EINVAL;
5814         }
5815         return 0;
5816 }
5817
5818 /**
5819  * Parse device parameters.
5820  *
5821  * @param devargs
5822  *   Device arguments structure.
5823  *
5824  * @return
5825  *   0 on success, negative errno value on failure.
5826  */
5827 static int
5828 mlx4_args(struct rte_devargs *devargs, struct mlx4_conf *conf)
5829 {
5830         struct rte_kvargs *kvlist;
5831         unsigned int arg_count;
5832         int ret = 0;
5833         int i;
5834
5835         if (devargs == NULL)
5836                 return 0;
5837         kvlist = rte_kvargs_parse(devargs->args, pmd_mlx4_init_params);
5838         if (kvlist == NULL) {
5839                 ERROR("failed to parse kvargs");
5840                 return -EINVAL;
5841         }
5842         /* Process parameters. */
5843         for (i = 0; pmd_mlx4_init_params[i]; ++i) {
5844                 arg_count = rte_kvargs_count(kvlist, MLX4_PMD_PORT_KVARG);
5845                 while (arg_count-- > 0) {
5846                         ret = rte_kvargs_process(kvlist, MLX4_PMD_PORT_KVARG,
5847                                         mlx4_arg_parse, conf);
5848                         if (ret != 0)
5849                                 goto free_kvlist;
5850                 }
5851         }
5852 free_kvlist:
5853         rte_kvargs_free(kvlist);
5854         return ret;
5855 }
5856
5857 static struct rte_pci_driver mlx4_driver;
5858
5859 /**
5860  * DPDK callback to register a PCI device.
5861  *
5862  * This function creates an Ethernet device for each port of a given
5863  * PCI device.
5864  *
5865  * @param[in] pci_drv
5866  *   PCI driver structure (mlx4_driver).
5867  * @param[in] pci_dev
5868  *   PCI device information.
5869  *
5870  * @return
5871  *   0 on success, negative errno value on failure.
5872  */
5873 static int
5874 mlx4_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
5875 {
5876         struct ibv_device **list;
5877         struct ibv_device *ibv_dev;
5878         int err = 0;
5879         struct ibv_context *attr_ctx = NULL;
5880         struct ibv_device_attr device_attr;
5881         struct mlx4_conf conf = {
5882                 .active_ports = 0,
5883         };
5884         unsigned int vf;
5885         int idx;
5886         int i;
5887
5888         (void)pci_drv;
5889         assert(pci_drv == &mlx4_driver);
5890         /* Get mlx4_dev[] index. */
5891         idx = mlx4_dev_idx(&pci_dev->addr);
5892         if (idx == -1) {
5893                 ERROR("this driver cannot support any more adapters");
5894                 return -ENOMEM;
5895         }
5896         DEBUG("using driver device index %d", idx);
5897
5898         /* Save PCI address. */
5899         mlx4_dev[idx].pci_addr = pci_dev->addr;
5900         list = ibv_get_device_list(&i);
5901         if (list == NULL) {
5902                 assert(errno);
5903                 if (errno == ENOSYS)
5904                         ERROR("cannot list devices, is ib_uverbs loaded?");
5905                 return -errno;
5906         }
5907         assert(i >= 0);
5908         /*
5909          * For each listed device, check related sysfs entry against
5910          * the provided PCI ID.
5911          */
5912         while (i != 0) {
5913                 struct rte_pci_addr pci_addr;
5914
5915                 --i;
5916                 DEBUG("checking device \"%s\"", list[i]->name);
5917                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
5918                         continue;
5919                 if ((pci_dev->addr.domain != pci_addr.domain) ||
5920                     (pci_dev->addr.bus != pci_addr.bus) ||
5921                     (pci_dev->addr.devid != pci_addr.devid) ||
5922                     (pci_dev->addr.function != pci_addr.function))
5923                         continue;
5924                 vf = (pci_dev->id.device_id ==
5925                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
5926                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
5927                      list[i]->name, (vf ? "true" : "false"));
5928                 attr_ctx = ibv_open_device(list[i]);
5929                 err = errno;
5930                 break;
5931         }
5932         if (attr_ctx == NULL) {
5933                 ibv_free_device_list(list);
5934                 switch (err) {
5935                 case 0:
5936                         ERROR("cannot access device, is mlx4_ib loaded?");
5937                         return -ENODEV;
5938                 case EINVAL:
5939                         ERROR("cannot use device, are drivers up to date?");
5940                         return -EINVAL;
5941                 }
5942                 assert(err > 0);
5943                 return -err;
5944         }
5945         ibv_dev = list[i];
5946
5947         DEBUG("device opened");
5948         if (ibv_query_device(attr_ctx, &device_attr))
5949                 goto error;
5950         INFO("%u port(s) detected", device_attr.phys_port_cnt);
5951
5952         if (mlx4_args(pci_dev->device.devargs, &conf)) {
5953                 ERROR("failed to process device arguments");
5954                 goto error;
5955         }
5956         /* Use all ports when none are defined */
5957         if (conf.active_ports == 0) {
5958                 for (i = 0; i < MLX4_PMD_MAX_PHYS_PORTS; i++)
5959                         conf.active_ports |= 1 << i;
5960         }
5961         for (i = 0; i < device_attr.phys_port_cnt; i++) {
5962                 uint32_t port = i + 1; /* ports are indexed from one */
5963                 uint32_t test = (1 << i);
5964                 struct ibv_context *ctx = NULL;
5965                 struct ibv_port_attr port_attr;
5966                 struct ibv_pd *pd = NULL;
5967                 struct priv *priv = NULL;
5968                 struct rte_eth_dev *eth_dev = NULL;
5969 #ifdef HAVE_EXP_QUERY_DEVICE
5970                 struct ibv_exp_device_attr exp_device_attr;
5971 #endif /* HAVE_EXP_QUERY_DEVICE */
5972                 struct ether_addr mac;
5973
5974                 /* If port is not active, skip. */
5975                 if (!(conf.active_ports & (1 << i)))
5976                         continue;
5977 #ifdef HAVE_EXP_QUERY_DEVICE
5978                 exp_device_attr.comp_mask = IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS;
5979 #ifdef RSS_SUPPORT
5980                 exp_device_attr.comp_mask |= IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ;
5981 #endif /* RSS_SUPPORT */
5982 #endif /* HAVE_EXP_QUERY_DEVICE */
5983
5984                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
5985
5986                 ctx = ibv_open_device(ibv_dev);
5987                 if (ctx == NULL)
5988                         goto port_error;
5989
5990                 /* Check port status. */
5991                 err = ibv_query_port(ctx, port, &port_attr);
5992                 if (err) {
5993                         ERROR("port query failed: %s", strerror(err));
5994                         goto port_error;
5995                 }
5996
5997                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
5998                         ERROR("port %d is not configured in Ethernet mode",
5999                               port);
6000                         goto port_error;
6001                 }
6002
6003                 if (port_attr.state != IBV_PORT_ACTIVE)
6004                         DEBUG("port %d is not active: \"%s\" (%d)",
6005                               port, ibv_port_state_str(port_attr.state),
6006                               port_attr.state);
6007
6008                 /* Allocate protection domain. */
6009                 pd = ibv_alloc_pd(ctx);
6010                 if (pd == NULL) {
6011                         ERROR("PD allocation failure");
6012                         err = ENOMEM;
6013                         goto port_error;
6014                 }
6015
6016                 mlx4_dev[idx].ports |= test;
6017
6018                 /* from rte_ethdev.c */
6019                 priv = rte_zmalloc("ethdev private structure",
6020                                    sizeof(*priv),
6021                                    RTE_CACHE_LINE_SIZE);
6022                 if (priv == NULL) {
6023                         ERROR("priv allocation failure");
6024                         err = ENOMEM;
6025                         goto port_error;
6026                 }
6027
6028                 priv->ctx = ctx;
6029                 priv->device_attr = device_attr;
6030                 priv->port = port;
6031                 priv->pd = pd;
6032                 priv->mtu = ETHER_MTU;
6033 #ifdef HAVE_EXP_QUERY_DEVICE
6034                 if (ibv_exp_query_device(ctx, &exp_device_attr)) {
6035                         ERROR("ibv_exp_query_device() failed");
6036                         goto port_error;
6037                 }
6038 #ifdef RSS_SUPPORT
6039                 if ((exp_device_attr.exp_device_cap_flags &
6040                      IBV_EXP_DEVICE_QPG) &&
6041                     (exp_device_attr.exp_device_cap_flags &
6042                      IBV_EXP_DEVICE_UD_RSS) &&
6043                     (exp_device_attr.comp_mask &
6044                      IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ) &&
6045                     (exp_device_attr.max_rss_tbl_sz > 0)) {
6046                         priv->hw_qpg = 1;
6047                         priv->hw_rss = 1;
6048                         priv->max_rss_tbl_sz = exp_device_attr.max_rss_tbl_sz;
6049                 } else {
6050                         priv->hw_qpg = 0;
6051                         priv->hw_rss = 0;
6052                         priv->max_rss_tbl_sz = 0;
6053                 }
6054                 priv->hw_tss = !!(exp_device_attr.exp_device_cap_flags &
6055                                   IBV_EXP_DEVICE_UD_TSS);
6056                 DEBUG("device flags: %s%s%s",
6057                       (priv->hw_qpg ? "IBV_DEVICE_QPG " : ""),
6058                       (priv->hw_tss ? "IBV_DEVICE_TSS " : ""),
6059                       (priv->hw_rss ? "IBV_DEVICE_RSS " : ""));
6060                 if (priv->hw_rss)
6061                         DEBUG("maximum RSS indirection table size: %u",
6062                               exp_device_attr.max_rss_tbl_sz);
6063 #endif /* RSS_SUPPORT */
6064
6065                 priv->hw_csum =
6066                         ((exp_device_attr.exp_device_cap_flags &
6067                           IBV_EXP_DEVICE_RX_CSUM_TCP_UDP_PKT) &&
6068                          (exp_device_attr.exp_device_cap_flags &
6069                           IBV_EXP_DEVICE_RX_CSUM_IP_PKT));
6070                 DEBUG("checksum offloading is %ssupported",
6071                       (priv->hw_csum ? "" : "not "));
6072
6073                 priv->hw_csum_l2tun = !!(exp_device_attr.exp_device_cap_flags &
6074                                          IBV_EXP_DEVICE_VXLAN_SUPPORT);
6075                 DEBUG("L2 tunnel checksum offloads are %ssupported",
6076                       (priv->hw_csum_l2tun ? "" : "not "));
6077
6078 #ifdef INLINE_RECV
6079                 priv->inl_recv_size = mlx4_getenv_int("MLX4_INLINE_RECV_SIZE");
6080
6081                 if (priv->inl_recv_size) {
6082                         exp_device_attr.comp_mask =
6083                                 IBV_EXP_DEVICE_ATTR_INLINE_RECV_SZ;
6084                         if (ibv_exp_query_device(ctx, &exp_device_attr)) {
6085                                 INFO("Couldn't query device for inline-receive"
6086                                      " capabilities.");
6087                                 priv->inl_recv_size = 0;
6088                         } else {
6089                                 if ((unsigned)exp_device_attr.inline_recv_sz <
6090                                     priv->inl_recv_size) {
6091                                         INFO("Max inline-receive (%d) <"
6092                                              " requested inline-receive (%u)",
6093                                              exp_device_attr.inline_recv_sz,
6094                                              priv->inl_recv_size);
6095                                         priv->inl_recv_size =
6096                                                 exp_device_attr.inline_recv_sz;
6097                                 }
6098                         }
6099                         INFO("Set inline receive size to %u",
6100                              priv->inl_recv_size);
6101                 }
6102 #endif /* INLINE_RECV */
6103 #endif /* HAVE_EXP_QUERY_DEVICE */
6104
6105                 (void)mlx4_getenv_int;
6106                 priv->vf = vf;
6107                 /* Configure the first MAC address by default. */
6108                 if (priv_get_mac(priv, &mac.addr_bytes)) {
6109                         ERROR("cannot get MAC address, is mlx4_en loaded?"
6110                               " (errno: %s)", strerror(errno));
6111                         goto port_error;
6112                 }
6113                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
6114                      priv->port,
6115                      mac.addr_bytes[0], mac.addr_bytes[1],
6116                      mac.addr_bytes[2], mac.addr_bytes[3],
6117                      mac.addr_bytes[4], mac.addr_bytes[5]);
6118                 /* Register MAC and broadcast addresses. */
6119                 claim_zero(priv_mac_addr_add(priv, 0,
6120                                              (const uint8_t (*)[ETHER_ADDR_LEN])
6121                                              mac.addr_bytes));
6122                 claim_zero(priv_mac_addr_add(priv, (elemof(priv->mac) - 1),
6123                                              &(const uint8_t [ETHER_ADDR_LEN])
6124                                              { "\xff\xff\xff\xff\xff\xff" }));
6125 #ifndef NDEBUG
6126                 {
6127                         char ifname[IF_NAMESIZE];
6128
6129                         if (priv_get_ifname(priv, &ifname) == 0)
6130                                 DEBUG("port %u ifname is \"%s\"",
6131                                       priv->port, ifname);
6132                         else
6133                                 DEBUG("port %u ifname is unknown", priv->port);
6134                 }
6135 #endif
6136                 /* Get actual MTU if possible. */
6137                 priv_get_mtu(priv, &priv->mtu);
6138                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
6139
6140                 /* from rte_ethdev.c */
6141                 {
6142                         char name[RTE_ETH_NAME_MAX_LEN];
6143
6144                         snprintf(name, sizeof(name), "%s port %u",
6145                                  ibv_get_device_name(ibv_dev), port);
6146                         eth_dev = rte_eth_dev_allocate(name);
6147                 }
6148                 if (eth_dev == NULL) {
6149                         ERROR("can not allocate rte ethdev");
6150                         err = ENOMEM;
6151                         goto port_error;
6152                 }
6153
6154                 /* Secondary processes have to use local storage for their
6155                  * private data as well as a copy of eth_dev->data, but this
6156                  * pointer must not be modified before burst functions are
6157                  * actually called. */
6158                 if (mlx4_is_secondary()) {
6159                         struct mlx4_secondary_data *sd =
6160                                 &mlx4_secondary_data[eth_dev->data->port_id];
6161
6162                         sd->primary_priv = eth_dev->data->dev_private;
6163                         if (sd->primary_priv == NULL) {
6164                                 ERROR("no private data for port %u",
6165                                       eth_dev->data->port_id);
6166                                 err = EINVAL;
6167                                 goto port_error;
6168                         }
6169                         sd->shared_dev_data = eth_dev->data;
6170                         rte_spinlock_init(&sd->lock);
6171                         memcpy(sd->data.name, sd->shared_dev_data->name,
6172                                sizeof(sd->data.name));
6173                         sd->data.dev_private = priv;
6174                         sd->data.rx_mbuf_alloc_failed = 0;
6175                         sd->data.mtu = ETHER_MTU;
6176                         sd->data.port_id = sd->shared_dev_data->port_id;
6177                         sd->data.mac_addrs = priv->mac;
6178                         eth_dev->tx_pkt_burst = mlx4_tx_burst_secondary_setup;
6179                         eth_dev->rx_pkt_burst = mlx4_rx_burst_secondary_setup;
6180                 } else {
6181                         eth_dev->data->dev_private = priv;
6182                         eth_dev->data->mac_addrs = priv->mac;
6183                 }
6184                 eth_dev->device = &pci_dev->device;
6185
6186                 rte_eth_copy_pci_info(eth_dev, pci_dev);
6187
6188                 eth_dev->device->driver = &mlx4_driver.driver;
6189
6190                 /*
6191                  * Copy and override interrupt handle to prevent it from
6192                  * being shared between all ethdev instances of a given PCI
6193                  * device. This is required to properly handle Rx interrupts
6194                  * on all ports.
6195                  */
6196                 priv->intr_handle_dev = *eth_dev->intr_handle;
6197                 eth_dev->intr_handle = &priv->intr_handle_dev;
6198
6199                 priv->dev = eth_dev;
6200                 eth_dev->dev_ops = &mlx4_dev_ops;
6201
6202                 /* Bring Ethernet device up. */
6203                 DEBUG("forcing Ethernet interface up");
6204                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
6205                 /* Update link status once if waiting for LSC. */
6206                 if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
6207                         mlx4_link_update(eth_dev, 0);
6208                 continue;
6209
6210 port_error:
6211                 rte_free(priv);
6212                 if (pd)
6213                         claim_zero(ibv_dealloc_pd(pd));
6214                 if (ctx)
6215                         claim_zero(ibv_close_device(ctx));
6216                 if (eth_dev)
6217                         rte_eth_dev_release_port(eth_dev);
6218                 break;
6219         }
6220
6221         /*
6222          * XXX if something went wrong in the loop above, there is a resource
6223          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
6224          * long as the dpdk does not provide a way to deallocate a ethdev and a
6225          * way to enumerate the registered ethdevs to free the previous ones.
6226          */
6227
6228         /* no port found, complain */
6229         if (!mlx4_dev[idx].ports) {
6230                 err = ENODEV;
6231                 goto error;
6232         }
6233
6234 error:
6235         if (attr_ctx)
6236                 claim_zero(ibv_close_device(attr_ctx));
6237         if (list)
6238                 ibv_free_device_list(list);
6239         assert(err >= 0);
6240         return -err;
6241 }
6242
6243 static const struct rte_pci_id mlx4_pci_id_map[] = {
6244         {
6245                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
6246                                PCI_DEVICE_ID_MELLANOX_CONNECTX3)
6247         },
6248         {
6249                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
6250                                PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO)
6251         },
6252         {
6253                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
6254                                PCI_DEVICE_ID_MELLANOX_CONNECTX3VF)
6255         },
6256         {
6257                 .vendor_id = 0
6258         }
6259 };
6260
6261 static struct rte_pci_driver mlx4_driver = {
6262         .driver = {
6263                 .name = MLX4_DRIVER_NAME
6264         },
6265         .id_table = mlx4_pci_id_map,
6266         .probe = mlx4_pci_probe,
6267         .drv_flags = RTE_PCI_DRV_INTR_LSC |
6268                      RTE_PCI_DRV_INTR_RMV,
6269 };
6270
6271 /**
6272  * Driver initialization routine.
6273  */
6274 RTE_INIT(rte_mlx4_pmd_init);
6275 static void
6276 rte_mlx4_pmd_init(void)
6277 {
6278         RTE_BUILD_BUG_ON(sizeof(wr_id_t) != sizeof(uint64_t));
6279         /*
6280          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
6281          * huge pages. Calling ibv_fork_init() during init allows
6282          * applications to use fork() safely for purposes other than
6283          * using this PMD, which is not supported in forked processes.
6284          */
6285         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
6286         ibv_fork_init();
6287         rte_pci_register(&mlx4_driver);
6288 }
6289
6290 RTE_PMD_EXPORT_NAME(net_mlx4, __COUNTER__);
6291 RTE_PMD_REGISTER_PCI_TABLE(net_mlx4, mlx4_pci_id_map);
6292 RTE_PMD_REGISTER_KMOD_DEP(net_mlx4,
6293         "* ib_uverbs & mlx4_en & mlx4_core & mlx4_ib");