1 /*
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 (0x6D757478) // 'mutx'
35
36 typedef 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
56 void mutex_init(mutex_t *);
57 void mutex_destroy(mutex_t *);
58 status_t mutex_acquire_timeout(mutex_t *, lk_time_t); /* try to acquire the mutex with a timeout value */
59 status_t mutex_release(mutex_t *);
60
mutex_acquire(mutex_t * m)61 static inline status_t mutex_acquire(mutex_t *m)
62 {
63 return mutex_acquire_timeout(m, INFINITE_TIME);
64 }
65
66 /* does the current thread hold the mutex? */
is_mutex_held(mutex_t * m)67 static bool is_mutex_held(mutex_t *m)
68 {
69 return m->holder == get_current_thread();
70 }
71
72 bool extern_is_mutex_held(mutex_t *m);
73
74 __END_CDECLS;
75 #endif
76
77