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