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