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