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