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