#
/*
 *	Copyright 1973 Bell Telephone Laboratories Inc
 */

#include "../param.h"
#include "../user.h"
#include "../filsys.h"
#include "../file.h"
#include "../conf.h"
#include "../inode.h"
#include "../reg.h"

getf(f)
{
	register *fp, rf;

	rf = f;
	if(rf<0 || rf>=NOFILE)
		goto bad;
	fp = u.u_ofile[rf];
	if(fp == NULL) {
	bad:
		u.u_error = EBADF;
		fp = NULL;
	}
	return(fp);
}

closef(fp)
int *fp;
{
	register *rfp, *ip;

	rfp = fp;
	if(rfp->f_flag&FPIPE) {
		ip = rfp->f_inode;
		ip->i_mode =& ~(IREAD|IWRITE);
		wakeup(ip+1);
		wakeup(ip+2);
	}
	if(rfp->f_count <= 1)
		closei(rfp->f_inode, rfp->f_flag&FWRITE);
	rfp->f_count--;
}

closei(ip, rw)
int *ip;
{
	register *rip;
	register dev, maj;

	rip = ip;
	dev = rip->i_addr[0];
	maj = rip->i_addr[0].d_major;
	if(rip->i_count <= 1)
	switch(rip->i_mode&IFMT) {

	case IFCHR:
		(*cdevsw[maj].d_close)(dev, rw);
		break;

	case IFBLK:
		(*bdevsw[maj].d_close)(dev, rw);
	}
	iput(rip);
}

openi(ip, rw)
int *ip;
{
	register *rip;
	register dev, maj;

	rip = ip;
	dev = rip->i_addr[0];
	maj = rip->i_addr[0].d_major;
	switch(rip->i_mode&IFMT) {

	case IFCHR:
		if(maj >= nchrdev)
			goto bad;
		(*cdevsw[maj].d_open)(dev, rw);
		break;

	case IFBLK:
		if(maj >= nblkdev) {
		bad:
			u.u_error = ENXIO;
			return;
		}
		(*bdevsw[maj].d_open)(dev, rw);
	}
}

access(ip, mode)
int *ip;
{
	register *rip, m;

	rip = ip;
	m = mode;
	if(m == IWRITE && getfs(ip->i_dev)->s_ronly != 0) {
		u.u_error = EROFS;
		return(1);
	}
	if(u.u_uid == 0)
		return(0);
	if(u.u_uid != rip->i_uid) {
		m =>> 3;
		if(u.u_gid != rip->i_gid)
			m =>> 3;
	}
	if((rip->i_mode&m) != 0)
		return(0);
	u.u_error = EACCES;
	return(1);
}

owner(ip)
int *ip;
{

	if(u.u_uid == ip->i_uid)
		return(1);
	return(suser());
}

suser()
{

	if(u.u_uid == 0)
		return(1);
	u.u_error = EPERM;
	return(0);
}

ufalloc()
{
	register i;

	for (i=0; i<NOFILE; i++)
		if (u.u_ofile[i] == NULL) {
			u.u_ar0[R0] = i;
			return(i);
		}
	u.u_error = EMFILE;
	return(-1);
}

struct  file *maxfp;

falloc()
{
	register struct file *fp;
	register i;

	if ((i = ufalloc()) < 0)
		return(NULL);
	for (fp = &file[0]; fp < &file[NFILE]; fp++)
		if (fp->f_count==0) {
			u.u_ofile[i] = fp;
			fp->f_count++;
			fp->f_offset[0] = 0;
			fp->f_offset[1] = 0;
			if (fp>maxfp)
				maxfp = fp;
			return(fp);
		}
	printf("no file\n");
	u.u_error = ENFILE;
	return(NULL);
}
