Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.60
      1 /*	$NetBSD: kern_descrip.c,v 1.60 1999/06/20 08:54:13 christos 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 
    734 	cwdi = pool_get(&cwdi_pool, PR_WAITOK);
    735 
    736 	cwdi->cwdi_cdir = p->p_cwdi->cwdi_cdir;
    737 	VREF(cwdi->cwdi_cdir);
    738 	cwdi->cwdi_rdir = p->p_cwdi->cwdi_rdir;
    739 	if (cwdi->cwdi_rdir)
    740 		VREF(cwdi->cwdi_rdir);
    741 	cwdi->cwdi_cmask =  p->p_cwdi->cwdi_cmask;
    742 	cwdi->cwdi_refcnt = 1;
    743 
    744 	return (cwdi);
    745 }
    746 
    747 /*
    748  * Make p2 share p1's cwdinfo.
    749  */
    750 void
    751 cwdshare(p1, p2)
    752 	struct proc *p1, *p2;
    753 {
    754 
    755 	p2->p_cwdi = p1->p_cwdi;
    756 	p1->p_cwdi->cwdi_refcnt++;
    757 }
    758 
    759 /*
    760  * Make this process not share its cwdinfo structure, maintaining
    761  * all cwdinfo state.
    762  */
    763 void
    764 cwdunshare(p)
    765 	struct proc *p;
    766 {
    767 	struct cwdinfo *newcwdi;
    768 
    769 	if (p->p_cwdi->cwdi_refcnt == 1)
    770 		return;
    771 
    772 	newcwdi = cwdinit(p);
    773 	cwdfree(p);
    774 	p->p_cwdi = newcwdi;
    775 }
    776 
    777 /*
    778  * Release a cwdinfo structure.
    779  */
    780 void
    781 cwdfree(p)
    782 	struct proc *p;
    783 {
    784 	struct cwdinfo *cwdi = p->p_cwdi;
    785 
    786 	if (--cwdi->cwdi_refcnt > 0)
    787 		return;
    788 
    789 	p->p_cwdi = NULL;
    790 
    791 	vrele(cwdi->cwdi_cdir);
    792 	if (cwdi->cwdi_rdir)
    793 		vrele(cwdi->cwdi_rdir);
    794 	pool_put(&cwdi_pool, cwdi);
    795 }
    796 
    797 /*
    798  * Create an initial filedesc structure, using the same current and root
    799  * directories as p.
    800  */
    801 struct filedesc *
    802 fdinit(p)
    803 	struct proc *p;
    804 {
    805 	struct filedesc0 *newfdp;
    806 
    807 	MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
    808 	    M_FILEDESC, M_WAITOK);
    809 	memset(newfdp, 0, sizeof(struct filedesc0));
    810 
    811 	fdinit1(newfdp);
    812 
    813 	return (&newfdp->fd_fd);
    814 }
    815 
    816 /*
    817  * Initialize a file descriptor table.
    818  */
    819 void
    820 fdinit1(newfdp)
    821 	struct filedesc0 *newfdp;
    822 {
    823 
    824 	newfdp->fd_fd.fd_refcnt = 1;
    825 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
    826 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
    827 	newfdp->fd_fd.fd_nfiles = NDFILE;
    828 }
    829 
    830 /*
    831  * Make p2 share p1's filedesc structure.
    832  */
    833 void
    834 fdshare(p1, p2)
    835 	struct proc *p1, *p2;
    836 {
    837 
    838 	p2->p_fd = p1->p_fd;
    839 	p1->p_fd->fd_refcnt++;
    840 }
    841 
    842 /*
    843  * Make this process not share its filedesc structure, maintaining
    844  * all file descriptor state.
    845  */
    846 void
    847 fdunshare(p)
    848 	struct proc *p;
    849 {
    850 	struct filedesc *newfd;
    851 
    852 	if (p->p_fd->fd_refcnt == 1)
    853 		return;
    854 
    855 	newfd = fdcopy(p);
    856 	fdfree(p);
    857 	p->p_fd = newfd;
    858 }
    859 
    860 /*
    861  * Clear a process's fd table.
    862  */
    863 void
    864 fdclear(p)
    865 	struct proc *p;
    866 {
    867 	struct filedesc *newfd;
    868 
    869 	newfd = fdinit(p);
    870 	fdfree(p);
    871 	p->p_fd = newfd;
    872 }
    873 
    874 /*
    875  * Copy a filedesc structure.
    876  */
    877 struct filedesc *
    878 fdcopy(p)
    879 	struct proc *p;
    880 {
    881 	register struct filedesc *newfdp, *fdp = p->p_fd;
    882 	register struct file **fpp;
    883 	register int i;
    884 
    885 	MALLOC(newfdp, struct filedesc *, sizeof(struct filedesc0),
    886 	    M_FILEDESC, M_WAITOK);
    887 	memcpy(newfdp, fdp, sizeof(struct filedesc));
    888 	newfdp->fd_refcnt = 1;
    889 
    890 	/*
    891 	 * If the number of open files fits in the internal arrays
    892 	 * of the open file structure, use them, otherwise allocate
    893 	 * additional memory for the number of descriptors currently
    894 	 * in use.
    895 	 */
    896 	if (newfdp->fd_lastfile < NDFILE) {
    897 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
    898 		newfdp->fd_ofileflags =
    899 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
    900 		i = NDFILE;
    901 	} else {
    902 		/*
    903 		 * Compute the smallest multiple of NDEXTENT needed
    904 		 * for the file descriptors currently in use,
    905 		 * allowing the table to shrink.
    906 		 */
    907 		i = newfdp->fd_nfiles;
    908 		while (i >= 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
    909 			i /= 2;
    910 		MALLOC(newfdp->fd_ofiles, struct file **, i * OFILESIZE,
    911 		    M_FILEDESC, M_WAITOK);
    912 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
    913 	}
    914 	newfdp->fd_nfiles = i;
    915 	memcpy(newfdp->fd_ofiles, fdp->fd_ofiles, i * sizeof(struct file **));
    916 	memcpy(newfdp->fd_ofileflags, fdp->fd_ofileflags, i * sizeof(char));
    917 	fpp = newfdp->fd_ofiles;
    918 	for (i = newfdp->fd_lastfile; i >= 0; i--, fpp++)
    919 		if (*fpp != NULL)
    920 			(*fpp)->f_count++;
    921 	return (newfdp);
    922 }
    923 
    924 /*
    925  * Release a filedesc structure.
    926  */
    927 void
    928 fdfree(p)
    929 	struct proc *p;
    930 {
    931 	register struct filedesc *fdp = p->p_fd;
    932 	register struct file **fpp, *fp;
    933 	register int i;
    934 
    935 	if (--fdp->fd_refcnt > 0)
    936 		return;
    937 	fpp = fdp->fd_ofiles;
    938 	for (i = fdp->fd_lastfile; i >= 0; i--, fpp++) {
    939 		fp = *fpp;
    940 		if (fp != NULL) {
    941 			*fpp = NULL;
    942 			FILE_USE(fp);
    943 			(void) closef(fp, p);
    944 		}
    945 	}
    946 	p->p_fd = NULL;
    947 	if (fdp->fd_nfiles > NDFILE)
    948 		FREE(fdp->fd_ofiles, M_FILEDESC);
    949 	FREE(fdp, M_FILEDESC);
    950 }
    951 
    952 /*
    953  * Internal form of close.
    954  * Decrement reference count on file structure.
    955  * Note: p may be NULL when closing a file
    956  * that was being passed in a message.
    957  *
    958  * Note: we expect the caller is holding a usecount, and expects us
    959  * to drop it (the caller thinks the file is going away forever).
    960  */
    961 int
    962 closef(fp, p)
    963 	register struct file *fp;
    964 	register struct proc *p;
    965 {
    966 	struct vnode *vp;
    967 	struct flock lf;
    968 	int error;
    969 
    970 	if (fp == NULL)
    971 		return (0);
    972 
    973 	/*
    974 	 * POSIX record locking dictates that any close releases ALL
    975 	 * locks owned by this process.  This is handled by setting
    976 	 * a flag in the unlock to free ONLY locks obeying POSIX
    977 	 * semantics, and not to free BSD-style file locks.
    978 	 * If the descriptor was in a message, POSIX-style locks
    979 	 * aren't passed with the descriptor.
    980 	 */
    981 	if (p && (p->p_flag & P_ADVLOCK) && fp->f_type == DTYPE_VNODE) {
    982 		lf.l_whence = SEEK_SET;
    983 		lf.l_start = 0;
    984 		lf.l_len = 0;
    985 		lf.l_type = F_UNLCK;
    986 		vp = (struct vnode *)fp->f_data;
    987 		(void) VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_POSIX);
    988 	}
    989 
    990 	/*
    991 	 * If WANTCLOSE is set, then the reference count on the file
    992 	 * is 0, but there were multiple users of the file.  This can
    993 	 * happen if a filedesc structure is shared by multiple
    994 	 * processes.
    995 	 */
    996 	if (fp->f_iflags & FIF_WANTCLOSE) {
    997 		/*
    998 		 * Another user of the file is already closing, and is
    999 		 * simply waiting for other users of the file to drain.
   1000 		 * Release our usecount, and wake up the closer if it
   1001 		 * is the only remaining use.
   1002 		 */
   1003 #ifdef DIAGNOSTIC
   1004 		if (fp->f_count != 0)
   1005 			panic("closef: wantclose and count != 0");
   1006 		if (fp->f_usecount < 2)
   1007 			panic("closef: wantclose and usecount < 2");
   1008 #endif
   1009 		if (--fp->f_usecount == 1)
   1010 			wakeup(&fp->f_usecount);
   1011 		return (0);
   1012 	} else {
   1013 		/*
   1014 		 * Decrement the reference count.  If we were not the
   1015 		 * last reference, then release our use and just
   1016 		 * return.
   1017 		 */
   1018 		if (--fp->f_count > 0) {
   1019 #ifdef DIAGNOSTIC
   1020 			if (fp->f_usecount < 1)
   1021 				panic("closef: no wantclose and usecount < 1");
   1022 #endif
   1023 			fp->f_usecount--;
   1024 			return (0);
   1025 		}
   1026 		if (fp->f_count < 0)
   1027 			panic("closef: count < 0");
   1028 	}
   1029 
   1030 	/*
   1031 	 * The reference count is now 0.  However, there may be
   1032 	 * multiple potential users of this file.  This can happen
   1033 	 * if multiple processes shared a single filedesc structure.
   1034 	 *
   1035 	 * Notify these potential users that the file is closing.
   1036 	 * This will prevent them from adding additional uses to
   1037 	 * the file.
   1038 	 */
   1039 	fp->f_iflags |= FIF_WANTCLOSE;
   1040 
   1041 	/*
   1042 	 * We expect the caller to add a use to the file.  So, if we
   1043 	 * are the last user, usecount will be 1.  If it is not, we
   1044 	 * must wait for the usecount to drain.  When it drains back
   1045 	 * to 1, we will be awakened so that we may proceed with the
   1046 	 * close.
   1047 	 */
   1048 #ifdef DIAGNOSTIC
   1049 	if (fp->f_usecount < 1)
   1050 		panic("closef: usecount < 1");
   1051 #endif
   1052 	while (fp->f_usecount > 1)
   1053 		(void) tsleep(&fp->f_usecount, PRIBIO, "closef", 0);
   1054 #ifdef DIAGNOSTIC
   1055 	if (fp->f_usecount != 1)
   1056 		panic("closef: usecount != 1");
   1057 #endif
   1058 
   1059 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
   1060 		lf.l_whence = SEEK_SET;
   1061 		lf.l_start = 0;
   1062 		lf.l_len = 0;
   1063 		lf.l_type = F_UNLCK;
   1064 		vp = (struct vnode *)fp->f_data;
   1065 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1066 	}
   1067 	if (fp->f_ops)
   1068 		error = (*fp->f_ops->fo_close)(fp, p);
   1069 	else
   1070 		error = 0;
   1071 
   1072 	/* Nothing references the file now, drop the final use (us). */
   1073 	fp->f_usecount--;
   1074 
   1075 	ffree(fp);
   1076 	return (error);
   1077 }
   1078 
   1079 /*
   1080  * Apply an advisory lock on a file descriptor.
   1081  *
   1082  * Just attempt to get a record lock of the requested type on
   1083  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
   1084  */
   1085 /* ARGSUSED */
   1086 int
   1087 sys_flock(p, v, retval)
   1088 	struct proc *p;
   1089 	void *v;
   1090 	register_t *retval;
   1091 {
   1092 	register struct sys_flock_args /* {
   1093 		syscallarg(int) fd;
   1094 		syscallarg(int) how;
   1095 	} */ *uap = v;
   1096 	int fd = SCARG(uap, fd);
   1097 	int how = SCARG(uap, how);
   1098 	register struct filedesc *fdp = p->p_fd;
   1099 	register struct file *fp;
   1100 	struct vnode *vp;
   1101 	struct flock lf;
   1102 	int error = 0;
   1103 
   1104 	if ((u_int)fd >= fdp->fd_nfiles ||
   1105 	    (fp = fdp->fd_ofiles[fd]) == NULL ||
   1106 	    (fp->f_iflags & FIF_WANTCLOSE) != 0)
   1107 		return (EBADF);
   1108 
   1109 	FILE_USE(fp);
   1110 
   1111 	if (fp->f_type != DTYPE_VNODE) {
   1112 		error = EOPNOTSUPP;
   1113 		goto out;
   1114 	}
   1115 
   1116 	vp = (struct vnode *)fp->f_data;
   1117 	lf.l_whence = SEEK_SET;
   1118 	lf.l_start = 0;
   1119 	lf.l_len = 0;
   1120 	if (how & LOCK_UN) {
   1121 		lf.l_type = F_UNLCK;
   1122 		fp->f_flag &= ~FHASLOCK;
   1123 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1124 		goto out;
   1125 	}
   1126 	if (how & LOCK_EX)
   1127 		lf.l_type = F_WRLCK;
   1128 	else if (how & LOCK_SH)
   1129 		lf.l_type = F_RDLCK;
   1130 	else {
   1131 		error = EINVAL;
   1132 		goto out;
   1133 	}
   1134 	fp->f_flag |= FHASLOCK;
   1135 	if (how & LOCK_NB)
   1136 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK);
   1137 	else
   1138 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
   1139 		    F_FLOCK|F_WAIT);
   1140  out:
   1141 	FILE_UNUSE(fp, p);
   1142 	return (error);
   1143 }
   1144 
   1145 /*
   1146  * File Descriptor pseudo-device driver (/dev/fd/).
   1147  *
   1148  * Opening minor device N dup()s the file (if any) connected to file
   1149  * descriptor N belonging to the calling process.  Note that this driver
   1150  * consists of only the ``open()'' routine, because all subsequent
   1151  * references to this file will be direct to the other driver.
   1152  */
   1153 /* ARGSUSED */
   1154 int
   1155 filedescopen(dev, mode, type, p)
   1156 	dev_t dev;
   1157 	int mode, type;
   1158 	struct proc *p;
   1159 {
   1160 
   1161 	/*
   1162 	 * XXX Kludge: set curproc->p_dupfd to contain the value of the
   1163 	 * the file descriptor being sought for duplication. The error
   1164 	 * return ensures that the vnode for this device will be released
   1165 	 * by vn_open. Open will detect this special error and take the
   1166 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
   1167 	 * will simply report the error.
   1168 	 */
   1169 	p->p_dupfd = minor(dev);
   1170 	return (ENODEV);
   1171 }
   1172 
   1173 /*
   1174  * Duplicate the specified descriptor to a free descriptor.
   1175  */
   1176 int
   1177 dupfdopen(p, indx, dfd, mode, error)
   1178 	struct proc *p;
   1179 	int indx, dfd, mode, error;
   1180 {
   1181 	struct filedesc *fdp = p->p_fd;
   1182 	struct file *wfp;
   1183 	struct file *fp;
   1184 
   1185 	/*
   1186 	 * If the to-be-dup'd fd number is greater than the allowed number
   1187 	 * of file descriptors, or the fd to be dup'd has already been
   1188 	 * closed, reject.  Note, check for new == old is necessary as
   1189 	 * falloc could allocate an already closed to-be-dup'd descriptor
   1190 	 * as the new descriptor.
   1191 	 */
   1192 	fp = fdp->fd_ofiles[indx];
   1193 	if ((u_int)dfd >= fdp->fd_nfiles ||
   1194 	    (wfp = fdp->fd_ofiles[dfd]) == NULL ||
   1195 	    (wfp->f_iflags & FIF_WANTCLOSE) != 0 ||
   1196 	    fp == wfp)
   1197 		return (EBADF);
   1198 
   1199 	FILE_USE(wfp);
   1200 
   1201 	/*
   1202 	 * There are two cases of interest here.
   1203 	 *
   1204 	 * For ENODEV simply dup (dfd) to file descriptor
   1205 	 * (indx) and return.
   1206 	 *
   1207 	 * For ENXIO steal away the file structure from (dfd) and
   1208 	 * store it in (indx).  (dfd) is effectively closed by
   1209 	 * this operation.
   1210 	 *
   1211 	 * Any other error code is just returned.
   1212 	 */
   1213 	switch (error) {
   1214 	case ENODEV:
   1215 		/*
   1216 		 * Check that the mode the file is being opened for is a
   1217 		 * subset of the mode of the existing descriptor.
   1218 		 */
   1219 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
   1220 			FILE_UNUSE(wfp, p);
   1221 			return (EACCES);
   1222 		}
   1223 		fdp->fd_ofiles[indx] = wfp;
   1224 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1225 		wfp->f_count++;
   1226 		fd_used(fdp, indx);
   1227 		FILE_UNUSE(wfp, p);
   1228 		return (0);
   1229 
   1230 	case ENXIO:
   1231 		/*
   1232 		 * Steal away the file pointer from dfd, and stuff it into indx.
   1233 		 */
   1234 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
   1235 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1236 		fdp->fd_ofiles[dfd] = NULL;
   1237 		fdp->fd_ofileflags[dfd] = 0;
   1238 		/*
   1239 		 * Complete the clean up of the filedesc structure by
   1240 		 * recomputing the various hints.
   1241 		 */
   1242 		fd_used(fdp, indx);
   1243 		fd_unused(fdp, dfd);
   1244 		FILE_UNUSE(wfp, p);
   1245 		return (0);
   1246 
   1247 	default:
   1248 		FILE_UNUSE(wfp, p);
   1249 		return (error);
   1250 	}
   1251 	/* NOTREACHED */
   1252 }
   1253 
   1254 /*
   1255  * Close any files on exec?
   1256  */
   1257 void
   1258 fdcloseexec(p)
   1259 	struct proc *p;
   1260 {
   1261 	register struct filedesc *fdp = p->p_fd;
   1262 	register int fd;
   1263 
   1264 	for (fd = 0; fd <= fdp->fd_lastfile; fd++)
   1265 		if (fdp->fd_ofileflags[fd] & UF_EXCLOSE)
   1266 			(void) fdrelease(p, fd);
   1267 }
   1268