net/mlx4: revert resource domain support
[dpdk.git] / drivers / net / mlx4 / mlx4.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright 2012 6WIND S.A.
5  *   Copyright 2012 Mellanox
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of 6WIND S.A. nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 /* System headers. */
35 #include <stddef.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <stdint.h>
39 #include <inttypes.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <unistd.h>
43 #include <assert.h>
44 #include <net/if.h>
45 #include <dirent.h>
46 #include <sys/ioctl.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <linux/ethtool.h>
50 #include <linux/sockios.h>
51 #include <fcntl.h>
52
53 #include <rte_ether.h>
54 #include <rte_ethdev.h>
55 #include <rte_ethdev_pci.h>
56 #include <rte_dev.h>
57 #include <rte_mbuf.h>
58 #include <rte_errno.h>
59 #include <rte_mempool.h>
60 #include <rte_prefetch.h>
61 #include <rte_malloc.h>
62 #include <rte_spinlock.h>
63 #include <rte_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 #ifdef HAVE_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK
1270                 /* MC loopback must be disabled when not using a VF. */
1271                 .family_flags =
1272                         (!priv->vf ?
1273                          IBV_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK :
1274                          0),
1275 #endif
1276         };
1277         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1278         if (tmpl.if_qp == NULL) {
1279                 ERROR("%p: QP interface family query failed with status %d",
1280                       (void *)dev, status);
1281                 goto error;
1282         }
1283         /* Clean up txq in case we're reinitializing it. */
1284         DEBUG("%p: cleaning-up old txq just in case", (void *)txq);
1285         txq_cleanup(txq);
1286         *txq = tmpl;
1287         DEBUG("%p: txq updated with %p", (void *)txq, (void *)&tmpl);
1288         /* Pre-register known mempools. */
1289         rte_mempool_walk(txq_mp2mr_iter, txq);
1290         assert(ret == 0);
1291         return 0;
1292 error:
1293         txq_cleanup(&tmpl);
1294         assert(ret > 0);
1295         return ret;
1296 }
1297
1298 /**
1299  * DPDK callback to configure a TX queue.
1300  *
1301  * @param dev
1302  *   Pointer to Ethernet device structure.
1303  * @param idx
1304  *   TX queue index.
1305  * @param desc
1306  *   Number of descriptors to configure in queue.
1307  * @param socket
1308  *   NUMA socket on which memory must be allocated.
1309  * @param[in] conf
1310  *   Thresholds parameters.
1311  *
1312  * @return
1313  *   0 on success, negative errno value on failure.
1314  */
1315 static int
1316 mlx4_tx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1317                     unsigned int socket, const struct rte_eth_txconf *conf)
1318 {
1319         struct priv *priv = dev->data->dev_private;
1320         struct txq *txq = (*priv->txqs)[idx];
1321         int ret;
1322
1323         priv_lock(priv);
1324         DEBUG("%p: configuring queue %u for %u descriptors",
1325               (void *)dev, idx, desc);
1326         if (idx >= priv->txqs_n) {
1327                 ERROR("%p: queue index out of range (%u >= %u)",
1328                       (void *)dev, idx, priv->txqs_n);
1329                 priv_unlock(priv);
1330                 return -EOVERFLOW;
1331         }
1332         if (txq != NULL) {
1333                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1334                       (void *)dev, idx, (void *)txq);
1335                 if (priv->started) {
1336                         priv_unlock(priv);
1337                         return -EEXIST;
1338                 }
1339                 (*priv->txqs)[idx] = NULL;
1340                 txq_cleanup(txq);
1341         } else {
1342                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0, socket);
1343                 if (txq == NULL) {
1344                         ERROR("%p: unable to allocate queue index %u",
1345                               (void *)dev, idx);
1346                         priv_unlock(priv);
1347                         return -ENOMEM;
1348                 }
1349         }
1350         ret = txq_setup(dev, txq, desc, socket, conf);
1351         if (ret)
1352                 rte_free(txq);
1353         else {
1354                 txq->stats.idx = idx;
1355                 DEBUG("%p: adding TX queue %p to list",
1356                       (void *)dev, (void *)txq);
1357                 (*priv->txqs)[idx] = txq;
1358                 /* Update send callback. */
1359                 dev->tx_pkt_burst = mlx4_tx_burst;
1360         }
1361         priv_unlock(priv);
1362         return -ret;
1363 }
1364
1365 /**
1366  * DPDK callback to release a TX queue.
1367  *
1368  * @param dpdk_txq
1369  *   Generic TX queue pointer.
1370  */
1371 static void
1372 mlx4_tx_queue_release(void *dpdk_txq)
1373 {
1374         struct txq *txq = (struct txq *)dpdk_txq;
1375         struct priv *priv;
1376         unsigned int i;
1377
1378         if (txq == NULL)
1379                 return;
1380         priv = txq->priv;
1381         priv_lock(priv);
1382         for (i = 0; (i != priv->txqs_n); ++i)
1383                 if ((*priv->txqs)[i] == txq) {
1384                         DEBUG("%p: removing TX queue %p from list",
1385                               (void *)priv->dev, (void *)txq);
1386                         (*priv->txqs)[i] = NULL;
1387                         break;
1388                 }
1389         txq_cleanup(txq);
1390         rte_free(txq);
1391         priv_unlock(priv);
1392 }
1393
1394 /* RX queues handling. */
1395
1396 /**
1397  * Allocate RX queue elements.
1398  *
1399  * @param rxq
1400  *   Pointer to RX queue structure.
1401  * @param elts_n
1402  *   Number of elements to allocate.
1403  *
1404  * @return
1405  *   0 on success, errno value on failure.
1406  */
1407 static int
1408 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n)
1409 {
1410         unsigned int i;
1411         struct rxq_elt (*elts)[elts_n] =
1412                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1413                                   rxq->socket);
1414         int ret = 0;
1415
1416         if (elts == NULL) {
1417                 ERROR("%p: can't allocate packets array", (void *)rxq);
1418                 ret = ENOMEM;
1419                 goto error;
1420         }
1421         /* For each WR (packet). */
1422         for (i = 0; (i != elts_n); ++i) {
1423                 struct rxq_elt *elt = &(*elts)[i];
1424                 struct ibv_recv_wr *wr = &elt->wr;
1425                 struct ibv_sge *sge = &(*elts)[i].sge;
1426                 struct rte_mbuf *buf = rte_pktmbuf_alloc(rxq->mp);
1427
1428                 if (buf == NULL) {
1429                         ERROR("%p: empty mbuf pool", (void *)rxq);
1430                         ret = ENOMEM;
1431                         goto error;
1432                 }
1433                 /* Configure WR. Work request ID contains its own index in
1434                  * the elts array and the offset between SGE buffer header and
1435                  * its data. */
1436                 WR_ID(wr->wr_id).id = i;
1437                 WR_ID(wr->wr_id).offset =
1438                         (((uintptr_t)buf->buf_addr + RTE_PKTMBUF_HEADROOM) -
1439                          (uintptr_t)buf);
1440                 wr->next = &(*elts)[(i + 1)].wr;
1441                 wr->sg_list = sge;
1442                 wr->num_sge = 1;
1443                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
1444                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1445                 /* Buffer is supposed to be empty. */
1446                 assert(rte_pktmbuf_data_len(buf) == 0);
1447                 assert(rte_pktmbuf_pkt_len(buf) == 0);
1448                 /* sge->addr must be able to store a pointer. */
1449                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1450                 /* SGE keeps its headroom. */
1451                 sge->addr = (uintptr_t)
1452                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
1453                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
1454                 sge->lkey = rxq->mr->lkey;
1455                 /* Redundant check for tailroom. */
1456                 assert(sge->length == rte_pktmbuf_tailroom(buf));
1457                 /* Make sure elts index and SGE mbuf pointer can be deduced
1458                  * from WR ID. */
1459                 if ((WR_ID(wr->wr_id).id != i) ||
1460                     ((void *)((uintptr_t)sge->addr -
1461                         WR_ID(wr->wr_id).offset) != buf)) {
1462                         ERROR("%p: cannot store index and offset in WR ID",
1463                               (void *)rxq);
1464                         sge->addr = 0;
1465                         rte_pktmbuf_free(buf);
1466                         ret = EOVERFLOW;
1467                         goto error;
1468                 }
1469         }
1470         /* The last WR pointer must be NULL. */
1471         (*elts)[(i - 1)].wr.next = NULL;
1472         DEBUG("%p: allocated and configured %u single-segment WRs",
1473               (void *)rxq, elts_n);
1474         rxq->elts_n = elts_n;
1475         rxq->elts_head = 0;
1476         rxq->elts = elts;
1477         assert(ret == 0);
1478         return 0;
1479 error:
1480         if (elts != NULL) {
1481                 for (i = 0; (i != elemof(*elts)); ++i) {
1482                         struct rxq_elt *elt = &(*elts)[i];
1483                         struct rte_mbuf *buf;
1484
1485                         if (elt->sge.addr == 0)
1486                                 continue;
1487                         assert(WR_ID(elt->wr.wr_id).id == i);
1488                         buf = (void *)((uintptr_t)elt->sge.addr -
1489                                 WR_ID(elt->wr.wr_id).offset);
1490                         rte_pktmbuf_free_seg(buf);
1491                 }
1492                 rte_free(elts);
1493         }
1494         DEBUG("%p: failed, freed everything", (void *)rxq);
1495         assert(ret > 0);
1496         return ret;
1497 }
1498
1499 /**
1500  * Free RX queue elements.
1501  *
1502  * @param rxq
1503  *   Pointer to RX queue structure.
1504  */
1505 static void
1506 rxq_free_elts(struct rxq *rxq)
1507 {
1508         unsigned int i;
1509         unsigned int elts_n = rxq->elts_n;
1510         struct rxq_elt (*elts)[elts_n] = rxq->elts;
1511
1512         DEBUG("%p: freeing WRs", (void *)rxq);
1513         rxq->elts_n = 0;
1514         rxq->elts = NULL;
1515         if (elts == NULL)
1516                 return;
1517         for (i = 0; (i != elemof(*elts)); ++i) {
1518                 struct rxq_elt *elt = &(*elts)[i];
1519                 struct rte_mbuf *buf;
1520
1521                 if (elt->sge.addr == 0)
1522                         continue;
1523                 assert(WR_ID(elt->wr.wr_id).id == i);
1524                 buf = (void *)((uintptr_t)elt->sge.addr -
1525                         WR_ID(elt->wr.wr_id).offset);
1526                 rte_pktmbuf_free_seg(buf);
1527         }
1528         rte_free(elts);
1529 }
1530
1531 /**
1532  * Unregister a MAC address.
1533  *
1534  * @param priv
1535  *   Pointer to private structure.
1536  */
1537 static void
1538 priv_mac_addr_del(struct priv *priv)
1539 {
1540 #ifndef NDEBUG
1541         uint8_t (*mac)[ETHER_ADDR_LEN] = &priv->mac.addr_bytes;
1542 #endif
1543
1544         if (!priv->mac_flow)
1545                 return;
1546         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x",
1547               (void *)priv,
1548               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);
1549         claim_zero(ibv_destroy_flow(priv->mac_flow));
1550         priv->mac_flow = NULL;
1551 }
1552
1553 /**
1554  * Register a MAC address.
1555  *
1556  * The MAC address is registered in queue 0.
1557  *
1558  * @param priv
1559  *   Pointer to private structure.
1560  *
1561  * @return
1562  *   0 on success, errno value on failure.
1563  */
1564 static int
1565 priv_mac_addr_add(struct priv *priv)
1566 {
1567         uint8_t (*mac)[ETHER_ADDR_LEN] = &priv->mac.addr_bytes;
1568         struct rxq *rxq;
1569         struct ibv_flow *flow;
1570
1571         /* If device isn't started, this is all we need to do. */
1572         if (!priv->started)
1573                 return 0;
1574         if (priv->isolated)
1575                 return 0;
1576         if (*priv->rxqs && (*priv->rxqs)[0])
1577                 rxq = (*priv->rxqs)[0];
1578         else
1579                 return 0;
1580
1581         /* Allocate flow specification on the stack. */
1582         struct __attribute__((packed)) {
1583                 struct ibv_flow_attr attr;
1584                 struct ibv_flow_spec_eth spec;
1585         } data;
1586         struct ibv_flow_attr *attr = &data.attr;
1587         struct ibv_flow_spec_eth *spec = &data.spec;
1588
1589         if (priv->mac_flow)
1590                 priv_mac_addr_del(priv);
1591         /*
1592          * No padding must be inserted by the compiler between attr and spec.
1593          * This layout is expected by libibverbs.
1594          */
1595         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
1596         *attr = (struct ibv_flow_attr){
1597                 .type = IBV_FLOW_ATTR_NORMAL,
1598                 .priority = 3,
1599                 .num_of_specs = 1,
1600                 .port = priv->port,
1601                 .flags = 0
1602         };
1603         *spec = (struct ibv_flow_spec_eth){
1604                 .type = IBV_FLOW_SPEC_ETH,
1605                 .size = sizeof(*spec),
1606                 .val = {
1607                         .dst_mac = {
1608                                 (*mac)[0], (*mac)[1], (*mac)[2],
1609                                 (*mac)[3], (*mac)[4], (*mac)[5]
1610                         },
1611                 },
1612                 .mask = {
1613                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
1614                 }
1615         };
1616         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x",
1617               (void *)priv,
1618               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);
1619         /* Create related flow. */
1620         errno = 0;
1621         flow = ibv_create_flow(rxq->qp, attr);
1622         if (flow == NULL) {
1623                 /* It's not clear whether errno is always set in this case. */
1624                 ERROR("%p: flow configuration failed, errno=%d: %s",
1625                       (void *)rxq, errno,
1626                       (errno ? strerror(errno) : "Unknown error"));
1627                 if (errno)
1628                         return errno;
1629                 return EINVAL;
1630         }
1631         assert(priv->mac_flow == NULL);
1632         priv->mac_flow = flow;
1633         return 0;
1634 }
1635
1636 /**
1637  * Clean up a RX queue.
1638  *
1639  * Destroy objects, free allocated memory and reset the structure for reuse.
1640  *
1641  * @param rxq
1642  *   Pointer to RX queue structure.
1643  */
1644 static void
1645 rxq_cleanup(struct rxq *rxq)
1646 {
1647         struct ibv_exp_release_intf_params params;
1648
1649         DEBUG("cleaning up %p", (void *)rxq);
1650         rxq_free_elts(rxq);
1651         if (rxq->if_qp != NULL) {
1652                 assert(rxq->priv != NULL);
1653                 assert(rxq->priv->ctx != NULL);
1654                 assert(rxq->qp != NULL);
1655                 params = (struct ibv_exp_release_intf_params){
1656                         .comp_mask = 0,
1657                 };
1658                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
1659                                                 rxq->if_qp,
1660                                                 &params));
1661         }
1662         if (rxq->if_cq != NULL) {
1663                 assert(rxq->priv != NULL);
1664                 assert(rxq->priv->ctx != NULL);
1665                 assert(rxq->cq != NULL);
1666                 params = (struct ibv_exp_release_intf_params){
1667                         .comp_mask = 0,
1668                 };
1669                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
1670                                                 rxq->if_cq,
1671                                                 &params));
1672         }
1673         if (rxq->qp != NULL)
1674                 claim_zero(ibv_destroy_qp(rxq->qp));
1675         if (rxq->cq != NULL)
1676                 claim_zero(ibv_destroy_cq(rxq->cq));
1677         if (rxq->channel != NULL)
1678                 claim_zero(ibv_destroy_comp_channel(rxq->channel));
1679         if (rxq->mr != NULL)
1680                 claim_zero(ibv_dereg_mr(rxq->mr));
1681         memset(rxq, 0, sizeof(*rxq));
1682 }
1683
1684 /**
1685  * DPDK callback for RX.
1686  *
1687  * The following function doesn't manage scattered packets.
1688  *
1689  * @param dpdk_rxq
1690  *   Generic pointer to RX queue structure.
1691  * @param[out] pkts
1692  *   Array to store received packets.
1693  * @param pkts_n
1694  *   Maximum number of packets in array.
1695  *
1696  * @return
1697  *   Number of packets successfully received (<= pkts_n).
1698  */
1699 static uint16_t
1700 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
1701 {
1702         struct rxq *rxq = (struct rxq *)dpdk_rxq;
1703         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts;
1704         const unsigned int elts_n = rxq->elts_n;
1705         unsigned int elts_head = rxq->elts_head;
1706         struct ibv_sge sges[pkts_n];
1707         unsigned int i;
1708         unsigned int pkts_ret = 0;
1709         int ret;
1710
1711         for (i = 0; (i != pkts_n); ++i) {
1712                 struct rxq_elt *elt = &(*elts)[elts_head];
1713                 struct ibv_recv_wr *wr = &elt->wr;
1714                 uint64_t wr_id = wr->wr_id;
1715                 unsigned int len;
1716                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
1717                         WR_ID(wr_id).offset);
1718                 struct rte_mbuf *rep;
1719                 uint32_t flags;
1720
1721                 /* Sanity checks. */
1722                 assert(WR_ID(wr_id).id < rxq->elts_n);
1723                 assert(wr->sg_list == &elt->sge);
1724                 assert(wr->num_sge == 1);
1725                 assert(elts_head < rxq->elts_n);
1726                 assert(rxq->elts_head < rxq->elts_n);
1727                 /*
1728                  * Fetch initial bytes of packet descriptor into a
1729                  * cacheline while allocating rep.
1730                  */
1731                 rte_mbuf_prefetch_part1(seg);
1732                 rte_mbuf_prefetch_part2(seg);
1733                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
1734                                                     &flags);
1735                 if (unlikely(ret < 0)) {
1736                         struct ibv_wc wc;
1737                         int wcs_n;
1738
1739                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
1740                               (void *)rxq, ret);
1741                         /* ibv_poll_cq() must be used in case of failure. */
1742                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
1743                         if (unlikely(wcs_n == 0))
1744                                 break;
1745                         if (unlikely(wcs_n < 0)) {
1746                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
1747                                       (void *)rxq, wcs_n);
1748                                 break;
1749                         }
1750                         assert(wcs_n == 1);
1751                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
1752                                 /* Whatever, just repost the offending WR. */
1753                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
1754                                       " completion status (%d): %s",
1755                                       (void *)rxq, wc.wr_id, wc.status,
1756                                       ibv_wc_status_str(wc.status));
1757                                 /* Increment dropped packets counter. */
1758                                 ++rxq->stats.idropped;
1759                                 /* Add SGE to array for repost. */
1760                                 sges[i] = elt->sge;
1761                                 goto repost;
1762                         }
1763                         ret = wc.byte_len;
1764                 }
1765                 if (ret == 0)
1766                         break;
1767                 len = ret;
1768                 rep = rte_mbuf_raw_alloc(rxq->mp);
1769                 if (unlikely(rep == NULL)) {
1770                         /*
1771                          * Unable to allocate a replacement mbuf,
1772                          * repost WR.
1773                          */
1774                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
1775                               " can't allocate a new mbuf",
1776                               (void *)rxq, WR_ID(wr_id).id);
1777                         /* Increase out of memory counters. */
1778                         ++rxq->stats.rx_nombuf;
1779                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
1780                         /* Add SGE to array for repost. */
1781                         sges[i] = elt->sge;
1782                         goto repost;
1783                 }
1784
1785                 /* Reconfigure sge to use rep instead of seg. */
1786                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
1787                 assert(elt->sge.lkey == rxq->mr->lkey);
1788                 WR_ID(wr->wr_id).offset =
1789                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
1790                          (uintptr_t)rep);
1791                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
1792
1793                 /* Add SGE to array for repost. */
1794                 sges[i] = elt->sge;
1795
1796                 /* Update seg information. */
1797                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
1798                 NB_SEGS(seg) = 1;
1799                 PORT(seg) = rxq->port_id;
1800                 NEXT(seg) = NULL;
1801                 PKT_LEN(seg) = len;
1802                 DATA_LEN(seg) = len;
1803                 seg->packet_type = 0;
1804                 seg->ol_flags = 0;
1805
1806                 /* Return packet. */
1807                 *(pkts++) = seg;
1808                 ++pkts_ret;
1809                 /* Increase bytes counter. */
1810                 rxq->stats.ibytes += len;
1811 repost:
1812                 if (++elts_head >= elts_n)
1813                         elts_head = 0;
1814                 continue;
1815         }
1816         if (unlikely(i == 0))
1817                 return 0;
1818         /* Repost WRs. */
1819         ret = rxq->if_qp->recv_burst(rxq->qp, sges, i);
1820         if (unlikely(ret)) {
1821                 /* Inability to repost WRs is fatal. */
1822                 DEBUG("%p: recv_burst(): failed (ret=%d)",
1823                       (void *)rxq->priv,
1824                       ret);
1825                 abort();
1826         }
1827         rxq->elts_head = elts_head;
1828         /* Increase packets counter. */
1829         rxq->stats.ipackets += pkts_ret;
1830         return pkts_ret;
1831 }
1832
1833 /**
1834  * Allocate a Queue Pair.
1835  * Optionally setup inline receive if supported.
1836  *
1837  * @param priv
1838  *   Pointer to private structure.
1839  * @param cq
1840  *   Completion queue to associate with QP.
1841  * @param desc
1842  *   Number of descriptors in QP (hint only).
1843  *
1844  * @return
1845  *   QP pointer or NULL in case of error.
1846  */
1847 static struct ibv_qp *
1848 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc)
1849 {
1850         struct ibv_qp_init_attr attr = {
1851                 /* CQ to be associated with the send queue. */
1852                 .send_cq = cq,
1853                 /* CQ to be associated with the receive queue. */
1854                 .recv_cq = cq,
1855                 .cap = {
1856                         /* Max number of outstanding WRs. */
1857                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
1858                                         priv->device_attr.max_qp_wr :
1859                                         desc),
1860                         /* Max number of scatter/gather elements in a WR. */
1861                         .max_recv_sge = 1,
1862                 },
1863                 .qp_type = IBV_QPT_RAW_PACKET,
1864         };
1865
1866         return ibv_create_qp(priv->pd, &attr);
1867 }
1868
1869 /**
1870  * Configure a RX queue.
1871  *
1872  * @param dev
1873  *   Pointer to Ethernet device structure.
1874  * @param rxq
1875  *   Pointer to RX queue structure.
1876  * @param desc
1877  *   Number of descriptors to configure in queue.
1878  * @param socket
1879  *   NUMA socket on which memory must be allocated.
1880  * @param[in] conf
1881  *   Thresholds parameters.
1882  * @param mp
1883  *   Memory pool for buffer allocations.
1884  *
1885  * @return
1886  *   0 on success, errno value on failure.
1887  */
1888 static int
1889 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
1890           unsigned int socket, const struct rte_eth_rxconf *conf,
1891           struct rte_mempool *mp)
1892 {
1893         struct priv *priv = dev->data->dev_private;
1894         struct rxq tmpl = {
1895                 .priv = priv,
1896                 .mp = mp,
1897                 .socket = socket
1898         };
1899         struct ibv_qp_attr mod;
1900         union {
1901                 struct ibv_exp_query_intf_params params;
1902         } attr;
1903         enum ibv_exp_query_intf_status status;
1904         struct ibv_recv_wr *bad_wr;
1905         unsigned int mb_len;
1906         int ret = 0;
1907
1908         (void)conf; /* Thresholds configuration (ignored). */
1909         mb_len = rte_pktmbuf_data_room_size(mp);
1910         if (desc == 0) {
1911                 ERROR("%p: invalid number of Rx descriptors", (void *)dev);
1912                 return EINVAL;
1913         }
1914         /* Enable scattered packets support for this queue if necessary. */
1915         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
1916         if (dev->data->dev_conf.rxmode.max_rx_pkt_len <=
1917             (mb_len - RTE_PKTMBUF_HEADROOM)) {
1918                 ;
1919         } else if (dev->data->dev_conf.rxmode.enable_scatter) {
1920                 WARN("%p: scattered mode has been requested but is"
1921                      " not supported, this may lead to packet loss",
1922                      (void *)dev);
1923         } else {
1924                 WARN("%p: the requested maximum Rx packet size (%u) is"
1925                      " larger than a single mbuf (%u) and scattered"
1926                      " mode has not been requested",
1927                      (void *)dev,
1928                      dev->data->dev_conf.rxmode.max_rx_pkt_len,
1929                      mb_len - RTE_PKTMBUF_HEADROOM);
1930         }
1931         /* Use the entire RX mempool as the memory region. */
1932         tmpl.mr = mlx4_mp2mr(priv->pd, mp);
1933         if (tmpl.mr == NULL) {
1934                 ret = EINVAL;
1935                 ERROR("%p: MR creation failure: %s",
1936                       (void *)dev, strerror(ret));
1937                 goto error;
1938         }
1939         if (dev->data->dev_conf.intr_conf.rxq) {
1940                 tmpl.channel = ibv_create_comp_channel(priv->ctx);
1941                 if (tmpl.channel == NULL) {
1942                         ret = ENOMEM;
1943                         ERROR("%p: Rx interrupt completion channel creation"
1944                               " failure: %s",
1945                               (void *)dev, strerror(ret));
1946                         goto error;
1947                 }
1948         }
1949         tmpl.cq = ibv_create_cq(priv->ctx, desc, NULL, tmpl.channel, 0);
1950         if (tmpl.cq == NULL) {
1951                 ret = ENOMEM;
1952                 ERROR("%p: CQ creation failure: %s",
1953                       (void *)dev, strerror(ret));
1954                 goto error;
1955         }
1956         DEBUG("priv->device_attr.max_qp_wr is %d",
1957               priv->device_attr.max_qp_wr);
1958         DEBUG("priv->device_attr.max_sge is %d",
1959               priv->device_attr.max_sge);
1960         tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc);
1961         if (tmpl.qp == NULL) {
1962                 ret = (errno ? errno : EINVAL);
1963                 ERROR("%p: QP creation failure: %s",
1964                       (void *)dev, strerror(ret));
1965                 goto error;
1966         }
1967         mod = (struct ibv_qp_attr){
1968                 /* Move the QP to this state. */
1969                 .qp_state = IBV_QPS_INIT,
1970                 /* Primary port number. */
1971                 .port_num = priv->port
1972         };
1973         ret = ibv_modify_qp(tmpl.qp, &mod, IBV_QP_STATE | IBV_QP_PORT);
1974         if (ret) {
1975                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1976                       (void *)dev, strerror(ret));
1977                 goto error;
1978         }
1979         ret = rxq_alloc_elts(&tmpl, desc);
1980         if (ret) {
1981                 ERROR("%p: RXQ allocation failed: %s",
1982                       (void *)dev, strerror(ret));
1983                 goto error;
1984         }
1985         ret = ibv_post_recv(tmpl.qp, &(*tmpl.elts)[0].wr, &bad_wr);
1986         if (ret) {
1987                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
1988                       (void *)dev,
1989                       (void *)bad_wr,
1990                       strerror(ret));
1991                 goto error;
1992         }
1993         mod = (struct ibv_qp_attr){
1994                 .qp_state = IBV_QPS_RTR
1995         };
1996         ret = ibv_modify_qp(tmpl.qp, &mod, IBV_QP_STATE);
1997         if (ret) {
1998                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1999                       (void *)dev, strerror(ret));
2000                 goto error;
2001         }
2002         /* Save port ID. */
2003         tmpl.port_id = dev->data->port_id;
2004         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
2005         attr.params = (struct ibv_exp_query_intf_params){
2006                 .intf_scope = IBV_EXP_INTF_GLOBAL,
2007                 .intf = IBV_EXP_INTF_CQ,
2008                 .obj = tmpl.cq,
2009         };
2010         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
2011         if (tmpl.if_cq == NULL) {
2012                 ERROR("%p: CQ interface family query failed with status %d",
2013                       (void *)dev, status);
2014                 goto error;
2015         }
2016         attr.params = (struct ibv_exp_query_intf_params){
2017                 .intf_scope = IBV_EXP_INTF_GLOBAL,
2018                 .intf = IBV_EXP_INTF_QP_BURST,
2019                 .obj = tmpl.qp,
2020         };
2021         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
2022         if (tmpl.if_qp == NULL) {
2023                 ERROR("%p: QP interface family query failed with status %d",
2024                       (void *)dev, status);
2025                 goto error;
2026         }
2027         /* Clean up rxq in case we're reinitializing it. */
2028         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
2029         rxq_cleanup(rxq);
2030         *rxq = tmpl;
2031         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
2032         assert(ret == 0);
2033         return 0;
2034 error:
2035         rxq_cleanup(&tmpl);
2036         assert(ret > 0);
2037         return ret;
2038 }
2039
2040 /**
2041  * DPDK callback to configure a RX queue.
2042  *
2043  * @param dev
2044  *   Pointer to Ethernet device structure.
2045  * @param idx
2046  *   RX queue index.
2047  * @param desc
2048  *   Number of descriptors to configure in queue.
2049  * @param socket
2050  *   NUMA socket on which memory must be allocated.
2051  * @param[in] conf
2052  *   Thresholds parameters.
2053  * @param mp
2054  *   Memory pool for buffer allocations.
2055  *
2056  * @return
2057  *   0 on success, negative errno value on failure.
2058  */
2059 static int
2060 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
2061                     unsigned int socket, const struct rte_eth_rxconf *conf,
2062                     struct rte_mempool *mp)
2063 {
2064         struct priv *priv = dev->data->dev_private;
2065         struct rxq *rxq = (*priv->rxqs)[idx];
2066         int ret;
2067
2068         priv_lock(priv);
2069         DEBUG("%p: configuring queue %u for %u descriptors",
2070               (void *)dev, idx, desc);
2071         if (idx >= priv->rxqs_n) {
2072                 ERROR("%p: queue index out of range (%u >= %u)",
2073                       (void *)dev, idx, priv->rxqs_n);
2074                 priv_unlock(priv);
2075                 return -EOVERFLOW;
2076         }
2077         if (rxq != NULL) {
2078                 DEBUG("%p: reusing already allocated queue index %u (%p)",
2079                       (void *)dev, idx, (void *)rxq);
2080                 if (priv->started) {
2081                         priv_unlock(priv);
2082                         return -EEXIST;
2083                 }
2084                 (*priv->rxqs)[idx] = NULL;
2085                 if (idx == 0)
2086                         priv_mac_addr_del(priv);
2087                 rxq_cleanup(rxq);
2088         } else {
2089                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
2090                 if (rxq == NULL) {
2091                         ERROR("%p: unable to allocate queue index %u",
2092                               (void *)dev, idx);
2093                         priv_unlock(priv);
2094                         return -ENOMEM;
2095                 }
2096         }
2097         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
2098         if (ret)
2099                 rte_free(rxq);
2100         else {
2101                 rxq->stats.idx = idx;
2102                 DEBUG("%p: adding RX queue %p to list",
2103                       (void *)dev, (void *)rxq);
2104                 (*priv->rxqs)[idx] = rxq;
2105                 /* Update receive callback. */
2106                 dev->rx_pkt_burst = mlx4_rx_burst;
2107         }
2108         priv_unlock(priv);
2109         return -ret;
2110 }
2111
2112 /**
2113  * DPDK callback to release a RX queue.
2114  *
2115  * @param dpdk_rxq
2116  *   Generic RX queue pointer.
2117  */
2118 static void
2119 mlx4_rx_queue_release(void *dpdk_rxq)
2120 {
2121         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2122         struct priv *priv;
2123         unsigned int i;
2124
2125         if (rxq == NULL)
2126                 return;
2127         priv = rxq->priv;
2128         priv_lock(priv);
2129         for (i = 0; (i != priv->rxqs_n); ++i)
2130                 if ((*priv->rxqs)[i] == rxq) {
2131                         DEBUG("%p: removing RX queue %p from list",
2132                               (void *)priv->dev, (void *)rxq);
2133                         (*priv->rxqs)[i] = NULL;
2134                         if (i == 0)
2135                                 priv_mac_addr_del(priv);
2136                         break;
2137                 }
2138         rxq_cleanup(rxq);
2139         rte_free(rxq);
2140         priv_unlock(priv);
2141 }
2142
2143 static int
2144 priv_dev_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2145
2146 static int
2147 priv_dev_removal_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2148
2149 static int
2150 priv_dev_link_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2151
2152 /**
2153  * DPDK callback to start the device.
2154  *
2155  * Simulate device start by attaching all configured flows.
2156  *
2157  * @param dev
2158  *   Pointer to Ethernet device structure.
2159  *
2160  * @return
2161  *   0 on success, negative errno value on failure.
2162  */
2163 static int
2164 mlx4_dev_start(struct rte_eth_dev *dev)
2165 {
2166         struct priv *priv = dev->data->dev_private;
2167         int ret;
2168
2169         priv_lock(priv);
2170         if (priv->started) {
2171                 priv_unlock(priv);
2172                 return 0;
2173         }
2174         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
2175         priv->started = 1;
2176         ret = priv_mac_addr_add(priv);
2177         if (ret)
2178                 goto err;
2179         ret = priv_dev_link_interrupt_handler_install(priv, dev);
2180         if (ret) {
2181                 ERROR("%p: LSC handler install failed",
2182                      (void *)dev);
2183                 goto err;
2184         }
2185         ret = priv_dev_removal_interrupt_handler_install(priv, dev);
2186         if (ret) {
2187                 ERROR("%p: RMV handler install failed",
2188                      (void *)dev);
2189                 goto err;
2190         }
2191         ret = priv_rx_intr_vec_enable(priv);
2192         if (ret) {
2193                 ERROR("%p: Rx interrupt vector creation failed",
2194                       (void *)dev);
2195                 goto err;
2196         }
2197         ret = mlx4_priv_flow_start(priv);
2198         if (ret) {
2199                 ERROR("%p: flow start failed: %s",
2200                       (void *)dev, strerror(ret));
2201                 goto err;
2202         }
2203         priv_unlock(priv);
2204         return 0;
2205 err:
2206         /* Rollback. */
2207         priv_mac_addr_del(priv);
2208         priv->started = 0;
2209         priv_unlock(priv);
2210         return -ret;
2211 }
2212
2213 /**
2214  * DPDK callback to stop the device.
2215  *
2216  * Simulate device stop by detaching all configured flows.
2217  *
2218  * @param dev
2219  *   Pointer to Ethernet device structure.
2220  */
2221 static void
2222 mlx4_dev_stop(struct rte_eth_dev *dev)
2223 {
2224         struct priv *priv = dev->data->dev_private;
2225
2226         priv_lock(priv);
2227         if (!priv->started) {
2228                 priv_unlock(priv);
2229                 return;
2230         }
2231         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
2232         priv->started = 0;
2233         mlx4_priv_flow_stop(priv);
2234         priv_mac_addr_del(priv);
2235         priv_unlock(priv);
2236 }
2237
2238 /**
2239  * Dummy DPDK callback for TX.
2240  *
2241  * This function is used to temporarily replace the real callback during
2242  * unsafe control operations on the queue, or in case of error.
2243  *
2244  * @param dpdk_txq
2245  *   Generic pointer to TX queue structure.
2246  * @param[in] pkts
2247  *   Packets to transmit.
2248  * @param pkts_n
2249  *   Number of packets in array.
2250  *
2251  * @return
2252  *   Number of packets successfully transmitted (<= pkts_n).
2253  */
2254 static uint16_t
2255 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
2256 {
2257         (void)dpdk_txq;
2258         (void)pkts;
2259         (void)pkts_n;
2260         return 0;
2261 }
2262
2263 /**
2264  * Dummy DPDK callback for RX.
2265  *
2266  * This function is used to temporarily replace the real callback during
2267  * unsafe control operations on the queue, or in case of error.
2268  *
2269  * @param dpdk_rxq
2270  *   Generic pointer to RX queue structure.
2271  * @param[out] pkts
2272  *   Array to store received packets.
2273  * @param pkts_n
2274  *   Maximum number of packets in array.
2275  *
2276  * @return
2277  *   Number of packets successfully received (<= pkts_n).
2278  */
2279 static uint16_t
2280 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2281 {
2282         (void)dpdk_rxq;
2283         (void)pkts;
2284         (void)pkts_n;
2285         return 0;
2286 }
2287
2288 static int
2289 priv_dev_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
2290
2291 static int
2292 priv_dev_removal_interrupt_handler_uninstall(struct priv *,
2293                                              struct rte_eth_dev *);
2294
2295 static int
2296 priv_dev_link_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
2297
2298 /**
2299  * DPDK callback to close the device.
2300  *
2301  * Destroy all queues and objects, free memory.
2302  *
2303  * @param dev
2304  *   Pointer to Ethernet device structure.
2305  */
2306 static void
2307 mlx4_dev_close(struct rte_eth_dev *dev)
2308 {
2309         struct priv *priv = dev->data->dev_private;
2310         void *tmp;
2311         unsigned int i;
2312
2313         if (priv == NULL)
2314                 return;
2315         priv_lock(priv);
2316         DEBUG("%p: closing device \"%s\"",
2317               (void *)dev,
2318               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
2319         priv_mac_addr_del(priv);
2320         /* Prevent crashes when queues are still in use. This is unfortunately
2321          * still required for DPDK 1.3 because some programs (such as testpmd)
2322          * never release them before closing the device. */
2323         dev->rx_pkt_burst = removed_rx_burst;
2324         dev->tx_pkt_burst = removed_tx_burst;
2325         if (priv->rxqs != NULL) {
2326                 /* XXX race condition if mlx4_rx_burst() is still running. */
2327                 usleep(1000);
2328                 for (i = 0; (i != priv->rxqs_n); ++i) {
2329                         tmp = (*priv->rxqs)[i];
2330                         if (tmp == NULL)
2331                                 continue;
2332                         (*priv->rxqs)[i] = NULL;
2333                         rxq_cleanup(tmp);
2334                         rte_free(tmp);
2335                 }
2336                 priv->rxqs_n = 0;
2337                 priv->rxqs = NULL;
2338         }
2339         if (priv->txqs != NULL) {
2340                 /* XXX race condition if mlx4_tx_burst() is still running. */
2341                 usleep(1000);
2342                 for (i = 0; (i != priv->txqs_n); ++i) {
2343                         tmp = (*priv->txqs)[i];
2344                         if (tmp == NULL)
2345                                 continue;
2346                         (*priv->txqs)[i] = NULL;
2347                         txq_cleanup(tmp);
2348                         rte_free(tmp);
2349                 }
2350                 priv->txqs_n = 0;
2351                 priv->txqs = NULL;
2352         }
2353         if (priv->pd != NULL) {
2354                 assert(priv->ctx != NULL);
2355                 claim_zero(ibv_dealloc_pd(priv->pd));
2356                 claim_zero(ibv_close_device(priv->ctx));
2357         } else
2358                 assert(priv->ctx == NULL);
2359         priv_dev_removal_interrupt_handler_uninstall(priv, dev);
2360         priv_dev_link_interrupt_handler_uninstall(priv, dev);
2361         priv_rx_intr_vec_disable(priv);
2362         priv_unlock(priv);
2363         memset(priv, 0, sizeof(*priv));
2364 }
2365
2366 /**
2367  * Change the link state (UP / DOWN).
2368  *
2369  * @param priv
2370  *   Pointer to Ethernet device private data.
2371  * @param up
2372  *   Nonzero for link up, otherwise link down.
2373  *
2374  * @return
2375  *   0 on success, errno value on failure.
2376  */
2377 static int
2378 priv_set_link(struct priv *priv, int up)
2379 {
2380         struct rte_eth_dev *dev = priv->dev;
2381         int err;
2382
2383         if (up) {
2384                 err = priv_set_flags(priv, ~IFF_UP, IFF_UP);
2385                 if (err)
2386                         return err;
2387                 dev->rx_pkt_burst = mlx4_rx_burst;
2388         } else {
2389                 err = priv_set_flags(priv, ~IFF_UP, ~IFF_UP);
2390                 if (err)
2391                         return err;
2392                 dev->rx_pkt_burst = removed_rx_burst;
2393                 dev->tx_pkt_burst = removed_tx_burst;
2394         }
2395         return 0;
2396 }
2397
2398 /**
2399  * DPDK callback to bring the link DOWN.
2400  *
2401  * @param dev
2402  *   Pointer to Ethernet device structure.
2403  *
2404  * @return
2405  *   0 on success, errno value on failure.
2406  */
2407 static int
2408 mlx4_set_link_down(struct rte_eth_dev *dev)
2409 {
2410         struct priv *priv = dev->data->dev_private;
2411         int err;
2412
2413         priv_lock(priv);
2414         err = priv_set_link(priv, 0);
2415         priv_unlock(priv);
2416         return err;
2417 }
2418
2419 /**
2420  * DPDK callback to bring the link UP.
2421  *
2422  * @param dev
2423  *   Pointer to Ethernet device structure.
2424  *
2425  * @return
2426  *   0 on success, errno value on failure.
2427  */
2428 static int
2429 mlx4_set_link_up(struct rte_eth_dev *dev)
2430 {
2431         struct priv *priv = dev->data->dev_private;
2432         int err;
2433
2434         priv_lock(priv);
2435         err = priv_set_link(priv, 1);
2436         priv_unlock(priv);
2437         return err;
2438 }
2439 /**
2440  * DPDK callback to get information about the device.
2441  *
2442  * @param dev
2443  *   Pointer to Ethernet device structure.
2444  * @param[out] info
2445  *   Info structure output buffer.
2446  */
2447 static void
2448 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
2449 {
2450         struct priv *priv = dev->data->dev_private;
2451         unsigned int max;
2452         char ifname[IF_NAMESIZE];
2453
2454         info->pci_dev = RTE_ETH_DEV_TO_PCI(dev);
2455
2456         if (priv == NULL)
2457                 return;
2458         priv_lock(priv);
2459         /* FIXME: we should ask the device for these values. */
2460         info->min_rx_bufsize = 32;
2461         info->max_rx_pktlen = 65536;
2462         /*
2463          * Since we need one CQ per QP, the limit is the minimum number
2464          * between the two values.
2465          */
2466         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
2467                priv->device_attr.max_qp : priv->device_attr.max_cq);
2468         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
2469         if (max >= 65535)
2470                 max = 65535;
2471         info->max_rx_queues = max;
2472         info->max_tx_queues = max;
2473         /* Last array entry is reserved for broadcast. */
2474         info->max_mac_addrs = 1;
2475         info->rx_offload_capa = 0;
2476         info->tx_offload_capa = 0;
2477         if (priv_get_ifname(priv, &ifname) == 0)
2478                 info->if_index = if_nametoindex(ifname);
2479         info->speed_capa =
2480                         ETH_LINK_SPEED_1G |
2481                         ETH_LINK_SPEED_10G |
2482                         ETH_LINK_SPEED_20G |
2483                         ETH_LINK_SPEED_40G |
2484                         ETH_LINK_SPEED_56G;
2485         priv_unlock(priv);
2486 }
2487
2488 /**
2489  * DPDK callback to get device statistics.
2490  *
2491  * @param dev
2492  *   Pointer to Ethernet device structure.
2493  * @param[out] stats
2494  *   Stats structure output buffer.
2495  */
2496 static void
2497 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
2498 {
2499         struct priv *priv = dev->data->dev_private;
2500         struct rte_eth_stats tmp = {0};
2501         unsigned int i;
2502         unsigned int idx;
2503
2504         if (priv == NULL)
2505                 return;
2506         priv_lock(priv);
2507         /* Add software counters. */
2508         for (i = 0; (i != priv->rxqs_n); ++i) {
2509                 struct rxq *rxq = (*priv->rxqs)[i];
2510
2511                 if (rxq == NULL)
2512                         continue;
2513                 idx = rxq->stats.idx;
2514                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
2515                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
2516                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
2517                         tmp.q_errors[idx] += (rxq->stats.idropped +
2518                                               rxq->stats.rx_nombuf);
2519                 }
2520                 tmp.ipackets += rxq->stats.ipackets;
2521                 tmp.ibytes += rxq->stats.ibytes;
2522                 tmp.ierrors += rxq->stats.idropped;
2523                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
2524         }
2525         for (i = 0; (i != priv->txqs_n); ++i) {
2526                 struct txq *txq = (*priv->txqs)[i];
2527
2528                 if (txq == NULL)
2529                         continue;
2530                 idx = txq->stats.idx;
2531                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
2532                         tmp.q_opackets[idx] += txq->stats.opackets;
2533                         tmp.q_obytes[idx] += txq->stats.obytes;
2534                         tmp.q_errors[idx] += txq->stats.odropped;
2535                 }
2536                 tmp.opackets += txq->stats.opackets;
2537                 tmp.obytes += txq->stats.obytes;
2538                 tmp.oerrors += txq->stats.odropped;
2539         }
2540         *stats = tmp;
2541         priv_unlock(priv);
2542 }
2543
2544 /**
2545  * DPDK callback to clear device statistics.
2546  *
2547  * @param dev
2548  *   Pointer to Ethernet device structure.
2549  */
2550 static void
2551 mlx4_stats_reset(struct rte_eth_dev *dev)
2552 {
2553         struct priv *priv = dev->data->dev_private;
2554         unsigned int i;
2555         unsigned int idx;
2556
2557         if (priv == NULL)
2558                 return;
2559         priv_lock(priv);
2560         for (i = 0; (i != priv->rxqs_n); ++i) {
2561                 if ((*priv->rxqs)[i] == NULL)
2562                         continue;
2563                 idx = (*priv->rxqs)[i]->stats.idx;
2564                 (*priv->rxqs)[i]->stats =
2565                         (struct mlx4_rxq_stats){ .idx = idx };
2566         }
2567         for (i = 0; (i != priv->txqs_n); ++i) {
2568                 if ((*priv->txqs)[i] == NULL)
2569                         continue;
2570                 idx = (*priv->txqs)[i]->stats.idx;
2571                 (*priv->txqs)[i]->stats =
2572                         (struct mlx4_txq_stats){ .idx = idx };
2573         }
2574         priv_unlock(priv);
2575 }
2576
2577 /**
2578  * DPDK callback to retrieve physical link information.
2579  *
2580  * @param dev
2581  *   Pointer to Ethernet device structure.
2582  * @param wait_to_complete
2583  *   Wait for request completion (ignored).
2584  */
2585 static int
2586 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
2587 {
2588         const struct priv *priv = dev->data->dev_private;
2589         struct ethtool_cmd edata = {
2590                 .cmd = ETHTOOL_GSET
2591         };
2592         struct ifreq ifr;
2593         struct rte_eth_link dev_link;
2594         int link_speed = 0;
2595
2596         /* priv_lock() is not taken to allow concurrent calls. */
2597
2598         if (priv == NULL)
2599                 return -EINVAL;
2600         (void)wait_to_complete;
2601         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
2602                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(errno));
2603                 return -1;
2604         }
2605         memset(&dev_link, 0, sizeof(dev_link));
2606         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
2607                                 (ifr.ifr_flags & IFF_RUNNING));
2608         ifr.ifr_data = (void *)&edata;
2609         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2610                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
2611                      strerror(errno));
2612                 return -1;
2613         }
2614         link_speed = ethtool_cmd_speed(&edata);
2615         if (link_speed == -1)
2616                 dev_link.link_speed = 0;
2617         else
2618                 dev_link.link_speed = link_speed;
2619         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
2620                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
2621         dev_link.link_autoneg = !(dev->data->dev_conf.link_speeds &
2622                         ETH_LINK_SPEED_FIXED);
2623         if (memcmp(&dev_link, &dev->data->dev_link, sizeof(dev_link))) {
2624                 /* Link status changed. */
2625                 dev->data->dev_link = dev_link;
2626                 return 0;
2627         }
2628         /* Link status is still the same. */
2629         return -1;
2630 }
2631
2632 /**
2633  * DPDK callback to change the MTU.
2634  *
2635  * @param dev
2636  *   Pointer to Ethernet device structure.
2637  * @param in_mtu
2638  *   New MTU.
2639  *
2640  * @return
2641  *   0 on success, negative errno value on failure.
2642  */
2643 static int
2644 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
2645 {
2646         struct priv *priv = dev->data->dev_private;
2647         int ret = 0;
2648
2649         priv_lock(priv);
2650         /* Set kernel interface MTU first. */
2651         if (priv_set_mtu(priv, mtu)) {
2652                 ret = errno;
2653                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
2654                      strerror(ret));
2655                 goto out;
2656         } else
2657                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
2658         priv->mtu = mtu;
2659 out:
2660         priv_unlock(priv);
2661         assert(ret >= 0);
2662         return -ret;
2663 }
2664
2665 /**
2666  * DPDK callback to get flow control status.
2667  *
2668  * @param dev
2669  *   Pointer to Ethernet device structure.
2670  * @param[out] fc_conf
2671  *   Flow control output buffer.
2672  *
2673  * @return
2674  *   0 on success, negative errno value on failure.
2675  */
2676 static int
2677 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
2678 {
2679         struct priv *priv = dev->data->dev_private;
2680         struct ifreq ifr;
2681         struct ethtool_pauseparam ethpause = {
2682                 .cmd = ETHTOOL_GPAUSEPARAM
2683         };
2684         int ret;
2685
2686         ifr.ifr_data = (void *)&ethpause;
2687         priv_lock(priv);
2688         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2689                 ret = errno;
2690                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
2691                      " failed: %s",
2692                      strerror(ret));
2693                 goto out;
2694         }
2695
2696         fc_conf->autoneg = ethpause.autoneg;
2697         if (ethpause.rx_pause && ethpause.tx_pause)
2698                 fc_conf->mode = RTE_FC_FULL;
2699         else if (ethpause.rx_pause)
2700                 fc_conf->mode = RTE_FC_RX_PAUSE;
2701         else if (ethpause.tx_pause)
2702                 fc_conf->mode = RTE_FC_TX_PAUSE;
2703         else
2704                 fc_conf->mode = RTE_FC_NONE;
2705         ret = 0;
2706
2707 out:
2708         priv_unlock(priv);
2709         assert(ret >= 0);
2710         return -ret;
2711 }
2712
2713 /**
2714  * DPDK callback to modify flow control parameters.
2715  *
2716  * @param dev
2717  *   Pointer to Ethernet device structure.
2718  * @param[in] fc_conf
2719  *   Flow control parameters.
2720  *
2721  * @return
2722  *   0 on success, negative errno value on failure.
2723  */
2724 static int
2725 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
2726 {
2727         struct priv *priv = dev->data->dev_private;
2728         struct ifreq ifr;
2729         struct ethtool_pauseparam ethpause = {
2730                 .cmd = ETHTOOL_SPAUSEPARAM
2731         };
2732         int ret;
2733
2734         ifr.ifr_data = (void *)&ethpause;
2735         ethpause.autoneg = fc_conf->autoneg;
2736         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
2737             (fc_conf->mode & RTE_FC_RX_PAUSE))
2738                 ethpause.rx_pause = 1;
2739         else
2740                 ethpause.rx_pause = 0;
2741
2742         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
2743             (fc_conf->mode & RTE_FC_TX_PAUSE))
2744                 ethpause.tx_pause = 1;
2745         else
2746                 ethpause.tx_pause = 0;
2747
2748         priv_lock(priv);
2749         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2750                 ret = errno;
2751                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
2752                      " failed: %s",
2753                      strerror(ret));
2754                 goto out;
2755         }
2756         ret = 0;
2757
2758 out:
2759         priv_unlock(priv);
2760         assert(ret >= 0);
2761         return -ret;
2762 }
2763
2764 const struct rte_flow_ops mlx4_flow_ops = {
2765         .validate = mlx4_flow_validate,
2766         .create = mlx4_flow_create,
2767         .destroy = mlx4_flow_destroy,
2768         .flush = mlx4_flow_flush,
2769         .query = NULL,
2770         .isolate = mlx4_flow_isolate,
2771 };
2772
2773 /**
2774  * Manage filter operations.
2775  *
2776  * @param dev
2777  *   Pointer to Ethernet device structure.
2778  * @param filter_type
2779  *   Filter type.
2780  * @param filter_op
2781  *   Operation to perform.
2782  * @param arg
2783  *   Pointer to operation-specific structure.
2784  *
2785  * @return
2786  *   0 on success, negative errno value on failure.
2787  */
2788 static int
2789 mlx4_dev_filter_ctrl(struct rte_eth_dev *dev,
2790                      enum rte_filter_type filter_type,
2791                      enum rte_filter_op filter_op,
2792                      void *arg)
2793 {
2794         int ret = EINVAL;
2795
2796         switch (filter_type) {
2797         case RTE_ETH_FILTER_GENERIC:
2798                 if (filter_op != RTE_ETH_FILTER_GET)
2799                         return -EINVAL;
2800                 *(const void **)arg = &mlx4_flow_ops;
2801                 return 0;
2802         default:
2803                 ERROR("%p: filter type (%d) not supported",
2804                       (void *)dev, filter_type);
2805                 break;
2806         }
2807         return -ret;
2808 }
2809
2810 static const struct eth_dev_ops mlx4_dev_ops = {
2811         .dev_configure = mlx4_dev_configure,
2812         .dev_start = mlx4_dev_start,
2813         .dev_stop = mlx4_dev_stop,
2814         .dev_set_link_down = mlx4_set_link_down,
2815         .dev_set_link_up = mlx4_set_link_up,
2816         .dev_close = mlx4_dev_close,
2817         .link_update = mlx4_link_update,
2818         .stats_get = mlx4_stats_get,
2819         .stats_reset = mlx4_stats_reset,
2820         .dev_infos_get = mlx4_dev_infos_get,
2821         .rx_queue_setup = mlx4_rx_queue_setup,
2822         .tx_queue_setup = mlx4_tx_queue_setup,
2823         .rx_queue_release = mlx4_rx_queue_release,
2824         .tx_queue_release = mlx4_tx_queue_release,
2825         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
2826         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
2827         .mtu_set = mlx4_dev_set_mtu,
2828         .filter_ctrl = mlx4_dev_filter_ctrl,
2829         .rx_queue_intr_enable = mlx4_rx_intr_enable,
2830         .rx_queue_intr_disable = mlx4_rx_intr_disable,
2831 };
2832
2833 /**
2834  * Get PCI information from struct ibv_device.
2835  *
2836  * @param device
2837  *   Pointer to Ethernet device structure.
2838  * @param[out] pci_addr
2839  *   PCI bus address output buffer.
2840  *
2841  * @return
2842  *   0 on success, -1 on failure and errno is set.
2843  */
2844 static int
2845 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
2846                             struct rte_pci_addr *pci_addr)
2847 {
2848         FILE *file;
2849         char line[32];
2850         MKSTR(path, "%s/device/uevent", device->ibdev_path);
2851
2852         file = fopen(path, "rb");
2853         if (file == NULL)
2854                 return -1;
2855         while (fgets(line, sizeof(line), file) == line) {
2856                 size_t len = strlen(line);
2857                 int ret;
2858
2859                 /* Truncate long lines. */
2860                 if (len == (sizeof(line) - 1))
2861                         while (line[(len - 1)] != '\n') {
2862                                 ret = fgetc(file);
2863                                 if (ret == EOF)
2864                                         break;
2865                                 line[(len - 1)] = ret;
2866                         }
2867                 /* Extract information. */
2868                 if (sscanf(line,
2869                            "PCI_SLOT_NAME="
2870                            "%" SCNx32 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
2871                            &pci_addr->domain,
2872                            &pci_addr->bus,
2873                            &pci_addr->devid,
2874                            &pci_addr->function) == 4) {
2875                         ret = 0;
2876                         break;
2877                 }
2878         }
2879         fclose(file);
2880         return 0;
2881 }
2882
2883 /**
2884  * Get MAC address by querying netdevice.
2885  *
2886  * @param[in] priv
2887  *   struct priv for the requested device.
2888  * @param[out] mac
2889  *   MAC address output buffer.
2890  *
2891  * @return
2892  *   0 on success, -1 on failure and errno is set.
2893  */
2894 static int
2895 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
2896 {
2897         struct ifreq request;
2898
2899         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
2900                 return -1;
2901         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
2902         return 0;
2903 }
2904
2905 static void
2906 mlx4_dev_link_status_handler(void *);
2907 static void
2908 mlx4_dev_interrupt_handler(void *);
2909
2910 /**
2911  * Link/device status handler.
2912  *
2913  * @param priv
2914  *   Pointer to private structure.
2915  * @param dev
2916  *   Pointer to the rte_eth_dev structure.
2917  * @param events
2918  *   Pointer to event flags holder.
2919  *
2920  * @return
2921  *   Number of events
2922  */
2923 static int
2924 priv_dev_status_handler(struct priv *priv, struct rte_eth_dev *dev,
2925                         uint32_t *events)
2926 {
2927         struct ibv_async_event event;
2928         int port_change = 0;
2929         struct rte_eth_link *link = &dev->data->dev_link;
2930         int ret = 0;
2931
2932         *events = 0;
2933         /* Read all message and acknowledge them. */
2934         for (;;) {
2935                 if (ibv_get_async_event(priv->ctx, &event))
2936                         break;
2937                 if ((event.event_type == IBV_EVENT_PORT_ACTIVE ||
2938                      event.event_type == IBV_EVENT_PORT_ERR) &&
2939                     (priv->intr_conf.lsc == 1)) {
2940                         port_change = 1;
2941                         ret++;
2942                 } else if (event.event_type == IBV_EVENT_DEVICE_FATAL &&
2943                            priv->intr_conf.rmv == 1) {
2944                         *events |= (1 << RTE_ETH_EVENT_INTR_RMV);
2945                         ret++;
2946                 } else
2947                         DEBUG("event type %d on port %d not handled",
2948                               event.event_type, event.element.port_num);
2949                 ibv_ack_async_event(&event);
2950         }
2951         if (!port_change)
2952                 return ret;
2953         mlx4_link_update(dev, 0);
2954         if (((link->link_speed == 0) && link->link_status) ||
2955             ((link->link_speed != 0) && !link->link_status)) {
2956                 if (!priv->pending_alarm) {
2957                         /* Inconsistent status, check again later. */
2958                         priv->pending_alarm = 1;
2959                         rte_eal_alarm_set(MLX4_ALARM_TIMEOUT_US,
2960                                           mlx4_dev_link_status_handler,
2961                                           dev);
2962                 }
2963         } else {
2964                 *events |= (1 << RTE_ETH_EVENT_INTR_LSC);
2965         }
2966         return ret;
2967 }
2968
2969 /**
2970  * Handle delayed link status event.
2971  *
2972  * @param arg
2973  *   Registered argument.
2974  */
2975 static void
2976 mlx4_dev_link_status_handler(void *arg)
2977 {
2978         struct rte_eth_dev *dev = arg;
2979         struct priv *priv = dev->data->dev_private;
2980         uint32_t events;
2981         int ret;
2982
2983         priv_lock(priv);
2984         assert(priv->pending_alarm == 1);
2985         priv->pending_alarm = 0;
2986         ret = priv_dev_status_handler(priv, dev, &events);
2987         priv_unlock(priv);
2988         if (ret > 0 && events & (1 << RTE_ETH_EVENT_INTR_LSC))
2989                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC, NULL,
2990                                               NULL);
2991 }
2992
2993 /**
2994  * Handle interrupts from the NIC.
2995  *
2996  * @param[in] intr_handle
2997  *   Interrupt handler.
2998  * @param cb_arg
2999  *   Callback argument.
3000  */
3001 static void
3002 mlx4_dev_interrupt_handler(void *cb_arg)
3003 {
3004         struct rte_eth_dev *dev = cb_arg;
3005         struct priv *priv = dev->data->dev_private;
3006         int ret;
3007         uint32_t ev;
3008         int i;
3009
3010         priv_lock(priv);
3011         ret = priv_dev_status_handler(priv, dev, &ev);
3012         priv_unlock(priv);
3013         if (ret > 0) {
3014                 for (i = RTE_ETH_EVENT_UNKNOWN;
3015                      i < RTE_ETH_EVENT_MAX;
3016                      i++) {
3017                         if (ev & (1 << i)) {
3018                                 ev &= ~(1 << i);
3019                                 _rte_eth_dev_callback_process(dev, i, NULL,
3020                                                               NULL);
3021                                 ret--;
3022                         }
3023                 }
3024                 if (ret)
3025                         WARN("%d event%s not processed", ret,
3026                              (ret > 1 ? "s were" : " was"));
3027         }
3028 }
3029
3030 /**
3031  * Uninstall interrupt handler.
3032  *
3033  * @param priv
3034  *   Pointer to private structure.
3035  * @param dev
3036  *   Pointer to the rte_eth_dev structure.
3037  * @return
3038  *   0 on success, negative errno value on failure.
3039  */
3040 static int
3041 priv_dev_interrupt_handler_uninstall(struct priv *priv, struct rte_eth_dev *dev)
3042 {
3043         int ret;
3044
3045         if (priv->intr_conf.lsc ||
3046             priv->intr_conf.rmv)
3047                 return 0;
3048         ret = rte_intr_callback_unregister(&priv->intr_handle,
3049                                            mlx4_dev_interrupt_handler,
3050                                            dev);
3051         if (ret < 0) {
3052                 ERROR("rte_intr_callback_unregister failed with %d"
3053                       "%s%s%s", ret,
3054                       (errno ? " (errno: " : ""),
3055                       (errno ? strerror(errno) : ""),
3056                       (errno ? ")" : ""));
3057         }
3058         priv->intr_handle.fd = 0;
3059         priv->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
3060         return ret;
3061 }
3062
3063 /**
3064  * Install interrupt handler.
3065  *
3066  * @param priv
3067  *   Pointer to private structure.
3068  * @param dev
3069  *   Pointer to the rte_eth_dev structure.
3070  * @return
3071  *   0 on success, negative errno value on failure.
3072  */
3073 static int
3074 priv_dev_interrupt_handler_install(struct priv *priv,
3075                                    struct rte_eth_dev *dev)
3076 {
3077         int flags;
3078         int rc;
3079
3080         /* Check whether the interrupt handler has already been installed
3081          * for either type of interrupt
3082          */
3083         if (priv->intr_conf.lsc &&
3084             priv->intr_conf.rmv &&
3085             priv->intr_handle.fd)
3086                 return 0;
3087         assert(priv->ctx->async_fd > 0);
3088         flags = fcntl(priv->ctx->async_fd, F_GETFL);
3089         rc = fcntl(priv->ctx->async_fd, F_SETFL, flags | O_NONBLOCK);
3090         if (rc < 0) {
3091                 INFO("failed to change file descriptor async event queue");
3092                 dev->data->dev_conf.intr_conf.lsc = 0;
3093                 dev->data->dev_conf.intr_conf.rmv = 0;
3094                 return -errno;
3095         } else {
3096                 priv->intr_handle.fd = priv->ctx->async_fd;
3097                 priv->intr_handle.type = RTE_INTR_HANDLE_EXT;
3098                 rc = rte_intr_callback_register(&priv->intr_handle,
3099                                                  mlx4_dev_interrupt_handler,
3100                                                  dev);
3101                 if (rc) {
3102                         ERROR("rte_intr_callback_register failed "
3103                               " (errno: %s)", strerror(errno));
3104                         return rc;
3105                 }
3106         }
3107         return 0;
3108 }
3109
3110 /**
3111  * Uninstall interrupt handler.
3112  *
3113  * @param priv
3114  *   Pointer to private structure.
3115  * @param dev
3116  *   Pointer to the rte_eth_dev structure.
3117  * @return
3118  *   0 on success, negative value on error.
3119  */
3120 static int
3121 priv_dev_removal_interrupt_handler_uninstall(struct priv *priv,
3122                                             struct rte_eth_dev *dev)
3123 {
3124         if (dev->data->dev_conf.intr_conf.rmv) {
3125                 priv->intr_conf.rmv = 0;
3126                 return priv_dev_interrupt_handler_uninstall(priv, dev);
3127         }
3128         return 0;
3129 }
3130
3131 /**
3132  * Uninstall interrupt handler.
3133  *
3134  * @param priv
3135  *   Pointer to private structure.
3136  * @param dev
3137  *   Pointer to the rte_eth_dev structure.
3138  * @return
3139  *   0 on success, negative value on error,
3140  */
3141 static int
3142 priv_dev_link_interrupt_handler_uninstall(struct priv *priv,
3143                                           struct rte_eth_dev *dev)
3144 {
3145         int ret = 0;
3146
3147         if (dev->data->dev_conf.intr_conf.lsc) {
3148                 priv->intr_conf.lsc = 0;
3149                 ret = priv_dev_interrupt_handler_uninstall(priv, dev);
3150                 if (ret)
3151                         return ret;
3152         }
3153         if (priv->pending_alarm)
3154                 if (rte_eal_alarm_cancel(mlx4_dev_link_status_handler,
3155                                          dev)) {
3156                         ERROR("rte_eal_alarm_cancel failed "
3157                               " (errno: %s)", strerror(rte_errno));
3158                         return -rte_errno;
3159                 }
3160         priv->pending_alarm = 0;
3161         return 0;
3162 }
3163
3164 /**
3165  * Install link interrupt handler.
3166  *
3167  * @param priv
3168  *   Pointer to private structure.
3169  * @param dev
3170  *   Pointer to the rte_eth_dev structure.
3171  * @return
3172  *   0 on success, negative value on error.
3173  */
3174 static int
3175 priv_dev_link_interrupt_handler_install(struct priv *priv,
3176                                         struct rte_eth_dev *dev)
3177 {
3178         int ret;
3179
3180         if (dev->data->dev_conf.intr_conf.lsc) {
3181                 ret = priv_dev_interrupt_handler_install(priv, dev);
3182                 if (ret)
3183                         return ret;
3184                 priv->intr_conf.lsc = 1;
3185         }
3186         return 0;
3187 }
3188
3189 /**
3190  * Install removal interrupt handler.
3191  *
3192  * @param priv
3193  *   Pointer to private structure.
3194  * @param dev
3195  *   Pointer to the rte_eth_dev structure.
3196  * @return
3197  *   0 on success, negative value on error.
3198  */
3199 static int
3200 priv_dev_removal_interrupt_handler_install(struct priv *priv,
3201                                            struct rte_eth_dev *dev)
3202 {
3203         int ret;
3204
3205         if (dev->data->dev_conf.intr_conf.rmv) {
3206                 ret = priv_dev_interrupt_handler_install(priv, dev);
3207                 if (ret)
3208                         return ret;
3209                 priv->intr_conf.rmv = 1;
3210         }
3211         return 0;
3212 }
3213
3214 /**
3215  * Allocate queue vector and fill epoll fd list for Rx interrupts.
3216  *
3217  * @param priv
3218  *   Pointer to private structure.
3219  *
3220  * @return
3221  *   0 on success, negative on failure.
3222  */
3223 static int
3224 priv_rx_intr_vec_enable(struct priv *priv)
3225 {
3226         unsigned int i;
3227         unsigned int rxqs_n = priv->rxqs_n;
3228         unsigned int n = RTE_MIN(rxqs_n, (uint32_t)RTE_MAX_RXTX_INTR_VEC_ID);
3229         unsigned int count = 0;
3230         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
3231
3232         if (!priv->dev->data->dev_conf.intr_conf.rxq)
3233                 return 0;
3234         priv_rx_intr_vec_disable(priv);
3235         intr_handle->intr_vec = malloc(sizeof(intr_handle->intr_vec[rxqs_n]));
3236         if (intr_handle->intr_vec == NULL) {
3237                 ERROR("failed to allocate memory for interrupt vector,"
3238                       " Rx interrupts will not be supported");
3239                 return -ENOMEM;
3240         }
3241         intr_handle->type = RTE_INTR_HANDLE_EXT;
3242         for (i = 0; i != n; ++i) {
3243                 struct rxq *rxq = (*priv->rxqs)[i];
3244                 int fd;
3245                 int flags;
3246                 int rc;
3247
3248                 /* Skip queues that cannot request interrupts. */
3249                 if (!rxq || !rxq->channel) {
3250                         /* Use invalid intr_vec[] index to disable entry. */
3251                         intr_handle->intr_vec[i] =
3252                                 RTE_INTR_VEC_RXTX_OFFSET +
3253                                 RTE_MAX_RXTX_INTR_VEC_ID;
3254                         continue;
3255                 }
3256                 if (count >= RTE_MAX_RXTX_INTR_VEC_ID) {
3257                         ERROR("too many Rx queues for interrupt vector size"
3258                               " (%d), Rx interrupts cannot be enabled",
3259                               RTE_MAX_RXTX_INTR_VEC_ID);
3260                         priv_rx_intr_vec_disable(priv);
3261                         return -1;
3262                 }
3263                 fd = rxq->channel->fd;
3264                 flags = fcntl(fd, F_GETFL);
3265                 rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
3266                 if (rc < 0) {
3267                         ERROR("failed to make Rx interrupt file descriptor"
3268                               " %d non-blocking for queue index %d", fd, i);
3269                         priv_rx_intr_vec_disable(priv);
3270                         return rc;
3271                 }
3272                 intr_handle->intr_vec[i] = RTE_INTR_VEC_RXTX_OFFSET + count;
3273                 intr_handle->efds[count] = fd;
3274                 count++;
3275         }
3276         if (!count)
3277                 priv_rx_intr_vec_disable(priv);
3278         else
3279                 intr_handle->nb_efd = count;
3280         return 0;
3281 }
3282
3283 /**
3284  * Clean up Rx interrupts handler.
3285  *
3286  * @param priv
3287  *   Pointer to private structure.
3288  */
3289 static void
3290 priv_rx_intr_vec_disable(struct priv *priv)
3291 {
3292         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
3293
3294         rte_intr_free_epoll_fd(intr_handle);
3295         free(intr_handle->intr_vec);
3296         intr_handle->nb_efd = 0;
3297         intr_handle->intr_vec = NULL;
3298 }
3299
3300 /**
3301  * DPDK callback for Rx queue interrupt enable.
3302  *
3303  * @param dev
3304  *   Pointer to Ethernet device structure.
3305  * @param idx
3306  *   Rx queue index.
3307  *
3308  * @return
3309  *   0 on success, negative on failure.
3310  */
3311 static int
3312 mlx4_rx_intr_enable(struct rte_eth_dev *dev, uint16_t idx)
3313 {
3314         struct priv *priv = dev->data->dev_private;
3315         struct rxq *rxq = (*priv->rxqs)[idx];
3316         int ret;
3317
3318         if (!rxq || !rxq->channel)
3319                 ret = EINVAL;
3320         else
3321                 ret = ibv_req_notify_cq(rxq->cq, 0);
3322         if (ret)
3323                 WARN("unable to arm interrupt on rx queue %d", idx);
3324         return -ret;
3325 }
3326
3327 /**
3328  * DPDK callback for Rx queue interrupt disable.
3329  *
3330  * @param dev
3331  *   Pointer to Ethernet device structure.
3332  * @param idx
3333  *   Rx queue index.
3334  *
3335  * @return
3336  *   0 on success, negative on failure.
3337  */
3338 static int
3339 mlx4_rx_intr_disable(struct rte_eth_dev *dev, uint16_t idx)
3340 {
3341         struct priv *priv = dev->data->dev_private;
3342         struct rxq *rxq = (*priv->rxqs)[idx];
3343         struct ibv_cq *ev_cq;
3344         void *ev_ctx;
3345         int ret;
3346
3347         if (!rxq || !rxq->channel) {
3348                 ret = EINVAL;
3349         } else {
3350                 ret = ibv_get_cq_event(rxq->cq->channel, &ev_cq, &ev_ctx);
3351                 if (ret || ev_cq != rxq->cq)
3352                         ret = EINVAL;
3353         }
3354         if (ret)
3355                 WARN("unable to disable interrupt on rx queue %d",
3356                      idx);
3357         else
3358                 ibv_ack_cq_events(rxq->cq, 1);
3359         return -ret;
3360 }
3361
3362 /**
3363  * Verify and store value for device argument.
3364  *
3365  * @param[in] key
3366  *   Key argument to verify.
3367  * @param[in] val
3368  *   Value associated with key.
3369  * @param[in, out] conf
3370  *   Shared configuration data.
3371  *
3372  * @return
3373  *   0 on success, negative errno value on failure.
3374  */
3375 static int
3376 mlx4_arg_parse(const char *key, const char *val, struct mlx4_conf *conf)
3377 {
3378         unsigned long tmp;
3379
3380         errno = 0;
3381         tmp = strtoul(val, NULL, 0);
3382         if (errno) {
3383                 WARN("%s: \"%s\" is not a valid integer", key, val);
3384                 return -errno;
3385         }
3386         if (strcmp(MLX4_PMD_PORT_KVARG, key) == 0) {
3387                 uint32_t ports = rte_log2_u32(conf->ports.present);
3388
3389                 if (tmp >= ports) {
3390                         ERROR("port index %lu outside range [0,%" PRIu32 ")",
3391                               tmp, ports);
3392                         return -EINVAL;
3393                 }
3394                 if (!(conf->ports.present & (1 << tmp))) {
3395                         ERROR("invalid port index %lu", tmp);
3396                         return -EINVAL;
3397                 }
3398                 conf->ports.enabled |= 1 << tmp;
3399         } else {
3400                 WARN("%s: unknown parameter", key);
3401                 return -EINVAL;
3402         }
3403         return 0;
3404 }
3405
3406 /**
3407  * Parse device parameters.
3408  *
3409  * @param devargs
3410  *   Device arguments structure.
3411  *
3412  * @return
3413  *   0 on success, negative errno value on failure.
3414  */
3415 static int
3416 mlx4_args(struct rte_devargs *devargs, struct mlx4_conf *conf)
3417 {
3418         struct rte_kvargs *kvlist;
3419         unsigned int arg_count;
3420         int ret = 0;
3421         int i;
3422
3423         if (devargs == NULL)
3424                 return 0;
3425         kvlist = rte_kvargs_parse(devargs->args, pmd_mlx4_init_params);
3426         if (kvlist == NULL) {
3427                 ERROR("failed to parse kvargs");
3428                 return -EINVAL;
3429         }
3430         /* Process parameters. */
3431         for (i = 0; pmd_mlx4_init_params[i]; ++i) {
3432                 arg_count = rte_kvargs_count(kvlist, MLX4_PMD_PORT_KVARG);
3433                 while (arg_count-- > 0) {
3434                         ret = rte_kvargs_process(kvlist,
3435                                                  MLX4_PMD_PORT_KVARG,
3436                                                  (int (*)(const char *,
3437                                                           const char *,
3438                                                           void *))
3439                                                  mlx4_arg_parse,
3440                                                  conf);
3441                         if (ret != 0)
3442                                 goto free_kvlist;
3443                 }
3444         }
3445 free_kvlist:
3446         rte_kvargs_free(kvlist);
3447         return ret;
3448 }
3449
3450 static struct rte_pci_driver mlx4_driver;
3451
3452 /**
3453  * DPDK callback to register a PCI device.
3454  *
3455  * This function creates an Ethernet device for each port of a given
3456  * PCI device.
3457  *
3458  * @param[in] pci_drv
3459  *   PCI driver structure (mlx4_driver).
3460  * @param[in] pci_dev
3461  *   PCI device information.
3462  *
3463  * @return
3464  *   0 on success, negative errno value on failure.
3465  */
3466 static int
3467 mlx4_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
3468 {
3469         struct ibv_device **list;
3470         struct ibv_device *ibv_dev;
3471         int err = 0;
3472         struct ibv_context *attr_ctx = NULL;
3473         struct ibv_device_attr device_attr;
3474         struct mlx4_conf conf = {
3475                 .ports.present = 0,
3476         };
3477         unsigned int vf;
3478         int i;
3479
3480         (void)pci_drv;
3481         assert(pci_drv == &mlx4_driver);
3482
3483         list = ibv_get_device_list(&i);
3484         if (list == NULL) {
3485                 assert(errno);
3486                 if (errno == ENOSYS)
3487                         ERROR("cannot list devices, is ib_uverbs loaded?");
3488                 return -errno;
3489         }
3490         assert(i >= 0);
3491         /*
3492          * For each listed device, check related sysfs entry against
3493          * the provided PCI ID.
3494          */
3495         while (i != 0) {
3496                 struct rte_pci_addr pci_addr;
3497
3498                 --i;
3499                 DEBUG("checking device \"%s\"", list[i]->name);
3500                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
3501                         continue;
3502                 if ((pci_dev->addr.domain != pci_addr.domain) ||
3503                     (pci_dev->addr.bus != pci_addr.bus) ||
3504                     (pci_dev->addr.devid != pci_addr.devid) ||
3505                     (pci_dev->addr.function != pci_addr.function))
3506                         continue;
3507                 vf = (pci_dev->id.device_id ==
3508                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
3509                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
3510                      list[i]->name, (vf ? "true" : "false"));
3511                 attr_ctx = ibv_open_device(list[i]);
3512                 err = errno;
3513                 break;
3514         }
3515         if (attr_ctx == NULL) {
3516                 ibv_free_device_list(list);
3517                 switch (err) {
3518                 case 0:
3519                         ERROR("cannot access device, is mlx4_ib loaded?");
3520                         return -ENODEV;
3521                 case EINVAL:
3522                         ERROR("cannot use device, are drivers up to date?");
3523                         return -EINVAL;
3524                 }
3525                 assert(err > 0);
3526                 return -err;
3527         }
3528         ibv_dev = list[i];
3529
3530         DEBUG("device opened");
3531         if (ibv_query_device(attr_ctx, &device_attr)) {
3532                 err = ENODEV;
3533                 goto error;
3534         }
3535         INFO("%u port(s) detected", device_attr.phys_port_cnt);
3536
3537         conf.ports.present |= (UINT64_C(1) << device_attr.phys_port_cnt) - 1;
3538         if (mlx4_args(pci_dev->device.devargs, &conf)) {
3539                 ERROR("failed to process device arguments");
3540                 err = EINVAL;
3541                 goto error;
3542         }
3543         /* Use all ports when none are defined */
3544         if (!conf.ports.enabled)
3545                 conf.ports.enabled = conf.ports.present;
3546         for (i = 0; i < device_attr.phys_port_cnt; i++) {
3547                 uint32_t port = i + 1; /* ports are indexed from one */
3548                 struct ibv_context *ctx = NULL;
3549                 struct ibv_port_attr port_attr;
3550                 struct ibv_pd *pd = NULL;
3551                 struct priv *priv = NULL;
3552                 struct rte_eth_dev *eth_dev = NULL;
3553                 struct ether_addr mac;
3554
3555                 /* If port is not enabled, skip. */
3556                 if (!(conf.ports.enabled & (1 << i)))
3557                         continue;
3558
3559                 DEBUG("using port %u", port);
3560
3561                 ctx = ibv_open_device(ibv_dev);
3562                 if (ctx == NULL) {
3563                         err = ENODEV;
3564                         goto port_error;
3565                 }
3566
3567                 /* Check port status. */
3568                 err = ibv_query_port(ctx, port, &port_attr);
3569                 if (err) {
3570                         ERROR("port query failed: %s", strerror(err));
3571                         err = ENODEV;
3572                         goto port_error;
3573                 }
3574
3575                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
3576                         ERROR("port %d is not configured in Ethernet mode",
3577                               port);
3578                         err = EINVAL;
3579                         goto port_error;
3580                 }
3581
3582                 if (port_attr.state != IBV_PORT_ACTIVE)
3583                         DEBUG("port %d is not active: \"%s\" (%d)",
3584                               port, ibv_port_state_str(port_attr.state),
3585                               port_attr.state);
3586
3587                 /* Allocate protection domain. */
3588                 pd = ibv_alloc_pd(ctx);
3589                 if (pd == NULL) {
3590                         ERROR("PD allocation failure");
3591                         err = ENOMEM;
3592                         goto port_error;
3593                 }
3594
3595                 /* from rte_ethdev.c */
3596                 priv = rte_zmalloc("ethdev private structure",
3597                                    sizeof(*priv),
3598                                    RTE_CACHE_LINE_SIZE);
3599                 if (priv == NULL) {
3600                         ERROR("priv allocation failure");
3601                         err = ENOMEM;
3602                         goto port_error;
3603                 }
3604
3605                 priv->ctx = ctx;
3606                 priv->device_attr = device_attr;
3607                 priv->port = port;
3608                 priv->pd = pd;
3609                 priv->mtu = ETHER_MTU;
3610
3611                 priv->vf = vf;
3612                 /* Configure the first MAC address by default. */
3613                 if (priv_get_mac(priv, &mac.addr_bytes)) {
3614                         ERROR("cannot get MAC address, is mlx4_en loaded?"
3615                               " (errno: %s)", strerror(errno));
3616                         err = ENODEV;
3617                         goto port_error;
3618                 }
3619                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
3620                      priv->port,
3621                      mac.addr_bytes[0], mac.addr_bytes[1],
3622                      mac.addr_bytes[2], mac.addr_bytes[3],
3623                      mac.addr_bytes[4], mac.addr_bytes[5]);
3624                 /* Register MAC address. */
3625                 priv->mac = mac;
3626                 if (priv_mac_addr_add(priv))
3627                         goto port_error;
3628 #ifndef NDEBUG
3629                 {
3630                         char ifname[IF_NAMESIZE];
3631
3632                         if (priv_get_ifname(priv, &ifname) == 0)
3633                                 DEBUG("port %u ifname is \"%s\"",
3634                                       priv->port, ifname);
3635                         else
3636                                 DEBUG("port %u ifname is unknown", priv->port);
3637                 }
3638 #endif
3639                 /* Get actual MTU if possible. */
3640                 priv_get_mtu(priv, &priv->mtu);
3641                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
3642
3643                 /* from rte_ethdev.c */
3644                 {
3645                         char name[RTE_ETH_NAME_MAX_LEN];
3646
3647                         snprintf(name, sizeof(name), "%s port %u",
3648                                  ibv_get_device_name(ibv_dev), port);
3649                         eth_dev = rte_eth_dev_allocate(name);
3650                 }
3651                 if (eth_dev == NULL) {
3652                         ERROR("can not allocate rte ethdev");
3653                         err = ENOMEM;
3654                         goto port_error;
3655                 }
3656
3657                 eth_dev->data->dev_private = priv;
3658                 eth_dev->data->mac_addrs = &priv->mac;
3659                 eth_dev->device = &pci_dev->device;
3660
3661                 rte_eth_copy_pci_info(eth_dev, pci_dev);
3662
3663                 eth_dev->device->driver = &mlx4_driver.driver;
3664
3665                 /*
3666                  * Copy and override interrupt handle to prevent it from
3667                  * being shared between all ethdev instances of a given PCI
3668                  * device. This is required to properly handle Rx interrupts
3669                  * on all ports.
3670                  */
3671                 priv->intr_handle_dev = *eth_dev->intr_handle;
3672                 eth_dev->intr_handle = &priv->intr_handle_dev;
3673
3674                 priv->dev = eth_dev;
3675                 eth_dev->dev_ops = &mlx4_dev_ops;
3676                 eth_dev->data->dev_flags |= RTE_ETH_DEV_DETACHABLE;
3677
3678                 /* Bring Ethernet device up. */
3679                 DEBUG("forcing Ethernet interface up");
3680                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
3681                 /* Update link status once if waiting for LSC. */
3682                 if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
3683                         mlx4_link_update(eth_dev, 0);
3684                 continue;
3685
3686 port_error:
3687                 rte_free(priv);
3688                 if (pd)
3689                         claim_zero(ibv_dealloc_pd(pd));
3690                 if (ctx)
3691                         claim_zero(ibv_close_device(ctx));
3692                 if (eth_dev)
3693                         rte_eth_dev_release_port(eth_dev);
3694                 break;
3695         }
3696         if (i == device_attr.phys_port_cnt)
3697                 return 0;
3698
3699         /*
3700          * XXX if something went wrong in the loop above, there is a resource
3701          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
3702          * long as the dpdk does not provide a way to deallocate a ethdev and a
3703          * way to enumerate the registered ethdevs to free the previous ones.
3704          */
3705
3706 error:
3707         if (attr_ctx)
3708                 claim_zero(ibv_close_device(attr_ctx));
3709         if (list)
3710                 ibv_free_device_list(list);
3711         assert(err >= 0);
3712         return -err;
3713 }
3714
3715 static const struct rte_pci_id mlx4_pci_id_map[] = {
3716         {
3717                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3718                                PCI_DEVICE_ID_MELLANOX_CONNECTX3)
3719         },
3720         {
3721                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3722                                PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO)
3723         },
3724         {
3725                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3726                                PCI_DEVICE_ID_MELLANOX_CONNECTX3VF)
3727         },
3728         {
3729                 .vendor_id = 0
3730         }
3731 };
3732
3733 static struct rte_pci_driver mlx4_driver = {
3734         .driver = {
3735                 .name = MLX4_DRIVER_NAME
3736         },
3737         .id_table = mlx4_pci_id_map,
3738         .probe = mlx4_pci_probe,
3739         .drv_flags = RTE_PCI_DRV_INTR_LSC |
3740                      RTE_PCI_DRV_INTR_RMV,
3741 };
3742
3743 /**
3744  * Driver initialization routine.
3745  */
3746 RTE_INIT(rte_mlx4_pmd_init);
3747 static void
3748 rte_mlx4_pmd_init(void)
3749 {
3750         RTE_BUILD_BUG_ON(sizeof(wr_id_t) != sizeof(uint64_t));
3751         /*
3752          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
3753          * huge pages. Calling ibv_fork_init() during init allows
3754          * applications to use fork() safely for purposes other than
3755          * using this PMD, which is not supported in forked processes.
3756          */
3757         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
3758         ibv_fork_init();
3759         rte_pci_register(&mlx4_driver);
3760 }
3761
3762 RTE_PMD_EXPORT_NAME(net_mlx4, __COUNTER__);
3763 RTE_PMD_REGISTER_PCI_TABLE(net_mlx4, mlx4_pci_id_map);
3764 RTE_PMD_REGISTER_KMOD_DEP(net_mlx4,
3765         "* ib_uverbs & mlx4_en & mlx4_core & mlx4_ib");