#include "../h/local.h"

#ifdef  SCCS_ID
static char SCCS_ID [] = "@(#)sys1.c    	3.5	 12:33:09 - 82/02/04 ";
#endif  SCCS_ID

#include "../h/param.h"
#include "../h/systm.h"
#include "../h/map.h"
#include "../h/dir.h"
#include "../h/user.h"
#include "../h/proc.h"
#include "../h/buf.h"
#include "../h/reg.h"
#include "../h/inode.h"
#include "../h/seg.h"
#include "../h/acct.h"

/*
 * exec system call, with and without environments.
 */
struct execa {
	char	*fname;
	char	**argp;
	char	**envp;
};

exec()
{
	((struct execa *)u.u_ap)->envp = NULL;
	exece();
}

exece()
{
	register nc;
	register char *cp;
	register struct buf *bp;
	register struct execa *uap;
#ifdef UCB_NKB
	int na, ne, ucp, ap, c;
	int bno_size;           /* num of PGSIZE blks to malloc */
	int bno_addr;           /* PGSIZE-blk num from malloc */
	daddr_t bno;            /* BSIZE-blk num for use in loops */
#else  UCB_NKB
	int na, ne, bno, ucp, ap, c;
#endif UCB_NKB
	struct inode *ip;

	if ((ip = namei(uchar, 0)) == NULL)
		return;
	bp = 0;
#ifdef UCB_NKB
	bno_addr = 0;
#else  UCB_NKB
	bno = 0;
#endif UCB_NKB
	if(access(ip, IEXEC))
		goto bad;
	if((ip->i_mode & IFMT) != IFREG ||
	   (ip->i_mode & (IEXEC|(IEXEC>>3)|(IEXEC>>6))) == 0) {
		u.u_error = EACCES;
		goto bad;
	}
	/*
	 * Collect arguments on "file" in swap space.
	 */
	na = 0;
	ne = 0;
	nc = 0;
	uap = (struct execa *)u.u_ap;
#ifdef  UCB_NKB
	/* The disk area used for the arg list has to be on a cluster
	 * boundary and has to be written a cluster at a time, so
	 * we need enough space so that the arg list will fit after
	 * 1. we round up bno_addr to a cluster boundary
	 * 2. we round up NCARGS to a cluster boundary
	 */
	bno_size = clrnd(bytetopage(NCARGS)) + CLSIZE;
	if ((bno_addr = malloc(swapmap, bno_size)) == 0)
		panic("Out of swap");
	bno = dbtofsb (clrnd (bno_addr + swplo));
#else   UCB_NKB
	if ((bno = malloc(swapmap,(NCARGS+BSIZE-1)/BSIZE)) == 0)
		panic("Out of swap");
#endif  UCB_NKB
	if (uap->argp) for (;;) {
		ap = NULL;
		if (uap->argp) {
			ap = fuword((caddr_t)uap->argp);
			uap->argp++;
		}
		if (ap==NULL && uap->envp) {
			uap->argp = NULL;
			if ((ap = fuword((caddr_t)uap->envp)) == NULL)
				break;
			uap->envp++;
			ne++;
		}
		if (ap==NULL)
			break;
		na++;
		if(ap == -1)
			u.u_error = EFAULT;
		do {
			if (nc >= NCARGS-1)
				u.u_error = E2BIG;
			if ((c = fubyte((caddr_t)ap++)) < 0)
				u.u_error = EFAULT;
			if (u.u_error)
				goto bad;
			if ((nc&BMASK) == 0) {
				if (bp)
					bawrite(bp);
#ifdef  UCB_NKB
				bp = getblk(swapdev, bno++);
#else   UCB_NKB
				bp = getblk(swapdev, swplo+bno+(nc>>BSHIFT));
#endif  UCB_NKB
				cp = bp->b_un.b_addr;
			}
			nc++;
			*cp++ = c;
		} while (c>0);
	}
	if (bp)
		bawrite(bp);
	bp = 0;
	nc = (nc + NBPW-1) & ~(NBPW-1);
	if (getxfile(ip, nc) || u.u_error)
		goto bad;

	/*
	 * copy back arglist
	 */

#ifdef DEC
	ucp = -nc - NBPW;
#else  DEC
	ucp = ctob(stoc(u.u_sseg) + u.u_ssize) - nc - NBPW;
#endif DEC
	ap = ucp - na*NBPW - 3*NBPW;
	u.u_ar0[RSP] = ap;
	suword((caddr_t)ap, na-ne);
	nc = 0;
#ifdef UCB_NKB
	bno = dbtofsb (clrnd (bno_addr + swplo));
#endif UCB_NKB
	for (;;) {
		ap += NBPW;
		if (na==ne) {
			suword((caddr_t)ap, 0);
			ap += NBPW;
		}
		if (--na < 0)
			break;
		suword((caddr_t)ap, ucp);
		do {
			if ((nc&BMASK) == 0) {
#ifdef  CGL_AGE
				if (bp) {
					bp->b_flags |= B_AGE;	/* abandon */
					brelse(bp);
				}
#else   CGL_AGE
				if (bp)
					brelse(bp);
#endif  CGL_AGE
#ifdef  UCB_NKB
				bp = bread(swapdev, bno++);
#else   UCB_NKB
				bp = bread(swapdev, swplo+bno+(nc>>BSHIFT));
#endif  UCB_NKB
				cp = bp->b_un.b_addr;
			}
			subyte((caddr_t)ucp++, (c = *cp++));
			nc++;
		} while(c&0377);
	}
	suword((caddr_t)ap, 0);
#ifndef DEC
	ucp = (ucp + NBPW-1) & ~(NBPW-1);
#endif  DEC
	suword((caddr_t)ucp, 0);
	setregs();
bad:
#ifdef  CGL_AGE
	if (bp) {
		bp->b_flags |= B_AGE;
		brelse(bp);
	}
#else   CGL_AGE
	if (bp)
		brelse(bp);
#endif  CGL_AGE
#ifdef  UCB_NKB
	if(bno_addr)
		mfree(swapmap, bno_size, bno_addr);
#else   UCB_NKB
	if(bno)
		mfree(swapmap, (NCARGS+BSIZE-1)/BSIZE, bno);
#endif  UCB_NKB
	iput(ip);
}

/*
 * Read in and set up memory for executed file.
 * Zero return is normal;
 * non-zero means only the text is being replaced
 */
getxfile(ip, nargc)
register struct inode *ip;
{
	register unsigned ds;
	register sep;
	register unsigned ts, ss;
	register i, overlay;
	long lsize;

	/*
	 * read in first few bytes
	 * of file for segment
	 * sizes:
	 * ux_mag = 407/410/411/405
	 *  407 is plain executable
	 *  410 is RO text
	 *  411 is separated ID
	 *  405 is overlaid text
	 */

	u.u_base = (caddr_t)&u.u_exdata;
	u.u_count = sizeof(u.u_exdata);
	u.u_offset = 0;
	u.u_segflg = 1;
	readi(ip);
	u.u_segflg = 0;
	if(u.u_error)
		goto bad;
	if (u.u_count!=0) {
		u.u_error = ENOEXEC;
		goto bad;
	}
	sep = 0;
	overlay = 0;
	if(u.u_exdata.ux_mag == 0407) {
		lsize = (long)u.u_exdata.ux_dsize + u.u_exdata.ux_tsize;
		u.u_exdata.ux_dsize = lsize;
		if (lsize != u.u_exdata.ux_dsize) {	/* check overflow */
			u.u_error = ENOMEM;
			goto bad;
		}
		u.u_exdata.ux_tsize = 0;
	} else if (u.u_exdata.ux_mag == 0411)
		sep++;
	else if (u.u_exdata.ux_mag == 0405)
		overlay++;
	else if (u.u_exdata.ux_mag != 0410) {
		u.u_error = ENOEXEC;
		goto bad;
	}
	if(u.u_exdata.ux_tsize!=0 && (ip->i_flag&ITEXT)==0 && ip->i_count!=1) {
		u.u_error = ETXTBSY;
		goto bad;
	}

	/*
	 * find text and data sizes
	 * try them out for possible
	 * overflow of max sizes
	 */
	ts = btoc(u.u_exdata.ux_tsize);
	lsize = (long)u.u_exdata.ux_dsize + u.u_exdata.ux_bsize;
	if (lsize != (unsigned)lsize) {
		u.u_error = ENOMEM;
		goto bad;
	}
	ds = btoc(lsize);
#ifdef DEC
	ss = SSIZE + btoc(nargc);
#else  DEC
	if ((ss = u.u_exdata.ux_ksize) == 0)
		ss = ctob(SSIZE);
	ss = btoc(ss + nargc);
#endif DEC
	if (overlay) {
		if (u.u_sep==0 && ctos(ts) != ctos(u.u_tsize) || nargc) {
			u.u_error = ENOMEM;
			goto bad;
		}
		ds = u.u_dsize;
		ss = u.u_ssize;
		sep = u.u_sep;
		xfree();
		xalloc(ip);
		u.u_ar0[PC] = u.u_exdata.ux_entloc & ~01;
	} else {
		if(estabur(ts, ds, ss, sep, RO))
			goto bad;
	
		/*
		 * allocate and clear core
		 * at this point, committed
		 * to the new image
		 */
	
		u.u_prof.pr_scale = 0;
		xfree();
		i = USIZE+ds+ss;
		expand(i);
		while(--i >= USIZE)
			clearseg(u.u_procp->p_addr+i);
		xalloc(ip);
	
		/*
		 * read in data segment
		 */
	
		estabur((unsigned)0, ds, (unsigned)0, 0, RO);
		u.u_base = 0;
		u.u_offset = sizeof(u.u_exdata)+u.u_exdata.ux_tsize;
		u.u_count = u.u_exdata.ux_dsize;
		readi(ip);
		/*
		 * set SUID/SGID protections, if no tracing
		 */
		if ((u.u_procp->p_flag&STRC)==0) {
			if(ip->i_mode&ISUID)
				if(u.u_uid != 0) {
					u.u_uid = ip->i_uid;
					u.u_procp->p_uid = ip->i_uid;
				}
			if(ip->i_mode&ISGID)
				u.u_gid = ip->i_gid;
		} else
			psignal(u.u_procp, SIGTRC);
	}
	u.u_tsize = ts;
	u.u_dsize = ds;
	u.u_ssize = ss;
	u.u_sep = sep;
	estabur(ts, ds, ss, sep, RO);
bad:
	return(overlay);
}

/*
 * Clear registers on exec
 */
setregs()
{
	register int *rp;
#ifdef  DEC
	register char *cp;
#else   DEC
	register int *cp;
	register savsp;
#endif  DEC
	register i;

	for(rp = &u.u_signal[0]; rp < &u.u_signal[NSIG]; rp++)
		if((*rp & 1) == 0)
			*rp = 0;
#ifdef  DEC
	for(cp = &regloc[0]; cp < &regloc[6];)
		u.u_ar0[*cp++] = 0;
	u.u_ar0[PC] = u.u_exdata.ux_entloc & ~01;
	for(rp = (int *)&u.u_fps; rp < (int *)&u.u_fps.u_fpregs[6];)
#else   DEC
	/*** Clear all regs except SP PC PS ***/
	savsp = u.u_ar0[RSP];
	for(cp = &regloc[0]; cp < &regloc[NREGS-2];)
		u.u_ar0[*cp++] = 0;
	u.u_ar0[RSP] = savsp;
	u.u_ar0[PC] = u.u_exdata.ux_entloc & ~01;
	for(rp = (int *)&u.u_fps; rp < (int *)(&u.u_fps+1);)
#endif  DEC
		*rp++ = 0;
	for(i=0; i<NOFILE; i++) {
		if (u.u_pofile[i]&EXCLOSE) {
			closef(u.u_ofile[i]);
			u.u_ofile[i] = NULL;
			u.u_pofile[i] &= ~EXCLOSE;
		}
	}
	/*
	 * Remember file name for accounting.
	 */
	u.u_acflag &= ~AFORK;
	bcopy((caddr_t)u.u_dbuf, (caddr_t)u.u_comm, DIRSIZ);
}

/*
 * exit system call:
 * pass back caller's arg
 */
rexit()
{
	register struct a {
		int	rval;
	} *uap;

	uap = (struct a *)u.u_ap;
	exit((uap->rval & 0377) << 8);
}

/*
 * Release resources.
 * Save u. area for parent to look at.
 * Enter zombie state.
 * Wake up parent and init processes,
 * and dispose of children.
 */
exit(rv)
{
	register int i;
	register struct proc *p, *q;
	register struct file *f;

	p = u.u_procp;
	p->p_flag &= ~(STRC|SULOCK);
	p->p_clktim = 0;
#ifdef	CGL_RTP
	/*
	 * If this is a "real time" process that is dying
	 * remove the rtpp flag.
	 */
	if (rtpp!=NULL && rtpp==p)
		rtpp = NULL;
#endif  CGL_RTP
	for(i=0; i<NSIG; i++)
		u.u_signal[i] = 1;
	for(i=0; i<NOFILE; i++) {
		f = u.u_ofile[i];
		u.u_ofile[i] = NULL;
		closef(f);
	}
	plock(u.u_cdir);
	iput(u.u_cdir);
	if (u.u_rdir) {
		plock(u.u_rdir);
		iput(u.u_rdir);
	}
	xfree();
	acct();
	mfree(coremap, p->p_size, p->p_addr);
	p->p_stat = SZOMB;
	((struct xproc *)p)->xp_xstat = rv;
	((struct xproc *)p)->xp_utime = u.u_cutime + u.u_utime;
	((struct xproc *)p)->xp_stime = u.u_cstime + u.u_stime;
	for(q = &proc[0]; q < procNPROC; q++)
		if(q->p_ppid == p->p_pid) {
			wakeup((caddr_t)&proc[1]);
			q->p_ppid = 1;
			if (q->p_stat==SSTOP)
				setrun(q);
		}
	for(q = &proc[0]; q < procNPROC; q++)
		if(p->p_ppid == q->p_pid) {
			wakeup((caddr_t)q);
			swtch();
			/* no return */
		}
	swtch();
}

/*
 * Wait system call.
 * Search for a terminated (zombie) child,
 * finally lay it to rest, and collect its status.
 * Look also for stopped (traced) children,
 * and pass back status from them.
 */
wait()
{
	register f;
	register struct proc *p;

	f = 0;

loop:
	for(p = &proc[0]; p < procNPROC; p++)
	if(p->p_ppid == u.u_procp->p_pid) {
		f++;
		if(p->p_stat == SZOMB) {
			u.u_r.r_val1 = p->p_pid;
			u.u_r.r_val2 = ((struct xproc *)p)->xp_xstat;
			u.u_cutime += ((struct xproc *)p)->xp_utime;
			u.u_cstime += ((struct xproc *)p)->xp_stime;
			p->p_pid = 0;
			p->p_ppid = 0;
			p->p_pgrp = 0;
			p->p_sig = 0;
			p->p_flag = 0;
			p->p_wchan = 0;
			p->p_stat = NULL;
			return;
		}
		if(p->p_stat == SSTOP) {
			if((p->p_flag&SWTED) == 0) {
				p->p_flag |= SWTED;
				u.u_r.r_val1 = p->p_pid;
				u.u_r.r_val2 = (fsig(p)<<8) | 0177;
				return;
			}
			continue;
		}
	}
	if(f) {
		sleep((caddr_t)u.u_procp, PWAIT);
		goto loop;
	}
	u.u_error = ECHILD;
}

/*
 * fork system call.
 */
fork()
{
	register struct proc *p1, *p2;
	register a;

	/*
	 * Make sure there's enough swap space for max
	 * core image, thus reducing chances of running out
	 */
	if ((a = malloc(swapmap, ctod(maxmem))) == 0) {
		u.u_error = ENOMEM;
		goto out;
	}
	mfree(swapmap, ctod(maxmem), a);
	a = 0;
	p2 = NULL;
	for(p1 = &proc[0]; p1 < procNPROC; p1++) {
		if (p1->p_stat==NULL && p2==NULL)
			p2 = p1;
		else {
			if (p1->p_uid==u.u_uid && p1->p_stat!=NULL)
				a++;
		}
	}
	/*
	 * Disallow if
	 *  No processes at all;
	 *  not su and too many procs owned; or
	 *  not su and there are 5 or less slots left
	 */
	if (p2==NULL || (u.u_uid!=0 && (p2>=&procNPROC[-5] || a>maxuprc))) {
		u.u_error = EAGAIN;
		goto out;
	}
	p1 = u.u_procp;
	if(newproc()) {
		u.u_r.r_val1 = p1->p_pid;
		u.u_start = time;
		u.u_cstime = 0;
		u.u_stime = 0;
		u.u_cutime = 0;
		u.u_utime = 0;
#ifdef	CGL_ACCT
		u.u_cgl.cgl_inblk = 0;
		u.u_cgl.cgl_oublk = 0;
		u.u_cgl.cgl_ntime = 0;
		u.u_cgl.cgl_ptime = 0;
#endif  CGL_ACCT
		u.u_acflag = AFORK;
		return;
	}
	u.u_r.r_val1 = p2->p_pid;

out:
#ifdef SVC6
	if (u.u_svc6)
		u.u_ar0[PC] += instrlen(u.u_ar0[PC]);
	else
#endif SVC6
	u.u_ar0[PC] += NBPW;
}

/*
 * break system call.
 *  -- bad planning: "break" is a dirty word in C.
 */
sbreak()
{
	struct a {
		char	*nsiz;
	};
	register a, n, d;
	int i;

	/*
	 * set n to new data size
	 * set d to new-old
	 * set n to new total size
	 */

	n = btoc((int)((struct a *)u.u_ap)->nsiz);
	if(!u.u_sep)
		n -= ctos(u.u_tsize) * stoc(1);
	if(n < 0)
		n = 0;
	d = n - u.u_dsize;
	n += USIZE+u.u_ssize;
	if(estabur(u.u_tsize, u.u_dsize+d, u.u_ssize, u.u_sep, RO))
		return;
	u.u_dsize += d;
	if(d > 0)
		goto bigger;
	a = u.u_procp->p_addr + n - u.u_ssize;
	i = n;
	n = u.u_ssize;
	while(n--) {
		copyseg(a-d, a);
		a++;
	}
	expand(i);
	return;

bigger:
	expand(n);
	a = u.u_procp->p_addr + n;
	n = u.u_ssize;
	while(n--) {
		a--;
		copyseg(a-d, a);
	}
	while(d--)
		clearseg(--a);
}
#ifdef SVC6

/*
 * instrlen:
 *	return the length of the instruction pointed to by ip
 * (in user space).
 */
instrlen(p)
register caddr_t p;
{
	register op;

	switch((op=fuibyte(p)) >> 4) {

	/* RR and SF */
	case 0:
	case 1:
	case 2:
	case 3:
	case 9:
	default:
		return(2);

	/* RI2 */
	case 15:
		return(6);

	/* RX1, RX2, RX3 */
	case 5:
	case 6:
	case 7:
	case 13:
rx:		if ((fuibyte(p+2)&0300) == 0100)
			return(6);
		return(4);

	/* odd cases */
	case 12:
		if (op <= (12<<4)+2)
			goto rx;
		return(4);

	case 14:
		if (op <= (14<<4)+9)
			goto rx;
		return(4);

	}
}
#endif SVC6
