xref: /dpdk/drivers/net/mlx5/linux/mlx5_os.c (revision 491b7137ff774bf0cbb8a1e8aff3d5d130c8f046)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2015 6WIND S.A.
3  * Copyright 2020 Mellanox Technologies, Ltd
4  */
5 
6 #include <stddef.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include <errno.h>
12 #include <net/if.h>
13 #include <linux/rtnetlink.h>
14 #include <linux/sockios.h>
15 #include <linux/ethtool.h>
16 #include <fcntl.h>
17 
18 #include <rte_malloc.h>
19 #include <ethdev_driver.h>
20 #include <ethdev_pci.h>
21 #include <rte_pci.h>
22 #include <rte_bus_pci.h>
23 #include <rte_common.h>
24 #include <rte_kvargs.h>
25 #include <rte_rwlock.h>
26 #include <rte_spinlock.h>
27 #include <rte_string_fns.h>
28 #include <rte_alarm.h>
29 #include <rte_eal_paging.h>
30 
31 #include <mlx5_glue.h>
32 #include <mlx5_devx_cmds.h>
33 #include <mlx5_common.h>
34 #include <mlx5_common_mp.h>
35 #include <mlx5_common_mr.h>
36 #include <mlx5_malloc.h>
37 
38 #include "mlx5_defs.h"
39 #include "mlx5.h"
40 #include "mlx5_common_os.h"
41 #include "mlx5_utils.h"
42 #include "mlx5_rxtx.h"
43 #include "mlx5_rx.h"
44 #include "mlx5_tx.h"
45 #include "mlx5_autoconf.h"
46 #include "mlx5_mr.h"
47 #include "mlx5_flow.h"
48 #include "rte_pmd_mlx5.h"
49 #include "mlx5_verbs.h"
50 #include "mlx5_nl.h"
51 #include "mlx5_devx.h"
52 
53 #define MLX5_TAGS_HLIST_ARRAY_SIZE 8192
54 
55 #ifndef HAVE_IBV_MLX5_MOD_MPW
56 #define MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED (1 << 2)
57 #define MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW (1 << 3)
58 #endif
59 
60 #ifndef HAVE_IBV_MLX5_MOD_CQE_128B_COMP
61 #define MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP (1 << 4)
62 #endif
63 
64 static const char *MZ_MLX5_PMD_SHARED_DATA = "mlx5_pmd_shared_data";
65 
66 /* Spinlock for mlx5_shared_data allocation. */
67 static rte_spinlock_t mlx5_shared_data_lock = RTE_SPINLOCK_INITIALIZER;
68 
69 /* Process local data for secondary processes. */
70 static struct mlx5_local_data mlx5_local_data;
71 
72 /* rte flow indexed pool configuration. */
73 static struct mlx5_indexed_pool_config icfg[] = {
74 	{
75 		.size = sizeof(struct rte_flow),
76 		.trunk_size = 64,
77 		.need_lock = 1,
78 		.release_mem_en = 0,
79 		.malloc = mlx5_malloc,
80 		.free = mlx5_free,
81 		.per_core_cache = 0,
82 		.type = "ctl_flow_ipool",
83 	},
84 	{
85 		.size = sizeof(struct rte_flow),
86 		.trunk_size = 64,
87 		.grow_trunk = 3,
88 		.grow_shift = 2,
89 		.need_lock = 1,
90 		.release_mem_en = 0,
91 		.malloc = mlx5_malloc,
92 		.free = mlx5_free,
93 		.per_core_cache = 1 << 14,
94 		.type = "rte_flow_ipool",
95 	},
96 	{
97 		.size = sizeof(struct rte_flow),
98 		.trunk_size = 64,
99 		.grow_trunk = 3,
100 		.grow_shift = 2,
101 		.need_lock = 1,
102 		.release_mem_en = 0,
103 		.malloc = mlx5_malloc,
104 		.free = mlx5_free,
105 		.per_core_cache = 0,
106 		.type = "mcp_flow_ipool",
107 	},
108 };
109 
110 /**
111  * Set the completion channel file descriptor interrupt as non-blocking.
112  *
113  * @param[in] rxq_obj
114  *   Pointer to RQ channel object, which includes the channel fd
115  *
116  * @param[out] fd
117  *   The file descriptor (representing the intetrrupt) used in this channel.
118  *
119  * @return
120  *   0 on successfully setting the fd to non-blocking, non-zero otherwise.
121  */
122 int
123 mlx5_os_set_nonblock_channel_fd(int fd)
124 {
125 	int flags;
126 
127 	flags = fcntl(fd, F_GETFL);
128 	return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
129 }
130 
131 /**
132  * Get mlx5 device attributes. The glue function query_device_ex() is called
133  * with out parameter of type 'struct ibv_device_attr_ex *'. Then fill in mlx5
134  * device attributes from the glue out parameter.
135  *
136  * @param dev
137  *   Pointer to ibv context.
138  *
139  * @param device_attr
140  *   Pointer to mlx5 device attributes.
141  *
142  * @return
143  *   0 on success, non zero error number otherwise
144  */
145 int
146 mlx5_os_get_dev_attr(void *ctx, struct mlx5_dev_attr *device_attr)
147 {
148 	int err;
149 	struct ibv_device_attr_ex attr_ex;
150 	memset(device_attr, 0, sizeof(*device_attr));
151 	err = mlx5_glue->query_device_ex(ctx, NULL, &attr_ex);
152 	if (err)
153 		return err;
154 
155 	device_attr->device_cap_flags_ex = attr_ex.device_cap_flags_ex;
156 	device_attr->max_qp_wr = attr_ex.orig_attr.max_qp_wr;
157 	device_attr->max_sge = attr_ex.orig_attr.max_sge;
158 	device_attr->max_cq = attr_ex.orig_attr.max_cq;
159 	device_attr->max_cqe = attr_ex.orig_attr.max_cqe;
160 	device_attr->max_mr = attr_ex.orig_attr.max_mr;
161 	device_attr->max_pd = attr_ex.orig_attr.max_pd;
162 	device_attr->max_qp = attr_ex.orig_attr.max_qp;
163 	device_attr->max_srq = attr_ex.orig_attr.max_srq;
164 	device_attr->max_srq_wr = attr_ex.orig_attr.max_srq_wr;
165 	device_attr->raw_packet_caps = attr_ex.raw_packet_caps;
166 	device_attr->max_rwq_indirection_table_size =
167 		attr_ex.rss_caps.max_rwq_indirection_table_size;
168 	device_attr->max_tso = attr_ex.tso_caps.max_tso;
169 	device_attr->tso_supported_qpts = attr_ex.tso_caps.supported_qpts;
170 
171 	struct mlx5dv_context dv_attr = { .comp_mask = 0 };
172 	err = mlx5_glue->dv_query_device(ctx, &dv_attr);
173 	if (err)
174 		return err;
175 
176 	device_attr->flags = dv_attr.flags;
177 	device_attr->comp_mask = dv_attr.comp_mask;
178 #ifdef HAVE_IBV_MLX5_MOD_SWP
179 	device_attr->sw_parsing_offloads =
180 		dv_attr.sw_parsing_caps.sw_parsing_offloads;
181 #endif
182 	device_attr->min_single_stride_log_num_of_bytes =
183 		dv_attr.striding_rq_caps.min_single_stride_log_num_of_bytes;
184 	device_attr->max_single_stride_log_num_of_bytes =
185 		dv_attr.striding_rq_caps.max_single_stride_log_num_of_bytes;
186 	device_attr->min_single_wqe_log_num_of_strides =
187 		dv_attr.striding_rq_caps.min_single_wqe_log_num_of_strides;
188 	device_attr->max_single_wqe_log_num_of_strides =
189 		dv_attr.striding_rq_caps.max_single_wqe_log_num_of_strides;
190 	device_attr->stride_supported_qpts =
191 		dv_attr.striding_rq_caps.supported_qpts;
192 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
193 	device_attr->tunnel_offloads_caps = dv_attr.tunnel_offloads_caps;
194 #endif
195 	strlcpy(device_attr->fw_ver, attr_ex.orig_attr.fw_ver,
196 		sizeof(device_attr->fw_ver));
197 
198 	return err;
199 }
200 
201 /**
202  * Verbs callback to allocate a memory. This function should allocate the space
203  * according to the size provided residing inside a huge page.
204  * Please note that all allocation must respect the alignment from libmlx5
205  * (i.e. currently rte_mem_page_size()).
206  *
207  * @param[in] size
208  *   The size in bytes of the memory to allocate.
209  * @param[in] data
210  *   A pointer to the callback data.
211  *
212  * @return
213  *   Allocated buffer, NULL otherwise and rte_errno is set.
214  */
215 static void *
216 mlx5_alloc_verbs_buf(size_t size, void *data)
217 {
218 	struct mlx5_dev_ctx_shared *sh = data;
219 	void *ret;
220 	size_t alignment = rte_mem_page_size();
221 	if (alignment == (size_t)-1) {
222 		DRV_LOG(ERR, "Failed to get mem page size");
223 		rte_errno = ENOMEM;
224 		return NULL;
225 	}
226 
227 	MLX5_ASSERT(data != NULL);
228 	ret = mlx5_malloc(0, size, alignment, sh->numa_node);
229 	if (!ret && size)
230 		rte_errno = ENOMEM;
231 	return ret;
232 }
233 
234 /**
235  * Detect misc5 support or not
236  *
237  * @param[in] priv
238  *   Device private data pointer
239  */
240 #ifdef HAVE_MLX5DV_DR
241 static void
242 __mlx5_discovery_misc5_cap(struct mlx5_priv *priv)
243 {
244 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
245 	/* Dummy VxLAN matcher to detect rdma-core misc5 cap
246 	 * Case: IPv4--->UDP--->VxLAN--->vni
247 	 */
248 	void *tbl;
249 	struct mlx5_flow_dv_match_params matcher_mask;
250 	void *match_m;
251 	void *matcher;
252 	void *headers_m;
253 	void *misc5_m;
254 	uint32_t *tunnel_header_m;
255 	struct mlx5dv_flow_matcher_attr dv_attr;
256 
257 	memset(&matcher_mask, 0, sizeof(matcher_mask));
258 	matcher_mask.size = sizeof(matcher_mask.buf);
259 	match_m = matcher_mask.buf;
260 	headers_m = MLX5_ADDR_OF(fte_match_param, match_m, outer_headers);
261 	misc5_m = MLX5_ADDR_OF(fte_match_param,
262 			       match_m, misc_parameters_5);
263 	tunnel_header_m = (uint32_t *)
264 				MLX5_ADDR_OF(fte_match_set_misc5,
265 				misc5_m, tunnel_header_1);
266 	MLX5_SET(fte_match_set_lyr_2_4, headers_m, ip_protocol, 0xff);
267 	MLX5_SET(fte_match_set_lyr_2_4, headers_m, ip_version, 4);
268 	MLX5_SET(fte_match_set_lyr_2_4, headers_m, udp_dport, 0xffff);
269 	*tunnel_header_m = 0xffffff;
270 
271 	tbl = mlx5_glue->dr_create_flow_tbl(priv->sh->rx_domain, 1);
272 	if (!tbl) {
273 		DRV_LOG(INFO, "No SW steering support");
274 		return;
275 	}
276 	dv_attr.type = IBV_FLOW_ATTR_NORMAL,
277 	dv_attr.match_mask = (void *)&matcher_mask,
278 	dv_attr.match_criteria_enable =
279 			(1 << MLX5_MATCH_CRITERIA_ENABLE_OUTER_BIT) |
280 			(1 << MLX5_MATCH_CRITERIA_ENABLE_MISC5_BIT);
281 	dv_attr.priority = 3;
282 #ifdef HAVE_MLX5DV_DR_ESWITCH
283 	void *misc2_m;
284 	if (priv->config.dv_esw_en) {
285 		/* FDB enabled reg_c_0 */
286 		dv_attr.match_criteria_enable |=
287 				(1 << MLX5_MATCH_CRITERIA_ENABLE_MISC2_BIT);
288 		misc2_m = MLX5_ADDR_OF(fte_match_param,
289 				       match_m, misc_parameters_2);
290 		MLX5_SET(fte_match_set_misc2, misc2_m,
291 			 metadata_reg_c_0, 0xffff);
292 	}
293 #endif
294 	matcher = mlx5_glue->dv_create_flow_matcher(priv->sh->ctx,
295 						    &dv_attr, tbl);
296 	if (matcher) {
297 		priv->sh->misc5_cap = 1;
298 		mlx5_glue->dv_destroy_flow_matcher(matcher);
299 	}
300 	mlx5_glue->dr_destroy_flow_tbl(tbl);
301 #else
302 	RTE_SET_USED(priv);
303 #endif
304 }
305 #endif
306 
307 /**
308  * Verbs callback to free a memory.
309  *
310  * @param[in] ptr
311  *   A pointer to the memory to free.
312  * @param[in] data
313  *   A pointer to the callback data.
314  */
315 static void
316 mlx5_free_verbs_buf(void *ptr, void *data __rte_unused)
317 {
318 	MLX5_ASSERT(data != NULL);
319 	mlx5_free(ptr);
320 }
321 
322 /**
323  * Initialize DR related data within private structure.
324  * Routine checks the reference counter and does actual
325  * resources creation/initialization only if counter is zero.
326  *
327  * @param[in] priv
328  *   Pointer to the private device data structure.
329  *
330  * @return
331  *   Zero on success, positive error code otherwise.
332  */
333 static int
334 mlx5_alloc_shared_dr(struct mlx5_priv *priv)
335 {
336 	struct mlx5_dev_ctx_shared *sh = priv->sh;
337 	char s[MLX5_HLIST_NAMESIZE] __rte_unused;
338 	int err;
339 
340 	MLX5_ASSERT(sh && sh->refcnt);
341 	if (sh->refcnt > 1)
342 		return 0;
343 	err = mlx5_alloc_table_hash_list(priv);
344 	if (err)
345 		goto error;
346 	/* The resources below are only valid with DV support. */
347 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
348 	/* Init port id action list. */
349 	snprintf(s, sizeof(s), "%s_port_id_action_list", sh->ibdev_name);
350 	mlx5_list_create(&sh->port_id_action_list, s, sh,
351 			 flow_dv_port_id_create_cb,
352 			 flow_dv_port_id_match_cb,
353 			 flow_dv_port_id_remove_cb,
354 			 flow_dv_port_id_clone_cb,
355 			 flow_dv_port_id_clone_free_cb);
356 	/* Init push vlan action list. */
357 	snprintf(s, sizeof(s), "%s_push_vlan_action_list", sh->ibdev_name);
358 	mlx5_list_create(&sh->push_vlan_action_list, s, sh,
359 			 flow_dv_push_vlan_create_cb,
360 			 flow_dv_push_vlan_match_cb,
361 			 flow_dv_push_vlan_remove_cb,
362 			 flow_dv_push_vlan_clone_cb,
363 			 flow_dv_push_vlan_clone_free_cb);
364 	/* Init sample action list. */
365 	snprintf(s, sizeof(s), "%s_sample_action_list", sh->ibdev_name);
366 	mlx5_list_create(&sh->sample_action_list, s, sh,
367 			 flow_dv_sample_create_cb,
368 			 flow_dv_sample_match_cb,
369 			 flow_dv_sample_remove_cb,
370 			 flow_dv_sample_clone_cb,
371 			 flow_dv_sample_clone_free_cb);
372 	/* Init dest array action list. */
373 	snprintf(s, sizeof(s), "%s_dest_array_list", sh->ibdev_name);
374 	mlx5_list_create(&sh->dest_array_list, s, sh,
375 			 flow_dv_dest_array_create_cb,
376 			 flow_dv_dest_array_match_cb,
377 			 flow_dv_dest_array_remove_cb,
378 			 flow_dv_dest_array_clone_cb,
379 			 flow_dv_dest_array_clone_free_cb);
380 	/* Create tags hash list table. */
381 	snprintf(s, sizeof(s), "%s_tags", sh->ibdev_name);
382 	sh->tag_table = mlx5_hlist_create(s, MLX5_TAGS_HLIST_ARRAY_SIZE, 0,
383 					  MLX5_HLIST_WRITE_MOST,
384 					  flow_dv_tag_create_cb,
385 					  flow_dv_tag_match_cb,
386 					  flow_dv_tag_remove_cb);
387 	if (!sh->tag_table) {
388 		DRV_LOG(ERR, "tags with hash creation failed.");
389 		err = ENOMEM;
390 		goto error;
391 	}
392 	sh->tag_table->ctx = sh;
393 	snprintf(s, sizeof(s), "%s_hdr_modify", sh->ibdev_name);
394 	sh->modify_cmds = mlx5_hlist_create(s, MLX5_FLOW_HDR_MODIFY_HTABLE_SZ,
395 					    0, MLX5_HLIST_WRITE_MOST |
396 					    MLX5_HLIST_DIRECT_KEY,
397 					    flow_dv_modify_create_cb,
398 					    flow_dv_modify_match_cb,
399 					    flow_dv_modify_remove_cb);
400 	if (!sh->modify_cmds) {
401 		DRV_LOG(ERR, "hdr modify hash creation failed");
402 		err = ENOMEM;
403 		goto error;
404 	}
405 	sh->modify_cmds->ctx = sh;
406 	snprintf(s, sizeof(s), "%s_encaps_decaps", sh->ibdev_name);
407 	sh->encaps_decaps = mlx5_hlist_create(s,
408 					      MLX5_FLOW_ENCAP_DECAP_HTABLE_SZ,
409 					      0, MLX5_HLIST_DIRECT_KEY |
410 					      MLX5_HLIST_WRITE_MOST,
411 					      flow_dv_encap_decap_create_cb,
412 					      flow_dv_encap_decap_match_cb,
413 					      flow_dv_encap_decap_remove_cb);
414 	if (!sh->encaps_decaps) {
415 		DRV_LOG(ERR, "encap decap hash creation failed");
416 		err = ENOMEM;
417 		goto error;
418 	}
419 	sh->encaps_decaps->ctx = sh;
420 #endif
421 #ifdef HAVE_MLX5DV_DR
422 	void *domain;
423 
424 	/* Reference counter is zero, we should initialize structures. */
425 	domain = mlx5_glue->dr_create_domain(sh->ctx,
426 					     MLX5DV_DR_DOMAIN_TYPE_NIC_RX);
427 	if (!domain) {
428 		DRV_LOG(ERR, "ingress mlx5dv_dr_create_domain failed");
429 		err = errno;
430 		goto error;
431 	}
432 	sh->rx_domain = domain;
433 	domain = mlx5_glue->dr_create_domain(sh->ctx,
434 					     MLX5DV_DR_DOMAIN_TYPE_NIC_TX);
435 	if (!domain) {
436 		DRV_LOG(ERR, "egress mlx5dv_dr_create_domain failed");
437 		err = errno;
438 		goto error;
439 	}
440 	sh->tx_domain = domain;
441 #ifdef HAVE_MLX5DV_DR_ESWITCH
442 	if (priv->config.dv_esw_en) {
443 		domain  = mlx5_glue->dr_create_domain
444 			(sh->ctx, MLX5DV_DR_DOMAIN_TYPE_FDB);
445 		if (!domain) {
446 			DRV_LOG(ERR, "FDB mlx5dv_dr_create_domain failed");
447 			err = errno;
448 			goto error;
449 		}
450 		sh->fdb_domain = domain;
451 	}
452 	/*
453 	 * The drop action is just some dummy placeholder in rdma-core. It
454 	 * does not belong to domains and has no any attributes, and, can be
455 	 * shared by the entire device.
456 	 */
457 	sh->dr_drop_action = mlx5_glue->dr_create_flow_action_drop();
458 	if (!sh->dr_drop_action) {
459 		DRV_LOG(ERR, "FDB mlx5dv_dr_create_flow_action_drop");
460 		err = errno;
461 		goto error;
462 	}
463 #endif
464 	if (!sh->tunnel_hub)
465 		err = mlx5_alloc_tunnel_hub(sh);
466 	if (err) {
467 		DRV_LOG(ERR, "mlx5_alloc_tunnel_hub failed err=%d", err);
468 		goto error;
469 	}
470 	if (priv->config.reclaim_mode == MLX5_RCM_AGGR) {
471 		mlx5_glue->dr_reclaim_domain_memory(sh->rx_domain, 1);
472 		mlx5_glue->dr_reclaim_domain_memory(sh->tx_domain, 1);
473 		if (sh->fdb_domain)
474 			mlx5_glue->dr_reclaim_domain_memory(sh->fdb_domain, 1);
475 	}
476 	sh->pop_vlan_action = mlx5_glue->dr_create_flow_action_pop_vlan();
477 	if (!priv->config.allow_duplicate_pattern) {
478 #ifndef HAVE_MLX5_DR_ALLOW_DUPLICATE
479 		DRV_LOG(WARNING, "Disallow duplicate pattern is not supported - maybe old rdma-core version?");
480 #endif
481 		mlx5_glue->dr_allow_duplicate_rules(sh->rx_domain, 0);
482 		mlx5_glue->dr_allow_duplicate_rules(sh->tx_domain, 0);
483 		if (sh->fdb_domain)
484 			mlx5_glue->dr_allow_duplicate_rules(sh->fdb_domain, 0);
485 	}
486 
487 	__mlx5_discovery_misc5_cap(priv);
488 #endif /* HAVE_MLX5DV_DR */
489 	sh->default_miss_action =
490 			mlx5_glue->dr_create_flow_action_default_miss();
491 	if (!sh->default_miss_action)
492 		DRV_LOG(WARNING, "Default miss action is not supported.");
493 	return 0;
494 error:
495 	/* Rollback the created objects. */
496 	if (sh->rx_domain) {
497 		mlx5_glue->dr_destroy_domain(sh->rx_domain);
498 		sh->rx_domain = NULL;
499 	}
500 	if (sh->tx_domain) {
501 		mlx5_glue->dr_destroy_domain(sh->tx_domain);
502 		sh->tx_domain = NULL;
503 	}
504 	if (sh->fdb_domain) {
505 		mlx5_glue->dr_destroy_domain(sh->fdb_domain);
506 		sh->fdb_domain = NULL;
507 	}
508 	if (sh->dr_drop_action) {
509 		mlx5_glue->destroy_flow_action(sh->dr_drop_action);
510 		sh->dr_drop_action = NULL;
511 	}
512 	if (sh->pop_vlan_action) {
513 		mlx5_glue->destroy_flow_action(sh->pop_vlan_action);
514 		sh->pop_vlan_action = NULL;
515 	}
516 	if (sh->encaps_decaps) {
517 		mlx5_hlist_destroy(sh->encaps_decaps);
518 		sh->encaps_decaps = NULL;
519 	}
520 	if (sh->modify_cmds) {
521 		mlx5_hlist_destroy(sh->modify_cmds);
522 		sh->modify_cmds = NULL;
523 	}
524 	if (sh->tag_table) {
525 		/* tags should be destroyed with flow before. */
526 		mlx5_hlist_destroy(sh->tag_table);
527 		sh->tag_table = NULL;
528 	}
529 	if (sh->tunnel_hub) {
530 		mlx5_release_tunnel_hub(sh, priv->dev_port);
531 		sh->tunnel_hub = NULL;
532 	}
533 	mlx5_free_table_hash_list(priv);
534 	return err;
535 }
536 
537 /**
538  * Destroy DR related data within private structure.
539  *
540  * @param[in] priv
541  *   Pointer to the private device data structure.
542  */
543 void
544 mlx5_os_free_shared_dr(struct mlx5_priv *priv)
545 {
546 	struct mlx5_dev_ctx_shared *sh = priv->sh;
547 
548 	MLX5_ASSERT(sh && sh->refcnt);
549 	if (sh->refcnt > 1)
550 		return;
551 #ifdef HAVE_MLX5DV_DR
552 	if (sh->rx_domain) {
553 		mlx5_glue->dr_destroy_domain(sh->rx_domain);
554 		sh->rx_domain = NULL;
555 	}
556 	if (sh->tx_domain) {
557 		mlx5_glue->dr_destroy_domain(sh->tx_domain);
558 		sh->tx_domain = NULL;
559 	}
560 #ifdef HAVE_MLX5DV_DR_ESWITCH
561 	if (sh->fdb_domain) {
562 		mlx5_glue->dr_destroy_domain(sh->fdb_domain);
563 		sh->fdb_domain = NULL;
564 	}
565 	if (sh->dr_drop_action) {
566 		mlx5_glue->destroy_flow_action(sh->dr_drop_action);
567 		sh->dr_drop_action = NULL;
568 	}
569 #endif
570 	if (sh->pop_vlan_action) {
571 		mlx5_glue->destroy_flow_action(sh->pop_vlan_action);
572 		sh->pop_vlan_action = NULL;
573 	}
574 #endif /* HAVE_MLX5DV_DR */
575 	if (sh->default_miss_action)
576 		mlx5_glue->destroy_flow_action
577 				(sh->default_miss_action);
578 	if (sh->encaps_decaps) {
579 		mlx5_hlist_destroy(sh->encaps_decaps);
580 		sh->encaps_decaps = NULL;
581 	}
582 	if (sh->modify_cmds) {
583 		mlx5_hlist_destroy(sh->modify_cmds);
584 		sh->modify_cmds = NULL;
585 	}
586 	if (sh->tag_table) {
587 		/* tags should be destroyed with flow before. */
588 		mlx5_hlist_destroy(sh->tag_table);
589 		sh->tag_table = NULL;
590 	}
591 	if (sh->tunnel_hub) {
592 		mlx5_release_tunnel_hub(sh, priv->dev_port);
593 		sh->tunnel_hub = NULL;
594 	}
595 	mlx5_list_destroy(&sh->port_id_action_list);
596 	mlx5_list_destroy(&sh->push_vlan_action_list);
597 	mlx5_free_table_hash_list(priv);
598 }
599 
600 /**
601  * Initialize shared data between primary and secondary process.
602  *
603  * A memzone is reserved by primary process and secondary processes attach to
604  * the memzone.
605  *
606  * @return
607  *   0 on success, a negative errno value otherwise and rte_errno is set.
608  */
609 static int
610 mlx5_init_shared_data(void)
611 {
612 	const struct rte_memzone *mz;
613 	int ret = 0;
614 
615 	rte_spinlock_lock(&mlx5_shared_data_lock);
616 	if (mlx5_shared_data == NULL) {
617 		if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
618 			/* Allocate shared memory. */
619 			mz = rte_memzone_reserve(MZ_MLX5_PMD_SHARED_DATA,
620 						 sizeof(*mlx5_shared_data),
621 						 SOCKET_ID_ANY, 0);
622 			if (mz == NULL) {
623 				DRV_LOG(ERR,
624 					"Cannot allocate mlx5 shared data");
625 				ret = -rte_errno;
626 				goto error;
627 			}
628 			mlx5_shared_data = mz->addr;
629 			memset(mlx5_shared_data, 0, sizeof(*mlx5_shared_data));
630 			rte_spinlock_init(&mlx5_shared_data->lock);
631 		} else {
632 			/* Lookup allocated shared memory. */
633 			mz = rte_memzone_lookup(MZ_MLX5_PMD_SHARED_DATA);
634 			if (mz == NULL) {
635 				DRV_LOG(ERR,
636 					"Cannot attach mlx5 shared data");
637 				ret = -rte_errno;
638 				goto error;
639 			}
640 			mlx5_shared_data = mz->addr;
641 			memset(&mlx5_local_data, 0, sizeof(mlx5_local_data));
642 		}
643 	}
644 error:
645 	rte_spinlock_unlock(&mlx5_shared_data_lock);
646 	return ret;
647 }
648 
649 /**
650  * PMD global initialization.
651  *
652  * Independent from individual device, this function initializes global
653  * per-PMD data structures distinguishing primary and secondary processes.
654  * Hence, each initialization is called once per a process.
655  *
656  * @return
657  *   0 on success, a negative errno value otherwise and rte_errno is set.
658  */
659 static int
660 mlx5_init_once(void)
661 {
662 	struct mlx5_shared_data *sd;
663 	struct mlx5_local_data *ld = &mlx5_local_data;
664 	int ret = 0;
665 
666 	if (mlx5_init_shared_data())
667 		return -rte_errno;
668 	sd = mlx5_shared_data;
669 	MLX5_ASSERT(sd);
670 	rte_spinlock_lock(&sd->lock);
671 	switch (rte_eal_process_type()) {
672 	case RTE_PROC_PRIMARY:
673 		if (sd->init_done)
674 			break;
675 		LIST_INIT(&sd->mem_event_cb_list);
676 		rte_rwlock_init(&sd->mem_event_rwlock);
677 		rte_mem_event_callback_register("MLX5_MEM_EVENT_CB",
678 						mlx5_mr_mem_event_cb, NULL);
679 		ret = mlx5_mp_init_primary(MLX5_MP_NAME,
680 					   mlx5_mp_os_primary_handle);
681 		if (ret)
682 			goto out;
683 		sd->init_done = true;
684 		break;
685 	case RTE_PROC_SECONDARY:
686 		if (ld->init_done)
687 			break;
688 		ret = mlx5_mp_init_secondary(MLX5_MP_NAME,
689 					     mlx5_mp_os_secondary_handle);
690 		if (ret)
691 			goto out;
692 		++sd->secondary_cnt;
693 		ld->init_done = true;
694 		break;
695 	default:
696 		break;
697 	}
698 out:
699 	rte_spinlock_unlock(&sd->lock);
700 	return ret;
701 }
702 
703 /**
704  * Create the Tx queue DevX/Verbs object.
705  *
706  * @param dev
707  *   Pointer to Ethernet device.
708  * @param idx
709  *   Queue index in DPDK Tx queue array.
710  *
711  * @return
712  *   0 on success, a negative errno value otherwise and rte_errno is set.
713  */
714 static int
715 mlx5_os_txq_obj_new(struct rte_eth_dev *dev, uint16_t idx)
716 {
717 	struct mlx5_priv *priv = dev->data->dev_private;
718 	struct mlx5_txq_data *txq_data = (*priv->txqs)[idx];
719 	struct mlx5_txq_ctrl *txq_ctrl =
720 			container_of(txq_data, struct mlx5_txq_ctrl, txq);
721 
722 	if (txq_ctrl->type == MLX5_TXQ_TYPE_HAIRPIN)
723 		return mlx5_txq_devx_obj_new(dev, idx);
724 #ifdef HAVE_MLX5DV_DEVX_UAR_OFFSET
725 	if (!priv->config.dv_esw_en)
726 		return mlx5_txq_devx_obj_new(dev, idx);
727 #endif
728 	return mlx5_txq_ibv_obj_new(dev, idx);
729 }
730 
731 /**
732  * Release an Tx DevX/verbs queue object.
733  *
734  * @param txq_obj
735  *   DevX/Verbs Tx queue object.
736  */
737 static void
738 mlx5_os_txq_obj_release(struct mlx5_txq_obj *txq_obj)
739 {
740 	if (txq_obj->txq_ctrl->type == MLX5_TXQ_TYPE_HAIRPIN) {
741 		mlx5_txq_devx_obj_release(txq_obj);
742 		return;
743 	}
744 #ifdef HAVE_MLX5DV_DEVX_UAR_OFFSET
745 	if (!txq_obj->txq_ctrl->priv->config.dv_esw_en) {
746 		mlx5_txq_devx_obj_release(txq_obj);
747 		return;
748 	}
749 #endif
750 	mlx5_txq_ibv_obj_release(txq_obj);
751 }
752 
753 /**
754  * DV flow counter mode detect and config.
755  *
756  * @param dev
757  *   Pointer to rte_eth_dev structure.
758  *
759  */
760 static void
761 mlx5_flow_counter_mode_config(struct rte_eth_dev *dev __rte_unused)
762 {
763 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
764 	struct mlx5_priv *priv = dev->data->dev_private;
765 	struct mlx5_dev_ctx_shared *sh = priv->sh;
766 	bool fallback;
767 
768 #ifndef HAVE_IBV_DEVX_ASYNC
769 	fallback = true;
770 #else
771 	fallback = false;
772 	if (!priv->config.devx || !priv->config.dv_flow_en ||
773 	    !priv->config.hca_attr.flow_counters_dump ||
774 	    !(priv->config.hca_attr.flow_counter_bulk_alloc_bitmap & 0x4) ||
775 	    (mlx5_flow_dv_discover_counter_offset_support(dev) == -ENOTSUP))
776 		fallback = true;
777 #endif
778 	if (fallback)
779 		DRV_LOG(INFO, "Use fall-back DV counter management. Flow "
780 			"counter dump:%d, bulk_alloc_bitmap:0x%hhx.",
781 			priv->config.hca_attr.flow_counters_dump,
782 			priv->config.hca_attr.flow_counter_bulk_alloc_bitmap);
783 	/* Initialize fallback mode only on the port initializes sh. */
784 	if (sh->refcnt == 1)
785 		sh->cmng.counter_fallback = fallback;
786 	else if (fallback != sh->cmng.counter_fallback)
787 		DRV_LOG(WARNING, "Port %d in sh has different fallback mode "
788 			"with others:%d.", PORT_ID(priv), fallback);
789 #endif
790 }
791 
792 static void
793 mlx5_queue_counter_id_prepare(struct rte_eth_dev *dev)
794 {
795 	struct mlx5_priv *priv = dev->data->dev_private;
796 	void *ctx = priv->sh->ctx;
797 
798 	priv->q_counters = mlx5_devx_cmd_queue_counter_alloc(ctx);
799 	if (!priv->q_counters) {
800 		struct ibv_cq *cq = mlx5_glue->create_cq(ctx, 1, NULL, NULL, 0);
801 		struct ibv_wq *wq;
802 
803 		DRV_LOG(DEBUG, "Port %d queue counter object cannot be created "
804 			"by DevX - fall-back to use the kernel driver global "
805 			"queue counter.", dev->data->port_id);
806 		/* Create WQ by kernel and query its queue counter ID. */
807 		if (cq) {
808 			wq = mlx5_glue->create_wq(ctx,
809 						  &(struct ibv_wq_init_attr){
810 						    .wq_type = IBV_WQT_RQ,
811 						    .max_wr = 1,
812 						    .max_sge = 1,
813 						    .pd = priv->sh->pd,
814 						    .cq = cq,
815 						});
816 			if (wq) {
817 				/* Counter is assigned only on RDY state. */
818 				int ret = mlx5_glue->modify_wq(wq,
819 						 &(struct ibv_wq_attr){
820 						 .attr_mask = IBV_WQ_ATTR_STATE,
821 						 .wq_state = IBV_WQS_RDY,
822 						});
823 
824 				if (ret == 0)
825 					mlx5_devx_cmd_wq_query(wq,
826 							 &priv->counter_set_id);
827 				claim_zero(mlx5_glue->destroy_wq(wq));
828 			}
829 			claim_zero(mlx5_glue->destroy_cq(cq));
830 		}
831 	} else {
832 		priv->counter_set_id = priv->q_counters->id;
833 	}
834 	if (priv->counter_set_id == 0)
835 		DRV_LOG(INFO, "Part of the port %d statistics will not be "
836 			"available.", dev->data->port_id);
837 }
838 
839 /**
840  * Check if representor spawn info match devargs.
841  *
842  * @param spawn
843  *   Verbs device parameters (name, port, switch_info) to spawn.
844  * @param eth_da
845  *   Device devargs to probe.
846  *
847  * @return
848  *   Match result.
849  */
850 static bool
851 mlx5_representor_match(struct mlx5_dev_spawn_data *spawn,
852 		       struct rte_eth_devargs *eth_da)
853 {
854 	struct mlx5_switch_info *switch_info = &spawn->info;
855 	unsigned int p, f;
856 	uint16_t id;
857 	uint16_t repr_id = mlx5_representor_id_encode(switch_info,
858 						      eth_da->type);
859 
860 	switch (eth_da->type) {
861 	case RTE_ETH_REPRESENTOR_SF:
862 		if (!(spawn->info.port_name == -1 &&
863 		      switch_info->name_type ==
864 				MLX5_PHYS_PORT_NAME_TYPE_PFHPF) &&
865 		    switch_info->name_type != MLX5_PHYS_PORT_NAME_TYPE_PFSF) {
866 			rte_errno = EBUSY;
867 			return false;
868 		}
869 		break;
870 	case RTE_ETH_REPRESENTOR_VF:
871 		/* Allows HPF representor index -1 as exception. */
872 		if (!(spawn->info.port_name == -1 &&
873 		      switch_info->name_type ==
874 				MLX5_PHYS_PORT_NAME_TYPE_PFHPF) &&
875 		    switch_info->name_type != MLX5_PHYS_PORT_NAME_TYPE_PFVF) {
876 			rte_errno = EBUSY;
877 			return false;
878 		}
879 		break;
880 	case RTE_ETH_REPRESENTOR_NONE:
881 		rte_errno = EBUSY;
882 		return false;
883 	default:
884 		rte_errno = ENOTSUP;
885 		DRV_LOG(ERR, "unsupported representor type");
886 		return false;
887 	}
888 	/* Check representor ID: */
889 	for (p = 0; p < eth_da->nb_ports; ++p) {
890 		if (spawn->pf_bond < 0) {
891 			/* For non-LAG mode, allow and ignore pf. */
892 			switch_info->pf_num = eth_da->ports[p];
893 			repr_id = mlx5_representor_id_encode(switch_info,
894 							     eth_da->type);
895 		}
896 		for (f = 0; f < eth_da->nb_representor_ports; ++f) {
897 			id = MLX5_REPRESENTOR_ID
898 				(eth_da->ports[p], eth_da->type,
899 				 eth_da->representor_ports[f]);
900 			if (repr_id == id)
901 				return true;
902 		}
903 	}
904 	rte_errno = EBUSY;
905 	return false;
906 }
907 
908 
909 /**
910  * Spawn an Ethernet device from Verbs information.
911  *
912  * @param dpdk_dev
913  *   Backing DPDK device.
914  * @param spawn
915  *   Verbs device parameters (name, port, switch_info) to spawn.
916  * @param config
917  *   Device configuration parameters.
918  * @param config
919  *   Device arguments.
920  *
921  * @return
922  *   A valid Ethernet device object on success, NULL otherwise and rte_errno
923  *   is set. The following errors are defined:
924  *
925  *   EBUSY: device is not supposed to be spawned.
926  *   EEXIST: device is already spawned
927  */
928 static struct rte_eth_dev *
929 mlx5_dev_spawn(struct rte_device *dpdk_dev,
930 	       struct mlx5_dev_spawn_data *spawn,
931 	       struct mlx5_dev_config *config,
932 	       struct rte_eth_devargs *eth_da)
933 {
934 	const struct mlx5_switch_info *switch_info = &spawn->info;
935 	struct mlx5_dev_ctx_shared *sh = NULL;
936 	struct ibv_port_attr port_attr;
937 	struct mlx5dv_context dv_attr = { .comp_mask = 0 };
938 	struct rte_eth_dev *eth_dev = NULL;
939 	struct mlx5_priv *priv = NULL;
940 	int err = 0;
941 	unsigned int hw_padding = 0;
942 	unsigned int mps;
943 	unsigned int tunnel_en = 0;
944 	unsigned int mpls_en = 0;
945 	unsigned int swp = 0;
946 	unsigned int mprq = 0;
947 	unsigned int mprq_min_stride_size_n = 0;
948 	unsigned int mprq_max_stride_size_n = 0;
949 	unsigned int mprq_min_stride_num_n = 0;
950 	unsigned int mprq_max_stride_num_n = 0;
951 	struct rte_ether_addr mac;
952 	char name[RTE_ETH_NAME_MAX_LEN];
953 	int own_domain_id = 0;
954 	uint16_t port_id;
955 	struct mlx5_port_info vport_info = { .query_flags = 0 };
956 	int i;
957 
958 	/* Determine if this port representor is supposed to be spawned. */
959 	if (switch_info->representor && dpdk_dev->devargs &&
960 	    !mlx5_representor_match(spawn, eth_da))
961 		return NULL;
962 	/* Build device name. */
963 	if (spawn->pf_bond < 0) {
964 		/* Single device. */
965 		if (!switch_info->representor)
966 			strlcpy(name, dpdk_dev->name, sizeof(name));
967 		else
968 			err = snprintf(name, sizeof(name), "%s_representor_%s%u",
969 				 dpdk_dev->name,
970 				 switch_info->name_type ==
971 				 MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
972 				 switch_info->port_name);
973 	} else {
974 		/* Bonding device. */
975 		if (!switch_info->representor) {
976 			err = snprintf(name, sizeof(name), "%s_%s",
977 				 dpdk_dev->name,
978 				 mlx5_os_get_dev_device_name(spawn->phys_dev));
979 		} else {
980 			err = snprintf(name, sizeof(name), "%s_%s_representor_c%dpf%d%s%u",
981 				dpdk_dev->name,
982 				mlx5_os_get_dev_device_name(spawn->phys_dev),
983 				switch_info->ctrl_num,
984 				switch_info->pf_num,
985 				switch_info->name_type ==
986 				MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
987 				switch_info->port_name);
988 		}
989 	}
990 	if (err >= (int)sizeof(name))
991 		DRV_LOG(WARNING, "device name overflow %s", name);
992 	/* check if the device is already spawned */
993 	if (rte_eth_dev_get_port_by_name(name, &port_id) == 0) {
994 		rte_errno = EEXIST;
995 		return NULL;
996 	}
997 	DRV_LOG(DEBUG, "naming Ethernet device \"%s\"", name);
998 	if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
999 		struct mlx5_mp_id mp_id;
1000 
1001 		eth_dev = rte_eth_dev_attach_secondary(name);
1002 		if (eth_dev == NULL) {
1003 			DRV_LOG(ERR, "can not attach rte ethdev");
1004 			rte_errno = ENOMEM;
1005 			return NULL;
1006 		}
1007 		eth_dev->device = dpdk_dev;
1008 		eth_dev->dev_ops = &mlx5_dev_sec_ops;
1009 		eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1010 		eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1011 		err = mlx5_proc_priv_init(eth_dev);
1012 		if (err)
1013 			return NULL;
1014 		mp_id.port_id = eth_dev->data->port_id;
1015 		strlcpy(mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
1016 		/* Receive command fd from primary process */
1017 		err = mlx5_mp_req_verbs_cmd_fd(&mp_id);
1018 		if (err < 0)
1019 			goto err_secondary;
1020 		/* Remap UAR for Tx queues. */
1021 		err = mlx5_tx_uar_init_secondary(eth_dev, err);
1022 		if (err)
1023 			goto err_secondary;
1024 		/*
1025 		 * Ethdev pointer is still required as input since
1026 		 * the primary device is not accessible from the
1027 		 * secondary process.
1028 		 */
1029 		eth_dev->rx_pkt_burst = mlx5_select_rx_function(eth_dev);
1030 		eth_dev->tx_pkt_burst = mlx5_select_tx_function(eth_dev);
1031 		return eth_dev;
1032 err_secondary:
1033 		mlx5_dev_close(eth_dev);
1034 		return NULL;
1035 	}
1036 	/*
1037 	 * Some parameters ("tx_db_nc" in particularly) are needed in
1038 	 * advance to create dv/verbs device context. We proceed the
1039 	 * devargs here to get ones, and later proceed devargs again
1040 	 * to override some hardware settings.
1041 	 */
1042 	err = mlx5_args(config, dpdk_dev->devargs);
1043 	if (err) {
1044 		err = rte_errno;
1045 		DRV_LOG(ERR, "failed to process device arguments: %s",
1046 			strerror(rte_errno));
1047 		goto error;
1048 	}
1049 	if (config->dv_miss_info) {
1050 		if (switch_info->master || switch_info->representor)
1051 			config->dv_xmeta_en = MLX5_XMETA_MODE_META16;
1052 	}
1053 	mlx5_malloc_mem_select(config->sys_mem_en);
1054 	sh = mlx5_alloc_shared_dev_ctx(spawn, config);
1055 	if (!sh)
1056 		return NULL;
1057 	config->devx = sh->devx;
1058 #ifdef HAVE_MLX5DV_DR_ACTION_DEST_DEVX_TIR
1059 	config->dest_tir = 1;
1060 #endif
1061 #ifdef HAVE_IBV_MLX5_MOD_SWP
1062 	dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_SWP;
1063 #endif
1064 	/*
1065 	 * Multi-packet send is supported by ConnectX-4 Lx PF as well
1066 	 * as all ConnectX-5 devices.
1067 	 */
1068 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
1069 	dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS;
1070 #endif
1071 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
1072 	dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_STRIDING_RQ;
1073 #endif
1074 	mlx5_glue->dv_query_device(sh->ctx, &dv_attr);
1075 	if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
1076 		if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
1077 			DRV_LOG(DEBUG, "enhanced MPW is supported");
1078 			mps = MLX5_MPW_ENHANCED;
1079 		} else {
1080 			DRV_LOG(DEBUG, "MPW is supported");
1081 			mps = MLX5_MPW;
1082 		}
1083 	} else {
1084 		DRV_LOG(DEBUG, "MPW isn't supported");
1085 		mps = MLX5_MPW_DISABLED;
1086 	}
1087 #ifdef HAVE_IBV_MLX5_MOD_SWP
1088 	if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_SWP)
1089 		swp = dv_attr.sw_parsing_caps.sw_parsing_offloads;
1090 	DRV_LOG(DEBUG, "SWP support: %u", swp);
1091 #endif
1092 	config->swp = !!swp;
1093 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
1094 	if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_STRIDING_RQ) {
1095 		struct mlx5dv_striding_rq_caps mprq_caps =
1096 			dv_attr.striding_rq_caps;
1097 
1098 		DRV_LOG(DEBUG, "\tmin_single_stride_log_num_of_bytes: %d",
1099 			mprq_caps.min_single_stride_log_num_of_bytes);
1100 		DRV_LOG(DEBUG, "\tmax_single_stride_log_num_of_bytes: %d",
1101 			mprq_caps.max_single_stride_log_num_of_bytes);
1102 		DRV_LOG(DEBUG, "\tmin_single_wqe_log_num_of_strides: %d",
1103 			mprq_caps.min_single_wqe_log_num_of_strides);
1104 		DRV_LOG(DEBUG, "\tmax_single_wqe_log_num_of_strides: %d",
1105 			mprq_caps.max_single_wqe_log_num_of_strides);
1106 		DRV_LOG(DEBUG, "\tsupported_qpts: %d",
1107 			mprq_caps.supported_qpts);
1108 		DRV_LOG(DEBUG, "device supports Multi-Packet RQ");
1109 		mprq = 1;
1110 		mprq_min_stride_size_n =
1111 			mprq_caps.min_single_stride_log_num_of_bytes;
1112 		mprq_max_stride_size_n =
1113 			mprq_caps.max_single_stride_log_num_of_bytes;
1114 		mprq_min_stride_num_n =
1115 			mprq_caps.min_single_wqe_log_num_of_strides;
1116 		mprq_max_stride_num_n =
1117 			mprq_caps.max_single_wqe_log_num_of_strides;
1118 	}
1119 #endif
1120 	/* Rx CQE compression is enabled by default. */
1121 	config->cqe_comp = 1;
1122 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
1123 	if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS) {
1124 		tunnel_en = ((dv_attr.tunnel_offloads_caps &
1125 			      MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN) &&
1126 			     (dv_attr.tunnel_offloads_caps &
1127 			      MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE) &&
1128 			     (dv_attr.tunnel_offloads_caps &
1129 			      MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GENEVE));
1130 	}
1131 	DRV_LOG(DEBUG, "tunnel offloading is %ssupported",
1132 		tunnel_en ? "" : "not ");
1133 #else
1134 	DRV_LOG(WARNING,
1135 		"tunnel offloading disabled due to old OFED/rdma-core version");
1136 #endif
1137 	config->tunnel_en = tunnel_en;
1138 #ifdef HAVE_IBV_DEVICE_MPLS_SUPPORT
1139 	mpls_en = ((dv_attr.tunnel_offloads_caps &
1140 		    MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_GRE) &&
1141 		   (dv_attr.tunnel_offloads_caps &
1142 		    MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_UDP));
1143 	DRV_LOG(DEBUG, "MPLS over GRE/UDP tunnel offloading is %ssupported",
1144 		mpls_en ? "" : "not ");
1145 #else
1146 	DRV_LOG(WARNING, "MPLS over GRE/UDP tunnel offloading disabled due to"
1147 		" old OFED/rdma-core version or firmware configuration");
1148 #endif
1149 	config->mpls_en = mpls_en;
1150 	/* Check port status. */
1151 	err = mlx5_glue->query_port(sh->ctx, spawn->phys_port, &port_attr);
1152 	if (err) {
1153 		DRV_LOG(ERR, "port query failed: %s", strerror(err));
1154 		goto error;
1155 	}
1156 	if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
1157 		DRV_LOG(ERR, "port is not configured in Ethernet mode");
1158 		err = EINVAL;
1159 		goto error;
1160 	}
1161 	if (port_attr.state != IBV_PORT_ACTIVE)
1162 		DRV_LOG(DEBUG, "port is not active: \"%s\" (%d)",
1163 			mlx5_glue->port_state_str(port_attr.state),
1164 			port_attr.state);
1165 	/* Allocate private eth device data. */
1166 	priv = mlx5_malloc(MLX5_MEM_ZERO | MLX5_MEM_RTE,
1167 			   sizeof(*priv),
1168 			   RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
1169 	if (priv == NULL) {
1170 		DRV_LOG(ERR, "priv allocation failure");
1171 		err = ENOMEM;
1172 		goto error;
1173 	}
1174 	priv->sh = sh;
1175 	priv->dev_port = spawn->phys_port;
1176 	priv->pci_dev = spawn->pci_dev;
1177 	priv->mtu = RTE_ETHER_MTU;
1178 	/* Some internal functions rely on Netlink sockets, open them now. */
1179 	priv->nl_socket_rdma = mlx5_nl_init(NETLINK_RDMA);
1180 	priv->nl_socket_route =	mlx5_nl_init(NETLINK_ROUTE);
1181 	priv->representor = !!switch_info->representor;
1182 	priv->master = !!switch_info->master;
1183 	priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
1184 	priv->vport_meta_tag = 0;
1185 	priv->vport_meta_mask = 0;
1186 	priv->pf_bond = spawn->pf_bond;
1187 	/*
1188 	 * If we have E-Switch we should determine the vport attributes.
1189 	 * E-Switch may use either source vport field or reg_c[0] metadata
1190 	 * register to match on vport index. The engaged part of metadata
1191 	 * register is defined by mask.
1192 	 */
1193 	if (switch_info->representor || switch_info->master) {
1194 		err = mlx5_glue->devx_port_query(sh->ctx,
1195 						 spawn->phys_port,
1196 						 &vport_info);
1197 		if (err) {
1198 			DRV_LOG(WARNING,
1199 				"can't query devx port %d on device %s",
1200 				spawn->phys_port,
1201 				mlx5_os_get_dev_device_name(spawn->phys_dev));
1202 			vport_info.query_flags = 0;
1203 		}
1204 	}
1205 	if (vport_info.query_flags & MLX5_PORT_QUERY_REG_C0) {
1206 		priv->vport_meta_tag = vport_info.vport_meta_tag;
1207 		priv->vport_meta_mask = vport_info.vport_meta_mask;
1208 		if (!priv->vport_meta_mask) {
1209 			DRV_LOG(ERR, "vport zero mask for port %d"
1210 				     " on bonding device %s",
1211 				     spawn->phys_port,
1212 				     mlx5_os_get_dev_device_name
1213 							(spawn->phys_dev));
1214 			err = ENOTSUP;
1215 			goto error;
1216 		}
1217 		if (priv->vport_meta_tag & ~priv->vport_meta_mask) {
1218 			DRV_LOG(ERR, "invalid vport tag for port %d"
1219 				     " on bonding device %s",
1220 				     spawn->phys_port,
1221 				     mlx5_os_get_dev_device_name
1222 							(spawn->phys_dev));
1223 			err = ENOTSUP;
1224 			goto error;
1225 		}
1226 	}
1227 	if (vport_info.query_flags & MLX5_PORT_QUERY_VPORT) {
1228 		priv->vport_id = vport_info.vport_id;
1229 	} else if (spawn->pf_bond >= 0 &&
1230 		   (switch_info->representor || switch_info->master)) {
1231 		DRV_LOG(ERR, "can't deduce vport index for port %d"
1232 			     " on bonding device %s",
1233 			     spawn->phys_port,
1234 			     mlx5_os_get_dev_device_name(spawn->phys_dev));
1235 		err = ENOTSUP;
1236 		goto error;
1237 	} else {
1238 		/*
1239 		 * Suppose vport index in compatible way. Kernel/rdma_core
1240 		 * support single E-Switch per PF configurations only and
1241 		 * vport_id field contains the vport index for associated VF,
1242 		 * which is deduced from representor port name.
1243 		 * For example, let's have the IB device port 10, it has
1244 		 * attached network device eth0, which has port name attribute
1245 		 * pf0vf2, we can deduce the VF number as 2, and set vport index
1246 		 * as 3 (2+1). This assigning schema should be changed if the
1247 		 * multiple E-Switch instances per PF configurations or/and PCI
1248 		 * subfunctions are added.
1249 		 */
1250 		priv->vport_id = switch_info->representor ?
1251 				 switch_info->port_name + 1 : -1;
1252 	}
1253 	priv->representor_id = mlx5_representor_id_encode(switch_info,
1254 							  eth_da->type);
1255 	/*
1256 	 * Look for sibling devices in order to reuse their switch domain
1257 	 * if any, otherwise allocate one.
1258 	 */
1259 	MLX5_ETH_FOREACH_DEV(port_id, priv->pci_dev) {
1260 		const struct mlx5_priv *opriv =
1261 			rte_eth_devices[port_id].data->dev_private;
1262 
1263 		if (!opriv ||
1264 		    opriv->sh != priv->sh ||
1265 			opriv->domain_id ==
1266 			RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID)
1267 			continue;
1268 		priv->domain_id = opriv->domain_id;
1269 		break;
1270 	}
1271 	if (priv->domain_id == RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
1272 		err = rte_eth_switch_domain_alloc(&priv->domain_id);
1273 		if (err) {
1274 			err = rte_errno;
1275 			DRV_LOG(ERR, "unable to allocate switch domain: %s",
1276 				strerror(rte_errno));
1277 			goto error;
1278 		}
1279 		own_domain_id = 1;
1280 	}
1281 	/* Override some values set by hardware configuration. */
1282 	mlx5_args(config, dpdk_dev->devargs);
1283 	err = mlx5_dev_check_sibling_config(priv, config);
1284 	if (err)
1285 		goto error;
1286 	config->hw_csum = !!(sh->device_attr.device_cap_flags_ex &
1287 			    IBV_DEVICE_RAW_IP_CSUM);
1288 	DRV_LOG(DEBUG, "checksum offloading is %ssupported",
1289 		(config->hw_csum ? "" : "not "));
1290 #if !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V42) && \
1291 	!defined(HAVE_IBV_DEVICE_COUNTERS_SET_V45)
1292 	DRV_LOG(DEBUG, "counters are not supported");
1293 #endif
1294 #if !defined(HAVE_IBV_FLOW_DV_SUPPORT) || !defined(HAVE_MLX5DV_DR)
1295 	if (config->dv_flow_en) {
1296 		DRV_LOG(WARNING, "DV flow is not supported");
1297 		config->dv_flow_en = 0;
1298 	}
1299 #endif
1300 	config->ind_table_max_size =
1301 		sh->device_attr.max_rwq_indirection_table_size;
1302 	/*
1303 	 * Remove this check once DPDK supports larger/variable
1304 	 * indirection tables.
1305 	 */
1306 	if (config->ind_table_max_size > (unsigned int)ETH_RSS_RETA_SIZE_512)
1307 		config->ind_table_max_size = ETH_RSS_RETA_SIZE_512;
1308 	DRV_LOG(DEBUG, "maximum Rx indirection table size is %u",
1309 		config->ind_table_max_size);
1310 	config->hw_vlan_strip = !!(sh->device_attr.raw_packet_caps &
1311 				  IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
1312 	DRV_LOG(DEBUG, "VLAN stripping is %ssupported",
1313 		(config->hw_vlan_strip ? "" : "not "));
1314 	config->hw_fcs_strip = !!(sh->device_attr.raw_packet_caps &
1315 				 IBV_RAW_PACKET_CAP_SCATTER_FCS);
1316 #if defined(HAVE_IBV_WQ_FLAG_RX_END_PADDING)
1317 	hw_padding = !!sh->device_attr.rx_pad_end_addr_align;
1318 #elif defined(HAVE_IBV_WQ_FLAGS_PCI_WRITE_END_PADDING)
1319 	hw_padding = !!(sh->device_attr.device_cap_flags_ex &
1320 			IBV_DEVICE_PCI_WRITE_END_PADDING);
1321 #endif
1322 	if (config->hw_padding && !hw_padding) {
1323 		DRV_LOG(DEBUG, "Rx end alignment padding isn't supported");
1324 		config->hw_padding = 0;
1325 	} else if (config->hw_padding) {
1326 		DRV_LOG(DEBUG, "Rx end alignment padding is enabled");
1327 	}
1328 	config->tso = (sh->device_attr.max_tso > 0 &&
1329 		      (sh->device_attr.tso_supported_qpts &
1330 		       (1 << IBV_QPT_RAW_PACKET)));
1331 	if (config->tso)
1332 		config->tso_max_payload_sz = sh->device_attr.max_tso;
1333 	/*
1334 	 * MPW is disabled by default, while the Enhanced MPW is enabled
1335 	 * by default.
1336 	 */
1337 	if (config->mps == MLX5_ARG_UNSET)
1338 		config->mps = (mps == MLX5_MPW_ENHANCED) ? MLX5_MPW_ENHANCED :
1339 							  MLX5_MPW_DISABLED;
1340 	else
1341 		config->mps = config->mps ? mps : MLX5_MPW_DISABLED;
1342 	DRV_LOG(INFO, "%sMPS is %s",
1343 		config->mps == MLX5_MPW_ENHANCED ? "enhanced " :
1344 		config->mps == MLX5_MPW ? "legacy " : "",
1345 		config->mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
1346 	if (config->devx) {
1347 		err = mlx5_devx_cmd_query_hca_attr(sh->ctx, &config->hca_attr);
1348 		if (err) {
1349 			err = -err;
1350 			goto error;
1351 		}
1352 		/* Check relax ordering support. */
1353 		if (!haswell_broadwell_cpu) {
1354 			sh->cmng.relaxed_ordering_write =
1355 				config->hca_attr.relaxed_ordering_write;
1356 			sh->cmng.relaxed_ordering_read =
1357 				config->hca_attr.relaxed_ordering_read;
1358 		} else {
1359 			sh->cmng.relaxed_ordering_read = 0;
1360 			sh->cmng.relaxed_ordering_write = 0;
1361 		}
1362 		sh->rq_ts_format = config->hca_attr.rq_ts_format;
1363 		sh->sq_ts_format = config->hca_attr.sq_ts_format;
1364 		sh->qp_ts_format = config->hca_attr.qp_ts_format;
1365 		/* Check for LRO support. */
1366 		if (config->dest_tir && config->hca_attr.lro_cap &&
1367 		    config->dv_flow_en) {
1368 			/* TBD check tunnel lro caps. */
1369 			config->lro.supported = config->hca_attr.lro_cap;
1370 			DRV_LOG(DEBUG, "Device supports LRO");
1371 			/*
1372 			 * If LRO timeout is not configured by application,
1373 			 * use the minimal supported value.
1374 			 */
1375 			if (!config->lro.timeout)
1376 				config->lro.timeout =
1377 				config->hca_attr.lro_timer_supported_periods[0];
1378 			DRV_LOG(DEBUG, "LRO session timeout set to %d usec",
1379 				config->lro.timeout);
1380 			DRV_LOG(DEBUG, "LRO minimal size of TCP segment "
1381 				"required for coalescing is %d bytes",
1382 				config->hca_attr.lro_min_mss_size);
1383 		}
1384 #if defined(HAVE_MLX5DV_DR) && \
1385 	(defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_METER) || \
1386 	 defined(HAVE_MLX5_DR_CREATE_ACTION_ASO))
1387 		if (config->hca_attr.qos.sup &&
1388 		    config->hca_attr.qos.flow_meter_old &&
1389 		    config->dv_flow_en) {
1390 			uint8_t reg_c_mask =
1391 				config->hca_attr.qos.flow_meter_reg_c_ids;
1392 			/*
1393 			 * Meter needs two REG_C's for color match and pre-sfx
1394 			 * flow match. Here get the REG_C for color match.
1395 			 * REG_C_0 and REG_C_1 is reserved for metadata feature.
1396 			 */
1397 			reg_c_mask &= 0xfc;
1398 			if (__builtin_popcount(reg_c_mask) < 1) {
1399 				priv->mtr_en = 0;
1400 				DRV_LOG(WARNING, "No available register for"
1401 					" meter.");
1402 			} else {
1403 				/*
1404 				 * The meter color register is used by the
1405 				 * flow-hit feature as well.
1406 				 * The flow-hit feature must use REG_C_3
1407 				 * Prefer REG_C_3 if it is available.
1408 				 */
1409 				if (reg_c_mask & (1 << (REG_C_3 - REG_C_0)))
1410 					priv->mtr_color_reg = REG_C_3;
1411 				else
1412 					priv->mtr_color_reg = ffs(reg_c_mask)
1413 							      - 1 + REG_C_0;
1414 				priv->mtr_en = 1;
1415 				priv->mtr_reg_share =
1416 				      config->hca_attr.qos.flow_meter;
1417 				DRV_LOG(DEBUG, "The REG_C meter uses is %d",
1418 					priv->mtr_color_reg);
1419 			}
1420 		}
1421 		if (config->hca_attr.qos.sup &&
1422 			config->hca_attr.qos.flow_meter_aso_sup) {
1423 			uint32_t log_obj_size =
1424 				rte_log2_u32(MLX5_ASO_MTRS_PER_POOL >> 1);
1425 			if (log_obj_size >=
1426 			config->hca_attr.qos.log_meter_aso_granularity &&
1427 			log_obj_size <=
1428 			config->hca_attr.qos.log_meter_aso_max_alloc)
1429 				sh->meter_aso_en = 1;
1430 		}
1431 		if (priv->mtr_en) {
1432 			err = mlx5_aso_flow_mtrs_mng_init(priv->sh);
1433 			if (err) {
1434 				err = -err;
1435 				goto error;
1436 			}
1437 		}
1438 		if (config->hca_attr.flow.tunnel_header_0_1)
1439 			sh->tunnel_header_0_1 = 1;
1440 #endif
1441 #ifdef HAVE_MLX5_DR_CREATE_ACTION_ASO
1442 		if (config->hca_attr.flow_hit_aso &&
1443 		    priv->mtr_color_reg == REG_C_3) {
1444 			sh->flow_hit_aso_en = 1;
1445 			err = mlx5_flow_aso_age_mng_init(sh);
1446 			if (err) {
1447 				err = -err;
1448 				goto error;
1449 			}
1450 			DRV_LOG(DEBUG, "Flow Hit ASO is supported.");
1451 		}
1452 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO */
1453 #if defined(HAVE_MLX5_DR_CREATE_ACTION_ASO) && \
1454 	defined(HAVE_MLX5_DR_ACTION_ASO_CT)
1455 		if (config->hca_attr.ct_offload &&
1456 		    priv->mtr_color_reg == REG_C_3) {
1457 			err = mlx5_flow_aso_ct_mng_init(sh);
1458 			if (err) {
1459 				err = -err;
1460 				goto error;
1461 			}
1462 			DRV_LOG(DEBUG, "CT ASO is supported.");
1463 			sh->ct_aso_en = 1;
1464 		}
1465 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO && HAVE_MLX5_DR_ACTION_ASO_CT */
1466 #if defined(HAVE_MLX5DV_DR) && defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_SAMPLE)
1467 		if (config->hca_attr.log_max_ft_sampler_num > 0  &&
1468 		    config->dv_flow_en) {
1469 			priv->sampler_en = 1;
1470 			DRV_LOG(DEBUG, "Sampler enabled!");
1471 		} else {
1472 			priv->sampler_en = 0;
1473 			if (!config->hca_attr.log_max_ft_sampler_num)
1474 				DRV_LOG(WARNING,
1475 					"No available register for sampler.");
1476 			else
1477 				DRV_LOG(DEBUG, "DV flow is not supported!");
1478 		}
1479 #endif
1480 	}
1481 	if (config->cqe_comp && RTE_CACHE_LINE_SIZE == 128 &&
1482 	    !(dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP)) {
1483 		DRV_LOG(WARNING, "Rx CQE 128B compression is not supported");
1484 		config->cqe_comp = 0;
1485 	}
1486 	if (config->cqe_comp_fmt == MLX5_CQE_RESP_FORMAT_FTAG_STRIDX &&
1487 	    (!config->devx || !config->hca_attr.mini_cqe_resp_flow_tag)) {
1488 		DRV_LOG(WARNING, "Flow Tag CQE compression"
1489 				 " format isn't supported.");
1490 		config->cqe_comp = 0;
1491 	}
1492 	if (config->cqe_comp_fmt == MLX5_CQE_RESP_FORMAT_L34H_STRIDX &&
1493 	    (!config->devx || !config->hca_attr.mini_cqe_resp_l3_l4_tag)) {
1494 		DRV_LOG(WARNING, "L3/L4 Header CQE compression"
1495 				 " format isn't supported.");
1496 		config->cqe_comp = 0;
1497 	}
1498 	DRV_LOG(DEBUG, "Rx CQE compression is %ssupported",
1499 			config->cqe_comp ? "" : "not ");
1500 	if (config->tx_pp) {
1501 		DRV_LOG(DEBUG, "Timestamp counter frequency %u kHz",
1502 			config->hca_attr.dev_freq_khz);
1503 		DRV_LOG(DEBUG, "Packet pacing is %ssupported",
1504 			config->hca_attr.qos.packet_pacing ? "" : "not ");
1505 		DRV_LOG(DEBUG, "Cross channel ops are %ssupported",
1506 			config->hca_attr.cross_channel ? "" : "not ");
1507 		DRV_LOG(DEBUG, "WQE index ignore is %ssupported",
1508 			config->hca_attr.wqe_index_ignore ? "" : "not ");
1509 		DRV_LOG(DEBUG, "Non-wire SQ feature is %ssupported",
1510 			config->hca_attr.non_wire_sq ? "" : "not ");
1511 		DRV_LOG(DEBUG, "Static WQE SQ feature is %ssupported (%d)",
1512 			config->hca_attr.log_max_static_sq_wq ? "" : "not ",
1513 			config->hca_attr.log_max_static_sq_wq);
1514 		DRV_LOG(DEBUG, "WQE rate PP mode is %ssupported",
1515 			config->hca_attr.qos.wqe_rate_pp ? "" : "not ");
1516 		if (!config->devx) {
1517 			DRV_LOG(ERR, "DevX is required for packet pacing");
1518 			err = ENODEV;
1519 			goto error;
1520 		}
1521 		if (!config->hca_attr.qos.packet_pacing) {
1522 			DRV_LOG(ERR, "Packet pacing is not supported");
1523 			err = ENODEV;
1524 			goto error;
1525 		}
1526 		if (!config->hca_attr.cross_channel) {
1527 			DRV_LOG(ERR, "Cross channel operations are"
1528 				     " required for packet pacing");
1529 			err = ENODEV;
1530 			goto error;
1531 		}
1532 		if (!config->hca_attr.wqe_index_ignore) {
1533 			DRV_LOG(ERR, "WQE index ignore feature is"
1534 				     " required for packet pacing");
1535 			err = ENODEV;
1536 			goto error;
1537 		}
1538 		if (!config->hca_attr.non_wire_sq) {
1539 			DRV_LOG(ERR, "Non-wire SQ feature is"
1540 				     " required for packet pacing");
1541 			err = ENODEV;
1542 			goto error;
1543 		}
1544 		if (!config->hca_attr.log_max_static_sq_wq) {
1545 			DRV_LOG(ERR, "Static WQE SQ feature is"
1546 				     " required for packet pacing");
1547 			err = ENODEV;
1548 			goto error;
1549 		}
1550 		if (!config->hca_attr.qos.wqe_rate_pp) {
1551 			DRV_LOG(ERR, "WQE rate mode is required"
1552 				     " for packet pacing");
1553 			err = ENODEV;
1554 			goto error;
1555 		}
1556 #ifndef HAVE_MLX5DV_DEVX_UAR_OFFSET
1557 		DRV_LOG(ERR, "DevX does not provide UAR offset,"
1558 			     " can't create queues for packet pacing");
1559 		err = ENODEV;
1560 		goto error;
1561 #endif
1562 	}
1563 	if (config->devx) {
1564 		uint32_t reg[MLX5_ST_SZ_DW(register_mtutc)];
1565 
1566 		err = config->hca_attr.access_register_user ?
1567 			mlx5_devx_cmd_register_read
1568 				(sh->ctx, MLX5_REGISTER_ID_MTUTC, 0,
1569 				reg, MLX5_ST_SZ_DW(register_mtutc)) : ENOTSUP;
1570 		if (!err) {
1571 			uint32_t ts_mode;
1572 
1573 			/* MTUTC register is read successfully. */
1574 			ts_mode = MLX5_GET(register_mtutc, reg,
1575 					   time_stamp_mode);
1576 			if (ts_mode == MLX5_MTUTC_TIMESTAMP_MODE_REAL_TIME)
1577 				config->rt_timestamp = 1;
1578 		} else {
1579 			/* Kernel does not support register reading. */
1580 			if (config->hca_attr.dev_freq_khz ==
1581 						 (NS_PER_S / MS_PER_S))
1582 				config->rt_timestamp = 1;
1583 		}
1584 	}
1585 	/*
1586 	 * If HW has bug working with tunnel packet decapsulation and
1587 	 * scatter FCS, and decapsulation is needed, clear the hw_fcs_strip
1588 	 * bit. Then DEV_RX_OFFLOAD_KEEP_CRC bit will not be set anymore.
1589 	 */
1590 	if (config->hca_attr.scatter_fcs_w_decap_disable && config->decap_en)
1591 		config->hw_fcs_strip = 0;
1592 	DRV_LOG(DEBUG, "FCS stripping configuration is %ssupported",
1593 		(config->hw_fcs_strip ? "" : "not "));
1594 	if (config->mprq.enabled && mprq) {
1595 		if (config->mprq.stride_num_n &&
1596 		    (config->mprq.stride_num_n > mprq_max_stride_num_n ||
1597 		     config->mprq.stride_num_n < mprq_min_stride_num_n)) {
1598 			config->mprq.stride_num_n =
1599 				RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
1600 						mprq_min_stride_num_n),
1601 					mprq_max_stride_num_n);
1602 			DRV_LOG(WARNING,
1603 				"the number of strides"
1604 				" for Multi-Packet RQ is out of range,"
1605 				" setting default value (%u)",
1606 				1 << config->mprq.stride_num_n);
1607 		}
1608 		if (config->mprq.stride_size_n &&
1609 		    (config->mprq.stride_size_n > mprq_max_stride_size_n ||
1610 		     config->mprq.stride_size_n < mprq_min_stride_size_n)) {
1611 			config->mprq.stride_size_n =
1612 				RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_SIZE_N,
1613 						mprq_min_stride_size_n),
1614 					mprq_max_stride_size_n);
1615 			DRV_LOG(WARNING,
1616 				"the size of a stride"
1617 				" for Multi-Packet RQ is out of range,"
1618 				" setting default value (%u)",
1619 				1 << config->mprq.stride_size_n);
1620 		}
1621 		config->mprq.min_stride_size_n = mprq_min_stride_size_n;
1622 		config->mprq.max_stride_size_n = mprq_max_stride_size_n;
1623 	} else if (config->mprq.enabled && !mprq) {
1624 		DRV_LOG(WARNING, "Multi-Packet RQ isn't supported");
1625 		config->mprq.enabled = 0;
1626 	}
1627 	if (config->max_dump_files_num == 0)
1628 		config->max_dump_files_num = 128;
1629 	eth_dev = rte_eth_dev_allocate(name);
1630 	if (eth_dev == NULL) {
1631 		DRV_LOG(ERR, "can not allocate rte ethdev");
1632 		err = ENOMEM;
1633 		goto error;
1634 	}
1635 	if (priv->representor) {
1636 		eth_dev->data->dev_flags |= RTE_ETH_DEV_REPRESENTOR;
1637 		eth_dev->data->representor_id = priv->representor_id;
1638 	}
1639 	priv->mp_id.port_id = eth_dev->data->port_id;
1640 	strlcpy(priv->mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
1641 	/*
1642 	 * Store associated network device interface index. This index
1643 	 * is permanent throughout the lifetime of device. So, we may store
1644 	 * the ifindex here and use the cached value further.
1645 	 */
1646 	MLX5_ASSERT(spawn->ifindex);
1647 	priv->if_index = spawn->ifindex;
1648 	eth_dev->data->dev_private = priv;
1649 	priv->dev_data = eth_dev->data;
1650 	eth_dev->data->mac_addrs = priv->mac;
1651 	eth_dev->device = dpdk_dev;
1652 	eth_dev->data->dev_flags |= RTE_ETH_DEV_AUTOFILL_QUEUE_XSTATS;
1653 	/* Configure the first MAC address by default. */
1654 	if (mlx5_get_mac(eth_dev, &mac.addr_bytes)) {
1655 		DRV_LOG(ERR,
1656 			"port %u cannot get MAC address, is mlx5_en"
1657 			" loaded? (errno: %s)",
1658 			eth_dev->data->port_id, strerror(rte_errno));
1659 		err = ENODEV;
1660 		goto error;
1661 	}
1662 	DRV_LOG(INFO,
1663 		"port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
1664 		eth_dev->data->port_id,
1665 		mac.addr_bytes[0], mac.addr_bytes[1],
1666 		mac.addr_bytes[2], mac.addr_bytes[3],
1667 		mac.addr_bytes[4], mac.addr_bytes[5]);
1668 #ifdef RTE_LIBRTE_MLX5_DEBUG
1669 	{
1670 		char ifname[MLX5_NAMESIZE];
1671 
1672 		if (mlx5_get_ifname(eth_dev, &ifname) == 0)
1673 			DRV_LOG(DEBUG, "port %u ifname is \"%s\"",
1674 				eth_dev->data->port_id, ifname);
1675 		else
1676 			DRV_LOG(DEBUG, "port %u ifname is unknown",
1677 				eth_dev->data->port_id);
1678 	}
1679 #endif
1680 	/* Get actual MTU if possible. */
1681 	err = mlx5_get_mtu(eth_dev, &priv->mtu);
1682 	if (err) {
1683 		err = rte_errno;
1684 		goto error;
1685 	}
1686 	DRV_LOG(DEBUG, "port %u MTU is %u", eth_dev->data->port_id,
1687 		priv->mtu);
1688 	/* Initialize burst functions to prevent crashes before link-up. */
1689 	eth_dev->rx_pkt_burst = removed_rx_burst;
1690 	eth_dev->tx_pkt_burst = removed_tx_burst;
1691 	eth_dev->dev_ops = &mlx5_dev_ops;
1692 	eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1693 	eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1694 	eth_dev->rx_queue_count = mlx5_rx_queue_count;
1695 	/* Register MAC address. */
1696 	claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
1697 	if (config->vf && config->vf_nl_en)
1698 		mlx5_nl_mac_addr_sync(priv->nl_socket_route,
1699 				      mlx5_ifindex(eth_dev),
1700 				      eth_dev->data->mac_addrs,
1701 				      MLX5_MAX_MAC_ADDRESSES);
1702 	priv->ctrl_flows = 0;
1703 	rte_spinlock_init(&priv->flow_list_lock);
1704 	TAILQ_INIT(&priv->flow_meters);
1705 	priv->mtr_profile_tbl = mlx5_l3t_create(MLX5_L3T_TYPE_PTR);
1706 	if (!priv->mtr_profile_tbl)
1707 		goto error;
1708 	/* Hint libmlx5 to use PMD allocator for data plane resources */
1709 	mlx5_glue->dv_set_context_attr(sh->ctx,
1710 			MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
1711 			(void *)((uintptr_t)&(struct mlx5dv_ctx_allocators){
1712 				.alloc = &mlx5_alloc_verbs_buf,
1713 				.free = &mlx5_free_verbs_buf,
1714 				.data = sh,
1715 			}));
1716 	/* Bring Ethernet device up. */
1717 	DRV_LOG(DEBUG, "port %u forcing Ethernet interface up",
1718 		eth_dev->data->port_id);
1719 	mlx5_set_link_up(eth_dev);
1720 	/*
1721 	 * Even though the interrupt handler is not installed yet,
1722 	 * interrupts will still trigger on the async_fd from
1723 	 * Verbs context returned by ibv_open_device().
1724 	 */
1725 	mlx5_link_update(eth_dev, 0);
1726 #ifdef HAVE_MLX5DV_DR_ESWITCH
1727 	if (!(config->hca_attr.eswitch_manager && config->dv_flow_en &&
1728 	      (switch_info->representor || switch_info->master)))
1729 		config->dv_esw_en = 0;
1730 #else
1731 	config->dv_esw_en = 0;
1732 #endif
1733 	/* Detect minimal data bytes to inline. */
1734 	mlx5_set_min_inline(spawn, config);
1735 	/* Store device configuration on private structure. */
1736 	priv->config = *config;
1737 	for (i = 0; i < MLX5_FLOW_TYPE_MAXI; i++) {
1738 		icfg[i].release_mem_en = !!config->reclaim_mode;
1739 		if (config->reclaim_mode)
1740 			icfg[i].per_core_cache = 0;
1741 		priv->flows[i] = mlx5_ipool_create(&icfg[i]);
1742 		if (!priv->flows[i])
1743 			goto error;
1744 	}
1745 	/* Create context for virtual machine VLAN workaround. */
1746 	priv->vmwa_context = mlx5_vlan_vmwa_init(eth_dev, spawn->ifindex);
1747 	if (config->dv_flow_en) {
1748 		err = mlx5_alloc_shared_dr(priv);
1749 		if (err)
1750 			goto error;
1751 	}
1752 	if (config->devx && config->dv_flow_en && config->dest_tir) {
1753 		priv->obj_ops = devx_obj_ops;
1754 		priv->obj_ops.drop_action_create =
1755 						ibv_obj_ops.drop_action_create;
1756 		priv->obj_ops.drop_action_destroy =
1757 						ibv_obj_ops.drop_action_destroy;
1758 #ifndef HAVE_MLX5DV_DEVX_UAR_OFFSET
1759 		priv->obj_ops.txq_obj_modify = ibv_obj_ops.txq_obj_modify;
1760 #else
1761 		if (config->dv_esw_en)
1762 			priv->obj_ops.txq_obj_modify =
1763 						ibv_obj_ops.txq_obj_modify;
1764 #endif
1765 		/* Use specific wrappers for Tx object. */
1766 		priv->obj_ops.txq_obj_new = mlx5_os_txq_obj_new;
1767 		priv->obj_ops.txq_obj_release = mlx5_os_txq_obj_release;
1768 		mlx5_queue_counter_id_prepare(eth_dev);
1769 		priv->obj_ops.lb_dummy_queue_create =
1770 					mlx5_rxq_ibv_obj_dummy_lb_create;
1771 		priv->obj_ops.lb_dummy_queue_release =
1772 					mlx5_rxq_ibv_obj_dummy_lb_release;
1773 	} else {
1774 		priv->obj_ops = ibv_obj_ops;
1775 	}
1776 	priv->drop_queue.hrxq = mlx5_drop_action_create(eth_dev);
1777 	if (!priv->drop_queue.hrxq)
1778 		goto error;
1779 	/* Supported Verbs flow priority number detection. */
1780 	err = mlx5_flow_discover_priorities(eth_dev);
1781 	if (err < 0) {
1782 		err = -err;
1783 		goto error;
1784 	}
1785 	priv->config.flow_prio = err;
1786 	if (!priv->config.dv_esw_en &&
1787 	    priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1788 		DRV_LOG(WARNING, "metadata mode %u is not supported "
1789 				 "(no E-Switch)", priv->config.dv_xmeta_en);
1790 		priv->config.dv_xmeta_en = MLX5_XMETA_MODE_LEGACY;
1791 	}
1792 	mlx5_set_metadata_mask(eth_dev);
1793 	if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1794 	    !priv->sh->dv_regc0_mask) {
1795 		DRV_LOG(ERR, "metadata mode %u is not supported "
1796 			     "(no metadata reg_c[0] is available)",
1797 			     priv->config.dv_xmeta_en);
1798 			err = ENOTSUP;
1799 			goto error;
1800 	}
1801 	mlx5_list_create(&priv->hrxqs, "hrxq", eth_dev, mlx5_hrxq_create_cb,
1802 			 mlx5_hrxq_match_cb,
1803 			 mlx5_hrxq_remove_cb,
1804 			 mlx5_hrxq_clone_cb,
1805 			 mlx5_hrxq_clone_free_cb);
1806 	rte_rwlock_init(&priv->ind_tbls_lock);
1807 	/* Query availability of metadata reg_c's. */
1808 	err = mlx5_flow_discover_mreg_c(eth_dev);
1809 	if (err < 0) {
1810 		err = -err;
1811 		goto error;
1812 	}
1813 	if (!mlx5_flow_ext_mreg_supported(eth_dev)) {
1814 		DRV_LOG(DEBUG,
1815 			"port %u extensive metadata register is not supported",
1816 			eth_dev->data->port_id);
1817 		if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1818 			DRV_LOG(ERR, "metadata mode %u is not supported "
1819 				     "(no metadata registers available)",
1820 				     priv->config.dv_xmeta_en);
1821 			err = ENOTSUP;
1822 			goto error;
1823 		}
1824 	}
1825 	if (priv->config.dv_flow_en &&
1826 	    priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1827 	    mlx5_flow_ext_mreg_supported(eth_dev) &&
1828 	    priv->sh->dv_regc0_mask) {
1829 		priv->mreg_cp_tbl = mlx5_hlist_create(MLX5_FLOW_MREG_HNAME,
1830 						      MLX5_FLOW_MREG_HTABLE_SZ,
1831 						      0, 0,
1832 						      flow_dv_mreg_create_cb,
1833 						      flow_dv_mreg_match_cb,
1834 						      flow_dv_mreg_remove_cb);
1835 		if (!priv->mreg_cp_tbl) {
1836 			err = ENOMEM;
1837 			goto error;
1838 		}
1839 		priv->mreg_cp_tbl->ctx = eth_dev;
1840 	}
1841 	rte_spinlock_init(&priv->shared_act_sl);
1842 	mlx5_flow_counter_mode_config(eth_dev);
1843 	if (priv->config.dv_flow_en)
1844 		eth_dev->data->dev_flags |= RTE_ETH_DEV_FLOW_OPS_THREAD_SAFE;
1845 	return eth_dev;
1846 error:
1847 	if (priv) {
1848 		if (priv->mreg_cp_tbl)
1849 			mlx5_hlist_destroy(priv->mreg_cp_tbl);
1850 		if (priv->sh)
1851 			mlx5_os_free_shared_dr(priv);
1852 		if (priv->nl_socket_route >= 0)
1853 			close(priv->nl_socket_route);
1854 		if (priv->nl_socket_rdma >= 0)
1855 			close(priv->nl_socket_rdma);
1856 		if (priv->vmwa_context)
1857 			mlx5_vlan_vmwa_exit(priv->vmwa_context);
1858 		if (eth_dev && priv->drop_queue.hrxq)
1859 			mlx5_drop_action_destroy(eth_dev);
1860 		if (priv->mtr_profile_tbl)
1861 			mlx5_l3t_destroy(priv->mtr_profile_tbl);
1862 		if (own_domain_id)
1863 			claim_zero(rte_eth_switch_domain_free(priv->domain_id));
1864 		mlx5_list_destroy(&priv->hrxqs);
1865 		mlx5_free(priv);
1866 		if (eth_dev != NULL)
1867 			eth_dev->data->dev_private = NULL;
1868 	}
1869 	if (eth_dev != NULL) {
1870 		/* mac_addrs must not be freed alone because part of
1871 		 * dev_private
1872 		 **/
1873 		eth_dev->data->mac_addrs = NULL;
1874 		rte_eth_dev_release_port(eth_dev);
1875 	}
1876 	if (sh)
1877 		mlx5_free_shared_dev_ctx(sh);
1878 	MLX5_ASSERT(err > 0);
1879 	rte_errno = err;
1880 	return NULL;
1881 }
1882 
1883 /**
1884  * Comparison callback to sort device data.
1885  *
1886  * This is meant to be used with qsort().
1887  *
1888  * @param a[in]
1889  *   Pointer to pointer to first data object.
1890  * @param b[in]
1891  *   Pointer to pointer to second data object.
1892  *
1893  * @return
1894  *   0 if both objects are equal, less than 0 if the first argument is less
1895  *   than the second, greater than 0 otherwise.
1896  */
1897 static int
1898 mlx5_dev_spawn_data_cmp(const void *a, const void *b)
1899 {
1900 	const struct mlx5_switch_info *si_a =
1901 		&((const struct mlx5_dev_spawn_data *)a)->info;
1902 	const struct mlx5_switch_info *si_b =
1903 		&((const struct mlx5_dev_spawn_data *)b)->info;
1904 	int ret;
1905 
1906 	/* Master device first. */
1907 	ret = si_b->master - si_a->master;
1908 	if (ret)
1909 		return ret;
1910 	/* Then representor devices. */
1911 	ret = si_b->representor - si_a->representor;
1912 	if (ret)
1913 		return ret;
1914 	/* Unidentified devices come last in no specific order. */
1915 	if (!si_a->representor)
1916 		return 0;
1917 	/* Order representors by name. */
1918 	return si_a->port_name - si_b->port_name;
1919 }
1920 
1921 /**
1922  * Match PCI information for possible slaves of bonding device.
1923  *
1924  * @param[in] ibv_dev
1925  *   Pointer to Infiniband device structure.
1926  * @param[in] pci_dev
1927  *   Pointer to primary PCI address structure to match.
1928  * @param[in] nl_rdma
1929  *   Netlink RDMA group socket handle.
1930  * @param[in] owner
1931  *   Rerepsentor owner PF index.
1932  * @param[out] bond_info
1933  *   Pointer to bonding information.
1934  *
1935  * @return
1936  *   negative value if no bonding device found, otherwise
1937  *   positive index of slave PF in bonding.
1938  */
1939 static int
1940 mlx5_device_bond_pci_match(const struct ibv_device *ibv_dev,
1941 			   const struct rte_pci_addr *pci_dev,
1942 			   int nl_rdma, uint16_t owner,
1943 			   struct mlx5_bond_info *bond_info)
1944 {
1945 	char ifname[IF_NAMESIZE + 1];
1946 	unsigned int ifindex;
1947 	unsigned int np, i;
1948 	FILE *bond_file = NULL, *file;
1949 	int pf = -1;
1950 	int ret;
1951 
1952 	/*
1953 	 * Try to get master device name. If something goes
1954 	 * wrong suppose the lack of kernel support and no
1955 	 * bonding devices.
1956 	 */
1957 	memset(bond_info, 0, sizeof(*bond_info));
1958 	if (nl_rdma < 0)
1959 		return -1;
1960 	if (!strstr(ibv_dev->name, "bond"))
1961 		return -1;
1962 	np = mlx5_nl_portnum(nl_rdma, ibv_dev->name);
1963 	if (!np)
1964 		return -1;
1965 	/*
1966 	 * The Master device might not be on the predefined
1967 	 * port (not on port index 1, it is not garanted),
1968 	 * we have to scan all Infiniband device port and
1969 	 * find master.
1970 	 */
1971 	for (i = 1; i <= np; ++i) {
1972 		/* Check whether Infiniband port is populated. */
1973 		ifindex = mlx5_nl_ifindex(nl_rdma, ibv_dev->name, i);
1974 		if (!ifindex)
1975 			continue;
1976 		if (!if_indextoname(ifindex, ifname))
1977 			continue;
1978 		/* Try to read bonding slave names from sysfs. */
1979 		MKSTR(slaves,
1980 		      "/sys/class/net/%s/master/bonding/slaves", ifname);
1981 		bond_file = fopen(slaves, "r");
1982 		if (bond_file)
1983 			break;
1984 	}
1985 	if (!bond_file)
1986 		return -1;
1987 	/* Use safe format to check maximal buffer length. */
1988 	MLX5_ASSERT(atol(RTE_STR(IF_NAMESIZE)) == IF_NAMESIZE);
1989 	while (fscanf(bond_file, "%" RTE_STR(IF_NAMESIZE) "s", ifname) == 1) {
1990 		char tmp_str[IF_NAMESIZE + 32];
1991 		struct rte_pci_addr pci_addr;
1992 		struct mlx5_switch_info	info;
1993 
1994 		/* Process slave interface names in the loop. */
1995 		snprintf(tmp_str, sizeof(tmp_str),
1996 			 "/sys/class/net/%s", ifname);
1997 		if (mlx5_dev_to_pci_addr(tmp_str, &pci_addr)) {
1998 			DRV_LOG(WARNING, "can not get PCI address"
1999 					 " for netdev \"%s\"", ifname);
2000 			continue;
2001 		}
2002 		/* Slave interface PCI address match found. */
2003 		snprintf(tmp_str, sizeof(tmp_str),
2004 			 "/sys/class/net/%s/phys_port_name", ifname);
2005 		file = fopen(tmp_str, "rb");
2006 		if (!file)
2007 			break;
2008 		info.name_type = MLX5_PHYS_PORT_NAME_TYPE_NOTSET;
2009 		if (fscanf(file, "%32s", tmp_str) == 1)
2010 			mlx5_translate_port_name(tmp_str, &info);
2011 		fclose(file);
2012 		/* Only process PF ports. */
2013 		if (info.name_type != MLX5_PHYS_PORT_NAME_TYPE_LEGACY &&
2014 		    info.name_type != MLX5_PHYS_PORT_NAME_TYPE_UPLINK)
2015 			continue;
2016 		/* Check max bonding member. */
2017 		if (info.port_name >= MLX5_BOND_MAX_PORTS) {
2018 			DRV_LOG(WARNING, "bonding index out of range, "
2019 				"please increase MLX5_BOND_MAX_PORTS: %s",
2020 				tmp_str);
2021 			break;
2022 		}
2023 		/* Match PCI address, allows BDF0+pfx or BDFx+pfx. */
2024 		if (pci_dev->domain == pci_addr.domain &&
2025 		    pci_dev->bus == pci_addr.bus &&
2026 		    pci_dev->devid == pci_addr.devid &&
2027 		    ((pci_dev->function == 0 &&
2028 		      pci_dev->function + owner == pci_addr.function) ||
2029 		     (pci_dev->function == owner &&
2030 		      pci_addr.function == owner)))
2031 			pf = info.port_name;
2032 		/* Get ifindex. */
2033 		snprintf(tmp_str, sizeof(tmp_str),
2034 			 "/sys/class/net/%s/ifindex", ifname);
2035 		file = fopen(tmp_str, "rb");
2036 		if (!file)
2037 			break;
2038 		ret = fscanf(file, "%u", &ifindex);
2039 		fclose(file);
2040 		if (ret != 1)
2041 			break;
2042 		/* Save bonding info. */
2043 		strncpy(bond_info->ports[info.port_name].ifname, ifname,
2044 			sizeof(bond_info->ports[0].ifname));
2045 		bond_info->ports[info.port_name].pci_addr = pci_addr;
2046 		bond_info->ports[info.port_name].ifindex = ifindex;
2047 		bond_info->n_port++;
2048 	}
2049 	if (pf >= 0) {
2050 		/* Get bond interface info */
2051 		ret = mlx5_sysfs_bond_info(ifindex, &bond_info->ifindex,
2052 					   bond_info->ifname);
2053 		if (ret)
2054 			DRV_LOG(ERR, "unable to get bond info: %s",
2055 				strerror(rte_errno));
2056 		else
2057 			DRV_LOG(INFO, "PF device %u, bond device %u(%s)",
2058 				ifindex, bond_info->ifindex, bond_info->ifname);
2059 	}
2060 	return pf;
2061 }
2062 
2063 /**
2064  * Register a PCI device within bonding.
2065  *
2066  * This function spawns Ethernet devices out of a given PCI device and
2067  * bonding owner PF index.
2068  *
2069  * @param[in] pci_dev
2070  *   PCI device information.
2071  * @param[in] req_eth_da
2072  *   Requested ethdev device argument.
2073  * @param[in] owner_id
2074  *   Requested owner PF port ID within bonding device, default to 0.
2075  *
2076  * @return
2077  *   0 on success, a negative errno value otherwise and rte_errno is set.
2078  */
2079 static int
2080 mlx5_os_pci_probe_pf(struct rte_pci_device *pci_dev,
2081 		     struct rte_eth_devargs *req_eth_da,
2082 		     uint16_t owner_id)
2083 {
2084 	struct ibv_device **ibv_list;
2085 	/*
2086 	 * Number of found IB Devices matching with requested PCI BDF.
2087 	 * nd != 1 means there are multiple IB devices over the same
2088 	 * PCI device and we have representors and master.
2089 	 */
2090 	unsigned int nd = 0;
2091 	/*
2092 	 * Number of found IB device Ports. nd = 1 and np = 1..n means
2093 	 * we have the single multiport IB device, and there may be
2094 	 * representors attached to some of found ports.
2095 	 */
2096 	unsigned int np = 0;
2097 	/*
2098 	 * Number of DPDK ethernet devices to Spawn - either over
2099 	 * multiple IB devices or multiple ports of single IB device.
2100 	 * Actually this is the number of iterations to spawn.
2101 	 */
2102 	unsigned int ns = 0;
2103 	/*
2104 	 * Bonding device
2105 	 *   < 0 - no bonding device (single one)
2106 	 *  >= 0 - bonding device (value is slave PF index)
2107 	 */
2108 	int bd = -1;
2109 	struct mlx5_dev_spawn_data *list = NULL;
2110 	struct mlx5_dev_config dev_config;
2111 	unsigned int dev_config_vf;
2112 	struct rte_eth_devargs eth_da = *req_eth_da;
2113 	struct rte_pci_addr owner_pci = pci_dev->addr; /* Owner PF. */
2114 	struct mlx5_bond_info bond_info;
2115 	int ret = -1;
2116 
2117 	if (rte_eal_process_type() == RTE_PROC_PRIMARY)
2118 		mlx5_pmd_socket_init();
2119 	ret = mlx5_init_once();
2120 	if (ret) {
2121 		DRV_LOG(ERR, "unable to init PMD global data: %s",
2122 			strerror(rte_errno));
2123 		return -rte_errno;
2124 	}
2125 	errno = 0;
2126 	ibv_list = mlx5_glue->get_device_list(&ret);
2127 	if (!ibv_list) {
2128 		rte_errno = errno ? errno : ENOSYS;
2129 		DRV_LOG(ERR, "cannot list devices, is ib_uverbs loaded?");
2130 		return -rte_errno;
2131 	}
2132 	/*
2133 	 * First scan the list of all Infiniband devices to find
2134 	 * matching ones, gathering into the list.
2135 	 */
2136 	struct ibv_device *ibv_match[ret + 1];
2137 	int nl_route = mlx5_nl_init(NETLINK_ROUTE);
2138 	int nl_rdma = mlx5_nl_init(NETLINK_RDMA);
2139 	unsigned int i;
2140 
2141 	while (ret-- > 0) {
2142 		struct rte_pci_addr pci_addr;
2143 
2144 		DRV_LOG(DEBUG, "checking device \"%s\"", ibv_list[ret]->name);
2145 		bd = mlx5_device_bond_pci_match
2146 				(ibv_list[ret], &owner_pci, nl_rdma, owner_id,
2147 				 &bond_info);
2148 		if (bd >= 0) {
2149 			/*
2150 			 * Bonding device detected. Only one match is allowed,
2151 			 * the bonding is supported over multi-port IB device,
2152 			 * there should be no matches on representor PCI
2153 			 * functions or non VF LAG bonding devices with
2154 			 * specified address.
2155 			 */
2156 			if (nd) {
2157 				DRV_LOG(ERR,
2158 					"multiple PCI match on bonding device"
2159 					"\"%s\" found", ibv_list[ret]->name);
2160 				rte_errno = ENOENT;
2161 				ret = -rte_errno;
2162 				goto exit;
2163 			}
2164 			/* Amend owner pci address if owner PF ID specified. */
2165 			if (eth_da.nb_representor_ports)
2166 				owner_pci.function += owner_id;
2167 			DRV_LOG(INFO, "PCI information matches for"
2168 				      " slave %d bonding device \"%s\"",
2169 				      bd, ibv_list[ret]->name);
2170 			ibv_match[nd++] = ibv_list[ret];
2171 			break;
2172 		} else {
2173 			/* Bonding device not found. */
2174 			if (mlx5_dev_to_pci_addr
2175 				(ibv_list[ret]->ibdev_path, &pci_addr))
2176 				continue;
2177 			if (owner_pci.domain != pci_addr.domain ||
2178 			    owner_pci.bus != pci_addr.bus ||
2179 			    owner_pci.devid != pci_addr.devid ||
2180 			    owner_pci.function != pci_addr.function)
2181 				continue;
2182 			DRV_LOG(INFO, "PCI information matches for device \"%s\"",
2183 				ibv_list[ret]->name);
2184 			ibv_match[nd++] = ibv_list[ret];
2185 		}
2186 	}
2187 	ibv_match[nd] = NULL;
2188 	if (!nd) {
2189 		/* No device matches, just complain and bail out. */
2190 		DRV_LOG(WARNING,
2191 			"no Verbs device matches PCI device " PCI_PRI_FMT ","
2192 			" are kernel drivers loaded?",
2193 			owner_pci.domain, owner_pci.bus,
2194 			owner_pci.devid, owner_pci.function);
2195 		rte_errno = ENOENT;
2196 		ret = -rte_errno;
2197 		goto exit;
2198 	}
2199 	if (nd == 1) {
2200 		/*
2201 		 * Found single matching device may have multiple ports.
2202 		 * Each port may be representor, we have to check the port
2203 		 * number and check the representors existence.
2204 		 */
2205 		if (nl_rdma >= 0)
2206 			np = mlx5_nl_portnum(nl_rdma, ibv_match[0]->name);
2207 		if (!np)
2208 			DRV_LOG(WARNING, "can not get IB device \"%s\""
2209 					 " ports number", ibv_match[0]->name);
2210 		if (bd >= 0 && !np) {
2211 			DRV_LOG(ERR, "can not get ports"
2212 				     " for bonding device");
2213 			rte_errno = ENOENT;
2214 			ret = -rte_errno;
2215 			goto exit;
2216 		}
2217 	}
2218 #ifndef HAVE_MLX5DV_DR_DEVX_PORT
2219 	if (bd >= 0) {
2220 		/*
2221 		 * This may happen if there is VF LAG kernel support and
2222 		 * application is compiled with older rdma_core library.
2223 		 */
2224 		DRV_LOG(ERR,
2225 			"No kernel/verbs support for VF LAG bonding found.");
2226 		rte_errno = ENOTSUP;
2227 		ret = -rte_errno;
2228 		goto exit;
2229 	}
2230 #endif
2231 	/*
2232 	 * Now we can determine the maximal
2233 	 * amount of devices to be spawned.
2234 	 */
2235 	list = mlx5_malloc(MLX5_MEM_ZERO,
2236 			   sizeof(struct mlx5_dev_spawn_data) *
2237 			   (np ? np : nd),
2238 			   RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
2239 	if (!list) {
2240 		DRV_LOG(ERR, "spawn data array allocation failure");
2241 		rte_errno = ENOMEM;
2242 		ret = -rte_errno;
2243 		goto exit;
2244 	}
2245 	if (bd >= 0 || np > 1) {
2246 		/*
2247 		 * Single IB device with multiple ports found,
2248 		 * it may be E-Switch master device and representors.
2249 		 * We have to perform identification through the ports.
2250 		 */
2251 		MLX5_ASSERT(nl_rdma >= 0);
2252 		MLX5_ASSERT(ns == 0);
2253 		MLX5_ASSERT(nd == 1);
2254 		MLX5_ASSERT(np);
2255 		for (i = 1; i <= np; ++i) {
2256 			list[ns].bond_info = &bond_info;
2257 			list[ns].max_port = np;
2258 			list[ns].phys_port = i;
2259 			list[ns].phys_dev = ibv_match[0];
2260 			list[ns].eth_dev = NULL;
2261 			list[ns].pci_dev = pci_dev;
2262 			list[ns].pf_bond = bd;
2263 			list[ns].ifindex = mlx5_nl_ifindex
2264 				(nl_rdma,
2265 				mlx5_os_get_dev_device_name
2266 						(list[ns].phys_dev), i);
2267 			if (!list[ns].ifindex) {
2268 				/*
2269 				 * No network interface index found for the
2270 				 * specified port, it means there is no
2271 				 * representor on this port. It's OK,
2272 				 * there can be disabled ports, for example
2273 				 * if sriov_numvfs < sriov_totalvfs.
2274 				 */
2275 				continue;
2276 			}
2277 			ret = -1;
2278 			if (nl_route >= 0)
2279 				ret = mlx5_nl_switch_info
2280 					       (nl_route,
2281 						list[ns].ifindex,
2282 						&list[ns].info);
2283 			if (ret || (!list[ns].info.representor &&
2284 				    !list[ns].info.master)) {
2285 				/*
2286 				 * We failed to recognize representors with
2287 				 * Netlink, let's try to perform the task
2288 				 * with sysfs.
2289 				 */
2290 				ret =  mlx5_sysfs_switch_info
2291 						(list[ns].ifindex,
2292 						 &list[ns].info);
2293 			}
2294 #ifdef HAVE_MLX5DV_DR_DEVX_PORT
2295 			if (!ret && bd >= 0) {
2296 				switch (list[ns].info.name_type) {
2297 				case MLX5_PHYS_PORT_NAME_TYPE_UPLINK:
2298 					if (list[ns].info.port_name == bd)
2299 						ns++;
2300 					break;
2301 				case MLX5_PHYS_PORT_NAME_TYPE_PFHPF:
2302 					/* Fallthrough */
2303 				case MLX5_PHYS_PORT_NAME_TYPE_PFVF:
2304 					/* Fallthrough */
2305 				case MLX5_PHYS_PORT_NAME_TYPE_PFSF:
2306 					if (list[ns].info.pf_num == bd)
2307 						ns++;
2308 					break;
2309 				default:
2310 					break;
2311 				}
2312 				continue;
2313 			}
2314 #endif
2315 			if (!ret && (list[ns].info.representor ^
2316 				     list[ns].info.master))
2317 				ns++;
2318 		}
2319 		if (!ns) {
2320 			DRV_LOG(ERR,
2321 				"unable to recognize master/representors"
2322 				" on the IB device with multiple ports");
2323 			rte_errno = ENOENT;
2324 			ret = -rte_errno;
2325 			goto exit;
2326 		}
2327 	} else {
2328 		/*
2329 		 * The existence of several matching entries (nd > 1) means
2330 		 * port representors have been instantiated. No existing Verbs
2331 		 * call nor sysfs entries can tell them apart, this can only
2332 		 * be done through Netlink calls assuming kernel drivers are
2333 		 * recent enough to support them.
2334 		 *
2335 		 * In the event of identification failure through Netlink,
2336 		 * try again through sysfs, then:
2337 		 *
2338 		 * 1. A single IB device matches (nd == 1) with single
2339 		 *    port (np=0/1) and is not a representor, assume
2340 		 *    no switch support.
2341 		 *
2342 		 * 2. Otherwise no safe assumptions can be made;
2343 		 *    complain louder and bail out.
2344 		 */
2345 		for (i = 0; i != nd; ++i) {
2346 			memset(&list[ns].info, 0, sizeof(list[ns].info));
2347 			list[ns].bond_info = NULL;
2348 			list[ns].max_port = 1;
2349 			list[ns].phys_port = 1;
2350 			list[ns].phys_dev = ibv_match[i];
2351 			list[ns].eth_dev = NULL;
2352 			list[ns].pci_dev = pci_dev;
2353 			list[ns].pf_bond = -1;
2354 			list[ns].ifindex = 0;
2355 			if (nl_rdma >= 0)
2356 				list[ns].ifindex = mlx5_nl_ifindex
2357 				(nl_rdma,
2358 				mlx5_os_get_dev_device_name
2359 						(list[ns].phys_dev), 1);
2360 			if (!list[ns].ifindex) {
2361 				char ifname[IF_NAMESIZE];
2362 
2363 				/*
2364 				 * Netlink failed, it may happen with old
2365 				 * ib_core kernel driver (before 4.16).
2366 				 * We can assume there is old driver because
2367 				 * here we are processing single ports IB
2368 				 * devices. Let's try sysfs to retrieve
2369 				 * the ifindex. The method works for
2370 				 * master device only.
2371 				 */
2372 				if (nd > 1) {
2373 					/*
2374 					 * Multiple devices found, assume
2375 					 * representors, can not distinguish
2376 					 * master/representor and retrieve
2377 					 * ifindex via sysfs.
2378 					 */
2379 					continue;
2380 				}
2381 				ret = mlx5_get_ifname_sysfs
2382 					(ibv_match[i]->ibdev_path, ifname);
2383 				if (!ret)
2384 					list[ns].ifindex =
2385 						if_nametoindex(ifname);
2386 				if (!list[ns].ifindex) {
2387 					/*
2388 					 * No network interface index found
2389 					 * for the specified device, it means
2390 					 * there it is neither representor
2391 					 * nor master.
2392 					 */
2393 					continue;
2394 				}
2395 			}
2396 			ret = -1;
2397 			if (nl_route >= 0)
2398 				ret = mlx5_nl_switch_info
2399 					       (nl_route,
2400 						list[ns].ifindex,
2401 						&list[ns].info);
2402 			if (ret || (!list[ns].info.representor &&
2403 				    !list[ns].info.master)) {
2404 				/*
2405 				 * We failed to recognize representors with
2406 				 * Netlink, let's try to perform the task
2407 				 * with sysfs.
2408 				 */
2409 				ret =  mlx5_sysfs_switch_info
2410 						(list[ns].ifindex,
2411 						 &list[ns].info);
2412 			}
2413 			if (!ret && (list[ns].info.representor ^
2414 				     list[ns].info.master)) {
2415 				ns++;
2416 			} else if ((nd == 1) &&
2417 				   !list[ns].info.representor &&
2418 				   !list[ns].info.master) {
2419 				/*
2420 				 * Single IB device with
2421 				 * one physical port and
2422 				 * attached network device.
2423 				 * May be SRIOV is not enabled
2424 				 * or there is no representors.
2425 				 */
2426 				DRV_LOG(INFO, "no E-Switch support detected");
2427 				ns++;
2428 				break;
2429 			}
2430 		}
2431 		if (!ns) {
2432 			DRV_LOG(ERR,
2433 				"unable to recognize master/representors"
2434 				" on the multiple IB devices");
2435 			rte_errno = ENOENT;
2436 			ret = -rte_errno;
2437 			goto exit;
2438 		}
2439 		/*
2440 		 * New kernels may add the switch_id attribute for the case
2441 		 * there is no E-Switch and we wrongly recognized the
2442 		 * only device as master. Override this if there is the
2443 		 * single device with single port and new device name
2444 		 * format present.
2445 		 */
2446 		if (nd == 1 &&
2447 		    list[0].info.name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK) {
2448 			list[0].info.master = 0;
2449 			list[0].info.representor = 0;
2450 		}
2451 	}
2452 	MLX5_ASSERT(ns);
2453 	/*
2454 	 * Sort list to probe devices in natural order for users convenience
2455 	 * (i.e. master first, then representors from lowest to highest ID).
2456 	 */
2457 	qsort(list, ns, sizeof(*list), mlx5_dev_spawn_data_cmp);
2458 	/* Device specific configuration. */
2459 	switch (pci_dev->id.device_id) {
2460 	case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
2461 	case PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF:
2462 	case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
2463 	case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
2464 	case PCI_DEVICE_ID_MELLANOX_CONNECTX5BFVF:
2465 	case PCI_DEVICE_ID_MELLANOX_CONNECTX6VF:
2466 	case PCI_DEVICE_ID_MELLANOX_CONNECTXVF:
2467 		dev_config_vf = 1;
2468 		break;
2469 	default:
2470 		dev_config_vf = 0;
2471 		break;
2472 	}
2473 	if (eth_da.type != RTE_ETH_REPRESENTOR_NONE) {
2474 		/* Set devargs default values. */
2475 		if (eth_da.nb_mh_controllers == 0) {
2476 			eth_da.nb_mh_controllers = 1;
2477 			eth_da.mh_controllers[0] = 0;
2478 		}
2479 		if (eth_da.nb_ports == 0 && ns > 0) {
2480 			if (list[0].pf_bond >= 0 && list[0].info.representor)
2481 				DRV_LOG(WARNING, "Representor on Bonding device should use pf#vf# syntax: %s",
2482 					pci_dev->device.devargs->args);
2483 			eth_da.nb_ports = 1;
2484 			eth_da.ports[0] = list[0].info.pf_num;
2485 		}
2486 		if (eth_da.nb_representor_ports == 0) {
2487 			eth_da.nb_representor_ports = 1;
2488 			eth_da.representor_ports[0] = 0;
2489 		}
2490 	}
2491 	for (i = 0; i != ns; ++i) {
2492 		uint32_t restore;
2493 
2494 		/* Default configuration. */
2495 		memset(&dev_config, 0, sizeof(struct mlx5_dev_config));
2496 		dev_config.vf = dev_config_vf;
2497 		dev_config.mps = MLX5_ARG_UNSET;
2498 		dev_config.dbnc = MLX5_ARG_UNSET;
2499 		dev_config.rx_vec_en = 1;
2500 		dev_config.txq_inline_max = MLX5_ARG_UNSET;
2501 		dev_config.txq_inline_min = MLX5_ARG_UNSET;
2502 		dev_config.txq_inline_mpw = MLX5_ARG_UNSET;
2503 		dev_config.txqs_inline = MLX5_ARG_UNSET;
2504 		dev_config.vf_nl_en = 1;
2505 		dev_config.mr_ext_memseg_en = 1;
2506 		dev_config.mprq.max_memcpy_len = MLX5_MPRQ_MEMCPY_DEFAULT_LEN;
2507 		dev_config.mprq.min_rxqs_num = MLX5_MPRQ_MIN_RXQS;
2508 		dev_config.dv_esw_en = 1;
2509 		dev_config.dv_flow_en = 1;
2510 		dev_config.decap_en = 1;
2511 		dev_config.log_hp_size = MLX5_ARG_UNSET;
2512 		dev_config.allow_duplicate_pattern = 1;
2513 		list[i].eth_dev = mlx5_dev_spawn(&pci_dev->device,
2514 						 &list[i],
2515 						 &dev_config,
2516 						 &eth_da);
2517 		if (!list[i].eth_dev) {
2518 			if (rte_errno != EBUSY && rte_errno != EEXIST)
2519 				break;
2520 			/* Device is disabled or already spawned. Ignore it. */
2521 			continue;
2522 		}
2523 		restore = list[i].eth_dev->data->dev_flags;
2524 		rte_eth_copy_pci_info(list[i].eth_dev, pci_dev);
2525 		/* Restore non-PCI flags cleared by the above call. */
2526 		list[i].eth_dev->data->dev_flags |= restore;
2527 		rte_eth_dev_probing_finish(list[i].eth_dev);
2528 	}
2529 	if (i != ns) {
2530 		DRV_LOG(ERR,
2531 			"probe of PCI device " PCI_PRI_FMT " aborted after"
2532 			" encountering an error: %s",
2533 			owner_pci.domain, owner_pci.bus,
2534 			owner_pci.devid, owner_pci.function,
2535 			strerror(rte_errno));
2536 		ret = -rte_errno;
2537 		/* Roll back. */
2538 		while (i--) {
2539 			if (!list[i].eth_dev)
2540 				continue;
2541 			mlx5_dev_close(list[i].eth_dev);
2542 			/* mac_addrs must not be freed because in dev_private */
2543 			list[i].eth_dev->data->mac_addrs = NULL;
2544 			claim_zero(rte_eth_dev_release_port(list[i].eth_dev));
2545 		}
2546 		/* Restore original error. */
2547 		rte_errno = -ret;
2548 	} else {
2549 		ret = 0;
2550 	}
2551 exit:
2552 	/*
2553 	 * Do the routine cleanup:
2554 	 * - close opened Netlink sockets
2555 	 * - free allocated spawn data array
2556 	 * - free the Infiniband device list
2557 	 */
2558 	if (nl_rdma >= 0)
2559 		close(nl_rdma);
2560 	if (nl_route >= 0)
2561 		close(nl_route);
2562 	if (list)
2563 		mlx5_free(list);
2564 	MLX5_ASSERT(ibv_list);
2565 	mlx5_glue->free_device_list(ibv_list);
2566 	return ret;
2567 }
2568 
2569 /**
2570  * DPDK callback to register a PCI device.
2571  *
2572  * This function spawns Ethernet devices out of a given PCI device.
2573  *
2574  * @param[in] pci_drv
2575  *   PCI driver structure (mlx5_driver).
2576  * @param[in] pci_dev
2577  *   PCI device information.
2578  *
2579  * @return
2580  *   0 on success, a negative errno value otherwise and rte_errno is set.
2581  */
2582 int
2583 mlx5_os_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
2584 		  struct rte_pci_device *pci_dev)
2585 {
2586 	struct rte_eth_devargs eth_da = { .type = RTE_ETH_REPRESENTOR_NONE };
2587 	int ret = 0;
2588 	uint16_t p;
2589 
2590 	if (pci_dev->device.devargs) {
2591 		/* Parse representor information from device argument. */
2592 		if (pci_dev->device.devargs->cls_str)
2593 			ret = rte_eth_devargs_parse
2594 				(pci_dev->device.devargs->cls_str, &eth_da);
2595 		if (ret) {
2596 			DRV_LOG(ERR, "failed to parse device arguments: %s",
2597 				pci_dev->device.devargs->cls_str);
2598 			return -rte_errno;
2599 		}
2600 		if (eth_da.type == RTE_ETH_REPRESENTOR_NONE) {
2601 			/* Support legacy device argument */
2602 			ret = rte_eth_devargs_parse
2603 				(pci_dev->device.devargs->args, &eth_da);
2604 			if (ret) {
2605 				DRV_LOG(ERR, "failed to parse device arguments: %s",
2606 					pci_dev->device.devargs->args);
2607 				return -rte_errno;
2608 			}
2609 		}
2610 	}
2611 
2612 	if (eth_da.nb_ports > 0) {
2613 		/* Iterate all port if devargs pf is range: "pf[0-1]vf[...]". */
2614 		for (p = 0; p < eth_da.nb_ports; p++)
2615 			ret = mlx5_os_pci_probe_pf(pci_dev, &eth_da,
2616 						   eth_da.ports[p]);
2617 	} else {
2618 		ret = mlx5_os_pci_probe_pf(pci_dev, &eth_da, 0);
2619 	}
2620 	return ret;
2621 }
2622 
2623 static int
2624 mlx5_config_doorbell_mapping_env(const struct mlx5_dev_config *config)
2625 {
2626 	char *env;
2627 	int value;
2628 
2629 	MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
2630 	/* Get environment variable to store. */
2631 	env = getenv(MLX5_SHUT_UP_BF);
2632 	value = env ? !!strcmp(env, "0") : MLX5_ARG_UNSET;
2633 	if (config->dbnc == MLX5_ARG_UNSET)
2634 		setenv(MLX5_SHUT_UP_BF, MLX5_SHUT_UP_BF_DEFAULT, 1);
2635 	else
2636 		setenv(MLX5_SHUT_UP_BF,
2637 		       config->dbnc == MLX5_TXDB_NCACHED ? "1" : "0", 1);
2638 	return value;
2639 }
2640 
2641 static void
2642 mlx5_restore_doorbell_mapping_env(int value)
2643 {
2644 	MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
2645 	/* Restore the original environment variable state. */
2646 	if (value == MLX5_ARG_UNSET)
2647 		unsetenv(MLX5_SHUT_UP_BF);
2648 	else
2649 		setenv(MLX5_SHUT_UP_BF, value ? "1" : "0", 1);
2650 }
2651 
2652 /**
2653  * Extract pdn of PD object using DV API.
2654  *
2655  * @param[in] pd
2656  *   Pointer to the verbs PD object.
2657  * @param[out] pdn
2658  *   Pointer to the PD object number variable.
2659  *
2660  * @return
2661  *   0 on success, error value otherwise.
2662  */
2663 int
2664 mlx5_os_get_pdn(void *pd, uint32_t *pdn)
2665 {
2666 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
2667 	struct mlx5dv_obj obj;
2668 	struct mlx5dv_pd pd_info;
2669 	int ret = 0;
2670 
2671 	obj.pd.in = pd;
2672 	obj.pd.out = &pd_info;
2673 	ret = mlx5_glue->dv_init_obj(&obj, MLX5DV_OBJ_PD);
2674 	if (ret) {
2675 		DRV_LOG(DEBUG, "Fail to get PD object info");
2676 		return ret;
2677 	}
2678 	*pdn = pd_info.pdn;
2679 	return 0;
2680 #else
2681 	(void)pd;
2682 	(void)pdn;
2683 	return -ENOTSUP;
2684 #endif /* HAVE_IBV_FLOW_DV_SUPPORT */
2685 }
2686 
2687 /**
2688  * Function API to open IB device.
2689  *
2690  * This function calls the Linux glue APIs to open a device.
2691  *
2692  * @param[in] spawn
2693  *   Pointer to the IB device attributes (name, port, etc).
2694  * @param[out] config
2695  *   Pointer to device configuration structure.
2696  * @param[out] sh
2697  *   Pointer to shared context structure.
2698  *
2699  * @return
2700  *   0 on success, a positive error value otherwise.
2701  */
2702 int
2703 mlx5_os_open_device(const struct mlx5_dev_spawn_data *spawn,
2704 		     const struct mlx5_dev_config *config,
2705 		     struct mlx5_dev_ctx_shared *sh)
2706 {
2707 	int dbmap_env;
2708 	int err = 0;
2709 
2710 	sh->numa_node = spawn->pci_dev->device.numa_node;
2711 	pthread_mutex_init(&sh->txpp.mutex, NULL);
2712 	/*
2713 	 * Configure environment variable "MLX5_BF_SHUT_UP"
2714 	 * before the device creation. The rdma_core library
2715 	 * checks the variable at device creation and
2716 	 * stores the result internally.
2717 	 */
2718 	dbmap_env = mlx5_config_doorbell_mapping_env(config);
2719 	/* Try to open IB device with DV first, then usual Verbs. */
2720 	errno = 0;
2721 	sh->ctx = mlx5_glue->dv_open_device(spawn->phys_dev);
2722 	if (sh->ctx) {
2723 		sh->devx = 1;
2724 		DRV_LOG(DEBUG, "DevX is supported");
2725 		/* The device is created, no need for environment. */
2726 		mlx5_restore_doorbell_mapping_env(dbmap_env);
2727 	} else {
2728 		/* The environment variable is still configured. */
2729 		sh->ctx = mlx5_glue->open_device(spawn->phys_dev);
2730 		err = errno ? errno : ENODEV;
2731 		/*
2732 		 * The environment variable is not needed anymore,
2733 		 * all device creation attempts are completed.
2734 		 */
2735 		mlx5_restore_doorbell_mapping_env(dbmap_env);
2736 		if (!sh->ctx)
2737 			return err;
2738 		DRV_LOG(DEBUG, "DevX is NOT supported");
2739 		err = 0;
2740 	}
2741 	if (!err && sh->ctx) {
2742 		/* Hint libmlx5 to use PMD allocator for data plane resources */
2743 		mlx5_glue->dv_set_context_attr(sh->ctx,
2744 			MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
2745 			(void *)((uintptr_t)&(struct mlx5dv_ctx_allocators){
2746 				.alloc = &mlx5_alloc_verbs_buf,
2747 				.free = &mlx5_free_verbs_buf,
2748 				.data = sh,
2749 			}));
2750 	}
2751 	return err;
2752 }
2753 
2754 /**
2755  * Install shared asynchronous device events handler.
2756  * This function is implemented to support event sharing
2757  * between multiple ports of single IB device.
2758  *
2759  * @param sh
2760  *   Pointer to mlx5_dev_ctx_shared object.
2761  */
2762 void
2763 mlx5_os_dev_shared_handler_install(struct mlx5_dev_ctx_shared *sh)
2764 {
2765 	int ret;
2766 	int flags;
2767 
2768 	sh->intr_handle.fd = -1;
2769 	flags = fcntl(((struct ibv_context *)sh->ctx)->async_fd, F_GETFL);
2770 	ret = fcntl(((struct ibv_context *)sh->ctx)->async_fd,
2771 		    F_SETFL, flags | O_NONBLOCK);
2772 	if (ret) {
2773 		DRV_LOG(INFO, "failed to change file descriptor async event"
2774 			" queue");
2775 	} else {
2776 		sh->intr_handle.fd = ((struct ibv_context *)sh->ctx)->async_fd;
2777 		sh->intr_handle.type = RTE_INTR_HANDLE_EXT;
2778 		if (rte_intr_callback_register(&sh->intr_handle,
2779 					mlx5_dev_interrupt_handler, sh)) {
2780 			DRV_LOG(INFO, "Fail to install the shared interrupt.");
2781 			sh->intr_handle.fd = -1;
2782 		}
2783 	}
2784 	if (sh->devx) {
2785 #ifdef HAVE_IBV_DEVX_ASYNC
2786 		sh->intr_handle_devx.fd = -1;
2787 		sh->devx_comp =
2788 			(void *)mlx5_glue->devx_create_cmd_comp(sh->ctx);
2789 		struct mlx5dv_devx_cmd_comp *devx_comp = sh->devx_comp;
2790 		if (!devx_comp) {
2791 			DRV_LOG(INFO, "failed to allocate devx_comp.");
2792 			return;
2793 		}
2794 		flags = fcntl(devx_comp->fd, F_GETFL);
2795 		ret = fcntl(devx_comp->fd, F_SETFL, flags | O_NONBLOCK);
2796 		if (ret) {
2797 			DRV_LOG(INFO, "failed to change file descriptor"
2798 				" devx comp");
2799 			return;
2800 		}
2801 		sh->intr_handle_devx.fd = devx_comp->fd;
2802 		sh->intr_handle_devx.type = RTE_INTR_HANDLE_EXT;
2803 		if (rte_intr_callback_register(&sh->intr_handle_devx,
2804 					mlx5_dev_interrupt_handler_devx, sh)) {
2805 			DRV_LOG(INFO, "Fail to install the devx shared"
2806 				" interrupt.");
2807 			sh->intr_handle_devx.fd = -1;
2808 		}
2809 #endif /* HAVE_IBV_DEVX_ASYNC */
2810 	}
2811 }
2812 
2813 /**
2814  * Uninstall shared asynchronous device events handler.
2815  * This function is implemented to support event sharing
2816  * between multiple ports of single IB device.
2817  *
2818  * @param dev
2819  *   Pointer to mlx5_dev_ctx_shared object.
2820  */
2821 void
2822 mlx5_os_dev_shared_handler_uninstall(struct mlx5_dev_ctx_shared *sh)
2823 {
2824 	if (sh->intr_handle.fd >= 0)
2825 		mlx5_intr_callback_unregister(&sh->intr_handle,
2826 					      mlx5_dev_interrupt_handler, sh);
2827 #ifdef HAVE_IBV_DEVX_ASYNC
2828 	if (sh->intr_handle_devx.fd >= 0)
2829 		rte_intr_callback_unregister(&sh->intr_handle_devx,
2830 				  mlx5_dev_interrupt_handler_devx, sh);
2831 	if (sh->devx_comp)
2832 		mlx5_glue->devx_destroy_cmd_comp(sh->devx_comp);
2833 #endif
2834 }
2835 
2836 /**
2837  * Read statistics by a named counter.
2838  *
2839  * @param[in] priv
2840  *   Pointer to the private device data structure.
2841  * @param[in] ctr_name
2842  *   Pointer to the name of the statistic counter to read
2843  * @param[out] stat
2844  *   Pointer to read statistic value.
2845  * @return
2846  *   0 on success and stat is valud, 1 if failed to read the value
2847  *   rte_errno is set.
2848  *
2849  */
2850 int
2851 mlx5_os_read_dev_stat(struct mlx5_priv *priv, const char *ctr_name,
2852 		      uint64_t *stat)
2853 {
2854 	int fd;
2855 
2856 	if (priv->sh) {
2857 		if (priv->q_counters != NULL &&
2858 		    strcmp(ctr_name, "out_of_buffer") == 0)
2859 			return mlx5_devx_cmd_queue_counter_query
2860 					(priv->q_counters, 0, (uint32_t *)stat);
2861 		MKSTR(path, "%s/ports/%d/hw_counters/%s",
2862 		      priv->sh->ibdev_path,
2863 		      priv->dev_port,
2864 		      ctr_name);
2865 		fd = open(path, O_RDONLY);
2866 		/*
2867 		 * in switchdev the file location is not per port
2868 		 * but rather in <ibdev_path>/hw_counters/<file_name>.
2869 		 */
2870 		if (fd == -1) {
2871 			MKSTR(path1, "%s/hw_counters/%s",
2872 			      priv->sh->ibdev_path,
2873 			      ctr_name);
2874 			fd = open(path1, O_RDONLY);
2875 		}
2876 		if (fd != -1) {
2877 			char buf[21] = {'\0'};
2878 			ssize_t n = read(fd, buf, sizeof(buf));
2879 
2880 			close(fd);
2881 			if (n != -1) {
2882 				*stat = strtoull(buf, NULL, 10);
2883 				return 0;
2884 			}
2885 		}
2886 	}
2887 	*stat = 0;
2888 	return 1;
2889 }
2890 
2891 /**
2892  * Set the reg_mr and dereg_mr call backs
2893  *
2894  * @param reg_mr_cb[out]
2895  *   Pointer to reg_mr func
2896  * @param dereg_mr_cb[out]
2897  *   Pointer to dereg_mr func
2898  *
2899  */
2900 void
2901 mlx5_os_set_reg_mr_cb(mlx5_reg_mr_t *reg_mr_cb,
2902 		      mlx5_dereg_mr_t *dereg_mr_cb)
2903 {
2904 	*reg_mr_cb = mlx5_mr_verbs_ops.reg_mr;
2905 	*dereg_mr_cb = mlx5_mr_verbs_ops.dereg_mr;
2906 }
2907 
2908 /**
2909  * Remove a MAC address from device
2910  *
2911  * @param dev
2912  *   Pointer to Ethernet device structure.
2913  * @param index
2914  *   MAC address index.
2915  */
2916 void
2917 mlx5_os_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
2918 {
2919 	struct mlx5_priv *priv = dev->data->dev_private;
2920 	const int vf = priv->config.vf;
2921 
2922 	if (vf)
2923 		mlx5_nl_mac_addr_remove(priv->nl_socket_route,
2924 					mlx5_ifindex(dev), priv->mac_own,
2925 					&dev->data->mac_addrs[index], index);
2926 }
2927 
2928 /**
2929  * Adds a MAC address to the device
2930  *
2931  * @param dev
2932  *   Pointer to Ethernet device structure.
2933  * @param mac_addr
2934  *   MAC address to register.
2935  * @param index
2936  *   MAC address index.
2937  *
2938  * @return
2939  *   0 on success, a negative errno value otherwise
2940  */
2941 int
2942 mlx5_os_mac_addr_add(struct rte_eth_dev *dev, struct rte_ether_addr *mac,
2943 		     uint32_t index)
2944 {
2945 	struct mlx5_priv *priv = dev->data->dev_private;
2946 	const int vf = priv->config.vf;
2947 	int ret = 0;
2948 
2949 	if (vf)
2950 		ret = mlx5_nl_mac_addr_add(priv->nl_socket_route,
2951 					   mlx5_ifindex(dev), priv->mac_own,
2952 					   mac, index);
2953 	return ret;
2954 }
2955 
2956 /**
2957  * Modify a VF MAC address
2958  *
2959  * @param priv
2960  *   Pointer to device private data.
2961  * @param mac_addr
2962  *   MAC address to modify into.
2963  * @param iface_idx
2964  *   Net device interface index
2965  * @param vf_index
2966  *   VF index
2967  *
2968  * @return
2969  *   0 on success, a negative errno value otherwise
2970  */
2971 int
2972 mlx5_os_vf_mac_addr_modify(struct mlx5_priv *priv,
2973 			   unsigned int iface_idx,
2974 			   struct rte_ether_addr *mac_addr,
2975 			   int vf_index)
2976 {
2977 	return mlx5_nl_vf_mac_addr_modify
2978 		(priv->nl_socket_route, iface_idx, mac_addr, vf_index);
2979 }
2980 
2981 /**
2982  * Set device promiscuous mode
2983  *
2984  * @param dev
2985  *   Pointer to Ethernet device structure.
2986  * @param enable
2987  *   0 - promiscuous is disabled, otherwise - enabled
2988  *
2989  * @return
2990  *   0 on success, a negative error value otherwise
2991  */
2992 int
2993 mlx5_os_set_promisc(struct rte_eth_dev *dev, int enable)
2994 {
2995 	struct mlx5_priv *priv = dev->data->dev_private;
2996 
2997 	return mlx5_nl_promisc(priv->nl_socket_route,
2998 			       mlx5_ifindex(dev), !!enable);
2999 }
3000 
3001 /**
3002  * Set device promiscuous mode
3003  *
3004  * @param dev
3005  *   Pointer to Ethernet device structure.
3006  * @param enable
3007  *   0 - all multicase is disabled, otherwise - enabled
3008  *
3009  * @return
3010  *   0 on success, a negative error value otherwise
3011  */
3012 int
3013 mlx5_os_set_allmulti(struct rte_eth_dev *dev, int enable)
3014 {
3015 	struct mlx5_priv *priv = dev->data->dev_private;
3016 
3017 	return mlx5_nl_allmulti(priv->nl_socket_route,
3018 				mlx5_ifindex(dev), !!enable);
3019 }
3020 
3021 /**
3022  * Flush device MAC addresses
3023  *
3024  * @param dev
3025  *   Pointer to Ethernet device structure.
3026  *
3027  */
3028 void
3029 mlx5_os_mac_addr_flush(struct rte_eth_dev *dev)
3030 {
3031 	struct mlx5_priv *priv = dev->data->dev_private;
3032 
3033 	mlx5_nl_mac_addr_flush(priv->nl_socket_route, mlx5_ifindex(dev),
3034 			       dev->data->mac_addrs,
3035 			       MLX5_MAX_MAC_ADDRESSES, priv->mac_own);
3036 }
3037