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