net/mlx5: add port representor awareness
[dpdk.git] / drivers / net / mlx5 / mlx5.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2015 6WIND S.A.
3  * Copyright 2015 Mellanox Technologies, Ltd
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 #include <linux/netlink.h>
17 #include <linux/rtnetlink.h>
18
19 /* Verbs header. */
20 /* ISO C doesn't support unnamed structs/unions, disabling -pedantic. */
21 #ifdef PEDANTIC
22 #pragma GCC diagnostic ignored "-Wpedantic"
23 #endif
24 #include <infiniband/verbs.h>
25 #ifdef PEDANTIC
26 #pragma GCC diagnostic error "-Wpedantic"
27 #endif
28
29 #include <rte_malloc.h>
30 #include <rte_ethdev_driver.h>
31 #include <rte_ethdev_pci.h>
32 #include <rte_pci.h>
33 #include <rte_bus_pci.h>
34 #include <rte_common.h>
35 #include <rte_config.h>
36 #include <rte_eal_memconfig.h>
37 #include <rte_kvargs.h>
38 #include <rte_rwlock.h>
39 #include <rte_spinlock.h>
40 #include <rte_string_fns.h>
41
42 #include "mlx5.h"
43 #include "mlx5_utils.h"
44 #include "mlx5_rxtx.h"
45 #include "mlx5_autoconf.h"
46 #include "mlx5_defs.h"
47 #include "mlx5_glue.h"
48 #include "mlx5_mr.h"
49
50 /* Device parameter to enable RX completion queue compression. */
51 #define MLX5_RXQ_CQE_COMP_EN "rxq_cqe_comp_en"
52
53 /* Device parameter to enable Multi-Packet Rx queue. */
54 #define MLX5_RX_MPRQ_EN "mprq_en"
55
56 /* Device parameter to configure log 2 of the number of strides for MPRQ. */
57 #define MLX5_RX_MPRQ_LOG_STRIDE_NUM "mprq_log_stride_num"
58
59 /* Device parameter to limit the size of memcpy'd packet for MPRQ. */
60 #define MLX5_RX_MPRQ_MAX_MEMCPY_LEN "mprq_max_memcpy_len"
61
62 /* Device parameter to set the minimum number of Rx queues to enable MPRQ. */
63 #define MLX5_RXQS_MIN_MPRQ "rxqs_min_mprq"
64
65 /* Device parameter to configure inline send. */
66 #define MLX5_TXQ_INLINE "txq_inline"
67
68 /*
69  * Device parameter to configure the number of TX queues threshold for
70  * enabling inline send.
71  */
72 #define MLX5_TXQS_MIN_INLINE "txqs_min_inline"
73
74 /* Device parameter to enable multi-packet send WQEs. */
75 #define MLX5_TXQ_MPW_EN "txq_mpw_en"
76
77 /* Device parameter to include 2 dsegs in the title WQEBB. */
78 #define MLX5_TXQ_MPW_HDR_DSEG_EN "txq_mpw_hdr_dseg_en"
79
80 /* Device parameter to limit the size of inlining packet. */
81 #define MLX5_TXQ_MAX_INLINE_LEN "txq_max_inline_len"
82
83 /* Device parameter to enable hardware Tx vector. */
84 #define MLX5_TX_VEC_EN "tx_vec_en"
85
86 /* Device parameter to enable hardware Rx vector. */
87 #define MLX5_RX_VEC_EN "rx_vec_en"
88
89 /* Allow L3 VXLAN flow creation. */
90 #define MLX5_L3_VXLAN_EN "l3_vxlan_en"
91
92 /* Activate Netlink support in VF mode. */
93 #define MLX5_VF_NL_EN "vf_nl_en"
94
95 #ifndef HAVE_IBV_MLX5_MOD_MPW
96 #define MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED (1 << 2)
97 #define MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW (1 << 3)
98 #endif
99
100 #ifndef HAVE_IBV_MLX5_MOD_CQE_128B_COMP
101 #define MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP (1 << 4)
102 #endif
103
104 static const char *MZ_MLX5_PMD_SHARED_DATA = "mlx5_pmd_shared_data";
105
106 /* Shared memory between primary and secondary processes. */
107 struct mlx5_shared_data *mlx5_shared_data;
108
109 /* Spinlock for mlx5_shared_data allocation. */
110 static rte_spinlock_t mlx5_shared_data_lock = RTE_SPINLOCK_INITIALIZER;
111
112 /** Driver-specific log messages type. */
113 int mlx5_logtype;
114
115 /**
116  * Prepare shared data between primary and secondary process.
117  */
118 static void
119 mlx5_prepare_shared_data(void)
120 {
121         const struct rte_memzone *mz;
122
123         rte_spinlock_lock(&mlx5_shared_data_lock);
124         if (mlx5_shared_data == NULL) {
125                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
126                         /* Allocate shared memory. */
127                         mz = rte_memzone_reserve(MZ_MLX5_PMD_SHARED_DATA,
128                                                  sizeof(*mlx5_shared_data),
129                                                  SOCKET_ID_ANY, 0);
130                 } else {
131                         /* Lookup allocated shared memory. */
132                         mz = rte_memzone_lookup(MZ_MLX5_PMD_SHARED_DATA);
133                 }
134                 if (mz == NULL)
135                         rte_panic("Cannot allocate mlx5 shared data\n");
136                 mlx5_shared_data = mz->addr;
137                 /* Initialize shared data. */
138                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
139                         LIST_INIT(&mlx5_shared_data->mem_event_cb_list);
140                         rte_rwlock_init(&mlx5_shared_data->mem_event_rwlock);
141                 }
142                 rte_mem_event_callback_register("MLX5_MEM_EVENT_CB",
143                                                 mlx5_mr_mem_event_cb, NULL);
144         }
145         rte_spinlock_unlock(&mlx5_shared_data_lock);
146 }
147
148 /**
149  * Retrieve integer value from environment variable.
150  *
151  * @param[in] name
152  *   Environment variable name.
153  *
154  * @return
155  *   Integer value, 0 if the variable is not set.
156  */
157 int
158 mlx5_getenv_int(const char *name)
159 {
160         const char *val = getenv(name);
161
162         if (val == NULL)
163                 return 0;
164         return atoi(val);
165 }
166
167 /**
168  * Verbs callback to allocate a memory. This function should allocate the space
169  * according to the size provided residing inside a huge page.
170  * Please note that all allocation must respect the alignment from libmlx5
171  * (i.e. currently sysconf(_SC_PAGESIZE)).
172  *
173  * @param[in] size
174  *   The size in bytes of the memory to allocate.
175  * @param[in] data
176  *   A pointer to the callback data.
177  *
178  * @return
179  *   Allocated buffer, NULL otherwise and rte_errno is set.
180  */
181 static void *
182 mlx5_alloc_verbs_buf(size_t size, void *data)
183 {
184         struct priv *priv = data;
185         void *ret;
186         size_t alignment = sysconf(_SC_PAGESIZE);
187         unsigned int socket = SOCKET_ID_ANY;
188
189         if (priv->verbs_alloc_ctx.type == MLX5_VERBS_ALLOC_TYPE_TX_QUEUE) {
190                 const struct mlx5_txq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
191
192                 socket = ctrl->socket;
193         } else if (priv->verbs_alloc_ctx.type ==
194                    MLX5_VERBS_ALLOC_TYPE_RX_QUEUE) {
195                 const struct mlx5_rxq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
196
197                 socket = ctrl->socket;
198         }
199         assert(data != NULL);
200         ret = rte_malloc_socket(__func__, size, alignment, socket);
201         if (!ret && size)
202                 rte_errno = ENOMEM;
203         return ret;
204 }
205
206 /**
207  * Verbs callback to free a memory.
208  *
209  * @param[in] ptr
210  *   A pointer to the memory to free.
211  * @param[in] data
212  *   A pointer to the callback data.
213  */
214 static void
215 mlx5_free_verbs_buf(void *ptr, void *data __rte_unused)
216 {
217         assert(data != NULL);
218         rte_free(ptr);
219 }
220
221 /**
222  * DPDK callback to close the device.
223  *
224  * Destroy all queues and objects, free memory.
225  *
226  * @param dev
227  *   Pointer to Ethernet device structure.
228  */
229 static void
230 mlx5_dev_close(struct rte_eth_dev *dev)
231 {
232         struct priv *priv = dev->data->dev_private;
233         unsigned int i;
234         int ret;
235
236         DRV_LOG(DEBUG, "port %u closing device \"%s\"",
237                 dev->data->port_id,
238                 ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
239         /* In case mlx5_dev_stop() has not been called. */
240         mlx5_dev_interrupt_handler_uninstall(dev);
241         mlx5_traffic_disable(dev);
242         /* Prevent crashes when queues are still in use. */
243         dev->rx_pkt_burst = removed_rx_burst;
244         dev->tx_pkt_burst = removed_tx_burst;
245         if (priv->rxqs != NULL) {
246                 /* XXX race condition if mlx5_rx_burst() is still running. */
247                 usleep(1000);
248                 for (i = 0; (i != priv->rxqs_n); ++i)
249                         mlx5_rxq_release(dev, i);
250                 priv->rxqs_n = 0;
251                 priv->rxqs = NULL;
252         }
253         if (priv->txqs != NULL) {
254                 /* XXX race condition if mlx5_tx_burst() is still running. */
255                 usleep(1000);
256                 for (i = 0; (i != priv->txqs_n); ++i)
257                         mlx5_txq_release(dev, i);
258                 priv->txqs_n = 0;
259                 priv->txqs = NULL;
260         }
261         mlx5_flow_delete_drop_queue(dev);
262         mlx5_mprq_free_mp(dev);
263         mlx5_mr_release(dev);
264         if (priv->pd != NULL) {
265                 assert(priv->ctx != NULL);
266                 claim_zero(mlx5_glue->dealloc_pd(priv->pd));
267                 claim_zero(mlx5_glue->close_device(priv->ctx));
268         } else
269                 assert(priv->ctx == NULL);
270         if (priv->rss_conf.rss_key != NULL)
271                 rte_free(priv->rss_conf.rss_key);
272         if (priv->reta_idx != NULL)
273                 rte_free(priv->reta_idx);
274         if (priv->primary_socket)
275                 mlx5_socket_uninit(dev);
276         if (priv->config.vf)
277                 mlx5_nl_mac_addr_flush(dev);
278         if (priv->nl_socket_route >= 0)
279                 close(priv->nl_socket_route);
280         if (priv->nl_socket_rdma >= 0)
281                 close(priv->nl_socket_rdma);
282         ret = mlx5_hrxq_ibv_verify(dev);
283         if (ret)
284                 DRV_LOG(WARNING, "port %u some hash Rx queue still remain",
285                         dev->data->port_id);
286         ret = mlx5_ind_table_ibv_verify(dev);
287         if (ret)
288                 DRV_LOG(WARNING, "port %u some indirection table still remain",
289                         dev->data->port_id);
290         ret = mlx5_rxq_ibv_verify(dev);
291         if (ret)
292                 DRV_LOG(WARNING, "port %u some Verbs Rx queue still remain",
293                         dev->data->port_id);
294         ret = mlx5_rxq_verify(dev);
295         if (ret)
296                 DRV_LOG(WARNING, "port %u some Rx queues still remain",
297                         dev->data->port_id);
298         ret = mlx5_txq_ibv_verify(dev);
299         if (ret)
300                 DRV_LOG(WARNING, "port %u some Verbs Tx queue still remain",
301                         dev->data->port_id);
302         ret = mlx5_txq_verify(dev);
303         if (ret)
304                 DRV_LOG(WARNING, "port %u some Tx queues still remain",
305                         dev->data->port_id);
306         ret = mlx5_flow_verify(dev);
307         if (ret)
308                 DRV_LOG(WARNING, "port %u some flows still remain",
309                         dev->data->port_id);
310         memset(priv, 0, sizeof(*priv));
311 }
312
313 const struct eth_dev_ops mlx5_dev_ops = {
314         .dev_configure = mlx5_dev_configure,
315         .dev_start = mlx5_dev_start,
316         .dev_stop = mlx5_dev_stop,
317         .dev_set_link_down = mlx5_set_link_down,
318         .dev_set_link_up = mlx5_set_link_up,
319         .dev_close = mlx5_dev_close,
320         .promiscuous_enable = mlx5_promiscuous_enable,
321         .promiscuous_disable = mlx5_promiscuous_disable,
322         .allmulticast_enable = mlx5_allmulticast_enable,
323         .allmulticast_disable = mlx5_allmulticast_disable,
324         .link_update = mlx5_link_update,
325         .stats_get = mlx5_stats_get,
326         .stats_reset = mlx5_stats_reset,
327         .xstats_get = mlx5_xstats_get,
328         .xstats_reset = mlx5_xstats_reset,
329         .xstats_get_names = mlx5_xstats_get_names,
330         .dev_infos_get = mlx5_dev_infos_get,
331         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
332         .vlan_filter_set = mlx5_vlan_filter_set,
333         .rx_queue_setup = mlx5_rx_queue_setup,
334         .tx_queue_setup = mlx5_tx_queue_setup,
335         .rx_queue_release = mlx5_rx_queue_release,
336         .tx_queue_release = mlx5_tx_queue_release,
337         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
338         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
339         .mac_addr_remove = mlx5_mac_addr_remove,
340         .mac_addr_add = mlx5_mac_addr_add,
341         .mac_addr_set = mlx5_mac_addr_set,
342         .set_mc_addr_list = mlx5_set_mc_addr_list,
343         .mtu_set = mlx5_dev_set_mtu,
344         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
345         .vlan_offload_set = mlx5_vlan_offload_set,
346         .reta_update = mlx5_dev_rss_reta_update,
347         .reta_query = mlx5_dev_rss_reta_query,
348         .rss_hash_update = mlx5_rss_hash_update,
349         .rss_hash_conf_get = mlx5_rss_hash_conf_get,
350         .filter_ctrl = mlx5_dev_filter_ctrl,
351         .rx_descriptor_status = mlx5_rx_descriptor_status,
352         .tx_descriptor_status = mlx5_tx_descriptor_status,
353         .rx_queue_intr_enable = mlx5_rx_intr_enable,
354         .rx_queue_intr_disable = mlx5_rx_intr_disable,
355         .is_removed = mlx5_is_removed,
356 };
357
358 static const struct eth_dev_ops mlx5_dev_sec_ops = {
359         .stats_get = mlx5_stats_get,
360         .stats_reset = mlx5_stats_reset,
361         .xstats_get = mlx5_xstats_get,
362         .xstats_reset = mlx5_xstats_reset,
363         .xstats_get_names = mlx5_xstats_get_names,
364         .dev_infos_get = mlx5_dev_infos_get,
365         .rx_descriptor_status = mlx5_rx_descriptor_status,
366         .tx_descriptor_status = mlx5_tx_descriptor_status,
367 };
368
369 /* Available operators in flow isolated mode. */
370 const struct eth_dev_ops mlx5_dev_ops_isolate = {
371         .dev_configure = mlx5_dev_configure,
372         .dev_start = mlx5_dev_start,
373         .dev_stop = mlx5_dev_stop,
374         .dev_set_link_down = mlx5_set_link_down,
375         .dev_set_link_up = mlx5_set_link_up,
376         .dev_close = mlx5_dev_close,
377         .link_update = mlx5_link_update,
378         .stats_get = mlx5_stats_get,
379         .stats_reset = mlx5_stats_reset,
380         .xstats_get = mlx5_xstats_get,
381         .xstats_reset = mlx5_xstats_reset,
382         .xstats_get_names = mlx5_xstats_get_names,
383         .dev_infos_get = mlx5_dev_infos_get,
384         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
385         .vlan_filter_set = mlx5_vlan_filter_set,
386         .rx_queue_setup = mlx5_rx_queue_setup,
387         .tx_queue_setup = mlx5_tx_queue_setup,
388         .rx_queue_release = mlx5_rx_queue_release,
389         .tx_queue_release = mlx5_tx_queue_release,
390         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
391         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
392         .mac_addr_remove = mlx5_mac_addr_remove,
393         .mac_addr_add = mlx5_mac_addr_add,
394         .mac_addr_set = mlx5_mac_addr_set,
395         .set_mc_addr_list = mlx5_set_mc_addr_list,
396         .mtu_set = mlx5_dev_set_mtu,
397         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
398         .vlan_offload_set = mlx5_vlan_offload_set,
399         .filter_ctrl = mlx5_dev_filter_ctrl,
400         .rx_descriptor_status = mlx5_rx_descriptor_status,
401         .tx_descriptor_status = mlx5_tx_descriptor_status,
402         .rx_queue_intr_enable = mlx5_rx_intr_enable,
403         .rx_queue_intr_disable = mlx5_rx_intr_disable,
404         .is_removed = mlx5_is_removed,
405 };
406
407 /**
408  * Verify and store value for device argument.
409  *
410  * @param[in] key
411  *   Key argument to verify.
412  * @param[in] val
413  *   Value associated with key.
414  * @param opaque
415  *   User data.
416  *
417  * @return
418  *   0 on success, a negative errno value otherwise and rte_errno is set.
419  */
420 static int
421 mlx5_args_check(const char *key, const char *val, void *opaque)
422 {
423         struct mlx5_dev_config *config = opaque;
424         unsigned long tmp;
425
426         errno = 0;
427         tmp = strtoul(val, NULL, 0);
428         if (errno) {
429                 rte_errno = errno;
430                 DRV_LOG(WARNING, "%s: \"%s\" is not a valid integer", key, val);
431                 return -rte_errno;
432         }
433         if (strcmp(MLX5_RXQ_CQE_COMP_EN, key) == 0) {
434                 config->cqe_comp = !!tmp;
435         } else if (strcmp(MLX5_RX_MPRQ_EN, key) == 0) {
436                 config->mprq.enabled = !!tmp;
437         } else if (strcmp(MLX5_RX_MPRQ_LOG_STRIDE_NUM, key) == 0) {
438                 config->mprq.stride_num_n = tmp;
439         } else if (strcmp(MLX5_RX_MPRQ_MAX_MEMCPY_LEN, key) == 0) {
440                 config->mprq.max_memcpy_len = tmp;
441         } else if (strcmp(MLX5_RXQS_MIN_MPRQ, key) == 0) {
442                 config->mprq.min_rxqs_num = tmp;
443         } else if (strcmp(MLX5_TXQ_INLINE, key) == 0) {
444                 config->txq_inline = tmp;
445         } else if (strcmp(MLX5_TXQS_MIN_INLINE, key) == 0) {
446                 config->txqs_inline = tmp;
447         } else if (strcmp(MLX5_TXQ_MPW_EN, key) == 0) {
448                 config->mps = !!tmp ? config->mps : 0;
449         } else if (strcmp(MLX5_TXQ_MPW_HDR_DSEG_EN, key) == 0) {
450                 config->mpw_hdr_dseg = !!tmp;
451         } else if (strcmp(MLX5_TXQ_MAX_INLINE_LEN, key) == 0) {
452                 config->inline_max_packet_sz = tmp;
453         } else if (strcmp(MLX5_TX_VEC_EN, key) == 0) {
454                 config->tx_vec_en = !!tmp;
455         } else if (strcmp(MLX5_RX_VEC_EN, key) == 0) {
456                 config->rx_vec_en = !!tmp;
457         } else if (strcmp(MLX5_L3_VXLAN_EN, key) == 0) {
458                 config->l3_vxlan_en = !!tmp;
459         } else if (strcmp(MLX5_VF_NL_EN, key) == 0) {
460                 config->vf_nl_en = !!tmp;
461         } else {
462                 DRV_LOG(WARNING, "%s: unknown parameter", key);
463                 rte_errno = EINVAL;
464                 return -rte_errno;
465         }
466         return 0;
467 }
468
469 /**
470  * Parse device parameters.
471  *
472  * @param config
473  *   Pointer to device configuration structure.
474  * @param devargs
475  *   Device arguments structure.
476  *
477  * @return
478  *   0 on success, a negative errno value otherwise and rte_errno is set.
479  */
480 static int
481 mlx5_args(struct mlx5_dev_config *config, struct rte_devargs *devargs)
482 {
483         const char **params = (const char *[]){
484                 MLX5_RXQ_CQE_COMP_EN,
485                 MLX5_RX_MPRQ_EN,
486                 MLX5_RX_MPRQ_LOG_STRIDE_NUM,
487                 MLX5_RX_MPRQ_MAX_MEMCPY_LEN,
488                 MLX5_RXQS_MIN_MPRQ,
489                 MLX5_TXQ_INLINE,
490                 MLX5_TXQS_MIN_INLINE,
491                 MLX5_TXQ_MPW_EN,
492                 MLX5_TXQ_MPW_HDR_DSEG_EN,
493                 MLX5_TXQ_MAX_INLINE_LEN,
494                 MLX5_TX_VEC_EN,
495                 MLX5_RX_VEC_EN,
496                 MLX5_L3_VXLAN_EN,
497                 MLX5_VF_NL_EN,
498                 NULL,
499         };
500         struct rte_kvargs *kvlist;
501         int ret = 0;
502         int i;
503
504         if (devargs == NULL)
505                 return 0;
506         /* Following UGLY cast is done to pass checkpatch. */
507         kvlist = rte_kvargs_parse(devargs->args, params);
508         if (kvlist == NULL)
509                 return 0;
510         /* Process parameters. */
511         for (i = 0; (params[i] != NULL); ++i) {
512                 if (rte_kvargs_count(kvlist, params[i])) {
513                         ret = rte_kvargs_process(kvlist, params[i],
514                                                  mlx5_args_check, config);
515                         if (ret) {
516                                 rte_errno = EINVAL;
517                                 rte_kvargs_free(kvlist);
518                                 return -rte_errno;
519                         }
520                 }
521         }
522         rte_kvargs_free(kvlist);
523         return 0;
524 }
525
526 static struct rte_pci_driver mlx5_driver;
527
528 /*
529  * Reserved UAR address space for TXQ UAR(hw doorbell) mapping, process
530  * local resource used by both primary and secondary to avoid duplicate
531  * reservation.
532  * The space has to be available on both primary and secondary process,
533  * TXQ UAR maps to this area using fixed mmap w/o double check.
534  */
535 static void *uar_base;
536
537 static int
538 find_lower_va_bound(const struct rte_memseg_list *msl __rte_unused,
539                 const struct rte_memseg *ms, void *arg)
540 {
541         void **addr = arg;
542
543         if (*addr == NULL)
544                 *addr = ms->addr;
545         else
546                 *addr = RTE_MIN(*addr, ms->addr);
547
548         return 0;
549 }
550
551 /**
552  * Reserve UAR address space for primary process.
553  *
554  * @param[in] dev
555  *   Pointer to Ethernet device.
556  *
557  * @return
558  *   0 on success, a negative errno value otherwise and rte_errno is set.
559  */
560 static int
561 mlx5_uar_init_primary(struct rte_eth_dev *dev)
562 {
563         struct priv *priv = dev->data->dev_private;
564         void *addr = (void *)0;
565
566         if (uar_base) { /* UAR address space mapped. */
567                 priv->uar_base = uar_base;
568                 return 0;
569         }
570         /* find out lower bound of hugepage segments */
571         rte_memseg_walk(find_lower_va_bound, &addr);
572
573         /* keep distance to hugepages to minimize potential conflicts. */
574         addr = RTE_PTR_SUB(addr, MLX5_UAR_OFFSET + MLX5_UAR_SIZE);
575         /* anonymous mmap, no real memory consumption. */
576         addr = mmap(addr, MLX5_UAR_SIZE,
577                     PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
578         if (addr == MAP_FAILED) {
579                 DRV_LOG(ERR,
580                         "port %u failed to reserve UAR address space, please"
581                         " adjust MLX5_UAR_SIZE or try --base-virtaddr",
582                         dev->data->port_id);
583                 rte_errno = ENOMEM;
584                 return -rte_errno;
585         }
586         /* Accept either same addr or a new addr returned from mmap if target
587          * range occupied.
588          */
589         DRV_LOG(INFO, "port %u reserved UAR address space: %p",
590                 dev->data->port_id, addr);
591         priv->uar_base = addr; /* for primary and secondary UAR re-mmap. */
592         uar_base = addr; /* process local, don't reserve again. */
593         return 0;
594 }
595
596 /**
597  * Reserve UAR address space for secondary process, align with
598  * primary process.
599  *
600  * @param[in] dev
601  *   Pointer to Ethernet device.
602  *
603  * @return
604  *   0 on success, a negative errno value otherwise and rte_errno is set.
605  */
606 static int
607 mlx5_uar_init_secondary(struct rte_eth_dev *dev)
608 {
609         struct priv *priv = dev->data->dev_private;
610         void *addr;
611
612         assert(priv->uar_base);
613         if (uar_base) { /* already reserved. */
614                 assert(uar_base == priv->uar_base);
615                 return 0;
616         }
617         /* anonymous mmap, no real memory consumption. */
618         addr = mmap(priv->uar_base, MLX5_UAR_SIZE,
619                     PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
620         if (addr == MAP_FAILED) {
621                 DRV_LOG(ERR, "port %u UAR mmap failed: %p size: %llu",
622                         dev->data->port_id, priv->uar_base, MLX5_UAR_SIZE);
623                 rte_errno = ENXIO;
624                 return -rte_errno;
625         }
626         if (priv->uar_base != addr) {
627                 DRV_LOG(ERR,
628                         "port %u UAR address %p size %llu occupied, please"
629                         " adjust MLX5_UAR_OFFSET or try EAL parameter"
630                         " --base-virtaddr",
631                         dev->data->port_id, priv->uar_base, MLX5_UAR_SIZE);
632                 rte_errno = ENXIO;
633                 return -rte_errno;
634         }
635         uar_base = addr; /* process local, don't reserve again */
636         DRV_LOG(INFO, "port %u reserved UAR address space: %p",
637                 dev->data->port_id, addr);
638         return 0;
639 }
640
641 /**
642  * Spawn an Ethernet device from Verbs information.
643  *
644  * @param dpdk_dev
645  *   Backing DPDK device.
646  * @param ibv_dev
647  *   Verbs device.
648  * @param vf
649  *   If nonzero, enable VF-specific features.
650  *
651  * @return
652  *   A valid Ethernet device object on success, NULL otherwise and rte_errno
653  *   is set.
654  */
655 static struct rte_eth_dev *
656 mlx5_dev_spawn(struct rte_device *dpdk_dev,
657                struct ibv_device *ibv_dev,
658                int vf)
659 {
660         struct ibv_context *ctx;
661         struct ibv_device_attr_ex attr;
662         struct ibv_port_attr port_attr;
663         struct ibv_pd *pd = NULL;
664         struct mlx5dv_context dv_attr = { .comp_mask = 0 };
665         struct mlx5_dev_config config = {
666                 .vf = !!vf,
667                 .tx_vec_en = 1,
668                 .rx_vec_en = 1,
669                 .mpw_hdr_dseg = 0,
670                 .txq_inline = MLX5_ARG_UNSET,
671                 .txqs_inline = MLX5_ARG_UNSET,
672                 .inline_max_packet_sz = MLX5_ARG_UNSET,
673                 .vf_nl_en = 1,
674                 .mprq = {
675                         .enabled = 0,
676                         .stride_num_n = MLX5_MPRQ_STRIDE_NUM_N,
677                         .max_memcpy_len = MLX5_MPRQ_MEMCPY_DEFAULT_LEN,
678                         .min_rxqs_num = MLX5_MPRQ_MIN_RXQS,
679                 },
680         };
681         struct rte_eth_dev *eth_dev = NULL;
682         struct priv *priv = NULL;
683         int err = 0;
684         unsigned int mps;
685         unsigned int cqe_comp;
686         unsigned int tunnel_en = 0;
687         unsigned int mpls_en = 0;
688         unsigned int swp = 0;
689         unsigned int verb_priorities = 0;
690         unsigned int mprq = 0;
691         unsigned int mprq_min_stride_size_n = 0;
692         unsigned int mprq_max_stride_size_n = 0;
693         unsigned int mprq_min_stride_num_n = 0;
694         unsigned int mprq_max_stride_num_n = 0;
695 #ifdef HAVE_IBV_DEVICE_COUNTERS_SET_SUPPORT
696         struct ibv_counter_set_description cs_desc = { .counter_type = 0 };
697 #endif
698         struct ether_addr mac;
699         char name[RTE_ETH_NAME_MAX_LEN];
700
701         /* Prepare shared data between primary and secondary process. */
702         mlx5_prepare_shared_data();
703         errno = 0;
704         ctx = mlx5_glue->open_device(ibv_dev);
705         if (!ctx) {
706                 rte_errno = errno ? errno : ENODEV;
707                 return NULL;
708         }
709 #ifdef HAVE_IBV_MLX5_MOD_SWP
710         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_SWP;
711 #endif
712         /*
713          * Multi-packet send is supported by ConnectX-4 Lx PF as well
714          * as all ConnectX-5 devices.
715          */
716 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
717         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS;
718 #endif
719 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
720         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_STRIDING_RQ;
721 #endif
722         mlx5_glue->dv_query_device(ctx, &dv_attr);
723         if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
724                 if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
725                         DRV_LOG(DEBUG, "enhanced MPW is supported");
726                         mps = MLX5_MPW_ENHANCED;
727                 } else {
728                         DRV_LOG(DEBUG, "MPW is supported");
729                         mps = MLX5_MPW;
730                 }
731         } else {
732                 DRV_LOG(DEBUG, "MPW isn't supported");
733                 mps = MLX5_MPW_DISABLED;
734         }
735         config.mps = mps;
736 #ifdef HAVE_IBV_MLX5_MOD_SWP
737         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_SWP)
738                 swp = dv_attr.sw_parsing_caps.sw_parsing_offloads;
739         DRV_LOG(DEBUG, "SWP support: %u", swp);
740 #endif
741         config.swp = !!swp;
742 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
743         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_STRIDING_RQ) {
744                 struct mlx5dv_striding_rq_caps mprq_caps =
745                         dv_attr.striding_rq_caps;
746
747                 DRV_LOG(DEBUG, "\tmin_single_stride_log_num_of_bytes: %d",
748                         mprq_caps.min_single_stride_log_num_of_bytes);
749                 DRV_LOG(DEBUG, "\tmax_single_stride_log_num_of_bytes: %d",
750                         mprq_caps.max_single_stride_log_num_of_bytes);
751                 DRV_LOG(DEBUG, "\tmin_single_wqe_log_num_of_strides: %d",
752                         mprq_caps.min_single_wqe_log_num_of_strides);
753                 DRV_LOG(DEBUG, "\tmax_single_wqe_log_num_of_strides: %d",
754                         mprq_caps.max_single_wqe_log_num_of_strides);
755                 DRV_LOG(DEBUG, "\tsupported_qpts: %d",
756                         mprq_caps.supported_qpts);
757                 DRV_LOG(DEBUG, "device supports Multi-Packet RQ");
758                 mprq = 1;
759                 mprq_min_stride_size_n =
760                         mprq_caps.min_single_stride_log_num_of_bytes;
761                 mprq_max_stride_size_n =
762                         mprq_caps.max_single_stride_log_num_of_bytes;
763                 mprq_min_stride_num_n =
764                         mprq_caps.min_single_wqe_log_num_of_strides;
765                 mprq_max_stride_num_n =
766                         mprq_caps.max_single_wqe_log_num_of_strides;
767                 config.mprq.stride_num_n = RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
768                                                    mprq_min_stride_num_n);
769         }
770 #endif
771         if (RTE_CACHE_LINE_SIZE == 128 &&
772             !(dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP))
773                 cqe_comp = 0;
774         else
775                 cqe_comp = 1;
776         config.cqe_comp = cqe_comp;
777 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
778         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS) {
779                 tunnel_en = ((dv_attr.tunnel_offloads_caps &
780                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN) &&
781                              (dv_attr.tunnel_offloads_caps &
782                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE));
783         }
784         DRV_LOG(DEBUG, "tunnel offloading is %ssupported",
785                 tunnel_en ? "" : "not ");
786 #else
787         DRV_LOG(WARNING,
788                 "tunnel offloading disabled due to old OFED/rdma-core version");
789 #endif
790         config.tunnel_en = tunnel_en;
791 #ifdef HAVE_IBV_DEVICE_MPLS_SUPPORT
792         mpls_en = ((dv_attr.tunnel_offloads_caps &
793                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_GRE) &&
794                    (dv_attr.tunnel_offloads_caps &
795                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_UDP));
796         DRV_LOG(DEBUG, "MPLS over GRE/UDP tunnel offloading is %ssupported",
797                 mpls_en ? "" : "not ");
798 #else
799         DRV_LOG(WARNING, "MPLS over GRE/UDP tunnel offloading disabled due to"
800                 " old OFED/rdma-core version or firmware configuration");
801 #endif
802         config.mpls_en = mpls_en;
803         err = mlx5_glue->query_device_ex(ctx, NULL, &attr);
804         if (err) {
805                 DEBUG("ibv_query_device_ex() failed");
806                 goto error;
807         }
808         rte_strlcpy(name, dpdk_dev->name, sizeof(name));
809         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
810                 eth_dev = rte_eth_dev_attach_secondary(name);
811                 if (eth_dev == NULL) {
812                         DRV_LOG(ERR, "can not attach rte ethdev");
813                         rte_errno = ENOMEM;
814                         err = rte_errno;
815                         goto error;
816                 }
817                 eth_dev->device = dpdk_dev;
818                 eth_dev->dev_ops = &mlx5_dev_sec_ops;
819                 err = mlx5_uar_init_secondary(eth_dev);
820                 if (err) {
821                         err = rte_errno;
822                         goto error;
823                 }
824                 /* Receive command fd from primary process */
825                 err = mlx5_socket_connect(eth_dev);
826                 if (err < 0) {
827                         err = rte_errno;
828                         goto error;
829                 }
830                 /* Remap UAR for Tx queues. */
831                 err = mlx5_tx_uar_remap(eth_dev, err);
832                 if (err) {
833                         err = rte_errno;
834                         goto error;
835                 }
836                 /*
837                  * Ethdev pointer is still required as input since
838                  * the primary device is not accessible from the
839                  * secondary process.
840                  */
841                 eth_dev->rx_pkt_burst = mlx5_select_rx_function(eth_dev);
842                 eth_dev->tx_pkt_burst = mlx5_select_tx_function(eth_dev);
843                 claim_zero(mlx5_glue->close_device(ctx));
844                 return eth_dev;
845         }
846         /* Check port status. */
847         err = mlx5_glue->query_port(ctx, 1, &port_attr);
848         if (err) {
849                 DRV_LOG(ERR, "port query failed: %s", strerror(err));
850                 goto error;
851         }
852         if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
853                 DRV_LOG(ERR, "port is not configured in Ethernet mode");
854                 err = EINVAL;
855                 goto error;
856         }
857         if (port_attr.state != IBV_PORT_ACTIVE)
858                 DRV_LOG(DEBUG, "port is not active: \"%s\" (%d)",
859                         mlx5_glue->port_state_str(port_attr.state),
860                         port_attr.state);
861         /* Allocate protection domain. */
862         pd = mlx5_glue->alloc_pd(ctx);
863         if (pd == NULL) {
864                 DRV_LOG(ERR, "PD allocation failure");
865                 err = ENOMEM;
866                 goto error;
867         }
868         priv = rte_zmalloc("ethdev private structure",
869                            sizeof(*priv),
870                            RTE_CACHE_LINE_SIZE);
871         if (priv == NULL) {
872                 DRV_LOG(ERR, "priv allocation failure");
873                 err = ENOMEM;
874                 goto error;
875         }
876         priv->ctx = ctx;
877         strncpy(priv->ibdev_path, priv->ctx->device->ibdev_path,
878                 sizeof(priv->ibdev_path));
879         priv->device_attr = attr;
880         priv->pd = pd;
881         priv->mtu = ETHER_MTU;
882         /* Some internal functions rely on Netlink sockets, open them now. */
883         priv->nl_socket_rdma = mlx5_nl_init(0, NETLINK_RDMA);
884         priv->nl_socket_route = mlx5_nl_init(RTMGRP_LINK, NETLINK_ROUTE);
885         priv->nl_sn = 0;
886         err = mlx5_args(&config, dpdk_dev->devargs);
887         if (err) {
888                 err = rte_errno;
889                 DRV_LOG(ERR, "failed to process device arguments: %s",
890                         strerror(rte_errno));
891                 goto error;
892         }
893         config.hw_csum = !!(attr.device_cap_flags_ex & IBV_DEVICE_RAW_IP_CSUM);
894         DRV_LOG(DEBUG, "checksum offloading is %ssupported",
895                 (config.hw_csum ? "" : "not "));
896 #ifdef HAVE_IBV_DEVICE_COUNTERS_SET_SUPPORT
897         config.flow_counter_en = !!attr.max_counter_sets;
898         mlx5_glue->describe_counter_set(ctx, 0, &cs_desc);
899         DRV_LOG(DEBUG, "counter type = %d, num of cs = %ld, attributes = %d",
900                 cs_desc.counter_type, cs_desc.num_of_cs,
901                 cs_desc.attributes);
902 #endif
903         config.ind_table_max_size =
904                 attr.rss_caps.max_rwq_indirection_table_size;
905         /*
906          * Remove this check once DPDK supports larger/variable
907          * indirection tables.
908          */
909         if (config.ind_table_max_size > (unsigned int)ETH_RSS_RETA_SIZE_512)
910                 config.ind_table_max_size = ETH_RSS_RETA_SIZE_512;
911         DRV_LOG(DEBUG, "maximum Rx indirection table size is %u",
912                 config.ind_table_max_size);
913         config.hw_vlan_strip = !!(attr.raw_packet_caps &
914                                   IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
915         DRV_LOG(DEBUG, "VLAN stripping is %ssupported",
916                 (config.hw_vlan_strip ? "" : "not "));
917         config.hw_fcs_strip = !!(attr.raw_packet_caps &
918                                  IBV_RAW_PACKET_CAP_SCATTER_FCS);
919         DRV_LOG(DEBUG, "FCS stripping configuration is %ssupported",
920                 (config.hw_fcs_strip ? "" : "not "));
921 #ifdef HAVE_IBV_WQ_FLAG_RX_END_PADDING
922         config.hw_padding = !!attr.rx_pad_end_addr_align;
923 #endif
924         DRV_LOG(DEBUG, "hardware Rx end alignment padding is %ssupported",
925                 (config.hw_padding ? "" : "not "));
926         config.tso = (attr.tso_caps.max_tso > 0 &&
927                       (attr.tso_caps.supported_qpts &
928                        (1 << IBV_QPT_RAW_PACKET)));
929         if (config.tso)
930                 config.tso_max_payload_sz = attr.tso_caps.max_tso;
931         if (config.mps && !mps) {
932                 DRV_LOG(ERR,
933                         "multi-packet send not supported on this device"
934                         " (" MLX5_TXQ_MPW_EN ")");
935                 err = ENOTSUP;
936                 goto error;
937         }
938         DRV_LOG(INFO, "%sMPS is %s",
939                 config.mps == MLX5_MPW_ENHANCED ? "enhanced " : "",
940                 config.mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
941         if (config.cqe_comp && !cqe_comp) {
942                 DRV_LOG(WARNING, "Rx CQE compression isn't supported");
943                 config.cqe_comp = 0;
944         }
945         if (config.mprq.enabled && mprq) {
946                 if (config.mprq.stride_num_n > mprq_max_stride_num_n ||
947                     config.mprq.stride_num_n < mprq_min_stride_num_n) {
948                         config.mprq.stride_num_n =
949                                 RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
950                                         mprq_min_stride_num_n);
951                         DRV_LOG(WARNING,
952                                 "the number of strides"
953                                 " for Multi-Packet RQ is out of range,"
954                                 " setting default value (%u)",
955                                 1 << config.mprq.stride_num_n);
956                 }
957                 config.mprq.min_stride_size_n = mprq_min_stride_size_n;
958                 config.mprq.max_stride_size_n = mprq_max_stride_size_n;
959         } else if (config.mprq.enabled && !mprq) {
960                 DRV_LOG(WARNING, "Multi-Packet RQ isn't supported");
961                 config.mprq.enabled = 0;
962         }
963         eth_dev = rte_eth_dev_allocate(name);
964         if (eth_dev == NULL) {
965                 DRV_LOG(ERR, "can not allocate rte ethdev");
966                 err = ENOMEM;
967                 goto error;
968         }
969         eth_dev->data->dev_private = priv;
970         priv->dev_data = eth_dev->data;
971         eth_dev->data->mac_addrs = priv->mac;
972         eth_dev->device = dpdk_dev;
973         eth_dev->device->driver = &mlx5_driver.driver;
974         err = mlx5_uar_init_primary(eth_dev);
975         if (err) {
976                 err = rte_errno;
977                 goto error;
978         }
979         /* Configure the first MAC address by default. */
980         if (mlx5_get_mac(eth_dev, &mac.addr_bytes)) {
981                 DRV_LOG(ERR,
982                         "port %u cannot get MAC address, is mlx5_en"
983                         " loaded? (errno: %s)",
984                         eth_dev->data->port_id, strerror(rte_errno));
985                 err = ENODEV;
986                 goto error;
987         }
988         DRV_LOG(INFO,
989                 "port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
990                 eth_dev->data->port_id,
991                 mac.addr_bytes[0], mac.addr_bytes[1],
992                 mac.addr_bytes[2], mac.addr_bytes[3],
993                 mac.addr_bytes[4], mac.addr_bytes[5]);
994 #ifndef NDEBUG
995         {
996                 char ifname[IF_NAMESIZE];
997
998                 if (mlx5_get_ifname(eth_dev, &ifname) == 0)
999                         DRV_LOG(DEBUG, "port %u ifname is \"%s\"",
1000                                 eth_dev->data->port_id, ifname);
1001                 else
1002                         DRV_LOG(DEBUG, "port %u ifname is unknown",
1003                                 eth_dev->data->port_id);
1004         }
1005 #endif
1006         /* Get actual MTU if possible. */
1007         err = mlx5_get_mtu(eth_dev, &priv->mtu);
1008         if (err) {
1009                 err = rte_errno;
1010                 goto error;
1011         }
1012         DRV_LOG(DEBUG, "port %u MTU is %u", eth_dev->data->port_id,
1013                 priv->mtu);
1014         /* Initialize burst functions to prevent crashes before link-up. */
1015         eth_dev->rx_pkt_burst = removed_rx_burst;
1016         eth_dev->tx_pkt_burst = removed_tx_burst;
1017         eth_dev->dev_ops = &mlx5_dev_ops;
1018         /* Register MAC address. */
1019         claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
1020         if (vf && config.vf_nl_en)
1021                 mlx5_nl_mac_addr_sync(eth_dev);
1022         TAILQ_INIT(&priv->flows);
1023         TAILQ_INIT(&priv->ctrl_flows);
1024         /* Hint libmlx5 to use PMD allocator for data plane resources */
1025         struct mlx5dv_ctx_allocators alctr = {
1026                 .alloc = &mlx5_alloc_verbs_buf,
1027                 .free = &mlx5_free_verbs_buf,
1028                 .data = priv,
1029         };
1030         mlx5_glue->dv_set_context_attr(ctx, MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
1031                                        (void *)((uintptr_t)&alctr));
1032         /* Bring Ethernet device up. */
1033         DRV_LOG(DEBUG, "port %u forcing Ethernet interface up",
1034                 eth_dev->data->port_id);
1035         mlx5_set_link_up(eth_dev);
1036         /*
1037          * Even though the interrupt handler is not installed yet,
1038          * interrupts will still trigger on the asyn_fd from
1039          * Verbs context returned by ibv_open_device().
1040          */
1041         mlx5_link_update(eth_dev, 0);
1042         /* Store device configuration on private structure. */
1043         priv->config = config;
1044         /* Create drop queue. */
1045         err = mlx5_flow_create_drop_queue(eth_dev);
1046         if (err) {
1047                 DRV_LOG(ERR, "port %u drop queue allocation failed: %s",
1048                         eth_dev->data->port_id, strerror(rte_errno));
1049                 err = rte_errno;
1050                 goto error;
1051         }
1052         /* Supported Verbs flow priority number detection. */
1053         if (verb_priorities == 0)
1054                 verb_priorities = mlx5_get_max_verbs_prio(eth_dev);
1055         if (verb_priorities < MLX5_VERBS_FLOW_PRIO_8) {
1056                 DRV_LOG(ERR, "port %u wrong Verbs flow priorities: %u",
1057                         eth_dev->data->port_id, verb_priorities);
1058                 err = ENOTSUP;
1059                 goto error;
1060         }
1061         priv->config.max_verbs_prio = verb_priorities;
1062         /*
1063          * Once the device is added to the list of memory event
1064          * callback, its global MR cache table cannot be expanded
1065          * on the fly because of deadlock. If it overflows, lookup
1066          * should be done by searching MR list linearly, which is slow.
1067          */
1068         err = mlx5_mr_btree_init(&priv->mr.cache,
1069                                  MLX5_MR_BTREE_CACHE_N * 2,
1070                                  eth_dev->device->numa_node);
1071         if (err) {
1072                 err = rte_errno;
1073                 goto error;
1074         }
1075         /* Add device to memory callback list. */
1076         rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
1077         LIST_INSERT_HEAD(&mlx5_shared_data->mem_event_cb_list,
1078                          priv, mem_event_cb);
1079         rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
1080         return eth_dev;
1081 error:
1082         if (priv) {
1083                 if (priv->nl_socket_route >= 0)
1084                         close(priv->nl_socket_route);
1085                 if (priv->nl_socket_rdma >= 0)
1086                         close(priv->nl_socket_rdma);
1087                 rte_free(priv);
1088         }
1089         if (pd)
1090                 claim_zero(mlx5_glue->dealloc_pd(pd));
1091         if (eth_dev)
1092                 rte_eth_dev_release_port(eth_dev);
1093         if (ctx)
1094                 claim_zero(mlx5_glue->close_device(ctx));
1095         assert(err > 0);
1096         rte_errno = err;
1097         return NULL;
1098 }
1099
1100 /**
1101  * DPDK callback to register a PCI device.
1102  *
1103  * This function spawns an Ethernet device out of a given PCI device.
1104  *
1105  * @param[in] pci_drv
1106  *   PCI driver structure (mlx5_driver).
1107  * @param[in] pci_dev
1108  *   PCI device information.
1109  *
1110  * @return
1111  *   0 on success, a negative errno value otherwise and rte_errno is set.
1112  */
1113 static int
1114 mlx5_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
1115                struct rte_pci_device *pci_dev)
1116 {
1117         struct ibv_device **ibv_list;
1118         struct rte_eth_dev *eth_dev = NULL;
1119         unsigned int n = 0;
1120         int vf;
1121         int ret;
1122
1123         assert(pci_drv == &mlx5_driver);
1124         errno = 0;
1125         ibv_list = mlx5_glue->get_device_list(&ret);
1126         if (!ibv_list) {
1127                 rte_errno = errno ? errno : ENOSYS;
1128                 DRV_LOG(ERR, "cannot list devices, is ib_uverbs loaded?");
1129                 return -rte_errno;
1130         }
1131
1132         struct ibv_device *ibv_match[ret + 1];
1133
1134         while (ret-- > 0) {
1135                 struct rte_pci_addr pci_addr;
1136
1137                 DRV_LOG(DEBUG, "checking device \"%s\"", ibv_list[ret]->name);
1138                 if (mlx5_ibv_device_to_pci_addr(ibv_list[ret], &pci_addr))
1139                         continue;
1140                 if (pci_dev->addr.domain != pci_addr.domain ||
1141                     pci_dev->addr.bus != pci_addr.bus ||
1142                     pci_dev->addr.devid != pci_addr.devid ||
1143                     pci_dev->addr.function != pci_addr.function)
1144                         continue;
1145                 DRV_LOG(INFO, "PCI information matches for device \"%s\"",
1146                         ibv_list[ret]->name);
1147                 ibv_match[n++] = ibv_list[ret];
1148         }
1149         ibv_match[n] = NULL;
1150
1151         unsigned int ifindex[n];
1152         struct mlx5_switch_info info[n];
1153         int nl_route = n ? mlx5_nl_init(0, NETLINK_ROUTE) : -1;
1154         int nl_rdma = n ? mlx5_nl_init(0, NETLINK_RDMA) : -1;
1155         unsigned int i;
1156
1157         /*
1158          * The existence of several matching entries (n > 1) means port
1159          * representors have been instantiated. No existing Verbs call nor
1160          * /sys entries can tell them apart, this can only be done through
1161          * Netlink calls assuming kernel drivers are recent enough to
1162          * support them.
1163          *
1164          * In the event of identification failure through Netlink, either:
1165          *
1166          * 1. No device matches (n == 0), complain and bail out.
1167          * 2. A single IB device matches (n == 1) and is not a representor,
1168          *    assume no switch support.
1169          * 3. Otherwise no safe assumptions can be made; complain louder and
1170          *    bail out.
1171          */
1172         for (i = 0; i != n; ++i) {
1173                 if (nl_rdma < 0)
1174                         ifindex[i] = 0;
1175                 else
1176                         ifindex[i] = mlx5_nl_ifindex(nl_rdma,
1177                                                      ibv_match[i]->name);
1178                 if (nl_route < 0 ||
1179                     !ifindex[i] ||
1180                     mlx5_nl_switch_info(nl_route, ifindex[i], &info[i])) {
1181                         ifindex[i] = 0;
1182                         memset(&info[i], 0, sizeof(info[i]));
1183                         continue;
1184                 }
1185         }
1186         if (nl_rdma >= 0)
1187                 close(nl_rdma);
1188         if (nl_route >= 0)
1189                 close(nl_route);
1190         /* Look for master device. */
1191         for (i = 0; i != n; ++i) {
1192                 if (!info[i].master)
1193                         continue;
1194                 /* Make it the first entry. */
1195                 if (i == 0)
1196                         break;
1197                 ibv_match[n] = ibv_match[0];
1198                 ibv_match[0] = ibv_match[i];
1199                 ibv_match[n] = NULL;
1200                 break;
1201         }
1202         if (n && i == n) {
1203                 if (n == 1 && !info[0].representor) {
1204                         /* Case #2. */
1205                         DRV_LOG(INFO, "no switch support detected");
1206                 } else if (n == 1) {
1207                         /* Case #3. */
1208                         DRV_LOG(ERR,
1209                                 "device looks like a port representor, this is"
1210                                 " not supported yet");
1211                         n = 0;
1212                 } else {
1213                         /* Case #3. */
1214                         DRV_LOG(ERR,
1215                                 "unable to tell which of the matching devices"
1216                                 " is the master (lack of kernel support?)");
1217                         n = 0;
1218                 }
1219         }
1220         switch (pci_dev->id.device_id) {
1221         case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
1222         case PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF:
1223         case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
1224         case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
1225                 vf = 1;
1226                 break;
1227         default:
1228                 vf = 0;
1229         }
1230         if (n)
1231                 eth_dev = mlx5_dev_spawn(&pci_dev->device, ibv_match[0], vf);
1232         mlx5_glue->free_device_list(ibv_list);
1233         if (!n) {
1234                 DRV_LOG(WARNING,
1235                         "no Verbs device matches PCI device " PCI_PRI_FMT ","
1236                         " are kernel drivers loaded?",
1237                         pci_dev->addr.domain, pci_dev->addr.bus,
1238                         pci_dev->addr.devid, pci_dev->addr.function);
1239                 rte_errno = ENOENT;
1240                 ret = -rte_errno;
1241         } else if (!eth_dev) {
1242                 DRV_LOG(ERR,
1243                         "probe of PCI device " PCI_PRI_FMT " aborted after"
1244                         " encountering an error: %s",
1245                         pci_dev->addr.domain, pci_dev->addr.bus,
1246                         pci_dev->addr.devid, pci_dev->addr.function,
1247                         strerror(rte_errno));
1248                 ret = -rte_errno;
1249         } else {
1250                 rte_eth_copy_pci_info(eth_dev, pci_dev);
1251                 rte_eth_dev_probing_finish(eth_dev);
1252                 ret = 0;
1253         }
1254         return ret;
1255 }
1256
1257 static const struct rte_pci_id mlx5_pci_id_map[] = {
1258         {
1259                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1260                                PCI_DEVICE_ID_MELLANOX_CONNECTX4)
1261         },
1262         {
1263                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1264                                PCI_DEVICE_ID_MELLANOX_CONNECTX4VF)
1265         },
1266         {
1267                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1268                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LX)
1269         },
1270         {
1271                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1272                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF)
1273         },
1274         {
1275                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1276                                PCI_DEVICE_ID_MELLANOX_CONNECTX5)
1277         },
1278         {
1279                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1280                                PCI_DEVICE_ID_MELLANOX_CONNECTX5VF)
1281         },
1282         {
1283                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1284                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EX)
1285         },
1286         {
1287                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1288                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF)
1289         },
1290         {
1291                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1292                                PCI_DEVICE_ID_MELLANOX_CONNECTX5BF)
1293         },
1294         {
1295                 .vendor_id = 0
1296         }
1297 };
1298
1299 static struct rte_pci_driver mlx5_driver = {
1300         .driver = {
1301                 .name = MLX5_DRIVER_NAME
1302         },
1303         .id_table = mlx5_pci_id_map,
1304         .probe = mlx5_pci_probe,
1305         .drv_flags = RTE_PCI_DRV_INTR_LSC | RTE_PCI_DRV_INTR_RMV,
1306 };
1307
1308 #ifdef RTE_LIBRTE_MLX5_DLOPEN_DEPS
1309
1310 /**
1311  * Suffix RTE_EAL_PMD_PATH with "-glue".
1312  *
1313  * This function performs a sanity check on RTE_EAL_PMD_PATH before
1314  * suffixing its last component.
1315  *
1316  * @param buf[out]
1317  *   Output buffer, should be large enough otherwise NULL is returned.
1318  * @param size
1319  *   Size of @p out.
1320  *
1321  * @return
1322  *   Pointer to @p buf or @p NULL in case suffix cannot be appended.
1323  */
1324 static char *
1325 mlx5_glue_path(char *buf, size_t size)
1326 {
1327         static const char *const bad[] = { "/", ".", "..", NULL };
1328         const char *path = RTE_EAL_PMD_PATH;
1329         size_t len = strlen(path);
1330         size_t off;
1331         int i;
1332
1333         while (len && path[len - 1] == '/')
1334                 --len;
1335         for (off = len; off && path[off - 1] != '/'; --off)
1336                 ;
1337         for (i = 0; bad[i]; ++i)
1338                 if (!strncmp(path + off, bad[i], (int)(len - off)))
1339                         goto error;
1340         i = snprintf(buf, size, "%.*s-glue", (int)len, path);
1341         if (i == -1 || (size_t)i >= size)
1342                 goto error;
1343         return buf;
1344 error:
1345         DRV_LOG(ERR,
1346                 "unable to append \"-glue\" to last component of"
1347                 " RTE_EAL_PMD_PATH (\"" RTE_EAL_PMD_PATH "\"),"
1348                 " please re-configure DPDK");
1349         return NULL;
1350 }
1351
1352 /**
1353  * Initialization routine for run-time dependency on rdma-core.
1354  */
1355 static int
1356 mlx5_glue_init(void)
1357 {
1358         char glue_path[sizeof(RTE_EAL_PMD_PATH) - 1 + sizeof("-glue")];
1359         const char *path[] = {
1360                 /*
1361                  * A basic security check is necessary before trusting
1362                  * MLX5_GLUE_PATH, which may override RTE_EAL_PMD_PATH.
1363                  */
1364                 (geteuid() == getuid() && getegid() == getgid() ?
1365                  getenv("MLX5_GLUE_PATH") : NULL),
1366                 /*
1367                  * When RTE_EAL_PMD_PATH is set, use its glue-suffixed
1368                  * variant, otherwise let dlopen() look up libraries on its
1369                  * own.
1370                  */
1371                 (*RTE_EAL_PMD_PATH ?
1372                  mlx5_glue_path(glue_path, sizeof(glue_path)) : ""),
1373         };
1374         unsigned int i = 0;
1375         void *handle = NULL;
1376         void **sym;
1377         const char *dlmsg;
1378
1379         while (!handle && i != RTE_DIM(path)) {
1380                 const char *end;
1381                 size_t len;
1382                 int ret;
1383
1384                 if (!path[i]) {
1385                         ++i;
1386                         continue;
1387                 }
1388                 end = strpbrk(path[i], ":;");
1389                 if (!end)
1390                         end = path[i] + strlen(path[i]);
1391                 len = end - path[i];
1392                 ret = 0;
1393                 do {
1394                         char name[ret + 1];
1395
1396                         ret = snprintf(name, sizeof(name), "%.*s%s" MLX5_GLUE,
1397                                        (int)len, path[i],
1398                                        (!len || *(end - 1) == '/') ? "" : "/");
1399                         if (ret == -1)
1400                                 break;
1401                         if (sizeof(name) != (size_t)ret + 1)
1402                                 continue;
1403                         DRV_LOG(DEBUG, "looking for rdma-core glue as \"%s\"",
1404                                 name);
1405                         handle = dlopen(name, RTLD_LAZY);
1406                         break;
1407                 } while (1);
1408                 path[i] = end + 1;
1409                 if (!*end)
1410                         ++i;
1411         }
1412         if (!handle) {
1413                 rte_errno = EINVAL;
1414                 dlmsg = dlerror();
1415                 if (dlmsg)
1416                         DRV_LOG(WARNING, "cannot load glue library: %s", dlmsg);
1417                 goto glue_error;
1418         }
1419         sym = dlsym(handle, "mlx5_glue");
1420         if (!sym || !*sym) {
1421                 rte_errno = EINVAL;
1422                 dlmsg = dlerror();
1423                 if (dlmsg)
1424                         DRV_LOG(ERR, "cannot resolve glue symbol: %s", dlmsg);
1425                 goto glue_error;
1426         }
1427         mlx5_glue = *sym;
1428         return 0;
1429 glue_error:
1430         if (handle)
1431                 dlclose(handle);
1432         DRV_LOG(WARNING,
1433                 "cannot initialize PMD due to missing run-time dependency on"
1434                 " rdma-core libraries (libibverbs, libmlx5)");
1435         return -rte_errno;
1436 }
1437
1438 #endif
1439
1440 /**
1441  * Driver initialization routine.
1442  */
1443 RTE_INIT(rte_mlx5_pmd_init)
1444 {
1445         /* Initialize driver log type. */
1446         mlx5_logtype = rte_log_register("pmd.net.mlx5");
1447         if (mlx5_logtype >= 0)
1448                 rte_log_set_level(mlx5_logtype, RTE_LOG_NOTICE);
1449
1450         /* Build the static tables for Verbs conversion. */
1451         mlx5_set_ptype_table();
1452         mlx5_set_cksum_table();
1453         mlx5_set_swp_types_table();
1454         /*
1455          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
1456          * huge pages. Calling ibv_fork_init() during init allows
1457          * applications to use fork() safely for purposes other than
1458          * using this PMD, which is not supported in forked processes.
1459          */
1460         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
1461         /* Match the size of Rx completion entry to the size of a cacheline. */
1462         if (RTE_CACHE_LINE_SIZE == 128)
1463                 setenv("MLX5_CQE_SIZE", "128", 0);
1464         /*
1465          * MLX5_DEVICE_FATAL_CLEANUP tells ibv_destroy functions to
1466          * cleanup all the Verbs resources even when the device was removed.
1467          */
1468         setenv("MLX5_DEVICE_FATAL_CLEANUP", "1", 1);
1469 #ifdef RTE_LIBRTE_MLX5_DLOPEN_DEPS
1470         if (mlx5_glue_init())
1471                 return;
1472         assert(mlx5_glue);
1473 #endif
1474 #ifndef NDEBUG
1475         /* Glue structure must not contain any NULL pointers. */
1476         {
1477                 unsigned int i;
1478
1479                 for (i = 0; i != sizeof(*mlx5_glue) / sizeof(void *); ++i)
1480                         assert(((const void *const *)mlx5_glue)[i]);
1481         }
1482 #endif
1483         if (strcmp(mlx5_glue->version, MLX5_GLUE_VERSION)) {
1484                 DRV_LOG(ERR,
1485                         "rdma-core glue \"%s\" mismatch: \"%s\" is required",
1486                         mlx5_glue->version, MLX5_GLUE_VERSION);
1487                 return;
1488         }
1489         mlx5_glue->fork_init();
1490         rte_pci_register(&mlx5_driver);
1491 }
1492
1493 RTE_PMD_EXPORT_NAME(net_mlx5, __COUNTER__);
1494 RTE_PMD_REGISTER_PCI_TABLE(net_mlx5, mlx5_pci_id_map);
1495 RTE_PMD_REGISTER_KMOD_DEP(net_mlx5, "* ib_uverbs & mlx5_core & mlx5_ib");