1 /*
2  * Copyright (C) 2015-2017 Alibaba Group Holding Limited
3  */
4 
5 #ifndef K_MUTEX_H
6 #define K_MUTEX_H
7 
8 #ifdef __cplusplus
9 extern "C" {
10 #endif
11 
12 /** @addtogroup aos_rhino mutex
13  *  Mutex can be used for mutual exclusion between tasks.
14  *
15  *  @{
16  */
17 
18 /**
19  * mutex object
20  */
21 typedef struct mutex_s {
22     /**<
23      *  Manage blocked tasks
24      *  List head is this mutex, list node is task, which are blocked in this mutex
25      */
26     blk_obj_t       blk_obj;
27     ktask_t        *mutex_task; /**< Pointer to the owner task */
28     /**<
29      *  Manage mutexs owned by the task
30      *  List head is task, list node is mutex, which are owned by the task
31      */
32     struct mutex_s *mutex_list;
33     mutex_nested_t  owner_nested;
34 #if (RHINO_CONFIG_KOBJ_LIST > 0)
35     klist_t         mutex_item; /**< kobj list for statistics */
36 #endif
37     uint8_t         mm_alloc_flag;  /**< buffer from internal malloc or caller input */
38 } kmutex_t;
39 
40 /**
41  * Create a mutex.
42  *
43  * @param[in] mutex     pointer to the mutex (the space is provided outside, by user)
44  * @param[in] name      name of the mutex
45  *
46  * @return the operation status, RHINO_SUCCESS is OK, others is error
47  */
48 kstat_t krhino_mutex_create(kmutex_t *mutex, const name_t *name);
49 
50 /**
51  * Delete a mutex.
52  *
53  * @param[in] mutex     pointer to the mutex
54  *
55  * @return the operation status, RHINO_SUCCESS is OK, others is error
56  */
57 kstat_t krhino_mutex_del(kmutex_t *mutex);
58 
59 #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0)
60 /**
61  * Malloc and create a mutex.
62  *
63  * @param[out] mutex    pointer to the mutex (the space is provided inside, from heap)
64  * @param[in]  name     name of the mutex
65  *
66  * @return  the operation status, RHINO_SUCCESS is OK, others is error
67  */
68 kstat_t krhino_mutex_dyn_create(kmutex_t **mutex, const name_t *name);
69 
70 /**
71  * Delete and free a mutex.
72  *
73  * @param[in] mutex     pointer to the mutex
74  *
75  * @return the operation status, RHINO_SUCCESS is OK, others is error
76  */
77 kstat_t krhino_mutex_dyn_del(kmutex_t *mutex);
78 #endif
79 
80 /**
81  * Lock mutex, task may be blocked.
82  *
83  * @param[in]  mutex    pointer to the mutex
84  * @param[in]  ticks    ticks to be wait for before lock
85  *
86  * @return  the operation status, RHINO_SUCCESS is OK, others is error
87  */
88 kstat_t krhino_mutex_lock(kmutex_t *mutex, tick_t ticks);
89 
90 /**
91  * Unlock a mutex.
92  *
93  * @param[in]  mutex    pointer to the mutex
94  *
95  * @return  the operation status, RHINO_SUCCESS is OK, others is error
96  */
97 kstat_t krhino_mutex_unlock(kmutex_t *mutex);
98 
99 /** @} */
100 
101 #ifdef __cplusplus
102 }
103 #endif
104 
105 #endif /* K_MUTEX_H */
106 
107