xref: /dpdk/drivers/net/mlx5/linux/mlx5_os.c (revision 4cbeba6fdbc4d58da40c2051a8543ca69d2eac17)
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 struct mlx5_indexed_pool_config 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 
1084 	/* Determine if this port representor is supposed to be spawned. */
1085 	if (switch_info->representor && dpdk_dev->devargs &&
1086 	    !mlx5_representor_match(spawn, eth_da))
1087 		return NULL;
1088 	/* Build device name. */
1089 	if (spawn->pf_bond >= 0) {
1090 		/* Bonding device. */
1091 		if (!switch_info->representor) {
1092 			err = snprintf(name, sizeof(name), "%s_%s",
1093 				       dpdk_dev->name, spawn->phys_dev_name);
1094 		} else {
1095 			err = snprintf(name, sizeof(name), "%s_%s_representor_c%dpf%d%s%u",
1096 				dpdk_dev->name, spawn->phys_dev_name,
1097 				switch_info->ctrl_num,
1098 				switch_info->pf_num,
1099 				switch_info->name_type ==
1100 				MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
1101 				switch_info->port_name);
1102 		}
1103 	} else if (mlx5_is_probed_port_on_mpesw_device(spawn)) {
1104 		/* MPESW device. */
1105 		if (switch_info->name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK) {
1106 			err = snprintf(name, sizeof(name), "%s_p%d",
1107 				       dpdk_dev->name, spawn->mpesw_port);
1108 		} else {
1109 			err = snprintf(name, sizeof(name), "%s_representor_c%dpf%d%s%u",
1110 				dpdk_dev->name,
1111 				switch_info->ctrl_num,
1112 				switch_info->pf_num,
1113 				switch_info->name_type ==
1114 				MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
1115 				switch_info->port_name);
1116 		}
1117 	} else {
1118 		/* Single device. */
1119 		if (!switch_info->representor)
1120 			strlcpy(name, dpdk_dev->name, sizeof(name));
1121 		else
1122 			err = snprintf(name, sizeof(name), "%s_representor_%s%u",
1123 				 dpdk_dev->name,
1124 				 switch_info->name_type ==
1125 				 MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
1126 				 switch_info->port_name);
1127 	}
1128 	if (err >= (int)sizeof(name))
1129 		DRV_LOG(WARNING, "device name overflow %s", name);
1130 	/* check if the device is already spawned */
1131 	if (rte_eth_dev_get_port_by_name(name, &port_id) == 0) {
1132 		/*
1133 		 * When device is already spawned, its devargs should be set
1134 		 * as used. otherwise, mlx5_kvargs_validate() will fail.
1135 		 */
1136 		if (mkvlist)
1137 			mlx5_port_args_set_used(name, port_id, mkvlist);
1138 		rte_errno = EEXIST;
1139 		return NULL;
1140 	}
1141 	DRV_LOG(DEBUG, "naming Ethernet device \"%s\"", name);
1142 	if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1143 		struct mlx5_mp_id mp_id;
1144 		int fd;
1145 
1146 		eth_dev = rte_eth_dev_attach_secondary(name);
1147 		if (eth_dev == NULL) {
1148 			DRV_LOG(ERR, "can not attach rte ethdev");
1149 			rte_errno = ENOMEM;
1150 			return NULL;
1151 		}
1152 		eth_dev->device = dpdk_dev;
1153 		eth_dev->dev_ops = &mlx5_dev_sec_ops;
1154 		eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1155 		eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1156 		err = mlx5_proc_priv_init(eth_dev);
1157 		if (err)
1158 			return NULL;
1159 		mlx5_mp_id_init(&mp_id, eth_dev->data->port_id);
1160 		/* Receive command fd from primary process */
1161 		fd = mlx5_mp_req_verbs_cmd_fd(&mp_id);
1162 		if (fd < 0)
1163 			goto err_secondary;
1164 		/* Remap UAR for Tx queues. */
1165 		err = mlx5_tx_uar_init_secondary(eth_dev, fd);
1166 		close(fd);
1167 		if (err)
1168 			goto err_secondary;
1169 		/*
1170 		 * Ethdev pointer is still required as input since
1171 		 * the primary device is not accessible from the
1172 		 * secondary process.
1173 		 */
1174 		eth_dev->rx_pkt_burst = mlx5_select_rx_function(eth_dev);
1175 		eth_dev->tx_pkt_burst = mlx5_select_tx_function(eth_dev);
1176 		return eth_dev;
1177 err_secondary:
1178 		mlx5_dev_close(eth_dev);
1179 		return NULL;
1180 	}
1181 	sh = mlx5_alloc_shared_dev_ctx(spawn, mkvlist);
1182 	if (!sh)
1183 		return NULL;
1184 	nl_rdma = mlx5_nl_init(NETLINK_RDMA, 0);
1185 	/* Check port status. */
1186 	if (spawn->phys_port <= UINT8_MAX) {
1187 		/* Legacy Verbs api only support u8 port number. */
1188 		err = mlx5_glue->query_port(sh->cdev->ctx, spawn->phys_port,
1189 					    &port_attr);
1190 		if (err) {
1191 			DRV_LOG(ERR, "port query failed: %s", strerror(err));
1192 			goto error;
1193 		}
1194 		if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
1195 			DRV_LOG(ERR, "port is not configured in Ethernet mode");
1196 			err = EINVAL;
1197 			goto error;
1198 		}
1199 	} else if (nl_rdma >= 0) {
1200 		/* IB doesn't allow more than 255 ports, must be Ethernet. */
1201 		err = mlx5_nl_port_state(nl_rdma,
1202 			spawn->phys_dev_name,
1203 			spawn->phys_port);
1204 		if (err < 0) {
1205 			DRV_LOG(INFO, "Failed to get netlink port state: %s",
1206 				strerror(rte_errno));
1207 			err = -rte_errno;
1208 			goto error;
1209 		}
1210 		port_attr.state = (enum ibv_port_state)err;
1211 	}
1212 	if (port_attr.state != IBV_PORT_ACTIVE)
1213 		DRV_LOG(INFO, "port is not active: \"%s\" (%d)",
1214 			mlx5_glue->port_state_str(port_attr.state),
1215 			port_attr.state);
1216 	/* Allocate private eth device data. */
1217 	priv = mlx5_malloc(MLX5_MEM_ZERO | MLX5_MEM_RTE,
1218 			   sizeof(*priv),
1219 			   RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
1220 	if (priv == NULL) {
1221 		DRV_LOG(ERR, "priv allocation failure");
1222 		err = ENOMEM;
1223 		goto error;
1224 	}
1225 	/*
1226 	 * When user configures remote PD and CTX and device creates RxQ by
1227 	 * DevX, external RxQ is both supported and requested.
1228 	 */
1229 	if (mlx5_imported_pd_and_ctx(sh->cdev) && mlx5_devx_obj_ops_en(sh)) {
1230 		priv->ext_rxqs = mlx5_malloc(MLX5_MEM_ZERO | MLX5_MEM_RTE,
1231 					     sizeof(struct mlx5_external_q) *
1232 					     MLX5_MAX_EXT_RX_QUEUES, 0,
1233 					     SOCKET_ID_ANY);
1234 		if (priv->ext_rxqs == NULL) {
1235 			DRV_LOG(ERR, "Fail to allocate external RxQ array.");
1236 			err = ENOMEM;
1237 			goto error;
1238 		}
1239 		priv->ext_txqs = mlx5_malloc(MLX5_MEM_ZERO | MLX5_MEM_RTE,
1240 					     sizeof(struct mlx5_external_q) *
1241 					     MLX5_MAX_EXT_TX_QUEUES, 0,
1242 					     SOCKET_ID_ANY);
1243 		if (priv->ext_txqs == NULL) {
1244 			DRV_LOG(ERR, "Fail to allocate external TxQ array.");
1245 			err = ENOMEM;
1246 			goto error;
1247 		}
1248 		DRV_LOG(DEBUG, "External queue is supported.");
1249 	}
1250 	priv->sh = sh;
1251 	priv->dev_port = spawn->phys_port;
1252 	priv->pci_dev = spawn->pci_dev;
1253 	priv->mtu = RTE_ETHER_MTU;
1254 	/* Some internal functions rely on Netlink sockets, open them now. */
1255 	priv->nl_socket_rdma = nl_rdma;
1256 	priv->nl_socket_route =	mlx5_nl_init(NETLINK_ROUTE, 0);
1257 	priv->representor = !!switch_info->representor;
1258 	priv->master = !!switch_info->master;
1259 	priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
1260 	priv->vport_meta_tag = 0;
1261 	priv->vport_meta_mask = 0;
1262 	priv->pf_bond = spawn->pf_bond;
1263 	priv->mpesw_port = spawn->mpesw_port;
1264 	priv->mpesw_uplink = false;
1265 	priv->mpesw_owner = spawn->info.mpesw_owner;
1266 	if (mlx5_is_port_on_mpesw_device(priv))
1267 		priv->mpesw_uplink = (spawn->info.name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK);
1268 
1269 	DRV_LOG(DEBUG,
1270 		"dev_port=%u bus=%s pci=%s master=%d representor=%d pf_bond=%d "
1271 		"mpesw_port=%d mpesw_uplink=%d",
1272 		priv->dev_port, dpdk_dev->bus->name,
1273 		priv->pci_dev ? priv->pci_dev->name : "NONE",
1274 		priv->master, priv->representor, priv->pf_bond,
1275 		priv->mpesw_port, priv->mpesw_uplink);
1276 
1277 	if (mlx5_is_port_on_mpesw_device(priv) && priv->sh->config.dv_flow_en != 2) {
1278 		DRV_LOG(ERR, "MPESW device is supported only with HWS");
1279 		err = ENOTSUP;
1280 		goto error;
1281 	}
1282 	/*
1283 	 * If we have E-Switch we should determine the vport attributes.
1284 	 * E-Switch may use either source vport field or reg_c[0] metadata
1285 	 * register to match on vport index. The engaged part of metadata
1286 	 * register is defined by mask.
1287 	 */
1288 	if (sh->esw_mode) {
1289 		err = mlx5_glue->devx_port_query(sh->cdev->ctx,
1290 						 spawn->phys_port,
1291 						 &vport_info);
1292 		if (err) {
1293 			DRV_LOG(WARNING,
1294 				"Cannot query devx port %d on device %s",
1295 				spawn->phys_port, spawn->phys_dev_name);
1296 			vport_info.query_flags = 0;
1297 		}
1298 	}
1299 	if (vport_info.query_flags & MLX5_PORT_QUERY_REG_C0) {
1300 		priv->vport_meta_tag = vport_info.vport_meta_tag;
1301 		priv->vport_meta_mask = vport_info.vport_meta_mask;
1302 		if (!priv->vport_meta_mask) {
1303 			DRV_LOG(ERR,
1304 				"vport zero mask for port %d on bonding device %s",
1305 				spawn->phys_port, spawn->phys_dev_name);
1306 			err = ENOTSUP;
1307 			goto error;
1308 		}
1309 		if (priv->vport_meta_tag & ~priv->vport_meta_mask) {
1310 			DRV_LOG(ERR,
1311 				"Invalid vport tag for port %d on bonding device %s",
1312 				spawn->phys_port, spawn->phys_dev_name);
1313 			err = ENOTSUP;
1314 			goto error;
1315 		}
1316 	}
1317 	if (vport_info.query_flags & MLX5_PORT_QUERY_VPORT) {
1318 		priv->vport_id = vport_info.vport_id;
1319 	} else if (spawn->pf_bond >= 0 && sh->esw_mode) {
1320 		DRV_LOG(ERR,
1321 			"Cannot deduce vport index for port %d on bonding device %s",
1322 			spawn->phys_port, spawn->phys_dev_name);
1323 		err = ENOTSUP;
1324 		goto error;
1325 	} else {
1326 		/*
1327 		 * Suppose vport index in compatible way. Kernel/rdma_core
1328 		 * support single E-Switch per PF configurations only and
1329 		 * vport_id field contains the vport index for associated VF,
1330 		 * which is deduced from representor port name.
1331 		 * For example, let's have the IB device port 10, it has
1332 		 * attached network device eth0, which has port name attribute
1333 		 * pf0vf2, we can deduce the VF number as 2, and set vport index
1334 		 * as 3 (2+1). This assigning schema should be changed if the
1335 		 * multiple E-Switch instances per PF configurations or/and PCI
1336 		 * subfunctions are added.
1337 		 */
1338 		priv->vport_id = switch_info->representor ?
1339 				 switch_info->port_name + 1 : -1;
1340 	}
1341 	priv->representor_id = mlx5_representor_id_encode(switch_info,
1342 							  eth_da->type);
1343 	/*
1344 	 * Look for sibling devices in order to reuse their switch domain
1345 	 * if any, otherwise allocate one.
1346 	 */
1347 	MLX5_ETH_FOREACH_DEV(port_id, dpdk_dev) {
1348 		const struct mlx5_priv *opriv =
1349 			rte_eth_devices[port_id].data->dev_private;
1350 
1351 		if (!opriv ||
1352 		    opriv->sh != priv->sh ||
1353 			opriv->domain_id ==
1354 			RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID)
1355 			continue;
1356 		priv->domain_id = opriv->domain_id;
1357 		DRV_LOG(DEBUG, "dev_port-%u inherit domain_id=%u\n",
1358 			priv->dev_port, priv->domain_id);
1359 		break;
1360 	}
1361 	if (priv->domain_id == RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
1362 		err = rte_eth_switch_domain_alloc(&priv->domain_id);
1363 		if (err) {
1364 			err = rte_errno;
1365 			DRV_LOG(ERR, "unable to allocate switch domain: %s",
1366 				strerror(rte_errno));
1367 			goto error;
1368 		}
1369 		own_domain_id = 1;
1370 		DRV_LOG(DEBUG, "dev_port-%u new domain_id=%u\n",
1371 			priv->dev_port, priv->domain_id);
1372 	}
1373 	if (sh->cdev->config.devx) {
1374 		struct mlx5_hca_attr *hca_attr = &sh->cdev->config.hca_attr;
1375 
1376 		sh->steering_format_version = hca_attr->steering_format_version;
1377 #if defined(HAVE_MLX5_DR_CREATE_ACTION_ASO_EXT)
1378 		if (hca_attr->qos.sup && hca_attr->qos.flow_meter_old &&
1379 		    sh->config.dv_flow_en) {
1380 			if (sh->registers.aso_reg != REG_NON) {
1381 				priv->mtr_en = 1;
1382 				priv->mtr_reg_share = hca_attr->qos.flow_meter;
1383 			}
1384 		}
1385 		if (hca_attr->qos.sup && hca_attr->qos.flow_meter_aso_sup) {
1386 			uint32_t log_obj_size =
1387 				rte_log2_u32(MLX5_ASO_MTRS_PER_POOL >> 1);
1388 			if (log_obj_size >=
1389 			    hca_attr->qos.log_meter_aso_granularity &&
1390 			    log_obj_size <=
1391 			    hca_attr->qos.log_meter_aso_max_alloc)
1392 				sh->meter_aso_en = 1;
1393 		}
1394 		if (priv->mtr_en) {
1395 			err = mlx5_aso_flow_mtrs_mng_init(priv->sh);
1396 			if (err) {
1397 				err = -err;
1398 				goto error;
1399 			}
1400 		}
1401 		if (hca_attr->flow.tunnel_header_0_1)
1402 			sh->tunnel_header_0_1 = 1;
1403 		if (hca_attr->flow.tunnel_header_2_3)
1404 			sh->tunnel_header_2_3 = 1;
1405 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO_EXT */
1406 #ifdef HAVE_MLX5_DR_CREATE_ACTION_ASO
1407 		if (hca_attr->flow_hit_aso && sh->registers.aso_reg == REG_C_3) {
1408 			sh->flow_hit_aso_en = 1;
1409 			err = mlx5_flow_aso_age_mng_init(sh);
1410 			if (err) {
1411 				err = -err;
1412 				goto error;
1413 			}
1414 			DRV_LOG(DEBUG, "Flow Hit ASO is supported.");
1415 		}
1416 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO */
1417 #if defined (HAVE_MLX5_DR_CREATE_ACTION_ASO) && \
1418     defined (HAVE_MLX5_DR_ACTION_ASO_CT)
1419 		/* HWS create CT ASO SQ based on HWS configure queue number. */
1420 		if (sh->config.dv_flow_en != 2 &&
1421 		    hca_attr->ct_offload && sh->registers.aso_reg == REG_C_3) {
1422 			err = mlx5_flow_aso_ct_mng_init(sh);
1423 			if (err) {
1424 				err = -err;
1425 				goto error;
1426 			}
1427 			DRV_LOG(DEBUG, "CT ASO is supported.");
1428 			sh->ct_aso_en = 1;
1429 		}
1430 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO && HAVE_MLX5_DR_ACTION_ASO_CT */
1431 #if defined(HAVE_MLX5DV_DR) && defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_SAMPLE)
1432 		if (hca_attr->log_max_ft_sampler_num > 0  &&
1433 		    sh->config.dv_flow_en) {
1434 			priv->sampler_en = 1;
1435 			DRV_LOG(DEBUG, "Sampler enabled!");
1436 		} else {
1437 			priv->sampler_en = 0;
1438 			if (!hca_attr->log_max_ft_sampler_num)
1439 				DRV_LOG(WARNING,
1440 					"No available register for sampler.");
1441 			else
1442 				DRV_LOG(DEBUG, "DV flow is not supported!");
1443 		}
1444 #endif
1445 		if (hca_attr->lag_rx_port_affinity) {
1446 			sh->lag_rx_port_affinity_en = 1;
1447 			DRV_LOG(DEBUG, "LAG Rx Port Affinity enabled");
1448 		}
1449 		priv->num_lag_ports = hca_attr->num_lag_ports;
1450 		DRV_LOG(DEBUG, "The number of lag ports is %d", priv->num_lag_ports);
1451 	}
1452 	/* Process parameters and store port configuration on priv structure. */
1453 	err = mlx5_port_args_config(priv, mkvlist, &priv->config);
1454 	if (err) {
1455 		err = rte_errno;
1456 		DRV_LOG(ERR, "Failed to process port configure: %s",
1457 			strerror(rte_errno));
1458 		goto error;
1459 	}
1460 	eth_dev = rte_eth_dev_allocate(name);
1461 	if (eth_dev == NULL) {
1462 		DRV_LOG(ERR, "can not allocate rte ethdev");
1463 		err = ENOMEM;
1464 		goto error;
1465 	}
1466 	if (priv->representor) {
1467 		eth_dev->data->dev_flags |= RTE_ETH_DEV_REPRESENTOR;
1468 		eth_dev->data->representor_id = priv->representor_id;
1469 		MLX5_ETH_FOREACH_DEV(port_id, dpdk_dev) {
1470 			struct mlx5_priv *opriv =
1471 				rte_eth_devices[port_id].data->dev_private;
1472 			if (opriv &&
1473 			    opriv->master &&
1474 			    opriv->domain_id == priv->domain_id &&
1475 			    opriv->sh == priv->sh) {
1476 				eth_dev->data->backer_port_id = port_id;
1477 				break;
1478 			}
1479 		}
1480 		if (port_id >= RTE_MAX_ETHPORTS)
1481 			eth_dev->data->backer_port_id = eth_dev->data->port_id;
1482 	}
1483 	priv->mp_id.port_id = eth_dev->data->port_id;
1484 	strlcpy(priv->mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
1485 	/*
1486 	 * Store associated network device interface index. This index
1487 	 * is permanent throughout the lifetime of device. So, we may store
1488 	 * the ifindex here and use the cached value further.
1489 	 */
1490 	MLX5_ASSERT(spawn->ifindex);
1491 	priv->if_index = spawn->ifindex;
1492 	priv->lag_affinity_idx = sh->refcnt - 1;
1493 	eth_dev->data->dev_private = priv;
1494 	priv->dev_data = eth_dev->data;
1495 	eth_dev->data->mac_addrs = priv->mac;
1496 	eth_dev->device = dpdk_dev;
1497 	eth_dev->data->dev_flags |= RTE_ETH_DEV_AUTOFILL_QUEUE_XSTATS;
1498 	/* Configure the first MAC address by default. */
1499 	if (mlx5_get_mac(eth_dev, &mac.addr_bytes)) {
1500 		DRV_LOG(ERR,
1501 			"port %u cannot get MAC address, is mlx5_en"
1502 			" loaded? (errno: %s)",
1503 			eth_dev->data->port_id, strerror(rte_errno));
1504 		err = ENODEV;
1505 		goto error;
1506 	}
1507 	DRV_LOG(INFO,
1508 		"port %u MAC address is " RTE_ETHER_ADDR_PRT_FMT,
1509 		eth_dev->data->port_id, RTE_ETHER_ADDR_BYTES(&mac));
1510 #ifdef RTE_LIBRTE_MLX5_DEBUG
1511 	{
1512 		char ifname[MLX5_NAMESIZE];
1513 
1514 		if (mlx5_get_ifname(eth_dev, &ifname) == 0)
1515 			DRV_LOG(DEBUG, "port %u ifname is \"%s\"",
1516 				eth_dev->data->port_id, ifname);
1517 		else
1518 			DRV_LOG(DEBUG, "port %u ifname is unknown",
1519 				eth_dev->data->port_id);
1520 	}
1521 #endif
1522 	/* Get actual MTU if possible. */
1523 	err = mlx5_get_mtu(eth_dev, &priv->mtu);
1524 	if (err) {
1525 		err = rte_errno;
1526 		goto error;
1527 	}
1528 	DRV_LOG(DEBUG, "port %u MTU is %u", eth_dev->data->port_id,
1529 		priv->mtu);
1530 	/* Initialize burst functions to prevent crashes before link-up. */
1531 	eth_dev->rx_pkt_burst = rte_eth_pkt_burst_dummy;
1532 	eth_dev->tx_pkt_burst = rte_eth_pkt_burst_dummy;
1533 	eth_dev->dev_ops = &mlx5_dev_ops;
1534 	eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1535 	eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1536 	eth_dev->rx_queue_count = mlx5_rx_queue_count;
1537 	/* Register MAC address. */
1538 	claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
1539 	if (sh->dev_cap.vf && sh->config.vf_nl_en)
1540 		mlx5_nl_mac_addr_sync(priv->nl_socket_route,
1541 				      mlx5_ifindex(eth_dev),
1542 				      eth_dev->data->mac_addrs,
1543 				      MLX5_MAX_MAC_ADDRESSES);
1544 	priv->ctrl_flows = 0;
1545 	rte_spinlock_init(&priv->flow_list_lock);
1546 	TAILQ_INIT(&priv->flow_meters);
1547 	priv->mtr_profile_tbl = mlx5_l3t_create(MLX5_L3T_TYPE_PTR);
1548 	if (!priv->mtr_profile_tbl)
1549 		goto error;
1550 	/* Bring Ethernet device up. */
1551 	DRV_LOG(DEBUG, "port %u forcing Ethernet interface up",
1552 		eth_dev->data->port_id);
1553 	/* Read link status in case it is up and there will be no event. */
1554 	mlx5_link_update(eth_dev, 0);
1555 	/* Watch LSC interrupts between port probe and port start. */
1556 	priv->sh->port[priv->dev_port - 1].nl_ih_port_id =
1557 							eth_dev->data->port_id;
1558 	mlx5_set_link_up(eth_dev);
1559 	for (i = 0; i < MLX5_FLOW_TYPE_MAXI; i++) {
1560 		icfg[i].release_mem_en = !!sh->config.reclaim_mode;
1561 		if (sh->config.reclaim_mode)
1562 			icfg[i].per_core_cache = 0;
1563 		priv->flows[i] = mlx5_ipool_create(&icfg[i]);
1564 		if (!priv->flows[i])
1565 			goto error;
1566 	}
1567 	/* Create context for virtual machine VLAN workaround. */
1568 	priv->vmwa_context = mlx5_vlan_vmwa_init(eth_dev, spawn->ifindex);
1569 	if (sh->config.dv_flow_en) {
1570 		err = mlx5_alloc_shared_dr(priv);
1571 		if (err)
1572 			goto error;
1573 		if (mlx5_flex_item_port_init(eth_dev) < 0)
1574 			goto error;
1575 	}
1576 	if (mlx5_devx_obj_ops_en(sh)) {
1577 		priv->obj_ops = devx_obj_ops;
1578 		mlx5_queue_counter_id_prepare(eth_dev);
1579 		priv->obj_ops.lb_dummy_queue_create =
1580 					mlx5_rxq_ibv_obj_dummy_lb_create;
1581 		priv->obj_ops.lb_dummy_queue_release =
1582 					mlx5_rxq_ibv_obj_dummy_lb_release;
1583 	} else if (spawn->max_port > UINT8_MAX) {
1584 		/* Verbs can't support ports larger than 255 by design. */
1585 		DRV_LOG(ERR, "must enable DV and ESW when RDMA link ports > 255");
1586 		err = ENOTSUP;
1587 		goto error;
1588 	} else {
1589 		priv->obj_ops = ibv_obj_ops;
1590 	}
1591 	if (sh->config.tx_pp &&
1592 	    priv->obj_ops.txq_obj_new != mlx5_txq_devx_obj_new) {
1593 		/*
1594 		 * HAVE_MLX5DV_DEVX_UAR_OFFSET is required to support
1595 		 * packet pacing and already checked above.
1596 		 * Hence, we should only make sure the SQs will be created
1597 		 * with DevX, not with Verbs.
1598 		 * Verbs allocates the SQ UAR on its own and it can't be shared
1599 		 * with Clock Queue UAR as required for Tx scheduling.
1600 		 */
1601 		DRV_LOG(ERR, "Verbs SQs, UAR can't be shared as required for packet pacing");
1602 		err = ENODEV;
1603 		goto error;
1604 	}
1605 	priv->drop_queue.hrxq = mlx5_drop_action_create(eth_dev);
1606 	if (!priv->drop_queue.hrxq)
1607 		goto error;
1608 	priv->hrxqs = mlx5_list_create("hrxq", eth_dev, true,
1609 				       mlx5_hrxq_create_cb,
1610 				       mlx5_hrxq_match_cb,
1611 				       mlx5_hrxq_remove_cb,
1612 				       mlx5_hrxq_clone_cb,
1613 				       mlx5_hrxq_clone_free_cb);
1614 	if (!priv->hrxqs)
1615 		goto error;
1616 	mlx5_set_metadata_mask(eth_dev);
1617 	if (sh->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1618 	    !priv->sh->dv_regc0_mask) {
1619 		DRV_LOG(ERR, "metadata mode %u is not supported "
1620 			     "(no metadata reg_c[0] is available)",
1621 			     sh->config.dv_xmeta_en);
1622 			err = ENOTSUP;
1623 			goto error;
1624 	}
1625 	rte_rwlock_init(&priv->ind_tbls_lock);
1626 	if (sh->phdev->config.ipv6_tc_fallback == MLX5_IPV6_TC_UNKNOWN) {
1627 		sh->phdev->config.ipv6_tc_fallback = MLX5_IPV6_TC_OK;
1628 		if (!sh->cdev->config.hca_attr.modify_outer_ipv6_traffic_class ||
1629 		    (sh->config.dv_flow_en == 1 && mlx5_flow_discover_ipv6_tc_support(eth_dev)))
1630 			sh->phdev->config.ipv6_tc_fallback = MLX5_IPV6_TC_FALLBACK;
1631 	}
1632 	if (priv->sh->config.dv_flow_en == 2) {
1633 #ifdef HAVE_MLX5_HWS_SUPPORT
1634 		if (priv->sh->config.dv_esw_en) {
1635 			uint32_t usable_bits;
1636 			uint32_t required_bits;
1637 
1638 			if (priv->sh->dv_regc0_mask == UINT32_MAX) {
1639 				DRV_LOG(ERR, "E-Switch port metadata is required when using HWS "
1640 					     "but it is disabled (configure it through devlink)");
1641 				err = ENOTSUP;
1642 				goto error;
1643 			}
1644 			if (priv->sh->dv_regc0_mask == 0) {
1645 				DRV_LOG(ERR, "E-Switch with HWS is not supported "
1646 					     "(no available bits in reg_c[0])");
1647 				err = ENOTSUP;
1648 				goto error;
1649 			}
1650 			usable_bits = rte_popcount32(priv->sh->dv_regc0_mask);
1651 			required_bits = rte_popcount32(priv->vport_meta_mask);
1652 			if (usable_bits < required_bits) {
1653 				DRV_LOG(ERR, "Not enough bits available in reg_c[0] to provide "
1654 					     "representor matching.");
1655 				err = ENOTSUP;
1656 				goto error;
1657 			}
1658 		}
1659 		if (priv->vport_meta_mask)
1660 			flow_hw_set_port_info(eth_dev);
1661 		if (priv->sh->config.dv_esw_en &&
1662 		    priv->sh->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1663 		    priv->sh->config.dv_xmeta_en != MLX5_XMETA_MODE_META32_HWS) {
1664 			DRV_LOG(ERR,
1665 				"metadata mode %u is not supported in HWS eswitch mode",
1666 				priv->sh->config.dv_xmeta_en);
1667 				err = ENOTSUP;
1668 				goto error;
1669 		}
1670 		if (priv->sh->config.dv_esw_en &&
1671 		    flow_hw_create_vport_action(eth_dev)) {
1672 			DRV_LOG(ERR, "port %u failed to create vport action",
1673 				eth_dev->data->port_id);
1674 			err = EINVAL;
1675 			goto error;
1676 		}
1677 		/*
1678 		 * If representor matching is disabled, PMD cannot create default flow rules
1679 		 * to receive traffic for all ports, since implicit source port match is not added.
1680 		 * Isolated mode is forced.
1681 		 */
1682 		if (priv->sh->config.dv_esw_en && !priv->sh->config.repr_matching) {
1683 			err = mlx5_flow_isolate(eth_dev, 1, NULL);
1684 			if (err < 0) {
1685 				err = -err;
1686 				goto error;
1687 			}
1688 			DRV_LOG(WARNING, "port %u ingress traffic is restricted to defined "
1689 					 "flow rules (isolated mode) since representor "
1690 					 "matching is disabled",
1691 				eth_dev->data->port_id);
1692 		}
1693 		eth_dev->data->dev_flags |= RTE_ETH_DEV_FLOW_OPS_THREAD_SAFE;
1694 		return eth_dev;
1695 #else
1696 		DRV_LOG(ERR, "DV support is missing for HWS.");
1697 		goto error;
1698 #endif
1699 	}
1700 	if (!priv->sh->flow_priority_check_flag) {
1701 		/* Supported Verbs flow priority number detection. */
1702 		err = mlx5_flow_discover_priorities(eth_dev);
1703 		priv->sh->flow_max_priority = err;
1704 		priv->sh->flow_priority_check_flag = 1;
1705 	} else {
1706 		err = priv->sh->flow_max_priority;
1707 	}
1708 	if (err < 0) {
1709 		err = -err;
1710 		goto error;
1711 	}
1712 	/* Query availability of metadata reg_c's. */
1713 	if (!priv->sh->metadata_regc_check_flag) {
1714 		err = mlx5_flow_discover_mreg_c(eth_dev);
1715 		if (err < 0) {
1716 			err = -err;
1717 			goto error;
1718 		}
1719 	}
1720 	if (!mlx5_flow_ext_mreg_supported(eth_dev)) {
1721 		DRV_LOG(DEBUG,
1722 			"port %u extensive metadata register is not supported",
1723 			eth_dev->data->port_id);
1724 		if (sh->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1725 			DRV_LOG(ERR, "metadata mode %u is not supported "
1726 				     "(no metadata registers available)",
1727 				     sh->config.dv_xmeta_en);
1728 			err = ENOTSUP;
1729 			goto error;
1730 		}
1731 	}
1732 	if (sh->config.dv_flow_en &&
1733 	    sh->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1734 	    mlx5_flow_ext_mreg_supported(eth_dev) &&
1735 	    priv->sh->dv_regc0_mask) {
1736 		priv->mreg_cp_tbl = mlx5_hlist_create(MLX5_FLOW_MREG_HNAME,
1737 						      MLX5_FLOW_MREG_HTABLE_SZ,
1738 						      false, true, eth_dev,
1739 						      flow_dv_mreg_create_cb,
1740 						      flow_dv_mreg_match_cb,
1741 						      flow_dv_mreg_remove_cb,
1742 						      flow_dv_mreg_clone_cb,
1743 						    flow_dv_mreg_clone_free_cb);
1744 		if (!priv->mreg_cp_tbl) {
1745 			err = ENOMEM;
1746 			goto error;
1747 		}
1748 	}
1749 	rte_spinlock_init(&priv->shared_act_sl);
1750 	mlx5_flow_counter_mode_config(eth_dev);
1751 	mlx5_flow_drop_action_config(eth_dev);
1752 	if (sh->config.dv_flow_en)
1753 		eth_dev->data->dev_flags |= RTE_ETH_DEV_FLOW_OPS_THREAD_SAFE;
1754 	return eth_dev;
1755 error:
1756 	if (priv) {
1757 		priv->sh->port[priv->dev_port - 1].nl_ih_port_id =
1758 							       RTE_MAX_ETHPORTS;
1759 		rte_io_wmb();
1760 #ifdef HAVE_MLX5_HWS_SUPPORT
1761 		if (eth_dev &&
1762 		    priv->sh &&
1763 		    priv->sh->config.dv_flow_en == 2 &&
1764 		    priv->sh->config.dv_esw_en)
1765 			flow_hw_destroy_vport_action(eth_dev);
1766 #endif
1767 		if (priv->mreg_cp_tbl)
1768 			mlx5_hlist_destroy(priv->mreg_cp_tbl);
1769 		if (priv->sh)
1770 			mlx5_os_free_shared_dr(priv);
1771 		if (priv->nl_socket_route >= 0)
1772 			close(priv->nl_socket_route);
1773 		if (priv->vmwa_context)
1774 			mlx5_vlan_vmwa_exit(priv->vmwa_context);
1775 		if (eth_dev && priv->drop_queue.hrxq)
1776 			mlx5_drop_action_destroy(eth_dev);
1777 		if (priv->mtr_profile_tbl)
1778 			mlx5_l3t_destroy(priv->mtr_profile_tbl);
1779 		if (own_domain_id)
1780 			claim_zero(rte_eth_switch_domain_free(priv->domain_id));
1781 		if (priv->hrxqs)
1782 			mlx5_list_destroy(priv->hrxqs);
1783 		if (eth_dev && priv->flex_item_map)
1784 			mlx5_flex_item_port_cleanup(eth_dev);
1785 		mlx5_free(priv->ext_rxqs);
1786 		mlx5_free(priv->ext_txqs);
1787 		mlx5_free(priv);
1788 		if (eth_dev != NULL)
1789 			eth_dev->data->dev_private = NULL;
1790 	}
1791 	if (eth_dev != NULL) {
1792 		/* mac_addrs must not be freed alone because part of
1793 		 * dev_private
1794 		 **/
1795 		eth_dev->data->mac_addrs = NULL;
1796 		rte_eth_dev_release_port(eth_dev);
1797 	}
1798 	if (sh)
1799 		mlx5_free_shared_dev_ctx(sh);
1800 	if (nl_rdma >= 0)
1801 		close(nl_rdma);
1802 	MLX5_ASSERT(err > 0);
1803 	rte_errno = err;
1804 	return NULL;
1805 }
1806 
1807 /**
1808  * Comparison callback to sort device data.
1809  *
1810  * This is meant to be used with qsort().
1811  *
1812  * @param a[in]
1813  *   Pointer to pointer to first data object.
1814  * @param b[in]
1815  *   Pointer to pointer to second data object.
1816  *
1817  * @return
1818  *   0 if both objects are equal, less than 0 if the first argument is less
1819  *   than the second, greater than 0 otherwise.
1820  */
1821 static int
1822 mlx5_dev_spawn_data_cmp(const void *a, const void *b)
1823 {
1824 	const struct mlx5_switch_info *si_a =
1825 		&((const struct mlx5_dev_spawn_data *)a)->info;
1826 	const struct mlx5_switch_info *si_b =
1827 		&((const struct mlx5_dev_spawn_data *)b)->info;
1828 	int uplink_a = si_a->name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK;
1829 	int uplink_b = si_b->name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK;
1830 	int ret;
1831 
1832 	/* Uplink ports first. */
1833 	ret = uplink_b - uplink_a;
1834 	if (ret)
1835 		return ret;
1836 	/* Then master devices. */
1837 	ret = si_b->master - si_a->master;
1838 	if (ret)
1839 		return ret;
1840 	/* Then representor devices. */
1841 	ret = si_b->representor - si_a->representor;
1842 	if (ret)
1843 		return ret;
1844 	/* Unidentified devices come last in no specific order. */
1845 	if (!si_a->representor)
1846 		return 0;
1847 	/* Order representors by name. */
1848 	return si_a->port_name - si_b->port_name;
1849 }
1850 
1851 /**
1852  * Match PCI information for possible slaves of bonding device.
1853  *
1854  * @param[in] ibdev_name
1855  *   Name of Infiniband device.
1856  * @param[in] pci_dev
1857  *   Pointer to primary PCI address structure to match.
1858  * @param[in] nl_rdma
1859  *   Netlink RDMA group socket handle.
1860  * @param[in] owner
1861  *   Representor owner PF index.
1862  * @param[out] bond_info
1863  *   Pointer to bonding information.
1864  *
1865  * @return
1866  *   negative value if no bonding device found, otherwise
1867  *   positive index of slave PF in bonding.
1868  */
1869 static int
1870 mlx5_device_bond_pci_match(const char *ibdev_name,
1871 			   const struct rte_pci_addr *pci_dev,
1872 			   int nl_rdma, uint16_t owner,
1873 			   struct mlx5_bond_info *bond_info)
1874 {
1875 	char ifname[IF_NAMESIZE + 1];
1876 	unsigned int ifindex;
1877 	unsigned int np, i;
1878 	FILE *bond_file = NULL, *file;
1879 	int pf = -1;
1880 	int ret;
1881 	uint8_t cur_guid[32] = {0};
1882 	uint8_t guid[32] = {0};
1883 
1884 	/*
1885 	 * Try to get master device name. If something goes wrong suppose
1886 	 * the lack of kernel support and no bonding devices.
1887 	 */
1888 	memset(bond_info, 0, sizeof(*bond_info));
1889 	if (nl_rdma < 0)
1890 		return -1;
1891 	if (!strstr(ibdev_name, "bond"))
1892 		return -1;
1893 	np = mlx5_nl_portnum(nl_rdma, ibdev_name);
1894 	if (!np)
1895 		return -1;
1896 	if (mlx5_get_device_guid(pci_dev, cur_guid, sizeof(cur_guid)) < 0)
1897 		return -1;
1898 	/*
1899 	 * The master device might not be on the predefined port(not on port
1900 	 * index 1, it is not guaranteed), we have to scan all Infiniband
1901 	 * device ports and find master.
1902 	 */
1903 	for (i = 1; i <= np; ++i) {
1904 		/* Check whether Infiniband port is populated. */
1905 		ifindex = mlx5_nl_ifindex(nl_rdma, ibdev_name, i);
1906 		if (!ifindex)
1907 			continue;
1908 		if (!if_indextoname(ifindex, ifname))
1909 			continue;
1910 		/* Try to read bonding slave names from sysfs. */
1911 		MKSTR(slaves,
1912 		      "/sys/class/net/%s/master/bonding/slaves", ifname);
1913 		bond_file = fopen(slaves, "r");
1914 		if (bond_file)
1915 			break;
1916 	}
1917 	if (!bond_file)
1918 		return -1;
1919 	/* Use safe format to check maximal buffer length. */
1920 	MLX5_ASSERT(atol(RTE_STR(IF_NAMESIZE)) == IF_NAMESIZE);
1921 	while (fscanf(bond_file, "%" RTE_STR(IF_NAMESIZE) "s", ifname) == 1) {
1922 		char tmp_str[IF_NAMESIZE + 32];
1923 		struct rte_pci_addr pci_addr;
1924 		struct mlx5_switch_info	info;
1925 		int ret;
1926 
1927 		/* Process slave interface names in the loop. */
1928 		snprintf(tmp_str, sizeof(tmp_str),
1929 			 "/sys/class/net/%s", ifname);
1930 		if (mlx5_get_pci_addr(tmp_str, &pci_addr)) {
1931 			DRV_LOG(WARNING,
1932 				"Cannot get PCI address for netdev \"%s\".",
1933 				ifname);
1934 			continue;
1935 		}
1936 		/* Slave interface PCI address match found. */
1937 		snprintf(tmp_str, sizeof(tmp_str),
1938 			 "/sys/class/net/%s/phys_port_name", ifname);
1939 		file = fopen(tmp_str, "rb");
1940 		if (!file)
1941 			break;
1942 		info.name_type = MLX5_PHYS_PORT_NAME_TYPE_NOTSET;
1943 		if (fscanf(file, "%32s", tmp_str) == 1)
1944 			mlx5_translate_port_name(tmp_str, &info);
1945 		fclose(file);
1946 		/* Only process PF ports. */
1947 		if (info.name_type != MLX5_PHYS_PORT_NAME_TYPE_LEGACY &&
1948 		    info.name_type != MLX5_PHYS_PORT_NAME_TYPE_UPLINK)
1949 			continue;
1950 		/* Check max bonding member. */
1951 		if (info.port_name >= MLX5_BOND_MAX_PORTS) {
1952 			DRV_LOG(WARNING, "bonding index out of range, "
1953 				"please increase MLX5_BOND_MAX_PORTS: %s",
1954 				tmp_str);
1955 			break;
1956 		}
1957 		/* Get ifindex. */
1958 		snprintf(tmp_str, sizeof(tmp_str),
1959 			 "/sys/class/net/%s/ifindex", ifname);
1960 		file = fopen(tmp_str, "rb");
1961 		if (!file)
1962 			break;
1963 		ret = fscanf(file, "%u", &ifindex);
1964 		fclose(file);
1965 		if (ret != 1)
1966 			break;
1967 		/* Save bonding info. */
1968 		strncpy(bond_info->ports[info.port_name].ifname, ifname,
1969 			sizeof(bond_info->ports[0].ifname));
1970 		bond_info->ports[info.port_name].pci_addr = pci_addr;
1971 		bond_info->ports[info.port_name].ifindex = ifindex;
1972 		bond_info->n_port++;
1973 		/*
1974 		 * Under socket direct mode, bonding will use
1975 		 * system_image_guid as identification.
1976 		 * After OFED 5.4, guid is readable (ret >= 0) under sysfs.
1977 		 * All bonding members should have the same guid even if driver
1978 		 * is using PCIe BDF.
1979 		 */
1980 		ret = mlx5_get_device_guid(&pci_addr, guid, sizeof(guid));
1981 		if (ret < 0)
1982 			break;
1983 		else if (ret > 0) {
1984 			if (!memcmp(guid, cur_guid, sizeof(guid)) &&
1985 			    owner == info.port_name &&
1986 			    (owner != 0 || (owner == 0 &&
1987 			    !rte_pci_addr_cmp(pci_dev, &pci_addr))))
1988 				pf = info.port_name;
1989 		} else if (pci_dev->domain == pci_addr.domain &&
1990 		    pci_dev->bus == pci_addr.bus &&
1991 		    pci_dev->devid == pci_addr.devid &&
1992 		    ((pci_dev->function == 0 &&
1993 		      pci_dev->function + owner == pci_addr.function) ||
1994 		     (pci_dev->function == owner &&
1995 		      pci_addr.function == owner)))
1996 			pf = info.port_name;
1997 	}
1998 	if (pf >= 0) {
1999 		/* Get bond interface info */
2000 		ret = mlx5_sysfs_bond_info(ifindex, &bond_info->ifindex,
2001 					   bond_info->ifname);
2002 		if (ret)
2003 			DRV_LOG(ERR, "unable to get bond info: %s",
2004 				strerror(rte_errno));
2005 		else
2006 			DRV_LOG(INFO, "PF device %u, bond device %u(%s)",
2007 				ifindex, bond_info->ifindex, bond_info->ifname);
2008 	}
2009 	if (owner == 0 && pf != 0) {
2010 		DRV_LOG(INFO, "PCIe instance " PCI_PRI_FMT " isn't bonding owner",
2011 				pci_dev->domain, pci_dev->bus, pci_dev->devid,
2012 				pci_dev->function);
2013 	}
2014 	return pf;
2015 }
2016 
2017 static int
2018 mlx5_nl_esw_multiport_get(struct rte_pci_addr *pci_addr, int *enabled)
2019 {
2020 	char pci_addr_str[PCI_PRI_STR_SIZE] = { 0 };
2021 	int nlsk_fd;
2022 	int devlink_id;
2023 	int ret;
2024 
2025 	/* Provide correct value to have defined enabled state in case of an error. */
2026 	*enabled = 0;
2027 	rte_pci_device_name(pci_addr, pci_addr_str, sizeof(pci_addr_str));
2028 	nlsk_fd = mlx5_nl_init(NETLINK_GENERIC, 0);
2029 	if (nlsk_fd < 0)
2030 		return nlsk_fd;
2031 	devlink_id = mlx5_nl_devlink_family_id_get(nlsk_fd);
2032 	if (devlink_id < 0) {
2033 		ret = devlink_id;
2034 		DRV_LOG(DEBUG, "Unable to get devlink family id for Multiport E-Switch checks "
2035 			       "by netlink, for PCI device %s", pci_addr_str);
2036 		goto close_nlsk_fd;
2037 	}
2038 	ret = mlx5_nl_devlink_esw_multiport_get(nlsk_fd, devlink_id, pci_addr_str, enabled);
2039 	if (ret < 0)
2040 		DRV_LOG(DEBUG, "Unable to get Multiport E-Switch state by Netlink.");
2041 close_nlsk_fd:
2042 	close(nlsk_fd);
2043 	return ret;
2044 }
2045 
2046 #define SYSFS_MPESW_PARAM_MAX_LEN 16
2047 
2048 static int
2049 mlx5_sysfs_esw_multiport_get(struct ibv_device *ibv, struct rte_pci_addr *pci_addr, int *enabled)
2050 {
2051 	int nl_rdma;
2052 	unsigned int n_ports;
2053 	unsigned int i;
2054 	int ret;
2055 
2056 	/* Provide correct value to have defined enabled state in case of an error. */
2057 	*enabled = 0;
2058 	nl_rdma = mlx5_nl_init(NETLINK_RDMA, 0);
2059 	if (nl_rdma < 0)
2060 		return nl_rdma;
2061 	n_ports = mlx5_nl_portnum(nl_rdma, ibv->name);
2062 	if (!n_ports) {
2063 		ret = -rte_errno;
2064 		goto close_nl_rdma;
2065 	}
2066 	for (i = 1; i <= n_ports; ++i) {
2067 		unsigned int ifindex;
2068 		char ifname[IF_NAMESIZE + 1];
2069 		struct rte_pci_addr if_pci_addr;
2070 		char mpesw[SYSFS_MPESW_PARAM_MAX_LEN + 1];
2071 		FILE *sysfs;
2072 		int n;
2073 
2074 		ifindex = mlx5_nl_ifindex(nl_rdma, ibv->name, i);
2075 		if (!ifindex)
2076 			continue;
2077 		if (!if_indextoname(ifindex, ifname))
2078 			continue;
2079 		MKSTR(sysfs_if_path, "/sys/class/net/%s", ifname);
2080 		if (mlx5_get_pci_addr(sysfs_if_path, &if_pci_addr))
2081 			continue;
2082 		if (pci_addr->domain != if_pci_addr.domain ||
2083 		    pci_addr->bus != if_pci_addr.bus ||
2084 		    pci_addr->devid != if_pci_addr.devid ||
2085 		    pci_addr->function != if_pci_addr.function)
2086 			continue;
2087 		MKSTR(sysfs_mpesw_path,
2088 		      "/sys/class/net/%s/compat/devlink/lag_port_select_mode", ifname);
2089 		sysfs = fopen(sysfs_mpesw_path, "r");
2090 		if (!sysfs)
2091 			continue;
2092 		n = fscanf(sysfs, "%" RTE_STR(SYSFS_MPESW_PARAM_MAX_LEN) "s", mpesw);
2093 		fclose(sysfs);
2094 		if (n != 1)
2095 			continue;
2096 		ret = 0;
2097 		if (strcmp(mpesw, "multiport_esw") == 0) {
2098 			*enabled = 1;
2099 			break;
2100 		}
2101 		*enabled = 0;
2102 		break;
2103 	}
2104 	if (i > n_ports) {
2105 		DRV_LOG(DEBUG, "Unable to get Multiport E-Switch state by sysfs.");
2106 		rte_errno = ENOENT;
2107 		ret = -rte_errno;
2108 	}
2109 
2110 close_nl_rdma:
2111 	close(nl_rdma);
2112 	return ret;
2113 }
2114 
2115 static int
2116 mlx5_is_mpesw_enabled(struct ibv_device *ibv, struct rte_pci_addr *ibv_pci_addr, int *enabled)
2117 {
2118 	/*
2119 	 * Try getting Multiport E-Switch state through netlink interface
2120 	 * If unable, try sysfs interface. If that is unable as well,
2121 	 * assume that Multiport E-Switch is disabled and return an error.
2122 	 */
2123 	if (mlx5_nl_esw_multiport_get(ibv_pci_addr, enabled) >= 0 ||
2124 	    mlx5_sysfs_esw_multiport_get(ibv, ibv_pci_addr, enabled) >= 0)
2125 		return 0;
2126 	DRV_LOG(DEBUG, "Unable to check MPESW state for IB device %s "
2127 		       "(PCI: " PCI_PRI_FMT ")",
2128 		       ibv->name,
2129 		       ibv_pci_addr->domain, ibv_pci_addr->bus,
2130 		       ibv_pci_addr->devid, ibv_pci_addr->function);
2131 	*enabled = 0;
2132 	return -rte_errno;
2133 }
2134 
2135 static int
2136 mlx5_device_mpesw_pci_match(struct ibv_device *ibv,
2137 			    const struct rte_pci_addr *owner_pci,
2138 			    int nl_rdma)
2139 {
2140 	struct rte_pci_addr ibdev_pci_addr = { 0 };
2141 	char ifname[IF_NAMESIZE + 1] = { 0 };
2142 	unsigned int ifindex;
2143 	unsigned int np;
2144 	unsigned int i;
2145 	int enabled = 0;
2146 	int ret;
2147 
2148 	/* Check if IB device's PCI address matches the probed PCI address. */
2149 	if (mlx5_get_pci_addr(ibv->ibdev_path, &ibdev_pci_addr)) {
2150 		DRV_LOG(DEBUG, "Skipping MPESW check for IB device %s since "
2151 			       "there is no underlying PCI device", ibv->name);
2152 		rte_errno = ENOENT;
2153 		return -rte_errno;
2154 	}
2155 	if (ibdev_pci_addr.domain != owner_pci->domain ||
2156 	    ibdev_pci_addr.bus != owner_pci->bus ||
2157 	    ibdev_pci_addr.devid != owner_pci->devid ||
2158 	    ibdev_pci_addr.function != owner_pci->function) {
2159 		return -1;
2160 	}
2161 	/* Check if IB device has MPESW enabled. */
2162 	if (mlx5_is_mpesw_enabled(ibv, &ibdev_pci_addr, &enabled))
2163 		return -1;
2164 	if (!enabled)
2165 		return -1;
2166 	/* Iterate through IB ports to find MPESW master uplink port. */
2167 	if (nl_rdma < 0)
2168 		return -1;
2169 	np = mlx5_nl_portnum(nl_rdma, ibv->name);
2170 	if (!np)
2171 		return -1;
2172 	for (i = 1; i <= np; ++i) {
2173 		struct rte_pci_addr pci_addr;
2174 		FILE *file;
2175 		char port_name[IF_NAMESIZE + 1];
2176 		struct mlx5_switch_info	info;
2177 
2178 		/* Check whether IB port has a corresponding netdev. */
2179 		ifindex = mlx5_nl_ifindex(nl_rdma, ibv->name, i);
2180 		if (!ifindex)
2181 			continue;
2182 		if (!if_indextoname(ifindex, ifname))
2183 			continue;
2184 		/* Read port name and determine its type. */
2185 		MKSTR(ifphysportname, "/sys/class/net/%s/phys_port_name", ifname);
2186 		file = fopen(ifphysportname, "rb");
2187 		if (!file)
2188 			continue;
2189 		ret = fscanf(file, "%16s", port_name);
2190 		fclose(file);
2191 		if (ret != 1)
2192 			continue;
2193 		memset(&info, 0, sizeof(info));
2194 		mlx5_translate_port_name(port_name, &info);
2195 		if (info.name_type != MLX5_PHYS_PORT_NAME_TYPE_UPLINK)
2196 			continue;
2197 		/* Fetch PCI address of the device to which the netdev is bound. */
2198 		MKSTR(ifpath, "/sys/class/net/%s", ifname);
2199 		if (mlx5_get_pci_addr(ifpath, &pci_addr))
2200 			continue;
2201 		if (pci_addr.domain == ibdev_pci_addr.domain &&
2202 		    pci_addr.bus == ibdev_pci_addr.bus &&
2203 		    pci_addr.devid == ibdev_pci_addr.devid &&
2204 		    pci_addr.function == ibdev_pci_addr.function) {
2205 			MLX5_ASSERT(info.port_name >= 0);
2206 			return info.port_name;
2207 		}
2208 	}
2209 	/* No matching MPESW uplink port was found. */
2210 	return -1;
2211 }
2212 
2213 /**
2214  * Register a PCI device within bonding.
2215  *
2216  * This function spawns Ethernet devices out of a given PCI device and
2217  * bonding owner PF index.
2218  *
2219  * @param[in] cdev
2220  *   Pointer to common mlx5 device structure.
2221  * @param[in] req_eth_da
2222  *   Requested ethdev device argument.
2223  * @param[in] owner_id
2224  *   Requested owner PF port ID within bonding device, default to 0.
2225  * @param[in, out] mkvlist
2226  *   Pointer to mlx5 kvargs control, can be NULL if there is no devargs.
2227  *
2228  * @return
2229  *   0 on success, a negative errno value otherwise and rte_errno is set.
2230  */
2231 static int
2232 mlx5_os_pci_probe_pf(struct mlx5_common_device *cdev,
2233 		     struct rte_eth_devargs *req_eth_da,
2234 		     uint16_t owner_id, struct mlx5_kvargs_ctrl *mkvlist)
2235 {
2236 	struct ibv_device **ibv_list;
2237 	/*
2238 	 * Number of found IB Devices matching with requested PCI BDF.
2239 	 * nd != 1 means there are multiple IB devices over the same
2240 	 * PCI device and we have representors and master.
2241 	 */
2242 	unsigned int nd = 0;
2243 	/*
2244 	 * Number of found IB device Ports. nd = 1 and np = 1..n means
2245 	 * we have the single multiport IB device, and there may be
2246 	 * representors attached to some of found ports.
2247 	 */
2248 	unsigned int np = 0;
2249 	/*
2250 	 * Number of DPDK ethernet devices to Spawn - either over
2251 	 * multiple IB devices or multiple ports of single IB device.
2252 	 * Actually this is the number of iterations to spawn.
2253 	 */
2254 	unsigned int ns = 0;
2255 	/*
2256 	 * Bonding device
2257 	 *   < 0 - no bonding device (single one)
2258 	 *  >= 0 - bonding device (value is slave PF index)
2259 	 */
2260 	int bd = -1;
2261 	/*
2262 	 * Multiport E-Switch (MPESW) device:
2263 	 *   < 0 - no MPESW device or could not determine if it is MPESW device,
2264 	 *  >= 0 - MPESW device. Value is the port index of the MPESW owner.
2265 	 */
2266 	int mpesw = MLX5_MPESW_PORT_INVALID;
2267 	struct rte_pci_device *pci_dev = RTE_DEV_TO_PCI(cdev->dev);
2268 	struct mlx5_dev_spawn_data *list = NULL;
2269 	struct rte_eth_devargs eth_da = *req_eth_da;
2270 	struct rte_pci_addr owner_pci = pci_dev->addr; /* Owner PF. */
2271 	struct mlx5_bond_info bond_info;
2272 	int ret = -1;
2273 
2274 	errno = 0;
2275 	ibv_list = mlx5_glue->get_device_list(&ret);
2276 	if (!ibv_list) {
2277 		rte_errno = errno ? errno : ENOSYS;
2278 		DRV_LOG(ERR, "Cannot list devices, is ib_uverbs loaded?");
2279 		return -rte_errno;
2280 	}
2281 	/*
2282 	 * First scan the list of all Infiniband devices to find
2283 	 * matching ones, gathering into the list.
2284 	 */
2285 	struct ibv_device *ibv_match[ret + 1];
2286 	int nl_route = mlx5_nl_init(NETLINK_ROUTE, 0);
2287 	int nl_rdma = mlx5_nl_init(NETLINK_RDMA, 0);
2288 	unsigned int i;
2289 
2290 	while (ret-- > 0) {
2291 		struct rte_pci_addr pci_addr;
2292 
2293 		DRV_LOG(DEBUG, "Checking device \"%s\"", ibv_list[ret]->name);
2294 		bd = mlx5_device_bond_pci_match(ibv_list[ret]->name, &owner_pci,
2295 						nl_rdma, owner_id, &bond_info);
2296 		if (bd >= 0) {
2297 			/*
2298 			 * Bonding device detected. Only one match is allowed,
2299 			 * the bonding is supported over multi-port IB device,
2300 			 * there should be no matches on representor PCI
2301 			 * functions or non VF LAG bonding devices with
2302 			 * specified address.
2303 			 */
2304 			if (nd) {
2305 				DRV_LOG(ERR,
2306 					"multiple PCI match on bonding device"
2307 					"\"%s\" found", ibv_list[ret]->name);
2308 				rte_errno = ENOENT;
2309 				ret = -rte_errno;
2310 				goto exit;
2311 			}
2312 			/* Amend owner pci address if owner PF ID specified. */
2313 			if (eth_da.nb_representor_ports)
2314 				owner_pci.function += owner_id;
2315 			DRV_LOG(INFO,
2316 				"PCI information matches for slave %d bonding device \"%s\"",
2317 				bd, ibv_list[ret]->name);
2318 			ibv_match[nd++] = ibv_list[ret];
2319 			break;
2320 		}
2321 		mpesw = mlx5_device_mpesw_pci_match(ibv_list[ret], &owner_pci, nl_rdma);
2322 		if (mpesw >= 0) {
2323 			/*
2324 			 * MPESW device detected. Only one matching IB device is allowed,
2325 			 * so if any matches were found previously, fail gracefully.
2326 			 */
2327 			if (nd) {
2328 				DRV_LOG(ERR,
2329 					"PCI information matches MPESW device \"%s\", "
2330 					"but multiple matching PCI devices were found. "
2331 					"Probing failed.",
2332 					ibv_list[ret]->name);
2333 				rte_errno = ENOENT;
2334 				ret = -rte_errno;
2335 				goto exit;
2336 			}
2337 			DRV_LOG(INFO,
2338 				"PCI information matches MPESW device \"%s\"",
2339 				ibv_list[ret]->name);
2340 			ibv_match[nd++] = ibv_list[ret];
2341 			break;
2342 		}
2343 		/* Bonding or MPESW device was not found. */
2344 		if (mlx5_get_pci_addr(ibv_list[ret]->ibdev_path,
2345 					&pci_addr))
2346 			continue;
2347 		if (rte_pci_addr_cmp(&owner_pci, &pci_addr) != 0)
2348 			continue;
2349 		DRV_LOG(INFO, "PCI information matches for device \"%s\"",
2350 			ibv_list[ret]->name);
2351 		ibv_match[nd++] = ibv_list[ret];
2352 	}
2353 	ibv_match[nd] = NULL;
2354 	if (!nd) {
2355 		/* No device matches, just complain and bail out. */
2356 		DRV_LOG(WARNING,
2357 			"PF %u doesn't have Verbs device matches PCI device " PCI_PRI_FMT ","
2358 			" are kernel drivers loaded?",
2359 			owner_id, owner_pci.domain, owner_pci.bus,
2360 			owner_pci.devid, owner_pci.function);
2361 		rte_errno = ENOENT;
2362 		ret = -rte_errno;
2363 		goto exit;
2364 	}
2365 	if (nd == 1) {
2366 		/*
2367 		 * Found single matching device may have multiple ports.
2368 		 * Each port may be representor, we have to check the port
2369 		 * number and check the representors existence.
2370 		 */
2371 		if (nl_rdma >= 0)
2372 			np = mlx5_nl_portnum(nl_rdma, ibv_match[0]->name);
2373 		if (!np)
2374 			DRV_LOG(WARNING,
2375 				"Cannot get IB device \"%s\" ports number.",
2376 				ibv_match[0]->name);
2377 		if (bd >= 0 && !np) {
2378 			DRV_LOG(ERR, "Cannot get ports for bonding device.");
2379 			rte_errno = ENOENT;
2380 			ret = -rte_errno;
2381 			goto exit;
2382 		}
2383 		if (mpesw >= 0 && !np) {
2384 			DRV_LOG(ERR, "Cannot get ports for MPESW device.");
2385 			rte_errno = ENOENT;
2386 			ret = -rte_errno;
2387 			goto exit;
2388 		}
2389 	}
2390 	/* Now we can determine the maximal amount of devices to be spawned. */
2391 	list = mlx5_malloc(MLX5_MEM_ZERO,
2392 			   sizeof(struct mlx5_dev_spawn_data) * (np ? np : nd),
2393 			   RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
2394 	if (!list) {
2395 		DRV_LOG(ERR, "Spawn data array allocation failure.");
2396 		rte_errno = ENOMEM;
2397 		ret = -rte_errno;
2398 		goto exit;
2399 	}
2400 	if (bd >= 0 || mpesw >= 0 || np > 1) {
2401 		/*
2402 		 * Single IB device with multiple ports found,
2403 		 * it may be E-Switch master device and representors.
2404 		 * We have to perform identification through the ports.
2405 		 */
2406 		MLX5_ASSERT(nl_rdma >= 0);
2407 		MLX5_ASSERT(ns == 0);
2408 		MLX5_ASSERT(nd == 1);
2409 		MLX5_ASSERT(np);
2410 		for (i = 1; i <= np; ++i) {
2411 			list[ns].bond_info = &bond_info;
2412 			list[ns].max_port = np;
2413 			list[ns].phys_port = i;
2414 			list[ns].phys_dev_name = ibv_match[0]->name;
2415 			list[ns].eth_dev = NULL;
2416 			list[ns].pci_dev = pci_dev;
2417 			list[ns].cdev = cdev;
2418 			list[ns].pf_bond = bd;
2419 			list[ns].mpesw_port = MLX5_MPESW_PORT_INVALID;
2420 			list[ns].ifindex = mlx5_nl_ifindex(nl_rdma,
2421 							   ibv_match[0]->name,
2422 							   i);
2423 			if (!list[ns].ifindex) {
2424 				/*
2425 				 * No network interface index found for the
2426 				 * specified port, it means there is no
2427 				 * representor on this port. It's OK,
2428 				 * there can be disabled ports, for example
2429 				 * if sriov_numvfs < sriov_totalvfs.
2430 				 */
2431 				continue;
2432 			}
2433 			ret = -1;
2434 			if (nl_route >= 0)
2435 				ret = mlx5_nl_switch_info(nl_route,
2436 							  list[ns].ifindex,
2437 							  &list[ns].info);
2438 			if (ret || (!list[ns].info.representor &&
2439 				    !list[ns].info.master)) {
2440 				/*
2441 				 * We failed to recognize representors with
2442 				 * Netlink, let's try to perform the task
2443 				 * with sysfs.
2444 				 */
2445 				ret = mlx5_sysfs_switch_info(list[ns].ifindex,
2446 							     &list[ns].info);
2447 			}
2448 			if (!ret && bd >= 0) {
2449 				switch (list[ns].info.name_type) {
2450 				case MLX5_PHYS_PORT_NAME_TYPE_UPLINK:
2451 					if (np == 1) {
2452 						/*
2453 						 * Force standalone bonding
2454 						 * device for ROCE LAG
2455 						 * configurations.
2456 						 */
2457 						list[ns].info.master = 0;
2458 						list[ns].info.representor = 0;
2459 					}
2460 					if (list[ns].info.port_name == bd)
2461 						ns++;
2462 					break;
2463 				case MLX5_PHYS_PORT_NAME_TYPE_PFHPF:
2464 					/* Fallthrough */
2465 				case MLX5_PHYS_PORT_NAME_TYPE_PFVF:
2466 					/* Fallthrough */
2467 				case MLX5_PHYS_PORT_NAME_TYPE_PFSF:
2468 					if (list[ns].info.pf_num == bd)
2469 						ns++;
2470 					break;
2471 				default:
2472 					break;
2473 				}
2474 				continue;
2475 			}
2476 			if (!ret && mpesw >= 0) {
2477 				switch (list[ns].info.name_type) {
2478 				case MLX5_PHYS_PORT_NAME_TYPE_UPLINK:
2479 					/* Owner port is treated as master port. */
2480 					if (list[ns].info.port_name == mpesw) {
2481 						list[ns].info.master = 1;
2482 						list[ns].info.representor = 0;
2483 					} else {
2484 						list[ns].info.master = 0;
2485 						list[ns].info.representor = 1;
2486 					}
2487 					/*
2488 					 * Ports of this type have uplink port index
2489 					 * encoded in the name. This index is also a PF index.
2490 					 */
2491 					list[ns].info.pf_num = list[ns].info.port_name;
2492 					list[ns].mpesw_port = list[ns].info.port_name;
2493 					list[ns].info.mpesw_owner = mpesw;
2494 					ns++;
2495 					break;
2496 				case MLX5_PHYS_PORT_NAME_TYPE_PFHPF:
2497 				case MLX5_PHYS_PORT_NAME_TYPE_PFVF:
2498 				case MLX5_PHYS_PORT_NAME_TYPE_PFSF:
2499 					/* Only spawn representors related to the probed PF. */
2500 					if (list[ns].info.pf_num == owner_id) {
2501 						/*
2502 						 * Ports of this type have PF index encoded in name,
2503 						 * which translate to the related uplink port index.
2504 						 */
2505 						list[ns].mpesw_port = list[ns].info.pf_num;
2506 						/* MPESW owner is also saved but not used now. */
2507 						list[ns].info.mpesw_owner = mpesw;
2508 						ns++;
2509 					}
2510 					break;
2511 				default:
2512 					break;
2513 				}
2514 				continue;
2515 			}
2516 			if (!ret && (list[ns].info.representor ^
2517 				     list[ns].info.master))
2518 				ns++;
2519 		}
2520 		if (!ns) {
2521 			DRV_LOG(ERR,
2522 				"Unable to recognize master/representors on the IB device with multiple ports.");
2523 			rte_errno = ENOENT;
2524 			ret = -rte_errno;
2525 			goto exit;
2526 		}
2527 	} else {
2528 		/*
2529 		 * The existence of several matching entries (nd > 1) means
2530 		 * port representors have been instantiated. No existing Verbs
2531 		 * call nor sysfs entries can tell them apart, this can only
2532 		 * be done through Netlink calls assuming kernel drivers are
2533 		 * recent enough to support them.
2534 		 *
2535 		 * In the event of identification failure through Netlink,
2536 		 * try again through sysfs, then:
2537 		 *
2538 		 * 1. A single IB device matches (nd == 1) with single
2539 		 *    port (np=0/1) and is not a representor, assume
2540 		 *    no switch support.
2541 		 *
2542 		 * 2. Otherwise no safe assumptions can be made;
2543 		 *    complain louder and bail out.
2544 		 */
2545 		for (i = 0; i != nd; ++i) {
2546 			memset(&list[ns].info, 0, sizeof(list[ns].info));
2547 			list[ns].bond_info = NULL;
2548 			list[ns].max_port = 1;
2549 			list[ns].phys_port = 1;
2550 			list[ns].phys_dev_name = ibv_match[i]->name;
2551 			list[ns].eth_dev = NULL;
2552 			list[ns].pci_dev = pci_dev;
2553 			list[ns].cdev = cdev;
2554 			list[ns].pf_bond = -1;
2555 			list[ns].mpesw_port = MLX5_MPESW_PORT_INVALID;
2556 			list[ns].ifindex = 0;
2557 			if (nl_rdma >= 0)
2558 				list[ns].ifindex = mlx5_nl_ifindex
2559 							    (nl_rdma,
2560 							     ibv_match[i]->name,
2561 							     1);
2562 			if (!list[ns].ifindex) {
2563 				char ifname[IF_NAMESIZE];
2564 
2565 				/*
2566 				 * Netlink failed, it may happen with old
2567 				 * ib_core kernel driver (before 4.16).
2568 				 * We can assume there is old driver because
2569 				 * here we are processing single ports IB
2570 				 * devices. Let's try sysfs to retrieve
2571 				 * the ifindex. The method works for
2572 				 * master device only.
2573 				 */
2574 				if (nd > 1) {
2575 					/*
2576 					 * Multiple devices found, assume
2577 					 * representors, can not distinguish
2578 					 * master/representor and retrieve
2579 					 * ifindex via sysfs.
2580 					 */
2581 					continue;
2582 				}
2583 				ret = mlx5_get_ifname_sysfs
2584 					(ibv_match[i]->ibdev_path, ifname);
2585 				if (!ret)
2586 					list[ns].ifindex =
2587 						if_nametoindex(ifname);
2588 				if (!list[ns].ifindex) {
2589 					/*
2590 					 * No network interface index found
2591 					 * for the specified device, it means
2592 					 * there it is neither representor
2593 					 * nor master.
2594 					 */
2595 					continue;
2596 				}
2597 			}
2598 			ret = -1;
2599 			if (nl_route >= 0)
2600 				ret = mlx5_nl_switch_info(nl_route,
2601 							  list[ns].ifindex,
2602 							  &list[ns].info);
2603 			if (ret || (!list[ns].info.representor &&
2604 				    !list[ns].info.master)) {
2605 				/*
2606 				 * We failed to recognize representors with
2607 				 * Netlink, let's try to perform the task
2608 				 * with sysfs.
2609 				 */
2610 				ret = mlx5_sysfs_switch_info(list[ns].ifindex,
2611 							     &list[ns].info);
2612 			}
2613 			if (!ret && (list[ns].info.representor ^
2614 				     list[ns].info.master)) {
2615 				ns++;
2616 			} else if ((nd == 1) &&
2617 				   !list[ns].info.representor &&
2618 				   !list[ns].info.master) {
2619 				/*
2620 				 * Single IB device with one physical port and
2621 				 * attached network device.
2622 				 * May be SRIOV is not enabled or there is no
2623 				 * representors.
2624 				 */
2625 				DRV_LOG(INFO, "No E-Switch support detected.");
2626 				ns++;
2627 				break;
2628 			}
2629 		}
2630 		if (!ns) {
2631 			DRV_LOG(ERR,
2632 				"Unable to recognize master/representors on the multiple IB devices.");
2633 			rte_errno = ENOENT;
2634 			ret = -rte_errno;
2635 			goto exit;
2636 		}
2637 		/*
2638 		 * New kernels may add the switch_id attribute for the case
2639 		 * there is no E-Switch and we wrongly recognized the only
2640 		 * device as master. Override this if there is the single
2641 		 * device with single port and new device name format present.
2642 		 */
2643 		if (nd == 1 &&
2644 		    list[0].info.name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK) {
2645 			list[0].info.master = 0;
2646 			list[0].info.representor = 0;
2647 		}
2648 	}
2649 	MLX5_ASSERT(ns);
2650 	/*
2651 	 * Sort list to probe devices in natural order for users convenience
2652 	 * (i.e. master first, then representors from lowest to highest ID).
2653 	 */
2654 	qsort(list, ns, sizeof(*list), mlx5_dev_spawn_data_cmp);
2655 	if (eth_da.type != RTE_ETH_REPRESENTOR_NONE) {
2656 		/* Set devargs default values. */
2657 		if (eth_da.nb_mh_controllers == 0) {
2658 			eth_da.nb_mh_controllers = 1;
2659 			eth_da.mh_controllers[0] = 0;
2660 		}
2661 		if (eth_da.nb_ports == 0 && ns > 0) {
2662 			if (list[0].pf_bond >= 0 && list[0].info.representor)
2663 				DRV_LOG(WARNING, "Representor on Bonding device should use pf#vf# syntax: %s",
2664 					pci_dev->device.devargs->args);
2665 			eth_da.nb_ports = 1;
2666 			eth_da.ports[0] = list[0].info.pf_num;
2667 		}
2668 		if (eth_da.nb_representor_ports == 0) {
2669 			eth_da.nb_representor_ports = 1;
2670 			eth_da.representor_ports[0] = 0;
2671 		}
2672 	}
2673 	for (i = 0; i != ns; ++i) {
2674 		uint32_t restore;
2675 
2676 		list[i].eth_dev = mlx5_dev_spawn(cdev->dev, &list[i], &eth_da,
2677 						 mkvlist);
2678 		if (!list[i].eth_dev) {
2679 			if (rte_errno != EBUSY && rte_errno != EEXIST)
2680 				break;
2681 			/* Device is disabled or already spawned. Ignore it. */
2682 			continue;
2683 		}
2684 		restore = list[i].eth_dev->data->dev_flags;
2685 		rte_eth_copy_pci_info(list[i].eth_dev, pci_dev);
2686 		/**
2687 		 * Each representor has a dedicated interrupts vector.
2688 		 * rte_eth_copy_pci_info() assigns PF interrupts handle to
2689 		 * representor eth_dev object because representor and PF
2690 		 * share the same PCI address.
2691 		 * Override representor device with a dedicated
2692 		 * interrupts handle here.
2693 		 * Representor interrupts handle is released in mlx5_dev_stop().
2694 		 */
2695 		if (list[i].info.representor) {
2696 			struct rte_intr_handle *intr_handle =
2697 				rte_intr_instance_alloc(RTE_INTR_INSTANCE_F_SHARED);
2698 			if (intr_handle == NULL) {
2699 				DRV_LOG(ERR,
2700 					"port %u failed to allocate memory for interrupt handler "
2701 					"Rx interrupts will not be supported",
2702 					i);
2703 				rte_errno = ENOMEM;
2704 				ret = -rte_errno;
2705 				goto exit;
2706 			}
2707 			list[i].eth_dev->intr_handle = intr_handle;
2708 		}
2709 		/* Restore non-PCI flags cleared by the above call. */
2710 		list[i].eth_dev->data->dev_flags |= restore;
2711 		rte_eth_dev_probing_finish(list[i].eth_dev);
2712 	}
2713 	if (i != ns) {
2714 		DRV_LOG(ERR,
2715 			"probe of PCI device " PCI_PRI_FMT " aborted after"
2716 			" encountering an error: %s",
2717 			owner_pci.domain, owner_pci.bus,
2718 			owner_pci.devid, owner_pci.function,
2719 			strerror(rte_errno));
2720 		ret = -rte_errno;
2721 		/* Roll back. */
2722 		while (i--) {
2723 			if (!list[i].eth_dev)
2724 				continue;
2725 			mlx5_dev_close(list[i].eth_dev);
2726 			/* mac_addrs must not be freed because in dev_private */
2727 			list[i].eth_dev->data->mac_addrs = NULL;
2728 			claim_zero(rte_eth_dev_release_port(list[i].eth_dev));
2729 		}
2730 		/* Restore original error. */
2731 		rte_errno = -ret;
2732 	} else {
2733 		ret = 0;
2734 	}
2735 exit:
2736 	/*
2737 	 * Do the routine cleanup:
2738 	 * - close opened Netlink sockets
2739 	 * - free allocated spawn data array
2740 	 * - free the Infiniband device list
2741 	 */
2742 	if (nl_rdma >= 0)
2743 		close(nl_rdma);
2744 	if (nl_route >= 0)
2745 		close(nl_route);
2746 	if (list)
2747 		mlx5_free(list);
2748 	MLX5_ASSERT(ibv_list);
2749 	mlx5_glue->free_device_list(ibv_list);
2750 	return ret;
2751 }
2752 
2753 static int
2754 mlx5_os_parse_eth_devargs(struct rte_device *dev,
2755 			  struct rte_eth_devargs *eth_da)
2756 {
2757 	int ret = 0;
2758 
2759 	if (dev->devargs == NULL)
2760 		return 0;
2761 	memset(eth_da, 0, sizeof(*eth_da));
2762 	/* Parse representor information first from class argument. */
2763 	if (dev->devargs->cls_str)
2764 		ret = rte_eth_devargs_parse(dev->devargs->cls_str, eth_da, 1);
2765 	if (ret < 0) {
2766 		DRV_LOG(ERR, "failed to parse device arguments: %s",
2767 			dev->devargs->cls_str);
2768 		return -rte_errno;
2769 	}
2770 	if (eth_da->type == RTE_ETH_REPRESENTOR_NONE && dev->devargs->args) {
2771 		/* Parse legacy device argument */
2772 		ret = rte_eth_devargs_parse(dev->devargs->args, eth_da, 1);
2773 		if (ret < 0) {
2774 			DRV_LOG(ERR, "failed to parse device arguments: %s",
2775 				dev->devargs->args);
2776 			return -rte_errno;
2777 		}
2778 	}
2779 	return 0;
2780 }
2781 
2782 /**
2783  * Callback to register a PCI device.
2784  *
2785  * This function spawns Ethernet devices out of a given PCI device.
2786  *
2787  * @param[in] cdev
2788  *   Pointer to common mlx5 device structure.
2789  * @param[in, out] mkvlist
2790  *   Pointer to mlx5 kvargs control, can be NULL if there is no devargs.
2791  *
2792  * @return
2793  *   0 on success, a negative errno value otherwise and rte_errno is set.
2794  */
2795 static int
2796 mlx5_os_pci_probe(struct mlx5_common_device *cdev,
2797 		  struct mlx5_kvargs_ctrl *mkvlist)
2798 {
2799 	struct rte_pci_device *pci_dev = RTE_DEV_TO_PCI(cdev->dev);
2800 	struct rte_eth_devargs eth_da = { .nb_ports = 0 };
2801 	int ret = 0;
2802 	uint16_t p;
2803 
2804 	ret = mlx5_os_parse_eth_devargs(cdev->dev, &eth_da);
2805 	if (ret != 0)
2806 		return ret;
2807 
2808 	if (eth_da.nb_ports > 0) {
2809 		/* Iterate all port if devargs pf is range: "pf[0-1]vf[...]". */
2810 		for (p = 0; p < eth_da.nb_ports; p++) {
2811 			ret = mlx5_os_pci_probe_pf(cdev, &eth_da,
2812 						   eth_da.ports[p], mkvlist);
2813 			if (ret) {
2814 				DRV_LOG(INFO, "Probe of PCI device " PCI_PRI_FMT " "
2815 					"aborted due to proding failure of PF %u",
2816 					pci_dev->addr.domain, pci_dev->addr.bus,
2817 					pci_dev->addr.devid, pci_dev->addr.function,
2818 					eth_da.ports[p]);
2819 				mlx5_net_remove(cdev);
2820 				if (p != 0)
2821 					break;
2822 			}
2823 		}
2824 	} else {
2825 		ret = mlx5_os_pci_probe_pf(cdev, &eth_da, 0, mkvlist);
2826 	}
2827 	return ret;
2828 }
2829 
2830 /* Probe a single SF device on auxiliary bus, no representor support. */
2831 static int
2832 mlx5_os_auxiliary_probe(struct mlx5_common_device *cdev,
2833 			struct mlx5_kvargs_ctrl *mkvlist)
2834 {
2835 	struct rte_eth_devargs eth_da = { .nb_ports = 0 };
2836 	struct mlx5_dev_spawn_data spawn = {
2837 		.pf_bond = -1,
2838 		.mpesw_port = MLX5_MPESW_PORT_INVALID,
2839 	};
2840 	struct rte_device *dev = cdev->dev;
2841 	struct rte_auxiliary_device *adev = RTE_DEV_TO_AUXILIARY(dev);
2842 	struct rte_eth_dev *eth_dev;
2843 	int ret = 0;
2844 
2845 	/* Parse ethdev devargs. */
2846 	ret = mlx5_os_parse_eth_devargs(dev, &eth_da);
2847 	if (ret != 0)
2848 		return ret;
2849 	/* Init spawn data. */
2850 	spawn.max_port = 1;
2851 	spawn.phys_port = 1;
2852 	spawn.phys_dev_name = mlx5_os_get_ctx_device_name(cdev->ctx);
2853 	ret = mlx5_auxiliary_get_ifindex(dev->name);
2854 	if (ret < 0) {
2855 		DRV_LOG(ERR, "failed to get ethdev ifindex: %s", dev->name);
2856 		return ret;
2857 	}
2858 	spawn.ifindex = ret;
2859 	spawn.cdev = cdev;
2860 	/* Spawn device. */
2861 	eth_dev = mlx5_dev_spawn(dev, &spawn, &eth_da, mkvlist);
2862 	if (eth_dev == NULL)
2863 		return -rte_errno;
2864 	/* Post create. */
2865 	eth_dev->intr_handle = adev->intr_handle;
2866 	if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
2867 		eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_LSC;
2868 		eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_RMV;
2869 		eth_dev->data->numa_node = dev->numa_node;
2870 	}
2871 	rte_eth_dev_probing_finish(eth_dev);
2872 	return 0;
2873 }
2874 
2875 /**
2876  * Net class driver callback to probe a device.
2877  *
2878  * This function probe PCI bus device(s) or a single SF on auxiliary bus.
2879  *
2880  * @param[in] cdev
2881  *   Pointer to the common mlx5 device.
2882  * @param[in, out] mkvlist
2883  *   Pointer to mlx5 kvargs control, can be NULL if there is no devargs.
2884  *
2885  * @return
2886  *   0 on success, a negative errno value otherwise and rte_errno is set.
2887  */
2888 int
2889 mlx5_os_net_probe(struct mlx5_common_device *cdev,
2890 		  struct mlx5_kvargs_ctrl *mkvlist)
2891 {
2892 	int ret;
2893 
2894 	if (rte_eal_process_type() == RTE_PROC_PRIMARY)
2895 		mlx5_pmd_socket_init();
2896 	ret = mlx5_init_once();
2897 	if (ret) {
2898 		DRV_LOG(ERR, "Unable to init PMD global data: %s",
2899 			strerror(rte_errno));
2900 		return -rte_errno;
2901 	}
2902 	ret = mlx5_probe_again_args_validate(cdev, mkvlist);
2903 	if (ret) {
2904 		DRV_LOG(ERR, "Probe again parameters are not compatible : %s",
2905 			strerror(rte_errno));
2906 		return -rte_errno;
2907 	}
2908 	if (mlx5_dev_is_pci(cdev->dev))
2909 		return mlx5_os_pci_probe(cdev, mkvlist);
2910 	else
2911 		return mlx5_os_auxiliary_probe(cdev, mkvlist);
2912 }
2913 
2914 /**
2915  * Cleanup resources when the last device is closed.
2916  */
2917 void
2918 mlx5_os_net_cleanup(void)
2919 {
2920 	mlx5_pmd_socket_uninit();
2921 }
2922 
2923 /**
2924  * Install shared asynchronous device events handler.
2925  * This function is implemented to support event sharing
2926  * between multiple ports of single IB device.
2927  *
2928  * @param sh
2929  *   Pointer to mlx5_dev_ctx_shared object.
2930  */
2931 void
2932 mlx5_os_dev_shared_handler_install(struct mlx5_dev_ctx_shared *sh)
2933 {
2934 	struct ibv_context *ctx = sh->cdev->ctx;
2935 	int nlsk_fd;
2936 
2937 	sh->intr_handle = mlx5_os_interrupt_handler_create
2938 		(RTE_INTR_INSTANCE_F_SHARED, true,
2939 		 ctx->async_fd, mlx5_dev_interrupt_handler, sh);
2940 	if (!sh->intr_handle) {
2941 		DRV_LOG(ERR, "Failed to allocate intr_handle.");
2942 		return;
2943 	}
2944 	nlsk_fd = mlx5_nl_init(NETLINK_ROUTE, RTMGRP_LINK);
2945 	if (nlsk_fd < 0) {
2946 		DRV_LOG(ERR, "Failed to create a socket for Netlink events: %s",
2947 			rte_strerror(rte_errno));
2948 		return;
2949 	}
2950 	sh->intr_handle_nl = mlx5_os_interrupt_handler_create
2951 		(RTE_INTR_INSTANCE_F_SHARED, true,
2952 		 nlsk_fd, mlx5_dev_interrupt_handler_nl, sh);
2953 	if (sh->intr_handle_nl == NULL) {
2954 		DRV_LOG(ERR, "Fail to allocate intr_handle");
2955 		return;
2956 	}
2957 	if (sh->cdev->config.devx) {
2958 #ifdef HAVE_IBV_DEVX_ASYNC
2959 		struct mlx5dv_devx_cmd_comp *devx_comp;
2960 
2961 		sh->devx_comp = (void *)mlx5_glue->devx_create_cmd_comp(ctx);
2962 		devx_comp = sh->devx_comp;
2963 		if (!devx_comp) {
2964 			DRV_LOG(INFO, "failed to allocate devx_comp.");
2965 			return;
2966 		}
2967 		sh->intr_handle_devx = mlx5_os_interrupt_handler_create
2968 			(RTE_INTR_INSTANCE_F_SHARED, true,
2969 			 devx_comp->fd,
2970 			 mlx5_dev_interrupt_handler_devx, sh);
2971 		if (!sh->intr_handle_devx) {
2972 			DRV_LOG(ERR, "Failed to allocate intr_handle.");
2973 			return;
2974 		}
2975 #endif /* HAVE_IBV_DEVX_ASYNC */
2976 	}
2977 }
2978 
2979 /**
2980  * Uninstall shared asynchronous device events handler.
2981  * This function is implemented to support event sharing
2982  * between multiple ports of single IB device.
2983  *
2984  * @param dev
2985  *   Pointer to mlx5_dev_ctx_shared object.
2986  */
2987 void
2988 mlx5_os_dev_shared_handler_uninstall(struct mlx5_dev_ctx_shared *sh)
2989 {
2990 	mlx5_os_interrupt_handler_destroy(sh->intr_handle,
2991 					  mlx5_dev_interrupt_handler, sh);
2992 	mlx5_os_interrupt_handler_destroy(sh->intr_handle_nl,
2993 					  mlx5_dev_interrupt_handler_nl, sh);
2994 #ifdef HAVE_IBV_DEVX_ASYNC
2995 	mlx5_os_interrupt_handler_destroy(sh->intr_handle_devx,
2996 					  mlx5_dev_interrupt_handler_devx, sh);
2997 	if (sh->devx_comp)
2998 		mlx5_glue->devx_destroy_cmd_comp(sh->devx_comp);
2999 #endif
3000 }
3001 
3002 /**
3003  * Read statistics by a named counter.
3004  *
3005  * @param[in] priv
3006  *   Pointer to the private device data structure.
3007  * @param[in] ctr_name
3008  *   Pointer to the name of the statistic counter to read
3009  * @param[out] stat
3010  *   Pointer to read statistic value.
3011  * @return
3012  *   0 on success and stat is valud, 1 if failed to read the value
3013  *   rte_errno is set.
3014  *
3015  */
3016 int
3017 mlx5_os_read_dev_stat(struct mlx5_priv *priv, const char *ctr_name,
3018 		      uint64_t *stat)
3019 {
3020 	int fd;
3021 
3022 	if (priv->sh) {
3023 		if (priv->q_counters != NULL &&
3024 		    strcmp(ctr_name, "out_of_buffer") == 0) {
3025 			if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
3026 				DRV_LOG(WARNING, "Devx out_of_buffer counter is not supported in the secondary process");
3027 				rte_errno = ENOTSUP;
3028 				return 1;
3029 			}
3030 			return mlx5_devx_cmd_queue_counter_query
3031 					(priv->q_counters, 0, (uint32_t *)stat);
3032 		}
3033 		MKSTR(path, "%s/ports/%d/hw_counters/%s",
3034 		      priv->sh->ibdev_path,
3035 		      priv->dev_port,
3036 		      ctr_name);
3037 		fd = open(path, O_RDONLY);
3038 		/*
3039 		 * in switchdev the file location is not per port
3040 		 * but rather in <ibdev_path>/hw_counters/<file_name>.
3041 		 */
3042 		if (fd == -1) {
3043 			MKSTR(path1, "%s/hw_counters/%s",
3044 			      priv->sh->ibdev_path,
3045 			      ctr_name);
3046 			fd = open(path1, O_RDONLY);
3047 		}
3048 		if (fd != -1) {
3049 			char buf[21] = {'\0'};
3050 			ssize_t n = read(fd, buf, sizeof(buf));
3051 
3052 			close(fd);
3053 			if (n != -1) {
3054 				*stat = strtoull(buf, NULL, 10);
3055 				return 0;
3056 			}
3057 		}
3058 	}
3059 	*stat = 0;
3060 	return 1;
3061 }
3062 
3063 /**
3064  * Remove a MAC address from device
3065  *
3066  * @param dev
3067  *   Pointer to Ethernet device structure.
3068  * @param index
3069  *   MAC address index.
3070  */
3071 void
3072 mlx5_os_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
3073 {
3074 	struct mlx5_priv *priv = dev->data->dev_private;
3075 	const int vf = priv->sh->dev_cap.vf;
3076 
3077 	if (vf)
3078 		mlx5_nl_mac_addr_remove(priv->nl_socket_route,
3079 					mlx5_ifindex(dev), priv->mac_own,
3080 					&dev->data->mac_addrs[index], index);
3081 }
3082 
3083 /**
3084  * Adds a MAC address to the device
3085  *
3086  * @param dev
3087  *   Pointer to Ethernet device structure.
3088  * @param mac_addr
3089  *   MAC address to register.
3090  * @param index
3091  *   MAC address index.
3092  *
3093  * @return
3094  *   0 on success, a negative errno value otherwise
3095  */
3096 int
3097 mlx5_os_mac_addr_add(struct rte_eth_dev *dev, struct rte_ether_addr *mac,
3098 		     uint32_t index)
3099 {
3100 	struct mlx5_priv *priv = dev->data->dev_private;
3101 	const int vf = priv->sh->dev_cap.vf;
3102 	int ret = 0;
3103 
3104 	if (vf)
3105 		ret = mlx5_nl_mac_addr_add(priv->nl_socket_route,
3106 					   mlx5_ifindex(dev), priv->mac_own,
3107 					   mac, index);
3108 	return ret;
3109 }
3110 
3111 /**
3112  * Modify a VF MAC address
3113  *
3114  * @param priv
3115  *   Pointer to device private data.
3116  * @param mac_addr
3117  *   MAC address to modify into.
3118  * @param iface_idx
3119  *   Net device interface index
3120  * @param vf_index
3121  *   VF index
3122  *
3123  * @return
3124  *   0 on success, a negative errno value otherwise
3125  */
3126 int
3127 mlx5_os_vf_mac_addr_modify(struct mlx5_priv *priv,
3128 			   unsigned int iface_idx,
3129 			   struct rte_ether_addr *mac_addr,
3130 			   int vf_index)
3131 {
3132 	return mlx5_nl_vf_mac_addr_modify
3133 		(priv->nl_socket_route, iface_idx, mac_addr, vf_index);
3134 }
3135 
3136 /**
3137  * Set device promiscuous mode
3138  *
3139  * @param dev
3140  *   Pointer to Ethernet device structure.
3141  * @param enable
3142  *   0 - promiscuous is disabled, otherwise - enabled
3143  *
3144  * @return
3145  *   0 on success, a negative error value otherwise
3146  */
3147 int
3148 mlx5_os_set_promisc(struct rte_eth_dev *dev, int enable)
3149 {
3150 	struct mlx5_priv *priv = dev->data->dev_private;
3151 
3152 	return mlx5_nl_promisc(priv->nl_socket_route,
3153 			       mlx5_ifindex(dev), !!enable);
3154 }
3155 
3156 /**
3157  * Set device promiscuous mode
3158  *
3159  * @param dev
3160  *   Pointer to Ethernet device structure.
3161  * @param enable
3162  *   0 - all multicase is disabled, otherwise - enabled
3163  *
3164  * @return
3165  *   0 on success, a negative error value otherwise
3166  */
3167 int
3168 mlx5_os_set_allmulti(struct rte_eth_dev *dev, int enable)
3169 {
3170 	struct mlx5_priv *priv = dev->data->dev_private;
3171 
3172 	return mlx5_nl_allmulti(priv->nl_socket_route,
3173 				mlx5_ifindex(dev), !!enable);
3174 }
3175 
3176 /**
3177  * Flush device MAC addresses
3178  *
3179  * @param dev
3180  *   Pointer to Ethernet device structure.
3181  *
3182  */
3183 void
3184 mlx5_os_mac_addr_flush(struct rte_eth_dev *dev)
3185 {
3186 	struct mlx5_priv *priv = dev->data->dev_private;
3187 
3188 	mlx5_nl_mac_addr_flush(priv->nl_socket_route, mlx5_ifindex(dev),
3189 			       dev->data->mac_addrs,
3190 			       MLX5_MAX_MAC_ADDRESSES, priv->mac_own);
3191 }
3192