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