net/mlx4: drop checksum offloads 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                 if (likely(segs == 1)) {
1262                         uintptr_t addr;
1263                         uint32_t length;
1264                         uint32_t lkey;
1265
1266                         /* Retrieve buffer information. */
1267                         addr = rte_pktmbuf_mtod(buf, uintptr_t);
1268                         length = DATA_LEN(buf);
1269                         /* Retrieve Memory Region key for this memory pool. */
1270                         lkey = txq_mp2mr(txq, txq_mb2mp(buf));
1271                         if (unlikely(lkey == (uint32_t)-1)) {
1272                                 /* MR does not exist. */
1273                                 DEBUG("%p: unable to get MP <-> MR"
1274                                       " association", (void *)txq);
1275                                 /* Clean up TX element. */
1276                                 elt->buf = NULL;
1277                                 goto stop;
1278                         }
1279                         /* Update element. */
1280                         elt->buf = buf;
1281                         if (txq->priv->vf)
1282                                 rte_prefetch0((volatile void *)
1283                                               (uintptr_t)addr);
1284                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1285                         /* Put packet into send queue. */
1286                         if (length <= txq->max_inline)
1287                                 err = txq->if_qp->send_pending_inline
1288                                         (txq->qp,
1289                                          (void *)addr,
1290                                          length,
1291                                          send_flags);
1292                         else
1293                                 err = txq->if_qp->send_pending
1294                                         (txq->qp,
1295                                          addr,
1296                                          length,
1297                                          lkey,
1298                                          send_flags);
1299                         if (unlikely(err))
1300                                 goto stop;
1301                         sent_size += length;
1302                 } else {
1303                         struct ibv_sge sges[MLX4_PMD_SGE_WR_N];
1304                         struct tx_burst_sg_ret ret;
1305
1306                         ret = tx_burst_sg(txq, segs, elt, buf, elts_head,
1307                                           &sges);
1308                         if (ret.length == (unsigned int)-1)
1309                                 goto stop;
1310                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1311                         /* Put SG list into send queue. */
1312                         err = txq->if_qp->send_pending_sg_list
1313                                 (txq->qp,
1314                                  sges,
1315                                  ret.num,
1316                                  send_flags);
1317                         if (unlikely(err))
1318                                 goto stop;
1319                         sent_size += ret.length;
1320                 }
1321                 elts_head = elts_head_next;
1322                 /* Increment sent bytes counter. */
1323                 txq->stats.obytes += sent_size;
1324         }
1325 stop:
1326         /* Take a shortcut if nothing must be sent. */
1327         if (unlikely(i == 0))
1328                 return 0;
1329         /* Increment sent packets counter. */
1330         txq->stats.opackets += i;
1331         /* Ring QP doorbell. */
1332         err = txq->if_qp->send_flush(txq->qp);
1333         if (unlikely(err)) {
1334                 /* A nonzero value is not supposed to be returned.
1335                  * Nothing can be done about it. */
1336                 DEBUG("%p: send_flush() failed with error %d",
1337                       (void *)txq, err);
1338         }
1339         txq->elts_head = elts_head;
1340         txq->elts_comp += elts_comp;
1341         txq->elts_comp_cd = elts_comp_cd;
1342         return i;
1343 }
1344
1345 /**
1346  * Configure a TX queue.
1347  *
1348  * @param dev
1349  *   Pointer to Ethernet device structure.
1350  * @param txq
1351  *   Pointer to TX queue structure.
1352  * @param desc
1353  *   Number of descriptors to configure in queue.
1354  * @param socket
1355  *   NUMA socket on which memory must be allocated.
1356  * @param[in] conf
1357  *   Thresholds parameters.
1358  *
1359  * @return
1360  *   0 on success, errno value on failure.
1361  */
1362 static int
1363 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
1364           unsigned int socket, const struct rte_eth_txconf *conf)
1365 {
1366         struct priv *priv = dev->data->dev_private;
1367         struct txq tmpl = {
1368                 .priv = priv,
1369                 .socket = socket
1370         };
1371         union {
1372                 struct ibv_exp_query_intf_params params;
1373                 struct ibv_exp_qp_init_attr init;
1374                 struct ibv_exp_res_domain_init_attr rd;
1375                 struct ibv_exp_cq_init_attr cq;
1376                 struct ibv_exp_qp_attr mod;
1377         } attr;
1378         enum ibv_exp_query_intf_status status;
1379         int ret = 0;
1380
1381         (void)conf; /* Thresholds configuration (ignored). */
1382         if (priv == NULL)
1383                 return EINVAL;
1384         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
1385                 ERROR("%p: invalid number of TX descriptors (must be a"
1386                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
1387                 return EINVAL;
1388         }
1389         desc /= MLX4_PMD_SGE_WR_N;
1390         /* MRs will be registered in mp2mr[] later. */
1391         attr.rd = (struct ibv_exp_res_domain_init_attr){
1392                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
1393                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
1394                 .thread_model = IBV_EXP_THREAD_SINGLE,
1395                 .msg_model = IBV_EXP_MSG_HIGH_BW,
1396         };
1397         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
1398         if (tmpl.rd == NULL) {
1399                 ret = ENOMEM;
1400                 ERROR("%p: RD creation failure: %s",
1401                       (void *)dev, strerror(ret));
1402                 goto error;
1403         }
1404         attr.cq = (struct ibv_exp_cq_init_attr){
1405                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
1406                 .res_domain = tmpl.rd,
1407         };
1408         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
1409         if (tmpl.cq == NULL) {
1410                 ret = ENOMEM;
1411                 ERROR("%p: CQ creation failure: %s",
1412                       (void *)dev, strerror(ret));
1413                 goto error;
1414         }
1415         DEBUG("priv->device_attr.max_qp_wr is %d",
1416               priv->device_attr.max_qp_wr);
1417         DEBUG("priv->device_attr.max_sge is %d",
1418               priv->device_attr.max_sge);
1419         attr.init = (struct ibv_exp_qp_init_attr){
1420                 /* CQ to be associated with the send queue. */
1421                 .send_cq = tmpl.cq,
1422                 /* CQ to be associated with the receive queue. */
1423                 .recv_cq = tmpl.cq,
1424                 .cap = {
1425                         /* Max number of outstanding WRs. */
1426                         .max_send_wr = ((priv->device_attr.max_qp_wr < desc) ?
1427                                         priv->device_attr.max_qp_wr :
1428                                         desc),
1429                         /* Max number of scatter/gather elements in a WR. */
1430                         .max_send_sge = ((priv->device_attr.max_sge <
1431                                           MLX4_PMD_SGE_WR_N) ?
1432                                          priv->device_attr.max_sge :
1433                                          MLX4_PMD_SGE_WR_N),
1434                         .max_inline_data = MLX4_PMD_MAX_INLINE,
1435                 },
1436                 .qp_type = IBV_QPT_RAW_PACKET,
1437                 /* Do *NOT* enable this, completions events are managed per
1438                  * TX burst. */
1439                 .sq_sig_all = 0,
1440                 .pd = priv->pd,
1441                 .res_domain = tmpl.rd,
1442                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
1443                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
1444         };
1445         tmpl.qp = ibv_exp_create_qp(priv->ctx, &attr.init);
1446         if (tmpl.qp == NULL) {
1447                 ret = (errno ? errno : EINVAL);
1448                 ERROR("%p: QP creation failure: %s",
1449                       (void *)dev, strerror(ret));
1450                 goto error;
1451         }
1452         /* ibv_create_qp() updates this value. */
1453         tmpl.max_inline = attr.init.cap.max_inline_data;
1454         attr.mod = (struct ibv_exp_qp_attr){
1455                 /* Move the QP to this state. */
1456                 .qp_state = IBV_QPS_INIT,
1457                 /* Primary port number. */
1458                 .port_num = priv->port
1459         };
1460         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod,
1461                                 (IBV_EXP_QP_STATE | IBV_EXP_QP_PORT));
1462         if (ret) {
1463                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1464                       (void *)dev, strerror(ret));
1465                 goto error;
1466         }
1467         ret = txq_alloc_elts(&tmpl, desc);
1468         if (ret) {
1469                 ERROR("%p: TXQ allocation failed: %s",
1470                       (void *)dev, strerror(ret));
1471                 goto error;
1472         }
1473         attr.mod = (struct ibv_exp_qp_attr){
1474                 .qp_state = IBV_QPS_RTR
1475         };
1476         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1477         if (ret) {
1478                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1479                       (void *)dev, strerror(ret));
1480                 goto error;
1481         }
1482         attr.mod.qp_state = IBV_QPS_RTS;
1483         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1484         if (ret) {
1485                 ERROR("%p: QP state to IBV_QPS_RTS failed: %s",
1486                       (void *)dev, strerror(ret));
1487                 goto error;
1488         }
1489         attr.params = (struct ibv_exp_query_intf_params){
1490                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1491                 .intf = IBV_EXP_INTF_CQ,
1492                 .obj = tmpl.cq,
1493         };
1494         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1495         if (tmpl.if_cq == NULL) {
1496                 ERROR("%p: CQ interface family query failed with status %d",
1497                       (void *)dev, status);
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_QP_BURST,
1503                 .obj = tmpl.qp,
1504 #ifdef HAVE_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK
1505                 /* MC loopback must be disabled when not using a VF. */
1506                 .family_flags =
1507                         (!priv->vf ?
1508                          IBV_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK :
1509                          0),
1510 #endif
1511         };
1512         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1513         if (tmpl.if_qp == NULL) {
1514                 ERROR("%p: QP interface family query failed with status %d",
1515                       (void *)dev, status);
1516                 goto error;
1517         }
1518         /* Clean up txq in case we're reinitializing it. */
1519         DEBUG("%p: cleaning-up old txq just in case", (void *)txq);
1520         txq_cleanup(txq);
1521         *txq = tmpl;
1522         DEBUG("%p: txq updated with %p", (void *)txq, (void *)&tmpl);
1523         /* Pre-register known mempools. */
1524         rte_mempool_walk(txq_mp2mr_iter, txq);
1525         assert(ret == 0);
1526         return 0;
1527 error:
1528         txq_cleanup(&tmpl);
1529         assert(ret > 0);
1530         return ret;
1531 }
1532
1533 /**
1534  * DPDK callback to configure a TX queue.
1535  *
1536  * @param dev
1537  *   Pointer to Ethernet device structure.
1538  * @param idx
1539  *   TX queue index.
1540  * @param desc
1541  *   Number of descriptors to configure in queue.
1542  * @param socket
1543  *   NUMA socket on which memory must be allocated.
1544  * @param[in] conf
1545  *   Thresholds parameters.
1546  *
1547  * @return
1548  *   0 on success, negative errno value on failure.
1549  */
1550 static int
1551 mlx4_tx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1552                     unsigned int socket, const struct rte_eth_txconf *conf)
1553 {
1554         struct priv *priv = dev->data->dev_private;
1555         struct txq *txq = (*priv->txqs)[idx];
1556         int ret;
1557
1558         priv_lock(priv);
1559         DEBUG("%p: configuring queue %u for %u descriptors",
1560               (void *)dev, idx, desc);
1561         if (idx >= priv->txqs_n) {
1562                 ERROR("%p: queue index out of range (%u >= %u)",
1563                       (void *)dev, idx, priv->txqs_n);
1564                 priv_unlock(priv);
1565                 return -EOVERFLOW;
1566         }
1567         if (txq != NULL) {
1568                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1569                       (void *)dev, idx, (void *)txq);
1570                 if (priv->started) {
1571                         priv_unlock(priv);
1572                         return -EEXIST;
1573                 }
1574                 (*priv->txqs)[idx] = NULL;
1575                 txq_cleanup(txq);
1576         } else {
1577                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0, socket);
1578                 if (txq == NULL) {
1579                         ERROR("%p: unable to allocate queue index %u",
1580                               (void *)dev, idx);
1581                         priv_unlock(priv);
1582                         return -ENOMEM;
1583                 }
1584         }
1585         ret = txq_setup(dev, txq, desc, socket, conf);
1586         if (ret)
1587                 rte_free(txq);
1588         else {
1589                 txq->stats.idx = idx;
1590                 DEBUG("%p: adding TX queue %p to list",
1591                       (void *)dev, (void *)txq);
1592                 (*priv->txqs)[idx] = txq;
1593                 /* Update send callback. */
1594                 dev->tx_pkt_burst = mlx4_tx_burst;
1595         }
1596         priv_unlock(priv);
1597         return -ret;
1598 }
1599
1600 /**
1601  * DPDK callback to release a TX queue.
1602  *
1603  * @param dpdk_txq
1604  *   Generic TX queue pointer.
1605  */
1606 static void
1607 mlx4_tx_queue_release(void *dpdk_txq)
1608 {
1609         struct txq *txq = (struct txq *)dpdk_txq;
1610         struct priv *priv;
1611         unsigned int i;
1612
1613         if (txq == NULL)
1614                 return;
1615         priv = txq->priv;
1616         priv_lock(priv);
1617         for (i = 0; (i != priv->txqs_n); ++i)
1618                 if ((*priv->txqs)[i] == txq) {
1619                         DEBUG("%p: removing TX queue %p from list",
1620                               (void *)priv->dev, (void *)txq);
1621                         (*priv->txqs)[i] = NULL;
1622                         break;
1623                 }
1624         txq_cleanup(txq);
1625         rte_free(txq);
1626         priv_unlock(priv);
1627 }
1628
1629 /* RX queues handling. */
1630
1631 /**
1632  * Allocate RX queue elements with scattered packets support.
1633  *
1634  * @param rxq
1635  *   Pointer to RX queue structure.
1636  * @param elts_n
1637  *   Number of elements to allocate.
1638  * @param[in] pool
1639  *   If not NULL, fetch buffers from this array instead of allocating them
1640  *   with rte_pktmbuf_alloc().
1641  *
1642  * @return
1643  *   0 on success, errno value on failure.
1644  */
1645 static int
1646 rxq_alloc_elts_sp(struct rxq *rxq, unsigned int elts_n,
1647                   struct rte_mbuf **pool)
1648 {
1649         unsigned int i;
1650         struct rxq_elt_sp (*elts)[elts_n] =
1651                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1652                                   rxq->socket);
1653         int ret = 0;
1654
1655         if (elts == NULL) {
1656                 ERROR("%p: can't allocate packets array", (void *)rxq);
1657                 ret = ENOMEM;
1658                 goto error;
1659         }
1660         /* For each WR (packet). */
1661         for (i = 0; (i != elts_n); ++i) {
1662                 unsigned int j;
1663                 struct rxq_elt_sp *elt = &(*elts)[i];
1664                 struct ibv_recv_wr *wr = &elt->wr;
1665                 struct ibv_sge (*sges)[(elemof(elt->sges))] = &elt->sges;
1666
1667                 /* These two arrays must have the same size. */
1668                 assert(elemof(elt->sges) == elemof(elt->bufs));
1669                 /* Configure WR. */
1670                 wr->wr_id = i;
1671                 wr->next = &(*elts)[(i + 1)].wr;
1672                 wr->sg_list = &(*sges)[0];
1673                 wr->num_sge = elemof(*sges);
1674                 /* For each SGE (segment). */
1675                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
1676                         struct ibv_sge *sge = &(*sges)[j];
1677                         struct rte_mbuf *buf;
1678
1679                         if (pool != NULL) {
1680                                 buf = *(pool++);
1681                                 assert(buf != NULL);
1682                                 rte_pktmbuf_reset(buf);
1683                         } else
1684                                 buf = rte_pktmbuf_alloc(rxq->mp);
1685                         if (buf == NULL) {
1686                                 assert(pool == NULL);
1687                                 ERROR("%p: empty mbuf pool", (void *)rxq);
1688                                 ret = ENOMEM;
1689                                 goto error;
1690                         }
1691                         elt->bufs[j] = buf;
1692                         /* Headroom is reserved by rte_pktmbuf_alloc(). */
1693                         assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1694                         /* Buffer is supposed to be empty. */
1695                         assert(rte_pktmbuf_data_len(buf) == 0);
1696                         assert(rte_pktmbuf_pkt_len(buf) == 0);
1697                         /* sge->addr must be able to store a pointer. */
1698                         assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1699                         if (j == 0) {
1700                                 /* The first SGE keeps its headroom. */
1701                                 sge->addr = rte_pktmbuf_mtod(buf, uintptr_t);
1702                                 sge->length = (buf->buf_len -
1703                                                RTE_PKTMBUF_HEADROOM);
1704                         } else {
1705                                 /* Subsequent SGEs lose theirs. */
1706                                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1707                                 SET_DATA_OFF(buf, 0);
1708                                 sge->addr = (uintptr_t)buf->buf_addr;
1709                                 sge->length = buf->buf_len;
1710                         }
1711                         sge->lkey = rxq->mr->lkey;
1712                         /* Redundant check for tailroom. */
1713                         assert(sge->length == rte_pktmbuf_tailroom(buf));
1714                 }
1715         }
1716         /* The last WR pointer must be NULL. */
1717         (*elts)[(i - 1)].wr.next = NULL;
1718         DEBUG("%p: allocated and configured %u WRs (%zu segments)",
1719               (void *)rxq, elts_n, (elts_n * elemof((*elts)[0].sges)));
1720         rxq->elts_n = elts_n;
1721         rxq->elts_head = 0;
1722         rxq->elts.sp = elts;
1723         assert(ret == 0);
1724         return 0;
1725 error:
1726         if (elts != NULL) {
1727                 assert(pool == NULL);
1728                 for (i = 0; (i != elemof(*elts)); ++i) {
1729                         unsigned int j;
1730                         struct rxq_elt_sp *elt = &(*elts)[i];
1731
1732                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
1733                                 struct rte_mbuf *buf = elt->bufs[j];
1734
1735                                 if (buf != NULL)
1736                                         rte_pktmbuf_free_seg(buf);
1737                         }
1738                 }
1739                 rte_free(elts);
1740         }
1741         DEBUG("%p: failed, freed everything", (void *)rxq);
1742         assert(ret > 0);
1743         return ret;
1744 }
1745
1746 /**
1747  * Free RX queue elements with scattered packets support.
1748  *
1749  * @param rxq
1750  *   Pointer to RX queue structure.
1751  */
1752 static void
1753 rxq_free_elts_sp(struct rxq *rxq)
1754 {
1755         unsigned int i;
1756         unsigned int elts_n = rxq->elts_n;
1757         struct rxq_elt_sp (*elts)[elts_n] = rxq->elts.sp;
1758
1759         DEBUG("%p: freeing WRs", (void *)rxq);
1760         rxq->elts_n = 0;
1761         rxq->elts.sp = NULL;
1762         if (elts == NULL)
1763                 return;
1764         for (i = 0; (i != elemof(*elts)); ++i) {
1765                 unsigned int j;
1766                 struct rxq_elt_sp *elt = &(*elts)[i];
1767
1768                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
1769                         struct rte_mbuf *buf = elt->bufs[j];
1770
1771                         if (buf != NULL)
1772                                 rte_pktmbuf_free_seg(buf);
1773                 }
1774         }
1775         rte_free(elts);
1776 }
1777
1778 /**
1779  * Allocate RX queue elements.
1780  *
1781  * @param rxq
1782  *   Pointer to RX queue structure.
1783  * @param elts_n
1784  *   Number of elements to allocate.
1785  * @param[in] pool
1786  *   If not NULL, fetch buffers from this array instead of allocating them
1787  *   with rte_pktmbuf_alloc().
1788  *
1789  * @return
1790  *   0 on success, errno value on failure.
1791  */
1792 static int
1793 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n, struct rte_mbuf **pool)
1794 {
1795         unsigned int i;
1796         struct rxq_elt (*elts)[elts_n] =
1797                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1798                                   rxq->socket);
1799         int ret = 0;
1800
1801         if (elts == NULL) {
1802                 ERROR("%p: can't allocate packets array", (void *)rxq);
1803                 ret = ENOMEM;
1804                 goto error;
1805         }
1806         /* For each WR (packet). */
1807         for (i = 0; (i != elts_n); ++i) {
1808                 struct rxq_elt *elt = &(*elts)[i];
1809                 struct ibv_recv_wr *wr = &elt->wr;
1810                 struct ibv_sge *sge = &(*elts)[i].sge;
1811                 struct rte_mbuf *buf;
1812
1813                 if (pool != NULL) {
1814                         buf = *(pool++);
1815                         assert(buf != NULL);
1816                         rte_pktmbuf_reset(buf);
1817                 } else
1818                         buf = rte_pktmbuf_alloc(rxq->mp);
1819                 if (buf == NULL) {
1820                         assert(pool == NULL);
1821                         ERROR("%p: empty mbuf pool", (void *)rxq);
1822                         ret = ENOMEM;
1823                         goto error;
1824                 }
1825                 /* Configure WR. Work request ID contains its own index in
1826                  * the elts array and the offset between SGE buffer header and
1827                  * its data. */
1828                 WR_ID(wr->wr_id).id = i;
1829                 WR_ID(wr->wr_id).offset =
1830                         (((uintptr_t)buf->buf_addr + RTE_PKTMBUF_HEADROOM) -
1831                          (uintptr_t)buf);
1832                 wr->next = &(*elts)[(i + 1)].wr;
1833                 wr->sg_list = sge;
1834                 wr->num_sge = 1;
1835                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
1836                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1837                 /* Buffer is supposed to be empty. */
1838                 assert(rte_pktmbuf_data_len(buf) == 0);
1839                 assert(rte_pktmbuf_pkt_len(buf) == 0);
1840                 /* sge->addr must be able to store a pointer. */
1841                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1842                 /* SGE keeps its headroom. */
1843                 sge->addr = (uintptr_t)
1844                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
1845                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
1846                 sge->lkey = rxq->mr->lkey;
1847                 /* Redundant check for tailroom. */
1848                 assert(sge->length == rte_pktmbuf_tailroom(buf));
1849                 /* Make sure elts index and SGE mbuf pointer can be deduced
1850                  * from WR ID. */
1851                 if ((WR_ID(wr->wr_id).id != i) ||
1852                     ((void *)((uintptr_t)sge->addr -
1853                         WR_ID(wr->wr_id).offset) != buf)) {
1854                         ERROR("%p: cannot store index and offset in WR ID",
1855                               (void *)rxq);
1856                         sge->addr = 0;
1857                         rte_pktmbuf_free(buf);
1858                         ret = EOVERFLOW;
1859                         goto error;
1860                 }
1861         }
1862         /* The last WR pointer must be NULL. */
1863         (*elts)[(i - 1)].wr.next = NULL;
1864         DEBUG("%p: allocated and configured %u single-segment WRs",
1865               (void *)rxq, elts_n);
1866         rxq->elts_n = elts_n;
1867         rxq->elts_head = 0;
1868         rxq->elts.no_sp = elts;
1869         assert(ret == 0);
1870         return 0;
1871 error:
1872         if (elts != NULL) {
1873                 assert(pool == NULL);
1874                 for (i = 0; (i != elemof(*elts)); ++i) {
1875                         struct rxq_elt *elt = &(*elts)[i];
1876                         struct rte_mbuf *buf;
1877
1878                         if (elt->sge.addr == 0)
1879                                 continue;
1880                         assert(WR_ID(elt->wr.wr_id).id == i);
1881                         buf = (void *)((uintptr_t)elt->sge.addr -
1882                                 WR_ID(elt->wr.wr_id).offset);
1883                         rte_pktmbuf_free_seg(buf);
1884                 }
1885                 rte_free(elts);
1886         }
1887         DEBUG("%p: failed, freed everything", (void *)rxq);
1888         assert(ret > 0);
1889         return ret;
1890 }
1891
1892 /**
1893  * Free RX queue elements.
1894  *
1895  * @param rxq
1896  *   Pointer to RX queue structure.
1897  */
1898 static void
1899 rxq_free_elts(struct rxq *rxq)
1900 {
1901         unsigned int i;
1902         unsigned int elts_n = rxq->elts_n;
1903         struct rxq_elt (*elts)[elts_n] = rxq->elts.no_sp;
1904
1905         DEBUG("%p: freeing WRs", (void *)rxq);
1906         rxq->elts_n = 0;
1907         rxq->elts.no_sp = NULL;
1908         if (elts == NULL)
1909                 return;
1910         for (i = 0; (i != elemof(*elts)); ++i) {
1911                 struct rxq_elt *elt = &(*elts)[i];
1912                 struct rte_mbuf *buf;
1913
1914                 if (elt->sge.addr == 0)
1915                         continue;
1916                 assert(WR_ID(elt->wr.wr_id).id == i);
1917                 buf = (void *)((uintptr_t)elt->sge.addr -
1918                         WR_ID(elt->wr.wr_id).offset);
1919                 rte_pktmbuf_free_seg(buf);
1920         }
1921         rte_free(elts);
1922 }
1923
1924 /**
1925  * Unregister a MAC address.
1926  *
1927  * @param priv
1928  *   Pointer to private structure.
1929  */
1930 static void
1931 priv_mac_addr_del(struct priv *priv)
1932 {
1933 #ifndef NDEBUG
1934         uint8_t (*mac)[ETHER_ADDR_LEN] = &priv->mac.addr_bytes;
1935 #endif
1936
1937         if (!priv->mac_flow)
1938                 return;
1939         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x",
1940               (void *)priv,
1941               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);
1942         claim_zero(ibv_destroy_flow(priv->mac_flow));
1943         priv->mac_flow = NULL;
1944 }
1945
1946 /**
1947  * Register a MAC address.
1948  *
1949  * The MAC address is registered in queue 0.
1950  *
1951  * @param priv
1952  *   Pointer to private structure.
1953  *
1954  * @return
1955  *   0 on success, errno value on failure.
1956  */
1957 static int
1958 priv_mac_addr_add(struct priv *priv)
1959 {
1960         uint8_t (*mac)[ETHER_ADDR_LEN] = &priv->mac.addr_bytes;
1961         struct rxq *rxq;
1962         struct ibv_flow *flow;
1963
1964         /* If device isn't started, this is all we need to do. */
1965         if (!priv->started)
1966                 return 0;
1967         if (priv->isolated)
1968                 return 0;
1969         if (*priv->rxqs && (*priv->rxqs)[0])
1970                 rxq = (*priv->rxqs)[0];
1971         else
1972                 return 0;
1973
1974         /* Allocate flow specification on the stack. */
1975         struct __attribute__((packed)) {
1976                 struct ibv_flow_attr attr;
1977                 struct ibv_flow_spec_eth spec;
1978         } data;
1979         struct ibv_flow_attr *attr = &data.attr;
1980         struct ibv_flow_spec_eth *spec = &data.spec;
1981
1982         if (priv->mac_flow)
1983                 priv_mac_addr_del(priv);
1984         /*
1985          * No padding must be inserted by the compiler between attr and spec.
1986          * This layout is expected by libibverbs.
1987          */
1988         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
1989         *attr = (struct ibv_flow_attr){
1990                 .type = IBV_FLOW_ATTR_NORMAL,
1991                 .priority = 3,
1992                 .num_of_specs = 1,
1993                 .port = priv->port,
1994                 .flags = 0
1995         };
1996         *spec = (struct ibv_flow_spec_eth){
1997                 .type = IBV_FLOW_SPEC_ETH,
1998                 .size = sizeof(*spec),
1999                 .val = {
2000                         .dst_mac = {
2001                                 (*mac)[0], (*mac)[1], (*mac)[2],
2002                                 (*mac)[3], (*mac)[4], (*mac)[5]
2003                         },
2004                 },
2005                 .mask = {
2006                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
2007                 }
2008         };
2009         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x",
2010               (void *)priv,
2011               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);
2012         /* Create related flow. */
2013         errno = 0;
2014         flow = ibv_create_flow(rxq->qp, attr);
2015         if (flow == NULL) {
2016                 /* It's not clear whether errno is always set in this case. */
2017                 ERROR("%p: flow configuration failed, errno=%d: %s",
2018                       (void *)rxq, errno,
2019                       (errno ? strerror(errno) : "Unknown error"));
2020                 if (errno)
2021                         return errno;
2022                 return EINVAL;
2023         }
2024         assert(priv->mac_flow == NULL);
2025         priv->mac_flow = flow;
2026         return 0;
2027 }
2028
2029 /**
2030  * Clean up a RX queue.
2031  *
2032  * Destroy objects, free allocated memory and reset the structure for reuse.
2033  *
2034  * @param rxq
2035  *   Pointer to RX queue structure.
2036  */
2037 static void
2038 rxq_cleanup(struct rxq *rxq)
2039 {
2040         struct ibv_exp_release_intf_params params;
2041
2042         DEBUG("cleaning up %p", (void *)rxq);
2043         if (rxq->sp)
2044                 rxq_free_elts_sp(rxq);
2045         else
2046                 rxq_free_elts(rxq);
2047         if (rxq->if_qp != NULL) {
2048                 assert(rxq->priv != NULL);
2049                 assert(rxq->priv->ctx != NULL);
2050                 assert(rxq->qp != NULL);
2051                 params = (struct ibv_exp_release_intf_params){
2052                         .comp_mask = 0,
2053                 };
2054                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
2055                                                 rxq->if_qp,
2056                                                 &params));
2057         }
2058         if (rxq->if_cq != NULL) {
2059                 assert(rxq->priv != NULL);
2060                 assert(rxq->priv->ctx != NULL);
2061                 assert(rxq->cq != 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_cq,
2067                                                 &params));
2068         }
2069         if (rxq->qp != NULL)
2070                 claim_zero(ibv_destroy_qp(rxq->qp));
2071         if (rxq->cq != NULL)
2072                 claim_zero(ibv_destroy_cq(rxq->cq));
2073         if (rxq->channel != NULL)
2074                 claim_zero(ibv_destroy_comp_channel(rxq->channel));
2075         if (rxq->rd != NULL) {
2076                 struct ibv_exp_destroy_res_domain_attr attr = {
2077                         .comp_mask = 0,
2078                 };
2079
2080                 assert(rxq->priv != NULL);
2081                 assert(rxq->priv->ctx != NULL);
2082                 claim_zero(ibv_exp_destroy_res_domain(rxq->priv->ctx,
2083                                                       rxq->rd,
2084                                                       &attr));
2085         }
2086         if (rxq->mr != NULL)
2087                 claim_zero(ibv_dereg_mr(rxq->mr));
2088         memset(rxq, 0, sizeof(*rxq));
2089 }
2090
2091 /**
2092  * Translate RX completion flags to packet type.
2093  *
2094  * @param flags
2095  *   RX completion flags returned by poll_length_flags().
2096  *
2097  * @note: fix mlx4_dev_supported_ptypes_get() if any change here.
2098  *
2099  * @return
2100  *   Packet type for struct rte_mbuf.
2101  */
2102 static inline uint32_t
2103 rxq_cq_to_pkt_type(uint32_t flags)
2104 {
2105         uint32_t pkt_type;
2106
2107         if (flags & IBV_EXP_CQ_RX_TUNNEL_PACKET)
2108                 pkt_type =
2109                         TRANSPOSE(flags,
2110                                   IBV_EXP_CQ_RX_OUTER_IPV4_PACKET,
2111                                   RTE_PTYPE_L3_IPV4_EXT_UNKNOWN) |
2112                         TRANSPOSE(flags,
2113                                   IBV_EXP_CQ_RX_OUTER_IPV6_PACKET,
2114                                   RTE_PTYPE_L3_IPV6_EXT_UNKNOWN) |
2115                         TRANSPOSE(flags,
2116                                   IBV_EXP_CQ_RX_IPV4_PACKET,
2117                                   RTE_PTYPE_INNER_L3_IPV4_EXT_UNKNOWN) |
2118                         TRANSPOSE(flags,
2119                                   IBV_EXP_CQ_RX_IPV6_PACKET,
2120                                   RTE_PTYPE_INNER_L3_IPV6_EXT_UNKNOWN);
2121         else
2122                 pkt_type =
2123                         TRANSPOSE(flags,
2124                                   IBV_EXP_CQ_RX_IPV4_PACKET,
2125                                   RTE_PTYPE_L3_IPV4_EXT_UNKNOWN) |
2126                         TRANSPOSE(flags,
2127                                   IBV_EXP_CQ_RX_IPV6_PACKET,
2128                                   RTE_PTYPE_L3_IPV6_EXT_UNKNOWN);
2129         return pkt_type;
2130 }
2131
2132 static uint16_t
2133 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n);
2134
2135 /**
2136  * DPDK callback for RX with scattered packets support.
2137  *
2138  * @param dpdk_rxq
2139  *   Generic pointer to RX queue structure.
2140  * @param[out] pkts
2141  *   Array to store received packets.
2142  * @param pkts_n
2143  *   Maximum number of packets in array.
2144  *
2145  * @return
2146  *   Number of packets successfully received (<= pkts_n).
2147  */
2148 static uint16_t
2149 mlx4_rx_burst_sp(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2150 {
2151         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2152         struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2153         const unsigned int elts_n = rxq->elts_n;
2154         unsigned int elts_head = rxq->elts_head;
2155         struct ibv_recv_wr head;
2156         struct ibv_recv_wr **next = &head.next;
2157         struct ibv_recv_wr *bad_wr;
2158         unsigned int i;
2159         unsigned int pkts_ret = 0;
2160         int ret;
2161
2162         if (unlikely(!rxq->sp))
2163                 return mlx4_rx_burst(dpdk_rxq, pkts, pkts_n);
2164         if (unlikely(elts == NULL)) /* See RTE_DEV_CMD_SET_MTU. */
2165                 return 0;
2166         for (i = 0; (i != pkts_n); ++i) {
2167                 struct rxq_elt_sp *elt = &(*elts)[elts_head];
2168                 struct ibv_recv_wr *wr = &elt->wr;
2169                 uint64_t wr_id = wr->wr_id;
2170                 unsigned int len;
2171                 unsigned int pkt_buf_len;
2172                 struct rte_mbuf *pkt_buf = NULL; /* Buffer returned in pkts. */
2173                 struct rte_mbuf **pkt_buf_next = &pkt_buf;
2174                 unsigned int seg_headroom = RTE_PKTMBUF_HEADROOM;
2175                 unsigned int j = 0;
2176                 uint32_t flags;
2177
2178                 /* Sanity checks. */
2179 #ifdef NDEBUG
2180                 (void)wr_id;
2181 #endif
2182                 assert(wr_id < rxq->elts_n);
2183                 assert(wr->sg_list == elt->sges);
2184                 assert(wr->num_sge == elemof(elt->sges));
2185                 assert(elts_head < rxq->elts_n);
2186                 assert(rxq->elts_head < rxq->elts_n);
2187                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
2188                                                     &flags);
2189                 if (unlikely(ret < 0)) {
2190                         struct ibv_wc wc;
2191                         int wcs_n;
2192
2193                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
2194                               (void *)rxq, ret);
2195                         /* ibv_poll_cq() must be used in case of failure. */
2196                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
2197                         if (unlikely(wcs_n == 0))
2198                                 break;
2199                         if (unlikely(wcs_n < 0)) {
2200                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
2201                                       (void *)rxq, wcs_n);
2202                                 break;
2203                         }
2204                         assert(wcs_n == 1);
2205                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
2206                                 /* Whatever, just repost the offending WR. */
2207                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
2208                                       " completion status (%d): %s",
2209                                       (void *)rxq, wc.wr_id, wc.status,
2210                                       ibv_wc_status_str(wc.status));
2211                                 /* Increment dropped packets counter. */
2212                                 ++rxq->stats.idropped;
2213                                 /* Link completed WRs together for repost. */
2214                                 *next = wr;
2215                                 next = &wr->next;
2216                                 goto repost;
2217                         }
2218                         ret = wc.byte_len;
2219                 }
2220                 if (ret == 0)
2221                         break;
2222                 len = ret;
2223                 pkt_buf_len = len;
2224                 /* Link completed WRs together for repost. */
2225                 *next = wr;
2226                 next = &wr->next;
2227                 /*
2228                  * Replace spent segments with new ones, concatenate and
2229                  * return them as pkt_buf.
2230                  */
2231                 while (1) {
2232                         struct ibv_sge *sge = &elt->sges[j];
2233                         struct rte_mbuf *seg = elt->bufs[j];
2234                         struct rte_mbuf *rep;
2235                         unsigned int seg_tailroom;
2236
2237                         /*
2238                          * Fetch initial bytes of packet descriptor into a
2239                          * cacheline while allocating rep.
2240                          */
2241                         rte_prefetch0(seg);
2242                         rep = rte_mbuf_raw_alloc(rxq->mp);
2243                         if (unlikely(rep == NULL)) {
2244                                 /*
2245                                  * Unable to allocate a replacement mbuf,
2246                                  * repost WR.
2247                                  */
2248                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ":"
2249                                       " can't allocate a new mbuf",
2250                                       (void *)rxq, wr_id);
2251                                 if (pkt_buf != NULL) {
2252                                         *pkt_buf_next = NULL;
2253                                         rte_pktmbuf_free(pkt_buf);
2254                                 }
2255                                 /* Increase out of memory counters. */
2256                                 ++rxq->stats.rx_nombuf;
2257                                 ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2258                                 goto repost;
2259                         }
2260 #ifndef NDEBUG
2261                         /* Poison user-modifiable fields in rep. */
2262                         NEXT(rep) = (void *)((uintptr_t)-1);
2263                         SET_DATA_OFF(rep, 0xdead);
2264                         DATA_LEN(rep) = 0xd00d;
2265                         PKT_LEN(rep) = 0xdeadd00d;
2266                         NB_SEGS(rep) = 0x2a;
2267                         PORT(rep) = 0x2a;
2268                         rep->ol_flags = -1;
2269                         /*
2270                          * Clear special flags in mbuf to avoid
2271                          * crashing while freeing.
2272                          */
2273                         rep->ol_flags &=
2274                                 ~(uint64_t)(IND_ATTACHED_MBUF |
2275                                             CTRL_MBUF_FLAG);
2276 #endif
2277                         assert(rep->buf_len == seg->buf_len);
2278                         /* Reconfigure sge to use rep instead of seg. */
2279                         assert(sge->lkey == rxq->mr->lkey);
2280                         sge->addr = ((uintptr_t)rep->buf_addr + seg_headroom);
2281                         elt->bufs[j] = rep;
2282                         ++j;
2283                         /* Update pkt_buf if it's the first segment, or link
2284                          * seg to the previous one and update pkt_buf_next. */
2285                         *pkt_buf_next = seg;
2286                         pkt_buf_next = &NEXT(seg);
2287                         /* Update seg information. */
2288                         seg_tailroom = (seg->buf_len - seg_headroom);
2289                         assert(sge->length == seg_tailroom);
2290                         SET_DATA_OFF(seg, seg_headroom);
2291                         if (likely(len <= seg_tailroom)) {
2292                                 /* Last segment. */
2293                                 DATA_LEN(seg) = len;
2294                                 PKT_LEN(seg) = len;
2295                                 /* Sanity check. */
2296                                 assert(rte_pktmbuf_headroom(seg) ==
2297                                        seg_headroom);
2298                                 assert(rte_pktmbuf_tailroom(seg) ==
2299                                        (seg_tailroom - len));
2300                                 break;
2301                         }
2302                         DATA_LEN(seg) = seg_tailroom;
2303                         PKT_LEN(seg) = seg_tailroom;
2304                         /* Sanity check. */
2305                         assert(rte_pktmbuf_headroom(seg) == seg_headroom);
2306                         assert(rte_pktmbuf_tailroom(seg) == 0);
2307                         /* Fix len and clear headroom for next segments. */
2308                         len -= seg_tailroom;
2309                         seg_headroom = 0;
2310                 }
2311                 /* Update head and tail segments. */
2312                 *pkt_buf_next = NULL;
2313                 assert(pkt_buf != NULL);
2314                 assert(j != 0);
2315                 NB_SEGS(pkt_buf) = j;
2316                 PORT(pkt_buf) = rxq->port_id;
2317                 PKT_LEN(pkt_buf) = pkt_buf_len;
2318                 pkt_buf->packet_type = rxq_cq_to_pkt_type(flags);
2319                 pkt_buf->ol_flags = 0;
2320
2321                 /* Return packet. */
2322                 *(pkts++) = pkt_buf;
2323                 ++pkts_ret;
2324                 /* Increase bytes counter. */
2325                 rxq->stats.ibytes += pkt_buf_len;
2326 repost:
2327                 if (++elts_head >= elts_n)
2328                         elts_head = 0;
2329                 continue;
2330         }
2331         if (unlikely(i == 0))
2332                 return 0;
2333         *next = NULL;
2334         /* Repost WRs. */
2335         ret = ibv_post_recv(rxq->qp, head.next, &bad_wr);
2336         if (unlikely(ret)) {
2337                 /* Inability to repost WRs is fatal. */
2338                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
2339                       (void *)rxq->priv,
2340                       (void *)bad_wr,
2341                       strerror(ret));
2342                 abort();
2343         }
2344         rxq->elts_head = elts_head;
2345         /* Increase packets counter. */
2346         rxq->stats.ipackets += pkts_ret;
2347         return pkts_ret;
2348 }
2349
2350 /**
2351  * DPDK callback for RX.
2352  *
2353  * The following function is the same as mlx4_rx_burst_sp(), except it doesn't
2354  * manage scattered packets. Improves performance when MRU is lower than the
2355  * size of the first segment.
2356  *
2357  * @param dpdk_rxq
2358  *   Generic pointer to RX queue structure.
2359  * @param[out] pkts
2360  *   Array to store received packets.
2361  * @param pkts_n
2362  *   Maximum number of packets in array.
2363  *
2364  * @return
2365  *   Number of packets successfully received (<= pkts_n).
2366  */
2367 static uint16_t
2368 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2369 {
2370         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2371         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
2372         const unsigned int elts_n = rxq->elts_n;
2373         unsigned int elts_head = rxq->elts_head;
2374         struct ibv_sge sges[pkts_n];
2375         unsigned int i;
2376         unsigned int pkts_ret = 0;
2377         int ret;
2378
2379         if (unlikely(rxq->sp))
2380                 return mlx4_rx_burst_sp(dpdk_rxq, pkts, pkts_n);
2381         for (i = 0; (i != pkts_n); ++i) {
2382                 struct rxq_elt *elt = &(*elts)[elts_head];
2383                 struct ibv_recv_wr *wr = &elt->wr;
2384                 uint64_t wr_id = wr->wr_id;
2385                 unsigned int len;
2386                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
2387                         WR_ID(wr_id).offset);
2388                 struct rte_mbuf *rep;
2389                 uint32_t flags;
2390
2391                 /* Sanity checks. */
2392                 assert(WR_ID(wr_id).id < rxq->elts_n);
2393                 assert(wr->sg_list == &elt->sge);
2394                 assert(wr->num_sge == 1);
2395                 assert(elts_head < rxq->elts_n);
2396                 assert(rxq->elts_head < rxq->elts_n);
2397                 /*
2398                  * Fetch initial bytes of packet descriptor into a
2399                  * cacheline while allocating rep.
2400                  */
2401                 rte_mbuf_prefetch_part1(seg);
2402                 rte_mbuf_prefetch_part2(seg);
2403                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
2404                                                     &flags);
2405                 if (unlikely(ret < 0)) {
2406                         struct ibv_wc wc;
2407                         int wcs_n;
2408
2409                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
2410                               (void *)rxq, ret);
2411                         /* ibv_poll_cq() must be used in case of failure. */
2412                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
2413                         if (unlikely(wcs_n == 0))
2414                                 break;
2415                         if (unlikely(wcs_n < 0)) {
2416                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
2417                                       (void *)rxq, wcs_n);
2418                                 break;
2419                         }
2420                         assert(wcs_n == 1);
2421                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
2422                                 /* Whatever, just repost the offending WR. */
2423                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
2424                                       " completion status (%d): %s",
2425                                       (void *)rxq, wc.wr_id, wc.status,
2426                                       ibv_wc_status_str(wc.status));
2427                                 /* Increment dropped packets counter. */
2428                                 ++rxq->stats.idropped;
2429                                 /* Add SGE to array for repost. */
2430                                 sges[i] = elt->sge;
2431                                 goto repost;
2432                         }
2433                         ret = wc.byte_len;
2434                 }
2435                 if (ret == 0)
2436                         break;
2437                 len = ret;
2438                 rep = rte_mbuf_raw_alloc(rxq->mp);
2439                 if (unlikely(rep == NULL)) {
2440                         /*
2441                          * Unable to allocate a replacement mbuf,
2442                          * repost WR.
2443                          */
2444                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
2445                               " can't allocate a new mbuf",
2446                               (void *)rxq, WR_ID(wr_id).id);
2447                         /* Increase out of memory counters. */
2448                         ++rxq->stats.rx_nombuf;
2449                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2450                         /* Add SGE to array for repost. */
2451                         sges[i] = elt->sge;
2452                         goto repost;
2453                 }
2454
2455                 /* Reconfigure sge to use rep instead of seg. */
2456                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
2457                 assert(elt->sge.lkey == rxq->mr->lkey);
2458                 WR_ID(wr->wr_id).offset =
2459                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
2460                          (uintptr_t)rep);
2461                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
2462
2463                 /* Add SGE to array for repost. */
2464                 sges[i] = elt->sge;
2465
2466                 /* Update seg information. */
2467                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
2468                 NB_SEGS(seg) = 1;
2469                 PORT(seg) = rxq->port_id;
2470                 NEXT(seg) = NULL;
2471                 PKT_LEN(seg) = len;
2472                 DATA_LEN(seg) = len;
2473                 seg->packet_type = rxq_cq_to_pkt_type(flags);
2474                 seg->ol_flags = 0;
2475
2476                 /* Return packet. */
2477                 *(pkts++) = seg;
2478                 ++pkts_ret;
2479                 /* Increase bytes counter. */
2480                 rxq->stats.ibytes += len;
2481 repost:
2482                 if (++elts_head >= elts_n)
2483                         elts_head = 0;
2484                 continue;
2485         }
2486         if (unlikely(i == 0))
2487                 return 0;
2488         /* Repost WRs. */
2489         ret = rxq->if_qp->recv_burst(rxq->qp, sges, i);
2490         if (unlikely(ret)) {
2491                 /* Inability to repost WRs is fatal. */
2492                 DEBUG("%p: recv_burst(): failed (ret=%d)",
2493                       (void *)rxq->priv,
2494                       ret);
2495                 abort();
2496         }
2497         rxq->elts_head = elts_head;
2498         /* Increase packets counter. */
2499         rxq->stats.ipackets += pkts_ret;
2500         return pkts_ret;
2501 }
2502
2503 /**
2504  * Allocate a Queue Pair.
2505  * Optionally setup inline receive if supported.
2506  *
2507  * @param priv
2508  *   Pointer to private structure.
2509  * @param cq
2510  *   Completion queue to associate with QP.
2511  * @param desc
2512  *   Number of descriptors in QP (hint only).
2513  *
2514  * @return
2515  *   QP pointer or NULL in case of error.
2516  */
2517 static struct ibv_qp *
2518 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
2519              struct ibv_exp_res_domain *rd)
2520 {
2521         struct ibv_exp_qp_init_attr attr = {
2522                 /* CQ to be associated with the send queue. */
2523                 .send_cq = cq,
2524                 /* CQ to be associated with the receive queue. */
2525                 .recv_cq = cq,
2526                 .cap = {
2527                         /* Max number of outstanding WRs. */
2528                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2529                                         priv->device_attr.max_qp_wr :
2530                                         desc),
2531                         /* Max number of scatter/gather elements in a WR. */
2532                         .max_recv_sge = ((priv->device_attr.max_sge <
2533                                           MLX4_PMD_SGE_WR_N) ?
2534                                          priv->device_attr.max_sge :
2535                                          MLX4_PMD_SGE_WR_N),
2536                 },
2537                 .qp_type = IBV_QPT_RAW_PACKET,
2538                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
2539                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
2540                 .pd = priv->pd,
2541                 .res_domain = rd,
2542         };
2543
2544         attr.max_inl_recv = priv->inl_recv_size,
2545         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
2546         return ibv_exp_create_qp(priv->ctx, &attr);
2547 }
2548
2549 /**
2550  * Reconfigure a RX queue with new parameters.
2551  *
2552  * rxq_rehash() does not allocate mbufs, which, if not done from the right
2553  * thread (such as a control thread), may corrupt the pool.
2554  * In case of failure, the queue is left untouched.
2555  *
2556  * @param dev
2557  *   Pointer to Ethernet device structure.
2558  * @param rxq
2559  *   RX queue pointer.
2560  *
2561  * @return
2562  *   0 on success, errno value on failure.
2563  */
2564 static int
2565 rxq_rehash(struct rte_eth_dev *dev, struct rxq *rxq)
2566 {
2567         struct priv *priv = rxq->priv;
2568         struct rxq tmpl = *rxq;
2569         unsigned int mbuf_n;
2570         unsigned int desc_n;
2571         struct rte_mbuf **pool;
2572         unsigned int i, k;
2573         struct ibv_exp_qp_attr mod;
2574         struct ibv_recv_wr *bad_wr;
2575         unsigned int mb_len;
2576         int err;
2577
2578         mb_len = rte_pktmbuf_data_room_size(rxq->mp);
2579         DEBUG("%p: rehashing queue %p", (void *)dev, (void *)rxq);
2580         /* Number of descriptors and mbufs currently allocated. */
2581         desc_n = (tmpl.elts_n * (tmpl.sp ? MLX4_PMD_SGE_WR_N : 1));
2582         mbuf_n = desc_n;
2583         /* Enable scattered packets support for this queue if necessary. */
2584         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
2585         if (dev->data->dev_conf.rxmode.enable_scatter &&
2586             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
2587              (mb_len - RTE_PKTMBUF_HEADROOM))) {
2588                 tmpl.sp = 1;
2589                 desc_n /= MLX4_PMD_SGE_WR_N;
2590         } else
2591                 tmpl.sp = 0;
2592         DEBUG("%p: %s scattered packets support (%u WRs)",
2593               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc_n);
2594         /* If scatter mode is the same as before, nothing to do. */
2595         if (tmpl.sp == rxq->sp) {
2596                 DEBUG("%p: nothing to do", (void *)dev);
2597                 return 0;
2598         }
2599         /* From now on, any failure will render the queue unusable.
2600          * Reinitialize QP. */
2601         mod = (struct ibv_exp_qp_attr){ .qp_state = IBV_QPS_RESET };
2602         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
2603         if (err) {
2604                 ERROR("%p: cannot reset QP: %s", (void *)dev, strerror(err));
2605                 assert(err > 0);
2606                 return err;
2607         }
2608         err = ibv_resize_cq(tmpl.cq, desc_n);
2609         if (err) {
2610                 ERROR("%p: cannot resize CQ: %s", (void *)dev, strerror(err));
2611                 assert(err > 0);
2612                 return err;
2613         }
2614         mod = (struct ibv_exp_qp_attr){
2615                 /* Move the QP to this state. */
2616                 .qp_state = IBV_QPS_INIT,
2617                 /* Primary port number. */
2618                 .port_num = priv->port
2619         };
2620         err = ibv_exp_modify_qp(tmpl.qp, &mod,
2621                                 IBV_EXP_QP_STATE |
2622                                 IBV_EXP_QP_PORT);
2623         if (err) {
2624                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
2625                       (void *)dev, strerror(err));
2626                 assert(err > 0);
2627                 return err;
2628         };
2629         /* Allocate pool. */
2630         pool = rte_malloc(__func__, (mbuf_n * sizeof(*pool)), 0);
2631         if (pool == NULL) {
2632                 ERROR("%p: cannot allocate memory", (void *)dev);
2633                 return ENOBUFS;
2634         }
2635         /* Snatch mbufs from original queue. */
2636         k = 0;
2637         if (rxq->sp) {
2638                 struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2639
2640                 for (i = 0; (i != elemof(*elts)); ++i) {
2641                         struct rxq_elt_sp *elt = &(*elts)[i];
2642                         unsigned int j;
2643
2644                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
2645                                 assert(elt->bufs[j] != NULL);
2646                                 pool[k++] = elt->bufs[j];
2647                         }
2648                 }
2649         } else {
2650                 struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
2651
2652                 for (i = 0; (i != elemof(*elts)); ++i) {
2653                         struct rxq_elt *elt = &(*elts)[i];
2654                         struct rte_mbuf *buf = (void *)
2655                                 ((uintptr_t)elt->sge.addr -
2656                                  WR_ID(elt->wr.wr_id).offset);
2657
2658                         assert(WR_ID(elt->wr.wr_id).id == i);
2659                         pool[k++] = buf;
2660                 }
2661         }
2662         assert(k == mbuf_n);
2663         tmpl.elts_n = 0;
2664         tmpl.elts.sp = NULL;
2665         assert((void *)&tmpl.elts.sp == (void *)&tmpl.elts.no_sp);
2666         err = ((tmpl.sp) ?
2667                rxq_alloc_elts_sp(&tmpl, desc_n, pool) :
2668                rxq_alloc_elts(&tmpl, desc_n, pool));
2669         if (err) {
2670                 ERROR("%p: cannot reallocate WRs, aborting", (void *)dev);
2671                 rte_free(pool);
2672                 assert(err > 0);
2673                 return err;
2674         }
2675         assert(tmpl.elts_n == desc_n);
2676         assert(tmpl.elts.sp != NULL);
2677         rte_free(pool);
2678         /* Clean up original data. */
2679         rxq->elts_n = 0;
2680         rte_free(rxq->elts.sp);
2681         rxq->elts.sp = NULL;
2682         /* Post WRs. */
2683         err = ibv_post_recv(tmpl.qp,
2684                             (tmpl.sp ?
2685                              &(*tmpl.elts.sp)[0].wr :
2686                              &(*tmpl.elts.no_sp)[0].wr),
2687                             &bad_wr);
2688         if (err) {
2689                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
2690                       (void *)dev,
2691                       (void *)bad_wr,
2692                       strerror(err));
2693                 goto skip_rtr;
2694         }
2695         mod = (struct ibv_exp_qp_attr){
2696                 .qp_state = IBV_QPS_RTR
2697         };
2698         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
2699         if (err)
2700                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
2701                       (void *)dev, strerror(err));
2702 skip_rtr:
2703         *rxq = tmpl;
2704         assert(err >= 0);
2705         return err;
2706 }
2707
2708 /**
2709  * Configure a RX queue.
2710  *
2711  * @param dev
2712  *   Pointer to Ethernet device structure.
2713  * @param rxq
2714  *   Pointer to RX queue structure.
2715  * @param desc
2716  *   Number of descriptors to configure in queue.
2717  * @param socket
2718  *   NUMA socket on which memory must be allocated.
2719  * @param[in] conf
2720  *   Thresholds parameters.
2721  * @param mp
2722  *   Memory pool for buffer allocations.
2723  *
2724  * @return
2725  *   0 on success, errno value on failure.
2726  */
2727 static int
2728 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
2729           unsigned int socket, const struct rte_eth_rxconf *conf,
2730           struct rte_mempool *mp)
2731 {
2732         struct priv *priv = dev->data->dev_private;
2733         struct rxq tmpl = {
2734                 .priv = priv,
2735                 .mp = mp,
2736                 .socket = socket
2737         };
2738         struct ibv_exp_qp_attr mod;
2739         union {
2740                 struct ibv_exp_query_intf_params params;
2741                 struct ibv_exp_cq_init_attr cq;
2742                 struct ibv_exp_res_domain_init_attr rd;
2743         } attr;
2744         enum ibv_exp_query_intf_status status;
2745         struct ibv_recv_wr *bad_wr;
2746         unsigned int mb_len;
2747         int ret = 0;
2748
2749         (void)conf; /* Thresholds configuration (ignored). */
2750         mb_len = rte_pktmbuf_data_room_size(mp);
2751         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
2752                 ERROR("%p: invalid number of RX descriptors (must be a"
2753                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
2754                 return EINVAL;
2755         }
2756         /* Enable scattered packets support for this queue if necessary. */
2757         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
2758         if (dev->data->dev_conf.rxmode.max_rx_pkt_len <=
2759             (mb_len - RTE_PKTMBUF_HEADROOM)) {
2760                 tmpl.sp = 0;
2761         } else if (dev->data->dev_conf.rxmode.enable_scatter) {
2762                 tmpl.sp = 1;
2763                 desc /= MLX4_PMD_SGE_WR_N;
2764         } else {
2765                 WARN("%p: the requested maximum Rx packet size (%u) is"
2766                      " larger than a single mbuf (%u) and scattered"
2767                      " mode has not been requested",
2768                      (void *)dev,
2769                      dev->data->dev_conf.rxmode.max_rx_pkt_len,
2770                      mb_len - RTE_PKTMBUF_HEADROOM);
2771         }
2772         DEBUG("%p: %s scattered packets support (%u WRs)",
2773               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
2774         /* Use the entire RX mempool as the memory region. */
2775         tmpl.mr = mlx4_mp2mr(priv->pd, mp);
2776         if (tmpl.mr == NULL) {
2777                 ret = EINVAL;
2778                 ERROR("%p: MR creation failure: %s",
2779                       (void *)dev, strerror(ret));
2780                 goto error;
2781         }
2782         attr.rd = (struct ibv_exp_res_domain_init_attr){
2783                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
2784                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
2785                 .thread_model = IBV_EXP_THREAD_SINGLE,
2786                 .msg_model = IBV_EXP_MSG_HIGH_BW,
2787         };
2788         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
2789         if (tmpl.rd == NULL) {
2790                 ret = ENOMEM;
2791                 ERROR("%p: RD creation failure: %s",
2792                       (void *)dev, strerror(ret));
2793                 goto error;
2794         }
2795         if (dev->data->dev_conf.intr_conf.rxq) {
2796                 tmpl.channel = ibv_create_comp_channel(priv->ctx);
2797                 if (tmpl.channel == NULL) {
2798                         ret = ENOMEM;
2799                         ERROR("%p: Rx interrupt completion channel creation"
2800                               " failure: %s",
2801                               (void *)dev, strerror(ret));
2802                         goto error;
2803                 }
2804         }
2805         attr.cq = (struct ibv_exp_cq_init_attr){
2806                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
2807                 .res_domain = tmpl.rd,
2808         };
2809         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, tmpl.channel, 0,
2810                                     &attr.cq);
2811         if (tmpl.cq == NULL) {
2812                 ret = ENOMEM;
2813                 ERROR("%p: CQ creation failure: %s",
2814                       (void *)dev, strerror(ret));
2815                 goto error;
2816         }
2817         DEBUG("priv->device_attr.max_qp_wr is %d",
2818               priv->device_attr.max_qp_wr);
2819         DEBUG("priv->device_attr.max_sge is %d",
2820               priv->device_attr.max_sge);
2821         tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc, tmpl.rd);
2822         if (tmpl.qp == NULL) {
2823                 ret = (errno ? errno : EINVAL);
2824                 ERROR("%p: QP creation failure: %s",
2825                       (void *)dev, strerror(ret));
2826                 goto error;
2827         }
2828         mod = (struct ibv_exp_qp_attr){
2829                 /* Move the QP to this state. */
2830                 .qp_state = IBV_QPS_INIT,
2831                 /* Primary port number. */
2832                 .port_num = priv->port
2833         };
2834         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
2835                                 IBV_EXP_QP_STATE |
2836                                 IBV_EXP_QP_PORT);
2837         if (ret) {
2838                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
2839                       (void *)dev, strerror(ret));
2840                 goto error;
2841         }
2842         if (tmpl.sp)
2843                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
2844         else
2845                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
2846         if (ret) {
2847                 ERROR("%p: RXQ allocation failed: %s",
2848                       (void *)dev, strerror(ret));
2849                 goto error;
2850         }
2851         ret = ibv_post_recv(tmpl.qp,
2852                             (tmpl.sp ?
2853                              &(*tmpl.elts.sp)[0].wr :
2854                              &(*tmpl.elts.no_sp)[0].wr),
2855                             &bad_wr);
2856         if (ret) {
2857                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
2858                       (void *)dev,
2859                       (void *)bad_wr,
2860                       strerror(ret));
2861                 goto error;
2862         }
2863         mod = (struct ibv_exp_qp_attr){
2864                 .qp_state = IBV_QPS_RTR
2865         };
2866         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
2867         if (ret) {
2868                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
2869                       (void *)dev, strerror(ret));
2870                 goto error;
2871         }
2872         /* Save port ID. */
2873         tmpl.port_id = dev->data->port_id;
2874         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
2875         attr.params = (struct ibv_exp_query_intf_params){
2876                 .intf_scope = IBV_EXP_INTF_GLOBAL,
2877                 .intf = IBV_EXP_INTF_CQ,
2878                 .obj = tmpl.cq,
2879         };
2880         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
2881         if (tmpl.if_cq == NULL) {
2882                 ERROR("%p: CQ interface family query failed with status %d",
2883                       (void *)dev, status);
2884                 goto error;
2885         }
2886         attr.params = (struct ibv_exp_query_intf_params){
2887                 .intf_scope = IBV_EXP_INTF_GLOBAL,
2888                 .intf = IBV_EXP_INTF_QP_BURST,
2889                 .obj = tmpl.qp,
2890         };
2891         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
2892         if (tmpl.if_qp == NULL) {
2893                 ERROR("%p: QP interface family query failed with status %d",
2894                       (void *)dev, status);
2895                 goto error;
2896         }
2897         /* Clean up rxq in case we're reinitializing it. */
2898         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
2899         rxq_cleanup(rxq);
2900         *rxq = tmpl;
2901         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
2902         assert(ret == 0);
2903         return 0;
2904 error:
2905         rxq_cleanup(&tmpl);
2906         assert(ret > 0);
2907         return ret;
2908 }
2909
2910 /**
2911  * DPDK callback to configure a RX queue.
2912  *
2913  * @param dev
2914  *   Pointer to Ethernet device structure.
2915  * @param idx
2916  *   RX queue index.
2917  * @param desc
2918  *   Number of descriptors to configure in queue.
2919  * @param socket
2920  *   NUMA socket on which memory must be allocated.
2921  * @param[in] conf
2922  *   Thresholds parameters.
2923  * @param mp
2924  *   Memory pool for buffer allocations.
2925  *
2926  * @return
2927  *   0 on success, negative errno value on failure.
2928  */
2929 static int
2930 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
2931                     unsigned int socket, const struct rte_eth_rxconf *conf,
2932                     struct rte_mempool *mp)
2933 {
2934         struct priv *priv = dev->data->dev_private;
2935         struct rxq *rxq = (*priv->rxqs)[idx];
2936         int ret;
2937
2938         priv_lock(priv);
2939         DEBUG("%p: configuring queue %u for %u descriptors",
2940               (void *)dev, idx, desc);
2941         if (idx >= priv->rxqs_n) {
2942                 ERROR("%p: queue index out of range (%u >= %u)",
2943                       (void *)dev, idx, priv->rxqs_n);
2944                 priv_unlock(priv);
2945                 return -EOVERFLOW;
2946         }
2947         if (rxq != NULL) {
2948                 DEBUG("%p: reusing already allocated queue index %u (%p)",
2949                       (void *)dev, idx, (void *)rxq);
2950                 if (priv->started) {
2951                         priv_unlock(priv);
2952                         return -EEXIST;
2953                 }
2954                 (*priv->rxqs)[idx] = NULL;
2955                 if (idx == 0)
2956                         priv_mac_addr_del(priv);
2957                 rxq_cleanup(rxq);
2958         } else {
2959                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
2960                 if (rxq == NULL) {
2961                         ERROR("%p: unable to allocate queue index %u",
2962                               (void *)dev, idx);
2963                         priv_unlock(priv);
2964                         return -ENOMEM;
2965                 }
2966         }
2967         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
2968         if (ret)
2969                 rte_free(rxq);
2970         else {
2971                 rxq->stats.idx = idx;
2972                 DEBUG("%p: adding RX queue %p to list",
2973                       (void *)dev, (void *)rxq);
2974                 (*priv->rxqs)[idx] = rxq;
2975                 /* Update receive callback. */
2976                 if (rxq->sp)
2977                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
2978                 else
2979                         dev->rx_pkt_burst = mlx4_rx_burst;
2980         }
2981         priv_unlock(priv);
2982         return -ret;
2983 }
2984
2985 /**
2986  * DPDK callback to release a RX queue.
2987  *
2988  * @param dpdk_rxq
2989  *   Generic RX queue pointer.
2990  */
2991 static void
2992 mlx4_rx_queue_release(void *dpdk_rxq)
2993 {
2994         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2995         struct priv *priv;
2996         unsigned int i;
2997
2998         if (rxq == NULL)
2999                 return;
3000         priv = rxq->priv;
3001         priv_lock(priv);
3002         for (i = 0; (i != priv->rxqs_n); ++i)
3003                 if ((*priv->rxqs)[i] == rxq) {
3004                         DEBUG("%p: removing RX queue %p from list",
3005                               (void *)priv->dev, (void *)rxq);
3006                         (*priv->rxqs)[i] = NULL;
3007                         if (i == 0)
3008                                 priv_mac_addr_del(priv);
3009                         break;
3010                 }
3011         rxq_cleanup(rxq);
3012         rte_free(rxq);
3013         priv_unlock(priv);
3014 }
3015
3016 static int
3017 priv_dev_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
3018
3019 static int
3020 priv_dev_removal_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
3021
3022 static int
3023 priv_dev_link_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
3024
3025 /**
3026  * DPDK callback to start the device.
3027  *
3028  * Simulate device start by attaching all configured flows.
3029  *
3030  * @param dev
3031  *   Pointer to Ethernet device structure.
3032  *
3033  * @return
3034  *   0 on success, negative errno value on failure.
3035  */
3036 static int
3037 mlx4_dev_start(struct rte_eth_dev *dev)
3038 {
3039         struct priv *priv = dev->data->dev_private;
3040         int ret;
3041
3042         priv_lock(priv);
3043         if (priv->started) {
3044                 priv_unlock(priv);
3045                 return 0;
3046         }
3047         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
3048         priv->started = 1;
3049         ret = priv_mac_addr_add(priv);
3050         if (ret)
3051                 goto err;
3052         ret = priv_dev_link_interrupt_handler_install(priv, dev);
3053         if (ret) {
3054                 ERROR("%p: LSC handler install failed",
3055                      (void *)dev);
3056                 goto err;
3057         }
3058         ret = priv_dev_removal_interrupt_handler_install(priv, dev);
3059         if (ret) {
3060                 ERROR("%p: RMV handler install failed",
3061                      (void *)dev);
3062                 goto err;
3063         }
3064         ret = priv_rx_intr_vec_enable(priv);
3065         if (ret) {
3066                 ERROR("%p: Rx interrupt vector creation failed",
3067                       (void *)dev);
3068                 goto err;
3069         }
3070         ret = mlx4_priv_flow_start(priv);
3071         if (ret) {
3072                 ERROR("%p: flow start failed: %s",
3073                       (void *)dev, strerror(ret));
3074                 goto err;
3075         }
3076         priv_unlock(priv);
3077         return 0;
3078 err:
3079         /* Rollback. */
3080         priv_mac_addr_del(priv);
3081         priv->started = 0;
3082         priv_unlock(priv);
3083         return -ret;
3084 }
3085
3086 /**
3087  * DPDK callback to stop the device.
3088  *
3089  * Simulate device stop by detaching all configured flows.
3090  *
3091  * @param dev
3092  *   Pointer to Ethernet device structure.
3093  */
3094 static void
3095 mlx4_dev_stop(struct rte_eth_dev *dev)
3096 {
3097         struct priv *priv = dev->data->dev_private;
3098
3099         priv_lock(priv);
3100         if (!priv->started) {
3101                 priv_unlock(priv);
3102                 return;
3103         }
3104         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
3105         priv->started = 0;
3106         mlx4_priv_flow_stop(priv);
3107         priv_mac_addr_del(priv);
3108         priv_unlock(priv);
3109 }
3110
3111 /**
3112  * Dummy DPDK callback for TX.
3113  *
3114  * This function is used to temporarily replace the real callback during
3115  * unsafe control operations on the queue, or in case of error.
3116  *
3117  * @param dpdk_txq
3118  *   Generic pointer to TX queue structure.
3119  * @param[in] pkts
3120  *   Packets to transmit.
3121  * @param pkts_n
3122  *   Number of packets in array.
3123  *
3124  * @return
3125  *   Number of packets successfully transmitted (<= pkts_n).
3126  */
3127 static uint16_t
3128 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
3129 {
3130         (void)dpdk_txq;
3131         (void)pkts;
3132         (void)pkts_n;
3133         return 0;
3134 }
3135
3136 /**
3137  * Dummy DPDK callback for RX.
3138  *
3139  * This function is used to temporarily replace the real callback during
3140  * unsafe control operations on the queue, or in case of error.
3141  *
3142  * @param dpdk_rxq
3143  *   Generic pointer to RX queue structure.
3144  * @param[out] pkts
3145  *   Array to store received packets.
3146  * @param pkts_n
3147  *   Maximum number of packets in array.
3148  *
3149  * @return
3150  *   Number of packets successfully received (<= pkts_n).
3151  */
3152 static uint16_t
3153 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
3154 {
3155         (void)dpdk_rxq;
3156         (void)pkts;
3157         (void)pkts_n;
3158         return 0;
3159 }
3160
3161 static int
3162 priv_dev_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
3163
3164 static int
3165 priv_dev_removal_interrupt_handler_uninstall(struct priv *,
3166                                              struct rte_eth_dev *);
3167
3168 static int
3169 priv_dev_link_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
3170
3171 /**
3172  * DPDK callback to close the device.
3173  *
3174  * Destroy all queues and objects, free memory.
3175  *
3176  * @param dev
3177  *   Pointer to Ethernet device structure.
3178  */
3179 static void
3180 mlx4_dev_close(struct rte_eth_dev *dev)
3181 {
3182         struct priv *priv = dev->data->dev_private;
3183         void *tmp;
3184         unsigned int i;
3185
3186         if (priv == NULL)
3187                 return;
3188         priv_lock(priv);
3189         DEBUG("%p: closing device \"%s\"",
3190               (void *)dev,
3191               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
3192         priv_mac_addr_del(priv);
3193         /* Prevent crashes when queues are still in use. This is unfortunately
3194          * still required for DPDK 1.3 because some programs (such as testpmd)
3195          * never release them before closing the device. */
3196         dev->rx_pkt_burst = removed_rx_burst;
3197         dev->tx_pkt_burst = removed_tx_burst;
3198         if (priv->rxqs != NULL) {
3199                 /* XXX race condition if mlx4_rx_burst() is still running. */
3200                 usleep(1000);
3201                 for (i = 0; (i != priv->rxqs_n); ++i) {
3202                         tmp = (*priv->rxqs)[i];
3203                         if (tmp == NULL)
3204                                 continue;
3205                         (*priv->rxqs)[i] = NULL;
3206                         rxq_cleanup(tmp);
3207                         rte_free(tmp);
3208                 }
3209                 priv->rxqs_n = 0;
3210                 priv->rxqs = NULL;
3211         }
3212         if (priv->txqs != NULL) {
3213                 /* XXX race condition if mlx4_tx_burst() is still running. */
3214                 usleep(1000);
3215                 for (i = 0; (i != priv->txqs_n); ++i) {
3216                         tmp = (*priv->txqs)[i];
3217                         if (tmp == NULL)
3218                                 continue;
3219                         (*priv->txqs)[i] = NULL;
3220                         txq_cleanup(tmp);
3221                         rte_free(tmp);
3222                 }
3223                 priv->txqs_n = 0;
3224                 priv->txqs = NULL;
3225         }
3226         if (priv->pd != NULL) {
3227                 assert(priv->ctx != NULL);
3228                 claim_zero(ibv_dealloc_pd(priv->pd));
3229                 claim_zero(ibv_close_device(priv->ctx));
3230         } else
3231                 assert(priv->ctx == NULL);
3232         priv_dev_removal_interrupt_handler_uninstall(priv, dev);
3233         priv_dev_link_interrupt_handler_uninstall(priv, dev);
3234         priv_rx_intr_vec_disable(priv);
3235         priv_unlock(priv);
3236         memset(priv, 0, sizeof(*priv));
3237 }
3238
3239 /**
3240  * Change the link state (UP / DOWN).
3241  *
3242  * @param priv
3243  *   Pointer to Ethernet device private data.
3244  * @param up
3245  *   Nonzero for link up, otherwise link down.
3246  *
3247  * @return
3248  *   0 on success, errno value on failure.
3249  */
3250 static int
3251 priv_set_link(struct priv *priv, int up)
3252 {
3253         struct rte_eth_dev *dev = priv->dev;
3254         int err;
3255         unsigned int i;
3256
3257         if (up) {
3258                 err = priv_set_flags(priv, ~IFF_UP, IFF_UP);
3259                 if (err)
3260                         return err;
3261                 for (i = 0; i < priv->rxqs_n; i++)
3262                         if ((*priv->rxqs)[i]->sp)
3263                                 break;
3264                 /* Check if an sp queue exists.
3265                  * Note: Some old frames might be received.
3266                  */
3267                 if (i == priv->rxqs_n)
3268                         dev->rx_pkt_burst = mlx4_rx_burst;
3269                 else
3270                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3271                 dev->tx_pkt_burst = mlx4_tx_burst;
3272         } else {
3273                 err = priv_set_flags(priv, ~IFF_UP, ~IFF_UP);
3274                 if (err)
3275                         return err;
3276                 dev->rx_pkt_burst = removed_rx_burst;
3277                 dev->tx_pkt_burst = removed_tx_burst;
3278         }
3279         return 0;
3280 }
3281
3282 /**
3283  * DPDK callback to bring the link DOWN.
3284  *
3285  * @param dev
3286  *   Pointer to Ethernet device structure.
3287  *
3288  * @return
3289  *   0 on success, errno value on failure.
3290  */
3291 static int
3292 mlx4_set_link_down(struct rte_eth_dev *dev)
3293 {
3294         struct priv *priv = dev->data->dev_private;
3295         int err;
3296
3297         priv_lock(priv);
3298         err = priv_set_link(priv, 0);
3299         priv_unlock(priv);
3300         return err;
3301 }
3302
3303 /**
3304  * DPDK callback to bring the link UP.
3305  *
3306  * @param dev
3307  *   Pointer to Ethernet device structure.
3308  *
3309  * @return
3310  *   0 on success, errno value on failure.
3311  */
3312 static int
3313 mlx4_set_link_up(struct rte_eth_dev *dev)
3314 {
3315         struct priv *priv = dev->data->dev_private;
3316         int err;
3317
3318         priv_lock(priv);
3319         err = priv_set_link(priv, 1);
3320         priv_unlock(priv);
3321         return err;
3322 }
3323 /**
3324  * DPDK callback to get information about the device.
3325  *
3326  * @param dev
3327  *   Pointer to Ethernet device structure.
3328  * @param[out] info
3329  *   Info structure output buffer.
3330  */
3331 static void
3332 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
3333 {
3334         struct priv *priv = dev->data->dev_private;
3335         unsigned int max;
3336         char ifname[IF_NAMESIZE];
3337
3338         info->pci_dev = RTE_ETH_DEV_TO_PCI(dev);
3339
3340         if (priv == NULL)
3341                 return;
3342         priv_lock(priv);
3343         /* FIXME: we should ask the device for these values. */
3344         info->min_rx_bufsize = 32;
3345         info->max_rx_pktlen = 65536;
3346         /*
3347          * Since we need one CQ per QP, the limit is the minimum number
3348          * between the two values.
3349          */
3350         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
3351                priv->device_attr.max_qp : priv->device_attr.max_cq);
3352         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
3353         if (max >= 65535)
3354                 max = 65535;
3355         info->max_rx_queues = max;
3356         info->max_tx_queues = max;
3357         /* Last array entry is reserved for broadcast. */
3358         info->max_mac_addrs = 1;
3359         info->rx_offload_capa = 0;
3360         info->tx_offload_capa = 0;
3361         if (priv_get_ifname(priv, &ifname) == 0)
3362                 info->if_index = if_nametoindex(ifname);
3363         info->speed_capa =
3364                         ETH_LINK_SPEED_1G |
3365                         ETH_LINK_SPEED_10G |
3366                         ETH_LINK_SPEED_20G |
3367                         ETH_LINK_SPEED_40G |
3368                         ETH_LINK_SPEED_56G;
3369         priv_unlock(priv);
3370 }
3371
3372 static const uint32_t *
3373 mlx4_dev_supported_ptypes_get(struct rte_eth_dev *dev)
3374 {
3375         static const uint32_t ptypes[] = {
3376                 /* refers to rxq_cq_to_pkt_type() */
3377                 RTE_PTYPE_L3_IPV4,
3378                 RTE_PTYPE_L3_IPV6,
3379                 RTE_PTYPE_INNER_L3_IPV4,
3380                 RTE_PTYPE_INNER_L3_IPV6,
3381                 RTE_PTYPE_UNKNOWN
3382         };
3383
3384         if (dev->rx_pkt_burst == mlx4_rx_burst ||
3385             dev->rx_pkt_burst == mlx4_rx_burst_sp)
3386                 return ptypes;
3387         return NULL;
3388 }
3389
3390 /**
3391  * DPDK callback to get device statistics.
3392  *
3393  * @param dev
3394  *   Pointer to Ethernet device structure.
3395  * @param[out] stats
3396  *   Stats structure output buffer.
3397  */
3398 static void
3399 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
3400 {
3401         struct priv *priv = dev->data->dev_private;
3402         struct rte_eth_stats tmp = {0};
3403         unsigned int i;
3404         unsigned int idx;
3405
3406         if (priv == NULL)
3407                 return;
3408         priv_lock(priv);
3409         /* Add software counters. */
3410         for (i = 0; (i != priv->rxqs_n); ++i) {
3411                 struct rxq *rxq = (*priv->rxqs)[i];
3412
3413                 if (rxq == NULL)
3414                         continue;
3415                 idx = rxq->stats.idx;
3416                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3417                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
3418                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
3419                         tmp.q_errors[idx] += (rxq->stats.idropped +
3420                                               rxq->stats.rx_nombuf);
3421                 }
3422                 tmp.ipackets += rxq->stats.ipackets;
3423                 tmp.ibytes += rxq->stats.ibytes;
3424                 tmp.ierrors += rxq->stats.idropped;
3425                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
3426         }
3427         for (i = 0; (i != priv->txqs_n); ++i) {
3428                 struct txq *txq = (*priv->txqs)[i];
3429
3430                 if (txq == NULL)
3431                         continue;
3432                 idx = txq->stats.idx;
3433                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3434                         tmp.q_opackets[idx] += txq->stats.opackets;
3435                         tmp.q_obytes[idx] += txq->stats.obytes;
3436                         tmp.q_errors[idx] += txq->stats.odropped;
3437                 }
3438                 tmp.opackets += txq->stats.opackets;
3439                 tmp.obytes += txq->stats.obytes;
3440                 tmp.oerrors += txq->stats.odropped;
3441         }
3442         *stats = tmp;
3443         priv_unlock(priv);
3444 }
3445
3446 /**
3447  * DPDK callback to clear device statistics.
3448  *
3449  * @param dev
3450  *   Pointer to Ethernet device structure.
3451  */
3452 static void
3453 mlx4_stats_reset(struct rte_eth_dev *dev)
3454 {
3455         struct priv *priv = dev->data->dev_private;
3456         unsigned int i;
3457         unsigned int idx;
3458
3459         if (priv == NULL)
3460                 return;
3461         priv_lock(priv);
3462         for (i = 0; (i != priv->rxqs_n); ++i) {
3463                 if ((*priv->rxqs)[i] == NULL)
3464                         continue;
3465                 idx = (*priv->rxqs)[i]->stats.idx;
3466                 (*priv->rxqs)[i]->stats =
3467                         (struct mlx4_rxq_stats){ .idx = idx };
3468         }
3469         for (i = 0; (i != priv->txqs_n); ++i) {
3470                 if ((*priv->txqs)[i] == NULL)
3471                         continue;
3472                 idx = (*priv->txqs)[i]->stats.idx;
3473                 (*priv->txqs)[i]->stats =
3474                         (struct mlx4_txq_stats){ .idx = idx };
3475         }
3476         priv_unlock(priv);
3477 }
3478
3479 /**
3480  * DPDK callback to retrieve physical link information.
3481  *
3482  * @param dev
3483  *   Pointer to Ethernet device structure.
3484  * @param wait_to_complete
3485  *   Wait for request completion (ignored).
3486  */
3487 static int
3488 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
3489 {
3490         const struct priv *priv = dev->data->dev_private;
3491         struct ethtool_cmd edata = {
3492                 .cmd = ETHTOOL_GSET
3493         };
3494         struct ifreq ifr;
3495         struct rte_eth_link dev_link;
3496         int link_speed = 0;
3497
3498         /* priv_lock() is not taken to allow concurrent calls. */
3499
3500         if (priv == NULL)
3501                 return -EINVAL;
3502         (void)wait_to_complete;
3503         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
3504                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(errno));
3505                 return -1;
3506         }
3507         memset(&dev_link, 0, sizeof(dev_link));
3508         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
3509                                 (ifr.ifr_flags & IFF_RUNNING));
3510         ifr.ifr_data = (void *)&edata;
3511         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
3512                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
3513                      strerror(errno));
3514                 return -1;
3515         }
3516         link_speed = ethtool_cmd_speed(&edata);
3517         if (link_speed == -1)
3518                 dev_link.link_speed = 0;
3519         else
3520                 dev_link.link_speed = link_speed;
3521         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
3522                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
3523         dev_link.link_autoneg = !(dev->data->dev_conf.link_speeds &
3524                         ETH_LINK_SPEED_FIXED);
3525         if (memcmp(&dev_link, &dev->data->dev_link, sizeof(dev_link))) {
3526                 /* Link status changed. */
3527                 dev->data->dev_link = dev_link;
3528                 return 0;
3529         }
3530         /* Link status is still the same. */
3531         return -1;
3532 }
3533
3534 /**
3535  * DPDK callback to change the MTU.
3536  *
3537  * Setting the MTU affects hardware MRU (packets larger than the MTU cannot be
3538  * received). Use this as a hint to enable/disable scattered packets support
3539  * and improve performance when not needed.
3540  * Since failure is not an option, reconfiguring queues on the fly is not
3541  * recommended.
3542  *
3543  * @param dev
3544  *   Pointer to Ethernet device structure.
3545  * @param in_mtu
3546  *   New MTU.
3547  *
3548  * @return
3549  *   0 on success, negative errno value on failure.
3550  */
3551 static int
3552 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
3553 {
3554         struct priv *priv = dev->data->dev_private;
3555         int ret = 0;
3556         unsigned int i;
3557         uint16_t (*rx_func)(void *, struct rte_mbuf **, uint16_t) =
3558                 mlx4_rx_burst;
3559
3560         priv_lock(priv);
3561         /* Set kernel interface MTU first. */
3562         if (priv_set_mtu(priv, mtu)) {
3563                 ret = errno;
3564                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
3565                      strerror(ret));
3566                 goto out;
3567         } else
3568                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
3569         priv->mtu = mtu;
3570         /* Remove MAC flow. */
3571         priv_mac_addr_del(priv);
3572         /* Temporarily replace RX handler with a fake one, assuming it has not
3573          * been copied elsewhere. */
3574         dev->rx_pkt_burst = removed_rx_burst;
3575         /* Make sure everyone has left mlx4_rx_burst() and uses
3576          * removed_rx_burst() instead. */
3577         rte_wmb();
3578         usleep(1000);
3579         /* Reconfigure each RX queue. */
3580         for (i = 0; (i != priv->rxqs_n); ++i) {
3581                 struct rxq *rxq = (*priv->rxqs)[i];
3582                 unsigned int max_frame_len;
3583
3584                 if (rxq == NULL)
3585                         continue;
3586                 /* Calculate new maximum frame length according to MTU. */
3587                 max_frame_len = (priv->mtu + ETHER_HDR_LEN +
3588                                  (ETHER_MAX_VLAN_FRAME_LEN - ETHER_MAX_LEN));
3589                 /* Provide new values to rxq_setup(). */
3590                 dev->data->dev_conf.rxmode.jumbo_frame =
3591                         (max_frame_len > ETHER_MAX_LEN);
3592                 dev->data->dev_conf.rxmode.max_rx_pkt_len = max_frame_len;
3593                 ret = rxq_rehash(dev, rxq);
3594                 if (ret) {
3595                         /* Force SP RX if that queue requires it and abort. */
3596                         if (rxq->sp)
3597                                 rx_func = mlx4_rx_burst_sp;
3598                         break;
3599                 }
3600                 /* Scattered burst function takes priority. */
3601                 if (rxq->sp)
3602                         rx_func = mlx4_rx_burst_sp;
3603         }
3604         /* Burst functions can now be called again. */
3605         rte_wmb();
3606         dev->rx_pkt_burst = rx_func;
3607         /* Restore MAC flow. */
3608         ret = priv_mac_addr_add(priv);
3609 out:
3610         priv_unlock(priv);
3611         assert(ret >= 0);
3612         return -ret;
3613 }
3614
3615 /**
3616  * DPDK callback to get flow control status.
3617  *
3618  * @param dev
3619  *   Pointer to Ethernet device structure.
3620  * @param[out] fc_conf
3621  *   Flow control output buffer.
3622  *
3623  * @return
3624  *   0 on success, negative errno value on failure.
3625  */
3626 static int
3627 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
3628 {
3629         struct priv *priv = dev->data->dev_private;
3630         struct ifreq ifr;
3631         struct ethtool_pauseparam ethpause = {
3632                 .cmd = ETHTOOL_GPAUSEPARAM
3633         };
3634         int ret;
3635
3636         ifr.ifr_data = (void *)&ethpause;
3637         priv_lock(priv);
3638         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
3639                 ret = errno;
3640                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
3641                      " failed: %s",
3642                      strerror(ret));
3643                 goto out;
3644         }
3645
3646         fc_conf->autoneg = ethpause.autoneg;
3647         if (ethpause.rx_pause && ethpause.tx_pause)
3648                 fc_conf->mode = RTE_FC_FULL;
3649         else if (ethpause.rx_pause)
3650                 fc_conf->mode = RTE_FC_RX_PAUSE;
3651         else if (ethpause.tx_pause)
3652                 fc_conf->mode = RTE_FC_TX_PAUSE;
3653         else
3654                 fc_conf->mode = RTE_FC_NONE;
3655         ret = 0;
3656
3657 out:
3658         priv_unlock(priv);
3659         assert(ret >= 0);
3660         return -ret;
3661 }
3662
3663 /**
3664  * DPDK callback to modify flow control parameters.
3665  *
3666  * @param dev
3667  *   Pointer to Ethernet device structure.
3668  * @param[in] fc_conf
3669  *   Flow control parameters.
3670  *
3671  * @return
3672  *   0 on success, negative errno value on failure.
3673  */
3674 static int
3675 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
3676 {
3677         struct priv *priv = dev->data->dev_private;
3678         struct ifreq ifr;
3679         struct ethtool_pauseparam ethpause = {
3680                 .cmd = ETHTOOL_SPAUSEPARAM
3681         };
3682         int ret;
3683
3684         ifr.ifr_data = (void *)&ethpause;
3685         ethpause.autoneg = fc_conf->autoneg;
3686         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
3687             (fc_conf->mode & RTE_FC_RX_PAUSE))
3688                 ethpause.rx_pause = 1;
3689         else
3690                 ethpause.rx_pause = 0;
3691
3692         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
3693             (fc_conf->mode & RTE_FC_TX_PAUSE))
3694                 ethpause.tx_pause = 1;
3695         else
3696                 ethpause.tx_pause = 0;
3697
3698         priv_lock(priv);
3699         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
3700                 ret = errno;
3701                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
3702                      " failed: %s",
3703                      strerror(ret));
3704                 goto out;
3705         }
3706         ret = 0;
3707
3708 out:
3709         priv_unlock(priv);
3710         assert(ret >= 0);
3711         return -ret;
3712 }
3713
3714 const struct rte_flow_ops mlx4_flow_ops = {
3715         .validate = mlx4_flow_validate,
3716         .create = mlx4_flow_create,
3717         .destroy = mlx4_flow_destroy,
3718         .flush = mlx4_flow_flush,
3719         .query = NULL,
3720         .isolate = mlx4_flow_isolate,
3721 };
3722
3723 /**
3724  * Manage filter operations.
3725  *
3726  * @param dev
3727  *   Pointer to Ethernet device structure.
3728  * @param filter_type
3729  *   Filter type.
3730  * @param filter_op
3731  *   Operation to perform.
3732  * @param arg
3733  *   Pointer to operation-specific structure.
3734  *
3735  * @return
3736  *   0 on success, negative errno value on failure.
3737  */
3738 static int
3739 mlx4_dev_filter_ctrl(struct rte_eth_dev *dev,
3740                      enum rte_filter_type filter_type,
3741                      enum rte_filter_op filter_op,
3742                      void *arg)
3743 {
3744         int ret = EINVAL;
3745
3746         switch (filter_type) {
3747         case RTE_ETH_FILTER_GENERIC:
3748                 if (filter_op != RTE_ETH_FILTER_GET)
3749                         return -EINVAL;
3750                 *(const void **)arg = &mlx4_flow_ops;
3751                 return 0;
3752         default:
3753                 ERROR("%p: filter type (%d) not supported",
3754                       (void *)dev, filter_type);
3755                 break;
3756         }
3757         return -ret;
3758 }
3759
3760 static const struct eth_dev_ops mlx4_dev_ops = {
3761         .dev_configure = mlx4_dev_configure,
3762         .dev_start = mlx4_dev_start,
3763         .dev_stop = mlx4_dev_stop,
3764         .dev_set_link_down = mlx4_set_link_down,
3765         .dev_set_link_up = mlx4_set_link_up,
3766         .dev_close = mlx4_dev_close,
3767         .link_update = mlx4_link_update,
3768         .stats_get = mlx4_stats_get,
3769         .stats_reset = mlx4_stats_reset,
3770         .dev_infos_get = mlx4_dev_infos_get,
3771         .dev_supported_ptypes_get = mlx4_dev_supported_ptypes_get,
3772         .rx_queue_setup = mlx4_rx_queue_setup,
3773         .tx_queue_setup = mlx4_tx_queue_setup,
3774         .rx_queue_release = mlx4_rx_queue_release,
3775         .tx_queue_release = mlx4_tx_queue_release,
3776         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
3777         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
3778         .mtu_set = mlx4_dev_set_mtu,
3779         .filter_ctrl = mlx4_dev_filter_ctrl,
3780         .rx_queue_intr_enable = mlx4_rx_intr_enable,
3781         .rx_queue_intr_disable = mlx4_rx_intr_disable,
3782 };
3783
3784 /**
3785  * Get PCI information from struct ibv_device.
3786  *
3787  * @param device
3788  *   Pointer to Ethernet device structure.
3789  * @param[out] pci_addr
3790  *   PCI bus address output buffer.
3791  *
3792  * @return
3793  *   0 on success, -1 on failure and errno is set.
3794  */
3795 static int
3796 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
3797                             struct rte_pci_addr *pci_addr)
3798 {
3799         FILE *file;
3800         char line[32];
3801         MKSTR(path, "%s/device/uevent", device->ibdev_path);
3802
3803         file = fopen(path, "rb");
3804         if (file == NULL)
3805                 return -1;
3806         while (fgets(line, sizeof(line), file) == line) {
3807                 size_t len = strlen(line);
3808                 int ret;
3809
3810                 /* Truncate long lines. */
3811                 if (len == (sizeof(line) - 1))
3812                         while (line[(len - 1)] != '\n') {
3813                                 ret = fgetc(file);
3814                                 if (ret == EOF)
3815                                         break;
3816                                 line[(len - 1)] = ret;
3817                         }
3818                 /* Extract information. */
3819                 if (sscanf(line,
3820                            "PCI_SLOT_NAME="
3821                            "%" SCNx32 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
3822                            &pci_addr->domain,
3823                            &pci_addr->bus,
3824                            &pci_addr->devid,
3825                            &pci_addr->function) == 4) {
3826                         ret = 0;
3827                         break;
3828                 }
3829         }
3830         fclose(file);
3831         return 0;
3832 }
3833
3834 /**
3835  * Get MAC address by querying netdevice.
3836  *
3837  * @param[in] priv
3838  *   struct priv for the requested device.
3839  * @param[out] mac
3840  *   MAC address output buffer.
3841  *
3842  * @return
3843  *   0 on success, -1 on failure and errno is set.
3844  */
3845 static int
3846 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
3847 {
3848         struct ifreq request;
3849
3850         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
3851                 return -1;
3852         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
3853         return 0;
3854 }
3855
3856 /**
3857  * Retrieve integer value from environment variable.
3858  *
3859  * @param[in] name
3860  *   Environment variable name.
3861  *
3862  * @return
3863  *   Integer value, 0 if the variable is not set.
3864  */
3865 static int
3866 mlx4_getenv_int(const char *name)
3867 {
3868         const char *val = getenv(name);
3869
3870         if (val == NULL)
3871                 return 0;
3872         return atoi(val);
3873 }
3874
3875 static void
3876 mlx4_dev_link_status_handler(void *);
3877 static void
3878 mlx4_dev_interrupt_handler(void *);
3879
3880 /**
3881  * Link/device status handler.
3882  *
3883  * @param priv
3884  *   Pointer to private structure.
3885  * @param dev
3886  *   Pointer to the rte_eth_dev structure.
3887  * @param events
3888  *   Pointer to event flags holder.
3889  *
3890  * @return
3891  *   Number of events
3892  */
3893 static int
3894 priv_dev_status_handler(struct priv *priv, struct rte_eth_dev *dev,
3895                         uint32_t *events)
3896 {
3897         struct ibv_async_event event;
3898         int port_change = 0;
3899         struct rte_eth_link *link = &dev->data->dev_link;
3900         int ret = 0;
3901
3902         *events = 0;
3903         /* Read all message and acknowledge them. */
3904         for (;;) {
3905                 if (ibv_get_async_event(priv->ctx, &event))
3906                         break;
3907                 if ((event.event_type == IBV_EVENT_PORT_ACTIVE ||
3908                      event.event_type == IBV_EVENT_PORT_ERR) &&
3909                     (priv->intr_conf.lsc == 1)) {
3910                         port_change = 1;
3911                         ret++;
3912                 } else if (event.event_type == IBV_EVENT_DEVICE_FATAL &&
3913                            priv->intr_conf.rmv == 1) {
3914                         *events |= (1 << RTE_ETH_EVENT_INTR_RMV);
3915                         ret++;
3916                 } else
3917                         DEBUG("event type %d on port %d not handled",
3918                               event.event_type, event.element.port_num);
3919                 ibv_ack_async_event(&event);
3920         }
3921         if (!port_change)
3922                 return ret;
3923         mlx4_link_update(dev, 0);
3924         if (((link->link_speed == 0) && link->link_status) ||
3925             ((link->link_speed != 0) && !link->link_status)) {
3926                 if (!priv->pending_alarm) {
3927                         /* Inconsistent status, check again later. */
3928                         priv->pending_alarm = 1;
3929                         rte_eal_alarm_set(MLX4_ALARM_TIMEOUT_US,
3930                                           mlx4_dev_link_status_handler,
3931                                           dev);
3932                 }
3933         } else {
3934                 *events |= (1 << RTE_ETH_EVENT_INTR_LSC);
3935         }
3936         return ret;
3937 }
3938
3939 /**
3940  * Handle delayed link status event.
3941  *
3942  * @param arg
3943  *   Registered argument.
3944  */
3945 static void
3946 mlx4_dev_link_status_handler(void *arg)
3947 {
3948         struct rte_eth_dev *dev = arg;
3949         struct priv *priv = dev->data->dev_private;
3950         uint32_t events;
3951         int ret;
3952
3953         priv_lock(priv);
3954         assert(priv->pending_alarm == 1);
3955         priv->pending_alarm = 0;
3956         ret = priv_dev_status_handler(priv, dev, &events);
3957         priv_unlock(priv);
3958         if (ret > 0 && events & (1 << RTE_ETH_EVENT_INTR_LSC))
3959                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC, NULL,
3960                                               NULL);
3961 }
3962
3963 /**
3964  * Handle interrupts from the NIC.
3965  *
3966  * @param[in] intr_handle
3967  *   Interrupt handler.
3968  * @param cb_arg
3969  *   Callback argument.
3970  */
3971 static void
3972 mlx4_dev_interrupt_handler(void *cb_arg)
3973 {
3974         struct rte_eth_dev *dev = cb_arg;
3975         struct priv *priv = dev->data->dev_private;
3976         int ret;
3977         uint32_t ev;
3978         int i;
3979
3980         priv_lock(priv);
3981         ret = priv_dev_status_handler(priv, dev, &ev);
3982         priv_unlock(priv);
3983         if (ret > 0) {
3984                 for (i = RTE_ETH_EVENT_UNKNOWN;
3985                      i < RTE_ETH_EVENT_MAX;
3986                      i++) {
3987                         if (ev & (1 << i)) {
3988                                 ev &= ~(1 << i);
3989                                 _rte_eth_dev_callback_process(dev, i, NULL,
3990                                                               NULL);
3991                                 ret--;
3992                         }
3993                 }
3994                 if (ret)
3995                         WARN("%d event%s not processed", ret,
3996                              (ret > 1 ? "s were" : " was"));
3997         }
3998 }
3999
4000 /**
4001  * Uninstall interrupt handler.
4002  *
4003  * @param priv
4004  *   Pointer to private structure.
4005  * @param dev
4006  *   Pointer to the rte_eth_dev structure.
4007  * @return
4008  *   0 on success, negative errno value on failure.
4009  */
4010 static int
4011 priv_dev_interrupt_handler_uninstall(struct priv *priv, struct rte_eth_dev *dev)
4012 {
4013         int ret;
4014
4015         if (priv->intr_conf.lsc ||
4016             priv->intr_conf.rmv)
4017                 return 0;
4018         ret = rte_intr_callback_unregister(&priv->intr_handle,
4019                                            mlx4_dev_interrupt_handler,
4020                                            dev);
4021         if (ret < 0) {
4022                 ERROR("rte_intr_callback_unregister failed with %d"
4023                       "%s%s%s", ret,
4024                       (errno ? " (errno: " : ""),
4025                       (errno ? strerror(errno) : ""),
4026                       (errno ? ")" : ""));
4027         }
4028         priv->intr_handle.fd = 0;
4029         priv->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
4030         return ret;
4031 }
4032
4033 /**
4034  * Install interrupt handler.
4035  *
4036  * @param priv
4037  *   Pointer to private structure.
4038  * @param dev
4039  *   Pointer to the rte_eth_dev structure.
4040  * @return
4041  *   0 on success, negative errno value on failure.
4042  */
4043 static int
4044 priv_dev_interrupt_handler_install(struct priv *priv,
4045                                    struct rte_eth_dev *dev)
4046 {
4047         int flags;
4048         int rc;
4049
4050         /* Check whether the interrupt handler has already been installed
4051          * for either type of interrupt
4052          */
4053         if (priv->intr_conf.lsc &&
4054             priv->intr_conf.rmv &&
4055             priv->intr_handle.fd)
4056                 return 0;
4057         assert(priv->ctx->async_fd > 0);
4058         flags = fcntl(priv->ctx->async_fd, F_GETFL);
4059         rc = fcntl(priv->ctx->async_fd, F_SETFL, flags | O_NONBLOCK);
4060         if (rc < 0) {
4061                 INFO("failed to change file descriptor async event queue");
4062                 dev->data->dev_conf.intr_conf.lsc = 0;
4063                 dev->data->dev_conf.intr_conf.rmv = 0;
4064                 return -errno;
4065         } else {
4066                 priv->intr_handle.fd = priv->ctx->async_fd;
4067                 priv->intr_handle.type = RTE_INTR_HANDLE_EXT;
4068                 rc = rte_intr_callback_register(&priv->intr_handle,
4069                                                  mlx4_dev_interrupt_handler,
4070                                                  dev);
4071                 if (rc) {
4072                         ERROR("rte_intr_callback_register failed "
4073                               " (errno: %s)", strerror(errno));
4074                         return rc;
4075                 }
4076         }
4077         return 0;
4078 }
4079
4080 /**
4081  * Uninstall interrupt handler.
4082  *
4083  * @param priv
4084  *   Pointer to private structure.
4085  * @param dev
4086  *   Pointer to the rte_eth_dev structure.
4087  * @return
4088  *   0 on success, negative value on error.
4089  */
4090 static int
4091 priv_dev_removal_interrupt_handler_uninstall(struct priv *priv,
4092                                             struct rte_eth_dev *dev)
4093 {
4094         if (dev->data->dev_conf.intr_conf.rmv) {
4095                 priv->intr_conf.rmv = 0;
4096                 return priv_dev_interrupt_handler_uninstall(priv, dev);
4097         }
4098         return 0;
4099 }
4100
4101 /**
4102  * Uninstall interrupt handler.
4103  *
4104  * @param priv
4105  *   Pointer to private structure.
4106  * @param dev
4107  *   Pointer to the rte_eth_dev structure.
4108  * @return
4109  *   0 on success, negative value on error,
4110  */
4111 static int
4112 priv_dev_link_interrupt_handler_uninstall(struct priv *priv,
4113                                           struct rte_eth_dev *dev)
4114 {
4115         int ret = 0;
4116
4117         if (dev->data->dev_conf.intr_conf.lsc) {
4118                 priv->intr_conf.lsc = 0;
4119                 ret = priv_dev_interrupt_handler_uninstall(priv, dev);
4120                 if (ret)
4121                         return ret;
4122         }
4123         if (priv->pending_alarm)
4124                 if (rte_eal_alarm_cancel(mlx4_dev_link_status_handler,
4125                                          dev)) {
4126                         ERROR("rte_eal_alarm_cancel failed "
4127                               " (errno: %s)", strerror(rte_errno));
4128                         return -rte_errno;
4129                 }
4130         priv->pending_alarm = 0;
4131         return 0;
4132 }
4133
4134 /**
4135  * Install link interrupt handler.
4136  *
4137  * @param priv
4138  *   Pointer to private structure.
4139  * @param dev
4140  *   Pointer to the rte_eth_dev structure.
4141  * @return
4142  *   0 on success, negative value on error.
4143  */
4144 static int
4145 priv_dev_link_interrupt_handler_install(struct priv *priv,
4146                                         struct rte_eth_dev *dev)
4147 {
4148         int ret;
4149
4150         if (dev->data->dev_conf.intr_conf.lsc) {
4151                 ret = priv_dev_interrupt_handler_install(priv, dev);
4152                 if (ret)
4153                         return ret;
4154                 priv->intr_conf.lsc = 1;
4155         }
4156         return 0;
4157 }
4158
4159 /**
4160  * Install removal interrupt handler.
4161  *
4162  * @param priv
4163  *   Pointer to private structure.
4164  * @param dev
4165  *   Pointer to the rte_eth_dev structure.
4166  * @return
4167  *   0 on success, negative value on error.
4168  */
4169 static int
4170 priv_dev_removal_interrupt_handler_install(struct priv *priv,
4171                                            struct rte_eth_dev *dev)
4172 {
4173         int ret;
4174
4175         if (dev->data->dev_conf.intr_conf.rmv) {
4176                 ret = priv_dev_interrupt_handler_install(priv, dev);
4177                 if (ret)
4178                         return ret;
4179                 priv->intr_conf.rmv = 1;
4180         }
4181         return 0;
4182 }
4183
4184 /**
4185  * Allocate queue vector and fill epoll fd list for Rx interrupts.
4186  *
4187  * @param priv
4188  *   Pointer to private structure.
4189  *
4190  * @return
4191  *   0 on success, negative on failure.
4192  */
4193 static int
4194 priv_rx_intr_vec_enable(struct priv *priv)
4195 {
4196         unsigned int i;
4197         unsigned int rxqs_n = priv->rxqs_n;
4198         unsigned int n = RTE_MIN(rxqs_n, (uint32_t)RTE_MAX_RXTX_INTR_VEC_ID);
4199         unsigned int count = 0;
4200         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
4201
4202         if (!priv->dev->data->dev_conf.intr_conf.rxq)
4203                 return 0;
4204         priv_rx_intr_vec_disable(priv);
4205         intr_handle->intr_vec = malloc(sizeof(intr_handle->intr_vec[rxqs_n]));
4206         if (intr_handle->intr_vec == NULL) {
4207                 ERROR("failed to allocate memory for interrupt vector,"
4208                       " Rx interrupts will not be supported");
4209                 return -ENOMEM;
4210         }
4211         intr_handle->type = RTE_INTR_HANDLE_EXT;
4212         for (i = 0; i != n; ++i) {
4213                 struct rxq *rxq = (*priv->rxqs)[i];
4214                 int fd;
4215                 int flags;
4216                 int rc;
4217
4218                 /* Skip queues that cannot request interrupts. */
4219                 if (!rxq || !rxq->channel) {
4220                         /* Use invalid intr_vec[] index to disable entry. */
4221                         intr_handle->intr_vec[i] =
4222                                 RTE_INTR_VEC_RXTX_OFFSET +
4223                                 RTE_MAX_RXTX_INTR_VEC_ID;
4224                         continue;
4225                 }
4226                 if (count >= RTE_MAX_RXTX_INTR_VEC_ID) {
4227                         ERROR("too many Rx queues for interrupt vector size"
4228                               " (%d), Rx interrupts cannot be enabled",
4229                               RTE_MAX_RXTX_INTR_VEC_ID);
4230                         priv_rx_intr_vec_disable(priv);
4231                         return -1;
4232                 }
4233                 fd = rxq->channel->fd;
4234                 flags = fcntl(fd, F_GETFL);
4235                 rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
4236                 if (rc < 0) {
4237                         ERROR("failed to make Rx interrupt file descriptor"
4238                               " %d non-blocking for queue index %d", fd, i);
4239                         priv_rx_intr_vec_disable(priv);
4240                         return rc;
4241                 }
4242                 intr_handle->intr_vec[i] = RTE_INTR_VEC_RXTX_OFFSET + count;
4243                 intr_handle->efds[count] = fd;
4244                 count++;
4245         }
4246         if (!count)
4247                 priv_rx_intr_vec_disable(priv);
4248         else
4249                 intr_handle->nb_efd = count;
4250         return 0;
4251 }
4252
4253 /**
4254  * Clean up Rx interrupts handler.
4255  *
4256  * @param priv
4257  *   Pointer to private structure.
4258  */
4259 static void
4260 priv_rx_intr_vec_disable(struct priv *priv)
4261 {
4262         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
4263
4264         rte_intr_free_epoll_fd(intr_handle);
4265         free(intr_handle->intr_vec);
4266         intr_handle->nb_efd = 0;
4267         intr_handle->intr_vec = NULL;
4268 }
4269
4270 /**
4271  * DPDK callback for Rx queue interrupt enable.
4272  *
4273  * @param dev
4274  *   Pointer to Ethernet device structure.
4275  * @param idx
4276  *   Rx queue index.
4277  *
4278  * @return
4279  *   0 on success, negative on failure.
4280  */
4281 static int
4282 mlx4_rx_intr_enable(struct rte_eth_dev *dev, uint16_t idx)
4283 {
4284         struct priv *priv = dev->data->dev_private;
4285         struct rxq *rxq = (*priv->rxqs)[idx];
4286         int ret;
4287
4288         if (!rxq || !rxq->channel)
4289                 ret = EINVAL;
4290         else
4291                 ret = ibv_req_notify_cq(rxq->cq, 0);
4292         if (ret)
4293                 WARN("unable to arm interrupt on rx queue %d", idx);
4294         return -ret;
4295 }
4296
4297 /**
4298  * DPDK callback for Rx queue interrupt disable.
4299  *
4300  * @param dev
4301  *   Pointer to Ethernet device structure.
4302  * @param idx
4303  *   Rx queue index.
4304  *
4305  * @return
4306  *   0 on success, negative on failure.
4307  */
4308 static int
4309 mlx4_rx_intr_disable(struct rte_eth_dev *dev, uint16_t idx)
4310 {
4311         struct priv *priv = dev->data->dev_private;
4312         struct rxq *rxq = (*priv->rxqs)[idx];
4313         struct ibv_cq *ev_cq;
4314         void *ev_ctx;
4315         int ret;
4316
4317         if (!rxq || !rxq->channel) {
4318                 ret = EINVAL;
4319         } else {
4320                 ret = ibv_get_cq_event(rxq->cq->channel, &ev_cq, &ev_ctx);
4321                 if (ret || ev_cq != rxq->cq)
4322                         ret = EINVAL;
4323         }
4324         if (ret)
4325                 WARN("unable to disable interrupt on rx queue %d",
4326                      idx);
4327         else
4328                 ibv_ack_cq_events(rxq->cq, 1);
4329         return -ret;
4330 }
4331
4332 /**
4333  * Verify and store value for device argument.
4334  *
4335  * @param[in] key
4336  *   Key argument to verify.
4337  * @param[in] val
4338  *   Value associated with key.
4339  * @param[in, out] conf
4340  *   Shared configuration data.
4341  *
4342  * @return
4343  *   0 on success, negative errno value on failure.
4344  */
4345 static int
4346 mlx4_arg_parse(const char *key, const char *val, struct mlx4_conf *conf)
4347 {
4348         unsigned long tmp;
4349
4350         errno = 0;
4351         tmp = strtoul(val, NULL, 0);
4352         if (errno) {
4353                 WARN("%s: \"%s\" is not a valid integer", key, val);
4354                 return -errno;
4355         }
4356         if (strcmp(MLX4_PMD_PORT_KVARG, key) == 0) {
4357                 uint32_t ports = rte_log2_u32(conf->ports.present);
4358
4359                 if (tmp >= ports) {
4360                         ERROR("port index %lu outside range [0,%" PRIu32 ")",
4361                               tmp, ports);
4362                         return -EINVAL;
4363                 }
4364                 if (!(conf->ports.present & (1 << tmp))) {
4365                         ERROR("invalid port index %lu", tmp);
4366                         return -EINVAL;
4367                 }
4368                 conf->ports.enabled |= 1 << tmp;
4369         } else {
4370                 WARN("%s: unknown parameter", key);
4371                 return -EINVAL;
4372         }
4373         return 0;
4374 }
4375
4376 /**
4377  * Parse device parameters.
4378  *
4379  * @param devargs
4380  *   Device arguments structure.
4381  *
4382  * @return
4383  *   0 on success, negative errno value on failure.
4384  */
4385 static int
4386 mlx4_args(struct rte_devargs *devargs, struct mlx4_conf *conf)
4387 {
4388         struct rte_kvargs *kvlist;
4389         unsigned int arg_count;
4390         int ret = 0;
4391         int i;
4392
4393         if (devargs == NULL)
4394                 return 0;
4395         kvlist = rte_kvargs_parse(devargs->args, pmd_mlx4_init_params);
4396         if (kvlist == NULL) {
4397                 ERROR("failed to parse kvargs");
4398                 return -EINVAL;
4399         }
4400         /* Process parameters. */
4401         for (i = 0; pmd_mlx4_init_params[i]; ++i) {
4402                 arg_count = rte_kvargs_count(kvlist, MLX4_PMD_PORT_KVARG);
4403                 while (arg_count-- > 0) {
4404                         ret = rte_kvargs_process(kvlist,
4405                                                  MLX4_PMD_PORT_KVARG,
4406                                                  (int (*)(const char *,
4407                                                           const char *,
4408                                                           void *))
4409                                                  mlx4_arg_parse,
4410                                                  conf);
4411                         if (ret != 0)
4412                                 goto free_kvlist;
4413                 }
4414         }
4415 free_kvlist:
4416         rte_kvargs_free(kvlist);
4417         return ret;
4418 }
4419
4420 static struct rte_pci_driver mlx4_driver;
4421
4422 /**
4423  * DPDK callback to register a PCI device.
4424  *
4425  * This function creates an Ethernet device for each port of a given
4426  * PCI device.
4427  *
4428  * @param[in] pci_drv
4429  *   PCI driver structure (mlx4_driver).
4430  * @param[in] pci_dev
4431  *   PCI device information.
4432  *
4433  * @return
4434  *   0 on success, negative errno value on failure.
4435  */
4436 static int
4437 mlx4_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
4438 {
4439         struct ibv_device **list;
4440         struct ibv_device *ibv_dev;
4441         int err = 0;
4442         struct ibv_context *attr_ctx = NULL;
4443         struct ibv_device_attr device_attr;
4444         struct mlx4_conf conf = {
4445                 .ports.present = 0,
4446         };
4447         unsigned int vf;
4448         int i;
4449
4450         (void)pci_drv;
4451         assert(pci_drv == &mlx4_driver);
4452
4453         list = ibv_get_device_list(&i);
4454         if (list == NULL) {
4455                 assert(errno);
4456                 if (errno == ENOSYS)
4457                         ERROR("cannot list devices, is ib_uverbs loaded?");
4458                 return -errno;
4459         }
4460         assert(i >= 0);
4461         /*
4462          * For each listed device, check related sysfs entry against
4463          * the provided PCI ID.
4464          */
4465         while (i != 0) {
4466                 struct rte_pci_addr pci_addr;
4467
4468                 --i;
4469                 DEBUG("checking device \"%s\"", list[i]->name);
4470                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
4471                         continue;
4472                 if ((pci_dev->addr.domain != pci_addr.domain) ||
4473                     (pci_dev->addr.bus != pci_addr.bus) ||
4474                     (pci_dev->addr.devid != pci_addr.devid) ||
4475                     (pci_dev->addr.function != pci_addr.function))
4476                         continue;
4477                 vf = (pci_dev->id.device_id ==
4478                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
4479                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
4480                      list[i]->name, (vf ? "true" : "false"));
4481                 attr_ctx = ibv_open_device(list[i]);
4482                 err = errno;
4483                 break;
4484         }
4485         if (attr_ctx == NULL) {
4486                 ibv_free_device_list(list);
4487                 switch (err) {
4488                 case 0:
4489                         ERROR("cannot access device, is mlx4_ib loaded?");
4490                         return -ENODEV;
4491                 case EINVAL:
4492                         ERROR("cannot use device, are drivers up to date?");
4493                         return -EINVAL;
4494                 }
4495                 assert(err > 0);
4496                 return -err;
4497         }
4498         ibv_dev = list[i];
4499
4500         DEBUG("device opened");
4501         if (ibv_query_device(attr_ctx, &device_attr)) {
4502                 err = ENODEV;
4503                 goto error;
4504         }
4505         INFO("%u port(s) detected", device_attr.phys_port_cnt);
4506
4507         conf.ports.present |= (UINT64_C(1) << device_attr.phys_port_cnt) - 1;
4508         if (mlx4_args(pci_dev->device.devargs, &conf)) {
4509                 ERROR("failed to process device arguments");
4510                 err = EINVAL;
4511                 goto error;
4512         }
4513         /* Use all ports when none are defined */
4514         if (!conf.ports.enabled)
4515                 conf.ports.enabled = conf.ports.present;
4516         for (i = 0; i < device_attr.phys_port_cnt; i++) {
4517                 uint32_t port = i + 1; /* ports are indexed from one */
4518                 struct ibv_context *ctx = NULL;
4519                 struct ibv_port_attr port_attr;
4520                 struct ibv_pd *pd = NULL;
4521                 struct priv *priv = NULL;
4522                 struct rte_eth_dev *eth_dev = NULL;
4523                 struct ibv_exp_device_attr exp_device_attr;
4524                 struct ether_addr mac;
4525
4526                 /* If port is not enabled, skip. */
4527                 if (!(conf.ports.enabled & (1 << i)))
4528                         continue;
4529                 exp_device_attr.comp_mask = IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS;
4530
4531                 DEBUG("using port %u", port);
4532
4533                 ctx = ibv_open_device(ibv_dev);
4534                 if (ctx == NULL) {
4535                         err = ENODEV;
4536                         goto port_error;
4537                 }
4538
4539                 /* Check port status. */
4540                 err = ibv_query_port(ctx, port, &port_attr);
4541                 if (err) {
4542                         ERROR("port query failed: %s", strerror(err));
4543                         err = ENODEV;
4544                         goto port_error;
4545                 }
4546
4547                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
4548                         ERROR("port %d is not configured in Ethernet mode",
4549                               port);
4550                         err = EINVAL;
4551                         goto port_error;
4552                 }
4553
4554                 if (port_attr.state != IBV_PORT_ACTIVE)
4555                         DEBUG("port %d is not active: \"%s\" (%d)",
4556                               port, ibv_port_state_str(port_attr.state),
4557                               port_attr.state);
4558
4559                 /* Allocate protection domain. */
4560                 pd = ibv_alloc_pd(ctx);
4561                 if (pd == NULL) {
4562                         ERROR("PD allocation failure");
4563                         err = ENOMEM;
4564                         goto port_error;
4565                 }
4566
4567                 /* from rte_ethdev.c */
4568                 priv = rte_zmalloc("ethdev private structure",
4569                                    sizeof(*priv),
4570                                    RTE_CACHE_LINE_SIZE);
4571                 if (priv == NULL) {
4572                         ERROR("priv allocation failure");
4573                         err = ENOMEM;
4574                         goto port_error;
4575                 }
4576
4577                 priv->ctx = ctx;
4578                 priv->device_attr = device_attr;
4579                 priv->port = port;
4580                 priv->pd = pd;
4581                 priv->mtu = ETHER_MTU;
4582                 if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4583                         ERROR("ibv_exp_query_device() failed");
4584                         err = ENODEV;
4585                         goto port_error;
4586                 }
4587
4588                 priv->inl_recv_size = mlx4_getenv_int("MLX4_INLINE_RECV_SIZE");
4589
4590                 if (priv->inl_recv_size) {
4591                         exp_device_attr.comp_mask =
4592                                 IBV_EXP_DEVICE_ATTR_INLINE_RECV_SZ;
4593                         if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4594                                 INFO("Couldn't query device for inline-receive"
4595                                      " capabilities.");
4596                                 priv->inl_recv_size = 0;
4597                         } else {
4598                                 if ((unsigned)exp_device_attr.inline_recv_sz <
4599                                     priv->inl_recv_size) {
4600                                         INFO("Max inline-receive (%d) <"
4601                                              " requested inline-receive (%u)",
4602                                              exp_device_attr.inline_recv_sz,
4603                                              priv->inl_recv_size);
4604                                         priv->inl_recv_size =
4605                                                 exp_device_attr.inline_recv_sz;
4606                                 }
4607                         }
4608                         INFO("Set inline receive size to %u",
4609                              priv->inl_recv_size);
4610                 }
4611
4612                 priv->vf = vf;
4613                 /* Configure the first MAC address by default. */
4614                 if (priv_get_mac(priv, &mac.addr_bytes)) {
4615                         ERROR("cannot get MAC address, is mlx4_en loaded?"
4616                               " (errno: %s)", strerror(errno));
4617                         err = ENODEV;
4618                         goto port_error;
4619                 }
4620                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
4621                      priv->port,
4622                      mac.addr_bytes[0], mac.addr_bytes[1],
4623                      mac.addr_bytes[2], mac.addr_bytes[3],
4624                      mac.addr_bytes[4], mac.addr_bytes[5]);
4625                 /* Register MAC address. */
4626                 priv->mac = mac;
4627                 if (priv_mac_addr_add(priv))
4628                         goto port_error;
4629 #ifndef NDEBUG
4630                 {
4631                         char ifname[IF_NAMESIZE];
4632
4633                         if (priv_get_ifname(priv, &ifname) == 0)
4634                                 DEBUG("port %u ifname is \"%s\"",
4635                                       priv->port, ifname);
4636                         else
4637                                 DEBUG("port %u ifname is unknown", priv->port);
4638                 }
4639 #endif
4640                 /* Get actual MTU if possible. */
4641                 priv_get_mtu(priv, &priv->mtu);
4642                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
4643
4644                 /* from rte_ethdev.c */
4645                 {
4646                         char name[RTE_ETH_NAME_MAX_LEN];
4647
4648                         snprintf(name, sizeof(name), "%s port %u",
4649                                  ibv_get_device_name(ibv_dev), port);
4650                         eth_dev = rte_eth_dev_allocate(name);
4651                 }
4652                 if (eth_dev == NULL) {
4653                         ERROR("can not allocate rte ethdev");
4654                         err = ENOMEM;
4655                         goto port_error;
4656                 }
4657
4658                 eth_dev->data->dev_private = priv;
4659                 eth_dev->data->mac_addrs = &priv->mac;
4660                 eth_dev->device = &pci_dev->device;
4661
4662                 rte_eth_copy_pci_info(eth_dev, pci_dev);
4663
4664                 eth_dev->device->driver = &mlx4_driver.driver;
4665
4666                 /*
4667                  * Copy and override interrupt handle to prevent it from
4668                  * being shared between all ethdev instances of a given PCI
4669                  * device. This is required to properly handle Rx interrupts
4670                  * on all ports.
4671                  */
4672                 priv->intr_handle_dev = *eth_dev->intr_handle;
4673                 eth_dev->intr_handle = &priv->intr_handle_dev;
4674
4675                 priv->dev = eth_dev;
4676                 eth_dev->dev_ops = &mlx4_dev_ops;
4677                 eth_dev->data->dev_flags |= RTE_ETH_DEV_DETACHABLE;
4678
4679                 /* Bring Ethernet device up. */
4680                 DEBUG("forcing Ethernet interface up");
4681                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
4682                 /* Update link status once if waiting for LSC. */
4683                 if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
4684                         mlx4_link_update(eth_dev, 0);
4685                 continue;
4686
4687 port_error:
4688                 rte_free(priv);
4689                 if (pd)
4690                         claim_zero(ibv_dealloc_pd(pd));
4691                 if (ctx)
4692                         claim_zero(ibv_close_device(ctx));
4693                 if (eth_dev)
4694                         rte_eth_dev_release_port(eth_dev);
4695                 break;
4696         }
4697         if (i == device_attr.phys_port_cnt)
4698                 return 0;
4699
4700         /*
4701          * XXX if something went wrong in the loop above, there is a resource
4702          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
4703          * long as the dpdk does not provide a way to deallocate a ethdev and a
4704          * way to enumerate the registered ethdevs to free the previous ones.
4705          */
4706
4707 error:
4708         if (attr_ctx)
4709                 claim_zero(ibv_close_device(attr_ctx));
4710         if (list)
4711                 ibv_free_device_list(list);
4712         assert(err >= 0);
4713         return -err;
4714 }
4715
4716 static const struct rte_pci_id mlx4_pci_id_map[] = {
4717         {
4718                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
4719                                PCI_DEVICE_ID_MELLANOX_CONNECTX3)
4720         },
4721         {
4722                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
4723                                PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO)
4724         },
4725         {
4726                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
4727                                PCI_DEVICE_ID_MELLANOX_CONNECTX3VF)
4728         },
4729         {
4730                 .vendor_id = 0
4731         }
4732 };
4733
4734 static struct rte_pci_driver mlx4_driver = {
4735         .driver = {
4736                 .name = MLX4_DRIVER_NAME
4737         },
4738         .id_table = mlx4_pci_id_map,
4739         .probe = mlx4_pci_probe,
4740         .drv_flags = RTE_PCI_DRV_INTR_LSC |
4741                      RTE_PCI_DRV_INTR_RMV,
4742 };
4743
4744 /**
4745  * Driver initialization routine.
4746  */
4747 RTE_INIT(rte_mlx4_pmd_init);
4748 static void
4749 rte_mlx4_pmd_init(void)
4750 {
4751         RTE_BUILD_BUG_ON(sizeof(wr_id_t) != sizeof(uint64_t));
4752         /*
4753          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
4754          * huge pages. Calling ibv_fork_init() during init allows
4755          * applications to use fork() safely for purposes other than
4756          * using this PMD, which is not supported in forked processes.
4757          */
4758         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
4759         ibv_fork_init();
4760         rte_pci_register(&mlx4_driver);
4761 }
4762
4763 RTE_PMD_EXPORT_NAME(net_mlx4, __COUNTER__);
4764 RTE_PMD_REGISTER_PCI_TABLE(net_mlx4, mlx4_pci_id_map);
4765 RTE_PMD_REGISTER_KMOD_DEP(net_mlx4,
4766         "* ib_uverbs & mlx4_en & mlx4_core & mlx4_ib");