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