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