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