1 /*
2  * Copyright (c) 2016 Wind River Systems, Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file @brief mutex kernel services
9  *
10  * This module contains routines for handling mutex locking and unlocking.
11  *
12  * Mutexes implement a priority inheritance algorithm that boosts the priority
13  * level of the owning thread to match the priority level of the highest
14  * priority thread waiting on the mutex.
15  *
16  * Each mutex that contributes to priority inheritance must be released in the
17  * reverse order in which it was acquired.  Furthermore each subsequent mutex
18  * that contributes to raising the owning thread's priority level must be
19  * acquired at a point after the most recent "bumping" of the priority level.
20  *
21  * For example, if thread A has two mutexes contributing to the raising of its
22  * priority level, the second mutex M2 must be acquired by thread A after
23  * thread A's priority level was bumped due to owning the first mutex M1.
24  * When releasing the mutex, thread A must release M2 before it releases M1.
25  * Failure to follow this nested model may result in threads running at
26  * unexpected priority levels (too high, or too low).
27  */
28 
29 #include <kernel.h>
30 #include <kernel_structs.h>
31 #include <toolchain.h>
32 #include <ksched.h>
33 #include <wait_q.h>
34 #include <errno.h>
35 #include <init.h>
36 #include <syscall_handler.h>
37 #include <tracing/tracing.h>
38 #include <sys/check.h>
39 #include <logging/log.h>
40 LOG_MODULE_DECLARE(os, CONFIG_KERNEL_LOG_LEVEL);
41 
42 /* We use a global spinlock here because some of the synchronization
43  * is protecting things like owner thread priorities which aren't
44  * "part of" a single k_mutex.  Should move those bits of the API
45  * under the scheduler lock so we can break this up.
46  */
47 static struct k_spinlock lock;
48 
z_impl_k_mutex_init(struct k_mutex * mutex)49 int z_impl_k_mutex_init(struct k_mutex *mutex)
50 {
51 	mutex->owner = NULL;
52 	mutex->lock_count = 0U;
53 
54 	z_waitq_init(&mutex->wait_q);
55 
56 	z_object_init(mutex);
57 
58 	SYS_PORT_TRACING_OBJ_INIT(k_mutex, mutex, 0);
59 
60 	return 0;
61 }
62 
63 #ifdef CONFIG_USERSPACE
z_vrfy_k_mutex_init(struct k_mutex * mutex)64 static inline int z_vrfy_k_mutex_init(struct k_mutex *mutex)
65 {
66 	Z_OOPS(Z_SYSCALL_OBJ_INIT(mutex, K_OBJ_MUTEX));
67 	return z_impl_k_mutex_init(mutex);
68 }
69 #include <syscalls/k_mutex_init_mrsh.c>
70 #endif
71 
new_prio_for_inheritance(int32_t target,int32_t limit)72 static int32_t new_prio_for_inheritance(int32_t target, int32_t limit)
73 {
74 	int new_prio = z_is_prio_higher(target, limit) ? target : limit;
75 
76 	new_prio = z_get_new_prio_with_ceiling(new_prio);
77 
78 	return new_prio;
79 }
80 
adjust_owner_prio(struct k_mutex * mutex,int32_t new_prio)81 static bool adjust_owner_prio(struct k_mutex *mutex, int32_t new_prio)
82 {
83 	if (mutex->owner->base.prio != new_prio) {
84 
85 		LOG_DBG("%p (ready (y/n): %c) prio changed to %d (was %d)",
86 			mutex->owner, z_is_thread_ready(mutex->owner) ?
87 			'y' : 'n',
88 			new_prio, mutex->owner->base.prio);
89 
90 		return z_set_prio(mutex->owner, new_prio);
91 	}
92 	return false;
93 }
94 
z_impl_k_mutex_lock(struct k_mutex * mutex,k_timeout_t timeout)95 int z_impl_k_mutex_lock(struct k_mutex *mutex, k_timeout_t timeout)
96 {
97 	int new_prio;
98 	k_spinlock_key_t key;
99 	bool resched = false;
100 
101 	__ASSERT(!arch_is_in_isr(), "mutexes cannot be used inside ISRs");
102 
103 	SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_mutex, lock, mutex, timeout);
104 
105 	key = k_spin_lock(&lock);
106 
107 	if (likely((mutex->lock_count == 0U) || (mutex->owner == _current))) {
108 
109 		mutex->owner_orig_prio = (mutex->lock_count == 0U) ?
110 					_current->base.prio :
111 					mutex->owner_orig_prio;
112 
113 		mutex->lock_count++;
114 		mutex->owner = _current;
115 
116 		LOG_DBG("%p took mutex %p, count: %d, orig prio: %d",
117 			_current, mutex, mutex->lock_count,
118 			mutex->owner_orig_prio);
119 
120 		k_spin_unlock(&lock, key);
121 
122 		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, 0);
123 
124 		return 0;
125 	}
126 
127 	if (unlikely(K_TIMEOUT_EQ(timeout, K_NO_WAIT))) {
128 		k_spin_unlock(&lock, key);
129 
130 		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, -EBUSY);
131 
132 		return -EBUSY;
133 	}
134 
135 	SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_mutex, lock, mutex, timeout);
136 
137 	new_prio = new_prio_for_inheritance(_current->base.prio,
138 					    mutex->owner->base.prio);
139 
140 	LOG_DBG("adjusting prio up on mutex %p", mutex);
141 
142 	if (z_is_prio_higher(new_prio, mutex->owner->base.prio)) {
143 		resched = adjust_owner_prio(mutex, new_prio);
144 	}
145 
146 	int got_mutex = z_pend_curr(&lock, key, &mutex->wait_q, timeout);
147 
148 	LOG_DBG("on mutex %p got_mutex value: %d", mutex, got_mutex);
149 
150 	LOG_DBG("%p got mutex %p (y/n): %c", _current, mutex,
151 		got_mutex ? 'y' : 'n');
152 
153 	if (got_mutex == 0) {
154 		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, 0);
155 		return 0;
156 	}
157 
158 	/* timed out */
159 
160 	LOG_DBG("%p timeout on mutex %p", _current, mutex);
161 
162 	key = k_spin_lock(&lock);
163 
164 	/*
165 	 * Check if mutex was unlocked after this thread was unpended.
166 	 * If so, skip adjusting owner's priority down.
167 	 */
168 	if (likely(mutex->owner != NULL)) {
169 		struct k_thread *waiter = z_waitq_head(&mutex->wait_q);
170 
171 		new_prio = (waiter != NULL) ?
172 			new_prio_for_inheritance(waiter->base.prio, mutex->owner_orig_prio) :
173 			mutex->owner_orig_prio;
174 
175 		LOG_DBG("adjusting prio down on mutex %p", mutex);
176 
177 		resched = adjust_owner_prio(mutex, new_prio) || resched;
178 	}
179 
180 	if (resched) {
181 		z_reschedule(&lock, key);
182 	} else {
183 		k_spin_unlock(&lock, key);
184 	}
185 
186 	SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, -EAGAIN);
187 
188 	return -EAGAIN;
189 }
190 
191 #ifdef CONFIG_USERSPACE
z_vrfy_k_mutex_lock(struct k_mutex * mutex,k_timeout_t timeout)192 static inline int z_vrfy_k_mutex_lock(struct k_mutex *mutex,
193 				      k_timeout_t timeout)
194 {
195 	Z_OOPS(Z_SYSCALL_OBJ(mutex, K_OBJ_MUTEX));
196 	return z_impl_k_mutex_lock(mutex, timeout);
197 }
198 #include <syscalls/k_mutex_lock_mrsh.c>
199 #endif
200 
z_impl_k_mutex_unlock(struct k_mutex * mutex)201 int z_impl_k_mutex_unlock(struct k_mutex *mutex)
202 {
203 	struct k_thread *new_owner;
204 
205 	__ASSERT(!arch_is_in_isr(), "mutexes cannot be used inside ISRs");
206 
207 	SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_mutex, unlock, mutex);
208 
209 	CHECKIF(mutex->owner == NULL) {
210 		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, unlock, mutex, -EINVAL);
211 
212 		return -EINVAL;
213 	}
214 	/*
215 	 * The current thread does not own the mutex.
216 	 */
217 	CHECKIF(mutex->owner != _current) {
218 		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, unlock, mutex, -EPERM);
219 
220 		return -EPERM;
221 	}
222 
223 	/*
224 	 * Attempt to unlock a mutex which is unlocked. mutex->lock_count
225 	 * cannot be zero if the current thread is equal to mutex->owner,
226 	 * therefore no underflow check is required. Use assert to catch
227 	 * undefined behavior.
228 	 */
229 	__ASSERT_NO_MSG(mutex->lock_count > 0U);
230 
231 	z_sched_lock();
232 
233 	LOG_DBG("mutex %p lock_count: %d", mutex, mutex->lock_count);
234 
235 	/*
236 	 * If we are the owner and count is greater than 1, then decrement
237 	 * the count and return and keep current thread as the owner.
238 	 */
239 	if (mutex->lock_count > 1U) {
240 		mutex->lock_count--;
241 		goto k_mutex_unlock_return;
242 	}
243 
244 	k_spinlock_key_t key = k_spin_lock(&lock);
245 
246 	adjust_owner_prio(mutex, mutex->owner_orig_prio);
247 
248 	/* Get the new owner, if any */
249 	new_owner = z_unpend_first_thread(&mutex->wait_q);
250 
251 	mutex->owner = new_owner;
252 
253 	LOG_DBG("new owner of mutex %p: %p (prio: %d)",
254 		mutex, new_owner, new_owner ? new_owner->base.prio : -1000);
255 
256 	if (new_owner != NULL) {
257 		/*
258 		 * new owner is already of higher or equal prio than first
259 		 * waiter since the wait queue is priority-based: no need to
260 		 * ajust its priority
261 		 */
262 		mutex->owner_orig_prio = new_owner->base.prio;
263 		arch_thread_return_value_set(new_owner, 0);
264 		z_ready_thread(new_owner);
265 		z_reschedule(&lock, key);
266 	} else {
267 		mutex->lock_count = 0U;
268 		k_spin_unlock(&lock, key);
269 	}
270 
271 
272 k_mutex_unlock_return:
273 	SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, unlock, mutex, 0);
274 
275 	k_sched_unlock();
276 
277 	return 0;
278 }
279 
280 #ifdef CONFIG_USERSPACE
z_vrfy_k_mutex_unlock(struct k_mutex * mutex)281 static inline int z_vrfy_k_mutex_unlock(struct k_mutex *mutex)
282 {
283 	Z_OOPS(Z_SYSCALL_OBJ(mutex, K_OBJ_MUTEX));
284 	return z_impl_k_mutex_unlock(mutex);
285 }
286 #include <syscalls/k_mutex_unlock_mrsh.c>
287 #endif
288