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