/* Gothrough the pending queue for the indicated semaphore
* looking for tasks that can be completed.
*/
static voidupdate_queue (struct sem_array * sma)
{
interror;
structsem_queue * q;
q =list_entry(sma->sem_pending.next, structsem_queue, list);
while (&q->list!= &sma->sem_pending) {
error = try_atomic_semop(sma,q->sops, q->nsops,
q->undo, q->pid);
/*Does q->sleeper still need to sleep? */
if(error <= 0) {
struct sem_queue *n;
/*
* Continue scanning. The next operation
* that must be checked depends on the type ofthe
* completed operation:
* - if the operation modified the array, then
* restart from the head of the queue and
* check for threads that might be waiting
* forsemaphore values to become 0.
* - if the operation didn't modify the array,
* thenjust continue.
* The order of list_del() and reading->next
* is crucial: In the former case, thelist_del()
* must be done first [because we might be the
* first entry in ->sem_pending], in thelatter
* case the list_del() must be done last
* [because the list is invalid after thelist_del()]
*/
if (q->alter) {
list_del(&q->list);
n =list_entry(sma->sem_pending.next,
struct sem_queue, list);
} else {
n =list_entry(q->list.next, struct sem_queue,
list);
list_del(&q->list);
}
/* wake up the waiting thread */
q->status =IN_WAKEUP;
wake_up_process(q->sleeper);
/* hands-off: q will disappear immediately after
* writing q->status.
*/
smp_wmb();
q->status =error;
q = n;
} else{
q =list_entry(q->list.next, struct sem_queue,list);
}
}
}
遍历sem_array对应sem_queue链表中的所有项,对链表中的每一项sem进行操作,具体值的更改操作由函数try_atomic_semop完成,当try_atomic_semop返回非正值时,表示不需要再等待,此时唤醒等待进程。
/*
* Determine whether a sequence of semaphoreoperations would succeed
* all at once. Return 0 if yes, 1 if need tosleep, else return error code.
*/
static inttry_atomic_semop (struct sem_array * sma, struct sembuf * sops,
int nsops,struct sem_undo *un, intpid)
{
intresult, sem_op;
structsembuf *sop;
structsem * curr;
for(sop = sops; sop < sops + nsops; sop++) {
curr = sma->sem_base +sop->sem_num;
sem_op = sop->sem_op;
result = curr->semval;
if(!sem_op && result)
goto would_block;
result += sem_op;
if(result < 0)
goto would_block;
if(result > SEMVMX)
goto out_of_range;
if(sop->sem_flg & SEM_UNDO) {
int undo = un->semadj[sop->sem_num] - sem_op;
/*
* Exceedingthe undo range is an error.
*/
if (undo < (-SEMAEM - 1) || undo > SEMAEM)
goto out_of_range;
}
curr->semval = result;
}
sop--;
while(sop >= sops) {
sma->sem_base[sop->sem_num].sempid= pid;
if(sop->sem_flg & SEM_UNDO)
un->semadj[sop->sem_num]-= sop->sem_op;
sop--;
}
sma->sem_otime = get_seconds();
return0;
out_of_range:
result = -ERANGE;
gotoundo;
would_block:
if(sop->sem_flg & IPC_NOWAIT)
result = -EAGAIN;
else
result = 1;
undo:
sop--;
while(sop >= sops) {
sma->sem_base[sop->sem_num].semval-= sop->sem_op;
sop--;
}
returnresult;
}
由curr =sma->sem_base + sop->sem_num;定位到具体的sem项,然后result = curr->semval;result += sem_op;两条语句用于对semval值进行操作。
