1 /*
2  * Copyright (c) 2021 Synopsys.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifdef CONFIG_MULTITHREADING
8 
9 #include <stdio.h>
10 #include <zephyr/init.h>
11 #include <zephyr/kernel.h>
12 #include <zephyr/sys/__assert.h>
13 #include <zephyr/sys/mutex.h>
14 #include <zephyr/logging/log.h>
15 
16 #ifndef CONFIG_USERSPACE
17 #define ARCMWDT_DYN_LOCK_SZ	(sizeof(struct k_mutex))
18 /* The library wants 2 locks per available FILE entry, and then some more */
19 #define ARCMWDT_MAX_DYN_LOCKS	(FOPEN_MAX * 2 + 5)
20 
21 K_MEM_SLAB_DEFINE(z_arcmwdt_lock_slab, ARCMWDT_DYN_LOCK_SZ, ARCMWDT_MAX_DYN_LOCKS, sizeof(void *));
22 #endif /* !CONFIG_USERSPACE */
23 
24 LOG_MODULE_DECLARE(os, CONFIG_KERNEL_LOG_LEVEL);
25 
26 typedef void *_lock_t;
27 
_mwmutex_create(_lock_t * mutex_ptr)28 void _mwmutex_create(_lock_t *mutex_ptr)
29 {
30 	bool alloc_fail;
31 #ifdef CONFIG_USERSPACE
32 	*mutex_ptr = k_object_alloc(K_OBJ_MUTEX);
33 	alloc_fail = (*mutex_ptr == NULL);
34 #else
35 	alloc_fail = !!k_mem_slab_alloc(&z_arcmwdt_lock_slab, mutex_ptr, K_NO_WAIT);
36 #endif /* CONFIG_USERSPACE */
37 
38 	if (alloc_fail) {
39 		LOG_ERR("MWDT lock allocation failed");
40 		k_panic();
41 	}
42 
43 	k_mutex_init((struct k_mutex *)*mutex_ptr);
44 }
45 
_mwmutex_delete(_lock_t * mutex_ptr)46 void _mwmutex_delete(_lock_t *mutex_ptr)
47 {
48 	__ASSERT_NO_MSG(mutex_ptr != NULL);
49 #ifdef CONFIG_USERSPACE
50 	k_object_release(mutex_ptr);
51 #else
52 	k_mem_slab_free(&z_arcmwdt_lock_slab, *mutex_ptr);
53 #endif /* CONFIG_USERSPACE */
54 }
55 
_mwmutex_lock(_lock_t mutex)56 void _mwmutex_lock(_lock_t mutex)
57 {
58 	__ASSERT_NO_MSG(mutex != NULL);
59 	k_mutex_lock((struct k_mutex *)mutex, K_FOREVER);
60 }
61 
_mwmutex_unlock(_lock_t mutex)62 void _mwmutex_unlock(_lock_t mutex)
63 {
64 	__ASSERT_NO_MSG(mutex != NULL);
65 	k_mutex_unlock((struct k_mutex *)mutex);
66 }
67 #endif /* CONFIG_MULTITHREADING */
68