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