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