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