80b0e3b7ecc96d0790b6f7fc54f376fa7c766158
[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         /*
612          * Request send completion every MLX4_PMD_TX_PER_COMP_REQ packets or
613          * at least 4 times per ring.
614          */
615         txq->elts_comp_cd_init =
616                 ((MLX4_PMD_TX_PER_COMP_REQ < (elts_n / 4)) ?
617                  MLX4_PMD_TX_PER_COMP_REQ : (elts_n / 4));
618         txq->elts_comp_cd = txq->elts_comp_cd_init;
619         assert(ret == 0);
620         return 0;
621 error:
622         rte_free(elts);
623         DEBUG("%p: failed, freed everything", (void *)txq);
624         assert(ret > 0);
625         rte_errno = ret;
626         return -rte_errno;
627 }
628
629 /**
630  * Free TX queue elements.
631  *
632  * @param txq
633  *   Pointer to TX queue structure.
634  */
635 static void
636 txq_free_elts(struct txq *txq)
637 {
638         unsigned int elts_n = txq->elts_n;
639         unsigned int elts_head = txq->elts_head;
640         unsigned int elts_tail = txq->elts_tail;
641         struct txq_elt (*elts)[elts_n] = txq->elts;
642
643         DEBUG("%p: freeing WRs", (void *)txq);
644         txq->elts_n = 0;
645         txq->elts_head = 0;
646         txq->elts_tail = 0;
647         txq->elts_comp = 0;
648         txq->elts_comp_cd = 0;
649         txq->elts_comp_cd_init = 0;
650         txq->elts = NULL;
651         if (elts == NULL)
652                 return;
653         while (elts_tail != elts_head) {
654                 struct txq_elt *elt = &(*elts)[elts_tail];
655
656                 assert(elt->buf != NULL);
657                 rte_pktmbuf_free(elt->buf);
658 #ifndef NDEBUG
659                 /* Poisoning. */
660                 memset(elt, 0x77, sizeof(*elt));
661 #endif
662                 if (++elts_tail == elts_n)
663                         elts_tail = 0;
664         }
665         rte_free(elts);
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         /* It already failed, skip the next chunks. */
759         if (data->ret != 0)
760                 return;
761         /* It is the first chunk. */
762         if (data->start == NULL && data->end == NULL) {
763                 data->start = memhdr->addr;
764                 data->end = data->start + memhdr->len;
765                 return;
766         }
767         if (data->end == memhdr->addr) {
768                 data->end += memhdr->len;
769                 return;
770         }
771         if (data->start == (char *)memhdr->addr + memhdr->len) {
772                 data->start -= memhdr->len;
773                 return;
774         }
775         /* Error, mempool is not virtually contigous. */
776         data->ret = -1;
777 }
778
779 /**
780  * Check if a mempool can be used: it must be virtually contiguous.
781  *
782  * @param[in] mp
783  *   Pointer to memory pool.
784  * @param[out] start
785  *   Pointer to the start address of the mempool virtual memory area
786  * @param[out] end
787  *   Pointer to the end address of the mempool virtual memory area
788  *
789  * @return
790  *   0 on success (mempool is virtually contiguous), -1 on error.
791  */
792 static int mlx4_check_mempool(struct rte_mempool *mp, uintptr_t *start,
793         uintptr_t *end)
794 {
795         struct mlx4_check_mempool_data data;
796
797         memset(&data, 0, sizeof(data));
798         rte_mempool_mem_iter(mp, mlx4_check_mempool_cb, &data);
799         *start = (uintptr_t)data.start;
800         *end = (uintptr_t)data.end;
801         return data.ret;
802 }
803
804 /* For best performance, this function should not be inlined. */
805 static struct ibv_mr *mlx4_mp2mr(struct ibv_pd *, struct rte_mempool *)
806         __rte_noinline;
807
808 /**
809  * Register mempool as a memory region.
810  *
811  * @param pd
812  *   Pointer to protection domain.
813  * @param mp
814  *   Pointer to memory pool.
815  *
816  * @return
817  *   Memory region pointer, NULL in case of error and rte_errno is set.
818  */
819 static struct ibv_mr *
820 mlx4_mp2mr(struct ibv_pd *pd, struct rte_mempool *mp)
821 {
822         const struct rte_memseg *ms = rte_eal_get_physmem_layout();
823         uintptr_t start;
824         uintptr_t end;
825         unsigned int i;
826         struct ibv_mr *mr;
827
828         if (mlx4_check_mempool(mp, &start, &end) != 0) {
829                 rte_errno = EINVAL;
830                 ERROR("mempool %p: not virtually contiguous",
831                         (void *)mp);
832                 return NULL;
833         }
834         DEBUG("mempool %p area start=%p end=%p size=%zu",
835               (void *)mp, (void *)start, (void *)end,
836               (size_t)(end - start));
837         /* Round start and end to page boundary if found in memory segments. */
838         for (i = 0; (i < RTE_MAX_MEMSEG) && (ms[i].addr != NULL); ++i) {
839                 uintptr_t addr = (uintptr_t)ms[i].addr;
840                 size_t len = ms[i].len;
841                 unsigned int align = ms[i].hugepage_sz;
842
843                 if ((start > addr) && (start < addr + len))
844                         start = RTE_ALIGN_FLOOR(start, align);
845                 if ((end > addr) && (end < addr + len))
846                         end = RTE_ALIGN_CEIL(end, align);
847         }
848         DEBUG("mempool %p using start=%p end=%p size=%zu for MR",
849               (void *)mp, (void *)start, (void *)end,
850               (size_t)(end - start));
851         mr = ibv_reg_mr(pd,
852                         (void *)start,
853                         end - start,
854                         IBV_ACCESS_LOCAL_WRITE);
855         if (!mr)
856                 rte_errno = errno ? errno : EINVAL;
857         return mr;
858 }
859
860 /**
861  * Get Memory Pool (MP) from mbuf. If mbuf is indirect, the pool from which
862  * the cloned mbuf is allocated is returned instead.
863  *
864  * @param buf
865  *   Pointer to mbuf.
866  *
867  * @return
868  *   Memory pool where data is located for given mbuf.
869  */
870 static struct rte_mempool *
871 txq_mb2mp(struct rte_mbuf *buf)
872 {
873         if (unlikely(RTE_MBUF_INDIRECT(buf)))
874                 return rte_mbuf_from_indirect(buf)->pool;
875         return buf->pool;
876 }
877
878 /**
879  * Get Memory Region (MR) <-> Memory Pool (MP) association from txq->mp2mr[].
880  * Add MP to txq->mp2mr[] if it's not registered yet. If mp2mr[] is full,
881  * remove an entry first.
882  *
883  * @param txq
884  *   Pointer to TX queue structure.
885  * @param[in] mp
886  *   Memory Pool for which a Memory Region lkey must be returned.
887  *
888  * @return
889  *   mr->lkey on success, (uint32_t)-1 on failure.
890  */
891 static uint32_t
892 txq_mp2mr(struct txq *txq, struct rte_mempool *mp)
893 {
894         unsigned int i;
895         struct ibv_mr *mr;
896
897         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
898                 if (unlikely(txq->mp2mr[i].mp == NULL)) {
899                         /* Unknown MP, add a new MR for it. */
900                         break;
901                 }
902                 if (txq->mp2mr[i].mp == mp) {
903                         assert(txq->mp2mr[i].lkey != (uint32_t)-1);
904                         assert(txq->mp2mr[i].mr->lkey == txq->mp2mr[i].lkey);
905                         return txq->mp2mr[i].lkey;
906                 }
907         }
908         /* Add a new entry, register MR first. */
909         DEBUG("%p: discovered new memory pool \"%s\" (%p)",
910               (void *)txq, mp->name, (void *)mp);
911         mr = mlx4_mp2mr(txq->priv->pd, mp);
912         if (unlikely(mr == NULL)) {
913                 DEBUG("%p: unable to configure MR, ibv_reg_mr() failed.",
914                       (void *)txq);
915                 return (uint32_t)-1;
916         }
917         if (unlikely(i == elemof(txq->mp2mr))) {
918                 /* Table is full, remove oldest entry. */
919                 DEBUG("%p: MR <-> MP table full, dropping oldest entry.",
920                       (void *)txq);
921                 --i;
922                 claim_zero(ibv_dereg_mr(txq->mp2mr[0].mr));
923                 memmove(&txq->mp2mr[0], &txq->mp2mr[1],
924                         (sizeof(txq->mp2mr) - sizeof(txq->mp2mr[0])));
925         }
926         /* Store the new entry. */
927         txq->mp2mr[i].mp = mp;
928         txq->mp2mr[i].mr = mr;
929         txq->mp2mr[i].lkey = mr->lkey;
930         DEBUG("%p: new MR lkey for MP \"%s\" (%p): 0x%08" PRIu32,
931               (void *)txq, mp->name, (void *)mp, txq->mp2mr[i].lkey);
932         return txq->mp2mr[i].lkey;
933 }
934
935 struct txq_mp2mr_mbuf_check_data {
936         int ret;
937 };
938
939 /**
940  * Callback function for rte_mempool_obj_iter() to check whether a given
941  * mempool object looks like a mbuf.
942  *
943  * @param[in] mp
944  *   The mempool pointer
945  * @param[in] arg
946  *   Context data (struct txq_mp2mr_mbuf_check_data). Contains the
947  *   return value.
948  * @param[in] obj
949  *   Object address.
950  * @param index
951  *   Object index, unused.
952  */
953 static void
954 txq_mp2mr_mbuf_check(struct rte_mempool *mp, void *arg, void *obj,
955         uint32_t index __rte_unused)
956 {
957         struct txq_mp2mr_mbuf_check_data *data = arg;
958         struct rte_mbuf *buf = obj;
959
960         /*
961          * Check whether mbuf structure fits element size and whether mempool
962          * pointer is valid.
963          */
964         if (sizeof(*buf) > mp->elt_size || buf->pool != mp)
965                 data->ret = -1;
966 }
967
968 /**
969  * Iterator function for rte_mempool_walk() to register existing mempools and
970  * fill the MP to MR cache of a TX queue.
971  *
972  * @param[in] mp
973  *   Memory Pool to register.
974  * @param *arg
975  *   Pointer to TX queue structure.
976  */
977 static void
978 txq_mp2mr_iter(struct rte_mempool *mp, void *arg)
979 {
980         struct txq *txq = arg;
981         struct txq_mp2mr_mbuf_check_data data = {
982                 .ret = 0,
983         };
984
985         /* Register mempool only if the first element looks like a mbuf. */
986         if (rte_mempool_obj_iter(mp, txq_mp2mr_mbuf_check, &data) == 0 ||
987                         data.ret == -1)
988                 return;
989         txq_mp2mr(txq, mp);
990 }
991
992 /**
993  * DPDK callback for TX.
994  *
995  * @param dpdk_txq
996  *   Generic pointer to TX queue structure.
997  * @param[in] pkts
998  *   Packets to transmit.
999  * @param pkts_n
1000  *   Number of packets in array.
1001  *
1002  * @return
1003  *   Number of packets successfully transmitted (<= pkts_n).
1004  */
1005 static uint16_t
1006 mlx4_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
1007 {
1008         struct txq *txq = (struct txq *)dpdk_txq;
1009         struct ibv_send_wr *wr_head = NULL;
1010         struct ibv_send_wr **wr_next = &wr_head;
1011         struct ibv_send_wr *wr_bad = NULL;
1012         unsigned int elts_head = txq->elts_head;
1013         const unsigned int elts_n = txq->elts_n;
1014         unsigned int elts_comp_cd = txq->elts_comp_cd;
1015         unsigned int elts_comp = 0;
1016         unsigned int i;
1017         unsigned int max;
1018         int err;
1019
1020         assert(elts_comp_cd != 0);
1021         txq_complete(txq);
1022         max = (elts_n - (elts_head - txq->elts_tail));
1023         if (max > elts_n)
1024                 max -= elts_n;
1025         assert(max >= 1);
1026         assert(max <= elts_n);
1027         /* Always leave one free entry in the ring. */
1028         --max;
1029         if (max == 0)
1030                 return 0;
1031         if (max > pkts_n)
1032                 max = pkts_n;
1033         for (i = 0; (i != max); ++i) {
1034                 struct rte_mbuf *buf = pkts[i];
1035                 unsigned int elts_head_next =
1036                         (((elts_head + 1) == elts_n) ? 0 : elts_head + 1);
1037                 struct txq_elt *elt_next = &(*txq->elts)[elts_head_next];
1038                 struct txq_elt *elt = &(*txq->elts)[elts_head];
1039                 struct ibv_send_wr *wr = &elt->wr;
1040                 unsigned int segs = NB_SEGS(buf);
1041                 unsigned int sent_size = 0;
1042                 uint32_t send_flags = 0;
1043
1044                 /* Clean up old buffer. */
1045                 if (likely(elt->buf != NULL)) {
1046                         struct rte_mbuf *tmp = elt->buf;
1047
1048 #ifndef NDEBUG
1049                         /* Poisoning. */
1050                         memset(elt, 0x66, sizeof(*elt));
1051 #endif
1052                         /* Faster than rte_pktmbuf_free(). */
1053                         do {
1054                                 struct rte_mbuf *next = NEXT(tmp);
1055
1056                                 rte_pktmbuf_free_seg(tmp);
1057                                 tmp = next;
1058                         } while (tmp != NULL);
1059                 }
1060                 /* Request TX completion. */
1061                 if (unlikely(--elts_comp_cd == 0)) {
1062                         elts_comp_cd = txq->elts_comp_cd_init;
1063                         ++elts_comp;
1064                         send_flags |= IBV_SEND_SIGNALED;
1065                 }
1066                 if (likely(segs == 1)) {
1067                         struct ibv_sge *sge = &elt->sge;
1068                         uintptr_t addr;
1069                         uint32_t length;
1070                         uint32_t lkey;
1071
1072                         /* Retrieve buffer information. */
1073                         addr = rte_pktmbuf_mtod(buf, uintptr_t);
1074                         length = DATA_LEN(buf);
1075                         /* Retrieve Memory Region key for this memory pool. */
1076                         lkey = txq_mp2mr(txq, txq_mb2mp(buf));
1077                         if (unlikely(lkey == (uint32_t)-1)) {
1078                                 /* MR does not exist. */
1079                                 DEBUG("%p: unable to get MP <-> MR"
1080                                       " association", (void *)txq);
1081                                 /* Clean up TX element. */
1082                                 elt->buf = NULL;
1083                                 goto stop;
1084                         }
1085                         /* Update element. */
1086                         elt->buf = buf;
1087                         if (txq->priv->vf)
1088                                 rte_prefetch0((volatile void *)
1089                                               (uintptr_t)addr);
1090                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1091                         sge->addr = addr;
1092                         sge->length = length;
1093                         sge->lkey = lkey;
1094                         sent_size += length;
1095                 } else {
1096                         err = -1;
1097                         goto stop;
1098                 }
1099                 if (sent_size <= txq->max_inline)
1100                         send_flags |= IBV_SEND_INLINE;
1101                 elts_head = elts_head_next;
1102                 /* Increment sent bytes counter. */
1103                 txq->stats.obytes += sent_size;
1104                 /* Set up WR. */
1105                 wr->sg_list = &elt->sge;
1106                 wr->num_sge = segs;
1107                 wr->opcode = IBV_WR_SEND;
1108                 wr->send_flags = send_flags;
1109                 *wr_next = wr;
1110                 wr_next = &wr->next;
1111         }
1112 stop:
1113         /* Take a shortcut if nothing must be sent. */
1114         if (unlikely(i == 0))
1115                 return 0;
1116         /* Increment sent packets counter. */
1117         txq->stats.opackets += i;
1118         /* Ring QP doorbell. */
1119         *wr_next = NULL;
1120         assert(wr_head);
1121         err = ibv_post_send(txq->qp, wr_head, &wr_bad);
1122         if (unlikely(err)) {
1123                 uint64_t obytes = 0;
1124                 uint64_t opackets = 0;
1125
1126                 /* Rewind bad WRs. */
1127                 while (wr_bad != NULL) {
1128                         int j;
1129
1130                         /* Force completion request if one was lost. */
1131                         if (wr_bad->send_flags & IBV_SEND_SIGNALED) {
1132                                 elts_comp_cd = 1;
1133                                 --elts_comp;
1134                         }
1135                         ++opackets;
1136                         for (j = 0; j < wr_bad->num_sge; ++j)
1137                                 obytes += wr_bad->sg_list[j].length;
1138                         elts_head = (elts_head ? elts_head : elts_n) - 1;
1139                         wr_bad = wr_bad->next;
1140                 }
1141                 txq->stats.opackets -= opackets;
1142                 txq->stats.obytes -= obytes;
1143                 i -= opackets;
1144                 DEBUG("%p: ibv_post_send() failed, %" PRIu64 " packets"
1145                       " (%" PRIu64 " bytes) rejected: %s",
1146                       (void *)txq,
1147                       opackets,
1148                       obytes,
1149                       (err <= -1) ? "Internal error" : strerror(err));
1150         }
1151         txq->elts_head = elts_head;
1152         txq->elts_comp += elts_comp;
1153         txq->elts_comp_cd = elts_comp_cd;
1154         return i;
1155 }
1156
1157 /**
1158  * Configure a TX queue.
1159  *
1160  * @param dev
1161  *   Pointer to Ethernet device structure.
1162  * @param txq
1163  *   Pointer to TX queue structure.
1164  * @param desc
1165  *   Number of descriptors to configure in queue.
1166  * @param socket
1167  *   NUMA socket on which memory must be allocated.
1168  * @param[in] conf
1169  *   Thresholds parameters.
1170  *
1171  * @return
1172  *   0 on success, negative errno value otherwise and rte_errno is set.
1173  */
1174 static int
1175 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
1176           unsigned int socket, const struct rte_eth_txconf *conf)
1177 {
1178         struct priv *priv = dev->data->dev_private;
1179         struct txq tmpl = {
1180                 .priv = priv,
1181                 .socket = socket
1182         };
1183         union {
1184                 struct ibv_qp_init_attr init;
1185                 struct ibv_qp_attr mod;
1186         } attr;
1187         int ret;
1188
1189         (void)conf; /* Thresholds configuration (ignored). */
1190         if (priv == NULL) {
1191                 rte_errno = EINVAL;
1192                 goto error;
1193         }
1194         if (desc == 0) {
1195                 rte_errno = EINVAL;
1196                 ERROR("%p: invalid number of Tx descriptors", (void *)dev);
1197                 goto error;
1198         }
1199         /* MRs will be registered in mp2mr[] later. */
1200         tmpl.cq = ibv_create_cq(priv->ctx, desc, NULL, NULL, 0);
1201         if (tmpl.cq == NULL) {
1202                 rte_errno = ENOMEM;
1203                 ERROR("%p: CQ creation failure: %s",
1204                       (void *)dev, strerror(rte_errno));
1205                 goto error;
1206         }
1207         DEBUG("priv->device_attr.max_qp_wr is %d",
1208               priv->device_attr.max_qp_wr);
1209         DEBUG("priv->device_attr.max_sge is %d",
1210               priv->device_attr.max_sge);
1211         attr.init = (struct ibv_qp_init_attr){
1212                 /* CQ to be associated with the send queue. */
1213                 .send_cq = tmpl.cq,
1214                 /* CQ to be associated with the receive queue. */
1215                 .recv_cq = tmpl.cq,
1216                 .cap = {
1217                         /* Max number of outstanding WRs. */
1218                         .max_send_wr = ((priv->device_attr.max_qp_wr < desc) ?
1219                                         priv->device_attr.max_qp_wr :
1220                                         desc),
1221                         /* Max number of scatter/gather elements in a WR. */
1222                         .max_send_sge = 1,
1223                         .max_inline_data = MLX4_PMD_MAX_INLINE,
1224                 },
1225                 .qp_type = IBV_QPT_RAW_PACKET,
1226                 /*
1227                  * Do *NOT* enable this, completions events are managed per
1228                  * Tx burst.
1229                  */
1230                 .sq_sig_all = 0,
1231         };
1232         tmpl.qp = ibv_create_qp(priv->pd, &attr.init);
1233         if (tmpl.qp == NULL) {
1234                 rte_errno = errno ? errno : EINVAL;
1235                 ERROR("%p: QP creation failure: %s",
1236                       (void *)dev, strerror(rte_errno));
1237                 goto error;
1238         }
1239         /* ibv_create_qp() updates this value. */
1240         tmpl.max_inline = attr.init.cap.max_inline_data;
1241         attr.mod = (struct ibv_qp_attr){
1242                 /* Move the QP to this state. */
1243                 .qp_state = IBV_QPS_INIT,
1244                 /* Primary port number. */
1245                 .port_num = priv->port
1246         };
1247         ret = ibv_modify_qp(tmpl.qp, &attr.mod, IBV_QP_STATE | IBV_QP_PORT);
1248         if (ret) {
1249                 rte_errno = ret;
1250                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1251                       (void *)dev, strerror(rte_errno));
1252                 goto error;
1253         }
1254         ret = txq_alloc_elts(&tmpl, desc);
1255         if (ret) {
1256                 rte_errno = ret;
1257                 ERROR("%p: TXQ allocation failed: %s",
1258                       (void *)dev, strerror(rte_errno));
1259                 goto error;
1260         }
1261         attr.mod = (struct ibv_qp_attr){
1262                 .qp_state = IBV_QPS_RTR
1263         };
1264         ret = ibv_modify_qp(tmpl.qp, &attr.mod, IBV_QP_STATE);
1265         if (ret) {
1266                 rte_errno = ret;
1267                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1268                       (void *)dev, strerror(rte_errno));
1269                 goto error;
1270         }
1271         attr.mod.qp_state = IBV_QPS_RTS;
1272         ret = ibv_modify_qp(tmpl.qp, &attr.mod, IBV_QP_STATE);
1273         if (ret) {
1274                 rte_errno = ret;
1275                 ERROR("%p: QP state to IBV_QPS_RTS failed: %s",
1276                       (void *)dev, strerror(rte_errno));
1277                 goto error;
1278         }
1279         /* Clean up txq in case we're reinitializing it. */
1280         DEBUG("%p: cleaning-up old txq just in case", (void *)txq);
1281         txq_cleanup(txq);
1282         *txq = tmpl;
1283         DEBUG("%p: txq updated with %p", (void *)txq, (void *)&tmpl);
1284         /* Pre-register known mempools. */
1285         rte_mempool_walk(txq_mp2mr_iter, txq);
1286         return 0;
1287 error:
1288         ret = rte_errno;
1289         txq_cleanup(&tmpl);
1290         rte_errno = ret;
1291         assert(rte_errno > 0);
1292         return -rte_errno;
1293 }
1294
1295 /**
1296  * DPDK callback to configure a TX queue.
1297  *
1298  * @param dev
1299  *   Pointer to Ethernet device structure.
1300  * @param idx
1301  *   TX queue index.
1302  * @param desc
1303  *   Number of descriptors to configure in queue.
1304  * @param socket
1305  *   NUMA socket on which memory must be allocated.
1306  * @param[in] conf
1307  *   Thresholds parameters.
1308  *
1309  * @return
1310  *   0 on success, negative errno value otherwise and rte_errno is set.
1311  */
1312 static int
1313 mlx4_tx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1314                     unsigned int socket, const struct rte_eth_txconf *conf)
1315 {
1316         struct priv *priv = dev->data->dev_private;
1317         struct txq *txq = (*priv->txqs)[idx];
1318         int ret;
1319
1320         priv_lock(priv);
1321         DEBUG("%p: configuring queue %u for %u descriptors",
1322               (void *)dev, idx, desc);
1323         if (idx >= priv->txqs_n) {
1324                 rte_errno = EOVERFLOW;
1325                 ERROR("%p: queue index out of range (%u >= %u)",
1326                       (void *)dev, idx, priv->txqs_n);
1327                 priv_unlock(priv);
1328                 return -rte_errno;
1329         }
1330         if (txq != NULL) {
1331                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1332                       (void *)dev, idx, (void *)txq);
1333                 if (priv->started) {
1334                         rte_errno = EEXIST;
1335                         priv_unlock(priv);
1336                         return -rte_errno;
1337                 }
1338                 (*priv->txqs)[idx] = NULL;
1339                 txq_cleanup(txq);
1340         } else {
1341                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0, socket);
1342                 if (txq == NULL) {
1343                         rte_errno = ENOMEM;
1344                         ERROR("%p: unable to allocate queue index %u",
1345                               (void *)dev, idx);
1346                         priv_unlock(priv);
1347                         return -rte_errno;
1348                 }
1349         }
1350         ret = txq_setup(dev, txq, desc, socket, conf);
1351         if (ret)
1352                 rte_free(txq);
1353         else {
1354                 txq->stats.idx = idx;
1355                 DEBUG("%p: adding TX queue %p to list",
1356                       (void *)dev, (void *)txq);
1357                 (*priv->txqs)[idx] = txq;
1358                 /* Update send callback. */
1359                 dev->tx_pkt_burst = mlx4_tx_burst;
1360         }
1361         priv_unlock(priv);
1362         return ret;
1363 }
1364
1365 /**
1366  * DPDK callback to release a TX queue.
1367  *
1368  * @param dpdk_txq
1369  *   Generic TX queue pointer.
1370  */
1371 static void
1372 mlx4_tx_queue_release(void *dpdk_txq)
1373 {
1374         struct txq *txq = (struct txq *)dpdk_txq;
1375         struct priv *priv;
1376         unsigned int i;
1377
1378         if (txq == NULL)
1379                 return;
1380         priv = txq->priv;
1381         priv_lock(priv);
1382         for (i = 0; (i != priv->txqs_n); ++i)
1383                 if ((*priv->txqs)[i] == txq) {
1384                         DEBUG("%p: removing TX queue %p from list",
1385                               (void *)priv->dev, (void *)txq);
1386                         (*priv->txqs)[i] = NULL;
1387                         break;
1388                 }
1389         txq_cleanup(txq);
1390         rte_free(txq);
1391         priv_unlock(priv);
1392 }
1393
1394 /* RX queues handling. */
1395
1396 /**
1397  * Allocate RX queue elements.
1398  *
1399  * @param rxq
1400  *   Pointer to RX queue structure.
1401  * @param elts_n
1402  *   Number of elements to allocate.
1403  *
1404  * @return
1405  *   0 on success, negative errno value otherwise and rte_errno is set.
1406  */
1407 static int
1408 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n)
1409 {
1410         unsigned int i;
1411         struct rxq_elt (*elts)[elts_n] =
1412                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1413                                   rxq->socket);
1414
1415         if (elts == NULL) {
1416                 rte_errno = ENOMEM;
1417                 ERROR("%p: can't allocate packets array", (void *)rxq);
1418                 goto error;
1419         }
1420         /* For each WR (packet). */
1421         for (i = 0; (i != elts_n); ++i) {
1422                 struct rxq_elt *elt = &(*elts)[i];
1423                 struct ibv_recv_wr *wr = &elt->wr;
1424                 struct ibv_sge *sge = &(*elts)[i].sge;
1425                 struct rte_mbuf *buf = rte_pktmbuf_alloc(rxq->mp);
1426
1427                 if (buf == NULL) {
1428                         rte_errno = ENOMEM;
1429                         ERROR("%p: empty mbuf pool", (void *)rxq);
1430                         goto error;
1431                 }
1432                 elt->buf = buf;
1433                 wr->next = &(*elts)[(i + 1)].wr;
1434                 wr->sg_list = sge;
1435                 wr->num_sge = 1;
1436                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
1437                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1438                 /* Buffer is supposed to be empty. */
1439                 assert(rte_pktmbuf_data_len(buf) == 0);
1440                 assert(rte_pktmbuf_pkt_len(buf) == 0);
1441                 /* sge->addr must be able to store a pointer. */
1442                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1443                 /* SGE keeps its headroom. */
1444                 sge->addr = (uintptr_t)
1445                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
1446                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
1447                 sge->lkey = rxq->mr->lkey;
1448                 /* Redundant check for tailroom. */
1449                 assert(sge->length == rte_pktmbuf_tailroom(buf));
1450         }
1451         /* The last WR pointer must be NULL. */
1452         (*elts)[(i - 1)].wr.next = NULL;
1453         DEBUG("%p: allocated and configured %u single-segment WRs",
1454               (void *)rxq, elts_n);
1455         rxq->elts_n = elts_n;
1456         rxq->elts_head = 0;
1457         rxq->elts = elts;
1458         return 0;
1459 error:
1460         if (elts != NULL) {
1461                 for (i = 0; (i != elemof(*elts)); ++i)
1462                         rte_pktmbuf_free_seg((*elts)[i].buf);
1463                 rte_free(elts);
1464         }
1465         DEBUG("%p: failed, freed everything", (void *)rxq);
1466         assert(rte_errno > 0);
1467         return -rte_errno;
1468 }
1469
1470 /**
1471  * Free RX queue elements.
1472  *
1473  * @param rxq
1474  *   Pointer to RX queue structure.
1475  */
1476 static void
1477 rxq_free_elts(struct rxq *rxq)
1478 {
1479         unsigned int i;
1480         unsigned int elts_n = rxq->elts_n;
1481         struct rxq_elt (*elts)[elts_n] = rxq->elts;
1482
1483         DEBUG("%p: freeing WRs", (void *)rxq);
1484         rxq->elts_n = 0;
1485         rxq->elts = NULL;
1486         if (elts == NULL)
1487                 return;
1488         for (i = 0; (i != elemof(*elts)); ++i)
1489                 rte_pktmbuf_free_seg((*elts)[i].buf);
1490         rte_free(elts);
1491 }
1492
1493 /**
1494  * Unregister a MAC address.
1495  *
1496  * @param priv
1497  *   Pointer to private structure.
1498  */
1499 static void
1500 priv_mac_addr_del(struct priv *priv)
1501 {
1502 #ifndef NDEBUG
1503         uint8_t (*mac)[ETHER_ADDR_LEN] = &priv->mac.addr_bytes;
1504 #endif
1505
1506         if (!priv->mac_flow)
1507                 return;
1508         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x",
1509               (void *)priv,
1510               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);
1511         claim_zero(ibv_destroy_flow(priv->mac_flow));
1512         priv->mac_flow = NULL;
1513 }
1514
1515 /**
1516  * Register a MAC address.
1517  *
1518  * The MAC address is registered in queue 0.
1519  *
1520  * @param priv
1521  *   Pointer to private structure.
1522  *
1523  * @return
1524  *   0 on success, negative errno value otherwise and rte_errno is set.
1525  */
1526 static int
1527 priv_mac_addr_add(struct priv *priv)
1528 {
1529         uint8_t (*mac)[ETHER_ADDR_LEN] = &priv->mac.addr_bytes;
1530         struct rxq *rxq;
1531         struct ibv_flow *flow;
1532
1533         /* If device isn't started, this is all we need to do. */
1534         if (!priv->started)
1535                 return 0;
1536         if (priv->isolated)
1537                 return 0;
1538         if (*priv->rxqs && (*priv->rxqs)[0])
1539                 rxq = (*priv->rxqs)[0];
1540         else
1541                 return 0;
1542
1543         /* Allocate flow specification on the stack. */
1544         struct __attribute__((packed)) {
1545                 struct ibv_flow_attr attr;
1546                 struct ibv_flow_spec_eth spec;
1547         } data;
1548         struct ibv_flow_attr *attr = &data.attr;
1549         struct ibv_flow_spec_eth *spec = &data.spec;
1550
1551         if (priv->mac_flow)
1552                 priv_mac_addr_del(priv);
1553         /*
1554          * No padding must be inserted by the compiler between attr and spec.
1555          * This layout is expected by libibverbs.
1556          */
1557         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
1558         *attr = (struct ibv_flow_attr){
1559                 .type = IBV_FLOW_ATTR_NORMAL,
1560                 .priority = 3,
1561                 .num_of_specs = 1,
1562                 .port = priv->port,
1563                 .flags = 0
1564         };
1565         *spec = (struct ibv_flow_spec_eth){
1566                 .type = IBV_FLOW_SPEC_ETH,
1567                 .size = sizeof(*spec),
1568                 .val = {
1569                         .dst_mac = {
1570                                 (*mac)[0], (*mac)[1], (*mac)[2],
1571                                 (*mac)[3], (*mac)[4], (*mac)[5]
1572                         },
1573                 },
1574                 .mask = {
1575                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
1576                 }
1577         };
1578         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x",
1579               (void *)priv,
1580               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);
1581         /* Create related flow. */
1582         flow = ibv_create_flow(rxq->qp, attr);
1583         if (flow == NULL) {
1584                 rte_errno = errno ? errno : EINVAL;
1585                 ERROR("%p: flow configuration failed, errno=%d: %s",
1586                       (void *)rxq, rte_errno, strerror(errno));
1587                 return -rte_errno;
1588         }
1589         assert(priv->mac_flow == NULL);
1590         priv->mac_flow = flow;
1591         return 0;
1592 }
1593
1594 /**
1595  * Clean up a RX queue.
1596  *
1597  * Destroy objects, free allocated memory and reset the structure for reuse.
1598  *
1599  * @param rxq
1600  *   Pointer to RX queue structure.
1601  */
1602 static void
1603 rxq_cleanup(struct rxq *rxq)
1604 {
1605         DEBUG("cleaning up %p", (void *)rxq);
1606         rxq_free_elts(rxq);
1607         if (rxq->qp != NULL)
1608                 claim_zero(ibv_destroy_qp(rxq->qp));
1609         if (rxq->cq != NULL)
1610                 claim_zero(ibv_destroy_cq(rxq->cq));
1611         if (rxq->channel != NULL)
1612                 claim_zero(ibv_destroy_comp_channel(rxq->channel));
1613         if (rxq->mr != NULL)
1614                 claim_zero(ibv_dereg_mr(rxq->mr));
1615         memset(rxq, 0, sizeof(*rxq));
1616 }
1617
1618 /**
1619  * DPDK callback for RX.
1620  *
1621  * The following function doesn't manage scattered packets.
1622  *
1623  * @param dpdk_rxq
1624  *   Generic pointer to RX queue structure.
1625  * @param[out] pkts
1626  *   Array to store received packets.
1627  * @param pkts_n
1628  *   Maximum number of packets in array.
1629  *
1630  * @return
1631  *   Number of packets successfully received (<= pkts_n).
1632  */
1633 static uint16_t
1634 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
1635 {
1636         struct rxq *rxq = (struct rxq *)dpdk_rxq;
1637         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts;
1638         const unsigned int elts_n = rxq->elts_n;
1639         unsigned int elts_head = rxq->elts_head;
1640         struct ibv_wc wcs[pkts_n];
1641         struct ibv_recv_wr *wr_head = NULL;
1642         struct ibv_recv_wr **wr_next = &wr_head;
1643         struct ibv_recv_wr *wr_bad = NULL;
1644         unsigned int i;
1645         unsigned int pkts_ret = 0;
1646         int ret;
1647
1648         ret = ibv_poll_cq(rxq->cq, pkts_n, wcs);
1649         if (unlikely(ret == 0))
1650                 return 0;
1651         if (unlikely(ret < 0)) {
1652                 DEBUG("rxq=%p, ibv_poll_cq() failed (wc_n=%d)",
1653                       (void *)rxq, ret);
1654                 return 0;
1655         }
1656         assert(ret <= (int)pkts_n);
1657         /* For each work completion. */
1658         for (i = 0; i != (unsigned int)ret; ++i) {
1659                 struct ibv_wc *wc = &wcs[i];
1660                 struct rxq_elt *elt = &(*elts)[elts_head];
1661                 struct ibv_recv_wr *wr = &elt->wr;
1662                 uint32_t len = wc->byte_len;
1663                 struct rte_mbuf *seg = elt->buf;
1664                 struct rte_mbuf *rep;
1665
1666                 /* Sanity checks. */
1667                 assert(wr->sg_list == &elt->sge);
1668                 assert(wr->num_sge == 1);
1669                 assert(elts_head < rxq->elts_n);
1670                 assert(rxq->elts_head < rxq->elts_n);
1671                 /*
1672                  * Fetch initial bytes of packet descriptor into a
1673                  * cacheline while allocating rep.
1674                  */
1675                 rte_mbuf_prefetch_part1(seg);
1676                 rte_mbuf_prefetch_part2(seg);
1677                 /* Link completed WRs together for repost. */
1678                 *wr_next = wr;
1679                 wr_next = &wr->next;
1680                 if (unlikely(wc->status != IBV_WC_SUCCESS)) {
1681                         /* Whatever, just repost the offending WR. */
1682                         DEBUG("rxq=%p: bad work completion status (%d): %s",
1683                               (void *)rxq, wc->status,
1684                               ibv_wc_status_str(wc->status));
1685                         /* Increment dropped packets counter. */
1686                         ++rxq->stats.idropped;
1687                         goto repost;
1688                 }
1689                 rep = rte_mbuf_raw_alloc(rxq->mp);
1690                 if (unlikely(rep == NULL)) {
1691                         /*
1692                          * Unable to allocate a replacement mbuf,
1693                          * repost WR.
1694                          */
1695                         DEBUG("rxq=%p: can't allocate a new mbuf",
1696                               (void *)rxq);
1697                         /* Increase out of memory counters. */
1698                         ++rxq->stats.rx_nombuf;
1699                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
1700                         goto repost;
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                 /* Update seg information. */
1707                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
1708                 NB_SEGS(seg) = 1;
1709                 PORT(seg) = rxq->port_id;
1710                 NEXT(seg) = NULL;
1711                 PKT_LEN(seg) = len;
1712                 DATA_LEN(seg) = len;
1713                 seg->packet_type = 0;
1714                 seg->ol_flags = 0;
1715                 /* Return packet. */
1716                 *(pkts++) = seg;
1717                 ++pkts_ret;
1718                 /* Increase bytes counter. */
1719                 rxq->stats.ibytes += len;
1720 repost:
1721                 if (++elts_head >= elts_n)
1722                         elts_head = 0;
1723                 continue;
1724         }
1725         if (unlikely(i == 0))
1726                 return 0;
1727         /* Repost WRs. */
1728         *wr_next = NULL;
1729         assert(wr_head);
1730         ret = ibv_post_recv(rxq->qp, wr_head, &wr_bad);
1731         if (unlikely(ret)) {
1732                 /* Inability to repost WRs is fatal. */
1733                 DEBUG("%p: recv_burst(): failed (ret=%d)",
1734                       (void *)rxq->priv,
1735                       ret);
1736                 abort();
1737         }
1738         rxq->elts_head = elts_head;
1739         /* Increase packets counter. */
1740         rxq->stats.ipackets += pkts_ret;
1741         return pkts_ret;
1742 }
1743
1744 /**
1745  * Allocate a Queue Pair.
1746  * Optionally setup inline receive if supported.
1747  *
1748  * @param priv
1749  *   Pointer to private structure.
1750  * @param cq
1751  *   Completion queue to associate with QP.
1752  * @param desc
1753  *   Number of descriptors in QP (hint only).
1754  *
1755  * @return
1756  *   QP pointer or NULL in case of error and rte_errno is set.
1757  */
1758 static struct ibv_qp *
1759 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc)
1760 {
1761         struct ibv_qp *qp;
1762         struct ibv_qp_init_attr attr = {
1763                 /* CQ to be associated with the send queue. */
1764                 .send_cq = cq,
1765                 /* CQ to be associated with the receive queue. */
1766                 .recv_cq = cq,
1767                 .cap = {
1768                         /* Max number of outstanding WRs. */
1769                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
1770                                         priv->device_attr.max_qp_wr :
1771                                         desc),
1772                         /* Max number of scatter/gather elements in a WR. */
1773                         .max_recv_sge = 1,
1774                 },
1775                 .qp_type = IBV_QPT_RAW_PACKET,
1776         };
1777
1778         qp = ibv_create_qp(priv->pd, &attr);
1779         if (!qp)
1780                 rte_errno = errno ? errno : EINVAL;
1781         return qp;
1782 }
1783
1784 /**
1785  * Configure a RX queue.
1786  *
1787  * @param dev
1788  *   Pointer to Ethernet device structure.
1789  * @param rxq
1790  *   Pointer to RX queue structure.
1791  * @param desc
1792  *   Number of descriptors to configure in queue.
1793  * @param socket
1794  *   NUMA socket on which memory must be allocated.
1795  * @param[in] conf
1796  *   Thresholds parameters.
1797  * @param mp
1798  *   Memory pool for buffer allocations.
1799  *
1800  * @return
1801  *   0 on success, negative errno value otherwise and rte_errno is set.
1802  */
1803 static int
1804 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
1805           unsigned int socket, const struct rte_eth_rxconf *conf,
1806           struct rte_mempool *mp)
1807 {
1808         struct priv *priv = dev->data->dev_private;
1809         struct rxq tmpl = {
1810                 .priv = priv,
1811                 .mp = mp,
1812                 .socket = socket
1813         };
1814         struct ibv_qp_attr mod;
1815         struct ibv_recv_wr *bad_wr;
1816         unsigned int mb_len;
1817         int ret;
1818
1819         (void)conf; /* Thresholds configuration (ignored). */
1820         mb_len = rte_pktmbuf_data_room_size(mp);
1821         if (desc == 0) {
1822                 rte_errno = EINVAL;
1823                 ERROR("%p: invalid number of Rx descriptors", (void *)dev);
1824                 goto error;
1825         }
1826         /* Enable scattered packets support for this queue if necessary. */
1827         assert(mb_len >= RTE_PKTMBUF_HEADROOM);
1828         if (dev->data->dev_conf.rxmode.max_rx_pkt_len <=
1829             (mb_len - RTE_PKTMBUF_HEADROOM)) {
1830                 ;
1831         } else if (dev->data->dev_conf.rxmode.enable_scatter) {
1832                 WARN("%p: scattered mode has been requested but is"
1833                      " not supported, this may lead to packet loss",
1834                      (void *)dev);
1835         } else {
1836                 WARN("%p: the requested maximum Rx packet size (%u) is"
1837                      " larger than a single mbuf (%u) and scattered"
1838                      " mode has not been requested",
1839                      (void *)dev,
1840                      dev->data->dev_conf.rxmode.max_rx_pkt_len,
1841                      mb_len - RTE_PKTMBUF_HEADROOM);
1842         }
1843         /* Use the entire RX mempool as the memory region. */
1844         tmpl.mr = mlx4_mp2mr(priv->pd, mp);
1845         if (tmpl.mr == NULL) {
1846                 rte_errno = EINVAL;
1847                 ERROR("%p: MR creation failure: %s",
1848                       (void *)dev, strerror(rte_errno));
1849                 goto error;
1850         }
1851         if (dev->data->dev_conf.intr_conf.rxq) {
1852                 tmpl.channel = ibv_create_comp_channel(priv->ctx);
1853                 if (tmpl.channel == NULL) {
1854                         rte_errno = ENOMEM;
1855                         ERROR("%p: Rx interrupt completion channel creation"
1856                               " failure: %s",
1857                               (void *)dev, strerror(rte_errno));
1858                         goto error;
1859                 }
1860         }
1861         tmpl.cq = ibv_create_cq(priv->ctx, desc, NULL, tmpl.channel, 0);
1862         if (tmpl.cq == NULL) {
1863                 rte_errno = ENOMEM;
1864                 ERROR("%p: CQ creation failure: %s",
1865                       (void *)dev, strerror(rte_errno));
1866                 goto error;
1867         }
1868         DEBUG("priv->device_attr.max_qp_wr is %d",
1869               priv->device_attr.max_qp_wr);
1870         DEBUG("priv->device_attr.max_sge is %d",
1871               priv->device_attr.max_sge);
1872         tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc);
1873         if (tmpl.qp == NULL) {
1874                 ERROR("%p: QP creation failure: %s",
1875                       (void *)dev, strerror(rte_errno));
1876                 goto error;
1877         }
1878         mod = (struct ibv_qp_attr){
1879                 /* Move the QP to this state. */
1880                 .qp_state = IBV_QPS_INIT,
1881                 /* Primary port number. */
1882                 .port_num = priv->port
1883         };
1884         ret = ibv_modify_qp(tmpl.qp, &mod, IBV_QP_STATE | IBV_QP_PORT);
1885         if (ret) {
1886                 rte_errno = ret;
1887                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1888                       (void *)dev, strerror(rte_errno));
1889                 goto error;
1890         }
1891         ret = rxq_alloc_elts(&tmpl, desc);
1892         if (ret) {
1893                 ERROR("%p: RXQ allocation failed: %s",
1894                       (void *)dev, strerror(rte_errno));
1895                 goto error;
1896         }
1897         ret = ibv_post_recv(tmpl.qp, &(*tmpl.elts)[0].wr, &bad_wr);
1898         if (ret) {
1899                 rte_errno = ret;
1900                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
1901                       (void *)dev,
1902                       (void *)bad_wr,
1903                       strerror(rte_errno));
1904                 goto error;
1905         }
1906         mod = (struct ibv_qp_attr){
1907                 .qp_state = IBV_QPS_RTR
1908         };
1909         ret = ibv_modify_qp(tmpl.qp, &mod, IBV_QP_STATE);
1910         if (ret) {
1911                 rte_errno = ret;
1912                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1913                       (void *)dev, strerror(rte_errno));
1914                 goto error;
1915         }
1916         /* Save port ID. */
1917         tmpl.port_id = dev->data->port_id;
1918         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
1919         /* Clean up rxq in case we're reinitializing it. */
1920         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
1921         rxq_cleanup(rxq);
1922         *rxq = tmpl;
1923         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
1924         return 0;
1925 error:
1926         ret = rte_errno;
1927         rxq_cleanup(&tmpl);
1928         rte_errno = ret;
1929         assert(rte_errno > 0);
1930         return -rte_errno;
1931 }
1932
1933 /**
1934  * DPDK callback to configure a RX queue.
1935  *
1936  * @param dev
1937  *   Pointer to Ethernet device structure.
1938  * @param idx
1939  *   RX queue index.
1940  * @param desc
1941  *   Number of descriptors to configure in queue.
1942  * @param socket
1943  *   NUMA socket on which memory must be allocated.
1944  * @param[in] conf
1945  *   Thresholds parameters.
1946  * @param mp
1947  *   Memory pool for buffer allocations.
1948  *
1949  * @return
1950  *   0 on success, negative errno value otherwise and rte_errno is set.
1951  */
1952 static int
1953 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1954                     unsigned int socket, const struct rte_eth_rxconf *conf,
1955                     struct rte_mempool *mp)
1956 {
1957         struct priv *priv = dev->data->dev_private;
1958         struct rxq *rxq = (*priv->rxqs)[idx];
1959         int ret;
1960
1961         priv_lock(priv);
1962         DEBUG("%p: configuring queue %u for %u descriptors",
1963               (void *)dev, idx, desc);
1964         if (idx >= priv->rxqs_n) {
1965                 rte_errno = EOVERFLOW;
1966                 ERROR("%p: queue index out of range (%u >= %u)",
1967                       (void *)dev, idx, priv->rxqs_n);
1968                 priv_unlock(priv);
1969                 return -rte_errno;
1970         }
1971         if (rxq != NULL) {
1972                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1973                       (void *)dev, idx, (void *)rxq);
1974                 if (priv->started) {
1975                         rte_errno = EEXIST;
1976                         priv_unlock(priv);
1977                         return -rte_errno;
1978                 }
1979                 (*priv->rxqs)[idx] = NULL;
1980                 if (idx == 0)
1981                         priv_mac_addr_del(priv);
1982                 rxq_cleanup(rxq);
1983         } else {
1984                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
1985                 if (rxq == NULL) {
1986                         rte_errno = ENOMEM;
1987                         ERROR("%p: unable to allocate queue index %u",
1988                               (void *)dev, idx);
1989                         priv_unlock(priv);
1990                         return -rte_errno;
1991                 }
1992         }
1993         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
1994         if (ret)
1995                 rte_free(rxq);
1996         else {
1997                 rxq->stats.idx = idx;
1998                 DEBUG("%p: adding RX queue %p to list",
1999                       (void *)dev, (void *)rxq);
2000                 (*priv->rxqs)[idx] = rxq;
2001                 /* Update receive callback. */
2002                 dev->rx_pkt_burst = mlx4_rx_burst;
2003         }
2004         priv_unlock(priv);
2005         return ret;
2006 }
2007
2008 /**
2009  * DPDK callback to release a RX queue.
2010  *
2011  * @param dpdk_rxq
2012  *   Generic RX queue pointer.
2013  */
2014 static void
2015 mlx4_rx_queue_release(void *dpdk_rxq)
2016 {
2017         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2018         struct priv *priv;
2019         unsigned int i;
2020
2021         if (rxq == NULL)
2022                 return;
2023         priv = rxq->priv;
2024         priv_lock(priv);
2025         for (i = 0; (i != priv->rxqs_n); ++i)
2026                 if ((*priv->rxqs)[i] == rxq) {
2027                         DEBUG("%p: removing RX queue %p from list",
2028                               (void *)priv->dev, (void *)rxq);
2029                         (*priv->rxqs)[i] = NULL;
2030                         if (i == 0)
2031                                 priv_mac_addr_del(priv);
2032                         break;
2033                 }
2034         rxq_cleanup(rxq);
2035         rte_free(rxq);
2036         priv_unlock(priv);
2037 }
2038
2039 static int
2040 priv_dev_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2041
2042 static int
2043 priv_dev_removal_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2044
2045 static int
2046 priv_dev_link_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
2047
2048 /**
2049  * DPDK callback to start the device.
2050  *
2051  * Simulate device start by attaching all configured flows.
2052  *
2053  * @param dev
2054  *   Pointer to Ethernet device structure.
2055  *
2056  * @return
2057  *   0 on success, negative errno value otherwise and rte_errno is set.
2058  */
2059 static int
2060 mlx4_dev_start(struct rte_eth_dev *dev)
2061 {
2062         struct priv *priv = dev->data->dev_private;
2063         int ret;
2064
2065         priv_lock(priv);
2066         if (priv->started) {
2067                 priv_unlock(priv);
2068                 return 0;
2069         }
2070         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
2071         priv->started = 1;
2072         ret = priv_mac_addr_add(priv);
2073         if (ret)
2074                 goto err;
2075         ret = priv_dev_link_interrupt_handler_install(priv, dev);
2076         if (ret) {
2077                 ERROR("%p: LSC handler install failed",
2078                      (void *)dev);
2079                 goto err;
2080         }
2081         ret = priv_dev_removal_interrupt_handler_install(priv, dev);
2082         if (ret) {
2083                 ERROR("%p: RMV handler install failed",
2084                      (void *)dev);
2085                 goto err;
2086         }
2087         ret = priv_rx_intr_vec_enable(priv);
2088         if (ret) {
2089                 ERROR("%p: Rx interrupt vector creation failed",
2090                       (void *)dev);
2091                 goto err;
2092         }
2093         ret = mlx4_priv_flow_start(priv);
2094         if (ret) {
2095                 ERROR("%p: flow start failed: %s",
2096                       (void *)dev, strerror(ret));
2097                 goto err;
2098         }
2099         priv_unlock(priv);
2100         return 0;
2101 err:
2102         /* Rollback. */
2103         priv_mac_addr_del(priv);
2104         priv->started = 0;
2105         priv_unlock(priv);
2106         return ret;
2107 }
2108
2109 /**
2110  * DPDK callback to stop the device.
2111  *
2112  * Simulate device stop by detaching all configured flows.
2113  *
2114  * @param dev
2115  *   Pointer to Ethernet device structure.
2116  */
2117 static void
2118 mlx4_dev_stop(struct rte_eth_dev *dev)
2119 {
2120         struct priv *priv = dev->data->dev_private;
2121
2122         priv_lock(priv);
2123         if (!priv->started) {
2124                 priv_unlock(priv);
2125                 return;
2126         }
2127         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
2128         priv->started = 0;
2129         mlx4_priv_flow_stop(priv);
2130         priv_mac_addr_del(priv);
2131         priv_unlock(priv);
2132 }
2133
2134 /**
2135  * Dummy DPDK callback for TX.
2136  *
2137  * This function is used to temporarily replace the real callback during
2138  * unsafe control operations on the queue, or in case of error.
2139  *
2140  * @param dpdk_txq
2141  *   Generic pointer to TX queue structure.
2142  * @param[in] pkts
2143  *   Packets to transmit.
2144  * @param pkts_n
2145  *   Number of packets in array.
2146  *
2147  * @return
2148  *   Number of packets successfully transmitted (<= pkts_n).
2149  */
2150 static uint16_t
2151 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
2152 {
2153         (void)dpdk_txq;
2154         (void)pkts;
2155         (void)pkts_n;
2156         return 0;
2157 }
2158
2159 /**
2160  * Dummy DPDK callback for RX.
2161  *
2162  * This function is used to temporarily replace the real callback during
2163  * unsafe control operations on the queue, or in case of error.
2164  *
2165  * @param dpdk_rxq
2166  *   Generic pointer to RX queue structure.
2167  * @param[out] pkts
2168  *   Array to store received packets.
2169  * @param pkts_n
2170  *   Maximum number of packets in array.
2171  *
2172  * @return
2173  *   Number of packets successfully received (<= pkts_n).
2174  */
2175 static uint16_t
2176 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2177 {
2178         (void)dpdk_rxq;
2179         (void)pkts;
2180         (void)pkts_n;
2181         return 0;
2182 }
2183
2184 static int
2185 priv_dev_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
2186
2187 static int
2188 priv_dev_removal_interrupt_handler_uninstall(struct priv *,
2189                                              struct rte_eth_dev *);
2190
2191 static int
2192 priv_dev_link_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
2193
2194 /**
2195  * DPDK callback to close the device.
2196  *
2197  * Destroy all queues and objects, free memory.
2198  *
2199  * @param dev
2200  *   Pointer to Ethernet device structure.
2201  */
2202 static void
2203 mlx4_dev_close(struct rte_eth_dev *dev)
2204 {
2205         struct priv *priv = dev->data->dev_private;
2206         void *tmp;
2207         unsigned int i;
2208
2209         if (priv == NULL)
2210                 return;
2211         priv_lock(priv);
2212         DEBUG("%p: closing device \"%s\"",
2213               (void *)dev,
2214               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
2215         priv_mac_addr_del(priv);
2216         /*
2217          * Prevent crashes when queues are still in use. This is unfortunately
2218          * still required for DPDK 1.3 because some programs (such as testpmd)
2219          * never release them before closing the device.
2220          */
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 /**
2339  * DPDK callback to get information about the device.
2340  *
2341  * @param dev
2342  *   Pointer to Ethernet device structure.
2343  * @param[out] info
2344  *   Info structure output buffer.
2345  */
2346 static void
2347 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
2348 {
2349         struct priv *priv = dev->data->dev_private;
2350         unsigned int max;
2351         char ifname[IF_NAMESIZE];
2352
2353         info->pci_dev = RTE_ETH_DEV_TO_PCI(dev);
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         if (priv == NULL) {
2499                 rte_errno = EINVAL;
2500                 return -rte_errno;
2501         }
2502         (void)wait_to_complete;
2503         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
2504                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(rte_errno));
2505                 return -rte_errno;
2506         }
2507         memset(&dev_link, 0, sizeof(dev_link));
2508         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
2509                                 (ifr.ifr_flags & IFF_RUNNING));
2510         ifr.ifr_data = (void *)&edata;
2511         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2512                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
2513                      strerror(rte_errno));
2514                 return -rte_errno;
2515         }
2516         link_speed = ethtool_cmd_speed(&edata);
2517         if (link_speed == -1)
2518                 dev_link.link_speed = 0;
2519         else
2520                 dev_link.link_speed = link_speed;
2521         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
2522                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
2523         dev_link.link_autoneg = !(dev->data->dev_conf.link_speeds &
2524                         ETH_LINK_SPEED_FIXED);
2525         dev->data->dev_link = dev_link;
2526         return 0;
2527 }
2528
2529 /**
2530  * DPDK callback to change the MTU.
2531  *
2532  * @param dev
2533  *   Pointer to Ethernet device structure.
2534  * @param in_mtu
2535  *   New MTU.
2536  *
2537  * @return
2538  *   0 on success, negative errno value otherwise and rte_errno is set.
2539  */
2540 static int
2541 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
2542 {
2543         struct priv *priv = dev->data->dev_private;
2544         int ret = 0;
2545
2546         priv_lock(priv);
2547         /* Set kernel interface MTU first. */
2548         if (priv_set_mtu(priv, mtu)) {
2549                 ret = rte_errno;
2550                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
2551                      strerror(rte_errno));
2552                 goto out;
2553         } else
2554                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
2555         priv->mtu = mtu;
2556 out:
2557         priv_unlock(priv);
2558         assert(ret >= 0);
2559         return -ret;
2560 }
2561
2562 /**
2563  * DPDK callback to get flow control status.
2564  *
2565  * @param dev
2566  *   Pointer to Ethernet device structure.
2567  * @param[out] fc_conf
2568  *   Flow control output buffer.
2569  *
2570  * @return
2571  *   0 on success, negative errno value otherwise and rte_errno is set.
2572  */
2573 static int
2574 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
2575 {
2576         struct priv *priv = dev->data->dev_private;
2577         struct ifreq ifr;
2578         struct ethtool_pauseparam ethpause = {
2579                 .cmd = ETHTOOL_GPAUSEPARAM
2580         };
2581         int ret;
2582
2583         ifr.ifr_data = (void *)&ethpause;
2584         priv_lock(priv);
2585         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2586                 ret = rte_errno;
2587                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
2588                      " failed: %s",
2589                      strerror(rte_errno));
2590                 goto out;
2591         }
2592         fc_conf->autoneg = ethpause.autoneg;
2593         if (ethpause.rx_pause && ethpause.tx_pause)
2594                 fc_conf->mode = RTE_FC_FULL;
2595         else if (ethpause.rx_pause)
2596                 fc_conf->mode = RTE_FC_RX_PAUSE;
2597         else if (ethpause.tx_pause)
2598                 fc_conf->mode = RTE_FC_TX_PAUSE;
2599         else
2600                 fc_conf->mode = RTE_FC_NONE;
2601         ret = 0;
2602 out:
2603         priv_unlock(priv);
2604         assert(ret >= 0);
2605         return -ret;
2606 }
2607
2608 /**
2609  * DPDK callback to modify flow control parameters.
2610  *
2611  * @param dev
2612  *   Pointer to Ethernet device structure.
2613  * @param[in] fc_conf
2614  *   Flow control parameters.
2615  *
2616  * @return
2617  *   0 on success, negative errno value otherwise and rte_errno is set.
2618  */
2619 static int
2620 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
2621 {
2622         struct priv *priv = dev->data->dev_private;
2623         struct ifreq ifr;
2624         struct ethtool_pauseparam ethpause = {
2625                 .cmd = ETHTOOL_SPAUSEPARAM
2626         };
2627         int ret;
2628
2629         ifr.ifr_data = (void *)&ethpause;
2630         ethpause.autoneg = fc_conf->autoneg;
2631         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
2632             (fc_conf->mode & RTE_FC_RX_PAUSE))
2633                 ethpause.rx_pause = 1;
2634         else
2635                 ethpause.rx_pause = 0;
2636         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
2637             (fc_conf->mode & RTE_FC_TX_PAUSE))
2638                 ethpause.tx_pause = 1;
2639         else
2640                 ethpause.tx_pause = 0;
2641         priv_lock(priv);
2642         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
2643                 ret = rte_errno;
2644                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
2645                      " failed: %s",
2646                      strerror(rte_errno));
2647                 goto out;
2648         }
2649         ret = 0;
2650 out:
2651         priv_unlock(priv);
2652         assert(ret >= 0);
2653         return -ret;
2654 }
2655
2656 const struct rte_flow_ops mlx4_flow_ops = {
2657         .validate = mlx4_flow_validate,
2658         .create = mlx4_flow_create,
2659         .destroy = mlx4_flow_destroy,
2660         .flush = mlx4_flow_flush,
2661         .query = NULL,
2662         .isolate = mlx4_flow_isolate,
2663 };
2664
2665 /**
2666  * Manage filter operations.
2667  *
2668  * @param dev
2669  *   Pointer to Ethernet device structure.
2670  * @param filter_type
2671  *   Filter type.
2672  * @param filter_op
2673  *   Operation to perform.
2674  * @param arg
2675  *   Pointer to operation-specific structure.
2676  *
2677  * @return
2678  *   0 on success, negative errno value otherwise and rte_errno is set.
2679  */
2680 static int
2681 mlx4_dev_filter_ctrl(struct rte_eth_dev *dev,
2682                      enum rte_filter_type filter_type,
2683                      enum rte_filter_op filter_op,
2684                      void *arg)
2685 {
2686         switch (filter_type) {
2687         case RTE_ETH_FILTER_GENERIC:
2688                 if (filter_op != RTE_ETH_FILTER_GET)
2689                         break;
2690                 *(const void **)arg = &mlx4_flow_ops;
2691                 return 0;
2692         default:
2693                 ERROR("%p: filter type (%d) not supported",
2694                       (void *)dev, filter_type);
2695                 break;
2696         }
2697         rte_errno = ENOTSUP;
2698         return -rte_errno;
2699 }
2700
2701 static const struct eth_dev_ops mlx4_dev_ops = {
2702         .dev_configure = mlx4_dev_configure,
2703         .dev_start = mlx4_dev_start,
2704         .dev_stop = mlx4_dev_stop,
2705         .dev_set_link_down = mlx4_set_link_down,
2706         .dev_set_link_up = mlx4_set_link_up,
2707         .dev_close = mlx4_dev_close,
2708         .link_update = mlx4_link_update,
2709         .stats_get = mlx4_stats_get,
2710         .stats_reset = mlx4_stats_reset,
2711         .dev_infos_get = mlx4_dev_infos_get,
2712         .rx_queue_setup = mlx4_rx_queue_setup,
2713         .tx_queue_setup = mlx4_tx_queue_setup,
2714         .rx_queue_release = mlx4_rx_queue_release,
2715         .tx_queue_release = mlx4_tx_queue_release,
2716         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
2717         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
2718         .mtu_set = mlx4_dev_set_mtu,
2719         .filter_ctrl = mlx4_dev_filter_ctrl,
2720         .rx_queue_intr_enable = mlx4_rx_intr_enable,
2721         .rx_queue_intr_disable = mlx4_rx_intr_disable,
2722 };
2723
2724 /**
2725  * Get PCI information from struct ibv_device.
2726  *
2727  * @param device
2728  *   Pointer to Ethernet device structure.
2729  * @param[out] pci_addr
2730  *   PCI bus address output buffer.
2731  *
2732  * @return
2733  *   0 on success, negative errno value otherwise and rte_errno is set.
2734  */
2735 static int
2736 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
2737                             struct rte_pci_addr *pci_addr)
2738 {
2739         FILE *file;
2740         char line[32];
2741         MKSTR(path, "%s/device/uevent", device->ibdev_path);
2742
2743         file = fopen(path, "rb");
2744         if (file == NULL) {
2745                 rte_errno = errno;
2746                 return -rte_errno;
2747         }
2748         while (fgets(line, sizeof(line), file) == line) {
2749                 size_t len = strlen(line);
2750                 int ret;
2751
2752                 /* Truncate long lines. */
2753                 if (len == (sizeof(line) - 1))
2754                         while (line[(len - 1)] != '\n') {
2755                                 ret = fgetc(file);
2756                                 if (ret == EOF)
2757                                         break;
2758                                 line[(len - 1)] = ret;
2759                         }
2760                 /* Extract information. */
2761                 if (sscanf(line,
2762                            "PCI_SLOT_NAME="
2763                            "%" SCNx32 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
2764                            &pci_addr->domain,
2765                            &pci_addr->bus,
2766                            &pci_addr->devid,
2767                            &pci_addr->function) == 4) {
2768                         ret = 0;
2769                         break;
2770                 }
2771         }
2772         fclose(file);
2773         return 0;
2774 }
2775
2776 /**
2777  * Get MAC address by querying netdevice.
2778  *
2779  * @param[in] priv
2780  *   struct priv for the requested device.
2781  * @param[out] mac
2782  *   MAC address output buffer.
2783  *
2784  * @return
2785  *   0 on success, negative errno value otherwise and rte_errno is set.
2786  */
2787 static int
2788 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
2789 {
2790         struct ifreq request;
2791         int ret = priv_ifreq(priv, SIOCGIFHWADDR, &request);
2792
2793         if (ret)
2794                 return ret;
2795         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
2796         return 0;
2797 }
2798
2799 static void
2800 mlx4_dev_link_status_handler(void *);
2801 static void
2802 mlx4_dev_interrupt_handler(void *);
2803
2804 /**
2805  * Link/device status handler.
2806  *
2807  * @param priv
2808  *   Pointer to private structure.
2809  * @param dev
2810  *   Pointer to the rte_eth_dev structure.
2811  * @param events
2812  *   Pointer to event flags holder.
2813  *
2814  * @return
2815  *   Number of events
2816  */
2817 static int
2818 priv_dev_status_handler(struct priv *priv, struct rte_eth_dev *dev,
2819                         uint32_t *events)
2820 {
2821         struct ibv_async_event event;
2822         int port_change = 0;
2823         struct rte_eth_link *link = &dev->data->dev_link;
2824         int ret = 0;
2825
2826         *events = 0;
2827         /* Read all message and acknowledge them. */
2828         for (;;) {
2829                 if (ibv_get_async_event(priv->ctx, &event))
2830                         break;
2831                 if ((event.event_type == IBV_EVENT_PORT_ACTIVE ||
2832                      event.event_type == IBV_EVENT_PORT_ERR) &&
2833                     (priv->intr_conf.lsc == 1)) {
2834                         port_change = 1;
2835                         ret++;
2836                 } else if (event.event_type == IBV_EVENT_DEVICE_FATAL &&
2837                            priv->intr_conf.rmv == 1) {
2838                         *events |= (1 << RTE_ETH_EVENT_INTR_RMV);
2839                         ret++;
2840                 } else
2841                         DEBUG("event type %d on port %d not handled",
2842                               event.event_type, event.element.port_num);
2843                 ibv_ack_async_event(&event);
2844         }
2845         if (!port_change)
2846                 return ret;
2847         mlx4_link_update(dev, 0);
2848         if (((link->link_speed == 0) && link->link_status) ||
2849             ((link->link_speed != 0) && !link->link_status)) {
2850                 if (!priv->pending_alarm) {
2851                         /* Inconsistent status, check again later. */
2852                         priv->pending_alarm = 1;
2853                         rte_eal_alarm_set(MLX4_ALARM_TIMEOUT_US,
2854                                           mlx4_dev_link_status_handler,
2855                                           dev);
2856                 }
2857         } else {
2858                 *events |= (1 << RTE_ETH_EVENT_INTR_LSC);
2859         }
2860         return ret;
2861 }
2862
2863 /**
2864  * Handle delayed link status event.
2865  *
2866  * @param arg
2867  *   Registered argument.
2868  */
2869 static void
2870 mlx4_dev_link_status_handler(void *arg)
2871 {
2872         struct rte_eth_dev *dev = arg;
2873         struct priv *priv = dev->data->dev_private;
2874         uint32_t events;
2875         int ret;
2876
2877         priv_lock(priv);
2878         assert(priv->pending_alarm == 1);
2879         priv->pending_alarm = 0;
2880         ret = priv_dev_status_handler(priv, dev, &events);
2881         priv_unlock(priv);
2882         if (ret > 0 && events & (1 << RTE_ETH_EVENT_INTR_LSC))
2883                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC,
2884                                               NULL, NULL);
2885 }
2886
2887 /**
2888  * Handle interrupts from the NIC.
2889  *
2890  * @param[in] intr_handle
2891  *   Interrupt handler.
2892  * @param cb_arg
2893  *   Callback argument.
2894  */
2895 static void
2896 mlx4_dev_interrupt_handler(void *cb_arg)
2897 {
2898         struct rte_eth_dev *dev = cb_arg;
2899         struct priv *priv = dev->data->dev_private;
2900         int ret;
2901         uint32_t ev;
2902         int i;
2903
2904         priv_lock(priv);
2905         ret = priv_dev_status_handler(priv, dev, &ev);
2906         priv_unlock(priv);
2907         if (ret > 0) {
2908                 for (i = RTE_ETH_EVENT_UNKNOWN;
2909                      i < RTE_ETH_EVENT_MAX;
2910                      i++) {
2911                         if (ev & (1 << i)) {
2912                                 ev &= ~(1 << i);
2913                                 _rte_eth_dev_callback_process(dev, i, NULL,
2914                                                               NULL);
2915                                 ret--;
2916                         }
2917                 }
2918                 if (ret)
2919                         WARN("%d event%s not processed", ret,
2920                              (ret > 1 ? "s were" : " was"));
2921         }
2922 }
2923
2924 /**
2925  * Uninstall interrupt handler.
2926  *
2927  * @param priv
2928  *   Pointer to private structure.
2929  * @param dev
2930  *   Pointer to the rte_eth_dev structure.
2931  *
2932  * @return
2933  *   0 on success, negative errno value otherwise and rte_errno is set.
2934  */
2935 static int
2936 priv_dev_interrupt_handler_uninstall(struct priv *priv, struct rte_eth_dev *dev)
2937 {
2938         int ret;
2939
2940         if (priv->intr_conf.lsc ||
2941             priv->intr_conf.rmv)
2942                 return 0;
2943         ret = rte_intr_callback_unregister(&priv->intr_handle,
2944                                            mlx4_dev_interrupt_handler,
2945                                            dev);
2946         if (ret < 0) {
2947                 rte_errno = ret;
2948                 ERROR("rte_intr_callback_unregister failed with %d %s",
2949                       ret, strerror(rte_errno));
2950         }
2951         priv->intr_handle.fd = 0;
2952         priv->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
2953         return ret;
2954 }
2955
2956 /**
2957  * Install interrupt handler.
2958  *
2959  * @param priv
2960  *   Pointer to private structure.
2961  * @param dev
2962  *   Pointer to the rte_eth_dev structure.
2963  *
2964  * @return
2965  *   0 on success, negative errno value otherwise and rte_errno is set.
2966  */
2967 static int
2968 priv_dev_interrupt_handler_install(struct priv *priv,
2969                                    struct rte_eth_dev *dev)
2970 {
2971         int flags;
2972         int rc;
2973
2974         /*
2975          * Check whether the interrupt handler has already been installed
2976          * for either type of interrupt.
2977          */
2978         if (priv->intr_conf.lsc &&
2979             priv->intr_conf.rmv &&
2980             priv->intr_handle.fd)
2981                 return 0;
2982         assert(priv->ctx->async_fd > 0);
2983         flags = fcntl(priv->ctx->async_fd, F_GETFL);
2984         rc = fcntl(priv->ctx->async_fd, F_SETFL, flags | O_NONBLOCK);
2985         if (rc < 0) {
2986                 rte_errno = errno ? errno : EINVAL;
2987                 INFO("failed to change file descriptor async event queue");
2988                 dev->data->dev_conf.intr_conf.lsc = 0;
2989                 dev->data->dev_conf.intr_conf.rmv = 0;
2990                 return -rte_errno;
2991         } else {
2992                 priv->intr_handle.fd = priv->ctx->async_fd;
2993                 priv->intr_handle.type = RTE_INTR_HANDLE_EXT;
2994                 rc = rte_intr_callback_register(&priv->intr_handle,
2995                                                  mlx4_dev_interrupt_handler,
2996                                                  dev);
2997                 if (rc) {
2998                         rte_errno = -rc;
2999                         ERROR("rte_intr_callback_register failed "
3000                               " (rte_errno: %s)", strerror(rte_errno));
3001                         return -rte_errno;
3002                 }
3003         }
3004         return 0;
3005 }
3006
3007 /**
3008  * Uninstall interrupt handler.
3009  *
3010  * @param priv
3011  *   Pointer to private structure.
3012  * @param dev
3013  *   Pointer to the rte_eth_dev structure.
3014  *
3015  * @return
3016  *   0 on success, negative errno value otherwise and rte_errno is set.
3017  */
3018 static int
3019 priv_dev_removal_interrupt_handler_uninstall(struct priv *priv,
3020                                             struct rte_eth_dev *dev)
3021 {
3022         if (dev->data->dev_conf.intr_conf.rmv) {
3023                 priv->intr_conf.rmv = 0;
3024                 return priv_dev_interrupt_handler_uninstall(priv, dev);
3025         }
3026         return 0;
3027 }
3028
3029 /**
3030  * Uninstall interrupt handler.
3031  *
3032  * @param priv
3033  *   Pointer to private structure.
3034  * @param dev
3035  *   Pointer to the rte_eth_dev structure.
3036  *
3037  * @return
3038  *   0 on success, negative errno value otherwise and rte_errno is set.
3039  */
3040 static int
3041 priv_dev_link_interrupt_handler_uninstall(struct priv *priv,
3042                                           struct rte_eth_dev *dev)
3043 {
3044         int ret = 0;
3045
3046         if (dev->data->dev_conf.intr_conf.lsc) {
3047                 priv->intr_conf.lsc = 0;
3048                 ret = priv_dev_interrupt_handler_uninstall(priv, dev);
3049                 if (ret)
3050                         return ret;
3051         }
3052         if (priv->pending_alarm)
3053                 if (rte_eal_alarm_cancel(mlx4_dev_link_status_handler,
3054                                          dev)) {
3055                         ERROR("rte_eal_alarm_cancel failed "
3056                               " (rte_errno: %s)", strerror(rte_errno));
3057                         return -rte_errno;
3058                 }
3059         priv->pending_alarm = 0;
3060         return 0;
3061 }
3062
3063 /**
3064  * Install link interrupt handler.
3065  *
3066  * @param priv
3067  *   Pointer to private structure.
3068  * @param dev
3069  *   Pointer to the rte_eth_dev structure.
3070  *
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  *
3097  * @return
3098  *   0 on success, negative errno value otherwise and rte_errno is set.
3099  */
3100 static int
3101 priv_dev_removal_interrupt_handler_install(struct priv *priv,
3102                                            struct rte_eth_dev *dev)
3103 {
3104         int ret;
3105
3106         if (dev->data->dev_conf.intr_conf.rmv) {
3107                 ret = priv_dev_interrupt_handler_install(priv, dev);
3108                 if (ret)
3109                         return ret;
3110                 priv->intr_conf.rmv = 1;
3111         }
3112         return 0;
3113 }
3114
3115 /**
3116  * Allocate queue vector and fill epoll fd list for Rx interrupts.
3117  *
3118  * @param priv
3119  *   Pointer to private structure.
3120  *
3121  * @return
3122  *   0 on success, negative errno value otherwise and rte_errno is set.
3123  */
3124 static int
3125 priv_rx_intr_vec_enable(struct priv *priv)
3126 {
3127         unsigned int i;
3128         unsigned int rxqs_n = priv->rxqs_n;
3129         unsigned int n = RTE_MIN(rxqs_n, (uint32_t)RTE_MAX_RXTX_INTR_VEC_ID);
3130         unsigned int count = 0;
3131         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
3132
3133         if (!priv->dev->data->dev_conf.intr_conf.rxq)
3134                 return 0;
3135         priv_rx_intr_vec_disable(priv);
3136         intr_handle->intr_vec = malloc(sizeof(intr_handle->intr_vec[rxqs_n]));
3137         if (intr_handle->intr_vec == NULL) {
3138                 rte_errno = ENOMEM;
3139                 ERROR("failed to allocate memory for interrupt vector,"
3140                       " Rx interrupts will not be supported");
3141                 return -rte_errno;
3142         }
3143         intr_handle->type = RTE_INTR_HANDLE_EXT;
3144         for (i = 0; i != n; ++i) {
3145                 struct rxq *rxq = (*priv->rxqs)[i];
3146                 int fd;
3147                 int flags;
3148                 int rc;
3149
3150                 /* Skip queues that cannot request interrupts. */
3151                 if (!rxq || !rxq->channel) {
3152                         /* Use invalid intr_vec[] index to disable entry. */
3153                         intr_handle->intr_vec[i] =
3154                                 RTE_INTR_VEC_RXTX_OFFSET +
3155                                 RTE_MAX_RXTX_INTR_VEC_ID;
3156                         continue;
3157                 }
3158                 if (count >= RTE_MAX_RXTX_INTR_VEC_ID) {
3159                         rte_errno = E2BIG;
3160                         ERROR("too many Rx queues for interrupt vector size"
3161                               " (%d), Rx interrupts cannot be enabled",
3162                               RTE_MAX_RXTX_INTR_VEC_ID);
3163                         priv_rx_intr_vec_disable(priv);
3164                         return -rte_errno;
3165                 }
3166                 fd = rxq->channel->fd;
3167                 flags = fcntl(fd, F_GETFL);
3168                 rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
3169                 if (rc < 0) {
3170                         rte_errno = errno;
3171                         ERROR("failed to make Rx interrupt file descriptor"
3172                               " %d non-blocking for queue index %d", fd, i);
3173                         priv_rx_intr_vec_disable(priv);
3174                         return -rte_errno;
3175                 }
3176                 intr_handle->intr_vec[i] = RTE_INTR_VEC_RXTX_OFFSET + count;
3177                 intr_handle->efds[count] = fd;
3178                 count++;
3179         }
3180         if (!count)
3181                 priv_rx_intr_vec_disable(priv);
3182         else
3183                 intr_handle->nb_efd = count;
3184         return 0;
3185 }
3186
3187 /**
3188  * Clean up Rx interrupts handler.
3189  *
3190  * @param priv
3191  *   Pointer to private structure.
3192  */
3193 static void
3194 priv_rx_intr_vec_disable(struct priv *priv)
3195 {
3196         struct rte_intr_handle *intr_handle = priv->dev->intr_handle;
3197
3198         rte_intr_free_epoll_fd(intr_handle);
3199         free(intr_handle->intr_vec);
3200         intr_handle->nb_efd = 0;
3201         intr_handle->intr_vec = NULL;
3202 }
3203
3204 /**
3205  * DPDK callback for Rx queue interrupt enable.
3206  *
3207  * @param dev
3208  *   Pointer to Ethernet device structure.
3209  * @param idx
3210  *   Rx queue index.
3211  *
3212  * @return
3213  *   0 on success, negative errno value otherwise and rte_errno is set.
3214  */
3215 static int
3216 mlx4_rx_intr_enable(struct rte_eth_dev *dev, uint16_t idx)
3217 {
3218         struct priv *priv = dev->data->dev_private;
3219         struct rxq *rxq = (*priv->rxqs)[idx];
3220         int ret;
3221
3222         if (!rxq || !rxq->channel)
3223                 ret = EINVAL;
3224         else
3225                 ret = ibv_req_notify_cq(rxq->cq, 0);
3226         if (ret) {
3227                 rte_errno = ret;
3228                 WARN("unable to arm interrupt on rx queue %d", idx);
3229         }
3230         return -ret;
3231 }
3232
3233 /**
3234  * DPDK callback for Rx queue interrupt disable.
3235  *
3236  * @param dev
3237  *   Pointer to Ethernet device structure.
3238  * @param idx
3239  *   Rx queue index.
3240  *
3241  * @return
3242  *   0 on success, negative errno value otherwise and rte_errno is set.
3243  */
3244 static int
3245 mlx4_rx_intr_disable(struct rte_eth_dev *dev, uint16_t idx)
3246 {
3247         struct priv *priv = dev->data->dev_private;
3248         struct rxq *rxq = (*priv->rxqs)[idx];
3249         struct ibv_cq *ev_cq;
3250         void *ev_ctx;
3251         int ret;
3252
3253         if (!rxq || !rxq->channel) {
3254                 ret = EINVAL;
3255         } else {
3256                 ret = ibv_get_cq_event(rxq->cq->channel, &ev_cq, &ev_ctx);
3257                 if (ret || ev_cq != rxq->cq)
3258                         ret = EINVAL;
3259         }
3260         if (ret) {
3261                 rte_errno = ret;
3262                 WARN("unable to disable interrupt on rx queue %d",
3263                      idx);
3264         } else {
3265                 ibv_ack_cq_events(rxq->cq, 1);
3266         }
3267         return -ret;
3268 }
3269
3270 /**
3271  * Verify and store value for device argument.
3272  *
3273  * @param[in] key
3274  *   Key argument to verify.
3275  * @param[in] val
3276  *   Value associated with key.
3277  * @param[in, out] conf
3278  *   Shared configuration data.
3279  *
3280  * @return
3281  *   0 on success, negative errno value otherwise and rte_errno is set.
3282  */
3283 static int
3284 mlx4_arg_parse(const char *key, const char *val, struct mlx4_conf *conf)
3285 {
3286         unsigned long tmp;
3287
3288         errno = 0;
3289         tmp = strtoul(val, NULL, 0);
3290         if (errno) {
3291                 rte_errno = errno;
3292                 WARN("%s: \"%s\" is not a valid integer", key, val);
3293                 return -rte_errno;
3294         }
3295         if (strcmp(MLX4_PMD_PORT_KVARG, key) == 0) {
3296                 uint32_t ports = rte_log2_u32(conf->ports.present);
3297
3298                 if (tmp >= ports) {
3299                         ERROR("port index %lu outside range [0,%" PRIu32 ")",
3300                               tmp, ports);
3301                         return -EINVAL;
3302                 }
3303                 if (!(conf->ports.present & (1 << tmp))) {
3304                         rte_errno = EINVAL;
3305                         ERROR("invalid port index %lu", tmp);
3306                         return -rte_errno;
3307                 }
3308                 conf->ports.enabled |= 1 << tmp;
3309         } else {
3310                 rte_errno = EINVAL;
3311                 WARN("%s: unknown parameter", key);
3312                 return -rte_errno;
3313         }
3314         return 0;
3315 }
3316
3317 /**
3318  * Parse device parameters.
3319  *
3320  * @param devargs
3321  *   Device arguments structure.
3322  *
3323  * @return
3324  *   0 on success, negative errno value otherwise and rte_errno is set.
3325  */
3326 static int
3327 mlx4_args(struct rte_devargs *devargs, struct mlx4_conf *conf)
3328 {
3329         struct rte_kvargs *kvlist;
3330         unsigned int arg_count;
3331         int ret = 0;
3332         int i;
3333
3334         if (devargs == NULL)
3335                 return 0;
3336         kvlist = rte_kvargs_parse(devargs->args, pmd_mlx4_init_params);
3337         if (kvlist == NULL) {
3338                 rte_errno = EINVAL;
3339                 ERROR("failed to parse kvargs");
3340                 return -rte_errno;
3341         }
3342         /* Process parameters. */
3343         for (i = 0; pmd_mlx4_init_params[i]; ++i) {
3344                 arg_count = rte_kvargs_count(kvlist, MLX4_PMD_PORT_KVARG);
3345                 while (arg_count-- > 0) {
3346                         ret = rte_kvargs_process(kvlist,
3347                                                  MLX4_PMD_PORT_KVARG,
3348                                                  (int (*)(const char *,
3349                                                           const char *,
3350                                                           void *))
3351                                                  mlx4_arg_parse,
3352                                                  conf);
3353                         if (ret != 0)
3354                                 goto free_kvlist;
3355                 }
3356         }
3357 free_kvlist:
3358         rte_kvargs_free(kvlist);
3359         return ret;
3360 }
3361
3362 static struct rte_pci_driver mlx4_driver;
3363
3364 /**
3365  * DPDK callback to register a PCI device.
3366  *
3367  * This function creates an Ethernet device for each port of a given
3368  * PCI device.
3369  *
3370  * @param[in] pci_drv
3371  *   PCI driver structure (mlx4_driver).
3372  * @param[in] pci_dev
3373  *   PCI device information.
3374  *
3375  * @return
3376  *   0 on success, negative errno value otherwise and rte_errno is set.
3377  */
3378 static int
3379 mlx4_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
3380 {
3381         struct ibv_device **list;
3382         struct ibv_device *ibv_dev;
3383         int err = 0;
3384         struct ibv_context *attr_ctx = NULL;
3385         struct ibv_device_attr device_attr;
3386         struct mlx4_conf conf = {
3387                 .ports.present = 0,
3388         };
3389         unsigned int vf;
3390         int i;
3391
3392         (void)pci_drv;
3393         assert(pci_drv == &mlx4_driver);
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         DEBUG("device opened");
3445         if (ibv_query_device(attr_ctx, &device_attr)) {
3446                 rte_errno = ENODEV;
3447                 goto error;
3448         }
3449         INFO("%u port(s) detected", device_attr.phys_port_cnt);
3450         conf.ports.present |= (UINT64_C(1) << device_attr.phys_port_cnt) - 1;
3451         if (mlx4_args(pci_dev->device.devargs, &conf)) {
3452                 ERROR("failed to process device arguments");
3453                 rte_errno = EINVAL;
3454                 goto error;
3455         }
3456         /* Use all ports when none are defined */
3457         if (!conf.ports.enabled)
3458                 conf.ports.enabled = conf.ports.present;
3459         for (i = 0; i < device_attr.phys_port_cnt; i++) {
3460                 uint32_t port = i + 1; /* ports are indexed from one */
3461                 struct ibv_context *ctx = NULL;
3462                 struct ibv_port_attr port_attr;
3463                 struct ibv_pd *pd = NULL;
3464                 struct priv *priv = NULL;
3465                 struct rte_eth_dev *eth_dev = NULL;
3466                 struct ether_addr mac;
3467
3468                 /* If port is not enabled, skip. */
3469                 if (!(conf.ports.enabled & (1 << i)))
3470                         continue;
3471                 DEBUG("using port %u", port);
3472                 ctx = ibv_open_device(ibv_dev);
3473                 if (ctx == NULL) {
3474                         rte_errno = ENODEV;
3475                         goto port_error;
3476                 }
3477                 /* Check port status. */
3478                 err = ibv_query_port(ctx, port, &port_attr);
3479                 if (err) {
3480                         rte_errno = err;
3481                         ERROR("port query failed: %s", strerror(rte_errno));
3482                         goto port_error;
3483                 }
3484                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
3485                         rte_errno = ENOTSUP;
3486                         ERROR("port %d is not configured in Ethernet mode",
3487                               port);
3488                         goto port_error;
3489                 }
3490                 if (port_attr.state != IBV_PORT_ACTIVE)
3491                         DEBUG("port %d is not active: \"%s\" (%d)",
3492                               port, ibv_port_state_str(port_attr.state),
3493                               port_attr.state);
3494                 /* Allocate protection domain. */
3495                 pd = ibv_alloc_pd(ctx);
3496                 if (pd == NULL) {
3497                         rte_errno = ENOMEM;
3498                         ERROR("PD allocation failure");
3499                         goto port_error;
3500                 }
3501                 /* from rte_ethdev.c */
3502                 priv = rte_zmalloc("ethdev private structure",
3503                                    sizeof(*priv),
3504                                    RTE_CACHE_LINE_SIZE);
3505                 if (priv == NULL) {
3506                         rte_errno = ENOMEM;
3507                         ERROR("priv allocation failure");
3508                         goto port_error;
3509                 }
3510                 priv->ctx = ctx;
3511                 priv->device_attr = device_attr;
3512                 priv->port = port;
3513                 priv->pd = pd;
3514                 priv->mtu = ETHER_MTU;
3515                 priv->vf = vf;
3516                 /* Configure the first MAC address by default. */
3517                 if (priv_get_mac(priv, &mac.addr_bytes)) {
3518                         ERROR("cannot get MAC address, is mlx4_en loaded?"
3519                               " (rte_errno: %s)", strerror(rte_errno));
3520                         goto port_error;
3521                 }
3522                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
3523                      priv->port,
3524                      mac.addr_bytes[0], mac.addr_bytes[1],
3525                      mac.addr_bytes[2], mac.addr_bytes[3],
3526                      mac.addr_bytes[4], mac.addr_bytes[5]);
3527                 /* Register MAC address. */
3528                 priv->mac = mac;
3529                 if (priv_mac_addr_add(priv))
3530                         goto port_error;
3531 #ifndef NDEBUG
3532                 {
3533                         char ifname[IF_NAMESIZE];
3534
3535                         if (priv_get_ifname(priv, &ifname) == 0)
3536                                 DEBUG("port %u ifname is \"%s\"",
3537                                       priv->port, ifname);
3538                         else
3539                                 DEBUG("port %u ifname is unknown", priv->port);
3540                 }
3541 #endif
3542                 /* Get actual MTU if possible. */
3543                 priv_get_mtu(priv, &priv->mtu);
3544                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
3545                 /* from rte_ethdev.c */
3546                 {
3547                         char name[RTE_ETH_NAME_MAX_LEN];
3548
3549                         snprintf(name, sizeof(name), "%s port %u",
3550                                  ibv_get_device_name(ibv_dev), port);
3551                         eth_dev = rte_eth_dev_allocate(name);
3552                 }
3553                 if (eth_dev == NULL) {
3554                         ERROR("can not allocate rte ethdev");
3555                         rte_errno = ENOMEM;
3556                         goto port_error;
3557                 }
3558                 eth_dev->data->dev_private = priv;
3559                 eth_dev->data->mac_addrs = &priv->mac;
3560                 eth_dev->device = &pci_dev->device;
3561                 rte_eth_copy_pci_info(eth_dev, pci_dev);
3562                 eth_dev->device->driver = &mlx4_driver.driver;
3563                 /*
3564                  * Copy and override interrupt handle to prevent it from
3565                  * being shared between all ethdev instances of a given PCI
3566                  * device. This is required to properly handle Rx interrupts
3567                  * on all ports.
3568                  */
3569                 priv->intr_handle_dev = *eth_dev->intr_handle;
3570                 eth_dev->intr_handle = &priv->intr_handle_dev;
3571                 priv->dev = eth_dev;
3572                 eth_dev->dev_ops = &mlx4_dev_ops;
3573                 eth_dev->data->dev_flags |= RTE_ETH_DEV_DETACHABLE;
3574                 /* Bring Ethernet device up. */
3575                 DEBUG("forcing Ethernet interface up");
3576                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
3577                 /* Update link status once if waiting for LSC. */
3578                 if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
3579                         mlx4_link_update(eth_dev, 0);
3580                 continue;
3581 port_error:
3582                 rte_free(priv);
3583                 if (pd)
3584                         claim_zero(ibv_dealloc_pd(pd));
3585                 if (ctx)
3586                         claim_zero(ibv_close_device(ctx));
3587                 if (eth_dev)
3588                         rte_eth_dev_release_port(eth_dev);
3589                 break;
3590         }
3591         if (i == device_attr.phys_port_cnt)
3592                 return 0;
3593         /*
3594          * XXX if something went wrong in the loop above, there is a resource
3595          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
3596          * long as the dpdk does not provide a way to deallocate a ethdev and a
3597          * way to enumerate the registered ethdevs to free the previous ones.
3598          */
3599 error:
3600         if (attr_ctx)
3601                 claim_zero(ibv_close_device(attr_ctx));
3602         if (list)
3603                 ibv_free_device_list(list);
3604         assert(rte_errno >= 0);
3605         return -rte_errno;
3606 }
3607
3608 static const struct rte_pci_id mlx4_pci_id_map[] = {
3609         {
3610                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3611                                PCI_DEVICE_ID_MELLANOX_CONNECTX3)
3612         },
3613         {
3614                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3615                                PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO)
3616         },
3617         {
3618                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3619                                PCI_DEVICE_ID_MELLANOX_CONNECTX3VF)
3620         },
3621         {
3622                 .vendor_id = 0
3623         }
3624 };
3625
3626 static struct rte_pci_driver mlx4_driver = {
3627         .driver = {
3628                 .name = MLX4_DRIVER_NAME
3629         },
3630         .id_table = mlx4_pci_id_map,
3631         .probe = mlx4_pci_probe,
3632         .drv_flags = RTE_PCI_DRV_INTR_LSC |
3633                      RTE_PCI_DRV_INTR_RMV,
3634 };
3635
3636 /**
3637  * Driver initialization routine.
3638  */
3639 RTE_INIT(rte_mlx4_pmd_init);
3640 static void
3641 rte_mlx4_pmd_init(void)
3642 {
3643         /*
3644          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
3645          * huge pages. Calling ibv_fork_init() during init allows
3646          * applications to use fork() safely for purposes other than
3647          * using this PMD, which is not supported in forked processes.
3648          */
3649         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
3650         ibv_fork_init();
3651         rte_pci_register(&mlx4_driver);
3652 }
3653
3654 RTE_PMD_EXPORT_NAME(net_mlx4, __COUNTER__);
3655 RTE_PMD_REGISTER_PCI_TABLE(net_mlx4, mlx4_pci_id_map);
3656 RTE_PMD_REGISTER_KMOD_DEP(net_mlx4,
3657         "* ib_uverbs & mlx4_en & mlx4_core & mlx4_ib");