1 /* semaphore.c
2  *
3  * Copyright 2012 Christopher Anderson <chris@nullcode.org>
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <kernel/semaphore.h>
18 
19 #include <kernel/thread.h>
20 #include <lk/debug.h>
21 #include <lk/err.h>
22 
sem_init(semaphore_t * sem,int initial_count)23 void sem_init(semaphore_t *sem, int initial_count) {
24     *sem = (semaphore_t)SEMAPHORE_INITIAL_VALUE(*sem, initial_count);
25 }
26 
sem_destroy(semaphore_t * sem)27 void sem_destroy(semaphore_t *sem) {
28     THREAD_LOCK(state);
29     sem->count = 0;
30     wait_queue_destroy(&sem->wait, true);
31     THREAD_UNLOCK(state);
32 }
33 
sem_post(semaphore_t * sem,bool resched)34 int sem_post(semaphore_t *sem, bool resched) {
35     int ret = 0;
36 
37     THREAD_LOCK(state);
38 
39     /*
40      * If the count is or was negative then a thread is waiting for a resource, otherwise
41      * it's safe to just increase the count available with no downsides
42      */
43     if (unlikely(++sem->count <= 0))
44         ret = wait_queue_wake_one(&sem->wait, resched, NO_ERROR);
45 
46     THREAD_UNLOCK(state);
47 
48     return ret;
49 }
50 
sem_wait(semaphore_t * sem)51 status_t sem_wait(semaphore_t *sem) {
52     status_t ret = NO_ERROR;
53     THREAD_LOCK(state);
54 
55     /*
56      * If there are no resources available then we need to
57      * sit in the wait queue until sem_post adds some.
58      */
59     if (unlikely(--sem->count < 0))
60         ret = wait_queue_block(&sem->wait, INFINITE_TIME);
61 
62     THREAD_UNLOCK(state);
63     return ret;
64 }
65 
sem_trywait(semaphore_t * sem)66 status_t sem_trywait(semaphore_t *sem) {
67     status_t ret = NO_ERROR;
68     THREAD_LOCK(state);
69 
70     if (unlikely(sem->count <= 0)) {
71         ret = ERR_NOT_READY;
72     } else {
73         sem->count--;
74     }
75 
76     THREAD_UNLOCK(state);
77     return ret;
78 }
79 
sem_timedwait(semaphore_t * sem,lk_time_t timeout)80 status_t sem_timedwait(semaphore_t *sem, lk_time_t timeout) {
81     status_t ret = NO_ERROR;
82     THREAD_LOCK(state);
83 
84     if (unlikely(--sem->count < 0)) {
85         ret = wait_queue_block(&sem->wait, timeout);
86         if (ret < NO_ERROR) {
87             if (ret == ERR_TIMED_OUT) {
88                 sem->count++;
89             }
90         }
91     }
92 
93     THREAD_UNLOCK(state);
94     return ret;
95 }
96