blob: ae7e2339408403b68866c2208225bfd3673cb503 [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * Copyright (c) 2008-2014 Travis Geiselbrecht
3 * Copyright (c) 2012 Shantanu Gupta
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files
7 * (the "Software"), to deal in the Software without restriction,
8 * including without limitation the rights to use, copy, modify, merge,
9 * publish, distribute, sublicense, and/or sell copies of the Software,
10 * and to permit persons to whom the Software is furnished to do so,
11 * subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be
14 * included in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24#ifndef __KERNEL_MUTEX_H
25#define __KERNEL_MUTEX_H
26
27#include <compiler.h>
28#include <debug.h>
29#include <stdint.h>
30#include <kernel/thread.h>
31
32__BEGIN_CDECLS;
33
34#define MUTEX_MAGIC 'mutx'
35
36typedef struct mutex {
37 uint32_t magic;
38 thread_t *holder;
39 int count;
40 wait_queue_t wait;
41} mutex_t;
42
43#define MUTEX_INITIAL_VALUE(m) \
44{ \
45 .magic = MUTEX_MAGIC, \
46 .holder = NULL, \
47 .count = 0, \
48 .wait = WAIT_QUEUE_INITIAL_VALUE((m).wait), \
49}
50
51/* Rules for Mutexes:
52 * - Mutexes are only safe to use from thread context.
53 * - Mutexes are non-recursive.
54*/
55
56void mutex_init(mutex_t *);
57void mutex_destroy(mutex_t *);
58status_t mutex_acquire_timeout(mutex_t *, lk_time_t); /* try to acquire the mutex with a timeout value */
59status_t mutex_release(mutex_t *);
60
61static inline status_t mutex_acquire(mutex_t *m) {
62 return mutex_acquire_timeout(m, INFINITE_TIME);
63}
64
65/* does the current thread hold the mutex? */
66static bool is_mutex_held(mutex_t *m) {
67 return m->holder == get_current_thread();
68}
69
70__END_CDECLS;
71#endif
72