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