Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.59
      1 /*	$NetBSD: kern_descrip.c,v 1.59 1999/05/05 20:01:08 thorpej Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  *
     40  *	@(#)kern_descrip.c	8.8 (Berkeley) 2/14/95
     41  */
     42 
     43 #include <sys/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/filedesc.h>
     46 #include <sys/kernel.h>
     47 #include <sys/vnode.h>
     48 #include <sys/proc.h>
     49 #include <sys/file.h>
     50 #include <sys/socket.h>
     51 #include <sys/socketvar.h>
     52 #include <sys/stat.h>
     53 #include <sys/ioctl.h>
     54 #include <sys/fcntl.h>
     55 #include <sys/malloc.h>
     56 #include <sys/pool.h>
     57 #include <sys/syslog.h>
     58 #include <sys/unistd.h>
     59 #include <sys/resourcevar.h>
     60 #include <sys/conf.h>
     61 
     62 #include <sys/mount.h>
     63 #include <sys/syscallargs.h>
     64 
     65 #include <vm/vm.h>
     66 
     67 /*
     68  * Descriptor management.
     69  */
     70 struct filelist filehead;	/* head of list of open files */
     71 int nfiles;			/* actual number of open files */
     72 struct pool file_pool;		/* memory pool for file structures */
     73 struct pool cwdi_pool;		/* memory pool for cwdinfo structures */
     74 
     75 static __inline void fd_used __P((struct filedesc *, int));
     76 static __inline void fd_unused __P((struct filedesc *, int));
     77 int finishdup __P((struct proc *, int, int, register_t *));
     78 
     79 static __inline void
     80 fd_used(fdp, fd)
     81 	register struct filedesc *fdp;
     82 	register int fd;
     83 {
     84 
     85 	if (fd > fdp->fd_lastfile)
     86 		fdp->fd_lastfile = fd;
     87 }
     88 
     89 static __inline void
     90 fd_unused(fdp, fd)
     91 	register struct filedesc *fdp;
     92 	register int fd;
     93 {
     94 
     95 	if (fd < fdp->fd_freefile)
     96 		fdp->fd_freefile = fd;
     97 #ifdef DIAGNOSTIC
     98 	if (fd > fdp->fd_lastfile)
     99 		panic("fd_unused: fd_lastfile inconsistent");
    100 #endif
    101 	if (fd == fdp->fd_lastfile) {
    102 		do {
    103 			fd--;
    104 		} while (fd >= 0 && fdp->fd_ofiles[fd] == NULL);
    105 		fdp->fd_lastfile = fd;
    106 	}
    107 }
    108 
    109 /*
    110  * System calls on descriptors.
    111  */
    112 
    113 /*
    114  * Duplicate a file descriptor.
    115  */
    116 /* ARGSUSED */
    117 int
    118 sys_dup(p, v, retval)
    119 	struct proc *p;
    120 	void *v;
    121 	register_t *retval;
    122 {
    123 	struct sys_dup_args /* {
    124 		syscallarg(int) fd;
    125 	} */ *uap = v;
    126 	struct file *fp;
    127 	register struct filedesc *fdp = p->p_fd;
    128 	register int old = SCARG(uap, fd);
    129 	int new;
    130 	int error;
    131 
    132 	if ((u_int)old >= fdp->fd_nfiles ||
    133 	    (fp = fdp->fd_ofiles[old]) == NULL ||
    134 	    (fp->f_iflags & FIF_WANTCLOSE) != 0)
    135 		return (EBADF);
    136 
    137 	FILE_USE(fp);
    138 
    139 	if ((error = fdalloc(p, 0, &new)) != 0) {
    140 		FILE_UNUSE(fp, p);
    141 		return (error);
    142 	}
    143 
    144 	/* finishdup() will unuse the descriptors for us */
    145 	return (finishdup(p, old, new, retval));
    146 }
    147 
    148 /*
    149  * Duplicate a file descriptor to a particular value.
    150  */
    151 /* ARGSUSED */
    152 int
    153 sys_dup2(p, v, retval)
    154 	struct proc *p;
    155 	void *v;
    156 	register_t *retval;
    157 {
    158 	struct sys_dup2_args /* {
    159 		syscallarg(int) from;
    160 		syscallarg(int) to;
    161 	} */ *uap = v;
    162 	struct file *fp;
    163 	register struct filedesc *fdp = p->p_fd;
    164 	register int old = SCARG(uap, from), new = SCARG(uap, to);
    165 	int i, error;
    166 
    167 	if ((u_int)old >= fdp->fd_nfiles ||
    168 	    (fp = fdp->fd_ofiles[old]) == NULL ||
    169 	    (fp->f_iflags & FIF_WANTCLOSE) != 0 ||
    170 	    (u_int)new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    171 	    (u_int)new >= maxfiles)
    172 		return (EBADF);
    173 	if (old == new) {
    174 		*retval = new;
    175 		return (0);
    176 	}
    177 
    178 	FILE_USE(fp);
    179 
    180 	if (new >= fdp->fd_nfiles) {
    181 		if ((error = fdalloc(p, new, &i)) != 0) {
    182 			FILE_UNUSE(fp, p);
    183 			return (error);
    184 		}
    185 		if (new != i)
    186 			panic("dup2: fdalloc");
    187 	} else {
    188 		(void) fdrelease(p, new);
    189 	}
    190 
    191 	/* finishdup() will unuse the descriptors for us */
    192 	return (finishdup(p, old, new, retval));
    193 }
    194 
    195 /*
    196  * The file control system call.
    197  */
    198 /* ARGSUSED */
    199 int
    200 sys_fcntl(p, v, retval)
    201 	struct proc *p;
    202 	void *v;
    203 	register_t *retval;
    204 {
    205 	register struct sys_fcntl_args /* {
    206 		syscallarg(int) fd;
    207 		syscallarg(int) cmd;
    208 		syscallarg(void *) arg;
    209 	} */ *uap = v;
    210 	int fd = SCARG(uap, fd);
    211 	register struct filedesc *fdp = p->p_fd;
    212 	register struct file *fp;
    213 	struct vnode *vp;
    214 	int i, tmp, error = 0, flg = F_POSIX;
    215 	struct flock fl;
    216 	int newmin;
    217 
    218 	if ((u_int)fd >= fdp->fd_nfiles ||
    219 	    (fp = fdp->fd_ofiles[fd]) == NULL ||
    220 	    (fp->f_iflags & FIF_WANTCLOSE) != 0)
    221 		return (EBADF);
    222 
    223 	FILE_USE(fp);
    224 
    225 	switch (SCARG(uap, cmd)) {
    226 
    227 	case F_DUPFD:
    228 		newmin = (long)SCARG(uap, arg);
    229 		if ((u_int)newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    230 		    (u_int)newmin >= maxfiles) {
    231 			error = EINVAL;
    232 			goto out;
    233 		}
    234 		if ((error = fdalloc(p, newmin, &i)) != 0)
    235 			goto out;
    236 
    237 		/* finishdup() will unuse the descriptors for us */
    238 		return (finishdup(p, fd, i, retval));
    239 
    240 	case F_GETFD:
    241 		*retval = fdp->fd_ofileflags[fd] & UF_EXCLOSE ? 1 : 0;
    242 		break;
    243 
    244 	case F_SETFD:
    245 		if ((long)SCARG(uap, arg) & 1)
    246 			fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
    247 		else
    248 			fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
    249 		break;
    250 
    251 	case F_GETFL:
    252 		*retval = OFLAGS(fp->f_flag);
    253 		break;
    254 
    255 	case F_SETFL:
    256 		fp->f_flag &= ~FCNTLFLAGS;
    257 		fp->f_flag |= FFLAGS((long)SCARG(uap, arg)) & FCNTLFLAGS;
    258 		tmp = fp->f_flag & FNONBLOCK;
    259 		error = (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
    260 		if (error)
    261 			goto out;
    262 		tmp = fp->f_flag & FASYNC;
    263 		error = (*fp->f_ops->fo_ioctl)(fp, FIOASYNC, (caddr_t)&tmp, p);
    264 		if (error == 0)
    265 			goto out;
    266 		fp->f_flag &= ~FNONBLOCK;
    267 		tmp = 0;
    268 		(void) (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
    269 		break;
    270 
    271 	case F_GETOWN:
    272 		if (fp->f_type == DTYPE_SOCKET) {
    273 			*retval = ((struct socket *)fp->f_data)->so_pgid;
    274 			goto out;
    275 		}
    276 		error = (*fp->f_ops->fo_ioctl)
    277 			(fp, TIOCGPGRP, (caddr_t)retval, p);
    278 		*retval = -*retval;
    279 		break;
    280 
    281 	case F_SETOWN:
    282 		if (fp->f_type == DTYPE_SOCKET) {
    283 			((struct socket *)fp->f_data)->so_pgid =
    284 			    (long)SCARG(uap, arg);
    285 			goto out;
    286 		}
    287 		if ((long)SCARG(uap, arg) <= 0) {
    288 			SCARG(uap, arg) = (void *)(-(long)SCARG(uap, arg));
    289 		} else {
    290 			struct proc *p1 = pfind((long)SCARG(uap, arg));
    291 			if (p1 == 0) {
    292 				error = ESRCH;
    293 				goto out;
    294 			}
    295 			SCARG(uap, arg) = (void *)(long)p1->p_pgrp->pg_id;
    296 		}
    297 		error = (*fp->f_ops->fo_ioctl)
    298 		    (fp, TIOCSPGRP, (caddr_t)&SCARG(uap, arg), p);
    299 		break;
    300 
    301 	case F_SETLKW:
    302 		flg |= F_WAIT;
    303 		/* Fall into F_SETLK */
    304 
    305 	case F_SETLK:
    306 		if (fp->f_type != DTYPE_VNODE) {
    307 			error = EINVAL;
    308 			goto out;
    309 		}
    310 		vp = (struct vnode *)fp->f_data;
    311 		/* Copy in the lock structure */
    312 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
    313 		    sizeof(fl));
    314 		if (error)
    315 			goto out;
    316 		if (fl.l_whence == SEEK_CUR)
    317 			fl.l_start += fp->f_offset;
    318 		switch (fl.l_type) {
    319 		case F_RDLCK:
    320 			if ((fp->f_flag & FREAD) == 0) {
    321 				error = EBADF;
    322 				goto out;
    323 			}
    324 			p->p_flag |= P_ADVLOCK;
    325 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg);
    326 			goto out;
    327 
    328 		case F_WRLCK:
    329 			if ((fp->f_flag & FWRITE) == 0) {
    330 				error = EBADF;
    331 				goto out;
    332 			}
    333 			p->p_flag |= P_ADVLOCK;
    334 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg);
    335 			goto out;
    336 
    337 		case F_UNLCK:
    338 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &fl,
    339 			    F_POSIX);
    340 			goto out;
    341 
    342 		default:
    343 			error = EINVAL;
    344 			goto out;
    345 		}
    346 
    347 	case F_GETLK:
    348 		if (fp->f_type != DTYPE_VNODE) {
    349 			error = EINVAL;
    350 			goto out;
    351 		}
    352 		vp = (struct vnode *)fp->f_data;
    353 		/* Copy in the lock structure */
    354 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
    355 		    sizeof(fl));
    356 		if (error)
    357 			goto out;
    358 		if (fl.l_whence == SEEK_CUR)
    359 			fl.l_start += fp->f_offset;
    360 		if (fl.l_type != F_RDLCK &&
    361 		    fl.l_type != F_WRLCK &&
    362 		    fl.l_type != F_UNLCK) {
    363 			error = EINVAL;
    364 			goto out;
    365 		}
    366 		error = VOP_ADVLOCK(vp, (caddr_t)p, F_GETLK, &fl, F_POSIX);
    367 		if (error)
    368 			goto out;
    369 		error = copyout((caddr_t)&fl, (caddr_t)SCARG(uap, arg),
    370 		    sizeof(fl));
    371 		break;
    372 
    373 	default:
    374 		error = EINVAL;
    375 	}
    376 
    377  out:
    378 	FILE_UNUSE(fp, p);
    379 	return (error);
    380 }
    381 
    382 /*
    383  * Common code for dup, dup2, and fcntl(F_DUPFD).
    384  */
    385 int
    386 finishdup(p, old, new, retval)
    387 	struct proc *p;
    388 	int old, new;
    389 	register_t *retval;
    390 {
    391 	struct filedesc *fdp = p->p_fd;
    392 	struct file *fp;
    393 
    394 	/*
    395 	 * Note: `old' is already used for us.
    396 	 */
    397 
    398 	fp = fdp->fd_ofiles[old];
    399 	fdp->fd_ofiles[new] = fp;
    400 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
    401 	fp->f_count++;
    402 	fd_used(fdp, new);
    403 	*retval = new;
    404 	FILE_UNUSE(fp, p);
    405 	return (0);
    406 }
    407 
    408 int
    409 fdrelease(p, fd)
    410 	struct proc *p;
    411 	int fd;
    412 {
    413 	register struct filedesc *fdp = p->p_fd;
    414 	register struct file **fpp, *fp;
    415 	register char *pf;
    416 
    417 	fpp = &fdp->fd_ofiles[fd];
    418 	fp = *fpp;
    419 	if (fp == NULL)
    420 		return (EBADF);
    421 
    422 	FILE_USE(fp);
    423 
    424 	pf = &fdp->fd_ofileflags[fd];
    425 	if (*pf & UF_MAPPED) {
    426 		/* XXX: USELESS? XXXCDC check it */
    427 		p->p_fd->fd_ofileflags[fd] &= ~UF_MAPPED;
    428 	}
    429 	*fpp = NULL;
    430 	*pf = 0;
    431 	fd_unused(fdp, fd);
    432 	return (closef(fp, p));
    433 }
    434 
    435 /*
    436  * Close a file descriptor.
    437  */
    438 /* ARGSUSED */
    439 int
    440 sys_close(p, v, retval)
    441 	struct proc *p;
    442 	void *v;
    443 	register_t *retval;
    444 {
    445 	struct sys_close_args /* {
    446 		syscallarg(int) fd;
    447 	} */ *uap = v;
    448 	int fd = SCARG(uap, fd);
    449 	register struct filedesc *fdp = p->p_fd;
    450 
    451 	if ((u_int)fd >= fdp->fd_nfiles)
    452 		return (EBADF);
    453 	return (fdrelease(p, fd));
    454 }
    455 
    456 /*
    457  * Return status information about a file descriptor.
    458  */
    459 /* ARGSUSED */
    460 int
    461 sys___fstat13(p, v, retval)
    462 	struct proc *p;
    463 	void *v;
    464 	register_t *retval;
    465 {
    466 	register struct sys___fstat13_args /* {
    467 		syscallarg(int) fd;
    468 		syscallarg(struct stat *) sb;
    469 	} */ *uap = v;
    470 	int fd = SCARG(uap, fd);
    471 	register struct filedesc *fdp = p->p_fd;
    472 	register struct file *fp;
    473 	struct stat ub;
    474 	int error;
    475 
    476 	if ((u_int)fd >= fdp->fd_nfiles ||
    477 	    (fp = fdp->fd_ofiles[fd]) == NULL ||
    478 	    (fp->f_iflags & FIF_WANTCLOSE) != 0)
    479 		return (EBADF);
    480 
    481 	FILE_USE(fp);
    482 
    483 	switch (fp->f_type) {
    484 
    485 	case DTYPE_VNODE:
    486 		error = vn_stat((struct vnode *)fp->f_data, &ub, p);
    487 		break;
    488 
    489 	case DTYPE_SOCKET:
    490 		error = soo_stat((struct socket *)fp->f_data, &ub);
    491 		break;
    492 
    493 	default:
    494 		panic("fstat");
    495 		/*NOTREACHED*/
    496 	}
    497 	if (error == 0)
    498 		error = copyout(&ub, SCARG(uap, sb), sizeof(ub));
    499 	FILE_UNUSE(fp, p);
    500 	return (error);
    501 }
    502 
    503 /*
    504  * Return pathconf information about a file descriptor.
    505  */
    506 /* ARGSUSED */
    507 int
    508 sys_fpathconf(p, v, retval)
    509 	struct proc *p;
    510 	void *v;
    511 	register_t *retval;
    512 {
    513 	register struct sys_fpathconf_args /* {
    514 		syscallarg(int) fd;
    515 		syscallarg(int) name;
    516 	} */ *uap = v;
    517 	int fd = SCARG(uap, fd);
    518 	struct filedesc *fdp = p->p_fd;
    519 	struct file *fp;
    520 	struct vnode *vp;
    521 	int error = 0;
    522 
    523 	if ((u_int)fd >= fdp->fd_nfiles ||
    524 	    (fp = fdp->fd_ofiles[fd]) == NULL ||
    525 	    (fp->f_iflags & FIF_WANTCLOSE) != 0)
    526 		return (EBADF);
    527 
    528 	FILE_USE(fp);
    529 
    530 	switch (fp->f_type) {
    531 
    532 	case DTYPE_SOCKET:
    533 		if (SCARG(uap, name) != _PC_PIPE_BUF)
    534 			error = EINVAL;
    535 		else
    536 			*retval = PIPE_BUF;
    537 		break;
    538 
    539 	case DTYPE_VNODE:
    540 		vp = (struct vnode *)fp->f_data;
    541 		error = VOP_PATHCONF(vp, SCARG(uap, name), retval);
    542 		break;
    543 
    544 	default:
    545 		panic("fpathconf");
    546 	}
    547 
    548 	FILE_UNUSE(fp, p);
    549 	return (error);
    550 }
    551 
    552 /*
    553  * Allocate a file descriptor for the process.
    554  */
    555 int fdexpand;
    556 
    557 int
    558 fdalloc(p, want, result)
    559 	struct proc *p;
    560 	int want;
    561 	int *result;
    562 {
    563 	register struct filedesc *fdp = p->p_fd;
    564 	register int i;
    565 	int lim, last, nfiles;
    566 	struct file **newofile;
    567 	char *newofileflags;
    568 
    569 	/*
    570 	 * Search for a free descriptor starting at the higher
    571 	 * of want or fd_freefile.  If that fails, consider
    572 	 * expanding the ofile array.
    573 	 */
    574 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    575 	for (;;) {
    576 		last = min(fdp->fd_nfiles, lim);
    577 		if ((i = want) < fdp->fd_freefile)
    578 			i = fdp->fd_freefile;
    579 		for (; i < last; i++) {
    580 			if (fdp->fd_ofiles[i] == NULL) {
    581 				fd_used(fdp, i);
    582 				if (want <= fdp->fd_freefile)
    583 					fdp->fd_freefile = i;
    584 				*result = i;
    585 				return (0);
    586 			}
    587 		}
    588 
    589 		/*
    590 		 * No space in current array.  Expand?
    591 		 */
    592 		if (fdp->fd_nfiles >= lim)
    593 			return (EMFILE);
    594 		if (fdp->fd_nfiles < NDEXTENT)
    595 			nfiles = NDEXTENT;
    596 		else
    597 			nfiles = 2 * fdp->fd_nfiles;
    598 		MALLOC(newofile, struct file **, nfiles * OFILESIZE,
    599 		    M_FILEDESC, M_WAITOK);
    600 		newofileflags = (char *) &newofile[nfiles];
    601 		/*
    602 		 * Copy the existing ofile and ofileflags arrays
    603 		 * and zero the new portion of each array.
    604 		 */
    605 		memcpy(newofile, fdp->fd_ofiles,
    606 			(i = sizeof(struct file *) * fdp->fd_nfiles));
    607 		memset((char *)newofile + i, 0, nfiles * sizeof(struct file *) - i);
    608 		memcpy(newofileflags, fdp->fd_ofileflags,
    609 			(i = sizeof(char) * fdp->fd_nfiles));
    610 		memset(newofileflags + i, 0, nfiles * sizeof(char) - i);
    611 		if (fdp->fd_nfiles > NDFILE)
    612 			FREE(fdp->fd_ofiles, M_FILEDESC);
    613 		fdp->fd_ofiles = newofile;
    614 		fdp->fd_ofileflags = newofileflags;
    615 		fdp->fd_nfiles = nfiles;
    616 		fdexpand++;
    617 	}
    618 }
    619 
    620 /*
    621  * Check to see whether n user file descriptors
    622  * are available to the process p.
    623  */
    624 int
    625 fdavail(p, n)
    626 	struct proc *p;
    627 	register int n;
    628 {
    629 	register struct filedesc *fdp = p->p_fd;
    630 	register struct file **fpp;
    631 	register int i, lim;
    632 
    633 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    634 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
    635 		return (1);
    636 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
    637 	for (i = min(lim,fdp->fd_nfiles) - fdp->fd_freefile; --i >= 0; fpp++)
    638 		if (*fpp == NULL && --n <= 0)
    639 			return (1);
    640 	return (0);
    641 }
    642 
    643 /*
    644  * Initialize the data structures necessary for managing files.
    645  */
    646 void
    647 finit()
    648 {
    649 
    650 	pool_init(&file_pool, sizeof(struct file), 0, 0, 0, "filepl",
    651 	    0, pool_page_alloc_nointr, pool_page_free_nointr, M_FILE);
    652 	pool_init(&cwdi_pool, sizeof(struct cwdinfo), 0, 0, 0, "cwdipl",
    653 	    0, pool_page_alloc_nointr, pool_page_free_nointr, M_FILEDESC);
    654 }
    655 
    656 /*
    657  * Create a new open file structure and allocate
    658  * a file decriptor for the process that refers to it.
    659  */
    660 int
    661 falloc(p, resultfp, resultfd)
    662 	register struct proc *p;
    663 	struct file **resultfp;
    664 	int *resultfd;
    665 {
    666 	register struct file *fp, *fq;
    667 	int error, i;
    668 
    669 	if ((error = fdalloc(p, 0, &i)) != 0)
    670 		return (error);
    671 	if (nfiles >= maxfiles) {
    672 		tablefull("file");
    673 		return (ENFILE);
    674 	}
    675 	/*
    676 	 * Allocate a new file descriptor.
    677 	 * If the process has file descriptor zero open, add to the list
    678 	 * of open files at that point, otherwise put it at the front of
    679 	 * the list of open files.
    680 	 */
    681 	nfiles++;
    682 	fp = pool_get(&file_pool, PR_WAITOK);
    683 	memset(fp, 0, sizeof(struct file));
    684 	if ((fq = p->p_fd->fd_ofiles[0]) != NULL) {
    685 		LIST_INSERT_AFTER(fq, fp, f_list);
    686 	} else {
    687 		LIST_INSERT_HEAD(&filehead, fp, f_list);
    688 	}
    689 	p->p_fd->fd_ofiles[i] = fp;
    690 	fp->f_count = 1;
    691 	fp->f_cred = p->p_ucred;
    692 	crhold(fp->f_cred);
    693 	if (resultfp) {
    694 		FILE_USE(fp);
    695 		*resultfp = fp;
    696 	}
    697 	if (resultfd)
    698 		*resultfd = i;
    699 	return (0);
    700 }
    701 
    702 /*
    703  * Free a file descriptor.
    704  */
    705 void
    706 ffree(fp)
    707 	register struct file *fp;
    708 {
    709 
    710 #ifdef DIAGNOSTIC
    711 	if (fp->f_usecount)
    712 		panic("ffree");
    713 #endif
    714 
    715 	LIST_REMOVE(fp, f_list);
    716 	crfree(fp->f_cred);
    717 #ifdef DIAGNOSTIC
    718 	fp->f_count = 0;
    719 #endif
    720 	nfiles--;
    721 	pool_put(&file_pool, fp);
    722 }
    723 
    724 /*
    725  * Create an initial cwdinfo structure, using the same current and root
    726  * directories as p.
    727  */
    728 struct cwdinfo *
    729 cwdinit(p)
    730 	struct proc *p;
    731 {
    732 	struct cwdinfo *cwdi;
    733 	extern int cmask;
    734 
    735 	cwdi = pool_get(&cwdi_pool, PR_WAITOK);
    736 
    737 	cwdi->cwdi_cdir = p->p_cwdi->cwdi_cdir;
    738 	VREF(cwdi->cwdi_cdir);
    739 	cwdi->cwdi_rdir = p->p_cwdi->cwdi_rdir;
    740 	if (cwdi->cwdi_rdir)
    741 		VREF(cwdi->cwdi_rdir);
    742 	cwdi->cwdi_cmask = cmask;
    743 	cwdi->cwdi_refcnt = 1;
    744 
    745 	return (cwdi);
    746 }
    747 
    748 /*
    749  * Make p2 share p1's cwdinfo.
    750  */
    751 void
    752 cwdshare(p1, p2)
    753 	struct proc *p1, *p2;
    754 {
    755 
    756 	p2->p_cwdi = p1->p_cwdi;
    757 	p1->p_cwdi->cwdi_refcnt++;
    758 }
    759 
    760 /*
    761  * Make this process not share its cwdinfo structure, maintaining
    762  * all cwdinfo state.
    763  */
    764 void
    765 cwdunshare(p)
    766 	struct proc *p;
    767 {
    768 	struct cwdinfo *newcwdi;
    769 
    770 	if (p->p_cwdi->cwdi_refcnt == 1)
    771 		return;
    772 
    773 	newcwdi = cwdinit(p);
    774 	cwdfree(p);
    775 	p->p_cwdi = newcwdi;
    776 }
    777 
    778 /*
    779  * Release a cwdinfo structure.
    780  */
    781 void
    782 cwdfree(p)
    783 	struct proc *p;
    784 {
    785 	struct cwdinfo *cwdi = p->p_cwdi;
    786 
    787 	if (--cwdi->cwdi_refcnt > 0)
    788 		return;
    789 
    790 	p->p_cwdi = NULL;
    791 
    792 	vrele(cwdi->cwdi_cdir);
    793 	if (cwdi->cwdi_rdir)
    794 		vrele(cwdi->cwdi_rdir);
    795 	pool_put(&cwdi_pool, cwdi);
    796 }
    797 
    798 /*
    799  * Create an initial filedesc structure, using the same current and root
    800  * directories as p.
    801  */
    802 struct filedesc *
    803 fdinit(p)
    804 	struct proc *p;
    805 {
    806 	struct filedesc0 *newfdp;
    807 
    808 	MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
    809 	    M_FILEDESC, M_WAITOK);
    810 	memset(newfdp, 0, sizeof(struct filedesc0));
    811 
    812 	fdinit1(newfdp);
    813 
    814 	return (&newfdp->fd_fd);
    815 }
    816 
    817 /*
    818  * Initialize a file descriptor table.
    819  */
    820 void
    821 fdinit1(newfdp)
    822 	struct filedesc0 *newfdp;
    823 {
    824 
    825 	newfdp->fd_fd.fd_refcnt = 1;
    826 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
    827 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
    828 	newfdp->fd_fd.fd_nfiles = NDFILE;
    829 }
    830 
    831 /*
    832  * Make p2 share p1's filedesc structure.
    833  */
    834 void
    835 fdshare(p1, p2)
    836 	struct proc *p1, *p2;
    837 {
    838 
    839 	p2->p_fd = p1->p_fd;
    840 	p1->p_fd->fd_refcnt++;
    841 }
    842 
    843 /*
    844  * Make this process not share its filedesc structure, maintaining
    845  * all file descriptor state.
    846  */
    847 void
    848 fdunshare(p)
    849 	struct proc *p;
    850 {
    851 	struct filedesc *newfd;
    852 
    853 	if (p->p_fd->fd_refcnt == 1)
    854 		return;
    855 
    856 	newfd = fdcopy(p);
    857 	fdfree(p);
    858 	p->p_fd = newfd;
    859 }
    860 
    861 /*
    862  * Clear a process's fd table.
    863  */
    864 void
    865 fdclear(p)
    866 	struct proc *p;
    867 {
    868 	struct filedesc *newfd;
    869 
    870 	newfd = fdinit(p);
    871 	fdfree(p);
    872 	p->p_fd = newfd;
    873 }
    874 
    875 /*
    876  * Copy a filedesc structure.
    877  */
    878 struct filedesc *
    879 fdcopy(p)
    880 	struct proc *p;
    881 {
    882 	register struct filedesc *newfdp, *fdp = p->p_fd;
    883 	register struct file **fpp;
    884 	register int i;
    885 
    886 	MALLOC(newfdp, struct filedesc *, sizeof(struct filedesc0),
    887 	    M_FILEDESC, M_WAITOK);
    888 	memcpy(newfdp, fdp, sizeof(struct filedesc));
    889 	newfdp->fd_refcnt = 1;
    890 
    891 	/*
    892 	 * If the number of open files fits in the internal arrays
    893 	 * of the open file structure, use them, otherwise allocate
    894 	 * additional memory for the number of descriptors currently
    895 	 * in use.
    896 	 */
    897 	if (newfdp->fd_lastfile < NDFILE) {
    898 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
    899 		newfdp->fd_ofileflags =
    900 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
    901 		i = NDFILE;
    902 	} else {
    903 		/*
    904 		 * Compute the smallest multiple of NDEXTENT needed
    905 		 * for the file descriptors currently in use,
    906 		 * allowing the table to shrink.
    907 		 */
    908 		i = newfdp->fd_nfiles;
    909 		while (i >= 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
    910 			i /= 2;
    911 		MALLOC(newfdp->fd_ofiles, struct file **, i * OFILESIZE,
    912 		    M_FILEDESC, M_WAITOK);
    913 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
    914 	}
    915 	newfdp->fd_nfiles = i;
    916 	memcpy(newfdp->fd_ofiles, fdp->fd_ofiles, i * sizeof(struct file **));
    917 	memcpy(newfdp->fd_ofileflags, fdp->fd_ofileflags, i * sizeof(char));
    918 	fpp = newfdp->fd_ofiles;
    919 	for (i = newfdp->fd_lastfile; i >= 0; i--, fpp++)
    920 		if (*fpp != NULL)
    921 			(*fpp)->f_count++;
    922 	return (newfdp);
    923 }
    924 
    925 /*
    926  * Release a filedesc structure.
    927  */
    928 void
    929 fdfree(p)
    930 	struct proc *p;
    931 {
    932 	register struct filedesc *fdp = p->p_fd;
    933 	register struct file **fpp, *fp;
    934 	register int i;
    935 
    936 	if (--fdp->fd_refcnt > 0)
    937 		return;
    938 	fpp = fdp->fd_ofiles;
    939 	for (i = fdp->fd_lastfile; i >= 0; i--, fpp++) {
    940 		fp = *fpp;
    941 		if (fp != NULL) {
    942 			*fpp = NULL;
    943 			FILE_USE(fp);
    944 			(void) closef(fp, p);
    945 		}
    946 	}
    947 	p->p_fd = NULL;
    948 	if (fdp->fd_nfiles > NDFILE)
    949 		FREE(fdp->fd_ofiles, M_FILEDESC);
    950 	FREE(fdp, M_FILEDESC);
    951 }
    952 
    953 /*
    954  * Internal form of close.
    955  * Decrement reference count on file structure.
    956  * Note: p may be NULL when closing a file
    957  * that was being passed in a message.
    958  *
    959  * Note: we expect the caller is holding a usecount, and expects us
    960  * to drop it (the caller thinks the file is going away forever).
    961  */
    962 int
    963 closef(fp, p)
    964 	register struct file *fp;
    965 	register struct proc *p;
    966 {
    967 	struct vnode *vp;
    968 	struct flock lf;
    969 	int error;
    970 
    971 	if (fp == NULL)
    972 		return (0);
    973 
    974 	/*
    975 	 * POSIX record locking dictates that any close releases ALL
    976 	 * locks owned by this process.  This is handled by setting
    977 	 * a flag in the unlock to free ONLY locks obeying POSIX
    978 	 * semantics, and not to free BSD-style file locks.
    979 	 * If the descriptor was in a message, POSIX-style locks
    980 	 * aren't passed with the descriptor.
    981 	 */
    982 	if (p && (p->p_flag & P_ADVLOCK) && fp->f_type == DTYPE_VNODE) {
    983 		lf.l_whence = SEEK_SET;
    984 		lf.l_start = 0;
    985 		lf.l_len = 0;
    986 		lf.l_type = F_UNLCK;
    987 		vp = (struct vnode *)fp->f_data;
    988 		(void) VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_POSIX);
    989 	}
    990 
    991 	/*
    992 	 * If WANTCLOSE is set, then the reference count on the file
    993 	 * is 0, but there were multiple users of the file.  This can
    994 	 * happen if a filedesc structure is shared by multiple
    995 	 * processes.
    996 	 */
    997 	if (fp->f_iflags & FIF_WANTCLOSE) {
    998 		/*
    999 		 * Another user of the file is already closing, and is
   1000 		 * simply waiting for other users of the file to drain.
   1001 		 * Release our usecount, and wake up the closer if it
   1002 		 * is the only remaining use.
   1003 		 */
   1004 #ifdef DIAGNOSTIC
   1005 		if (fp->f_count != 0)
   1006 			panic("closef: wantclose and count != 0");
   1007 		if (fp->f_usecount < 2)
   1008 			panic("closef: wantclose and usecount < 2");
   1009 #endif
   1010 		if (--fp->f_usecount == 1)
   1011 			wakeup(&fp->f_usecount);
   1012 		return (0);
   1013 	} else {
   1014 		/*
   1015 		 * Decrement the reference count.  If we were not the
   1016 		 * last reference, then release our use and just
   1017 		 * return.
   1018 		 */
   1019 		if (--fp->f_count > 0) {
   1020 #ifdef DIAGNOSTIC
   1021 			if (fp->f_usecount < 1)
   1022 				panic("closef: no wantclose and usecount < 1");
   1023 #endif
   1024 			fp->f_usecount--;
   1025 			return (0);
   1026 		}
   1027 		if (fp->f_count < 0)
   1028 			panic("closef: count < 0");
   1029 	}
   1030 
   1031 	/*
   1032 	 * The reference count is now 0.  However, there may be
   1033 	 * multiple potential users of this file.  This can happen
   1034 	 * if multiple processes shared a single filedesc structure.
   1035 	 *
   1036 	 * Notify these potential users that the file is closing.
   1037 	 * This will prevent them from adding additional uses to
   1038 	 * the file.
   1039 	 */
   1040 	fp->f_iflags |= FIF_WANTCLOSE;
   1041 
   1042 	/*
   1043 	 * We expect the caller to add a use to the file.  So, if we
   1044 	 * are the last user, usecount will be 1.  If it is not, we
   1045 	 * must wait for the usecount to drain.  When it drains back
   1046 	 * to 1, we will be awakened so that we may proceed with the
   1047 	 * close.
   1048 	 */
   1049 #ifdef DIAGNOSTIC
   1050 	if (fp->f_usecount < 1)
   1051 		panic("closef: usecount < 1");
   1052 #endif
   1053 	while (fp->f_usecount > 1)
   1054 		(void) tsleep(&fp->f_usecount, PRIBIO, "closef", 0);
   1055 #ifdef DIAGNOSTIC
   1056 	if (fp->f_usecount != 1)
   1057 		panic("closef: usecount != 1");
   1058 #endif
   1059 
   1060 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
   1061 		lf.l_whence = SEEK_SET;
   1062 		lf.l_start = 0;
   1063 		lf.l_len = 0;
   1064 		lf.l_type = F_UNLCK;
   1065 		vp = (struct vnode *)fp->f_data;
   1066 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1067 	}
   1068 	if (fp->f_ops)
   1069 		error = (*fp->f_ops->fo_close)(fp, p);
   1070 	else
   1071 		error = 0;
   1072 
   1073 	/* Nothing references the file now, drop the final use (us). */
   1074 	fp->f_usecount--;
   1075 
   1076 	ffree(fp);
   1077 	return (error);
   1078 }
   1079 
   1080 /*
   1081  * Apply an advisory lock on a file descriptor.
   1082  *
   1083  * Just attempt to get a record lock of the requested type on
   1084  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
   1085  */
   1086 /* ARGSUSED */
   1087 int
   1088 sys_flock(p, v, retval)
   1089 	struct proc *p;
   1090 	void *v;
   1091 	register_t *retval;
   1092 {
   1093 	register struct sys_flock_args /* {
   1094 		syscallarg(int) fd;
   1095 		syscallarg(int) how;
   1096 	} */ *uap = v;
   1097 	int fd = SCARG(uap, fd);
   1098 	int how = SCARG(uap, how);
   1099 	register struct filedesc *fdp = p->p_fd;
   1100 	register struct file *fp;
   1101 	struct vnode *vp;
   1102 	struct flock lf;
   1103 	int error = 0;
   1104 
   1105 	if ((u_int)fd >= fdp->fd_nfiles ||
   1106 	    (fp = fdp->fd_ofiles[fd]) == NULL ||
   1107 	    (fp->f_iflags & FIF_WANTCLOSE) != 0)
   1108 		return (EBADF);
   1109 
   1110 	FILE_USE(fp);
   1111 
   1112 	if (fp->f_type != DTYPE_VNODE) {
   1113 		error = EOPNOTSUPP;
   1114 		goto out;
   1115 	}
   1116 
   1117 	vp = (struct vnode *)fp->f_data;
   1118 	lf.l_whence = SEEK_SET;
   1119 	lf.l_start = 0;
   1120 	lf.l_len = 0;
   1121 	if (how & LOCK_UN) {
   1122 		lf.l_type = F_UNLCK;
   1123 		fp->f_flag &= ~FHASLOCK;
   1124 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1125 		goto out;
   1126 	}
   1127 	if (how & LOCK_EX)
   1128 		lf.l_type = F_WRLCK;
   1129 	else if (how & LOCK_SH)
   1130 		lf.l_type = F_RDLCK;
   1131 	else {
   1132 		error = EINVAL;
   1133 		goto out;
   1134 	}
   1135 	fp->f_flag |= FHASLOCK;
   1136 	if (how & LOCK_NB)
   1137 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK);
   1138 	else
   1139 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
   1140 		    F_FLOCK|F_WAIT);
   1141  out:
   1142 	FILE_UNUSE(fp, p);
   1143 	return (error);
   1144 }
   1145 
   1146 /*
   1147  * File Descriptor pseudo-device driver (/dev/fd/).
   1148  *
   1149  * Opening minor device N dup()s the file (if any) connected to file
   1150  * descriptor N belonging to the calling process.  Note that this driver
   1151  * consists of only the ``open()'' routine, because all subsequent
   1152  * references to this file will be direct to the other driver.
   1153  */
   1154 /* ARGSUSED */
   1155 int
   1156 filedescopen(dev, mode, type, p)
   1157 	dev_t dev;
   1158 	int mode, type;
   1159 	struct proc *p;
   1160 {
   1161 
   1162 	/*
   1163 	 * XXX Kludge: set curproc->p_dupfd to contain the value of the
   1164 	 * the file descriptor being sought for duplication. The error
   1165 	 * return ensures that the vnode for this device will be released
   1166 	 * by vn_open. Open will detect this special error and take the
   1167 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
   1168 	 * will simply report the error.
   1169 	 */
   1170 	p->p_dupfd = minor(dev);
   1171 	return (ENODEV);
   1172 }
   1173 
   1174 /*
   1175  * Duplicate the specified descriptor to a free descriptor.
   1176  */
   1177 int
   1178 dupfdopen(p, indx, dfd, mode, error)
   1179 	struct proc *p;
   1180 	int indx, dfd, mode, error;
   1181 {
   1182 	struct filedesc *fdp = p->p_fd;
   1183 	struct file *wfp;
   1184 	struct file *fp;
   1185 
   1186 	/*
   1187 	 * If the to-be-dup'd fd number is greater than the allowed number
   1188 	 * of file descriptors, or the fd to be dup'd has already been
   1189 	 * closed, reject.  Note, check for new == old is necessary as
   1190 	 * falloc could allocate an already closed to-be-dup'd descriptor
   1191 	 * as the new descriptor.
   1192 	 */
   1193 	fp = fdp->fd_ofiles[indx];
   1194 	if ((u_int)dfd >= fdp->fd_nfiles ||
   1195 	    (wfp = fdp->fd_ofiles[dfd]) == NULL ||
   1196 	    (wfp->f_iflags & FIF_WANTCLOSE) != 0 ||
   1197 	    fp == wfp)
   1198 		return (EBADF);
   1199 
   1200 	FILE_USE(wfp);
   1201 
   1202 	/*
   1203 	 * There are two cases of interest here.
   1204 	 *
   1205 	 * For ENODEV simply dup (dfd) to file descriptor
   1206 	 * (indx) and return.
   1207 	 *
   1208 	 * For ENXIO steal away the file structure from (dfd) and
   1209 	 * store it in (indx).  (dfd) is effectively closed by
   1210 	 * this operation.
   1211 	 *
   1212 	 * Any other error code is just returned.
   1213 	 */
   1214 	switch (error) {
   1215 	case ENODEV:
   1216 		/*
   1217 		 * Check that the mode the file is being opened for is a
   1218 		 * subset of the mode of the existing descriptor.
   1219 		 */
   1220 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
   1221 			FILE_UNUSE(wfp, p);
   1222 			return (EACCES);
   1223 		}
   1224 		fdp->fd_ofiles[indx] = wfp;
   1225 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1226 		wfp->f_count++;
   1227 		fd_used(fdp, indx);
   1228 		FILE_UNUSE(wfp, p);
   1229 		return (0);
   1230 
   1231 	case ENXIO:
   1232 		/*
   1233 		 * Steal away the file pointer from dfd, and stuff it into indx.
   1234 		 */
   1235 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
   1236 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1237 		fdp->fd_ofiles[dfd] = NULL;
   1238 		fdp->fd_ofileflags[dfd] = 0;
   1239 		/*
   1240 		 * Complete the clean up of the filedesc structure by
   1241 		 * recomputing the various hints.
   1242 		 */
   1243 		fd_used(fdp, indx);
   1244 		fd_unused(fdp, dfd);
   1245 		FILE_UNUSE(wfp, p);
   1246 		return (0);
   1247 
   1248 	default:
   1249 		FILE_UNUSE(wfp, p);
   1250 		return (error);
   1251 	}
   1252 	/* NOTREACHED */
   1253 }
   1254 
   1255 /*
   1256  * Close any files on exec?
   1257  */
   1258 void
   1259 fdcloseexec(p)
   1260 	struct proc *p;
   1261 {
   1262 	register struct filedesc *fdp = p->p_fd;
   1263 	register int fd;
   1264 
   1265 	for (fd = 0; fd <= fdp->fd_lastfile; fd++)
   1266 		if (fdp->fd_ofileflags[fd] & UF_EXCLOSE)
   1267 			(void) fdrelease(p, fd);
   1268 }
   1269