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