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