xref: /dpdk/drivers/common/mlx5/mlx5_common.c (revision 69f9d8aa357d2299e057b7e335f340e20a0c5e7e)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2019 Mellanox Technologies, Ltd
3  */
4 
5 #include <unistd.h>
6 #include <string.h>
7 #include <stdio.h>
8 
9 #include <rte_errno.h>
10 #include <rte_mempool.h>
11 #include <rte_class.h>
12 #include <rte_malloc.h>
13 #include <rte_eal_paging.h>
14 
15 #include "mlx5_common.h"
16 #include "mlx5_common_os.h"
17 #include "mlx5_common_mp.h"
18 #include "mlx5_common_log.h"
19 #include "mlx5_common_defs.h"
20 #include "mlx5_common_private.h"
21 
22 uint8_t haswell_broadwell_cpu;
23 
24 /* In case this is an x86_64 intel processor to check if
25  * we should use relaxed ordering.
26  */
27 #ifdef RTE_ARCH_X86_64
28 /**
29  * This function returns processor identification and feature information
30  * into the registers.
31  *
32  * @param eax, ebx, ecx, edx
33  *		Pointers to the registers that will hold cpu information.
34  * @param level
35  *		The main category of information returned.
36  */
37 static inline void mlx5_cpu_id(unsigned int level,
38 				unsigned int *eax, unsigned int *ebx,
39 				unsigned int *ecx, unsigned int *edx)
40 {
41 	__asm__("cpuid\n\t"
42 		: "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx)
43 		: "0" (level));
44 }
45 #endif
46 
47 RTE_LOG_REGISTER_DEFAULT(mlx5_common_logtype, NOTICE)
48 
49 /* Head of list of drivers. */
50 static TAILQ_HEAD(mlx5_drivers, mlx5_class_driver) drivers_list =
51 				TAILQ_HEAD_INITIALIZER(drivers_list);
52 
53 /* Head of devices. */
54 static TAILQ_HEAD(mlx5_devices, mlx5_common_device) devices_list =
55 				TAILQ_HEAD_INITIALIZER(devices_list);
56 static pthread_mutex_t devices_list_lock;
57 
58 static const struct {
59 	const char *name;
60 	unsigned int drv_class;
61 } mlx5_classes[] = {
62 	{ .name = "vdpa", .drv_class = MLX5_CLASS_VDPA },
63 	{ .name = "eth", .drv_class = MLX5_CLASS_ETH },
64 	/* Keep class "net" for backward compatibility. */
65 	{ .name = "net", .drv_class = MLX5_CLASS_ETH },
66 	{ .name = "regex", .drv_class = MLX5_CLASS_REGEX },
67 	{ .name = "compress", .drv_class = MLX5_CLASS_COMPRESS },
68 	{ .name = "crypto", .drv_class = MLX5_CLASS_CRYPTO },
69 };
70 
71 static int
72 class_name_to_value(const char *class_name)
73 {
74 	unsigned int i;
75 
76 	for (i = 0; i < RTE_DIM(mlx5_classes); i++) {
77 		if (strcmp(class_name, mlx5_classes[i].name) == 0)
78 			return mlx5_classes[i].drv_class;
79 	}
80 	return -EINVAL;
81 }
82 
83 static struct mlx5_class_driver *
84 driver_get(uint32_t class)
85 {
86 	struct mlx5_class_driver *driver;
87 
88 	TAILQ_FOREACH(driver, &drivers_list, next) {
89 		if ((uint32_t)driver->drv_class == class)
90 			return driver;
91 	}
92 	return NULL;
93 }
94 
95 /**
96  * Verify and store value for devargs.
97  *
98  * @param[in] key
99  *   Key argument to verify.
100  * @param[in] val
101  *   Value associated with key.
102  * @param opaque
103  *   User data.
104  *
105  * @return
106  *   0 on success, a negative errno value otherwise and rte_errno is set.
107  */
108 static int
109 mlx5_common_args_check_handler(const char *key, const char *val, void *opaque)
110 {
111 	struct mlx5_common_dev_config *config = opaque;
112 	signed long tmp;
113 
114 	errno = 0;
115 	tmp = strtol(val, NULL, 0);
116 	if (errno) {
117 		rte_errno = errno;
118 		DRV_LOG(WARNING, "%s: \"%s\" is an invalid integer.", key, val);
119 		return -rte_errno;
120 	}
121 	if (strcmp(key, "tx_db_nc") == 0) {
122 		if (tmp != MLX5_TXDB_CACHED &&
123 		    tmp != MLX5_TXDB_NCACHED &&
124 		    tmp != MLX5_TXDB_HEURISTIC) {
125 			DRV_LOG(ERR, "Invalid Tx doorbell mapping parameter.");
126 			rte_errno = EINVAL;
127 			return -rte_errno;
128 		}
129 		config->dbnc = tmp;
130 	} else if (strcmp(key, "mr_ext_memseg_en") == 0) {
131 		config->mr_ext_memseg_en = !!tmp;
132 	} else if (strcmp(key, "mr_mempool_reg_en") == 0) {
133 		config->mr_mempool_reg_en = !!tmp;
134 	} else if (strcmp(key, "sys_mem_en") == 0) {
135 		config->sys_mem_en = !!tmp;
136 	}
137 	return 0;
138 }
139 
140 /**
141  * Parse common device parameters.
142  *
143  * @param devargs
144  *   Device arguments structure.
145  * @param config
146  *   Pointer to device configuration structure.
147  *
148  * @return
149  *   0 on success, a negative errno value otherwise and rte_errno is set.
150  */
151 static int
152 mlx5_common_config_get(struct rte_devargs *devargs,
153 		       struct mlx5_common_dev_config *config)
154 {
155 	struct rte_kvargs *kvlist;
156 	int ret = 0;
157 
158 	/* Set defaults. */
159 	config->mr_ext_memseg_en = 1;
160 	config->mr_mempool_reg_en = 1;
161 	config->sys_mem_en = 0;
162 	config->dbnc = MLX5_ARG_UNSET;
163 	if (devargs == NULL)
164 		return 0;
165 	kvlist = rte_kvargs_parse(devargs->args, NULL);
166 	if (kvlist == NULL) {
167 		rte_errno = EINVAL;
168 		return -rte_errno;
169 	}
170 	ret = rte_kvargs_process(kvlist, NULL, mlx5_common_args_check_handler,
171 				 config);
172 	if (ret)
173 		ret = -rte_errno;
174 	rte_kvargs_free(kvlist);
175 	DRV_LOG(DEBUG, "mr_ext_memseg_en is %u.", config->mr_ext_memseg_en);
176 	DRV_LOG(DEBUG, "mr_mempool_reg_en is %u.", config->mr_mempool_reg_en);
177 	DRV_LOG(DEBUG, "sys_mem_en is %u.", config->sys_mem_en);
178 	DRV_LOG(DEBUG, "Tx doorbell mapping parameter is %d.", config->dbnc);
179 	return ret;
180 }
181 
182 static int
183 devargs_class_handler(__rte_unused const char *key,
184 		      const char *class_names, void *opaque)
185 {
186 	int *ret = opaque;
187 	int class_val;
188 	char *scratch;
189 	char *found;
190 	char *refstr = NULL;
191 
192 	*ret = 0;
193 	scratch = strdup(class_names);
194 	if (scratch == NULL) {
195 		*ret = -ENOMEM;
196 		return *ret;
197 	}
198 	found = strtok_r(scratch, ":", &refstr);
199 	if (found == NULL)
200 		/* Empty string. */
201 		goto err;
202 	do {
203 		/* Extract each individual class name. Multiple
204 		 * classes can be supplied as class=net:regex:foo:bar.
205 		 */
206 		class_val = class_name_to_value(found);
207 		/* Check if its a valid class. */
208 		if (class_val < 0) {
209 			*ret = -EINVAL;
210 			goto err;
211 		}
212 		*ret |= class_val;
213 		found = strtok_r(NULL, ":", &refstr);
214 	} while (found != NULL);
215 err:
216 	free(scratch);
217 	if (*ret < 0)
218 		DRV_LOG(ERR, "Invalid mlx5 class options: %s.\n", class_names);
219 	return *ret;
220 }
221 
222 static int
223 parse_class_options(const struct rte_devargs *devargs)
224 {
225 	struct rte_kvargs *kvlist;
226 	int ret = 0;
227 
228 	if (devargs == NULL)
229 		return 0;
230 	if (devargs->cls != NULL && devargs->cls->name != NULL)
231 		/* Global syntax, only one class type. */
232 		return class_name_to_value(devargs->cls->name);
233 	/* Legacy devargs support multiple classes. */
234 	kvlist = rte_kvargs_parse(devargs->args, NULL);
235 	if (kvlist == NULL)
236 		return 0;
237 	rte_kvargs_process(kvlist, RTE_DEVARGS_KEY_CLASS,
238 			   devargs_class_handler, &ret);
239 	rte_kvargs_free(kvlist);
240 	return ret;
241 }
242 
243 static const unsigned int mlx5_class_invalid_combinations[] = {
244 	MLX5_CLASS_ETH | MLX5_CLASS_VDPA,
245 	/* New class combination should be added here. */
246 };
247 
248 static int
249 is_valid_class_combination(uint32_t user_classes)
250 {
251 	unsigned int i;
252 
253 	/* Verify if user specified unsupported combination. */
254 	for (i = 0; i < RTE_DIM(mlx5_class_invalid_combinations); i++) {
255 		if ((mlx5_class_invalid_combinations[i] & user_classes) ==
256 		    mlx5_class_invalid_combinations[i])
257 			return -EINVAL;
258 	}
259 	/* Not found any invalid class combination. */
260 	return 0;
261 }
262 
263 static bool
264 mlx5_bus_match(const struct mlx5_class_driver *drv,
265 	       const struct rte_device *dev)
266 {
267 	if (mlx5_dev_is_pci(dev))
268 		return mlx5_dev_pci_match(drv, dev);
269 	return true;
270 }
271 
272 static struct mlx5_common_device *
273 to_mlx5_device(const struct rte_device *rte_dev)
274 {
275 	struct mlx5_common_device *cdev;
276 
277 	TAILQ_FOREACH(cdev, &devices_list, next) {
278 		if (rte_dev == cdev->dev)
279 			return cdev;
280 	}
281 	return NULL;
282 }
283 
284 int
285 mlx5_dev_to_pci_str(const struct rte_device *dev, char *addr, size_t size)
286 {
287 	struct rte_pci_addr pci_addr = { 0 };
288 	int ret;
289 
290 	if (mlx5_dev_is_pci(dev)) {
291 		/* Input might be <BDF>, format PCI address to <DBDF>. */
292 		ret = rte_pci_addr_parse(dev->name, &pci_addr);
293 		if (ret != 0)
294 			return -ENODEV;
295 		rte_pci_device_name(&pci_addr, addr, size);
296 		return 0;
297 	}
298 #ifdef RTE_EXEC_ENV_LINUX
299 	return mlx5_auxiliary_get_pci_str(RTE_DEV_TO_AUXILIARY_CONST(dev),
300 			addr, size);
301 #else
302 	rte_errno = ENODEV;
303 	return -rte_errno;
304 #endif
305 }
306 
307 /**
308  * Register the mempool for the protection domain.
309  *
310  * @param cdev
311  *   Pointer to the mlx5 common device.
312  * @param mp
313  *   Mempool being registered.
314  *
315  * @return
316  *   0 on success, (-1) on failure and rte_errno is set.
317  */
318 static int
319 mlx5_dev_mempool_register(struct mlx5_common_device *cdev,
320 			  struct rte_mempool *mp)
321 {
322 	return mlx5_mr_mempool_register(cdev, mp);
323 }
324 
325 /**
326  * Unregister the mempool from the protection domain.
327  *
328  * @param cdev
329  *   Pointer to the mlx5 common device.
330  * @param mp
331  *   Mempool being unregistered.
332  */
333 void
334 mlx5_dev_mempool_unregister(struct mlx5_common_device *cdev,
335 			    struct rte_mempool *mp)
336 {
337 	if (mlx5_mr_mempool_unregister(cdev, mp) < 0)
338 		DRV_LOG(WARNING, "Failed to unregister mempool %s for PD %p: %s",
339 			mp->name, cdev->pd, rte_strerror(rte_errno));
340 }
341 
342 /**
343  * rte_mempool_walk() callback to register mempools for the protection domain.
344  *
345  * @param mp
346  *   The mempool being walked.
347  * @param arg
348  *   Pointer to the device shared context.
349  */
350 static void
351 mlx5_dev_mempool_register_cb(struct rte_mempool *mp, void *arg)
352 {
353 	struct mlx5_common_device *cdev = arg;
354 	int ret;
355 
356 	ret = mlx5_dev_mempool_register(cdev, mp);
357 	if (ret < 0 && rte_errno != EEXIST)
358 		DRV_LOG(ERR,
359 			"Failed to register existing mempool %s for PD %p: %s",
360 			mp->name, cdev->pd, rte_strerror(rte_errno));
361 }
362 
363 /**
364  * rte_mempool_walk() callback to unregister mempools
365  * from the protection domain.
366  *
367  * @param mp
368  *   The mempool being walked.
369  * @param arg
370  *   Pointer to the device shared context.
371  */
372 static void
373 mlx5_dev_mempool_unregister_cb(struct rte_mempool *mp, void *arg)
374 {
375 	mlx5_dev_mempool_unregister((struct mlx5_common_device *)arg, mp);
376 }
377 
378 /**
379  * Mempool life cycle callback for mlx5 common devices.
380  *
381  * @param event
382  *   Mempool life cycle event.
383  * @param mp
384  *   Associated mempool.
385  * @param arg
386  *   Pointer to a device shared context.
387  */
388 static void
389 mlx5_dev_mempool_event_cb(enum rte_mempool_event event, struct rte_mempool *mp,
390 			  void *arg)
391 {
392 	struct mlx5_common_device *cdev = arg;
393 	bool extmem = rte_pktmbuf_priv_flags(mp) &
394 		      RTE_PKTMBUF_POOL_F_PINNED_EXT_BUF;
395 
396 	switch (event) {
397 	case RTE_MEMPOOL_EVENT_READY:
398 		if (extmem)
399 			break;
400 		if (mlx5_dev_mempool_register(cdev, mp) < 0)
401 			DRV_LOG(ERR,
402 				"Failed to register new mempool %s for PD %p: %s",
403 				mp->name, cdev->pd, rte_strerror(rte_errno));
404 		break;
405 	case RTE_MEMPOOL_EVENT_DESTROY:
406 		mlx5_dev_mempool_unregister(cdev, mp);
407 		break;
408 	}
409 }
410 
411 int
412 mlx5_dev_mempool_subscribe(struct mlx5_common_device *cdev)
413 {
414 	int ret = 0;
415 
416 	if (!cdev->config.mr_mempool_reg_en)
417 		return 0;
418 	rte_rwlock_write_lock(&cdev->mr_scache.mprwlock);
419 	if (cdev->mr_scache.mp_cb_registered)
420 		goto exit;
421 	/* Callback for this device may be already registered. */
422 	ret = rte_mempool_event_callback_register(mlx5_dev_mempool_event_cb,
423 						  cdev);
424 	if (ret != 0 && rte_errno != EEXIST)
425 		goto exit;
426 	/* Register mempools only once for this device. */
427 	if (ret == 0)
428 		rte_mempool_walk(mlx5_dev_mempool_register_cb, cdev);
429 	ret = 0;
430 	cdev->mr_scache.mp_cb_registered = 1;
431 exit:
432 	rte_rwlock_write_unlock(&cdev->mr_scache.mprwlock);
433 	return ret;
434 }
435 
436 static void
437 mlx5_dev_mempool_unsubscribe(struct mlx5_common_device *cdev)
438 {
439 	int ret;
440 
441 	if (!cdev->mr_scache.mp_cb_registered ||
442 	    !cdev->config.mr_mempool_reg_en)
443 		return;
444 	/* Stop watching for mempool events and unregister all mempools. */
445 	ret = rte_mempool_event_callback_unregister(mlx5_dev_mempool_event_cb,
446 						    cdev);
447 	if (ret == 0)
448 		rte_mempool_walk(mlx5_dev_mempool_unregister_cb, cdev);
449 }
450 
451 /**
452  * Callback for memory event.
453  *
454  * @param event_type
455  *   Memory event type.
456  * @param addr
457  *   Address of memory.
458  * @param len
459  *   Size of memory.
460  */
461 static void
462 mlx5_mr_mem_event_cb(enum rte_mem_event event_type, const void *addr,
463 		     size_t len, void *arg __rte_unused)
464 {
465 	struct mlx5_common_device *cdev;
466 
467 	/* Must be called from the primary process. */
468 	MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
469 	switch (event_type) {
470 	case RTE_MEM_EVENT_FREE:
471 		pthread_mutex_lock(&devices_list_lock);
472 		/* Iterate all the existing mlx5 devices. */
473 		TAILQ_FOREACH(cdev, &devices_list, next)
474 			mlx5_free_mr_by_addr(&cdev->mr_scache,
475 					     mlx5_os_get_ctx_device_name
476 								    (cdev->ctx),
477 					     addr, len);
478 		pthread_mutex_unlock(&devices_list_lock);
479 		break;
480 	case RTE_MEM_EVENT_ALLOC:
481 	default:
482 		break;
483 	}
484 }
485 
486 /**
487  * Uninitialize all HW global of device context.
488  *
489  * @param cdev
490  *   Pointer to mlx5 device structure.
491  *
492  * @return
493  *   0 on success, a negative errno value otherwise and rte_errno is set.
494  */
495 static void
496 mlx5_dev_hw_global_release(struct mlx5_common_device *cdev)
497 {
498 	if (cdev->pd != NULL) {
499 		claim_zero(mlx5_os_dealloc_pd(cdev->pd));
500 		cdev->pd = NULL;
501 	}
502 	if (cdev->ctx != NULL) {
503 		claim_zero(mlx5_glue->close_device(cdev->ctx));
504 		cdev->ctx = NULL;
505 	}
506 }
507 
508 /**
509  * Initialize all HW global of device context.
510  *
511  * @param cdev
512  *   Pointer to mlx5 device structure.
513  * @param classes
514  *   Chosen classes come from user device arguments.
515  *
516  * @return
517  *   0 on success, a negative errno value otherwise and rte_errno is set.
518  */
519 static int
520 mlx5_dev_hw_global_prepare(struct mlx5_common_device *cdev, uint32_t classes)
521 {
522 	int ret;
523 
524 	/* Create context device */
525 	ret = mlx5_os_open_device(cdev, classes);
526 	if (ret < 0)
527 		return ret;
528 	/* Allocate Protection Domain object and extract its pdn. */
529 	ret = mlx5_os_pd_create(cdev);
530 	if (ret)
531 		goto error;
532 	/* All actions taken below are relevant only when DevX is supported */
533 	if (cdev->config.devx == 0)
534 		return 0;
535 	/* Query HCA attributes. */
536 	ret = mlx5_devx_cmd_query_hca_attr(cdev->ctx, &cdev->config.hca_attr);
537 	if (ret) {
538 		DRV_LOG(ERR, "Unable to read HCA capabilities.");
539 		rte_errno = ENOTSUP;
540 		goto error;
541 	}
542 	return 0;
543 error:
544 	mlx5_dev_hw_global_release(cdev);
545 	return ret;
546 }
547 
548 static void
549 mlx5_common_dev_release(struct mlx5_common_device *cdev)
550 {
551 	pthread_mutex_lock(&devices_list_lock);
552 	TAILQ_REMOVE(&devices_list, cdev, next);
553 	pthread_mutex_unlock(&devices_list_lock);
554 	if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
555 		if (TAILQ_EMPTY(&devices_list))
556 			rte_mem_event_callback_unregister("MLX5_MEM_EVENT_CB",
557 							  NULL);
558 		mlx5_dev_mempool_unsubscribe(cdev);
559 		mlx5_mr_release_cache(&cdev->mr_scache);
560 		mlx5_dev_hw_global_release(cdev);
561 	}
562 	rte_free(cdev);
563 }
564 
565 static struct mlx5_common_device *
566 mlx5_common_dev_create(struct rte_device *eal_dev, uint32_t classes)
567 {
568 	struct mlx5_common_device *cdev;
569 	int ret;
570 
571 	cdev = rte_zmalloc("mlx5_common_device", sizeof(*cdev), 0);
572 	if (!cdev) {
573 		DRV_LOG(ERR, "Device allocation failure.");
574 		rte_errno = ENOMEM;
575 		return NULL;
576 	}
577 	cdev->dev = eal_dev;
578 	if (rte_eal_process_type() != RTE_PROC_PRIMARY)
579 		goto exit;
580 	/* Parse device parameters. */
581 	ret = mlx5_common_config_get(eal_dev->devargs, &cdev->config);
582 	if (ret < 0) {
583 		DRV_LOG(ERR, "Failed to process device arguments: %s",
584 			strerror(rte_errno));
585 		rte_free(cdev);
586 		return NULL;
587 	}
588 	mlx5_malloc_mem_select(cdev->config.sys_mem_en);
589 	/* Initialize all HW global of device context. */
590 	ret = mlx5_dev_hw_global_prepare(cdev, classes);
591 	if (ret) {
592 		DRV_LOG(ERR, "Failed to initialize device context.");
593 		rte_free(cdev);
594 		return NULL;
595 	}
596 	/* Initialize global MR cache resources and update its functions. */
597 	ret = mlx5_mr_create_cache(&cdev->mr_scache, eal_dev->numa_node);
598 	if (ret) {
599 		DRV_LOG(ERR, "Failed to initialize global MR share cache.");
600 		mlx5_dev_hw_global_release(cdev);
601 		rte_free(cdev);
602 		return NULL;
603 	}
604 	/* Register callback function for global shared MR cache management. */
605 	if (TAILQ_EMPTY(&devices_list))
606 		rte_mem_event_callback_register("MLX5_MEM_EVENT_CB",
607 						mlx5_mr_mem_event_cb, NULL);
608 exit:
609 	pthread_mutex_lock(&devices_list_lock);
610 	TAILQ_INSERT_HEAD(&devices_list, cdev, next);
611 	pthread_mutex_unlock(&devices_list_lock);
612 	return cdev;
613 }
614 
615 static int
616 drivers_remove(struct mlx5_common_device *cdev, uint32_t enabled_classes)
617 {
618 	struct mlx5_class_driver *driver;
619 	int local_ret = -ENODEV;
620 	unsigned int i = 0;
621 	int ret = 0;
622 
623 	enabled_classes &= cdev->classes_loaded;
624 	while (enabled_classes) {
625 		driver = driver_get(RTE_BIT64(i));
626 		if (driver != NULL) {
627 			local_ret = driver->remove(cdev);
628 			if (local_ret == 0)
629 				cdev->classes_loaded &= ~RTE_BIT64(i);
630 			else if (ret == 0)
631 				ret = local_ret;
632 		}
633 		enabled_classes &= ~RTE_BIT64(i);
634 		i++;
635 	}
636 	if (local_ret != 0 && ret == 0)
637 		ret = local_ret;
638 	return ret;
639 }
640 
641 static int
642 drivers_probe(struct mlx5_common_device *cdev, uint32_t user_classes)
643 {
644 	struct mlx5_class_driver *driver;
645 	uint32_t enabled_classes = 0;
646 	bool already_loaded;
647 	int ret;
648 
649 	TAILQ_FOREACH(driver, &drivers_list, next) {
650 		if ((driver->drv_class & user_classes) == 0)
651 			continue;
652 		if (!mlx5_bus_match(driver, cdev->dev))
653 			continue;
654 		already_loaded = cdev->classes_loaded & driver->drv_class;
655 		if (already_loaded && driver->probe_again == 0) {
656 			DRV_LOG(ERR, "Device %s is already probed",
657 				cdev->dev->name);
658 			ret = -EEXIST;
659 			goto probe_err;
660 		}
661 		ret = driver->probe(cdev);
662 		if (ret < 0) {
663 			DRV_LOG(ERR, "Failed to load driver %s",
664 				driver->name);
665 			goto probe_err;
666 		}
667 		enabled_classes |= driver->drv_class;
668 	}
669 	cdev->classes_loaded |= enabled_classes;
670 	return 0;
671 probe_err:
672 	/* Only unload drivers which are enabled which were enabled
673 	 * in this probe instance.
674 	 */
675 	drivers_remove(cdev, enabled_classes);
676 	return ret;
677 }
678 
679 int
680 mlx5_common_dev_probe(struct rte_device *eal_dev)
681 {
682 	struct mlx5_common_device *cdev;
683 	uint32_t classes = 0;
684 	bool new_device = false;
685 	int ret;
686 
687 	DRV_LOG(INFO, "probe device \"%s\".", eal_dev->name);
688 	ret = parse_class_options(eal_dev->devargs);
689 	if (ret < 0) {
690 		DRV_LOG(ERR, "Unsupported mlx5 class type: %s",
691 			eal_dev->devargs->args);
692 		return ret;
693 	}
694 	classes = ret;
695 	if (classes == 0)
696 		/* Default to net class. */
697 		classes = MLX5_CLASS_ETH;
698 	cdev = to_mlx5_device(eal_dev);
699 	if (!cdev) {
700 		cdev = mlx5_common_dev_create(eal_dev, classes);
701 		if (!cdev)
702 			return -ENOMEM;
703 		new_device = true;
704 	}
705 	/*
706 	 * Validate combination here.
707 	 * For new device, the classes_loaded field is 0 and it check only
708 	 * the classes given as user device arguments.
709 	 */
710 	ret = is_valid_class_combination(classes | cdev->classes_loaded);
711 	if (ret != 0) {
712 		DRV_LOG(ERR, "Unsupported mlx5 classes combination.");
713 		goto class_err;
714 	}
715 	ret = drivers_probe(cdev, classes);
716 	if (ret)
717 		goto class_err;
718 	return 0;
719 class_err:
720 	if (new_device)
721 		mlx5_common_dev_release(cdev);
722 	return ret;
723 }
724 
725 int
726 mlx5_common_dev_remove(struct rte_device *eal_dev)
727 {
728 	struct mlx5_common_device *cdev;
729 	int ret;
730 
731 	cdev = to_mlx5_device(eal_dev);
732 	if (!cdev)
733 		return -ENODEV;
734 	/* Matching device found, cleanup and unload drivers. */
735 	ret = drivers_remove(cdev, cdev->classes_loaded);
736 	if (ret == 0)
737 		mlx5_common_dev_release(cdev);
738 	return ret;
739 }
740 
741 /**
742  * Callback to DMA map external memory to a device.
743  *
744  * @param rte_dev
745  *   Pointer to the generic device.
746  * @param addr
747  *   Starting virtual address of memory to be mapped.
748  * @param iova
749  *   Starting IOVA address of memory to be mapped.
750  * @param len
751  *   Length of memory segment being mapped.
752  *
753  * @return
754  *   0 on success, negative value on error.
755  */
756 int
757 mlx5_common_dev_dma_map(struct rte_device *rte_dev, void *addr,
758 			uint64_t iova __rte_unused, size_t len)
759 {
760 	struct mlx5_common_device *dev;
761 	struct mlx5_mr *mr;
762 
763 	dev = to_mlx5_device(rte_dev);
764 	if (!dev) {
765 		DRV_LOG(WARNING,
766 			"Unable to find matching mlx5 device to device %s",
767 			rte_dev->name);
768 		rte_errno = ENODEV;
769 		return -1;
770 	}
771 	mr = mlx5_create_mr_ext(dev->pd, (uintptr_t)addr, len,
772 				SOCKET_ID_ANY, dev->mr_scache.reg_mr_cb);
773 	if (!mr) {
774 		DRV_LOG(WARNING, "Device %s unable to DMA map", rte_dev->name);
775 		rte_errno = EINVAL;
776 		return -1;
777 	}
778 	rte_rwlock_write_lock(&dev->mr_scache.rwlock);
779 	LIST_INSERT_HEAD(&dev->mr_scache.mr_list, mr, mr);
780 	/* Insert to the global cache table. */
781 	mlx5_mr_insert_cache(&dev->mr_scache, mr);
782 	rte_rwlock_write_unlock(&dev->mr_scache.rwlock);
783 	return 0;
784 }
785 
786 /**
787  * Callback to DMA unmap external memory to a device.
788  *
789  * @param rte_dev
790  *   Pointer to the generic device.
791  * @param addr
792  *   Starting virtual address of memory to be unmapped.
793  * @param iova
794  *   Starting IOVA address of memory to be unmapped.
795  * @param len
796  *   Length of memory segment being unmapped.
797  *
798  * @return
799  *   0 on success, negative value on error.
800  */
801 int
802 mlx5_common_dev_dma_unmap(struct rte_device *rte_dev, void *addr,
803 			  uint64_t iova __rte_unused, size_t len __rte_unused)
804 {
805 	struct mlx5_common_device *dev;
806 	struct mr_cache_entry entry;
807 	struct mlx5_mr *mr;
808 
809 	dev = to_mlx5_device(rte_dev);
810 	if (!dev) {
811 		DRV_LOG(WARNING,
812 			"Unable to find matching mlx5 device to device %s.",
813 			rte_dev->name);
814 		rte_errno = ENODEV;
815 		return -1;
816 	}
817 	rte_rwlock_read_lock(&dev->mr_scache.rwlock);
818 	mr = mlx5_mr_lookup_list(&dev->mr_scache, &entry, (uintptr_t)addr);
819 	if (!mr) {
820 		rte_rwlock_read_unlock(&dev->mr_scache.rwlock);
821 		DRV_LOG(WARNING,
822 			"Address 0x%" PRIxPTR " wasn't registered to device %s",
823 			(uintptr_t)addr, rte_dev->name);
824 		rte_errno = EINVAL;
825 		return -1;
826 	}
827 	LIST_REMOVE(mr, mr);
828 	DRV_LOG(DEBUG, "MR(%p) is removed from list.", (void *)mr);
829 	mlx5_mr_free(mr, dev->mr_scache.dereg_mr_cb);
830 	mlx5_mr_rebuild_cache(&dev->mr_scache);
831 	/*
832 	 * No explicit wmb is needed after updating dev_gen due to
833 	 * store-release ordering in unlock that provides the
834 	 * implicit barrier at the software visible level.
835 	 */
836 	++dev->mr_scache.dev_gen;
837 	DRV_LOG(DEBUG, "Broadcasting local cache flush, gen=%d.",
838 		dev->mr_scache.dev_gen);
839 	rte_rwlock_read_unlock(&dev->mr_scache.rwlock);
840 	return 0;
841 }
842 
843 void
844 mlx5_class_driver_register(struct mlx5_class_driver *driver)
845 {
846 	mlx5_common_driver_on_register_pci(driver);
847 	TAILQ_INSERT_TAIL(&drivers_list, driver, next);
848 }
849 
850 static void mlx5_common_driver_init(void)
851 {
852 	mlx5_common_pci_init();
853 #ifdef RTE_EXEC_ENV_LINUX
854 	mlx5_common_auxiliary_init();
855 #endif
856 }
857 
858 static bool mlx5_common_initialized;
859 
860 /**
861  * One time innitialization routine for run-time dependency on glue library
862  * for multiple PMDs. Each mlx5 PMD that depends on mlx5_common module,
863  * must invoke in its constructor.
864  */
865 void
866 mlx5_common_init(void)
867 {
868 	if (mlx5_common_initialized)
869 		return;
870 
871 	pthread_mutex_init(&devices_list_lock, NULL);
872 	mlx5_glue_constructor();
873 	mlx5_common_driver_init();
874 	mlx5_common_initialized = true;
875 }
876 
877 /**
878  * This function is responsible of initializing the variable
879  *  haswell_broadwell_cpu by checking if the cpu is intel
880  *  and reading the data returned from mlx5_cpu_id().
881  *  since haswell and broadwell cpus don't have improved performance
882  *  when using relaxed ordering we want to check the cpu type before
883  *  before deciding whether to enable RO or not.
884  *  if the cpu is haswell or broadwell the variable will be set to 1
885  *  otherwise it will be 0.
886  */
887 RTE_INIT_PRIO(mlx5_is_haswell_broadwell_cpu, LOG)
888 {
889 #ifdef RTE_ARCH_X86_64
890 	unsigned int broadwell_models[4] = {0x3d, 0x47, 0x4F, 0x56};
891 	unsigned int haswell_models[4] = {0x3c, 0x3f, 0x45, 0x46};
892 	unsigned int i, model, family, brand_id, vendor;
893 	unsigned int signature_intel_ebx = 0x756e6547;
894 	unsigned int extended_model;
895 	unsigned int eax = 0;
896 	unsigned int ebx = 0;
897 	unsigned int ecx = 0;
898 	unsigned int edx = 0;
899 	int max_level;
900 
901 	mlx5_cpu_id(0, &eax, &ebx, &ecx, &edx);
902 	vendor = ebx;
903 	max_level = eax;
904 	if (max_level < 1) {
905 		haswell_broadwell_cpu = 0;
906 		return;
907 	}
908 	mlx5_cpu_id(1, &eax, &ebx, &ecx, &edx);
909 	model = (eax >> 4) & 0x0f;
910 	family = (eax >> 8) & 0x0f;
911 	brand_id = ebx & 0xff;
912 	extended_model = (eax >> 12) & 0xf0;
913 	/* Check if the processor is Haswell or Broadwell */
914 	if (vendor == signature_intel_ebx) {
915 		if (family == 0x06)
916 			model += extended_model;
917 		if (brand_id == 0 && family == 0x6) {
918 			for (i = 0; i < RTE_DIM(broadwell_models); i++)
919 				if (model == broadwell_models[i]) {
920 					haswell_broadwell_cpu = 1;
921 					return;
922 				}
923 			for (i = 0; i < RTE_DIM(haswell_models); i++)
924 				if (model == haswell_models[i]) {
925 					haswell_broadwell_cpu = 1;
926 					return;
927 				}
928 		}
929 	}
930 #endif
931 	haswell_broadwell_cpu = 0;
932 }
933 
934 /**
935  * Allocate the User Access Region with DevX on specified device.
936  * This routine handles the following UAR allocation issues:
937  *
938  *  - Try to allocate the UAR with the most appropriate memory mapping
939  *    type from the ones supported by the host.
940  *
941  *  - Try to allocate the UAR with non-NULL base address OFED 5.0.x and
942  *    Upstream rdma_core before v29 returned the NULL as UAR base address
943  *    if UAR was not the first object in the UAR page.
944  *    It caused the PMD failure and we should try to get another UAR till
945  *    we get the first one with non-NULL base address returned.
946  *
947  * @param [in] cdev
948  *   Pointer to mlx5 device structure to perform allocation on its context.
949  *
950  * @return
951  *   UAR object pointer on success, NULL otherwise and rte_errno is set.
952  */
953 static void *
954 mlx5_devx_alloc_uar(struct mlx5_common_device *cdev)
955 {
956 	void *uar;
957 	uint32_t retry, uar_mapping;
958 	void *base_addr;
959 
960 	for (retry = 0; retry < MLX5_ALLOC_UAR_RETRY; ++retry) {
961 #ifdef MLX5DV_UAR_ALLOC_TYPE_NC
962 		/* Control the mapping type according to the settings. */
963 		uar_mapping = (cdev->config.dbnc == MLX5_TXDB_NCACHED) ?
964 			    MLX5DV_UAR_ALLOC_TYPE_NC : MLX5DV_UAR_ALLOC_TYPE_BF;
965 #else
966 		/*
967 		 * It seems we have no way to control the memory mapping type
968 		 * for the UAR, the default "Write-Combining" type is supposed.
969 		 */
970 		uar_mapping = 0;
971 #endif
972 		uar = mlx5_glue->devx_alloc_uar(cdev->ctx, uar_mapping);
973 #ifdef MLX5DV_UAR_ALLOC_TYPE_NC
974 		if (!uar && uar_mapping == MLX5DV_UAR_ALLOC_TYPE_BF) {
975 			/*
976 			 * In some environments like virtual machine the
977 			 * Write Combining mapped might be not supported and
978 			 * UAR allocation fails. We tried "Non-Cached" mapping
979 			 * for the case.
980 			 */
981 			DRV_LOG(DEBUG, "Failed to allocate DevX UAR (BF)");
982 			uar_mapping = MLX5DV_UAR_ALLOC_TYPE_NC;
983 			uar = mlx5_glue->devx_alloc_uar(cdev->ctx, uar_mapping);
984 		} else if (!uar && uar_mapping == MLX5DV_UAR_ALLOC_TYPE_NC) {
985 			/*
986 			 * If Verbs/kernel does not support "Non-Cached"
987 			 * try the "Write-Combining".
988 			 */
989 			DRV_LOG(DEBUG, "Failed to allocate DevX UAR (NC)");
990 			uar_mapping = MLX5DV_UAR_ALLOC_TYPE_BF;
991 			uar = mlx5_glue->devx_alloc_uar(cdev->ctx, uar_mapping);
992 		}
993 #endif
994 		if (!uar) {
995 			DRV_LOG(ERR, "Failed to allocate DevX UAR (BF/NC)");
996 			rte_errno = ENOMEM;
997 			goto exit;
998 		}
999 		base_addr = mlx5_os_get_devx_uar_base_addr(uar);
1000 		if (base_addr)
1001 			break;
1002 		/*
1003 		 * The UARs are allocated by rdma_core within the
1004 		 * IB device context, on context closure all UARs
1005 		 * will be freed, should be no memory/object leakage.
1006 		 */
1007 		DRV_LOG(DEBUG, "Retrying to allocate DevX UAR");
1008 		uar = NULL;
1009 	}
1010 	/* Check whether we finally succeeded with valid UAR allocation. */
1011 	if (!uar) {
1012 		DRV_LOG(ERR, "Failed to allocate DevX UAR (NULL base)");
1013 		rte_errno = ENOMEM;
1014 	}
1015 	/*
1016 	 * Return void * instead of struct mlx5dv_devx_uar *
1017 	 * is for compatibility with older rdma-core library headers.
1018 	 */
1019 exit:
1020 	return uar;
1021 }
1022 
1023 void
1024 mlx5_devx_uar_release(struct mlx5_uar *uar)
1025 {
1026 	if (uar->obj != NULL)
1027 		mlx5_glue->devx_free_uar(uar->obj);
1028 	memset(uar, 0, sizeof(*uar));
1029 }
1030 
1031 int
1032 mlx5_devx_uar_prepare(struct mlx5_common_device *cdev, struct mlx5_uar *uar)
1033 {
1034 	off_t uar_mmap_offset;
1035 	const size_t page_size = rte_mem_page_size();
1036 	void *base_addr;
1037 	void *uar_obj;
1038 
1039 	if (page_size == (size_t)-1) {
1040 		DRV_LOG(ERR, "Failed to get mem page size");
1041 		rte_errno = ENOMEM;
1042 		return -1;
1043 	}
1044 	uar_obj = mlx5_devx_alloc_uar(cdev);
1045 	if (uar_obj == NULL || mlx5_os_get_devx_uar_reg_addr(uar_obj) == NULL) {
1046 		rte_errno = errno;
1047 		DRV_LOG(ERR, "Failed to allocate UAR.");
1048 		return -1;
1049 	}
1050 	uar->obj = uar_obj;
1051 	uar_mmap_offset = mlx5_os_get_devx_uar_mmap_offset(uar_obj);
1052 	base_addr = mlx5_os_get_devx_uar_base_addr(uar_obj);
1053 	uar->dbnc = mlx5_db_map_type_get(uar_mmap_offset, page_size);
1054 	uar->bf_db.db = mlx5_os_get_devx_uar_reg_addr(uar_obj);
1055 	uar->cq_db.db = RTE_PTR_ADD(base_addr, MLX5_CQ_DOORBELL);
1056 #ifndef RTE_ARCH_64
1057 	rte_spinlock_init(&uar->bf_sl);
1058 	rte_spinlock_init(&uar->cq_sl);
1059 	uar->bf_db.sl_p = &uar->bf_sl;
1060 	uar->cq_db.sl_p = &uar->cq_sl;
1061 #endif /* RTE_ARCH_64 */
1062 	return 0;
1063 }
1064 
1065 RTE_PMD_EXPORT_NAME(mlx5_common_driver, __COUNTER__);
1066