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