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