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