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