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