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