/*
 * linux/ipc/sem.c
 * Copyright (C) 1992 Krishna Balasubramanian
 * Copyright (C) 1995 Eric Schenk, Bruno Haible
 *
 * IMPLEMENTATION NOTES ON CODE REWRITE (Eric Schenk, January 1995):
 * This code underwent a massive rewrite in order to solve some problems
 * with the original code. In particular the original code failed to
 * wake up processes that were waiting for semval to go to 0 if the
 * value went to 0 and was then incremented rapidly enough. In solving
 * this problem I have also modified the implementation so that it
 * processes pending operations in a FIFO manner, thus give a guarantee
 * that processes waiting for a lock on the semaphore won't starve
 * unless another locking process fails to unlock.
 * In addition the following two changes in behavior have been introduced:
 * - The original implementation of semop returned the value
 *   last semaphore element examined on success. This does not
 *   match the manual page specifications, and effectively
 *   allows the user to read the semaphore even if they do not
 *   have read permissions. The implementation now returns 0
 *   on success as stated in the manual page.
 * - There is some confusion over whether the set of undo adjustments
 *   to be performed at exit should be done in an atomic manner.
 *   That is, if we are attempting to decrement the semval should we queue
 *   up and wait until we can do so legally?
 *   The original implementation attempted to do this.
 *   The current implementation does not do so. This is because I don't
 *   think it is the right thing (TM) to do, and because I couldn't
 *   see a clean way to get the old behavior with the new design.
 *   The POSIX standard and SVID should be consulted to determine
 *   what behavior is mandated.
 *
 * Further notes on refinement (Christoph Rohland, December 1998):
 * - The POSIX standard says, that the undo adjustments simply should
 *   redo. So the current implementation is o.K.
 * - The previous code had two flaws:
 *   1) It actively gave the semaphore to the next waiting process
 *      sleeping on the semaphore. Since this process did not have the
 *      cpu this led to many unnecessary context switches and bad
 *      performance. Now we only check which process should be able to
 *      get the semaphore and if this process wants to reduce some
 *      semaphore value we simply wake it up without doing the
 *      operation. So it has to try to get it later. Thus e.g. the
 *      running process may reaquire the semaphore during the current
 *      time slice. If it only waits for zero or increases the semaphore,
 *      we do the operation in advance and wake it up.
 *   2) It did not wake up all zero waiting processes. We try to do
 *      better but only get the semops right which only wait for zero or
 *      increase. If there are decrement operations in the operations
 *      array we do the same as before.
 *
 * /proc/sysvipc/sem support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
 *
 * SMP-threaded (c) 1999 Manfred Spraul <manfreds@colorfullife.com>
 */

#include <linux/config.h>
#include <linux/malloc.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/proc_fs.h>

#include <asm/uaccess.h>

extern int ipcperms (struct ipc_perm *ipcp, short semflg);
static int newary (key_t, int, int);
static int findkey (key_t key);
static void freeary (int id);
#ifdef CONFIG_PROC_FS
static int sysvipc_sem_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data);
#endif

struct semid_ary
{
	spinlock_t lock;
	struct semid_ds* s;
};

static struct semid_ary semary[SEMMNI];

static DECLARE_MUTEX(sem_lock);
static int max_semid = 0;
static int used_sems = 0;
static int used_semids = 0;

static unsigned short sem_seq = 0;

/* anti-deadlock ordering:
 *	sem_lock < semary[].lock
 * linked list protection:
 *	sem_undo.id_next,
 *	semid_ds.sem_pending{,last},
 *	semid_ds.sem_undo: semary[].lock for read/write
 *	sem_undo.proc_next: only "current" is allowed to read/write that field.
 *	
 */

void __init sem_init (void)
{
	int i;

	used_sems = used_semids = max_semid = sem_seq = 0;
	for (i = 0; i < SEMMNI; i++) {
		semary[i].lock = SPIN_LOCK_UNLOCKED;
		semary[i].s = NULL;
	}
#ifdef CONFIG_PROC_FS
	create_proc_read_entry("sysvipc/sem", 0, 0, sysvipc_sem_read_proc, NULL);
#endif
	return;
}

static int findkey (key_t key)
{
	int id;
	struct semid_ds *sma;

	for (id = 0; id <= max_semid; id++) {
		sma = semary[id].s;
		if(sma==NULL)
			continue;

		if (key == sma->sem_perm.key)
			return id;
	}
	return -1;
}

static int newary (key_t key, int nsems, int semflg)
{
	int id;
	struct semid_ds *sma;
	struct ipc_perm *ipcp;
	int size;

	if (!nsems)
		return -EINVAL;
	if (used_sems + nsems > SEMMNS)
		return -ENOSPC;
	for (id = 0; id < SEMMNI; id++) {
		if(semary[id].s == NULL)
			goto found;
	}
	return -ENOSPC;
found:
	size = sizeof (*sma) + nsems * sizeof (struct sem);
	used_sems += nsems;
	sma = (struct semid_ds *) kmalloc (size, GFP_KERNEL);
	if (!sma) {
		used_sems -= nsems;
		return -ENOMEM;
	}
	memset (sma, 0, size);
	sma->sem_base = (struct sem *) &sma[1];
	ipcp = &sma->sem_perm;
	ipcp->mode = (semflg & S_IRWXUGO);
	ipcp->key = key;
	ipcp->cuid = ipcp->uid = current->euid;
	ipcp->gid = ipcp->cgid = current->egid;
	/* sma->sem_perm.seq*MSGMNI must be a positive integer.
	 * this limits MSGMNI to 32768
	 */
	sma->sem_perm.seq = sem_seq++;
	/* sma->sem_pending = NULL; */
	sma->sem_pending_last = &sma->sem_pending;
	/* sma->undo = NULL; */
	sma->sem_nsems = nsems;
	sma->sem_ctime = CURRENT_TIME;
	if (id > max_semid)
		max_semid = id;
	used_semids++;
	spin_lock(&semary[id].lock);
	semary[id].s = sma;
	spin_unlock(&semary[id].lock);
	return (unsigned int) sma->sem_perm.seq * SEMMNI + id;
}

asmlinkage long sys_semget (key_t key, int nsems, int semflg)
{
	int id, err = -EINVAL;
	struct semid_ds *sma;

	if (nsems < 0 || nsems > SEMMSL)
		return -EINVAL;
	down(&sem_lock);
	
	if (key == IPC_PRIVATE) {
		err = newary(key, nsems, semflg);
	} else if ((id = findkey (key)) == -1) {  /* key not used */
		if (!(semflg & IPC_CREAT))
			err = -ENOENT;
		else
			err = newary(key, nsems, semflg);
	} else if (semflg & IPC_CREAT && semflg & IPC_EXCL) {
		err = -EEXIST;
	} else {
		sma = semary[id].s;
		if (nsems > sma->sem_nsems)
			err = -EINVAL;
		else if (ipcperms(&sma->sem_perm, semflg))
			err = -EACCES;
		else
			err = (int) sma->sem_perm.seq * SEMMNI + id;
	}

	up(&sem_lock);
	return err;
}

/* Manage the doubly linked list sma->sem_pending as a FIFO:
 * insert new queue elements at the tail sma->sem_pending_last.
 */
static inline void append_to_queue (struct semid_ds * sma,
				    struct sem_queue * q)
{
	*(q->prev = sma->sem_pending_last) = q;
	*(sma->sem_pending_last = &q->next) = NULL;
}

static inline void prepend_to_queue (struct semid_ds * sma,
				     struct sem_queue * q)
{
	q->next = sma->sem_pending;
	*(q->prev = &sma->sem_pending) = q;
	if (q->next)
		q->next->prev = &q->next;
	else /* sma->sem_pending_last == &sma->sem_pending */
		sma->sem_pending_last = &q->next;
}

static inline void remove_from_queue (struct semid_ds * sma,
				      struct sem_queue * q)
{
	*(q->prev) = q->next;
	if (q->next)
		q->next->prev = q->prev;
	else /* sma->sem_pending_last == &q->next */
		sma->sem_pending_last = q->prev;
	q->prev = NULL; /* mark as removed */
}

/*
 * Determine whether a sequence of semaphore operations would succeed
 * all at once. Return 0 if yes, 1 if need to sleep, else return error code.
 */

static int try_atomic_semop (struct semid_ds * sma, struct sembuf * sops,
			     int nsops, struct sem_undo *un, int pid,
			     int do_undo)
{
	int result, sem_op;
	struct sembuf *sop;
	struct sem * curr;

	for (sop = sops; sop < sops + nsops; sop++) {
		curr = sma->sem_base + sop->sem_num;
		sem_op = sop->sem_op;

		if (!sem_op && curr->semval)
			goto would_block;

		curr->sempid = (curr->sempid << 16) | pid;
		curr->semval += sem_op;
		if (sop->sem_flg & SEM_UNDO)
			un->semadj[sop->sem_num] -= sem_op;

		if (curr->semval < 0)
			goto would_block;
		if (curr->semval > SEMVMX)
			goto out_of_range;
	}

	if (do_undo)
	{
		sop--;
		result = 0;
		goto undo;
	}

	sma->sem_otime = CURRENT_TIME;
	return 0;

out_of_range:
	result = -ERANGE;
	goto undo;

would_block:
	if (sop->sem_flg & IPC_NOWAIT)
		result = -EAGAIN;
	else
		result = 1;

undo:
	while (sop >= sops) {
		curr = sma->sem_base + sop->sem_num;
		curr->semval -= sop->sem_op;
		curr->sempid >>= 16;

		if (sop->sem_flg & SEM_UNDO)
			un->semadj[sop->sem_num] += sop->sem_op;
		sop--;
	}

	return result;
}

/* Go through the pending queue for the indicated semaphore
 * looking for tasks that can be completed.
 */
static void update_queue (struct semid_ds * sma)
{
	int error;
	struct sem_queue * q;

	for (q = sma->sem_pending; q; q = q->next) {
			
		if (q->status == 1)
			return; /* wait for other process */

		error = try_atomic_semop(sma, q->sops, q->nsops,
					 q->undo, q->pid, q->alter);

		/* Does q->sleeper still need to sleep? */
		if (error <= 0) {
				/* Found one, wake it up */
			wake_up_process(q->sleeper);
			if (error == 0 && q->alter) {
				/* if q-> alter let it self try */
				q->status = 1;
				return;
			}
			q->status = error;
			remove_from_queue(sma,q);
		}
	}
}

/* The following counts are associated to each semaphore:
 *   semncnt        number of tasks waiting on semval being nonzero
 *   semzcnt        number of tasks waiting on semval being zero
 * This model assumes that a task waits on exactly one semaphore.
 * Since semaphore operations are to be performed atomically, tasks actually
 * wait on a whole sequence of semaphores simultaneously.
 * The counts we return here are a rough approximation, but still
 * warrant that semncnt+semzcnt>0 if the task is on the pending queue.
 */
static int count_semncnt (struct semid_ds * sma, ushort semnum)
{
	int semncnt;
	struct sem_queue * q;

	semncnt = 0;
	for (q = sma->sem_pending; q; q = q->next) {
		struct sembuf * sops = q->sops;
		int nsops = q->nsops;
		int i;
		for (i = 0; i < nsops; i++)
			if (sops[i].sem_num == semnum
			    && (sops[i].sem_op < 0)
			    && !(sops[i].sem_flg & IPC_NOWAIT))
				semncnt++;
	}
	return semncnt;
}
static int count_semzcnt (struct semid_ds * sma, ushort semnum)
{
	int semzcnt;
	struct sem_queue * q;

	semzcnt = 0;
	for (q = sma->sem_pending; q; q = q->next) {
		struct sembuf * sops = q->sops;
		int nsops = q->nsops;
		int i;
		for (i = 0; i < nsops; i++)
			if (sops[i].sem_num == semnum
			    && (sops[i].sem_op == 0)
			    && !(sops[i].sem_flg & IPC_NOWAIT))
				semzcnt++;
	}
	return semzcnt;
}

/* Free a semaphore set. */
static void freeary (int id)
{
	struct semid_ds *sma;
	struct sem_undo *un;
	struct sem_queue *q;

	/* we own both locks, noone can get in */
	sma = semary[id].s;
	semary[id].s = NULL;

	used_sems -= sma->sem_nsems;
	if (id == max_semid)
		while (max_semid && (semary[--max_semid].s == NULL));
	used_semids--;

	/* Invalidate the existing undo structures for this semaphore set.
	 * (They will be freed without any further action in sem_exit()
	 * or during the next semop.)
	 */
	for (un = sma->undo; un; un = un->id_next)
		un->semid = -1;

	/* Wake up all pending processes and let them fail with EIDRM. */
	for (q = sma->sem_pending; q; q = q->next) {
		q->status = -EIDRM;
		q->prev = NULL;
		wake_up_process(q->sleeper); /* doesn't sleep */
	}

	kfree(sma);
}

int semctl_nolock(int semid, int semnum, int cmd, union semun arg)
{
	int err = -EINVAL;
	int lid = semid % SEMMNI;

	switch(cmd) {
	case IPC_INFO:
	case SEM_INFO:
	{
		struct seminfo seminfo;

		seminfo.semmni = SEMMNI;
		seminfo.semmns = SEMMNS;
		seminfo.semmsl = SEMMSL;
		seminfo.semopm = SEMOPM;
		seminfo.semvmx = SEMVMX;
		seminfo.semmnu = SEMMNU;
		seminfo.semmap = SEMMAP;
		seminfo.semume = SEMUME;
		seminfo.semusz = SEMUSZ;
		seminfo.semaem = SEMAEM;
		if (cmd == SEM_INFO) {
			down(&sem_lock);
			seminfo.semusz = used_semids;
			seminfo.semaem = used_sems;
			up(&sem_lock);
		}
		if (copy_to_user (arg.__buf, &seminfo, sizeof(struct seminfo))) 
			return -EFAULT;
		return max_semid;
	}
	case SEM_STAT:
	{
		struct semid_ds *sma;
		struct semid_ds tbuf;
		int id;

		if (semid > max_semid)
			return -EINVAL;

		spin_lock(&semary[lid].lock);
		err = -EINVAL;
		sma = semary[semid].s;
		if (sma ==  NULL)
			goto out_unlock;
		err = -EACCES;
		if (ipcperms (&sma->sem_perm, S_IRUGO))
			goto out_unlock;
		id = (unsigned int) sma->sem_perm.seq * SEMMNI + semid;
		memset(&tbuf,0,sizeof(tbuf));
		tbuf.sem_perm   = sma->sem_perm;
		tbuf.sem_otime  = sma->sem_otime;
		tbuf.sem_ctime  = sma->sem_ctime;
		tbuf.sem_nsems  = sma->sem_nsems;
		spin_unlock(&semary[lid].lock);
		if (copy_to_user (arg.buf, &tbuf, sizeof(tbuf)))
			return -EFAULT;
		return id;
	}
	default:
		return -EINVAL;
	}
	return err;
out_unlock:
	spin_unlock(&semary[lid].lock);
	return err;
}

int semctl_locked_unlock(int semid, int semnum, int cmd, union semun arg)
{
	struct semid_ds *sma;
	struct semid_ds tbuf;
	int err;
	int lid = semid % SEMMNI;

	sma = semary[lid].s;
	err=-EINVAL;
	if (sma == NULL)
		goto out_unlock;
	err=-EIDRM;
	if (sma->sem_perm.seq != (unsigned int) semid / SEMMNI)
		goto out_unlock;

	err = -EACCES;
	if (ipcperms(&sma->sem_perm, S_IRUGO))
			goto out_unlock;	
	
	switch (cmd) {
	case GETALL:
	{
		ushort *array = arg.array;
		ushort sem_io[SEMMSL];
		int i;
		int nsems = sma->sem_nsems;

		for (i = 0; i < sma->sem_nsems; i++)
			sem_io[i] = sma->sem_base[i].semval;
		spin_unlock(&semary[lid].lock);
		if (copy_to_user (array, sem_io, nsems*sizeof(ushort)))
			return -EFAULT;
		return 0;
	}
	case IPC_STAT:
		memset(&tbuf,0,sizeof(tbuf));
		tbuf.sem_perm   = sma->sem_perm;
		tbuf.sem_otime  = sma->sem_otime;
		tbuf.sem_ctime  = sma->sem_ctime;
		tbuf.sem_nsems  = sma->sem_nsems;
		spin_unlock(&semary[lid].lock);
		if (copy_to_user (arg.buf, &tbuf, sizeof(tbuf)))
			return -EFAULT;
		return 0;
default:
		err = -EINVAL;
	}
out_unlock:
	spin_unlock(&semary[lid].lock);
	return err;

}

int semctl_locked(int semid, int semnum, int cmd, union semun arg)
{
	struct semid_ds *sma;
	int lid = semid % SEMMNI;
	struct sem *curr;

	sma = semary[lid].s;
	if (sma == NULL)
		return -EINVAL;

	if (ipcperms (&sma->sem_perm, (cmd==SETVAL)?S_IWUGO:S_IRUGO))
		return -EACCES;

	if (sma->sem_perm.seq != (unsigned int) semid / SEMMNI)
		return -EIDRM;

	if (semnum >= sma->sem_nsems)
		return -EINVAL;

	curr = &sma->sem_base[semnum];

	switch (cmd) {
	case GETVAL:
		return curr->semval;
	case GETPID:
		return curr->sempid & 0xffff;
	case GETNCNT:
		return count_semncnt(sma,semnum);
	case GETZCNT:
		return count_semzcnt(sma,semnum);
	case SETVAL:
	{
		int val = arg.val;
		struct sem_undo *un;
		if (val > SEMVMX || val < 0)
			return -ERANGE;

		for (un = sma->undo; un; un = un->id_next)
			un->semadj[semnum] = 0;
		curr->semval = val;
		sma->sem_ctime = CURRENT_TIME;
		/* maybe some queued-up processes were waiting for this */
		update_queue(sma);
		return 0;
	}
	}
	return -EINVAL;
}

int semctl_down(int semid, int semnum, int cmd, union semun arg)
{
	struct semid_ds *sma;
	int err;
	int lid = semid % SEMMNI;
	struct semid_ds tbuf;
	struct ipc_perm *ipcp;

	if(cmd == IPC_SET) {
		if(copy_from_user (&tbuf, arg.buf, sizeof (tbuf)))
			return -EFAULT;
	}
	spin_lock(&semary[lid].lock);
	sma = semary[lid].s;
	err=-EINVAL;
	if (sma == NULL)
		goto out_unlock;
	ipcp = &sma->sem_perm;
	
	if(cmd == SETALL) {
		int i;
		struct sem_undo *un;
		unsigned int nsems;
		ushort sem_io[SEMMSL];
		/* SETALL doesn't belong into this
		 * group, but I need the semaphore
		 * for atomically reading nsems
		 * and changing the semaphore values
		 */
		err=-EACCES;
		if (ipcperms (ipcp, S_IWUGO))
			goto out_unlock;
		nsems=sma->sem_nsems;
		spin_unlock(&semary[lid].lock);

		if (copy_from_user (sem_io, arg.array, nsems*sizeof(ushort)))
			return -EFAULT;
		for (i = 0; i < nsems; i++) {
			if (sem_io[i] > SEMVMX) {
				return -ERANGE;
			}
		}
		/* we still own sem_lock, ie neither ownership
		 * nor permissions of the sem array could
		 * have changed. Just continue.
		 */
		spin_lock(&semary[lid].lock);
		for (i = 0; i < nsems; i++)
			sma->sem_base[i].semval = sem_io[i];
		for (un = sma->undo; un; un = un->id_next)
			for (i = 0; i < nsems; i++)
				un->semadj[i] = 0;
		sma->sem_ctime = CURRENT_TIME;
		/* maybe some queued-up processes were waiting for this */
		update_queue(sma);
		err = 0;
		goto out_unlock;
	}

	if (current->euid != ipcp->cuid && 
	    current->euid != ipcp->uid && !capable(CAP_SYS_ADMIN)) {
	    	err=-EPERM;
		goto out_unlock;
	}
		
	if (sma->sem_perm.seq != (unsigned int) semid / SEMMNI) {
		err=-EIDRM;
		goto out_unlock;
	}	
	switch(cmd){
	case IPC_RMID:
		freeary(lid);
		err = 0;
		break;
	case IPC_SET:
		ipcp->uid = tbuf.sem_perm.uid;
		ipcp->gid = tbuf.sem_perm.gid;
		ipcp->mode = (ipcp->mode & ~S_IRWXUGO)
				| (tbuf.sem_perm.mode & S_IRWXUGO);
		sma->sem_ctime = CURRENT_TIME;
		err = 0;
		break;
	default:
		err = -EINVAL;
	}

out_unlock:
	spin_unlock(&semary[lid].lock);
	return err;
}

asmlinkage long sys_semctl (int semid, int semnum, int cmd, union semun arg)
{
	int lid; /* lock id */
	int err = -EINVAL;

	if (semid < 0 || semnum < 0 || cmd < 0)
		return -EINVAL;

	lid = semid % SEMMNI;

	switch(cmd) {
	case IPC_INFO:
	case SEM_INFO:
	case SEM_STAT:
		err = semctl_nolock(semid,semnum,cmd,arg);
		return err;
	case GETALL:
	case IPC_STAT:
		spin_lock(&semary[lid].lock);
		err = semctl_locked_unlock(semid,semnum,cmd,arg);
		return err;
	case GETVAL:
	case GETPID:
	case GETNCNT:
	case GETZCNT:
	case SETVAL:
		spin_lock(&semary[lid].lock);
		err= semctl_locked(semid,semnum,cmd,arg);
		spin_unlock(&semary[lid].lock);
		return err;
	case SETALL:
	case IPC_RMID:
	case IPC_SET:
		down(&sem_lock);
		err= semctl_down(semid,semnum,cmd,arg);
		up(&sem_lock);
		return err;
	default:
		return -EINVAL;
	}
}

static struct sem_undo* freeundos(struct semid_ds *sma, struct sem_undo* un)
{
	struct sem_undo* u;
	struct sem_undo** up;

	for(up = &current->semundo;(u=*up);up=&u->proc_next) {
		if(un==u) {
			un=u->proc_next;
			*up=un;
			kfree(u);
			return un;
		}
	}
	printk ("freeundos undo list error id=%d\n", un->semid);
	return un->proc_next;
}

static int alloc_undo(struct semid_ds *sma, struct sem_undo** unp, int semid, int alter)
{
	int size;
	struct sem_undo *un;
	int error,id;
	id = (unsigned int) semid % SEMMNI;
	size = sizeof(struct sem_undo) + sizeof(short)*sma->sem_nsems;
	spin_unlock(&semary[id].lock);

	un = (struct sem_undo *) kmalloc(size, GFP_KERNEL);
	spin_lock(&semary[id].lock);
	if (!un) {
		return -ENOMEM;
	}
	sma = semary[id].s;
	error = -EIDRM;
	if (sma == NULL)
		goto out;
	if (sma->sem_perm.seq != (unsigned int) semid / SEMMNI)
		goto out;
	if (size != sizeof(struct sem_undo) + sizeof(short)*sma->sem_nsems)
		goto out;

	error = -EACCES;
	if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
		goto out;
	memset(un, 0, size);
	un->semadj = (short *) &un[1];
	un->semid = semid;
	un->proc_next = current->semundo;
	current->semundo = un;
	un->id_next = sma->undo;
	sma->undo = un;
	*unp = un;
	return 0;
out:
	kfree(un);
	return error;
}

asmlinkage long sys_semop (int semid, struct sembuf *tsops, unsigned nsops)
{
	int id, error = -EINVAL;
	struct semid_ds *sma;
	struct sembuf sops[SEMOPM], *sop;
	struct sem_undo *un;
	int undos = 0, decrease = 0, alter = 0;
	struct sem_queue queue;

	if (nsops < 1 || semid < 0)
		return -EINVAL;

	if (nsops > SEMOPM)
		return -E2BIG;
	if (copy_from_user (sops, tsops, nsops * sizeof(*tsops)))
		return -EFAULT;

	id = (unsigned int) semid % SEMMNI;
	spin_lock(&semary[id].lock);
	sma = semary[id].s;
	error = -EINVAL;
	if (sma == NULL)
		goto out;
	error = -EIDRM;
	if (sma->sem_perm.seq != (unsigned int) semid / SEMMNI)
		goto out;

	error = -EFBIG;
	for (sop = sops; sop < sops + nsops; sop++) {
		if (sop->sem_num >= sma->sem_nsems)
			goto out;
		if (sop->sem_flg & SEM_UNDO)
			undos++;
		if (sop->sem_op < 0)
			decrease = 1;
		if (sop->sem_op > 0)
			alter = 1;
	}
	alter |= decrease;

	error = -EACCES;
	if (ipcperms(&sma->sem_perm, alter ? S_IWUGO : S_IRUGO))
		goto out;
	if (undos) {
		/* Make sure we have an undo structure
		 * for this process and this semaphore set.
		 */
		un=current->semundo;
		while(un != NULL) {
			if(un->semid==semid)
				break;
			if(un->semid==-1)
				un=freeundos(sma,un);
			 else
				un=un->proc_next;
		}
		if (!un) {
			error = alloc_undo(sma,&un,semid,alter);
			if(error<0)
				goto out;
		}
	} else
		un = NULL;

	error = try_atomic_semop (sma, sops, nsops, un, current->pid, 0);
	if (error <= 0)
		goto update;

	/* We need to sleep on this operation, so we put the current
	 * task into the pending queue and go to sleep.
	 */
		
	queue.sma = sma;
	queue.sops = sops;
	queue.nsops = nsops;
	queue.undo = un;
	queue.pid = current->pid;
	queue.alter = decrease;
	queue.id = id;
	current->semsleeping = &queue;
	if (alter)
		append_to_queue(sma ,&queue);
	else
		prepend_to_queue(sma ,&queue);

	for (;;) {
		queue.status = -EINTR;
		queue.sleeper = current;
		current->state = TASK_INTERRUPTIBLE;
		spin_unlock(&semary[id].lock);

		schedule();

		/* we can lock the semary even if it was
		 * deleted.
		 */
		spin_lock(&semary[id].lock);
		/*
		 * If queue.status == 1 we where woken up and
		 * have to retry else we simply return.
		 * If an interrupt occurred we have to clean up the
		 * queue
		 *
		 */
		if (queue.status == 1)
		{
			error = try_atomic_semop (sma, sops, nsops, un,
						  current->pid,0);
			if (error <= 0) 
				break;
		} else {
			error = queue.status;
			if (queue.prev) /* got Interrupt */
				break;
			/* Everything done by update_queue */
			current->semsleeping = NULL;
			goto out;
		}
	}
	current->semsleeping = NULL;
	remove_from_queue(sma,&queue);
update:
	if (alter)
		update_queue (sma);
out:
	spin_unlock(&semary[id].lock);
	return error;
}

/*
 * add semadj values to semaphores, free undo structures.
 * undo structures are not freed when semaphore arrays are destroyed
 * so some of them may be out of date.
 * IMPLEMENTATION NOTE: There is some confusion over whether the
 * set of adjustments that needs to be done should be done in an atomic
 * manner or not. That is, if we are attempting to decrement the semval
 * should we queue up and wait until we can do so legally?
 * The original implementation attempted to do this (queue and wait).
 * The current implementation does not do so. The POSIX standard
 * and SVID should be consulted to determine what behavior is mandated.
 */
void sem_exit (void)
{
	struct sem_queue *q;
	struct sem_undo *u, *un = NULL, **up, **unp;
	struct semid_ds *sma;
	int nsems, i;

	/* If the current process was sleeping for a semaphore,
	 * remove it from the queue.
	 */
	/* semsleeping is part of "current", and it
	 * is never modified by another thread.
	 * No synchronization required.
	 */
	if ((q = current->semsleeping)) {
		spin_lock(&semary[current->semsleeping->id].lock);

		if (q->prev)
			remove_from_queue(q->sma,q);
		current->semsleeping = NULL;
		spin_unlock(&semary[current->semsleeping->id].lock);
	}

	for (up = &current->semundo; (u = *up); *up = u->proc_next, kfree(u)) {
		int semid = u->semid;
		int lid;
		if(semid == -1)
			continue;
		lid = semid % SEMMNI;
		spin_lock(&semary[lid].lock);

		if (u->semid == -1)
			goto next_entry;

		sma = semary[lid].s;
		if (sma == NULL)
			goto next_entry;
		if (sma->sem_perm.seq != (unsigned int) u->semid / SEMMNI)
			goto next_entry;

		/* remove u from the sma->undo list */
		for (unp = &sma->undo; (un = *unp); unp = &un->id_next) {
			if (u == un)
				goto found;
		}
		printk ("sem_exit undo list error id=%d\n", u->semid);
		goto next_entry;
found:
		*unp = un->id_next;
		/* perform adjustments registered in u */
		nsems = sma->sem_nsems;
		for (i = 0; i < nsems; i++) {
			struct sem * sem = &sma->sem_base[i];
			sem->semval += u->semadj[i];
			if (sem->semval < 0)
				sem->semval = 0; /* shouldn't happen */
			sem->sempid = current->pid;
		}
		sma->sem_otime = CURRENT_TIME;
		/* maybe some queued-up processes were waiting for this */
		update_queue(sma);
next_entry:
		spin_unlock(&semary[lid].lock);
	}
	current->semundo = NULL;
}

#ifdef CONFIG_PROC_FS
static int sysvipc_sem_read_proc(char *buffer, char **start, off_t offset, int length, int *eof, void *data)
{
	off_t pos = 0;
	off_t begin = 0;
	int i, len = 0;

	len += sprintf(buffer, "       key      semid perms nsems   uid   gid  cuid  cgid      otime      ctime\n");
	down(&sem_lock);

	for(i = 0; i < SEMMNI; i++)
		if(semary[i].s != NULL) {
			spin_lock(&semary[i].lock);
			len += sprintf(buffer + len, "%10d %10d  %4o %5u %5u %5u %5u %5u %10lu %10lu\n",
				semary[i].s->sem_perm.key,
				semary[i].s->sem_perm.seq * SEMMNI + i,
				semary[i].s->sem_perm.mode,
				semary[i].s->sem_nsems,
				semary[i].s->sem_perm.uid,
				semary[i].s->sem_perm.gid,
				semary[i].s->sem_perm.cuid,
				semary[i].s->sem_perm.cgid,
				semary[i].s->sem_otime,
				semary[i].s->sem_ctime);
			spin_unlock(&semary[i].lock);

			pos += len;
			if(pos < offset) {
				len = 0;
	    		begin = pos;
			}
			if(pos > offset + length)
				goto done;
		}
	*eof = 1;
done:
	up(&sem_lock);
	*start = buffer + (offset - begin);
	len -= (offset - begin);
	if(len > length)
		len = length;
	if(len < 0)
		len = 0;
	return len;
}
#endif
