|
|
|
@ -40,32 +40,35 @@ void mtx_init(struct mtx *mtx)
|
|
|
|
|
|
|
|
|
|
void mtx_lock(struct mtx *mtx)
|
|
|
|
|
{
|
|
|
|
|
while (1) {
|
|
|
|
|
/*
|
|
|
|
|
* acquire a lock on the wait queue before trying to claim the
|
|
|
|
|
* mutex itself to make sure the mutex isn't released while we
|
|
|
|
|
* are inserting ourselves into the wait queue
|
|
|
|
|
*/
|
|
|
|
|
spin_lock(&mtx->wait_queue_lock);
|
|
|
|
|
if (atom_write(&mtx->lock, 1) == 0) {
|
|
|
|
|
spin_unlock(&mtx->wait_queue_lock);
|
|
|
|
|
} else {
|
|
|
|
|
struct task *task = current;
|
|
|
|
|
/*
|
|
|
|
|
* acquire a lock on the wait queue before trying to claim the
|
|
|
|
|
* mutex itself to make sure the mutex isn't released while we
|
|
|
|
|
* are inserting ourselves into the wait queue
|
|
|
|
|
* It might not be the smartest idea to allocate this thing on
|
|
|
|
|
* the stack because it's gonna blow up if the task somehow dies
|
|
|
|
|
* before returning here. Let's see how this turns out.
|
|
|
|
|
*/
|
|
|
|
|
spin_lock(&mtx->wait_queue_lock);
|
|
|
|
|
if (atom_write(&mtx->lock, 1) == 0) {
|
|
|
|
|
spin_unlock(&mtx->wait_queue_lock);
|
|
|
|
|
break;
|
|
|
|
|
} else {
|
|
|
|
|
struct task *cur = current;
|
|
|
|
|
/*
|
|
|
|
|
* It might not be the smartest idea to allocate this thing on
|
|
|
|
|
* the stack because it's gonna blow up if the task somehow dies
|
|
|
|
|
* before returning here. Let's see how this turns out.
|
|
|
|
|
*/
|
|
|
|
|
struct lock_waiter waiter = {
|
|
|
|
|
.task = cur,
|
|
|
|
|
};
|
|
|
|
|
clist_add(&mtx->wait_queue, &waiter.clink);
|
|
|
|
|
spin_unlock(&mtx->wait_queue_lock);
|
|
|
|
|
struct lock_waiter waiter = {
|
|
|
|
|
.task = task,
|
|
|
|
|
};
|
|
|
|
|
clist_add(&mtx->wait_queue, &waiter.clink);
|
|
|
|
|
spin_unlock(&mtx->wait_queue_lock);
|
|
|
|
|
|
|
|
|
|
cur->state = TASK_BLOCKED;
|
|
|
|
|
schedule();
|
|
|
|
|
}
|
|
|
|
|
task->state = TASK_BLOCKED;
|
|
|
|
|
/*
|
|
|
|
|
* This is only gonna return when the task currently owning the
|
|
|
|
|
* lock releases it. In that case, it doesn't unlock the mutex
|
|
|
|
|
* but merely switches back to us directly and thereby implicitly
|
|
|
|
|
* transfers the ownership of the mutex to us (see mtx_unlock()).
|
|
|
|
|
*/
|
|
|
|
|
schedule();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|