5abfb37789b0e528b432972888039c2ebf98c9be
[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_log.h>
64 #include <rte_alarm.h>
65 #include <rte_memory.h>
66 #include <rte_flow.h>
67 #include <rte_kvargs.h>
68 #include <rte_interrupts.h>
69 #include <rte_branch_prediction.h>
70
71 /* Generated configuration header. */
72 #include "mlx4_autoconf.h"
73
74 /* PMD headers. */
75 #include "mlx4.h"
76 #include "mlx4_flow.h"
77
78 /* Convenience macros for accessing mbuf fields. */
79 #define NEXT(m) ((m)->next)
80 #define DATA_LEN(m) ((m)->data_len)
81 #define PKT_LEN(m) ((m)->pkt_len)
82 #define DATA_OFF(m) ((m)->data_off)
83 #define SET_DATA_OFF(m, o) ((m)->data_off = (o))
84 #define NB_SEGS(m) ((m)->nb_segs)
85 #define PORT(m) ((m)->port)
86
87 /* Work Request ID data type (64 bit). */
88 typedef union {
89         struct {
90                 uint32_t id;
91                 uint16_t offset;
92         } data;
93         uint64_t raw;
94 } wr_id_t;
95
96 #define WR_ID(o) (((wr_id_t *)&(o))->data)
97
98 /** Configuration structure for device arguments. */
99 struct mlx4_conf {
100         struct {
101                 uint32_t present; /**< Bit-field for existing ports. */
102                 uint32_t enabled; /**< Bit-field for user-enabled ports. */
103         } ports;
104 };
105
106 /* Available parameters list. */
107 const char *pmd_mlx4_init_params[] = {
108         MLX4_PMD_PORT_KVARG,
109         NULL,
110 };
111
112 static int
113 mlx4_rx_intr_enable(struct rte_eth_dev *dev, uint16_t idx);
114
115 static int
116 mlx4_rx_intr_disable(struct rte_eth_dev *dev, uint16_t idx);
117
118 static int
119 priv_rx_intr_vec_enable(struct priv *priv);
120
121 static void
122 priv_rx_intr_vec_disable(struct priv *priv);
123
124 /**
125  * Lock private structure to protect it from concurrent access in the
126  * control path.
127  *
128  * @param priv
129  *   Pointer to private structure.
130  */
131 void priv_lock(struct priv *priv)
132 {
133         rte_spinlock_lock(&priv->lock);
134 }
135
136 /**
137  * Unlock private structure.
138  *
139  * @param priv
140  *   Pointer to private structure.
141  */
142 void priv_unlock(struct priv *priv)
143 {
144         rte_spinlock_unlock(&priv->lock);
145 }
146
147 /* Allocate a buffer on the stack and fill it with a printf format string. */
148 #define MKSTR(name, ...) \
149         char name[snprintf(NULL, 0, __VA_ARGS__) + 1]; \
150         \
151         snprintf(name, sizeof(name), __VA_ARGS__)
152
153 /**
154  * Get interface name from private structure.
155  *
156  * @param[in] priv
157  *   Pointer to private structure.
158  * @param[out] ifname
159  *   Interface name output buffer.
160  *
161  * @return
162  *   0 on success, -1 on failure and errno is set.
163  */
164 static int
165 priv_get_ifname(const struct priv *priv, char (*ifname)[IF_NAMESIZE])
166 {
167         DIR *dir;
168         struct dirent *dent;
169         unsigned int dev_type = 0;
170         unsigned int dev_port_prev = ~0u;
171         char match[IF_NAMESIZE] = "";
172
173         {
174                 MKSTR(path, "%s/device/net", priv->ctx->device->ibdev_path);
175
176                 dir = opendir(path);
177                 if (dir == NULL)
178                         return -1;
179         }
180         while ((dent = readdir(dir)) != NULL) {
181                 char *name = dent->d_name;
182                 FILE *file;
183                 unsigned int dev_port;
184                 int r;
185
186                 if ((name[0] == '.') &&
187                     ((name[1] == '\0') ||
188                      ((name[1] == '.') && (name[2] == '\0'))))
189                         continue;
190
191                 MKSTR(path, "%s/device/net/%s/%s",
192                       priv->ctx->device->ibdev_path, name,
193                       (dev_type ? "dev_id" : "dev_port"));
194
195                 file = fopen(path, "rb");
196                 if (file == NULL) {
197                         if (errno != ENOENT)
198                                 continue;
199                         /*
200                          * Switch to dev_id when dev_port does not exist as
201                          * is the case with Linux kernel versions < 3.15.
202                          */
203 try_dev_id:
204                         match[0] = '\0';
205                         if (dev_type)
206                                 break;
207                         dev_type = 1;
208                         dev_port_prev = ~0u;
209                         rewinddir(dir);
210                         continue;
211                 }
212                 r = fscanf(file, (dev_type ? "%x" : "%u"), &dev_port);
213                 fclose(file);
214                 if (r != 1)
215                         continue;
216                 /*
217                  * Switch to dev_id when dev_port returns the same value for
218                  * all ports. May happen when using a MOFED release older than
219                  * 3.0 with a Linux kernel >= 3.15.
220                  */
221                 if (dev_port == dev_port_prev)
222                         goto try_dev_id;
223                 dev_port_prev = dev_port;
224                 if (dev_port == (priv->port - 1u))
225                         snprintf(match, sizeof(match), "%s", name);
226         }
227         closedir(dir);
228         if (match[0] == '\0')
229                 return -1;
230         strncpy(*ifname, match, sizeof(*ifname));
231         return 0;
232 }
233
234 /**
235  * Read from sysfs entry.
236  *
237  * @param[in] priv
238  *   Pointer to private structure.
239  * @param[in] entry
240  *   Entry name relative to sysfs path.
241  * @param[out] buf
242  *   Data output buffer.
243  * @param size
244  *   Buffer size.
245  *
246  * @return
247  *   0 on success, -1 on failure and errno is set.
248  */
249 static int
250 priv_sysfs_read(const struct priv *priv, const char *entry,
251                 char *buf, size_t size)
252 {
253         char ifname[IF_NAMESIZE];
254         FILE *file;
255         int ret;
256         int err;
257
258         if (priv_get_ifname(priv, &ifname))
259                 return -1;
260
261         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
262               ifname, entry);
263
264         file = fopen(path, "rb");
265         if (file == NULL)
266                 return -1;
267         ret = fread(buf, 1, size, file);
268         err = errno;
269         if (((size_t)ret < size) && (ferror(file)))
270                 ret = -1;
271         else
272                 ret = size;
273         fclose(file);
274         errno = err;
275         return ret;
276 }
277
278 /**
279  * Write to sysfs entry.
280  *
281  * @param[in] priv
282  *   Pointer to private structure.
283  * @param[in] entry
284  *   Entry name relative to sysfs path.
285  * @param[in] buf
286  *   Data buffer.
287  * @param size
288  *   Buffer size.
289  *
290  * @return
291  *   0 on success, -1 on failure and errno is set.
292  */
293 static int
294 priv_sysfs_write(const struct priv *priv, const char *entry,
295                  char *buf, size_t size)
296 {
297         char ifname[IF_NAMESIZE];
298         FILE *file;
299         int ret;
300         int err;
301
302         if (priv_get_ifname(priv, &ifname))
303                 return -1;
304
305         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
306               ifname, entry);
307
308         file = fopen(path, "wb");
309         if (file == NULL)
310                 return -1;
311         ret = fwrite(buf, 1, size, file);
312         err = errno;
313         if (((size_t)ret < size) || (ferror(file)))
314                 ret = -1;
315         else
316                 ret = size;
317         fclose(file);
318         errno = err;
319         return ret;
320 }
321
322 /**
323  * Get unsigned long sysfs property.
324  *
325  * @param priv
326  *   Pointer to private structure.
327  * @param[in] name
328  *   Entry name relative to sysfs path.
329  * @param[out] value
330  *   Value output buffer.
331  *
332  * @return
333  *   0 on success, -1 on failure and errno is set.
334  */
335 static int
336 priv_get_sysfs_ulong(struct priv *priv, const char *name, unsigned long *value)
337 {
338         int ret;
339         unsigned long value_ret;
340         char value_str[32];
341
342         ret = priv_sysfs_read(priv, name, value_str, (sizeof(value_str) - 1));
343         if (ret == -1) {
344                 DEBUG("cannot read %s value from sysfs: %s",
345                       name, strerror(errno));
346                 return -1;
347         }
348         value_str[ret] = '\0';
349         errno = 0;
350         value_ret = strtoul(value_str, NULL, 0);
351         if (errno) {
352                 DEBUG("invalid %s value `%s': %s", name, value_str,
353                       strerror(errno));
354                 return -1;
355         }
356         *value = value_ret;
357         return 0;
358 }
359
360 /**
361  * Set unsigned long sysfs property.
362  *
363  * @param priv
364  *   Pointer to private structure.
365  * @param[in] name
366  *   Entry name relative to sysfs path.
367  * @param value
368  *   Value to set.
369  *
370  * @return
371  *   0 on success, -1 on failure and errno is set.
372  */
373 static int
374 priv_set_sysfs_ulong(struct priv *priv, const char *name, unsigned long value)
375 {
376         int ret;
377         MKSTR(value_str, "%lu", value);
378
379         ret = priv_sysfs_write(priv, name, value_str, (sizeof(value_str) - 1));
380         if (ret == -1) {
381                 DEBUG("cannot write %s `%s' (%lu) to sysfs: %s",
382                       name, value_str, value, strerror(errno));
383                 return -1;
384         }
385         return 0;
386 }
387
388 /**
389  * Perform ifreq ioctl() on associated Ethernet device.
390  *
391  * @param[in] priv
392  *   Pointer to private structure.
393  * @param req
394  *   Request number to pass to ioctl().
395  * @param[out] ifr
396  *   Interface request structure output buffer.
397  *
398  * @return
399  *   0 on success, -1 on failure and errno is set.
400  */
401 static int
402 priv_ifreq(const struct priv *priv, int req, struct ifreq *ifr)
403 {
404         int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
405         int ret = -1;
406
407         if (sock == -1)
408                 return ret;
409         if (priv_get_ifname(priv, &ifr->ifr_name) == 0)
410                 ret = ioctl(sock, req, ifr);
411         close(sock);
412         return ret;
413 }
414
415 /**
416  * Get device MTU.
417  *
418  * @param priv
419  *   Pointer to private structure.
420  * @param[out] mtu
421  *   MTU value output buffer.
422  *
423  * @return
424  *   0 on success, -1 on failure and errno is set.
425  */
426 static int
427 priv_get_mtu(struct priv *priv, uint16_t *mtu)
428 {
429         unsigned long ulong_mtu;
430
431         if (priv_get_sysfs_ulong(priv, "mtu", &ulong_mtu) == -1)
432                 return -1;
433         *mtu = ulong_mtu;
434         return 0;
435 }
436
437 /**
438  * Set device MTU.
439  *
440  * @param priv
441  *   Pointer to private structure.
442  * @param mtu
443  *   MTU value to set.
444  *
445  * @return
446  *   0 on success, -1 on failure and errno is set.
447  */
448 static int
449 priv_set_mtu(struct priv *priv, uint16_t mtu)
450 {
451         uint16_t new_mtu;
452
453         if (priv_set_sysfs_ulong(priv, "mtu", mtu) ||
454             priv_get_mtu(priv, &new_mtu))
455                 return -1;
456         if (new_mtu == mtu)
457                 return 0;
458         errno = EINVAL;
459         return -1;
460 }
461
462 /**
463  * Set device flags.
464  *
465  * @param priv
466  *   Pointer to private structure.
467  * @param keep
468  *   Bitmask for flags that must remain untouched.
469  * @param flags
470  *   Bitmask for flags to modify.
471  *
472  * @return
473  *   0 on success, -1 on failure and errno is set.
474  */
475 static int
476 priv_set_flags(struct priv *priv, unsigned int keep, unsigned int flags)
477 {
478         unsigned long tmp;
479
480         if (priv_get_sysfs_ulong(priv, "flags", &tmp) == -1)
481                 return -1;
482         tmp &= keep;
483         tmp |= (flags & (~keep));
484         return priv_set_sysfs_ulong(priv, "flags", tmp);
485 }
486
487 /* Device configuration. */
488
489 static int
490 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
491           unsigned int socket, const struct rte_eth_txconf *conf);
492
493 static void
494 txq_cleanup(struct txq *txq);
495
496 static int
497 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
498           unsigned int socket, const struct rte_eth_rxconf *conf,
499           struct rte_mempool *mp);
500
501 static void
502 rxq_cleanup(struct rxq *rxq);
503
504 static void
505 priv_mac_addr_del(struct priv *priv);
506
507 /**
508  * Ethernet device configuration.
509  *
510  * Prepare the driver for a given number of TX and RX queues.
511  *
512  * @param dev
513  *   Pointer to Ethernet device structure.
514  *
515  * @return
516  *   0 on success, errno value on failure.
517  */
518 static int
519 dev_configure(struct rte_eth_dev *dev)
520 {
521         struct priv *priv = dev->data->dev_private;
522         unsigned int rxqs_n = dev->data->nb_rx_queues;
523         unsigned int txqs_n = dev->data->nb_tx_queues;
524
525         priv->rxqs = (void *)dev->data->rx_queues;
526         priv->txqs = (void *)dev->data->tx_queues;
527         if (txqs_n != priv->txqs_n) {
528                 INFO("%p: TX queues number update: %u -> %u",
529                      (void *)dev, priv->txqs_n, txqs_n);
530                 priv->txqs_n = txqs_n;
531         }
532         if (rxqs_n != priv->rxqs_n) {
533                 INFO("%p: Rx queues number update: %u -> %u",
534                      (void *)dev, priv->rxqs_n, rxqs_n);
535                 priv->rxqs_n = rxqs_n;
536         }
537         return 0;
538 }
539
540 /**
541  * DPDK callback for Ethernet device configuration.
542  *
543  * @param dev
544  *   Pointer to Ethernet device structure.
545  *
546  * @return
547  *   0 on success, negative errno value on failure.
548  */
549 static int
550 mlx4_dev_configure(struct rte_eth_dev *dev)
551 {
552         struct priv *priv = dev->data->dev_private;
553         int ret;
554
555         priv_lock(priv);
556         ret = dev_configure(dev);
557         assert(ret >= 0);
558         priv_unlock(priv);
559         return -ret;
560 }
561
562 static uint16_t mlx4_tx_burst(void *, struct rte_mbuf **, uint16_t);
563 static uint16_t removed_rx_burst(void *, struct rte_mbuf **, uint16_t);
564
565 /* TX queues handling. */
566
567 /**
568  * Allocate TX queue elements.
569  *
570  * @param txq
571  *   Pointer to TX queue structure.
572  * @param elts_n
573  *   Number of elements to allocate.
574  *
575  * @return
576  *   0 on success, errno value on failure.
577  */
578 static int
579 txq_alloc_elts(struct txq *txq, unsigned int elts_n)
580 {
581         unsigned int i;
582         struct txq_elt (*elts)[elts_n] =
583                 rte_calloc_socket("TXQ", 1, sizeof(*elts), 0, txq->socket);
584         int ret = 0;
585
586         if (elts == NULL) {
587                 ERROR("%p: can't allocate packets array", (void *)txq);
588                 ret = ENOMEM;
589                 goto error;
590         }
591         for (i = 0; (i != elts_n); ++i) {
592                 struct txq_elt *elt = &(*elts)[i];
593
594                 elt->buf = NULL;
595         }
596         DEBUG("%p: allocated and configured %u WRs", (void *)txq, elts_n);
597         txq->elts_n = elts_n;
598         txq->elts = elts;
599         txq->elts_head = 0;
600         txq->elts_tail = 0;
601         txq->elts_comp = 0;
602         /* Request send completion every MLX4_PMD_TX_PER_COMP_REQ packets or
603          * at least 4 times per ring. */
604         txq->elts_comp_cd_init =
605                 ((MLX4_PMD_TX_PER_COMP_REQ < (elts_n / 4)) ?
606                  MLX4_PMD_TX_PER_COMP_REQ : (elts_n / 4));
607         txq->elts_comp_cd = txq->elts_comp_cd_init;
608         assert(ret == 0);
609         return 0;
610 error:
611         rte_free(elts);
612
613         DEBUG("%p: failed, freed everything", (void *)txq);
614         assert(ret > 0);
615         return ret;
616 }
617
618 /**
619  * Free TX queue elements.
620  *
621  * @param txq
622  *   Pointer to TX queue structure.
623  */
624 static void
625 txq_free_elts(struct txq *txq)
626 {
627         unsigned int elts_n = txq->elts_n;
628         unsigned int elts_head = txq->elts_head;
629         unsigned int elts_tail = txq->elts_tail;
630         struct txq_elt (*elts)[elts_n] = txq->elts;
631
632         DEBUG("%p: freeing WRs", (void *)txq);
633         txq->elts_n = 0;
634         txq->elts_head = 0;
635         txq->elts_tail = 0;
636         txq->elts_comp = 0;
637         txq->elts_comp_cd = 0;
638         txq->elts_comp_cd_init = 0;
639         txq->elts = NULL;
640         if (elts == NULL)
641                 return;
642         while (elts_tail != elts_head) {
643                 struct txq_elt *elt = &(*elts)[elts_tail];
644
645                 assert(elt->buf != NULL);
646                 rte_pktmbuf_free(elt->buf);
647 #ifndef NDEBUG
648                 /* Poisoning. */
649                 memset(elt, 0x77, sizeof(*elt));
650 #endif
651                 if (++elts_tail == elts_n)
652                         elts_tail = 0;
653         }
654         rte_free(elts);
655 }
656
657
658 /**
659  * Clean up a TX queue.
660  *
661  * Destroy objects, free allocated memory and reset the structure for reuse.
662  *
663  * @param txq
664  *   Pointer to TX queue structure.
665  */
666 static void
667 txq_cleanup(struct txq *txq)
668 {
669         struct ibv_exp_release_intf_params params;
670         size_t i;
671
672         DEBUG("cleaning up %p", (void *)txq);
673         txq_free_elts(txq);
674         if (txq->if_qp != NULL) {
675                 assert(txq->priv != NULL);
676                 assert(txq->priv->ctx != NULL);
677                 assert(txq->qp != NULL);
678                 params = (struct ibv_exp_release_intf_params){
679                         .comp_mask = 0,
680                 };
681                 claim_zero(ibv_exp_release_intf(txq->priv->ctx,
682                                                 txq->if_qp,
683                                                 &params));
684         }
685         if (txq->if_cq != NULL) {
686                 assert(txq->priv != NULL);
687                 assert(txq->priv->ctx != NULL);
688                 assert(txq->cq != NULL);
689                 params = (struct ibv_exp_release_intf_params){
690                         .comp_mask = 0,
691                 };
692                 claim_zero(ibv_exp_release_intf(txq->priv->ctx,
693                                                 txq->if_cq,
694                                                 &params));
695         }
696         if (txq->qp != NULL)
697                 claim_zero(ibv_destroy_qp(txq->qp));
698         if (txq->cq != NULL)
699                 claim_zero(ibv_destroy_cq(txq->cq));
700         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
701                 if (txq->mp2mr[i].mp == NULL)
702                         break;
703                 assert(txq->mp2mr[i].mr != NULL);
704                 claim_zero(ibv_dereg_mr(txq->mp2mr[i].mr));
705         }
706         memset(txq, 0, sizeof(*txq));
707 }
708
709 /**
710  * Manage TX completions.
711  *
712  * When sending a burst, mlx4_tx_burst() posts several WRs.
713  * To improve performance, a completion event is only required once every
714  * MLX4_PMD_TX_PER_COMP_REQ sends. Doing so discards completion information
715  * for other WRs, but this information would not be used anyway.
716  *
717  * @param txq
718  *   Pointer to TX queue structure.
719  *
720  * @return
721  *   0 on success, -1 on failure.
722  */
723 static int
724 txq_complete(struct txq *txq)
725 {
726         unsigned int elts_comp = txq->elts_comp;
727         unsigned int elts_tail = txq->elts_tail;
728         const unsigned int elts_n = txq->elts_n;
729         int wcs_n;
730
731         if (unlikely(elts_comp == 0))
732                 return 0;
733         wcs_n = txq->if_cq->poll_cnt(txq->cq, elts_comp);
734         if (unlikely(wcs_n == 0))
735                 return 0;
736         if (unlikely(wcs_n < 0)) {
737                 DEBUG("%p: ibv_poll_cq() failed (wcs_n=%d)",
738                       (void *)txq, wcs_n);
739                 return -1;
740         }
741         elts_comp -= wcs_n;
742         assert(elts_comp <= txq->elts_comp);
743         /*
744          * Assume WC status is successful as nothing can be done about it
745          * anyway.
746          */
747         elts_tail += wcs_n * txq->elts_comp_cd_init;
748         if (elts_tail >= elts_n)
749                 elts_tail -= elts_n;
750         txq->elts_tail = elts_tail;
751         txq->elts_comp = elts_comp;
752         return 0;
753 }
754
755 struct mlx4_check_mempool_data {
756         int ret;
757         char *start;
758         char *end;
759 };
760
761 /* Called by mlx4_check_mempool() when iterating the memory chunks. */
762 static void mlx4_check_mempool_cb(struct rte_mempool *mp,
763         void *opaque, struct rte_mempool_memhdr *memhdr,
764         unsigned mem_idx)
765 {
766         struct mlx4_check_mempool_data *data = opaque;
767
768         (void)mp;
769         (void)mem_idx;
770
771         /* It already failed, skip the next chunks. */
772         if (data->ret != 0)
773                 return;
774         /* It is the first chunk. */
775         if (data->start == NULL && data->end == NULL) {
776                 data->start = memhdr->addr;
777                 data->end = data->start + memhdr->len;
778                 return;
779         }
780         if (data->end == memhdr->addr) {
781                 data->end += memhdr->len;
782                 return;
783         }
784         if (data->start == (char *)memhdr->addr + memhdr->len) {
785                 data->start -= memhdr->len;
786                 return;
787         }
788         /* Error, mempool is not virtually contigous. */
789         data->ret = -1;
790 }
791
792 /**
793  * Check if a mempool can be used: it must be virtually contiguous.
794  *
795  * @param[in] mp
796  *   Pointer to memory pool.
797  * @param[out] start
798  *   Pointer to the start address of the mempool virtual memory area
799  * @param[out] end
800  *   Pointer to the end address of the mempool virtual memory area
801  *
802  * @return
803  *   0 on success (mempool is virtually contiguous), -1 on error.
804  */
805 static int mlx4_check_mempool(struct rte_mempool *mp, uintptr_t *start,
806         uintptr_t *end)
807 {
808         struct mlx4_check_mempool_data data;
809
810         memset(&data, 0, sizeof(data));
811         rte_mempool_mem_iter(mp, mlx4_check_mempool_cb, &data);
812         *start = (uintptr_t)data.start;
813         *end = (uintptr_t)data.end;
814
815         return data.ret;
816 }
817
818 /* For best performance, this function should not be inlined. */
819 static struct ibv_mr *mlx4_mp2mr(struct ibv_pd *, struct rte_mempool *)
820         __rte_noinline;
821
822 /**
823  * Register mempool as a memory region.
824  *
825  * @param pd
826  *   Pointer to protection domain.
827  * @param mp
828  *   Pointer to memory pool.
829  *
830  * @return
831  *   Memory region pointer, NULL in case of error.
832  */
833 static struct ibv_mr *
834 mlx4_mp2mr(struct ibv_pd *pd, struct rte_mempool *mp)
835 {
836         const struct rte_memseg *ms = rte_eal_get_physmem_layout();
837         uintptr_t start;
838         uintptr_t end;
839         unsigned int i;
840
841         if (mlx4_check_mempool(mp, &start, &end) != 0) {
842                 ERROR("mempool %p: not virtually contiguous",
843                         (void *)mp);
844                 return NULL;
845         }
846
847         DEBUG("mempool %p area start=%p end=%p size=%zu",
848               (void *)mp, (void *)start, (void *)end,
849               (size_t)(end - start));
850         /* Round start and end to page boundary if found in memory segments. */
851         for (i = 0; (i < RTE_MAX_MEMSEG) && (ms[i].addr != NULL); ++i) {
852                 uintptr_t addr = (uintptr_t)ms[i].addr;
853                 size_t len = ms[i].len;
854                 unsigned int align = ms[i].hugepage_sz;
855
856                 if ((start > addr) && (start < addr + len))
857                         start = RTE_ALIGN_FLOOR(start, align);
858                 if ((end > addr) && (end < addr + len))
859                         end = RTE_ALIGN_CEIL(end, align);
860         }
861         DEBUG("mempool %p using start=%p end=%p size=%zu for MR",
862               (void *)mp, (void *)start, (void *)end,
863               (size_t)(end - start));
864         return ibv_reg_mr(pd,
865                           (void *)start,
866                           end - start,
867                           IBV_ACCESS_LOCAL_WRITE);
868 }
869
870 /**
871  * Get Memory Pool (MP) from mbuf. If mbuf is indirect, the pool from which
872  * the cloned mbuf is allocated is returned instead.
873  *
874  * @param buf
875  *   Pointer to mbuf.
876  *
877  * @return
878  *   Memory pool where data is located for given mbuf.
879  */
880 static struct rte_mempool *
881 txq_mb2mp(struct rte_mbuf *buf)
882 {
883         if (unlikely(RTE_MBUF_INDIRECT(buf)))
884                 return rte_mbuf_from_indirect(buf)->pool;
885         return buf->pool;
886 }
887
888 /**
889  * Get Memory Region (MR) <-> Memory Pool (MP) association from txq->mp2mr[].
890  * Add MP to txq->mp2mr[] if it's not registered yet. If mp2mr[] is full,
891  * remove an entry first.
892  *
893  * @param txq
894  *   Pointer to TX queue structure.
895  * @param[in] mp
896  *   Memory Pool for which a Memory Region lkey must be returned.
897  *
898  * @return
899  *   mr->lkey on success, (uint32_t)-1 on failure.
900  */
901 static uint32_t
902 txq_mp2mr(struct txq *txq, struct rte_mempool *mp)
903 {
904         unsigned int i;
905         struct ibv_mr *mr;
906
907         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
908                 if (unlikely(txq->mp2mr[i].mp == NULL)) {
909                         /* Unknown MP, add a new MR for it. */
910                         break;
911                 }
912                 if (txq->mp2mr[i].mp == mp) {
913                         assert(txq->mp2mr[i].lkey != (uint32_t)-1);
914                         assert(txq->mp2mr[i].mr->lkey == txq->mp2mr[i].lkey);
915                         return txq->mp2mr[i].lkey;
916                 }
917         }
918         /* Add a new entry, register MR first. */
919         DEBUG("%p: discovered new memory pool \"%s\" (%p)",
920               (void *)txq, mp->name, (void *)mp);
921         mr = mlx4_mp2mr(txq->priv->pd, mp);
922         if (unlikely(mr == NULL)) {
923                 DEBUG("%p: unable to configure MR, ibv_reg_mr() failed.",
924                       (void *)txq);
925                 return (uint32_t)-1;
926         }
927         if (unlikely(i == elemof(txq->mp2mr))) {
928                 /* Table is full, remove oldest entry. */
929                 DEBUG("%p: MR <-> MP table full, dropping oldest entry.",
930                       (void *)txq);
931                 --i;
932                 claim_zero(ibv_dereg_mr(txq->mp2mr[0].mr));
933                 memmove(&txq->mp2mr[0], &txq->mp2mr[1],
934                         (sizeof(txq->mp2mr) - sizeof(txq->mp2mr[0])));
935         }
936         /* Store the new entry. */
937         txq->mp2mr[i].mp = mp;
938         txq->mp2mr[i].mr = mr;
939         txq->mp2mr[i].lkey = mr->lkey;
940         DEBUG("%p: new MR lkey for MP \"%s\" (%p): 0x%08" PRIu32,
941               (void *)txq, mp->name, (void *)mp, txq->mp2mr[i].lkey);
942         return txq->mp2mr[i].lkey;
943 }
944
945 struct txq_mp2mr_mbuf_check_data {
946         int ret;
947 };
948
949 /**
950  * Callback function for rte_mempool_obj_iter() to check whether a given
951  * mempool object looks like a mbuf.
952  *
953  * @param[in] mp
954  *   The mempool pointer
955  * @param[in] arg
956  *   Context data (struct txq_mp2mr_mbuf_check_data). Contains the
957  *   return value.
958  * @param[in] obj
959  *   Object address.
960  * @param index
961  *   Object index, unused.
962  */
963 static void
964 txq_mp2mr_mbuf_check(struct rte_mempool *mp, void *arg, void *obj,
965         uint32_t index __rte_unused)
966 {
967         struct txq_mp2mr_mbuf_check_data *data = arg;
968         struct rte_mbuf *buf = obj;
969
970         /* Check whether mbuf structure fits element size and whether mempool
971          * pointer is valid. */
972         if (sizeof(*buf) > mp->elt_size || buf->pool != mp)
973                 data->ret = -1;
974 }
975
976 /**
977  * Iterator function for rte_mempool_walk() to register existing mempools and
978  * fill the MP to MR cache of a TX queue.
979  *
980  * @param[in] mp
981  *   Memory Pool to register.
982  * @param *arg
983  *   Pointer to TX queue structure.
984  */
985 static void
986 txq_mp2mr_iter(struct rte_mempool *mp, void *arg)
987 {
988         struct txq *txq = arg;
989         struct txq_mp2mr_mbuf_check_data data = {
990                 .ret = 0,
991         };
992
993         /* Register mempool only if the first element looks like a mbuf. */
994         if (rte_mempool_obj_iter(mp, txq_mp2mr_mbuf_check, &data) == 0 ||
995                         data.ret == -1)
996                 return;
997         txq_mp2mr(txq, mp);
998 }
999
1000 /**
1001  * DPDK callback for TX.
1002  *
1003  * @param dpdk_txq
1004  *   Generic pointer to TX queue structure.
1005  * @param[in] pkts
1006  *   Packets to transmit.
1007  * @param pkts_n
1008  *   Number of packets in array.
1009  *
1010  * @return
1011  *   Number of packets successfully transmitted (<= pkts_n).
1012  */
1013 static uint16_t
1014 mlx4_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
1015 {
1016         struct txq *txq = (struct txq *)dpdk_txq;
1017         unsigned int elts_head = txq->elts_head;
1018         const unsigned int elts_n = txq->elts_n;
1019         unsigned int elts_comp_cd = txq->elts_comp_cd;
1020         unsigned int elts_comp = 0;
1021         unsigned int i;
1022         unsigned int max;
1023         int err;
1024
1025         assert(elts_comp_cd != 0);
1026         txq_complete(txq);
1027         max = (elts_n - (elts_head - txq->elts_tail));
1028         if (max > elts_n)
1029                 max -= elts_n;
1030         assert(max >= 1);
1031         assert(max <= elts_n);
1032         /* Always leave one free entry in the ring. */
1033         --max;
1034         if (max == 0)
1035                 return 0;
1036         if (max > pkts_n)
1037                 max = pkts_n;
1038         for (i = 0; (i != max); ++i) {
1039                 struct rte_mbuf *buf = pkts[i];
1040                 unsigned int elts_head_next =
1041                         (((elts_head + 1) == elts_n) ? 0 : elts_head + 1);
1042                 struct txq_elt *elt_next = &(*txq->elts)[elts_head_next];
1043                 struct txq_elt *elt = &(*txq->elts)[elts_head];
1044                 unsigned int segs = NB_SEGS(buf);
1045                 unsigned int sent_size = 0;
1046                 uint32_t send_flags = 0;
1047
1048                 /* Clean up old buffer. */
1049                 if (likely(elt->buf != NULL)) {
1050                         struct rte_mbuf *tmp = elt->buf;
1051
1052 #ifndef NDEBUG
1053                         /* Poisoning. */
1054                         memset(elt, 0x66, sizeof(*elt));
1055 #endif
1056                         /* Faster than rte_pktmbuf_free(). */
1057                         do {
1058                                 struct rte_mbuf *next = NEXT(tmp);
1059
1060                                 rte_pktmbuf_free_seg(tmp);
1061                                 tmp = next;
1062                         } while (tmp != NULL);
1063                 }
1064                 /* Request TX completion. */
1065                 if (unlikely(--elts_comp_cd == 0)) {
1066                         elts_comp_cd = txq->elts_comp_cd_init;
1067                         ++elts_comp;
1068                         send_flags |= IBV_EXP_QP_BURST_SIGNALED;
1069                 }
1070                 if (likely(segs == 1)) {
1071                         uintptr_t addr;
1072                         uint32_t length;
1073                         uint32_t lkey;
1074
1075                         /* Retrieve buffer information. */
1076                         addr = rte_pktmbuf_mtod(buf, uintptr_t);
1077                         length = DATA_LEN(buf);
1078                         /* Retrieve Memory Region key for this memory pool. */
1079                         lkey = txq_mp2mr(txq, txq_mb2mp(buf));
1080                         if (unlikely(lkey == (uint32_t)-1)) {
1081                                 /* MR does not exist. */
1082                                 DEBUG("%p: unable to get MP <-> MR"
1083                                       " association", (void *)txq);
1084                                 /* Clean up TX element. */
1085                                 elt->buf = NULL;
1086                                 goto stop;
1087                         }
1088                         /* Update element. */
1089                         elt->buf = buf;
1090                         if (txq->priv->vf)
1091                                 rte_prefetch0((volatile void *)
1092                                               (uintptr_t)addr);
1093                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1094                         /* Put packet into send queue. */
1095                         if (length <= txq->max_inline)
1096                                 err = txq->if_qp->send_pending_inline
1097                                         (txq->qp,
1098                                          (void *)addr,
1099                                          length,
1100                                          send_flags);
1101                         else
1102                                 err = txq->if_qp->send_pending
1103                                         (txq->qp,
1104                                          addr,
1105                                          length,
1106                                          lkey,
1107                                          send_flags);
1108                         if (unlikely(err))
1109                                 goto stop;
1110                         sent_size += length;
1111                 } else {
1112                         err = -1;
1113                         goto stop;
1114                 }
1115                 elts_head = elts_head_next;
1116                 /* Increment sent bytes counter. */
1117                 txq->stats.obytes += sent_size;
1118         }
1119 stop:
1120         /* Take a shortcut if nothing must be sent. */
1121         if (unlikely(i == 0))
1122                 return 0;
1123         /* Increment sent packets counter. */
1124         txq->stats.opackets += i;
1125         /* Ring QP doorbell. */
1126         err = txq->if_qp->send_flush(txq->qp);
1127         if (unlikely(err)) {
1128                 /* A nonzero value is not supposed to be returned.
1129                  * Nothing can be done about it. */
1130                 DEBUG("%p: send_flush() failed with error %d",
1131                       (void *)txq, err);
1132         }
1133         txq->elts_head = elts_head;
1134         txq->elts_comp += elts_comp;
1135         txq->elts_comp_cd = elts_comp_cd;
1136         return i;
1137 }
1138
1139 /**
1140  * Configure a TX queue.
1141  *
1142  * @param dev
1143  *   Pointer to Ethernet device structure.
1144  * @param txq
1145  *   Pointer to TX queue structure.
1146  * @param desc
1147  *   Number of descriptors to configure in queue.
1148  * @param socket
1149  *   NUMA socket on which memory must be allocated.
1150  * @param[in] conf
1151  *   Thresholds parameters.
1152  *
1153  * @return
1154  *   0 on success, errno value on failure.
1155  */
1156 static int
1157 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
1158           unsigned int socket, const struct rte_eth_txconf *conf)
1159 {
1160         struct priv *priv = dev->data->dev_private;
1161         struct txq tmpl = {
1162                 .priv = priv,
1163                 .socket = socket
1164         };
1165         union {
1166                 struct ibv_exp_query_intf_params params;
1167                 struct ibv_qp_init_attr init;
1168                 struct ibv_qp_attr mod;
1169         } attr;
1170         enum ibv_exp_query_intf_status status;
1171         int ret = 0;
1172
1173         (void)conf; /* Thresholds configuration (ignored). */
1174         if (priv == NULL)
1175                 return EINVAL;
1176         if (desc == 0) {
1177                 ERROR("%p: invalid number of Tx descriptors", (void *)dev);
1178                 return EINVAL;
1179         }
1180         /* MRs will be registered in mp2mr[] later. */
1181         tmpl.cq = ibv_create_cq(priv->ctx, desc, NULL, NULL, 0);
1182         if (tmpl.cq == NULL) {
1183                 ret = ENOMEM;
1184                 ERROR("%p: CQ creation failure: %s",
1185                       (void *)dev, strerror(ret));
1186                 goto error;
1187         }
1188         DEBUG("priv->device_attr.max_qp_wr is %d",
1189               priv->device_attr.max_qp_wr);
1190         DEBUG("priv->device_attr.max_sge is %d",
1191               priv->device_attr.max_sge);
1192         attr.init = (struct ibv_qp_init_attr){
1193                 /* CQ to be associated with the send queue. */
1194                 .send_cq = tmpl.cq,
1195                 /* CQ to be associated with the receive queue. */
1196                 .recv_cq = tmpl.cq,
1197                 .cap = {
1198                         /* Max number of outstanding WRs. */
1199                         .max_send_wr = ((priv->device_attr.max_qp_wr < desc) ?
1200                                         priv->device_attr.max_qp_wr :
1201                                         desc),
1202                         /* Max number of scatter/gather elements in a WR. */
1203                         .max_send_sge = 1,
1204                         .max_inline_data = MLX4_PMD_MAX_INLINE,
1205                 },
1206                 .qp_type = IBV_QPT_RAW_PACKET,
1207                 /* Do *NOT* enable this, completions events are managed per
1208                  * TX burst. */
1209                 .sq_sig_all = 0,
1210         };
1211         tmpl.qp = ibv_create_qp(priv->pd, &attr.init);
1212         if (tmpl.qp == NULL) {
1213                 ret = (errno ? errno : EINVAL);
1214                 ERROR("%p: QP creation failure: %s",
1215                       (void *)dev, strerror(ret));
1216                 goto error;
1217         }
1218         /* ibv_create_qp() updates this value. */
1219         tmpl.max_inline = attr.init.cap.max_inline_data;
1220         attr.mod = (struct ibv_qp_attr){
1221                 /* Move the QP to this state. */
1222                 .qp_state = IBV_QPS_INIT,
1223                 /* Primary port number. */
1224                 .port_num = priv->port
1225         };
1226         ret = ibv_modify_qp(tmpl.qp, &attr.mod, IBV_QP_STATE | IBV_QP_PORT);
1227         if (ret) {
1228                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1229                       (void *)dev, strerror(ret));
1230                 goto error;
1231         }
1232         ret = txq_alloc_elts(&tmpl, desc);
1233         if (ret) {
1234                 ERROR("%p: TXQ allocation failed: %s",
1235                       (void *)dev, strerror(ret));
1236                 goto error;
1237         }
1238         attr.mod = (struct ibv_qp_attr){
1239                 .qp_state = IBV_QPS_RTR
1240         };
1241         ret = ibv_modify_qp(tmpl.qp, &attr.mod, IBV_QP_STATE);
1242         if (ret) {
1243                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1244                       (void *)dev, strerror(ret));
1245                 goto error;
1246         }
1247         attr.mod.qp_state = IBV_QPS_RTS;
1248         ret = ibv_modify_qp(tmpl.qp, &attr.mod, IBV_QP_STATE);
1249         if (ret) {
1250                 ERROR("%p: QP state to IBV_QPS_RTS failed: %s",
1251                       (void *)dev, strerror(ret));
1252                 goto error;
1253         }
1254         attr.params = (struct ibv_exp_query_intf_params){
1255                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1256                 .intf = IBV_EXP_INTF_CQ,
1257                 .obj = tmpl.cq,
1258         };
1259         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1260         if (tmpl.if_cq == NULL) {
1261                 ERROR("%p: CQ interface family query failed with status %d",
1262                       (void *)dev, status);
1263                 goto error;
1264         }
1265         attr.params = (struct ibv_exp_query_intf_params){
1266                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1267                 .intf = IBV_EXP_INTF_QP_BURST,
1268                 .obj = tmpl.qp,
1269         };
1270         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1271         if (tmpl.if_qp == NULL) {
1272                 ERROR("%p: QP interface family query failed with status %d",
1273                       (void *)dev, status);
1274                 goto error;
1275         }
1276         /* Clean up txq in case we're reinitializing it. */
1277         DEBUG("%p: cleaning-up old txq just in case", (void *)txq);
1278         txq_cleanup(txq);
1279         *txq = tmpl;
1280         DEBUG("%p: txq updated with %p", (void *)txq, (void *)&tmpl);
1281         /* Pre-register known mempools. */
1282         rte_mempool_walk(txq_mp2mr_iter, txq);
1283         assert(ret == 0);
1284         return 0;
1285 error:
1286         txq_cleanup(&tmpl);
1287         assert(ret > 0);
1288         return ret;
1289 }
1290
1291 /**
1292  * DPDK callback to configure a TX queue.
1293  *
1294  * @param dev
1295  *   Pointer to Ethernet device structure.
1296  * @param idx
1297  *   TX queue index.
1298  * @param desc
1299  *   Number of descriptors to configure in queue.
1300  * @param socket
1301  *   NUMA socket on which memory must be allocated.
1302  * @param[in] conf
1303  *   Thresholds parameters.
1304  *
1305  * @return
1306  *   0 on success, negative errno value on failure.
1307  */
1308 static int
1309 mlx4_tx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1310                     unsigned int socket, const struct rte_eth_txconf *conf)
1311 {
1312         struct priv *priv = dev->data->dev_private;
1313         struct txq *txq = (*priv->txqs)[idx];
1314         int ret;
1315
1316         priv_lock(priv);
1317         DEBUG("%p: configuring queue %u for %u descriptors",
1318               (void *)dev, idx, desc);
1319         if (idx >= priv->txqs_n) {
1320                 ERROR("%p: queue index out of range (%u >= %u)",
1321                       (void *)dev, idx, priv->txqs_n);
1322                 priv_unlock(priv);
1323                 return -EOVERFLOW;
1324         }
1325         if (txq != NULL) {
1326                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1327                       (void *)dev, idx, (void *)txq);
1328                 if (priv->started) {
1329                         priv_unlock(priv);
1330                         return -EEXIST;
1331                 }
1332                 (*priv->txqs)[idx] = NULL;
1333                 txq_cleanup(txq);
1334         } else {
1335                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0, socket);
1336                 if (txq == NULL) {
1337                         ERROR("%p: unable to allocate queue index %u",
1338                               (void *)dev, idx);
1339                         priv_unlock(priv);
1340                         return -ENOMEM;
1341                 }
1342         }
1343         ret = txq_setup(dev, txq, desc, socket, conf);
1344         if (ret)
1345                 rte_free(txq);
1346         else {
1347                 txq->stats.idx = idx;
1348                 DEBUG("%p: adding TX queue %p to list",
1349                       (void *)dev, (void *)txq);
1350                 (*priv->txqs)[idx] = txq;
1351                 /* Update send callback. */
1352                 dev->tx_pkt_burst = mlx4_tx_burst;
1353         }
1354         priv_unlock(priv);
1355         return -ret;
1356 }
1357
1358 /**
1359  * DPDK callback to release a TX queue.
1360  *
1361  * @param dpdk_txq
1362  *   Generic TX queue pointer.
1363  */
1364 static void
1365 mlx4_tx_queue_release(void *dpdk_txq)
1366 {
1367         struct txq *txq = (struct txq *)dpdk_txq;
1368         struct priv *priv;
1369         unsigned int i;
1370
1371         if (txq == NULL)
1372                 return;
1373         priv = txq->priv;
1374         priv_lock(priv);
1375         for (i = 0; (i != priv->txqs_n); ++i)
1376                 if ((*priv->txqs)[i] == txq) {
1377                         DEBUG("%p: removing TX queue %p from list",
1378                               (void *)priv->dev, (void *)txq);
1379                         (*priv->txqs)[i] = NULL;
1380                         break;
1381                 }
1382         txq_cleanup(txq);
1383         rte_free(txq);
1384         priv_unlock(priv);
1385 }
1386
1387 /* RX queues handling. */
1388
1389 /**
1390  * Allocate RX queue elements.
1391  *
1392  * @param rxq
1393  *   Pointer to RX queue structure.
1394  * @param elts_n
1395  *   Number of elements to allocate.
1396  *
1397  * @return
1398  *   0 on success, errno value on failure.
1399  */
1400 static int
1401 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n)
1402 {
1403         unsigned int i;
1404         struct rxq_elt (*elts)[elts_n] =
1405                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1406                                   rxq->socket);
1407         int ret = 0;
1408
1409         if (elts == NULL) {
1410                 ERROR("%p: can't allocate packets array", (void *)rxq);
1411                 ret = ENOMEM;
1412                 goto error;
1413         }
1414         /* For each WR (packet). */
1415         for (i = 0; (i != elts_n); ++i) {
1416                 struct rxq_elt *elt = &(*elts)[i];
1417                 struct ibv_recv_wr *wr = &elt->wr;
1418                 struct ibv_sge *sge = &(*elts)[i].sge;
1419                 struct rte_mbuf *buf = rte_pktmbuf_alloc(rxq->mp);
1420
1421                 if (buf == NULL) {
1422                         ERROR("%p: empty mbuf pool", (void *)rxq);
1423                         ret = ENOMEM;
1424                         goto error;
1425                 }
1426                 /* Configure WR. Work request ID contains its own index in
1427                  * the elts array and the offset between SGE buffer header and
1428                  * its data. */
1429                 WR_ID(wr->wr_id).id = i;
1430                 WR_ID(wr->wr_id).offset =
1431                         (((uintptr_t)buf->buf_addr + RTE_PKTMBUF_HEADROOM) -
1432                          (uintptr_t)buf);
1433                 wr->next = &(*elts)[(i + 1)].wr;
1434                 wr->sg_list = sge;
1435                 wr->num_sge = 1;
1436                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
1437                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1438                 /* Buffer is supposed to be empty. */
1439                 assert(rte_pktmbuf_data_len(buf) == 0);
1440                 assert(rte_pktmbuf_pkt_len(buf) == 0);
1441                 /* sge->addr must be able to store a pointer. */
1442                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1443                 /* SGE keeps its headroom. */
1444                 sge->addr = (uintptr_t)
1445                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
1446                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
1447                 sge->lkey = rxq->mr->lkey;
1448                 /* Redundant check for tailroom. */
1449                 assert(sge->length == rte_pktmbuf_tailroom(buf));
1450                 /* Make sure elts index and SGE mbuf pointer can be deduced
1451                  * from WR ID. */
1452                 if ((WR_ID(wr->wr_id).id != i) ||
1453                     ((void *)((uintptr_t)sge->addr -
1454                         WR_ID(wr->wr_id).offset) != buf)) {
1455                         ERROR("%p: cannot store index and offset in WR ID",
1456                               (void *)rxq);
1457                         sge->addr = 0;
1458                         rte_pktmbuf_free(buf);
1459                         ret = EOVERFLOW;
1460                         goto error;
1461                 }
1462         }
1463         /* The last WR pointer must be NULL. */
1464         (*elts)[(i - 1)].wr.next = NULL;
1465         DEBUG("%p: allocated and configured %u single-segment WRs",
1466               (void *)rxq, elts_n);
1467         rxq->elts_n = elts_n;
1468         rxq->elts_head = 0;
1469         rxq->elts = elts;
1470         assert(ret == 0);
1471         return 0;
1472 error:
1473         if (elts != NULL) {
1474                 for (i = 0; (i != elemof(*elts)); ++i) {
1475                         struct rxq_elt *elt = &(*elts)[i];
1476                         struct rte_mbuf *buf;
1477
1478                         if (elt->sge.addr == 0)
1479                                 continue;
1480                         assert(WR_ID(elt->wr.wr_id).id == i);
1481                         buf = (void *)((uintptr_t)elt->sge.addr -
1482                                 WR_ID(elt->wr.wr_id).offset);
1483                         rte_pktmbuf_free_seg(buf);
1484                 }
1485                 rte_free(elts);
1486         }
1487         DEBUG("%p: failed, freed everything", (void *)rxq);
1488         assert(ret > 0);
1489         return ret;
1490 }
1491
1492 /**
1493  * Free RX queue elements.
1494  *
1495  * @param rxq
1496  *   Pointer to RX queue structure.
1497  */
1498 static void
1499 rxq_free_elts(struct rxq *rxq)
1500 {
1501         unsigned int i;
1502         unsigned int elts_n = rxq->elts_n;
1503         struct rxq_elt (*elts)[elts_n] = rxq->elts;
1504
1505         DEBUG("%p: freeing WRs", (void *)rxq);
1506         rxq->elts_n = 0;
1507         rxq->elts = NULL;
1508         if (elts == NULL)
1509                 return;
1510         for (i = 0; (i != elemof(*elts)); ++i) {
1511                 struct rxq_elt *elt = &(*elts)[i];
1512                 struct rte_mbuf *buf;
1513
1514                 if (elt->sge.addr == 0)
1515                         continue;
1516                 assert(WR_ID(elt->wr.wr_id).id == i);
1517                 buf = (void *)((uintptr_t)elt->sge.addr -
1518                         WR_ID(elt->wr.wr_id).offset);
1519                 rte_pktmbuf_free_seg(buf);
1520         }
1521         rte_free(elts);
1522 }
1523
1524 /**
1525  * Unregister a MAC address.
1526  *
1527  * @param priv
1528  *   Pointer to private structure.
1529  */
1530 static void
1531 priv_mac_addr_del(struct priv *priv)
1532 {
1533 #ifndef NDEBUG
1534         uint8_t (*mac)[ETHER_ADDR_LEN] = &priv->mac.addr_bytes;
1535 #endif
1536
1537         if (!priv->mac_flow)
1538                 return;
1539         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x",
1540               (void *)priv,
1541               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);
1542         claim_zero(ibv_destroy_flow(priv->mac_flow));
1543         priv->mac_flow = NULL;
1544 }
1545
1546 /**
1547  * Register a MAC address.
1548  *
1549  * The MAC address is registered in queue 0.
1550  *
1551  * @param priv
1552  *   Pointer to private structure.
1553  *
1554  * @return
1555  *   0 on success, errno value on failure.
1556  */
1557 static int
1558 priv_mac_addr_add(struct priv *priv)
1559 {
1560         uint8_t (*mac)[ETHER_ADDR_LEN] = &priv->mac.addr_bytes;
1561         struct rxq *rxq;
1562         struct ibv_flow *flow;
1563
1564         /* If device isn't started, this is all we need to do. */
1565         if (!priv->started)
1566                 return 0;
1567         if (priv->isolated)
1568                 return 0;
1569         if (*priv->rxqs && (*priv->rxqs)[0])
1570                 rxq = (*priv->rxqs)[0];
1571         else
1572                 return 0;
1573
1574         /* Allocate flow specification on the stack. */
1575         struct __attribute__((packed)) {
1576                 struct ibv_flow_attr attr;
1577                 struct ibv_flow_spec_eth spec;
1578         } data;
1579         struct ibv_flow_attr *attr = &data.attr;
1580         struct ibv_flow_spec_eth *spec = &data.spec;
1581
1582         if (priv->mac_flow)
1583                 priv_mac_addr_del(priv);
1584         /*
1585          * No padding must be inserted by the compiler between attr and spec.
1586          * This layout is expected by libibverbs.
1587          */
1588         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
1589         *attr = (struct ibv_flow_attr){
1590                 .type = IBV_FLOW_ATTR_NORMAL,
1591                 .priority = 3,
1592                 .num_of_specs = 1,
1593                 .port = priv->port,
1594                 .flags = 0
1595         };
1596         *spec = (struct ibv_flow_spec_eth){
1597                 .type = IBV_FLOW_SPEC_ETH,
1598                 .size = sizeof(*spec),
1599                 .val = {
1600                         .dst_mac = {
1601                                 (*mac)[0], (*mac)[1], (*mac)[2],
1602                                 (*mac)[3], (*mac)[4], (*mac)[5]
1603                         },
1604                 },
1605                 .mask = {
1606                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
1607                 }
1608         };
1609         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x",
1610               (void *)priv,
1611               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);
1612         /* Create related flow. */
1613         errno = 0;
1614         flow = ibv_create_flow(rxq->qp, attr);
1615         if (flow == NULL) {
1616                 /* It's not clear whether errno is always set in this case. */
1617                 ERROR("%p: flow configuration failed, errno=%d: %s",
1618                       (void *)rxq, errno,
1619                       (errno ? strerror(errno) : "Unknown error"));
1620                 if (errno)
1621                         return errno;
1622                 return EINVAL;
1623         }
1624         assert(priv->mac_flow == NULL);
1625         priv->mac_flow = flow;
1626         return 0;
1627 }
1628
1629 /**
1630  * Clean up a RX queue.
1631  *
1632  * Destroy objects, free allocated memory and reset the structure for reuse.
1633  *
1634  * @param rxq
1635  *   Pointer to RX queue structure.
1636  */
1637 static void
1638 rxq_cleanup(struct rxq *rxq)
1639 {
1640         struct ibv_exp_release_intf_params params;
1641
1642         DEBUG("cleaning up %p", (void *)rxq);
1643         rxq_free_elts(rxq);
1644         if (rxq->if_qp != NULL) {
1645                 assert(rxq->priv != NULL);
1646                 assert(rxq->priv->ctx != NULL);
1647                 assert(rxq->qp != NULL);
1648                 params = (struct ibv_exp_release_intf_params){
1649                         .comp_mask = 0,
1650                 };
1651                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
1652                                                 rxq->if_qp,
1653                                                 &params));
1654         }
1655         if (rxq->if_cq != NULL) {
1656                 assert(rxq->priv != NULL);
1657                 assert(rxq->priv->ctx != NULL);
1658                 assert(rxq->cq != NULL);
1659                 params = (struct ibv_exp_release_intf_params){
1660                         .comp_mask = 0,
1661                 };
1662                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
1663                                                 rxq->if_cq,
1664                                                 &params));
1665         }
1666         if (rxq->qp != NULL)
1667                 claim_zero(ibv_destroy_qp(rxq->qp));
1668         if (rxq->cq != NULL)
1669                 claim_zero(ibv_destroy_cq(rxq->cq));
1670         if (rxq->channel != NULL)
1671                 claim_zero(ibv_destroy_comp_channel(rxq->channel));
1672         if (rxq->mr != NULL)
1673                 claim_zero(ibv_dereg_mr(rxq->mr));
1674         memset(rxq, 0, sizeof(*rxq));
1675 }
1676
1677 /**
1678  * DPDK callback for RX.
1679  *
1680  * The following function doesn't manage scattered packets.
1681  *
1682  * @param dpdk_rxq
1683  *   Generic pointer to RX queue structure.
1684  * @param[out] pkts
1685  *   Array to store received packets.
1686  * @param pkts_n
1687  *   Maximum number of packets in array.
1688  *
1689  * @return
1690  *   Number of packets successfully received (<= pkts_n).
1691  */
1692 static uint16_t
1693 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
1694 {
1695         struct rxq *rxq = (struct rxq *)dpdk_rxq;
1696         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts;
1697         const unsigned int elts_n = rxq->elts_n;
1698         unsigned int elts_head = rxq->elts_head;
1699         struct ibv_sge sges[pkts_n];
1700         unsigned int i;
1701         unsigned int pkts_ret = 0;
1702         int ret;
1703
1704         for (i = 0; (i != pkts_n); ++i) {
1705                 struct rxq_elt *elt = &(*elts)[elts_head];
1706                 struct ibv_recv_wr *wr = &elt->wr;
1707                 uint64_t wr_id = wr->wr_id;
1708                 unsigned int len;
1709                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
1710                         WR_ID(wr_id).offset);
1711                 struct rte_mbuf *rep;
1712                 uint32_t flags;
1713
1714                 /* Sanity checks. */
1715                 assert(WR_ID(wr_id).id < rxq->elts_n);
1716                 assert(wr->sg_list == &elt->sge);
1717                 assert(wr->num_sge == 1);
1718                 assert(elts_head < rxq->elts_n);
1719                 assert(rxq->elts_head < rxq->elts_n);
1720                 /*
1721                  * Fetch initial bytes of packet descriptor into a
1722                  * cacheline while allocating rep.
1723                  */
1724                 rte_mbuf_prefetch_part1(seg);
1725                 rte_mbuf_prefetch_part2(seg);
1726                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
1727                                                     &flags);
1728                 if (unlikely(ret < 0)) {
1729                         struct ibv_wc wc;
1730                         int wcs_n;
1731
1732                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
1733                               (void *)rxq, ret);
1734                         /* ibv_poll_cq() must be used in case of failure. */
1735                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
1736                         if (unlikely(wcs_n == 0))
1737                                 break;
1738                         if (unlikely(wcs_n < 0)) {
1739                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
1740                                       (void *)rxq, wcs_n);
1741                                 break;
1742                         }
1743                         assert(wcs_n == 1);
1744                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
1745                                 /* Whatever, just repost the offending WR. */
1746                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
1747                                       " completion status (%d): %s",
1748                                       (void *)rxq, wc.wr_id, wc.status,
1749                                       ibv_wc_status_str(wc.status));
1750                                 /* Increment dropped packets counter. */
1751                                 ++rxq->stats.idropped;
1752                                 /* Add SGE to array for repost. */
1753                                 sges[i] = elt->sge;
1754                                 goto repost;
1755                         }
1756                         ret = wc.byte_len;
1757                 }
1758                 if (ret == 0)
1759                         break;
1760                 len = ret;
1761                 rep = rte_mbuf_raw_alloc(rxq->mp);
1762                 if (unlikely(rep == NULL)) {
1763                         /*
1764                          * Unable to allocate a replacement mbuf,
1765                          * repost WR.
1766                          */
1767                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
1768                               " can't allocate a new mbuf",
1769                               (void *)rxq, WR_ID(wr_id).id);
1770                         /* Increase out of memory counters. */
1771                         ++rxq->stats.rx_nombuf;
1772                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
1773                         /* Add SGE to array for repost. */
1774                         sges[i] = elt->sge;
1775                         goto repost;
1776                 }
1777
1778                 /* Reconfigure sge to use rep instead of seg. */
1779                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
1780                 assert(elt->sge.lkey == rxq->mr->lkey);
1781                 WR_ID(wr->wr_id).offset =
1782                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
1783                          (uintptr_t)rep);
1784                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
1785
1786                 /* Add SGE to array for repost. */
1787                 sges[i] = elt->sge;
1788
1789                 /* Update seg information. */
1790                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
1791                 NB_SEGS(seg) = 1;
1792                 PORT(seg) = rxq->port_id;
1793                 NEXT(seg) = NULL;
1794                 PKT_LEN(seg) = len;
1795                 DATA_LEN(seg) = len;
1796                 seg->packet_type = 0;
1797                 seg->ol_flags = 0;
1798
1799                 /* Return packet. */
1800                 *(pkts++) = seg;
1801                 ++pkts_ret;
1802                 /* Increase bytes counter. */
1803                 rxq->stats.ibytes += len;
1804 repost:
1805                 if (++elts_head >= elts_n)
1806                         elts_head = 0;
1807                 continue;
1808         }
1809         if (unlikely(i == 0))
1810                 return 0;
1811         /* Repost WRs. */
1812         ret = rxq->if_qp->recv_burst(rxq->qp, sges, i);
1813         if (unlikely(ret)) {
1814                 /* Inability to repost WRs is fatal. */
1815                 DEBUG("%p: recv_burst(): failed (ret=%d)",
1816                       (void *)rxq->priv,
1817                       ret);
1818                 abort();
1819         }
1820         rxq->elts_head = elts_head;
1821         /* Increase packets counter. */
1822         rxq->stats.ipackets += pkts_ret;
1823         return pkts_ret;
1824 }
1825
1826 /**
1827  * Allocate a Queue Pair.
1828  * Optionally setup inline receive if supported.
1829  *
1830  * @param priv
1831  *   Pointer to private structure.
1832  * @param cq
1833  *   Completion queue to associate with QP.
1834  * @param desc
1835  *   Number of descriptors in QP (hint only).
1836  *
1837  * @return
1838  *   QP pointer or NULL in case of error.
1839  */
1840 static struct ibv_qp *
1841 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc)
1842 {
1843         struct ibv_qp_init_attr attr = {
1844                 /* CQ to be associated with the send queue. */
1845                 .send_cq = cq,
1846                 /* CQ to be associated with the receive queue. */
1847                 .recv_cq = cq,
1848                 .cap = {
1849                         /* Max number of outstanding WRs. */
1850                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
1851                                         priv->device_attr.max_qp_wr :
1852                                         desc),
1853                         /* Max number of scatter/gather elements in a WR. */
1854                         .max_recv_sge = 1,
1855                 },
1856                 .qp_type = IBV_QPT_RAW_PACKET,
1857         };
1858
1859         return ibv_create_qp(priv->pd, &attr);
1860 }
1861
1862 /**
1863  * Configure a RX queue.
1864  *
1865  * @param dev
1866  *   Pointer to Ethernet device structure.
1867  * @param rxq
1868  *   Pointer to RX queue structure.
1869  * @param desc
1870  *   Number of descriptors to configure in queue.
1871  * @param socket
1872  *   NUMA socket on which memory must be allocated.
1873  * @param[in] conf
1874  *   Thresholds parameters.
1875  * @param mp
1876  *   Memory pool for buffer allocations.
1877  *
1878  * @return
1879  *   0 on success, errno value on failure.
1880  */
1881 static int
1882 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
1883           unsigned int socket, const struct rte_eth_rxconf *conf,
1884           struct rte_mempool *mp)
1885 {
1886         struct priv *priv = dev->data->dev_private;
1887         struct rxq tmpl = {
1888                 .priv = priv,
1889                 .mp = mp,
1890                 .socket = socket
1891         };
1892         struct ibv_qp_attr mod;
1893         union {
1894                 struct ibv_exp_query_intf_params params;
1895         } attr;
1896         enum ibv_exp_query_intf_status status;
1897         struct ibv_recv_wr *bad_wr;
1898         unsigned int mb_len;
1899         int ret = 0;
1900
1901         (void)conf; /* Thresholds configuration (ignored). */
1902         mb_len = rte_pktmbuf_data_room_size(mp);
1903         if (desc == 0) {
1904                 ERROR("%p: invalid number of Rx descriptors", (void *)dev);
1905                 return EINVAL;
1906         }
1907         /* Enable scattered packets support for this queue if necessary. */
1908         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
1909         if (dev->data->dev_conf.rxmode.max_rx_pkt_len <=
1910             (mb_len - RTE_PKTMBUF_HEADROOM)) {
1911                 ;
1912         } else if (dev->data->dev_conf.rxmode.enable_scatter) {
1913                 WARN("%p: scattered mode has been requested but is"
1914                      " not supported, this may lead to packet loss",
1915                      (void *)dev);
1916         } else {
1917                 WARN("%p: the requested maximum Rx packet size (%u) is"
1918                      " larger than a single mbuf (%u) and scattered"
1919                      " mode has not been requested",
1920                      (void *)dev,
1921                      dev->data->dev_conf.rxmode.max_rx_pkt_len,
1922                      mb_len - RTE_PKTMBUF_HEADROOM);
1923         }
1924         /* Use the entire RX mempool as the memory region. */
1925         tmpl.mr = mlx4_mp2mr(priv->pd, mp);
1926         if (tmpl.mr == NULL) {
1927                 ret = EINVAL;
1928                 ERROR("%p: MR creation failure: %s",
1929                       (void *)dev, strerror(ret));
1930                 goto error;
1931         }
1932         if (dev->data->dev_conf.intr_conf.rxq) {
1933                 tmpl.channel = ibv_create_comp_channel(priv->ctx);
1934                 if (tmpl.channel == NULL) {
1935                         ret = ENOMEM;
1936                         ERROR("%p: Rx interrupt completion channel creation"
1937                               " failure: %s",
1938                               (void *)dev, strerror(ret));
1939                         goto error;
1940                 }
1941         }
1942         tmpl.cq = ibv_create_cq(priv->ctx, desc, NULL, tmpl.channel, 0);
1943         if (tmpl.cq == NULL) {
1944                 ret = ENOMEM;
1945                 ERROR("%p: CQ creation failure: %s",
1946                       (void *)dev, strerror(ret));
1947                 goto error;
1948         }
1949         DEBUG("priv->device_attr.max_qp_wr is %d",
1950               priv->device_attr.max_qp_wr);
1951         DEBUG("priv->device_attr.max_sge is %d",
1952               priv->device_attr.max_sge);
1953         tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc);
1954         if (tmpl.qp == NULL) {
1955                 ret = (errno ? errno : EINVAL);
1956                 ERROR("%p: QP creation failure: %s",
1957                       (void *)dev, strerror(ret));
1958                 goto error;
1959         }
1960         mod = (struct ibv_qp_attr){
1961                 /* Move the QP to this state. */
1962                 .qp_state = IBV_QPS_INIT,
1963                 /* Primary port number. */
1964                 .port_num = priv->port
1965         };
1966         ret = ibv_modify_qp(tmpl.qp, &mod, IBV_QP_STATE | IBV_QP_PORT);
1967         if (ret) {
1968                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1969                       (void *)dev, strerror(ret));
1970                 goto error;
1971         }
1972         ret = rxq_alloc_elts(&tmpl, desc);
1973         if (ret) {
1974                 ERROR("%p: RXQ allocation failed: %s",
1975                       (void *)dev, strerror(ret));
1976                 goto error;
1977         }
1978         ret = ibv_post_recv(tmpl.qp, &(*tmpl.elts)[0].wr, &bad_wr);
1979         if (ret) {
1980                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
1981                       (void *)dev,
1982                       (void *)bad_wr,
1983                       strerror(ret));
1984                 goto error;
1985         }
1986         mod = (struct ibv_qp_attr){
1987                 .qp_state = IBV_QPS_RTR
1988         };
1989         ret = ibv_modify_qp(tmpl.qp, &mod, IBV_QP_STATE);
1990         if (ret) {
1991                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1992                       (void *)dev, strerror(ret));
1993                 goto error;
1994         }
1995         /* Save port ID. */
1996         tmpl.port_id = dev->data->port_id;
1997         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
1998         attr.params = (struct ibv_exp_query_intf_params){
1999                 .intf_scope = IBV_EXP_INTF_GLOBAL,
2000                 .intf = IBV_EXP_INTF_CQ,
2001                 .obj = tmpl.cq,
2002         };
2003         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
2004         if (tmpl.if_cq == NULL) {
2005                 ERROR("%p: CQ interface family query failed with status %d",
2006                       (void *)dev, status);
2007                 goto error;
2008         }
2009         attr.params = (struct ibv_exp_query_intf_params){
2010                 .intf_scope = IBV_EXP_INTF_GLOBAL,
2011                 .intf = IBV_EXP_INTF_QP_BURST,
2012                 .obj = tmpl.qp,
2013         };
2014         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
2015         if (tmpl.if_qp == NULL) {
2016                 ERROR("%p: QP interface family query failed with status %d",
2017                       (void *)dev, status);
2018                 goto error;
2019         }
2020         /* Clean up rxq in case we're reinitializing it. */
2021         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
2022         rxq_cleanup(rxq);
2023         *rxq = tmpl;
2024         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
2025         assert(ret == 0);
2026         return 0;
2027 error:
2028         rxq_cleanup(&tmpl);
2029         assert(ret > 0);
2030         return ret;
2031 }
2032
2033 /**
2034  * DPDK callback to configure a RX queue.
2035  *
2036  * @param dev
2037  *   Pointer to Ethernet device structure.
2038  * @param idx
2039  *   RX queue index.
2040  * @param desc
2041  *   Number of descriptors to configure in queue.
2042  * @param socket
2043  *   NUMA socket on which memory must be allocated.
2044  * @param[in] conf
2045  *   Thresholds parameters.
2046  * @param mp
2047  *   Memory pool for buffer allocations.
2048  *
2049  * @return
2050  *   0 on success, negative errno value on failure.
2051  */
2052 static int
2053 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
2054                     unsigned int socket, const struct rte_eth_rxconf *conf,
2055                     struct rte_mempool *mp)
2056 {
2057         struct priv *priv = dev->data->dev_private;
2058         struct rxq *rxq = (*priv->rxqs)[idx];
2059         int ret;
2060
2061         priv_lock(priv);
2062         DEBUG("%p: configuring queue %u for %u descriptors",
2063               (void *)dev, idx, desc);
2064         if (idx >= priv->rxqs_n) {
2065                 ERROR("%p: queue index out of range (%u >= %u)",
2066                       (void *)dev, idx, priv->rxqs_n);
2067                 priv_unlock(priv);
2068                 return -EOVERFLOW;
2069         }
2070         if (rxq != NULL) {
2071                 DEBUG("%p: reusing already allocated queue index %u (%p)",
2072                       (void *)dev, idx, (void *)rxq);
2073                 if (priv->started) {
2074                         priv_unlock(priv);
2075                         return -EEXIST;
2076                 }
2077                 (*priv->rxqs)[idx] = NULL;
2078                 if (idx == 0)
2079                         priv_mac_addr_del(priv);
2080                 rxq_cleanup(rxq);
2081         } else {
2082                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
2083                 if (rxq == NULL) {
2084                         ERROR("%p: unable to allocate queue index %u",
2085                               (void *)dev, idx);
2086                         priv_unlock(priv);
2087                         return -ENOMEM;
2088                 }
2089         }
2090         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
2091         if (ret)
2092                 rte_free(rxq);
2093         else {
2094                 rxq->stats.idx = idx;
2095                 DEBUG("%p: adding RX queue %p to list",
2096                       (void *)dev, (void *)rxq);
2097                 (*priv->rxqs)[idx] = rxq;
2098                 /* Update receive callback. */
2099                 dev->rx_pkt_burst = mlx4_rx_burst;
2100         }
2101         priv_unlock(priv);
2102         return -ret;
2103 }
2104
2105 /**
2106  * DPDK callback to release a RX queue.
2107  *
2108  * @param dpdk_rxq
2109  *   Generic RX queue pointer.
2110  */
2111 static void
2112 mlx4_rx_queue_release(void *dpdk_rxq)
2113 {
2114         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2115         struct priv *priv;
2116         unsigned int i;
2117
2118         if (rxq == NULL)
2119                 return;
2120         priv = rxq->priv;
2121         priv_lock(priv);
2122         for (i = 0; (i != priv->rxqs_n); ++i)
2123                 if ((*priv->rxqs)[i] == rxq) {
2124                         DEBUG("%p: removing RX queue %p from list",
2125                               (void *)priv->dev, (void *)rxq);
2126                         (*priv->rxqs)[i] = NULL;
2127                         if (i == 0)
2128                                 priv_mac_addr_del(priv);
2129                         break;
2130                 }
2131         rxq_cleanup(rxq);
2132         rte_free(rxq);
2133         priv_unlock(priv);
2134 }
2135
2136 static int
2137 priv_dev_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2138
2139 static int
2140 priv_dev_removal_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2141
2142 static int
2143 priv_dev_link_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2144
2145 /**
2146  * DPDK callback to start the device.
2147  *
2148  * Simulate device start by attaching all configured flows.
2149  *
2150  * @param dev
2151  *   Pointer to Ethernet device structure.
2152  *
2153  * @return
2154  *   0 on success, negative errno value on failure.
2155  */
2156 static int
2157 mlx4_dev_start(struct rte_eth_dev *dev)
2158 {
2159         struct priv *priv = dev->data->dev_private;
2160         int ret;
2161
2162         priv_lock(priv);
2163         if (priv->started) {
2164                 priv_unlock(priv);
2165                 return 0;
2166         }
2167         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
2168         priv->started = 1;
2169         ret = priv_mac_addr_add(priv);
2170         if (ret)
2171                 goto err;
2172         ret = priv_dev_link_interrupt_handler_install(priv, dev);
2173         if (ret) {
2174                 ERROR("%p: LSC handler install failed",
2175                      (void *)dev);
2176                 goto err;
2177         }
2178         ret = priv_dev_removal_interrupt_handler_install(priv, dev);
2179         if (ret) {
2180                 ERROR("%p: RMV handler install failed",
2181                      (void *)dev);
2182                 goto err;
2183         }
2184         ret = priv_rx_intr_vec_enable(priv);
2185         if (ret) {
2186                 ERROR("%p: Rx interrupt vector creation failed",
2187                       (void *)dev);
2188                 goto err;
2189         }
2190         ret = mlx4_priv_flow_start(priv);
2191         if (ret) {
2192                 ERROR("%p: flow start failed: %s",
2193                       (void *)dev, strerror(ret));
2194                 goto err;
2195         }
2196         priv_unlock(priv);
2197         return 0;
2198 err:
2199         /* Rollback. */
2200         priv_mac_addr_del(priv);
2201         priv->started = 0;
2202         priv_unlock(priv);
2203         return -ret;
2204 }
2205
2206 /**
2207  * DPDK callback to stop the device.
2208  *
2209  * Simulate device stop by detaching all configured flows.
2210  *
2211  * @param dev
2212  *   Pointer to Ethernet device structure.
2213  */
2214 static void
2215 mlx4_dev_stop(struct rte_eth_dev *dev)
2216 {
2217         struct priv *priv = dev->data->dev_private;
2218
2219         priv_lock(priv);
2220         if (!priv->started) {
2221                 priv_unlock(priv);
2222                 return;
2223         }
2224         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
2225         priv->started = 0;
2226         mlx4_priv_flow_stop(priv);
2227         priv_mac_addr_del(priv);
2228         priv_unlock(priv);
2229 }
2230
2231 /**
2232  * Dummy DPDK callback for TX.
2233  *
2234  * This function is used to temporarily replace the real callback during
2235  * unsafe control operations on the queue, or in case of error.
2236  *
2237  * @param dpdk_txq
2238  *   Generic pointer to TX queue structure.
2239  * @param[in] pkts
2240  *   Packets to transmit.
2241  * @param pkts_n
2242  *   Number of packets in array.
2243  *
2244  * @return
2245  *   Number of packets successfully transmitted (<= pkts_n).
2246  */
2247 static uint16_t
2248 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
2249 {
2250         (void)dpdk_txq;
2251         (void)pkts;
2252         (void)pkts_n;
2253         return 0;
2254 }
2255
2256 /**
2257  * Dummy DPDK callback for RX.
2258  *
2259  * This function is used to temporarily replace the real callback during
2260  * unsafe control operations on the queue, or in case of error.
2261  *
2262  * @param dpdk_rxq
2263  *   Generic pointer to RX queue structure.
2264  * @param[out] pkts
2265  *   Array to store received packets.
2266  * @param pkts_n
2267  *   Maximum number of packets in array.
2268  *
2269  * @return
2270  *   Number of packets successfully received (<= pkts_n).
2271  */
2272 static uint16_t
2273 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2274 {
2275         (void)dpdk_rxq;
2276         (void)pkts;
2277         (void)pkts_n;
2278         return 0;
2279 }
2280
2281 static int
2282 priv_dev_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
2283
2284 static int
2285 priv_dev_removal_interrupt_handler_uninstall(struct priv *,
2286                                              struct rte_eth_dev *);
2287
2288 static int
2289 priv_dev_link_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
2290
2291 /**
2292  * DPDK callback to close the device.
2293  *
2294  * Destroy all queues and objects, free memory.
2295  *
2296  * @param dev
2297  *   Pointer to Ethernet device structure.
2298  */
2299 static void
2300 mlx4_dev_close(struct rte_eth_dev *dev)
2301 {
2302         struct priv *priv = dev->data->dev_private;
2303         void *tmp;
2304         unsigned int i;
2305
2306         if (priv == NULL)
2307                 return;
2308         priv_lock(priv);
2309         DEBUG("%p: closing device \"%s\"",
2310               (void *)dev,
2311               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
2312         priv_mac_addr_del(priv);
2313         /* Prevent crashes when queues are still in use. This is unfortunately
2314          * still required for DPDK 1.3 because some programs (such as testpmd)
2315          * never release them before closing the device. */
2316         dev->rx_pkt_burst = removed_rx_burst;
2317         dev->tx_pkt_burst = removed_tx_burst;
2318         if (priv->rxqs != NULL) {
2319                 /* XXX race condition if mlx4_rx_burst() is still running. */
2320                 usleep(1000);
2321                 for (i = 0; (i != priv->rxqs_n); ++i) {
2322                         tmp = (*priv->rxqs)[i];
2323                         if (tmp == NULL)
2324                                 continue;
2325                         (*priv->rxqs)[i] = NULL;
2326                         rxq_cleanup(tmp);
2327                         rte_free(tmp);
2328                 }
2329                 priv->rxqs_n = 0;
2330                 priv->rxqs = NULL;
2331         }
2332         if (priv->txqs != NULL) {
2333                 /* XXX race condition if mlx4_tx_burst() is still running. */
2334                 usleep(1000);
2335                 for (i = 0; (i != priv->txqs_n); ++i) {
2336                         tmp = (*priv->txqs)[i];
2337                         if (tmp == NULL)
2338                                 continue;
2339                         (*priv->txqs)[i] = NULL;
2340                         txq_cleanup(tmp);
2341                         rte_free(tmp);
2342                 }
2343                 priv->txqs_n = 0;
2344                 priv->txqs = NULL;
2345         }
2346         if (priv->pd != NULL) {
2347                 assert(priv->ctx != NULL);
2348                 claim_zero(ibv_dealloc_pd(priv->pd));
2349                 claim_zero(ibv_close_device(priv->ctx));
2350         } else
2351                 assert(priv->ctx == NULL);
2352         priv_dev_removal_interrupt_handler_uninstall(priv, dev);
2353         priv_dev_link_interrupt_handler_uninstall(priv, dev);
2354         priv_rx_intr_vec_disable(priv);
2355         priv_unlock(priv);
2356         memset(priv, 0, sizeof(*priv));
2357 }
2358
2359 /**
2360  * Change the link state (UP / DOWN).
2361  *
2362  * @param priv
2363  *   Pointer to Ethernet device private data.
2364  * @param up
2365  *   Nonzero for link up, otherwise link down.
2366  *
2367  * @return
2368  *   0 on success, errno value on failure.
2369  */
2370 static int
2371 priv_set_link(struct priv *priv, int up)
2372 {
2373         struct rte_eth_dev *dev = priv->dev;
2374         int err;
2375
2376         if (up) {
2377                 err = priv_set_flags(priv, ~IFF_UP, IFF_UP);
2378                 if (err)
2379                         return err;
2380                 dev->rx_pkt_burst = mlx4_rx_burst;
2381         } else {
2382                 err = priv_set_flags(priv, ~IFF_UP, ~IFF_UP);
2383                 if (err)
2384                         return err;
2385                 dev->rx_pkt_burst = removed_rx_burst;
2386                 dev->tx_pkt_burst = removed_tx_burst;
2387         }
2388         return 0;
2389 }
2390
2391 /**
2392  * DPDK callback to bring the link DOWN.
2393  *
2394  * @param dev
2395  *   Pointer to Ethernet device structure.
2396  *
2397  * @return
2398  *   0 on success, errno value on failure.
2399  */
2400 static int
2401 mlx4_set_link_down(struct rte_eth_dev *dev)
2402 {
2403         struct priv *priv = dev->data->dev_private;
2404         int err;
2405
2406         priv_lock(priv);
2407         err = priv_set_link(priv, 0);
2408         priv_unlock(priv);
2409         return err;
2410 }
2411
2412 /**
2413  * DPDK callback to bring the link UP.
2414  *
2415  * @param dev
2416  *   Pointer to Ethernet device structure.
2417  *
2418  * @return
2419  *   0 on success, errno value on failure.
2420  */
2421 static int
2422 mlx4_set_link_up(struct rte_eth_dev *dev)
2423 {
2424         struct priv *priv = dev->data->dev_private;
2425         int err;
2426
2427         priv_lock(priv);
2428         err = priv_set_link(priv, 1);
2429         priv_unlock(priv);
2430         return err;
2431 }
2432 /**
2433  * DPDK callback to get information about the device.
2434  *
2435  * @param dev
2436  *   Pointer to Ethernet device structure.
2437  * @param[out] info
2438  *   Info structure output buffer.
2439  */
2440 static void
2441 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
2442 {
2443         struct priv *priv = dev->data->dev_private;
2444         unsigned int max;
2445         char ifname[IF_NAMESIZE];
2446
2447         info->pci_dev = RTE_ETH_DEV_TO_PCI(dev);
2448
2449         if (priv == NULL)
2450                 return;
2451         priv_lock(priv);
2452         /* FIXME: we should ask the device for these values. */
2453         info->min_rx_bufsize = 32;
2454         info->max_rx_pktlen = 65536;
2455         /*
2456          * Since we need one CQ per QP, the limit is the minimum number
2457          * between the two values.
2458          */
2459         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
2460                priv->device_attr.max_qp : priv->device_attr.max_cq);
2461         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
2462         if (max >= 65535)
2463                 max = 65535;
2464         info->max_rx_queues = max;
2465         info->max_tx_queues = max;
2466         /* Last array entry is reserved for broadcast. */
2467         info->max_mac_addrs = 1;
2468         info->rx_offload_capa = 0;
2469         info->tx_offload_capa = 0;
2470         if (priv_get_ifname(priv, &ifname) == 0)
2471                 info->if_index = if_nametoindex(ifname);
2472         info->speed_capa =
2473                         ETH_LINK_SPEED_1G |
2474                         ETH_LINK_SPEED_10G |
2475                         ETH_LINK_SPEED_20G |
2476                         ETH_LINK_SPEED_40G |
2477                         ETH_LINK_SPEED_56G;
2478         priv_unlock(priv);
2479 }
2480
2481 /**
2482  * DPDK callback to get device statistics.
2483  *
2484  * @param dev
2485  *   Pointer to Ethernet device structure.
2486  * @param[out] stats
2487  *   Stats structure output buffer.
2488  */
2489 static void
2490 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
2491 {
2492         struct priv *priv = dev->data->dev_private;
2493         struct rte_eth_stats tmp = {0};
2494         unsigned int i;
2495         unsigned int idx;
2496
2497         if (priv == NULL)
2498                 return;
2499         priv_lock(priv);
2500         /* Add software counters. */
2501         for (i = 0; (i != priv->rxqs_n); ++i) {
2502                 struct rxq *rxq = (*priv->rxqs)[i];
2503
2504                 if (rxq == NULL)
2505                         continue;
2506                 idx = rxq->stats.idx;
2507                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
2508                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
2509                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
2510                         tmp.q_errors[idx] += (rxq->stats.idropped +
2511                                               rxq->stats.rx_nombuf);
2512                 }
2513                 tmp.ipackets += rxq->stats.ipackets;
2514                 tmp.ibytes += rxq->stats.ibytes;
2515                 tmp.ierrors += rxq->stats.idropped;
2516                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
2517         }
2518         for (i = 0; (i != priv->txqs_n); ++i) {
2519                 struct txq *txq = (*priv->txqs)[i];
2520
2521                 if (txq == NULL)
2522                         continue;
2523                 idx = txq->stats.idx;
2524                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
2525                         tmp.q_opackets[idx] += txq->stats.opackets;
2526                         tmp.q_obytes[idx] += txq->stats.obytes;
2527                         tmp.q_errors[idx] += txq->stats.odropped;
2528                 }
2529                 tmp.opackets += txq->stats.opackets;
2530                 tmp.obytes += txq->stats.obytes;
2531                 tmp.oerrors += txq->stats.odropped;
2532         }
2533         *stats = tmp;
2534         priv_unlock(priv);
2535 }
2536
2537 /**
2538  * DPDK callback to clear device statistics.
2539  *
2540  * @param dev
2541  *   Pointer to Ethernet device structure.
2542  */
2543 static void
2544 mlx4_stats_reset(struct rte_eth_dev *dev)
2545 {
2546         struct priv *priv = dev->data->dev_private;
2547         unsigned int i;
2548         unsigned int idx;
2549
2550         if (priv == NULL)
2551                 return;
2552         priv_lock(priv);
2553         for (i = 0; (i != priv->rxqs_n); ++i) {
2554                 if ((*priv->rxqs)[i] == NULL)
2555                         continue;
2556                 idx = (*priv->rxqs)[i]->stats.idx;
2557                 (*priv->rxqs)[i]->stats =
2558                         (struct mlx4_rxq_stats){ .idx = idx };
2559         }
2560         for (i = 0; (i != priv->txqs_n); ++i) {
2561                 if ((*priv->txqs)[i] == NULL)
2562                         continue;
2563                 idx = (*priv->txqs)[i]->stats.idx;
2564                 (*priv->txqs)[i]->stats =
2565                         (struct mlx4_txq_stats){ .idx = idx };
2566         }
2567         priv_unlock(priv);
2568 }
2569
2570 /**
2571  * DPDK callback to retrieve physical link information.
2572  *
2573  * @param dev
2574  *   Pointer to Ethernet device structure.
2575  * @param wait_to_complete
2576  *   Wait for request completion (ignored).
2577  */
2578 static int
2579 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
2580 {
2581         const struct priv *priv = dev->data->dev_private;
2582         struct ethtool_cmd edata = {
2583                 .cmd = ETHTOOL_GSET
2584         };
2585         struct ifreq ifr;
2586         struct rte_eth_link dev_link;
2587         int link_speed = 0;
2588
2589         /* priv_lock() is not taken to allow concurrent calls. */
2590
2591         if (priv == NULL)
2592                 return -EINVAL;
2593         (void)wait_to_complete;
2594         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
2595                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(errno));
2596                 return -1;
2597         }
2598         memset(&dev_link, 0, sizeof(dev_link));
2599         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
2600                                 (ifr.ifr_flags & IFF_RUNNING));
2601         ifr.ifr_data = (void *)&edata;
2602         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2603                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
2604                      strerror(errno));
2605                 return -1;
2606         }
2607         link_speed = ethtool_cmd_speed(&edata);
2608         if (link_speed == -1)
2609                 dev_link.link_speed = 0;
2610         else
2611                 dev_link.link_speed = link_speed;
2612         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
2613                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
2614         dev_link.link_autoneg = !(dev->data->dev_conf.link_speeds &
2615                         ETH_LINK_SPEED_FIXED);
2616         if (memcmp(&dev_link, &dev->data->dev_link, sizeof(dev_link))) {
2617                 /* Link status changed. */
2618                 dev->data->dev_link = dev_link;
2619                 return 0;
2620         }
2621         /* Link status is still the same. */
2622         return -1;
2623 }
2624
2625 /**
2626  * DPDK callback to change the MTU.
2627  *
2628  * @param dev
2629  *   Pointer to Ethernet device structure.
2630  * @param in_mtu
2631  *   New MTU.
2632  *
2633  * @return
2634  *   0 on success, negative errno value on failure.
2635  */
2636 static int
2637 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
2638 {
2639         struct priv *priv = dev->data->dev_private;
2640         int ret = 0;
2641
2642         priv_lock(priv);
2643         /* Set kernel interface MTU first. */
2644         if (priv_set_mtu(priv, mtu)) {
2645                 ret = errno;
2646                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
2647                      strerror(ret));
2648                 goto out;
2649         } else
2650                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
2651         priv->mtu = mtu;
2652 out:
2653         priv_unlock(priv);
2654         assert(ret >= 0);
2655         return -ret;
2656 }
2657
2658 /**
2659  * DPDK callback to get flow control status.
2660  *
2661  * @param dev
2662  *   Pointer to Ethernet device structure.
2663  * @param[out] fc_conf
2664  *   Flow control output buffer.
2665  *
2666  * @return
2667  *   0 on success, negative errno value on failure.
2668  */
2669 static int
2670 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
2671 {
2672         struct priv *priv = dev->data->dev_private;
2673         struct ifreq ifr;
2674         struct ethtool_pauseparam ethpause = {
2675                 .cmd = ETHTOOL_GPAUSEPARAM
2676         };
2677         int ret;
2678
2679         ifr.ifr_data = (void *)&ethpause;
2680         priv_lock(priv);
2681         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2682                 ret = errno;
2683                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
2684                      " failed: %s",
2685                      strerror(ret));
2686                 goto out;
2687         }
2688
2689         fc_conf->autoneg = ethpause.autoneg;
2690         if (ethpause.rx_pause && ethpause.tx_pause)
2691                 fc_conf->mode = RTE_FC_FULL;
2692         else if (ethpause.rx_pause)
2693                 fc_conf->mode = RTE_FC_RX_PAUSE;
2694         else if (ethpause.tx_pause)
2695                 fc_conf->mode = RTE_FC_TX_PAUSE;
2696         else
2697                 fc_conf->mode = RTE_FC_NONE;
2698         ret = 0;
2699
2700 out:
2701         priv_unlock(priv);
2702         assert(ret >= 0);
2703         return -ret;
2704 }
2705
2706 /**
2707  * DPDK callback to modify flow control parameters.
2708  *
2709  * @param dev
2710  *   Pointer to Ethernet device structure.
2711  * @param[in] fc_conf
2712  *   Flow control parameters.
2713  *
2714  * @return
2715  *   0 on success, negative errno value on failure.
2716  */
2717 static int
2718 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
2719 {
2720         struct priv *priv = dev->data->dev_private;
2721         struct ifreq ifr;
2722         struct ethtool_pauseparam ethpause = {
2723                 .cmd = ETHTOOL_SPAUSEPARAM
2724         };
2725         int ret;
2726
2727         ifr.ifr_data = (void *)&ethpause;
2728         ethpause.autoneg = fc_conf->autoneg;
2729         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
2730             (fc_conf->mode & RTE_FC_RX_PAUSE))
2731                 ethpause.rx_pause = 1;
2732         else
2733                 ethpause.rx_pause = 0;
2734
2735         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
2736             (fc_conf->mode & RTE_FC_TX_PAUSE))
2737                 ethpause.tx_pause = 1;
2738         else
2739                 ethpause.tx_pause = 0;
2740
2741         priv_lock(priv);
2742         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2743                 ret = errno;
2744                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
2745                      " failed: %s",
2746                      strerror(ret));
2747                 goto out;
2748         }
2749         ret = 0;
2750
2751 out:
2752         priv_unlock(priv);
2753         assert(ret >= 0);
2754         return -ret;
2755 }
2756
2757 const struct rte_flow_ops mlx4_flow_ops = {
2758         .validate = mlx4_flow_validate,
2759         .create = mlx4_flow_create,
2760         .destroy = mlx4_flow_destroy,
2761         .flush = mlx4_flow_flush,
2762         .query = NULL,
2763         .isolate = mlx4_flow_isolate,
2764 };
2765
2766 /**
2767  * Manage filter operations.
2768  *
2769  * @param dev
2770  *   Pointer to Ethernet device structure.
2771  * @param filter_type
2772  *   Filter type.
2773  * @param filter_op
2774  *   Operation to perform.
2775  * @param arg
2776  *   Pointer to operation-specific structure.
2777  *
2778  * @return
2779  *   0 on success, negative errno value on failure.
2780  */
2781 static int
2782 mlx4_dev_filter_ctrl(struct rte_eth_dev *dev,
2783                      enum rte_filter_type filter_type,
2784                      enum rte_filter_op filter_op,
2785                      void *arg)
2786 {
2787         int ret = EINVAL;
2788
2789         switch (filter_type) {
2790         case RTE_ETH_FILTER_GENERIC:
2791                 if (filter_op != RTE_ETH_FILTER_GET)
2792                         return -EINVAL;
2793                 *(const void **)arg = &mlx4_flow_ops;
2794                 return 0;
2795         default:
2796                 ERROR("%p: filter type (%d) not supported",
2797                       (void *)dev, filter_type);
2798                 break;
2799         }
2800         return -ret;
2801 }
2802
2803 static const struct eth_dev_ops mlx4_dev_ops = {
2804         .dev_configure = mlx4_dev_configure,
2805         .dev_start = mlx4_dev_start,
2806         .dev_stop = mlx4_dev_stop,
2807         .dev_set_link_down = mlx4_set_link_down,
2808         .dev_set_link_up = mlx4_set_link_up,
2809         .dev_close = mlx4_dev_close,
2810         .link_update = mlx4_link_update,
2811         .stats_get = mlx4_stats_get,
2812         .stats_reset = mlx4_stats_reset,
2813         .dev_infos_get = mlx4_dev_infos_get,
2814         .rx_queue_setup = mlx4_rx_queue_setup,
2815         .tx_queue_setup = mlx4_tx_queue_setup,
2816         .rx_queue_release = mlx4_rx_queue_release,
2817         .tx_queue_release = mlx4_tx_queue_release,
2818         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
2819         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
2820         .mtu_set = mlx4_dev_set_mtu,
2821         .filter_ctrl = mlx4_dev_filter_ctrl,
2822         .rx_queue_intr_enable = mlx4_rx_intr_enable,
2823         .rx_queue_intr_disable = mlx4_rx_intr_disable,
2824 };
2825
2826 /**
2827  * Get PCI information from struct ibv_device.
2828  *
2829  * @param device
2830  *   Pointer to Ethernet device structure.
2831  * @param[out] pci_addr
2832  *   PCI bus address output buffer.
2833  *
2834  * @return
2835  *   0 on success, -1 on failure and errno is set.
2836  */
2837 static int
2838 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
2839                             struct rte_pci_addr *pci_addr)
2840 {
2841         FILE *file;
2842         char line[32];
2843         MKSTR(path, "%s/device/uevent", device->ibdev_path);
2844
2845         file = fopen(path, "rb");
2846         if (file == NULL)
2847                 return -1;
2848         while (fgets(line, sizeof(line), file) == line) {
2849                 size_t len = strlen(line);
2850                 int ret;
2851
2852                 /* Truncate long lines. */
2853                 if (len == (sizeof(line) - 1))
2854                         while (line[(len - 1)] != '\n') {
2855                                 ret = fgetc(file);
2856                                 if (ret == EOF)
2857                                         break;
2858                                 line[(len - 1)] = ret;
2859                         }
2860                 /* Extract information. */
2861                 if (sscanf(line,
2862                            "PCI_SLOT_NAME="
2863                            "%" SCNx32 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
2864                            &pci_addr->domain,
2865                            &pci_addr->bus,
2866                            &pci_addr->devid,
2867                            &pci_addr->function) == 4) {
2868                         ret = 0;
2869                         break;
2870                 }
2871         }
2872         fclose(file);
2873         return 0;
2874 }
2875
2876 /**
2877  * Get MAC address by querying netdevice.
2878  *
2879  * @param[in] priv
2880  *   struct priv for the requested device.
2881  * @param[out] mac
2882  *   MAC address output buffer.
2883  *
2884  * @return
2885  *   0 on success, -1 on failure and errno is set.
2886  */
2887 static int
2888 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
2889 {
2890         struct ifreq request;
2891
2892         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
2893                 return -1;
2894         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
2895         return 0;
2896 }
2897
2898 static void
2899 mlx4_dev_link_status_handler(void *);
2900 static void
2901 mlx4_dev_interrupt_handler(void *);
2902
2903 /**
2904  * Link/device status handler.
2905  *
2906  * @param priv
2907  *   Pointer to private structure.
2908  * @param dev
2909  *   Pointer to the rte_eth_dev structure.
2910  * @param events
2911  *   Pointer to event flags holder.
2912  *
2913  * @return
2914  *   Number of events
2915  */
2916 static int
2917 priv_dev_status_handler(struct priv *priv, struct rte_eth_dev *dev,
2918                         uint32_t *events)
2919 {
2920         struct ibv_async_event event;
2921         int port_change = 0;
2922         struct rte_eth_link *link = &dev->data->dev_link;
2923         int ret = 0;
2924
2925         *events = 0;
2926         /* Read all message and acknowledge them. */
2927         for (;;) {
2928                 if (ibv_get_async_event(priv->ctx, &event))
2929                         break;
2930                 if ((event.event_type == IBV_EVENT_PORT_ACTIVE ||
2931                      event.event_type == IBV_EVENT_PORT_ERR) &&
2932                     (priv->intr_conf.lsc == 1)) {
2933                         port_change = 1;
2934                         ret++;
2935                 } else if (event.event_type == IBV_EVENT_DEVICE_FATAL &&
2936                            priv->intr_conf.rmv == 1) {
2937                         *events |= (1 << RTE_ETH_EVENT_INTR_RMV);
2938                         ret++;
2939                 } else
2940                         DEBUG("event type %d on port %d not handled",
2941                               event.event_type, event.element.port_num);
2942                 ibv_ack_async_event(&event);
2943         }
2944         if (!port_change)
2945                 return ret;
2946         mlx4_link_update(dev, 0);
2947         if (((link->link_speed == 0) && link->link_status) ||
2948             ((link->link_speed != 0) && !link->link_status)) {
2949                 if (!priv->pending_alarm) {
2950                         /* Inconsistent status, check again later. */
2951                         priv->pending_alarm = 1;
2952                         rte_eal_alarm_set(MLX4_ALARM_TIMEOUT_US,
2953                                           mlx4_dev_link_status_handler,
2954                                           dev);
2955                 }
2956         } else {
2957                 *events |= (1 << RTE_ETH_EVENT_INTR_LSC);
2958         }
2959         return ret;
2960 }
2961
2962 /**
2963  * Handle delayed link status event.
2964  *
2965  * @param arg
2966  *   Registered argument.
2967  */
2968 static void
2969 mlx4_dev_link_status_handler(void *arg)
2970 {
2971         struct rte_eth_dev *dev = arg;
2972         struct priv *priv = dev->data->dev_private;
2973         uint32_t events;
2974         int ret;
2975
2976         priv_lock(priv);
2977         assert(priv->pending_alarm == 1);
2978         priv->pending_alarm = 0;
2979         ret = priv_dev_status_handler(priv, dev, &events);
2980         priv_unlock(priv);
2981         if (ret > 0 && events & (1 << RTE_ETH_EVENT_INTR_LSC))
2982                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC, NULL,
2983                                               NULL);
2984 }
2985
2986 /**
2987  * Handle interrupts from the NIC.
2988  *
2989  * @param[in] intr_handle
2990  *   Interrupt handler.
2991  * @param cb_arg
2992  *   Callback argument.
2993  */
2994 static void
2995 mlx4_dev_interrupt_handler(void *cb_arg)
2996 {
2997         struct rte_eth_dev *dev = cb_arg;
2998         struct priv *priv = dev->data->dev_private;
2999         int ret;
3000         uint32_t ev;
3001         int i;
3002
3003         priv_lock(priv);
3004         ret = priv_dev_status_handler(priv, dev, &ev);
3005         priv_unlock(priv);
3006         if (ret > 0) {
3007                 for (i = RTE_ETH_EVENT_UNKNOWN;
3008                      i < RTE_ETH_EVENT_MAX;
3009                      i++) {
3010                         if (ev & (1 << i)) {
3011                                 ev &= ~(1 << i);
3012                                 _rte_eth_dev_callback_process(dev, i, NULL,
3013                                                               NULL);
3014                                 ret--;
3015                         }
3016                 }
3017                 if (ret)
3018                         WARN("%d event%s not processed", ret,
3019                              (ret > 1 ? "s were" : " was"));
3020         }
3021 }
3022
3023 /**
3024  * Uninstall interrupt handler.
3025  *
3026  * @param priv
3027  *   Pointer to private structure.
3028  * @param dev
3029  *   Pointer to the rte_eth_dev structure.
3030  * @return
3031  *   0 on success, negative errno value on failure.
3032  */
3033 static int
3034 priv_dev_interrupt_handler_uninstall(struct priv *priv, struct rte_eth_dev *dev)
3035 {
3036         int ret;
3037
3038         if (priv->intr_conf.lsc ||
3039             priv->intr_conf.rmv)
3040                 return 0;
3041         ret = rte_intr_callback_unregister(&priv->intr_handle,
3042                                            mlx4_dev_interrupt_handler,
3043                                            dev);
3044         if (ret < 0) {
3045                 ERROR("rte_intr_callback_unregister failed with %d"
3046                       "%s%s%s", ret,
3047                       (errno ? " (errno: " : ""),
3048                       (errno ? strerror(errno) : ""),
3049                       (errno ? ")" : ""));
3050         }
3051         priv->intr_handle.fd = 0;
3052         priv->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
3053         return ret;
3054 }
3055
3056 /**
3057  * Install interrupt handler.
3058  *
3059  * @param priv
3060  *   Pointer to private structure.
3061  * @param dev
3062  *   Pointer to the rte_eth_dev structure.
3063  * @return
3064  *   0 on success, negative errno value on failure.
3065  */
3066 static int
3067 priv_dev_interrupt_handler_install(struct priv *priv,
3068                                    struct rte_eth_dev *dev)
3069 {
3070         int flags;
3071         int rc;
3072
3073         /* Check whether the interrupt handler has already been installed
3074          * for either type of interrupt
3075          */
3076         if (priv->intr_conf.lsc &&
3077             priv->intr_conf.rmv &&
3078             priv->intr_handle.fd)
3079                 return 0;
3080         assert(priv->ctx->async_fd > 0);
3081         flags = fcntl(priv->ctx->async_fd, F_GETFL);
3082         rc = fcntl(priv->ctx->async_fd, F_SETFL, flags | O_NONBLOCK);
3083         if (rc < 0) {
3084                 INFO("failed to change file descriptor async event queue");
3085                 dev->data->dev_conf.intr_conf.lsc = 0;
3086                 dev->data->dev_conf.intr_conf.rmv = 0;
3087                 return -errno;
3088         } else {
3089                 priv->intr_handle.fd = priv->ctx->async_fd;
3090                 priv->intr_handle.type = RTE_INTR_HANDLE_EXT;
3091                 rc = rte_intr_callback_register(&priv->intr_handle,
3092                                                  mlx4_dev_interrupt_handler,
3093                                                  dev);
3094                 if (rc) {
3095                         ERROR("rte_intr_callback_register failed "
3096                               " (errno: %s)", strerror(errno));
3097                         return rc;
3098                 }
3099         }
3100         return 0;
3101 }
3102
3103 /**
3104  * Uninstall interrupt handler.
3105  *
3106  * @param priv
3107  *   Pointer to private structure.
3108  * @param dev
3109  *   Pointer to the rte_eth_dev structure.
3110  * @return
3111  *   0 on success, negative value on error.
3112  */
3113 static int
3114 priv_dev_removal_interrupt_handler_uninstall(struct priv *priv,
3115                                             struct rte_eth_dev *dev)
3116 {
3117         if (dev->data->dev_conf.intr_conf.rmv) {
3118                 priv->intr_conf.rmv = 0;
3119                 return priv_dev_interrupt_handler_uninstall(priv, dev);
3120         }
3121         return 0;
3122 }
3123
3124 /**
3125  * Uninstall interrupt handler.
3126  *
3127  * @param priv
3128  *   Pointer to private structure.
3129  * @param dev
3130  *   Pointer to the rte_eth_dev structure.
3131  * @return
3132  *   0 on success, negative value on error,
3133  */
3134 static int
3135 priv_dev_link_interrupt_handler_uninstall(struct priv *priv,
3136                                           struct rte_eth_dev *dev)
3137 {
3138         int ret = 0;
3139
3140         if (dev->data->dev_conf.intr_conf.lsc) {
3141                 priv->intr_conf.lsc = 0;
3142                 ret = priv_dev_interrupt_handler_uninstall(priv, dev);
3143                 if (ret)
3144                         return ret;
3145         }
3146         if (priv->pending_alarm)
3147                 if (rte_eal_alarm_cancel(mlx4_dev_link_status_handler,
3148                                          dev)) {
3149                         ERROR("rte_eal_alarm_cancel failed "
3150                               " (errno: %s)", strerror(rte_errno));
3151                         return -rte_errno;
3152                 }
3153         priv->pending_alarm = 0;
3154         return 0;
3155 }
3156
3157 /**
3158  * Install link interrupt handler.
3159  *
3160  * @param priv
3161  *   Pointer to private structure.
3162  * @param dev
3163  *   Pointer to the rte_eth_dev structure.
3164  * @return
3165  *   0 on success, negative value on error.
3166  */
3167 static int
3168 priv_dev_link_interrupt_handler_install(struct priv *priv,
3169                                         struct rte_eth_dev *dev)
3170 {
3171         int ret;
3172
3173         if (dev->data->dev_conf.intr_conf.lsc) {
3174                 ret = priv_dev_interrupt_handler_install(priv, dev);
3175                 if (ret)
3176                         return ret;
3177                 priv->intr_conf.lsc = 1;
3178         }
3179         return 0;
3180 }
3181
3182 /**
3183  * Install removal interrupt handler.
3184  *
3185  * @param priv
3186  *   Pointer to private structure.
3187  * @param dev
3188  *   Pointer to the rte_eth_dev structure.
3189  * @return
3190  *   0 on success, negative value on error.
3191  */
3192 static int
3193 priv_dev_removal_interrupt_handler_install(struct priv *priv,
3194                                            struct rte_eth_dev *dev)
3195 {
3196         int ret;
3197
3198         if (dev->data->dev_conf.intr_conf.rmv) {
3199                 ret = priv_dev_interrupt_handler_install(priv, dev);
3200                 if (ret)
3201                         return ret;
3202                 priv->intr_conf.rmv = 1;
3203         }
3204         return 0;
3205 }
3206
3207 /**
3208  * Allocate queue vector and fill epoll fd list for Rx interrupts.
3209  *
3210  * @param priv
3211  *   Pointer to private structure.
3212  *
3213  * @return
3214  *   0 on success, negative on failure.
3215  */
3216 static int
3217 priv_rx_intr_vec_enable(struct priv *priv)
3218 {
3219         unsigned int i;
3220         unsigned int rxqs_n = priv->rxqs_n;
3221         unsigned int n = RTE_MIN(rxqs_n, (uint32_t)RTE_MAX_RXTX_INTR_VEC_ID);
3222         unsigned int count = 0;
3223         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
3224
3225         if (!priv->dev->data->dev_conf.intr_conf.rxq)
3226                 return 0;
3227         priv_rx_intr_vec_disable(priv);
3228         intr_handle->intr_vec = malloc(sizeof(intr_handle->intr_vec[rxqs_n]));
3229         if (intr_handle->intr_vec == NULL) {
3230                 ERROR("failed to allocate memory for interrupt vector,"
3231                       " Rx interrupts will not be supported");
3232                 return -ENOMEM;
3233         }
3234         intr_handle->type = RTE_INTR_HANDLE_EXT;
3235         for (i = 0; i != n; ++i) {
3236                 struct rxq *rxq = (*priv->rxqs)[i];
3237                 int fd;
3238                 int flags;
3239                 int rc;
3240
3241                 /* Skip queues that cannot request interrupts. */
3242                 if (!rxq || !rxq->channel) {
3243                         /* Use invalid intr_vec[] index to disable entry. */
3244                         intr_handle->intr_vec[i] =
3245                                 RTE_INTR_VEC_RXTX_OFFSET +
3246                                 RTE_MAX_RXTX_INTR_VEC_ID;
3247                         continue;
3248                 }
3249                 if (count >= RTE_MAX_RXTX_INTR_VEC_ID) {
3250                         ERROR("too many Rx queues for interrupt vector size"
3251                               " (%d), Rx interrupts cannot be enabled",
3252                               RTE_MAX_RXTX_INTR_VEC_ID);
3253                         priv_rx_intr_vec_disable(priv);
3254                         return -1;
3255                 }
3256                 fd = rxq->channel->fd;
3257                 flags = fcntl(fd, F_GETFL);
3258                 rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
3259                 if (rc < 0) {
3260                         ERROR("failed to make Rx interrupt file descriptor"
3261                               " %d non-blocking for queue index %d", fd, i);
3262                         priv_rx_intr_vec_disable(priv);
3263                         return rc;
3264                 }
3265                 intr_handle->intr_vec[i] = RTE_INTR_VEC_RXTX_OFFSET + count;
3266                 intr_handle->efds[count] = fd;
3267                 count++;
3268         }
3269         if (!count)
3270                 priv_rx_intr_vec_disable(priv);
3271         else
3272                 intr_handle->nb_efd = count;
3273         return 0;
3274 }
3275
3276 /**
3277  * Clean up Rx interrupts handler.
3278  *
3279  * @param priv
3280  *   Pointer to private structure.
3281  */
3282 static void
3283 priv_rx_intr_vec_disable(struct priv *priv)
3284 {
3285         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
3286
3287         rte_intr_free_epoll_fd(intr_handle);
3288         free(intr_handle->intr_vec);
3289         intr_handle->nb_efd = 0;
3290         intr_handle->intr_vec = NULL;
3291 }
3292
3293 /**
3294  * DPDK callback for Rx queue interrupt enable.
3295  *
3296  * @param dev
3297  *   Pointer to Ethernet device structure.
3298  * @param idx
3299  *   Rx queue index.
3300  *
3301  * @return
3302  *   0 on success, negative on failure.
3303  */
3304 static int
3305 mlx4_rx_intr_enable(struct rte_eth_dev *dev, uint16_t idx)
3306 {
3307         struct priv *priv = dev->data->dev_private;
3308         struct rxq *rxq = (*priv->rxqs)[idx];
3309         int ret;
3310
3311         if (!rxq || !rxq->channel)
3312                 ret = EINVAL;
3313         else
3314                 ret = ibv_req_notify_cq(rxq->cq, 0);
3315         if (ret)
3316                 WARN("unable to arm interrupt on rx queue %d", idx);
3317         return -ret;
3318 }
3319
3320 /**
3321  * DPDK callback for Rx queue interrupt disable.
3322  *
3323  * @param dev
3324  *   Pointer to Ethernet device structure.
3325  * @param idx
3326  *   Rx queue index.
3327  *
3328  * @return
3329  *   0 on success, negative on failure.
3330  */
3331 static int
3332 mlx4_rx_intr_disable(struct rte_eth_dev *dev, uint16_t idx)
3333 {
3334         struct priv *priv = dev->data->dev_private;
3335         struct rxq *rxq = (*priv->rxqs)[idx];
3336         struct ibv_cq *ev_cq;
3337         void *ev_ctx;
3338         int ret;
3339
3340         if (!rxq || !rxq->channel) {
3341                 ret = EINVAL;
3342         } else {
3343                 ret = ibv_get_cq_event(rxq->cq->channel, &ev_cq, &ev_ctx);
3344                 if (ret || ev_cq != rxq->cq)
3345                         ret = EINVAL;
3346         }
3347         if (ret)
3348                 WARN("unable to disable interrupt on rx queue %d",
3349                      idx);
3350         else
3351                 ibv_ack_cq_events(rxq->cq, 1);
3352         return -ret;
3353 }
3354
3355 /**
3356  * Verify and store value for device argument.
3357  *
3358  * @param[in] key
3359  *   Key argument to verify.
3360  * @param[in] val
3361  *   Value associated with key.
3362  * @param[in, out] conf
3363  *   Shared configuration data.
3364  *
3365  * @return
3366  *   0 on success, negative errno value on failure.
3367  */
3368 static int
3369 mlx4_arg_parse(const char *key, const char *val, struct mlx4_conf *conf)
3370 {
3371         unsigned long tmp;
3372
3373         errno = 0;
3374         tmp = strtoul(val, NULL, 0);
3375         if (errno) {
3376                 WARN("%s: \"%s\" is not a valid integer", key, val);
3377                 return -errno;
3378         }
3379         if (strcmp(MLX4_PMD_PORT_KVARG, key) == 0) {
3380                 uint32_t ports = rte_log2_u32(conf->ports.present);
3381
3382                 if (tmp >= ports) {
3383                         ERROR("port index %lu outside range [0,%" PRIu32 ")",
3384                               tmp, ports);
3385                         return -EINVAL;
3386                 }
3387                 if (!(conf->ports.present & (1 << tmp))) {
3388                         ERROR("invalid port index %lu", tmp);
3389                         return -EINVAL;
3390                 }
3391                 conf->ports.enabled |= 1 << tmp;
3392         } else {
3393                 WARN("%s: unknown parameter", key);
3394                 return -EINVAL;
3395         }
3396         return 0;
3397 }
3398
3399 /**
3400  * Parse device parameters.
3401  *
3402  * @param devargs
3403  *   Device arguments structure.
3404  *
3405  * @return
3406  *   0 on success, negative errno value on failure.
3407  */
3408 static int
3409 mlx4_args(struct rte_devargs *devargs, struct mlx4_conf *conf)
3410 {
3411         struct rte_kvargs *kvlist;
3412         unsigned int arg_count;
3413         int ret = 0;
3414         int i;
3415
3416         if (devargs == NULL)
3417                 return 0;
3418         kvlist = rte_kvargs_parse(devargs->args, pmd_mlx4_init_params);
3419         if (kvlist == NULL) {
3420                 ERROR("failed to parse kvargs");
3421                 return -EINVAL;
3422         }
3423         /* Process parameters. */
3424         for (i = 0; pmd_mlx4_init_params[i]; ++i) {
3425                 arg_count = rte_kvargs_count(kvlist, MLX4_PMD_PORT_KVARG);
3426                 while (arg_count-- > 0) {
3427                         ret = rte_kvargs_process(kvlist,
3428                                                  MLX4_PMD_PORT_KVARG,
3429                                                  (int (*)(const char *,
3430                                                           const char *,
3431                                                           void *))
3432                                                  mlx4_arg_parse,
3433                                                  conf);
3434                         if (ret != 0)
3435                                 goto free_kvlist;
3436                 }
3437         }
3438 free_kvlist:
3439         rte_kvargs_free(kvlist);
3440         return ret;
3441 }
3442
3443 static struct rte_pci_driver mlx4_driver;
3444
3445 /**
3446  * DPDK callback to register a PCI device.
3447  *
3448  * This function creates an Ethernet device for each port of a given
3449  * PCI device.
3450  *
3451  * @param[in] pci_drv
3452  *   PCI driver structure (mlx4_driver).
3453  * @param[in] pci_dev
3454  *   PCI device information.
3455  *
3456  * @return
3457  *   0 on success, negative errno value on failure.
3458  */
3459 static int
3460 mlx4_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
3461 {
3462         struct ibv_device **list;
3463         struct ibv_device *ibv_dev;
3464         int err = 0;
3465         struct ibv_context *attr_ctx = NULL;
3466         struct ibv_device_attr device_attr;
3467         struct mlx4_conf conf = {
3468                 .ports.present = 0,
3469         };
3470         unsigned int vf;
3471         int i;
3472
3473         (void)pci_drv;
3474         assert(pci_drv == &mlx4_driver);
3475
3476         list = ibv_get_device_list(&i);
3477         if (list == NULL) {
3478                 assert(errno);
3479                 if (errno == ENOSYS)
3480                         ERROR("cannot list devices, is ib_uverbs loaded?");
3481                 return -errno;
3482         }
3483         assert(i >= 0);
3484         /*
3485          * For each listed device, check related sysfs entry against
3486          * the provided PCI ID.
3487          */
3488         while (i != 0) {
3489                 struct rte_pci_addr pci_addr;
3490
3491                 --i;
3492                 DEBUG("checking device \"%s\"", list[i]->name);
3493                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
3494                         continue;
3495                 if ((pci_dev->addr.domain != pci_addr.domain) ||
3496                     (pci_dev->addr.bus != pci_addr.bus) ||
3497                     (pci_dev->addr.devid != pci_addr.devid) ||
3498                     (pci_dev->addr.function != pci_addr.function))
3499                         continue;
3500                 vf = (pci_dev->id.device_id ==
3501                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
3502                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
3503                      list[i]->name, (vf ? "true" : "false"));
3504                 attr_ctx = ibv_open_device(list[i]);
3505                 err = errno;
3506                 break;
3507         }
3508         if (attr_ctx == NULL) {
3509                 ibv_free_device_list(list);
3510                 switch (err) {
3511                 case 0:
3512                         ERROR("cannot access device, is mlx4_ib loaded?");
3513                         return -ENODEV;
3514                 case EINVAL:
3515                         ERROR("cannot use device, are drivers up to date?");
3516                         return -EINVAL;
3517                 }
3518                 assert(err > 0);
3519                 return -err;
3520         }
3521         ibv_dev = list[i];
3522
3523         DEBUG("device opened");
3524         if (ibv_query_device(attr_ctx, &device_attr)) {
3525                 err = ENODEV;
3526                 goto error;
3527         }
3528         INFO("%u port(s) detected", device_attr.phys_port_cnt);
3529
3530         conf.ports.present |= (UINT64_C(1) << device_attr.phys_port_cnt) - 1;
3531         if (mlx4_args(pci_dev->device.devargs, &conf)) {
3532                 ERROR("failed to process device arguments");
3533                 err = EINVAL;
3534                 goto error;
3535         }
3536         /* Use all ports when none are defined */
3537         if (!conf.ports.enabled)
3538                 conf.ports.enabled = conf.ports.present;
3539         for (i = 0; i < device_attr.phys_port_cnt; i++) {
3540                 uint32_t port = i + 1; /* ports are indexed from one */
3541                 struct ibv_context *ctx = NULL;
3542                 struct ibv_port_attr port_attr;
3543                 struct ibv_pd *pd = NULL;
3544                 struct priv *priv = NULL;
3545                 struct rte_eth_dev *eth_dev = NULL;
3546                 struct ether_addr mac;
3547
3548                 /* If port is not enabled, skip. */
3549                 if (!(conf.ports.enabled & (1 << i)))
3550                         continue;
3551
3552                 DEBUG("using port %u", port);
3553
3554                 ctx = ibv_open_device(ibv_dev);
3555                 if (ctx == NULL) {
3556                         err = ENODEV;
3557                         goto port_error;
3558                 }
3559
3560                 /* Check port status. */
3561                 err = ibv_query_port(ctx, port, &port_attr);
3562                 if (err) {
3563                         ERROR("port query failed: %s", strerror(err));
3564                         err = ENODEV;
3565                         goto port_error;
3566                 }
3567
3568                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
3569                         ERROR("port %d is not configured in Ethernet mode",
3570                               port);
3571                         err = EINVAL;
3572                         goto port_error;
3573                 }
3574
3575                 if (port_attr.state != IBV_PORT_ACTIVE)
3576                         DEBUG("port %d is not active: \"%s\" (%d)",
3577                               port, ibv_port_state_str(port_attr.state),
3578                               port_attr.state);
3579
3580                 /* Allocate protection domain. */
3581                 pd = ibv_alloc_pd(ctx);
3582                 if (pd == NULL) {
3583                         ERROR("PD allocation failure");
3584                         err = ENOMEM;
3585                         goto port_error;
3586                 }
3587
3588                 /* from rte_ethdev.c */
3589                 priv = rte_zmalloc("ethdev private structure",
3590                                    sizeof(*priv),
3591                                    RTE_CACHE_LINE_SIZE);
3592                 if (priv == NULL) {
3593                         ERROR("priv allocation failure");
3594                         err = ENOMEM;
3595                         goto port_error;
3596                 }
3597
3598                 priv->ctx = ctx;
3599                 priv->device_attr = device_attr;
3600                 priv->port = port;
3601                 priv->pd = pd;
3602                 priv->mtu = ETHER_MTU;
3603
3604                 priv->vf = vf;
3605                 /* Configure the first MAC address by default. */
3606                 if (priv_get_mac(priv, &mac.addr_bytes)) {
3607                         ERROR("cannot get MAC address, is mlx4_en loaded?"
3608                               " (errno: %s)", strerror(errno));
3609                         err = ENODEV;
3610                         goto port_error;
3611                 }
3612                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
3613                      priv->port,
3614                      mac.addr_bytes[0], mac.addr_bytes[1],
3615                      mac.addr_bytes[2], mac.addr_bytes[3],
3616                      mac.addr_bytes[4], mac.addr_bytes[5]);
3617                 /* Register MAC address. */
3618                 priv->mac = mac;
3619                 if (priv_mac_addr_add(priv))
3620                         goto port_error;
3621 #ifndef NDEBUG
3622                 {
3623                         char ifname[IF_NAMESIZE];
3624
3625                         if (priv_get_ifname(priv, &ifname) == 0)
3626                                 DEBUG("port %u ifname is \"%s\"",
3627                                       priv->port, ifname);
3628                         else
3629                                 DEBUG("port %u ifname is unknown", priv->port);
3630                 }
3631 #endif
3632                 /* Get actual MTU if possible. */
3633                 priv_get_mtu(priv, &priv->mtu);
3634                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
3635
3636                 /* from rte_ethdev.c */
3637                 {
3638                         char name[RTE_ETH_NAME_MAX_LEN];
3639
3640                         snprintf(name, sizeof(name), "%s port %u",
3641                                  ibv_get_device_name(ibv_dev), port);
3642                         eth_dev = rte_eth_dev_allocate(name);
3643                 }
3644                 if (eth_dev == NULL) {
3645                         ERROR("can not allocate rte ethdev");
3646                         err = ENOMEM;
3647                         goto port_error;
3648                 }
3649
3650                 eth_dev->data->dev_private = priv;
3651                 eth_dev->data->mac_addrs = &priv->mac;
3652                 eth_dev->device = &pci_dev->device;
3653
3654                 rte_eth_copy_pci_info(eth_dev, pci_dev);
3655
3656                 eth_dev->device->driver = &mlx4_driver.driver;
3657
3658                 /*
3659                  * Copy and override interrupt handle to prevent it from
3660                  * being shared between all ethdev instances of a given PCI
3661                  * device. This is required to properly handle Rx interrupts
3662                  * on all ports.
3663                  */
3664                 priv->intr_handle_dev = *eth_dev->intr_handle;
3665                 eth_dev->intr_handle = &priv->intr_handle_dev;
3666
3667                 priv->dev = eth_dev;
3668                 eth_dev->dev_ops = &mlx4_dev_ops;
3669                 eth_dev->data->dev_flags |= RTE_ETH_DEV_DETACHABLE;
3670
3671                 /* Bring Ethernet device up. */
3672                 DEBUG("forcing Ethernet interface up");
3673                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
3674                 /* Update link status once if waiting for LSC. */
3675                 if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
3676                         mlx4_link_update(eth_dev, 0);
3677                 continue;
3678
3679 port_error:
3680                 rte_free(priv);
3681                 if (pd)
3682                         claim_zero(ibv_dealloc_pd(pd));
3683                 if (ctx)
3684                         claim_zero(ibv_close_device(ctx));
3685                 if (eth_dev)
3686                         rte_eth_dev_release_port(eth_dev);
3687                 break;
3688         }
3689         if (i == device_attr.phys_port_cnt)
3690                 return 0;
3691
3692         /*
3693          * XXX if something went wrong in the loop above, there is a resource
3694          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
3695          * long as the dpdk does not provide a way to deallocate a ethdev and a
3696          * way to enumerate the registered ethdevs to free the previous ones.
3697          */
3698
3699 error:
3700         if (attr_ctx)
3701                 claim_zero(ibv_close_device(attr_ctx));
3702         if (list)
3703                 ibv_free_device_list(list);
3704         assert(err >= 0);
3705         return -err;
3706 }
3707
3708 static const struct rte_pci_id mlx4_pci_id_map[] = {
3709         {
3710                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3711                                PCI_DEVICE_ID_MELLANOX_CONNECTX3)
3712         },
3713         {
3714                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3715                                PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO)
3716         },
3717         {
3718                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3719                                PCI_DEVICE_ID_MELLANOX_CONNECTX3VF)
3720         },
3721         {
3722                 .vendor_id = 0
3723         }
3724 };
3725
3726 static struct rte_pci_driver mlx4_driver = {
3727         .driver = {
3728                 .name = MLX4_DRIVER_NAME
3729         },
3730         .id_table = mlx4_pci_id_map,
3731         .probe = mlx4_pci_probe,
3732         .drv_flags = RTE_PCI_DRV_INTR_LSC |
3733                      RTE_PCI_DRV_INTR_RMV,
3734 };
3735
3736 /**
3737  * Driver initialization routine.
3738  */
3739 RTE_INIT(rte_mlx4_pmd_init);
3740 static void
3741 rte_mlx4_pmd_init(void)
3742 {
3743         RTE_BUILD_BUG_ON(sizeof(wr_id_t) != sizeof(uint64_t));
3744         /*
3745          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
3746          * huge pages. Calling ibv_fork_init() during init allows
3747          * applications to use fork() safely for purposes other than
3748          * using this PMD, which is not supported in forked processes.
3749          */
3750         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
3751         ibv_fork_init();
3752         rte_pci_register(&mlx4_driver);
3753 }
3754
3755 RTE_PMD_EXPORT_NAME(net_mlx4, __COUNTER__);
3756 RTE_PMD_REGISTER_PCI_TABLE(net_mlx4, mlx4_pci_id_map);
3757 RTE_PMD_REGISTER_KMOD_DEP(net_mlx4,
3758         "* ib_uverbs & mlx4_en & mlx4_core & mlx4_ib");