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