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