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