net/mlx5: remove control path locks
[dpdk.git] / drivers / net / mlx5 / mlx5.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2015 6WIND S.A.
3  * Copyright 2015 Mellanox.
4  */
5
6 #include <stddef.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <assert.h>
10 #include <dlfcn.h>
11 #include <stdint.h>
12 #include <stdlib.h>
13 #include <errno.h>
14 #include <net/if.h>
15 #include <sys/mman.h>
16
17 /* Verbs header. */
18 /* ISO C doesn't support unnamed structs/unions, disabling -pedantic. */
19 #ifdef PEDANTIC
20 #pragma GCC diagnostic ignored "-Wpedantic"
21 #endif
22 #include <infiniband/verbs.h>
23 #ifdef PEDANTIC
24 #pragma GCC diagnostic error "-Wpedantic"
25 #endif
26
27 #include <rte_malloc.h>
28 #include <rte_ethdev_driver.h>
29 #include <rte_ethdev_pci.h>
30 #include <rte_pci.h>
31 #include <rte_bus_pci.h>
32 #include <rte_common.h>
33 #include <rte_config.h>
34 #include <rte_eal_memconfig.h>
35 #include <rte_kvargs.h>
36
37 #include "mlx5.h"
38 #include "mlx5_utils.h"
39 #include "mlx5_rxtx.h"
40 #include "mlx5_autoconf.h"
41 #include "mlx5_defs.h"
42 #include "mlx5_glue.h"
43
44 /* Device parameter to enable RX completion queue compression. */
45 #define MLX5_RXQ_CQE_COMP_EN "rxq_cqe_comp_en"
46
47 /* Device parameter to configure inline send. */
48 #define MLX5_TXQ_INLINE "txq_inline"
49
50 /*
51  * Device parameter to configure the number of TX queues threshold for
52  * enabling inline send.
53  */
54 #define MLX5_TXQS_MIN_INLINE "txqs_min_inline"
55
56 /* Device parameter to enable multi-packet send WQEs. */
57 #define MLX5_TXQ_MPW_EN "txq_mpw_en"
58
59 /* Device parameter to include 2 dsegs in the title WQEBB. */
60 #define MLX5_TXQ_MPW_HDR_DSEG_EN "txq_mpw_hdr_dseg_en"
61
62 /* Device parameter to limit the size of inlining packet. */
63 #define MLX5_TXQ_MAX_INLINE_LEN "txq_max_inline_len"
64
65 /* Device parameter to enable hardware Tx vector. */
66 #define MLX5_TX_VEC_EN "tx_vec_en"
67
68 /* Device parameter to enable hardware Rx vector. */
69 #define MLX5_RX_VEC_EN "rx_vec_en"
70
71 #ifndef HAVE_IBV_MLX5_MOD_MPW
72 #define MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED (1 << 2)
73 #define MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW (1 << 3)
74 #endif
75
76 #ifndef HAVE_IBV_MLX5_MOD_CQE_128B_COMP
77 #define MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP (1 << 4)
78 #endif
79
80 /**
81  * Retrieve integer value from environment variable.
82  *
83  * @param[in] name
84  *   Environment variable name.
85  *
86  * @return
87  *   Integer value, 0 if the variable is not set.
88  */
89 int
90 mlx5_getenv_int(const char *name)
91 {
92         const char *val = getenv(name);
93
94         if (val == NULL)
95                 return 0;
96         return atoi(val);
97 }
98
99 /**
100  * Verbs callback to allocate a memory. This function should allocate the space
101  * according to the size provided residing inside a huge page.
102  * Please note that all allocation must respect the alignment from libmlx5
103  * (i.e. currently sysconf(_SC_PAGESIZE)).
104  *
105  * @param[in] size
106  *   The size in bytes of the memory to allocate.
107  * @param[in] data
108  *   A pointer to the callback data.
109  *
110  * @return
111  *   a pointer to the allocate space.
112  */
113 static void *
114 mlx5_alloc_verbs_buf(size_t size, void *data)
115 {
116         struct priv *priv = data;
117         void *ret;
118         size_t alignment = sysconf(_SC_PAGESIZE);
119         unsigned int socket = SOCKET_ID_ANY;
120
121         if (priv->verbs_alloc_ctx.type == MLX5_VERBS_ALLOC_TYPE_TX_QUEUE) {
122                 const struct mlx5_txq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
123
124                 socket = ctrl->socket;
125         } else if (priv->verbs_alloc_ctx.type ==
126                    MLX5_VERBS_ALLOC_TYPE_RX_QUEUE) {
127                 const struct mlx5_rxq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
128
129                 socket = ctrl->socket;
130         }
131         assert(data != NULL);
132         ret = rte_malloc_socket(__func__, size, alignment, socket);
133         DEBUG("Extern alloc size: %lu, align: %lu: %p", size, alignment, ret);
134         return ret;
135 }
136
137 /**
138  * Verbs callback to free a memory.
139  *
140  * @param[in] ptr
141  *   A pointer to the memory to free.
142  * @param[in] data
143  *   A pointer to the callback data.
144  */
145 static void
146 mlx5_free_verbs_buf(void *ptr, void *data __rte_unused)
147 {
148         assert(data != NULL);
149         DEBUG("Extern free request: %p", ptr);
150         rte_free(ptr);
151 }
152
153 /**
154  * DPDK callback to close the device.
155  *
156  * Destroy all queues and objects, free memory.
157  *
158  * @param dev
159  *   Pointer to Ethernet device structure.
160  */
161 static void
162 mlx5_dev_close(struct rte_eth_dev *dev)
163 {
164         struct priv *priv = dev->data->dev_private;
165         unsigned int i;
166         int ret;
167
168         DEBUG("%p: closing device \"%s\"",
169               (void *)dev,
170               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
171         /* In case mlx5_dev_stop() has not been called. */
172         priv_dev_interrupt_handler_uninstall(priv, dev);
173         priv_dev_traffic_disable(priv, dev);
174         /* Prevent crashes when queues are still in use. */
175         dev->rx_pkt_burst = removed_rx_burst;
176         dev->tx_pkt_burst = removed_tx_burst;
177         if (priv->rxqs != NULL) {
178                 /* XXX race condition if mlx5_rx_burst() is still running. */
179                 usleep(1000);
180                 for (i = 0; (i != priv->rxqs_n); ++i)
181                         mlx5_priv_rxq_release(priv, i);
182                 priv->rxqs_n = 0;
183                 priv->rxqs = NULL;
184         }
185         if (priv->txqs != NULL) {
186                 /* XXX race condition if mlx5_tx_burst() is still running. */
187                 usleep(1000);
188                 for (i = 0; (i != priv->txqs_n); ++i)
189                         mlx5_priv_txq_release(priv, i);
190                 priv->txqs_n = 0;
191                 priv->txqs = NULL;
192         }
193         if (priv->pd != NULL) {
194                 assert(priv->ctx != NULL);
195                 claim_zero(mlx5_glue->dealloc_pd(priv->pd));
196                 claim_zero(mlx5_glue->close_device(priv->ctx));
197         } else
198                 assert(priv->ctx == NULL);
199         if (priv->rss_conf.rss_key != NULL)
200                 rte_free(priv->rss_conf.rss_key);
201         if (priv->reta_idx != NULL)
202                 rte_free(priv->reta_idx);
203         if (priv->primary_socket)
204                 priv_socket_uninit(priv);
205         ret = mlx5_priv_hrxq_ibv_verify(priv);
206         if (ret)
207                 WARN("%p: some Hash Rx queue still remain", (void *)priv);
208         ret = mlx5_priv_ind_table_ibv_verify(priv);
209         if (ret)
210                 WARN("%p: some Indirection table still remain", (void *)priv);
211         ret = mlx5_priv_rxq_ibv_verify(priv);
212         if (ret)
213                 WARN("%p: some Verbs Rx queue still remain", (void *)priv);
214         ret = mlx5_priv_rxq_verify(priv);
215         if (ret)
216                 WARN("%p: some Rx Queues still remain", (void *)priv);
217         ret = mlx5_priv_txq_ibv_verify(priv);
218         if (ret)
219                 WARN("%p: some Verbs Tx queue still remain", (void *)priv);
220         ret = mlx5_priv_txq_verify(priv);
221         if (ret)
222                 WARN("%p: some Tx Queues still remain", (void *)priv);
223         ret = priv_flow_verify(priv);
224         if (ret)
225                 WARN("%p: some flows still remain", (void *)priv);
226         ret = priv_mr_verify(priv);
227         if (ret)
228                 WARN("%p: some Memory Region still remain", (void *)priv);
229         memset(priv, 0, sizeof(*priv));
230 }
231
232 const struct eth_dev_ops mlx5_dev_ops = {
233         .dev_configure = mlx5_dev_configure,
234         .dev_start = mlx5_dev_start,
235         .dev_stop = mlx5_dev_stop,
236         .dev_set_link_down = mlx5_set_link_down,
237         .dev_set_link_up = mlx5_set_link_up,
238         .dev_close = mlx5_dev_close,
239         .promiscuous_enable = mlx5_promiscuous_enable,
240         .promiscuous_disable = mlx5_promiscuous_disable,
241         .allmulticast_enable = mlx5_allmulticast_enable,
242         .allmulticast_disable = mlx5_allmulticast_disable,
243         .link_update = mlx5_link_update,
244         .stats_get = mlx5_stats_get,
245         .stats_reset = mlx5_stats_reset,
246         .xstats_get = mlx5_xstats_get,
247         .xstats_reset = mlx5_xstats_reset,
248         .xstats_get_names = mlx5_xstats_get_names,
249         .dev_infos_get = mlx5_dev_infos_get,
250         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
251         .vlan_filter_set = mlx5_vlan_filter_set,
252         .rx_queue_setup = mlx5_rx_queue_setup,
253         .tx_queue_setup = mlx5_tx_queue_setup,
254         .rx_queue_release = mlx5_rx_queue_release,
255         .tx_queue_release = mlx5_tx_queue_release,
256         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
257         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
258         .mac_addr_remove = mlx5_mac_addr_remove,
259         .mac_addr_add = mlx5_mac_addr_add,
260         .mac_addr_set = mlx5_mac_addr_set,
261         .mtu_set = mlx5_dev_set_mtu,
262         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
263         .vlan_offload_set = mlx5_vlan_offload_set,
264         .reta_update = mlx5_dev_rss_reta_update,
265         .reta_query = mlx5_dev_rss_reta_query,
266         .rss_hash_update = mlx5_rss_hash_update,
267         .rss_hash_conf_get = mlx5_rss_hash_conf_get,
268         .filter_ctrl = mlx5_dev_filter_ctrl,
269         .rx_descriptor_status = mlx5_rx_descriptor_status,
270         .tx_descriptor_status = mlx5_tx_descriptor_status,
271         .rx_queue_intr_enable = mlx5_rx_intr_enable,
272         .rx_queue_intr_disable = mlx5_rx_intr_disable,
273         .is_removed = mlx5_is_removed,
274 };
275
276 static const struct eth_dev_ops mlx5_dev_sec_ops = {
277         .stats_get = mlx5_stats_get,
278         .stats_reset = mlx5_stats_reset,
279         .xstats_get = mlx5_xstats_get,
280         .xstats_reset = mlx5_xstats_reset,
281         .xstats_get_names = mlx5_xstats_get_names,
282         .dev_infos_get = mlx5_dev_infos_get,
283         .rx_descriptor_status = mlx5_rx_descriptor_status,
284         .tx_descriptor_status = mlx5_tx_descriptor_status,
285 };
286
287 /* Available operators in flow isolated mode. */
288 const struct eth_dev_ops mlx5_dev_ops_isolate = {
289         .dev_configure = mlx5_dev_configure,
290         .dev_start = mlx5_dev_start,
291         .dev_stop = mlx5_dev_stop,
292         .dev_set_link_down = mlx5_set_link_down,
293         .dev_set_link_up = mlx5_set_link_up,
294         .dev_close = mlx5_dev_close,
295         .link_update = mlx5_link_update,
296         .stats_get = mlx5_stats_get,
297         .stats_reset = mlx5_stats_reset,
298         .xstats_get = mlx5_xstats_get,
299         .xstats_reset = mlx5_xstats_reset,
300         .xstats_get_names = mlx5_xstats_get_names,
301         .dev_infos_get = mlx5_dev_infos_get,
302         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
303         .vlan_filter_set = mlx5_vlan_filter_set,
304         .rx_queue_setup = mlx5_rx_queue_setup,
305         .tx_queue_setup = mlx5_tx_queue_setup,
306         .rx_queue_release = mlx5_rx_queue_release,
307         .tx_queue_release = mlx5_tx_queue_release,
308         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
309         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
310         .mac_addr_remove = mlx5_mac_addr_remove,
311         .mac_addr_add = mlx5_mac_addr_add,
312         .mac_addr_set = mlx5_mac_addr_set,
313         .mtu_set = mlx5_dev_set_mtu,
314         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
315         .vlan_offload_set = mlx5_vlan_offload_set,
316         .filter_ctrl = mlx5_dev_filter_ctrl,
317         .rx_descriptor_status = mlx5_rx_descriptor_status,
318         .tx_descriptor_status = mlx5_tx_descriptor_status,
319         .rx_queue_intr_enable = mlx5_rx_intr_enable,
320         .rx_queue_intr_disable = mlx5_rx_intr_disable,
321         .is_removed = mlx5_is_removed,
322 };
323
324 static struct {
325         struct rte_pci_addr pci_addr; /* associated PCI address */
326         uint32_t ports; /* physical ports bitfield. */
327 } mlx5_dev[32];
328
329 /**
330  * Get device index in mlx5_dev[] from PCI bus address.
331  *
332  * @param[in] pci_addr
333  *   PCI bus address to look for.
334  *
335  * @return
336  *   mlx5_dev[] index on success, -1 on failure.
337  */
338 static int
339 mlx5_dev_idx(struct rte_pci_addr *pci_addr)
340 {
341         unsigned int i;
342         int ret = -1;
343
344         assert(pci_addr != NULL);
345         for (i = 0; (i != RTE_DIM(mlx5_dev)); ++i) {
346                 if ((mlx5_dev[i].pci_addr.domain == pci_addr->domain) &&
347                     (mlx5_dev[i].pci_addr.bus == pci_addr->bus) &&
348                     (mlx5_dev[i].pci_addr.devid == pci_addr->devid) &&
349                     (mlx5_dev[i].pci_addr.function == pci_addr->function))
350                         return i;
351                 if ((mlx5_dev[i].ports == 0) && (ret == -1))
352                         ret = i;
353         }
354         return ret;
355 }
356
357 /**
358  * Verify and store value for device argument.
359  *
360  * @param[in] key
361  *   Key argument to verify.
362  * @param[in] val
363  *   Value associated with key.
364  * @param opaque
365  *   User data.
366  *
367  * @return
368  *   0 on success, negative errno value on failure.
369  */
370 static int
371 mlx5_args_check(const char *key, const char *val, void *opaque)
372 {
373         struct mlx5_dev_config *config = opaque;
374         unsigned long tmp;
375
376         errno = 0;
377         tmp = strtoul(val, NULL, 0);
378         if (errno) {
379                 WARN("%s: \"%s\" is not a valid integer", key, val);
380                 return errno;
381         }
382         if (strcmp(MLX5_RXQ_CQE_COMP_EN, key) == 0) {
383                 config->cqe_comp = !!tmp;
384         } else if (strcmp(MLX5_TXQ_INLINE, key) == 0) {
385                 config->txq_inline = tmp;
386         } else if (strcmp(MLX5_TXQS_MIN_INLINE, key) == 0) {
387                 config->txqs_inline = tmp;
388         } else if (strcmp(MLX5_TXQ_MPW_EN, key) == 0) {
389                 config->mps = !!tmp ? config->mps : 0;
390         } else if (strcmp(MLX5_TXQ_MPW_HDR_DSEG_EN, key) == 0) {
391                 config->mpw_hdr_dseg = !!tmp;
392         } else if (strcmp(MLX5_TXQ_MAX_INLINE_LEN, key) == 0) {
393                 config->inline_max_packet_sz = tmp;
394         } else if (strcmp(MLX5_TX_VEC_EN, key) == 0) {
395                 config->tx_vec_en = !!tmp;
396         } else if (strcmp(MLX5_RX_VEC_EN, key) == 0) {
397                 config->rx_vec_en = !!tmp;
398         } else {
399                 WARN("%s: unknown parameter", key);
400                 return -EINVAL;
401         }
402         return 0;
403 }
404
405 /**
406  * Parse device parameters.
407  *
408  * @param config
409  *   Pointer to device configuration structure.
410  * @param devargs
411  *   Device arguments structure.
412  *
413  * @return
414  *   0 on success, errno value on failure.
415  */
416 static int
417 mlx5_args(struct mlx5_dev_config *config, struct rte_devargs *devargs)
418 {
419         const char **params = (const char *[]){
420                 MLX5_RXQ_CQE_COMP_EN,
421                 MLX5_TXQ_INLINE,
422                 MLX5_TXQS_MIN_INLINE,
423                 MLX5_TXQ_MPW_EN,
424                 MLX5_TXQ_MPW_HDR_DSEG_EN,
425                 MLX5_TXQ_MAX_INLINE_LEN,
426                 MLX5_TX_VEC_EN,
427                 MLX5_RX_VEC_EN,
428                 NULL,
429         };
430         struct rte_kvargs *kvlist;
431         int ret = 0;
432         int i;
433
434         if (devargs == NULL)
435                 return 0;
436         /* Following UGLY cast is done to pass checkpatch. */
437         kvlist = rte_kvargs_parse(devargs->args, params);
438         if (kvlist == NULL)
439                 return 0;
440         /* Process parameters. */
441         for (i = 0; (params[i] != NULL); ++i) {
442                 if (rte_kvargs_count(kvlist, params[i])) {
443                         ret = rte_kvargs_process(kvlist, params[i],
444                                                  mlx5_args_check, config);
445                         if (ret != 0) {
446                                 rte_kvargs_free(kvlist);
447                                 return ret;
448                         }
449                 }
450         }
451         rte_kvargs_free(kvlist);
452         return 0;
453 }
454
455 static struct rte_pci_driver mlx5_driver;
456
457 /*
458  * Reserved UAR address space for TXQ UAR(hw doorbell) mapping, process
459  * local resource used by both primary and secondary to avoid duplicate
460  * reservation.
461  * The space has to be available on both primary and secondary process,
462  * TXQ UAR maps to this area using fixed mmap w/o double check.
463  */
464 static void *uar_base;
465
466 /**
467  * Reserve UAR address space for primary process.
468  *
469  * @param[in] priv
470  *   Pointer to private structure.
471  *
472  * @return
473  *   0 on success, errno value on failure.
474  */
475 static int
476 priv_uar_init_primary(struct priv *priv)
477 {
478         void *addr = (void *)0;
479         int i;
480         const struct rte_mem_config *mcfg;
481         int ret;
482
483         if (uar_base) { /* UAR address space mapped. */
484                 priv->uar_base = uar_base;
485                 return 0;
486         }
487         /* find out lower bound of hugepage segments */
488         mcfg = rte_eal_get_configuration()->mem_config;
489         for (i = 0; i < RTE_MAX_MEMSEG && mcfg->memseg[i].addr; i++) {
490                 if (addr)
491                         addr = RTE_MIN(addr, mcfg->memseg[i].addr);
492                 else
493                         addr = mcfg->memseg[i].addr;
494         }
495         /* keep distance to hugepages to minimize potential conflicts. */
496         addr = RTE_PTR_SUB(addr, MLX5_UAR_OFFSET + MLX5_UAR_SIZE);
497         /* anonymous mmap, no real memory consumption. */
498         addr = mmap(addr, MLX5_UAR_SIZE,
499                     PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
500         if (addr == MAP_FAILED) {
501                 ERROR("Failed to reserve UAR address space, please adjust "
502                       "MLX5_UAR_SIZE or try --base-virtaddr");
503                 ret = ENOMEM;
504                 return ret;
505         }
506         /* Accept either same addr or a new addr returned from mmap if target
507          * range occupied.
508          */
509         INFO("Reserved UAR address space: %p", addr);
510         priv->uar_base = addr; /* for primary and secondary UAR re-mmap. */
511         uar_base = addr; /* process local, don't reserve again. */
512         return 0;
513 }
514
515 /**
516  * Reserve UAR address space for secondary process, align with
517  * primary process.
518  *
519  * @param[in] priv
520  *   Pointer to private structure.
521  *
522  * @return
523  *   0 on success, errno value on failure.
524  */
525 static int
526 priv_uar_init_secondary(struct priv *priv)
527 {
528         void *addr;
529         int ret;
530
531         assert(priv->uar_base);
532         if (uar_base) { /* already reserved. */
533                 assert(uar_base == priv->uar_base);
534                 return 0;
535         }
536         /* anonymous mmap, no real memory consumption. */
537         addr = mmap(priv->uar_base, MLX5_UAR_SIZE,
538                     PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
539         if (addr == MAP_FAILED) {
540                 ERROR("UAR mmap failed: %p size: %llu",
541                       priv->uar_base, MLX5_UAR_SIZE);
542                 ret = ENXIO;
543                 return ret;
544         }
545         if (priv->uar_base != addr) {
546                 ERROR("UAR address %p size %llu occupied, please adjust "
547                       "MLX5_UAR_OFFSET or try EAL parameter --base-virtaddr",
548                       priv->uar_base, MLX5_UAR_SIZE);
549                 ret = ENXIO;
550                 return ret;
551         }
552         uar_base = addr; /* process local, don't reserve again */
553         INFO("Reserved UAR address space: %p", addr);
554         return 0;
555 }
556
557 /**
558  * DPDK callback to register a PCI device.
559  *
560  * This function creates an Ethernet device for each port of a given
561  * PCI device.
562  *
563  * @param[in] pci_drv
564  *   PCI driver structure (mlx5_driver).
565  * @param[in] pci_dev
566  *   PCI device information.
567  *
568  * @return
569  *   0 on success, negative errno value on failure.
570  */
571 static int
572 mlx5_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
573                struct rte_pci_device *pci_dev)
574 {
575         struct ibv_device **list;
576         struct ibv_device *ibv_dev;
577         int err = 0;
578         struct ibv_context *attr_ctx = NULL;
579         struct ibv_device_attr_ex device_attr;
580         unsigned int mps;
581         unsigned int cqe_comp;
582         unsigned int tunnel_en = 0;
583         int idx;
584         int i;
585         struct mlx5dv_context attrs_out = {0};
586 #ifdef HAVE_IBV_DEVICE_COUNTERS_SET_SUPPORT
587         struct ibv_counter_set_description cs_desc;
588 #endif
589
590         assert(pci_drv == &mlx5_driver);
591         /* Get mlx5_dev[] index. */
592         idx = mlx5_dev_idx(&pci_dev->addr);
593         if (idx == -1) {
594                 ERROR("this driver cannot support any more adapters");
595                 return -ENOMEM;
596         }
597         DEBUG("using driver device index %d", idx);
598         /* Save PCI address. */
599         mlx5_dev[idx].pci_addr = pci_dev->addr;
600         list = mlx5_glue->get_device_list(&i);
601         if (list == NULL) {
602                 assert(errno);
603                 if (errno == ENOSYS)
604                         ERROR("cannot list devices, is ib_uverbs loaded?");
605                 return -errno;
606         }
607         assert(i >= 0);
608         /*
609          * For each listed device, check related sysfs entry against
610          * the provided PCI ID.
611          */
612         while (i != 0) {
613                 struct rte_pci_addr pci_addr;
614
615                 --i;
616                 DEBUG("checking device \"%s\"", list[i]->name);
617                 if (mlx5_ibv_device_to_pci_addr(list[i], &pci_addr))
618                         continue;
619                 if ((pci_dev->addr.domain != pci_addr.domain) ||
620                     (pci_dev->addr.bus != pci_addr.bus) ||
621                     (pci_dev->addr.devid != pci_addr.devid) ||
622                     (pci_dev->addr.function != pci_addr.function))
623                         continue;
624                 INFO("PCI information matches, using device \"%s\"",
625                      list[i]->name);
626                 attr_ctx = mlx5_glue->open_device(list[i]);
627                 err = errno;
628                 break;
629         }
630         if (attr_ctx == NULL) {
631                 mlx5_glue->free_device_list(list);
632                 switch (err) {
633                 case 0:
634                         ERROR("cannot access device, is mlx5_ib loaded?");
635                         return -ENODEV;
636                 case EINVAL:
637                         ERROR("cannot use device, are drivers up to date?");
638                         return -EINVAL;
639                 }
640                 assert(err > 0);
641                 return -err;
642         }
643         ibv_dev = list[i];
644         DEBUG("device opened");
645         /*
646          * Multi-packet send is supported by ConnectX-4 Lx PF as well
647          * as all ConnectX-5 devices.
648          */
649 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
650         attrs_out.comp_mask |= MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS;
651 #endif
652         mlx5_glue->dv_query_device(attr_ctx, &attrs_out);
653         if (attrs_out.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
654                 if (attrs_out.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
655                         DEBUG("Enhanced MPW is supported");
656                         mps = MLX5_MPW_ENHANCED;
657                 } else {
658                         DEBUG("MPW is supported");
659                         mps = MLX5_MPW;
660                 }
661         } else {
662                 DEBUG("MPW isn't supported");
663                 mps = MLX5_MPW_DISABLED;
664         }
665         if (RTE_CACHE_LINE_SIZE == 128 &&
666             !(attrs_out.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP))
667                 cqe_comp = 0;
668         else
669                 cqe_comp = 1;
670 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
671         if (attrs_out.comp_mask & MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS) {
672                 tunnel_en = ((attrs_out.tunnel_offloads_caps &
673                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN) &&
674                              (attrs_out.tunnel_offloads_caps &
675                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE));
676         }
677         DEBUG("Tunnel offloading is %ssupported", tunnel_en ? "" : "not ");
678 #else
679         WARN("Tunnel offloading disabled due to old OFED/rdma-core version");
680 #endif
681         if (mlx5_glue->query_device_ex(attr_ctx, NULL, &device_attr))
682                 goto error;
683         INFO("%u port(s) detected", device_attr.orig_attr.phys_port_cnt);
684         for (i = 0; i < device_attr.orig_attr.phys_port_cnt; i++) {
685                 char name[RTE_ETH_NAME_MAX_LEN];
686                 int len;
687                 uint32_t port = i + 1; /* ports are indexed from one */
688                 uint32_t test = (1 << i);
689                 struct ibv_context *ctx = NULL;
690                 struct ibv_port_attr port_attr;
691                 struct ibv_pd *pd = NULL;
692                 struct priv *priv = NULL;
693                 struct rte_eth_dev *eth_dev;
694                 struct ibv_device_attr_ex device_attr_ex;
695                 struct ether_addr mac;
696                 struct ibv_device_attr_ex device_attr;
697                 struct mlx5_dev_config config = {
698                         .cqe_comp = cqe_comp,
699                         .mps = mps,
700                         .tunnel_en = tunnel_en,
701                         .tx_vec_en = 1,
702                         .rx_vec_en = 1,
703                         .mpw_hdr_dseg = 0,
704                         .txq_inline = MLX5_ARG_UNSET,
705                         .txqs_inline = MLX5_ARG_UNSET,
706                         .inline_max_packet_sz = MLX5_ARG_UNSET,
707                 };
708
709                 len = snprintf(name, sizeof(name), PCI_PRI_FMT,
710                          pci_dev->addr.domain, pci_dev->addr.bus,
711                          pci_dev->addr.devid, pci_dev->addr.function);
712                 if (device_attr.orig_attr.phys_port_cnt > 1)
713                         snprintf(name + len, sizeof(name), " port %u", i);
714                 mlx5_dev[idx].ports |= test;
715                 if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
716                         eth_dev = rte_eth_dev_attach_secondary(name);
717                         if (eth_dev == NULL) {
718                                 ERROR("can not attach rte ethdev");
719                                 err = ENOMEM;
720                                 goto error;
721                         }
722                         eth_dev->device = &pci_dev->device;
723                         eth_dev->dev_ops = &mlx5_dev_sec_ops;
724                         priv = eth_dev->data->dev_private;
725                         err = priv_uar_init_secondary(priv);
726                         if (err < 0) {
727                                 err = -err;
728                                 goto error;
729                         }
730                         /* Receive command fd from primary process */
731                         err = priv_socket_connect(priv);
732                         if (err < 0) {
733                                 err = -err;
734                                 goto error;
735                         }
736                         /* Remap UAR for Tx queues. */
737                         err = priv_tx_uar_remap(priv, err);
738                         if (err)
739                                 goto error;
740                         /*
741                          * Ethdev pointer is still required as input since
742                          * the primary device is not accessible from the
743                          * secondary process.
744                          */
745                         eth_dev->rx_pkt_burst =
746                                 priv_select_rx_function(priv, eth_dev);
747                         eth_dev->tx_pkt_burst =
748                                 priv_select_tx_function(priv, eth_dev);
749                         continue;
750                 }
751                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
752                 ctx = mlx5_glue->open_device(ibv_dev);
753                 if (ctx == NULL) {
754                         err = ENODEV;
755                         goto port_error;
756                 }
757                 mlx5_glue->query_device_ex(ctx, NULL, &device_attr);
758                 /* Check port status. */
759                 err = mlx5_glue->query_port(ctx, port, &port_attr);
760                 if (err) {
761                         ERROR("port query failed: %s", strerror(err));
762                         goto port_error;
763                 }
764                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
765                         ERROR("port %d is not configured in Ethernet mode",
766                               port);
767                         err = EINVAL;
768                         goto port_error;
769                 }
770                 if (port_attr.state != IBV_PORT_ACTIVE)
771                         DEBUG("port %d is not active: \"%s\" (%d)",
772                               port, mlx5_glue->port_state_str(port_attr.state),
773                               port_attr.state);
774                 /* Allocate protection domain. */
775                 pd = mlx5_glue->alloc_pd(ctx);
776                 if (pd == NULL) {
777                         ERROR("PD allocation failure");
778                         err = ENOMEM;
779                         goto port_error;
780                 }
781                 mlx5_dev[idx].ports |= test;
782                 /* from rte_ethdev.c */
783                 priv = rte_zmalloc("ethdev private structure",
784                                    sizeof(*priv),
785                                    RTE_CACHE_LINE_SIZE);
786                 if (priv == NULL) {
787                         ERROR("priv allocation failure");
788                         err = ENOMEM;
789                         goto port_error;
790                 }
791                 priv->ctx = ctx;
792                 strncpy(priv->ibdev_path, priv->ctx->device->ibdev_path,
793                         sizeof(priv->ibdev_path));
794                 priv->device_attr = device_attr;
795                 priv->port = port;
796                 priv->pd = pd;
797                 priv->mtu = ETHER_MTU;
798                 err = mlx5_args(&config, pci_dev->device.devargs);
799                 if (err) {
800                         ERROR("failed to process device arguments: %s",
801                               strerror(err));
802                         goto port_error;
803                 }
804                 if (mlx5_glue->query_device_ex(ctx, NULL, &device_attr_ex)) {
805                         ERROR("ibv_query_device_ex() failed");
806                         goto port_error;
807                 }
808                 config.hw_csum = !!(device_attr_ex.device_cap_flags_ex &
809                                     IBV_DEVICE_RAW_IP_CSUM);
810                 DEBUG("checksum offloading is %ssupported",
811                       (config.hw_csum ? "" : "not "));
812 #ifdef HAVE_IBV_DEVICE_COUNTERS_SET_SUPPORT
813                 config.flow_counter_en = !!(device_attr.max_counter_sets);
814                 mlx5_glue->describe_counter_set(ctx, 0, &cs_desc);
815                 DEBUG("counter type = %d, num of cs = %ld, attributes = %d",
816                       cs_desc.counter_type, cs_desc.num_of_cs,
817                       cs_desc.attributes);
818 #endif
819                 config.ind_table_max_size =
820                         device_attr_ex.rss_caps.max_rwq_indirection_table_size;
821                 /* Remove this check once DPDK supports larger/variable
822                  * indirection tables. */
823                 if (config.ind_table_max_size >
824                                 (unsigned int)ETH_RSS_RETA_SIZE_512)
825                         config.ind_table_max_size = ETH_RSS_RETA_SIZE_512;
826                 DEBUG("maximum RX indirection table size is %u",
827                       config.ind_table_max_size);
828                 config.hw_vlan_strip = !!(device_attr_ex.raw_packet_caps &
829                                          IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
830                 DEBUG("VLAN stripping is %ssupported",
831                       (config.hw_vlan_strip ? "" : "not "));
832
833                 config.hw_fcs_strip = !!(device_attr_ex.raw_packet_caps &
834                                          IBV_RAW_PACKET_CAP_SCATTER_FCS);
835                 DEBUG("FCS stripping configuration is %ssupported",
836                       (config.hw_fcs_strip ? "" : "not "));
837
838 #ifdef HAVE_IBV_WQ_FLAG_RX_END_PADDING
839                 config.hw_padding = !!device_attr_ex.rx_pad_end_addr_align;
840 #endif
841                 DEBUG("hardware RX end alignment padding is %ssupported",
842                       (config.hw_padding ? "" : "not "));
843                 config.tso = ((device_attr_ex.tso_caps.max_tso > 0) &&
844                               (device_attr_ex.tso_caps.supported_qpts &
845                               (1 << IBV_QPT_RAW_PACKET)));
846                 if (config.tso)
847                         config.tso_max_payload_sz =
848                                         device_attr_ex.tso_caps.max_tso;
849                 if (config.mps && !mps) {
850                         ERROR("multi-packet send not supported on this device"
851                               " (" MLX5_TXQ_MPW_EN ")");
852                         err = ENOTSUP;
853                         goto port_error;
854                 }
855                 INFO("%sMPS is %s",
856                      config.mps == MLX5_MPW_ENHANCED ? "Enhanced " : "",
857                      config.mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
858                 if (config.cqe_comp && !cqe_comp) {
859                         WARN("Rx CQE compression isn't supported");
860                         config.cqe_comp = 0;
861                 }
862                 err = priv_uar_init_primary(priv);
863                 if (err)
864                         goto port_error;
865                 /* Configure the first MAC address by default. */
866                 if (priv_get_mac(priv, &mac.addr_bytes)) {
867                         ERROR("cannot get MAC address, is mlx5_en loaded?"
868                               " (errno: %s)", strerror(errno));
869                         err = ENODEV;
870                         goto port_error;
871                 }
872                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
873                      priv->port,
874                      mac.addr_bytes[0], mac.addr_bytes[1],
875                      mac.addr_bytes[2], mac.addr_bytes[3],
876                      mac.addr_bytes[4], mac.addr_bytes[5]);
877 #ifndef NDEBUG
878                 {
879                         char ifname[IF_NAMESIZE];
880
881                         if (priv_get_ifname(priv, &ifname) == 0)
882                                 DEBUG("port %u ifname is \"%s\"",
883                                       priv->port, ifname);
884                         else
885                                 DEBUG("port %u ifname is unknown", priv->port);
886                 }
887 #endif
888                 /* Get actual MTU if possible. */
889                 priv_get_mtu(priv, &priv->mtu);
890                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
891                 eth_dev = rte_eth_dev_allocate(name);
892                 if (eth_dev == NULL) {
893                         ERROR("can not allocate rte ethdev");
894                         err = ENOMEM;
895                         goto port_error;
896                 }
897                 eth_dev->data->dev_private = priv;
898                 eth_dev->data->mac_addrs = priv->mac;
899                 eth_dev->device = &pci_dev->device;
900                 rte_eth_copy_pci_info(eth_dev, pci_dev);
901                 eth_dev->device->driver = &mlx5_driver.driver;
902                 /*
903                  * Initialize burst functions to prevent crashes before link-up.
904                  */
905                 eth_dev->rx_pkt_burst = removed_rx_burst;
906                 eth_dev->tx_pkt_burst = removed_tx_burst;
907                 priv->dev = eth_dev;
908                 eth_dev->dev_ops = &mlx5_dev_ops;
909                 /* Register MAC address. */
910                 claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
911                 TAILQ_INIT(&priv->flows);
912                 TAILQ_INIT(&priv->ctrl_flows);
913                 /* Hint libmlx5 to use PMD allocator for data plane resources */
914                 struct mlx5dv_ctx_allocators alctr = {
915                         .alloc = &mlx5_alloc_verbs_buf,
916                         .free = &mlx5_free_verbs_buf,
917                         .data = priv,
918                 };
919                 mlx5_glue->dv_set_context_attr(ctx,
920                                                MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
921                                                (void *)((uintptr_t)&alctr));
922
923                 /* Bring Ethernet device up. */
924                 DEBUG("forcing Ethernet interface up");
925                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
926                 /* Store device configuration on private structure. */
927                 priv->config = config;
928                 continue;
929 port_error:
930                 if (priv)
931                         rte_free(priv);
932                 if (pd)
933                         claim_zero(mlx5_glue->dealloc_pd(pd));
934                 if (ctx)
935                         claim_zero(mlx5_glue->close_device(ctx));
936                 break;
937         }
938         /*
939          * XXX if something went wrong in the loop above, there is a resource
940          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
941          * long as the dpdk does not provide a way to deallocate a ethdev and a
942          * way to enumerate the registered ethdevs to free the previous ones.
943          */
944         /* no port found, complain */
945         if (!mlx5_dev[idx].ports) {
946                 err = ENODEV;
947                 goto error;
948         }
949 error:
950         if (attr_ctx)
951                 claim_zero(mlx5_glue->close_device(attr_ctx));
952         if (list)
953                 mlx5_glue->free_device_list(list);
954         assert(err >= 0);
955         return -err;
956 }
957
958 static const struct rte_pci_id mlx5_pci_id_map[] = {
959         {
960                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
961                                PCI_DEVICE_ID_MELLANOX_CONNECTX4)
962         },
963         {
964                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
965                                PCI_DEVICE_ID_MELLANOX_CONNECTX4VF)
966         },
967         {
968                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
969                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LX)
970         },
971         {
972                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
973                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF)
974         },
975         {
976                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
977                                PCI_DEVICE_ID_MELLANOX_CONNECTX5)
978         },
979         {
980                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
981                                PCI_DEVICE_ID_MELLANOX_CONNECTX5VF)
982         },
983         {
984                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
985                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EX)
986         },
987         {
988                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
989                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF)
990         },
991         {
992                 .vendor_id = 0
993         }
994 };
995
996 static struct rte_pci_driver mlx5_driver = {
997         .driver = {
998                 .name = MLX5_DRIVER_NAME
999         },
1000         .id_table = mlx5_pci_id_map,
1001         .probe = mlx5_pci_probe,
1002         .drv_flags = RTE_PCI_DRV_INTR_LSC | RTE_PCI_DRV_INTR_RMV,
1003 };
1004
1005 #ifdef RTE_LIBRTE_MLX5_DLOPEN_DEPS
1006
1007 /**
1008  * Suffix RTE_EAL_PMD_PATH with "-glue".
1009  *
1010  * This function performs a sanity check on RTE_EAL_PMD_PATH before
1011  * suffixing its last component.
1012  *
1013  * @param buf[out]
1014  *   Output buffer, should be large enough otherwise NULL is returned.
1015  * @param size
1016  *   Size of @p out.
1017  *
1018  * @return
1019  *   Pointer to @p buf or @p NULL in case suffix cannot be appended.
1020  */
1021 static char *
1022 mlx5_glue_path(char *buf, size_t size)
1023 {
1024         static const char *const bad[] = { "/", ".", "..", NULL };
1025         const char *path = RTE_EAL_PMD_PATH;
1026         size_t len = strlen(path);
1027         size_t off;
1028         int i;
1029
1030         while (len && path[len - 1] == '/')
1031                 --len;
1032         for (off = len; off && path[off - 1] != '/'; --off)
1033                 ;
1034         for (i = 0; bad[i]; ++i)
1035                 if (!strncmp(path + off, bad[i], (int)(len - off)))
1036                         goto error;
1037         i = snprintf(buf, size, "%.*s-glue", (int)len, path);
1038         if (i == -1 || (size_t)i >= size)
1039                 goto error;
1040         return buf;
1041 error:
1042         ERROR("unable to append \"-glue\" to last component of"
1043               " RTE_EAL_PMD_PATH (\"" RTE_EAL_PMD_PATH "\"),"
1044               " please re-configure DPDK");
1045         return NULL;
1046 }
1047
1048 /**
1049  * Initialization routine for run-time dependency on rdma-core.
1050  */
1051 static int
1052 mlx5_glue_init(void)
1053 {
1054         char glue_path[sizeof(RTE_EAL_PMD_PATH) - 1 + sizeof("-glue")];
1055         const char *path[] = {
1056                 /*
1057                  * A basic security check is necessary before trusting
1058                  * MLX5_GLUE_PATH, which may override RTE_EAL_PMD_PATH.
1059                  */
1060                 (geteuid() == getuid() && getegid() == getgid() ?
1061                  getenv("MLX5_GLUE_PATH") : NULL),
1062                 /*
1063                  * When RTE_EAL_PMD_PATH is set, use its glue-suffixed
1064                  * variant, otherwise let dlopen() look up libraries on its
1065                  * own.
1066                  */
1067                 (*RTE_EAL_PMD_PATH ?
1068                  mlx5_glue_path(glue_path, sizeof(glue_path)) : ""),
1069         };
1070         unsigned int i = 0;
1071         void *handle = NULL;
1072         void **sym;
1073         const char *dlmsg;
1074
1075         while (!handle && i != RTE_DIM(path)) {
1076                 const char *end;
1077                 size_t len;
1078                 int ret;
1079
1080                 if (!path[i]) {
1081                         ++i;
1082                         continue;
1083                 }
1084                 end = strpbrk(path[i], ":;");
1085                 if (!end)
1086                         end = path[i] + strlen(path[i]);
1087                 len = end - path[i];
1088                 ret = 0;
1089                 do {
1090                         char name[ret + 1];
1091
1092                         ret = snprintf(name, sizeof(name), "%.*s%s" MLX5_GLUE,
1093                                        (int)len, path[i],
1094                                        (!len || *(end - 1) == '/') ? "" : "/");
1095                         if (ret == -1)
1096                                 break;
1097                         if (sizeof(name) != (size_t)ret + 1)
1098                                 continue;
1099                         DEBUG("looking for rdma-core glue as \"%s\"", name);
1100                         handle = dlopen(name, RTLD_LAZY);
1101                         break;
1102                 } while (1);
1103                 path[i] = end + 1;
1104                 if (!*end)
1105                         ++i;
1106         }
1107         if (!handle) {
1108                 rte_errno = EINVAL;
1109                 dlmsg = dlerror();
1110                 if (dlmsg)
1111                         WARN("cannot load glue library: %s", dlmsg);
1112                 goto glue_error;
1113         }
1114         sym = dlsym(handle, "mlx5_glue");
1115         if (!sym || !*sym) {
1116                 rte_errno = EINVAL;
1117                 dlmsg = dlerror();
1118                 if (dlmsg)
1119                         ERROR("cannot resolve glue symbol: %s", dlmsg);
1120                 goto glue_error;
1121         }
1122         mlx5_glue = *sym;
1123         return 0;
1124 glue_error:
1125         if (handle)
1126                 dlclose(handle);
1127         WARN("cannot initialize PMD due to missing run-time"
1128              " dependency on rdma-core libraries (libibverbs,"
1129              " libmlx5)");
1130         return -rte_errno;
1131 }
1132
1133 #endif
1134
1135 /**
1136  * Driver initialization routine.
1137  */
1138 RTE_INIT(rte_mlx5_pmd_init);
1139 static void
1140 rte_mlx5_pmd_init(void)
1141 {
1142         /* Build the static table for ptype conversion. */
1143         mlx5_set_ptype_table();
1144         /*
1145          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
1146          * huge pages. Calling ibv_fork_init() during init allows
1147          * applications to use fork() safely for purposes other than
1148          * using this PMD, which is not supported in forked processes.
1149          */
1150         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
1151         /* Match the size of Rx completion entry to the size of a cacheline. */
1152         if (RTE_CACHE_LINE_SIZE == 128)
1153                 setenv("MLX5_CQE_SIZE", "128", 0);
1154 #ifdef RTE_LIBRTE_MLX5_DLOPEN_DEPS
1155         if (mlx5_glue_init())
1156                 return;
1157         assert(mlx5_glue);
1158 #endif
1159 #ifndef NDEBUG
1160         /* Glue structure must not contain any NULL pointers. */
1161         {
1162                 unsigned int i;
1163
1164                 for (i = 0; i != sizeof(*mlx5_glue) / sizeof(void *); ++i)
1165                         assert(((const void *const *)mlx5_glue)[i]);
1166         }
1167 #endif
1168         if (strcmp(mlx5_glue->version, MLX5_GLUE_VERSION)) {
1169                 ERROR("rdma-core glue \"%s\" mismatch: \"%s\" is required",
1170                       mlx5_glue->version, MLX5_GLUE_VERSION);
1171                 return;
1172         }
1173         mlx5_glue->fork_init();
1174         rte_pci_register(&mlx5_driver);
1175 }
1176
1177 RTE_PMD_EXPORT_NAME(net_mlx5, __COUNTER__);
1178 RTE_PMD_REGISTER_PCI_TABLE(net_mlx5, mlx5_pci_id_map);
1179 RTE_PMD_REGISTER_KMOD_DEP(net_mlx5, "* ib_uverbs & mlx5_core & mlx5_ib");