/*
 * This file is subject to the terms and conditions of the GNU General Public
 * License.  See the file "COPYING" in the main directory of this archive
 * for more details.
 *
 * Copyright (C) Equator Technologies
 */

#ifndef _ASM_BSP_SEMAPHORE_H_
#define _ASM_BSP_SEMAPHORE_H_

/* Stolen from asm-i386/semaphore.h  -- khilman 2000/06/15 */

#include <linux/linkage.h>
#include <linux/wait.h>

#include <asm/system.h>
#include <asm/atomic.h>
#include <asm/spinlock.h>

struct semaphore {
	atomic_t count;
	int waking;
	struct wait_queue * wait;
};

#define MUTEX		((struct semaphore) { ATOMIC_INIT(1), 0, NULL })
#define MUTEX_LOCKED	((struct semaphore) { ATOMIC_INIT(0), 0, NULL })

#define init_MUTEX(x)			*(x)=MUTEX
#define init_MUTEX_LOCKED(x)		*(x)=MUTEX_LOCKED
#define DECLARE_MUTEX(name)		struct semaphore name=MUTEX
#define DECLARE_MUTEX_LOCKED(name)	struct semaphore name=MUTEX_LOCKED

asmlinkage void __down              (struct semaphore * sem);
asmlinkage int  __down_interruptible(struct semaphore * sem);
asmlinkage int  __down_trylock      (struct semaphore * sem);
asmlinkage void __up                (struct semaphore * sem);

extern spinlock_t semaphore_wake_lock;


extern inline void sema_init(struct semaphore * sem, int val)
{
       sem->waking= 0;
       atomic_set(&(sem->count), val);
       init_waitqueue(&sem->wait);
}


extern inline void down(struct semaphore * sem)
{
	if (atomic_dec_return(&sem->count) < 0)
		__down(sem);
}

extern inline int down_interruptible(struct semaphore * sem)
{
	int ret = 0;

	if (atomic_dec_return(&sem->count) < 0)
		ret = __down_interruptible(sem);
	return ret;
}

/*
 * down_trylock returns 0 on success, 1 if we failed to get the lock.
 *
 * We must manipulate count and waking simultaneously and atomically.
 * Do this by using ll/sc on the pair of 32-bit words.
 */
extern inline int down_trylock(struct semaphore * sem)
{
	int ret = 0;

	if (atomic_dec_return(&sem->count) < 0)
	   	ret = __down_trylock(sem);
	return ret;
}

/*
 * Note! This is subtle. We jump to wake people up only if
 * the semaphore was negative (== somebody was waiting on it).
 */
extern inline void up(struct semaphore * sem)
{
	if (atomic_inc_return(&sem->count) <= 0)
		__up(sem);
}

#endif	/* _ASM_BSP_SEMAPHORE_H_ */
