/ c library - semaphore functions
/
/	allocsem(number, usage)
/	freesem(number)
/
/	lock(number)
/	unlock(number)
/	tlock(number)
/
/	p(number)
/	v(number)
/	test(number)
/

.globl	_allocsem, _freesem
.globl	_lock, _unlock, _tlock
.globl	_p, _v, _test
.globl	cerror

INDIR = 0
SEMI4 = 62.
NLOCKS = 10.
TBLSZ = [NLOCKS + 7] \/ 8.
EINVAL = 22.

PV = 3
LOCK = 0
UNLOCK = 1
TLOCK = 2
P = 3
V = 4
TEST = 5
ALLOC = 6
FREE = 7

.text
_lock:
	movb	$LOCK,desire
	br	1f
_unlock:
	movb	$UNLOCK,desire
	br	1f
_tlock:
	movb	$TLOCK,desire
	br	1f
_p:
	movb	$P,desire
	br	1f
_v:
	movb	$V,desire
	br	1f
_test:
	movb	$TEST,desire
1:
	mov	r5,-(sp)
	mov	sp,r5
	mov	4(r5),flag
	bge	1f
	mov	$EINVAL,r0		/neg semi4 numbers bad
	jmp	cerror
1:
	jsr	pc,mposit
	bitb	mapmsk,*mapadd		/already allocated?
	bne	2f
	mov	$ALLOC,func
	cmpb	$P,desire
	bhi	1f
	movb	$PV,func+1
1:
	sys	INDIR; 9f
	bec	1f
	jmp	cerror
1:
	bisb	mapmsk,*mapadd
2:
	clr	func
	movb	desire,func
	sys	INDIR; 9f
	bec	1f
	jmp	cerror
1:
	mov	(sp)+,r5
	rts	pc

_allocsem:
	mov	r5,-(sp)
	mov	sp,r5
	mov	$ALLOC,func
	movb	6(r5),func+1
	mov	4(r5),flag
	sys	INDIR; 9f
	bec	1f
	jmp	cerror
1:
	mov	r0,flag
	jsr	pc,mposit
	bisb	mapmsk,*mapadd
	mov	flag,r0
	mov	(sp)+,r5
	rts	pc

_freesem:
	mov	r5,-(sp)
	mov	sp,r5
	mov	$FREE,func
	mov	4(r5),flag
	bmi	1f
	jsr	pc,mposit
	bicb	mapmsk,*mapadd
	br	2f
1:
	mov	$[TBLSZ-1],r0
1:
	clrb	bmap(r0)
	dec	r0
	bge	1b
2:
	sys	INDIR; 9f
	bec	1f
	jmp	cerror
1:
	clr	r0
	mov	(sp)+,r5
	rts	pc

mposit:					/ find bit map position
	cmp	$NLOCKS,flag
	bhi	1f
	movb	$1,mapmsk		/out of range...response
	mov	$mapmsk,mapadd		/will never fail
	rts	pc
1:
	mov	flag,r0
	mov	r0,r1
	ash	$-3,r1
	add	$bmap,r1
	mov	r1,mapadd
	mov	$1,r1
	bic	$!7,r0
	ash	r0,r1
	movb	r1,mapmsk
	rts	pc

.data
9:
	sys	SEMI4; func:..; flag:..
mapadd: ..
mapmsk:	.byte 0
desire:	.byte 0
bmap:
	. = . + TBLSZ
