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