1/*
2 * Copyright 2017, Data61
3 * Commonwealth Scientific and Industrial Research Organisation (CSIRO)
4 * ABN 41 687 119 230.
5 *
6 * This software may be distributed and modified according to the terms of
7 * the BSD 2-Clause license. Note that NO WARRANTY is provided.
8 * See "LICENSE_BSD2.txt" for details.
9 *
10 * @TAG(DATA61_BSD)
11 */
12
13#pragma once
14
15#include <sel4/sel4.h>
16#include <vka/vka.h>
17#include <sync/bin_sem.h>
18
19typedef sync_bin_sem_t sync_mutex_t;
20
21/* Initialise an unmanaged mutex with a notification object
22 * @param sem           A mutex object to be initialised.
23 * @param notification  A notification object to use for the lock.
24 * @return              0 on success, an error code on failure. */
25static inline int sync_mutex_init(sync_mutex_t *mutex, seL4_CPtr notification) {
26    return sync_bin_sem_init(mutex, notification, 1);
27}
28
29/* Acquire a mutex
30 * @param mutex         An initialised mutex to acquire.
31 * @return              0 on success, an error code on failure. */
32static inline int sync_mutex_lock(sync_mutex_t *mutex) {
33    return sync_bin_sem_wait(mutex);
34}
35
36/* Release a mutex
37 * @param mutex         An initialised mutex to release.
38 * @return              0 on success, an error code on failure. */
39static inline int sync_mutex_unlock(sync_mutex_t *mutex) {
40    return sync_bin_sem_post(mutex);
41}
42
43/* Allocate and initialise a managed mutex
44 * @param vka           A VKA instance used to allocate a notification object.
45 * @param mutex         A mutex object to initialise.
46 * @return              0 on success, an error code on failure. */
47static inline int sync_mutex_new(vka_t *vka, sync_mutex_t *mutex) {
48    return sync_bin_sem_new(vka, mutex, 1);
49}
50
51/* Deallocate a managed mutex (do not use with sync_mutex_init)
52 * @param vka           A VKA instance used to deallocate the notification object.
53 * @param mutex         A mutex object initialised by sync_mutex_new.
54 * @return              0 on success, an error code on failure. */
55static inline int sync_mutex_destroy(vka_t *vka, sync_mutex_t *mutex) {
56    return sync_bin_sem_destroy(vka, mutex);
57}
58
59