Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.100
      1 /*	$NetBSD: kern_descrip.c,v 1.100 2003/01/19 22:54:47 simonb 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/cdefs.h>
     44 __KERNEL_RCSID(0, "$NetBSD: kern_descrip.c,v 1.100 2003/01/19 22:54:47 simonb Exp $");
     45 
     46 #include <sys/param.h>
     47 #include <sys/systm.h>
     48 #include <sys/filedesc.h>
     49 #include <sys/kernel.h>
     50 #include <sys/vnode.h>
     51 #include <sys/proc.h>
     52 #include <sys/file.h>
     53 #include <sys/namei.h>
     54 #include <sys/socket.h>
     55 #include <sys/socketvar.h>
     56 #include <sys/stat.h>
     57 #include <sys/ioctl.h>
     58 #include <sys/fcntl.h>
     59 #include <sys/malloc.h>
     60 #include <sys/pool.h>
     61 #include <sys/syslog.h>
     62 #include <sys/unistd.h>
     63 #include <sys/resourcevar.h>
     64 #include <sys/conf.h>
     65 #include <sys/event.h>
     66 
     67 #include <sys/mount.h>
     68 #include <sys/sa.h>
     69 #include <sys/syscallargs.h>
     70 
     71 /*
     72  * Descriptor management.
     73  */
     74 struct filelist	filehead;	/* head of list of open files */
     75 int		nfiles;		/* actual number of open files */
     76 struct pool	file_pool;	/* memory pool for file structures */
     77 struct pool	cwdi_pool;	/* memory pool for cwdinfo structures */
     78 struct pool	filedesc0_pool;	/* memory pool for filedesc0 structures */
     79 
     80 static __inline void	fd_used(struct filedesc *, int);
     81 static __inline void	fd_unused(struct filedesc *, int);
     82 int			finishdup(struct proc *, int, int, register_t *);
     83 int			fcntl_forfs(int, struct proc *, int, void *);
     84 
     85 dev_type_open(filedescopen);
     86 
     87 const struct cdevsw filedesc_cdevsw = {
     88 	filedescopen, noclose, noread, nowrite, noioctl,
     89 	nostop, notty, nopoll, nommap, nokqfilter,
     90 };
     91 
     92 static __inline void
     93 fd_used(struct filedesc *fdp, int fd)
     94 {
     95 
     96 	if (fd > fdp->fd_lastfile)
     97 		fdp->fd_lastfile = fd;
     98 }
     99 
    100 static __inline void
    101 fd_unused(struct filedesc *fdp, int fd)
    102 {
    103 
    104 	if (fd < fdp->fd_freefile)
    105 		fdp->fd_freefile = fd;
    106 #ifdef DIAGNOSTIC
    107 	if (fd > fdp->fd_lastfile)
    108 		panic("fd_unused: fd_lastfile inconsistent");
    109 #endif
    110 	if (fd == fdp->fd_lastfile) {
    111 		do {
    112 			fd--;
    113 		} while (fd >= 0 && fdp->fd_ofiles[fd] == NULL);
    114 		fdp->fd_lastfile = fd;
    115 	}
    116 }
    117 
    118 struct file *
    119 fd_getfile(struct filedesc *fdp, int fd)
    120 {
    121 	struct file *fp;
    122 
    123 	if ((u_int) fd >= fdp->fd_nfiles || (fp = fdp->fd_ofiles[fd]) == NULL)
    124 		return (NULL);
    125 
    126 	if (FILE_IS_USABLE(fp) == 0)
    127 		return (NULL);
    128 
    129 	return (fp);
    130 }
    131 
    132 /*
    133  * System calls on descriptors.
    134  */
    135 
    136 /*
    137  * Duplicate a file descriptor.
    138  */
    139 /* ARGSUSED */
    140 int
    141 sys_dup(struct lwp *l, void *v, register_t *retval)
    142 {
    143 	struct sys_dup_args /* {
    144 		syscallarg(int)	fd;
    145 	} */ *uap = v;
    146 	struct file	*fp;
    147 	struct filedesc	*fdp;
    148 	struct proc	*p;
    149 	int		old, new, error;
    150 
    151 	p = l->l_proc;
    152 	fdp = p->p_fd;
    153 	old = SCARG(uap, fd);
    154 
    155  restart:
    156 	if ((fp = fd_getfile(fdp, old)) == NULL)
    157 		return (EBADF);
    158 
    159 	FILE_USE(fp);
    160 
    161 	if ((error = fdalloc(p, 0, &new)) != 0) {
    162 		if (error == ENOSPC) {
    163 			fdexpand(p);
    164 			FILE_UNUSE(fp, p);
    165 			goto restart;
    166 		}
    167 		FILE_UNUSE(fp, p);
    168 		return (error);
    169 	}
    170 
    171 	/* finishdup() will unuse the descriptors for us */
    172 	return (finishdup(p, old, new, retval));
    173 }
    174 
    175 /*
    176  * Duplicate a file descriptor to a particular value.
    177  */
    178 /* ARGSUSED */
    179 int
    180 sys_dup2(struct lwp *l, void *v, register_t *retval)
    181 {
    182 	struct sys_dup2_args /* {
    183 		syscallarg(int)	from;
    184 		syscallarg(int)	to;
    185 	} */ *uap = v;
    186 	struct file	*fp;
    187 	struct filedesc	*fdp;
    188 	struct proc	*p;
    189 	int		old, new, i, error;
    190 
    191 	p = l->l_proc;
    192 	fdp = p->p_fd;
    193 	old = SCARG(uap, from);
    194 	new = SCARG(uap, to);
    195 
    196  restart:
    197 	if ((fp = fd_getfile(fdp, old)) == NULL)
    198 		return (EBADF);
    199 
    200 	if ((u_int)new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    201 	    (u_int)new >= maxfiles)
    202 		return (EBADF);
    203 
    204 	if (old == new) {
    205 		*retval = new;
    206 		return (0);
    207 	}
    208 
    209 	FILE_USE(fp);
    210 
    211 	if (new >= fdp->fd_nfiles) {
    212 		if ((error = fdalloc(p, new, &i)) != 0) {
    213 			if (error == ENOSPC) {
    214 				fdexpand(p);
    215 				FILE_UNUSE(fp, p);
    216 				goto restart;
    217 			}
    218 			FILE_UNUSE(fp, p);
    219 			return (error);
    220 		}
    221 		if (new != i)
    222 			panic("dup2: fdalloc");
    223 	}
    224 
    225 	/*
    226 	 * finishdup() will close the file that's in the `new'
    227 	 * slot, if there's one there.
    228 	 */
    229 
    230 	/* finishdup() will unuse the descriptors for us */
    231 	return (finishdup(p, old, new, retval));
    232 }
    233 
    234 /*
    235  * The file control system call.
    236  */
    237 /* ARGSUSED */
    238 int
    239 sys_fcntl(struct lwp *l, void *v, register_t *retval)
    240 {
    241 	struct sys_fcntl_args /* {
    242 		syscallarg(int)		fd;
    243 		syscallarg(int)		cmd;
    244 		syscallarg(void *)	arg;
    245 	} */ *uap = v;
    246 	struct filedesc *fdp;
    247 	struct file	*fp;
    248 	struct proc	*p;
    249 	struct vnode	*vp;
    250 	int		fd, i, tmp, error, flg, cmd, newmin;
    251 	struct flock	fl;
    252 
    253 	p = l->l_proc;
    254 	fd = SCARG(uap, fd);
    255 	fdp = p->p_fd;
    256 	error = 0;
    257 	flg = F_POSIX;
    258 
    259  restart:
    260 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    261 		return (EBADF);
    262 
    263 	FILE_USE(fp);
    264 
    265 	cmd = SCARG(uap, cmd);
    266 	if ((cmd & F_FSCTL)) {
    267 		error = fcntl_forfs(fd, p, cmd, SCARG(uap, arg));
    268 		goto out;
    269 	}
    270 
    271 	switch (cmd) {
    272 
    273 	case F_DUPFD:
    274 		newmin = (long)SCARG(uap, arg);
    275 		if ((u_int)newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    276 		    (u_int)newmin >= maxfiles) {
    277 			error = EINVAL;
    278 			goto out;
    279 		}
    280 		if ((error = fdalloc(p, newmin, &i)) != 0) {
    281 			if (error == ENOSPC) {
    282 				fdexpand(p);
    283 				FILE_UNUSE(fp, p);
    284 				goto restart;
    285 			}
    286 			goto out;
    287 		}
    288 
    289 		/* finishdup() will unuse the descriptors for us */
    290 		return (finishdup(p, fd, i, retval));
    291 
    292 	case F_GETFD:
    293 		*retval = fdp->fd_ofileflags[fd] & UF_EXCLOSE ? 1 : 0;
    294 		break;
    295 
    296 	case F_SETFD:
    297 		if ((long)SCARG(uap, arg) & 1)
    298 			fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
    299 		else
    300 			fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
    301 		break;
    302 
    303 	case F_GETFL:
    304 		*retval = OFLAGS(fp->f_flag);
    305 		break;
    306 
    307 	case F_SETFL:
    308 		tmp = FFLAGS((long)SCARG(uap, arg)) & FCNTLFLAGS;
    309 		error = (*fp->f_ops->fo_fcntl)(fp, F_SETFL, (caddr_t)&tmp, p);
    310 		if (error)
    311 			goto out;
    312 		fp->f_flag &= ~FCNTLFLAGS;
    313 		fp->f_flag |= tmp;
    314 		tmp = fp->f_flag & FNONBLOCK;
    315 		error = (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
    316 		if (error)
    317 			goto out;
    318 		tmp = fp->f_flag & FASYNC;
    319 		error = (*fp->f_ops->fo_ioctl)(fp, FIOASYNC, (caddr_t)&tmp, p);
    320 		if (error == 0)
    321 			goto out;
    322 		fp->f_flag &= ~FNONBLOCK;
    323 		tmp = 0;
    324 		(void) (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
    325 		break;
    326 
    327 	case F_GETOWN:
    328 		if (fp->f_type == DTYPE_SOCKET) {
    329 			*retval = ((struct socket *)fp->f_data)->so_pgid;
    330 			goto out;
    331 		}
    332 		error = (*fp->f_ops->fo_ioctl)
    333 			(fp, TIOCGPGRP, (caddr_t)&tmp, p);
    334 		*retval = -tmp;
    335 		break;
    336 
    337 	case F_SETOWN:
    338 		if (fp->f_type == DTYPE_SOCKET) {
    339 			((struct socket *)fp->f_data)->so_pgid =
    340 			    (long)SCARG(uap, arg);
    341 			goto out;
    342 		}
    343 		if ((long)SCARG(uap, arg) <= 0) {
    344 			tmp = (-(long)SCARG(uap, arg));
    345 		} else {
    346 			struct proc *p1 = pfind((long)SCARG(uap, arg));
    347 			if (p1 == 0) {
    348 				error = ESRCH;
    349 				goto out;
    350 			}
    351 			tmp = (long)p1->p_pgrp->pg_id;
    352 		}
    353 		error = (*fp->f_ops->fo_ioctl)
    354 		    (fp, TIOCSPGRP, (caddr_t)&tmp, p);
    355 		break;
    356 
    357 	case F_SETLKW:
    358 		flg |= F_WAIT;
    359 		/* Fall into F_SETLK */
    360 
    361 	case F_SETLK:
    362 		if (fp->f_type != DTYPE_VNODE) {
    363 			error = EINVAL;
    364 			goto out;
    365 		}
    366 		vp = (struct vnode *)fp->f_data;
    367 		/* Copy in the lock structure */
    368 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
    369 		    sizeof(fl));
    370 		if (error)
    371 			goto out;
    372 		if (fl.l_whence == SEEK_CUR)
    373 			fl.l_start += fp->f_offset;
    374 		switch (fl.l_type) {
    375 		case F_RDLCK:
    376 			if ((fp->f_flag & FREAD) == 0) {
    377 				error = EBADF;
    378 				goto out;
    379 			}
    380 			p->p_flag |= P_ADVLOCK;
    381 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg);
    382 			goto out;
    383 
    384 		case F_WRLCK:
    385 			if ((fp->f_flag & FWRITE) == 0) {
    386 				error = EBADF;
    387 				goto out;
    388 			}
    389 			p->p_flag |= P_ADVLOCK;
    390 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg);
    391 			goto out;
    392 
    393 		case F_UNLCK:
    394 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &fl,
    395 			    F_POSIX);
    396 			goto out;
    397 
    398 		default:
    399 			error = EINVAL;
    400 			goto out;
    401 		}
    402 
    403 	case F_GETLK:
    404 		if (fp->f_type != DTYPE_VNODE) {
    405 			error = EINVAL;
    406 			goto out;
    407 		}
    408 		vp = (struct vnode *)fp->f_data;
    409 		/* Copy in the lock structure */
    410 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
    411 		    sizeof(fl));
    412 		if (error)
    413 			goto out;
    414 		if (fl.l_whence == SEEK_CUR)
    415 			fl.l_start += fp->f_offset;
    416 		if (fl.l_type != F_RDLCK &&
    417 		    fl.l_type != F_WRLCK &&
    418 		    fl.l_type != F_UNLCK) {
    419 			error = EINVAL;
    420 			goto out;
    421 		}
    422 		error = VOP_ADVLOCK(vp, (caddr_t)p, F_GETLK, &fl, F_POSIX);
    423 		if (error)
    424 			goto out;
    425 		error = copyout((caddr_t)&fl, (caddr_t)SCARG(uap, arg),
    426 		    sizeof(fl));
    427 		break;
    428 
    429 	default:
    430 		error = EINVAL;
    431 	}
    432 
    433  out:
    434 	FILE_UNUSE(fp, p);
    435 	return (error);
    436 }
    437 
    438 /*
    439  * Common code for dup, dup2, and fcntl(F_DUPFD).
    440  */
    441 int
    442 finishdup(struct proc *p, int old, int new, register_t *retval)
    443 {
    444 	struct filedesc	*fdp;
    445 	struct file	*fp, *delfp;
    446 
    447 	fdp = p->p_fd;
    448 
    449 	/*
    450 	 * If there is a file in the new slot, remember it so we
    451 	 * can close it after we've finished the dup.  We need
    452 	 * to do it after the dup is finished, since closing
    453 	 * the file may block.
    454 	 *
    455 	 * Note: `old' is already used for us.
    456 	 */
    457 	delfp = fdp->fd_ofiles[new];
    458 
    459 	fp = fdp->fd_ofiles[old];
    460 	fdp->fd_ofiles[new] = fp;
    461 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
    462 	fp->f_count++;
    463 	/*
    464 	 * Note, don't have to mark it "used" in the table if there
    465 	 * was already a file in the `new' slot.
    466 	 */
    467 	if (delfp == NULL)
    468 		fd_used(fdp, new);
    469 	*retval = new;
    470 	FILE_UNUSE(fp, p);
    471 
    472 	if (delfp != NULL) {
    473 		FILE_USE(delfp);
    474 		if (new < fdp->fd_knlistsize)
    475 			knote_fdclose(p, new);
    476 		(void) closef(delfp, p);
    477 	}
    478 	return (0);
    479 }
    480 
    481 void
    482 fdremove(struct filedesc *fdp, int fd)
    483 {
    484 
    485 	fdp->fd_ofiles[fd] = NULL;
    486 	fd_unused(fdp, fd);
    487 }
    488 
    489 int
    490 fdrelease(struct proc *p, int fd)
    491 {
    492 	struct filedesc	*fdp;
    493 	struct file	**fpp, *fp;
    494 
    495 	fdp = p->p_fd;
    496 	fpp = &fdp->fd_ofiles[fd];
    497 	fp = *fpp;
    498 	if (fp == NULL)
    499 		return (EBADF);
    500 
    501 	FILE_USE(fp);
    502 
    503 	*fpp = NULL;
    504 	fdp->fd_ofileflags[fd] = 0;
    505 	if (fd < fdp->fd_knlistsize)
    506 		knote_fdclose(p, fd);
    507 	fd_unused(fdp, fd);
    508 	return (closef(fp, p));
    509 }
    510 
    511 /*
    512  * Close a file descriptor.
    513  */
    514 /* ARGSUSED */
    515 int
    516 sys_close(struct lwp *l, void *v, register_t *retval)
    517 {
    518 	struct sys_close_args /* {
    519 		syscallarg(int)	fd;
    520 	} */ *uap = v;
    521 	int		fd;
    522 	struct filedesc	*fdp;
    523 	struct proc *p;
    524 
    525 	p = l->l_proc;
    526 	fd = SCARG(uap, fd);
    527 	fdp = p->p_fd;
    528 
    529 	if (fd_getfile(fdp, fd) == NULL)
    530 		return (EBADF);
    531 
    532 	return (fdrelease(p, fd));
    533 }
    534 
    535 /*
    536  * Return status information about a file descriptor.
    537  */
    538 /* ARGSUSED */
    539 int
    540 sys___fstat13(struct lwp *l, void *v, register_t *retval)
    541 {
    542 	struct sys___fstat13_args /* {
    543 		syscallarg(int)			fd;
    544 		syscallarg(struct stat *)	sb;
    545 	} */ *uap = v;
    546 	int		fd;
    547 	struct filedesc	*fdp;
    548 	struct file	*fp;
    549 	struct proc	*p;
    550 	struct stat	ub;
    551 	int		error;
    552 
    553 	p = l->l_proc;
    554 	fd = SCARG(uap, fd);
    555 	fdp = p->p_fd;
    556 
    557 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    558 		return (EBADF);
    559 
    560 	FILE_USE(fp);
    561 	error = (*fp->f_ops->fo_stat)(fp, &ub, p);
    562 	FILE_UNUSE(fp, p);
    563 
    564 	if (error == 0)
    565 		error = copyout(&ub, SCARG(uap, sb), sizeof(ub));
    566 
    567 	return (error);
    568 }
    569 
    570 /*
    571  * Return pathconf information about a file descriptor.
    572  */
    573 /* ARGSUSED */
    574 int
    575 sys_fpathconf(struct lwp *l, void *v, register_t *retval)
    576 {
    577 	struct sys_fpathconf_args /* {
    578 		syscallarg(int)	fd;
    579 		syscallarg(int)	name;
    580 	} */ *uap = v;
    581 	int		fd;
    582 	struct filedesc	*fdp;
    583 	struct file	*fp;
    584 	struct proc 	*p;
    585 	struct vnode	*vp;
    586 	int		error;
    587 
    588 	p = l->l_proc;
    589 	fd = SCARG(uap, fd);
    590 	fdp = p->p_fd;
    591 	error = 0;
    592 
    593 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    594 		return (EBADF);
    595 
    596 	FILE_USE(fp);
    597 
    598 	switch (fp->f_type) {
    599 
    600 	case DTYPE_SOCKET:
    601 	case DTYPE_PIPE:
    602 		if (SCARG(uap, name) != _PC_PIPE_BUF)
    603 			error = EINVAL;
    604 		else
    605 			*retval = PIPE_BUF;
    606 		break;
    607 
    608 	case DTYPE_VNODE:
    609 		vp = (struct vnode *)fp->f_data;
    610 		error = VOP_PATHCONF(vp, SCARG(uap, name), retval);
    611 		break;
    612 
    613 	case DTYPE_KQUEUE:
    614 		error = EINVAL;
    615 		break;
    616 
    617 	default:
    618 		error = EOPNOTSUPP;
    619 		break;
    620 	}
    621 
    622 	FILE_UNUSE(fp, p);
    623 	return (error);
    624 }
    625 
    626 /*
    627  * Allocate a file descriptor for the process.
    628  */
    629 int	fdexpanded;		/* XXX: what else uses this? */
    630 
    631 int
    632 fdalloc(struct proc *p, int want, int *result)
    633 {
    634 	struct filedesc	*fdp;
    635 	int i, lim, last;
    636 
    637 	fdp = p->p_fd;
    638 
    639 	/*
    640 	 * Search for a free descriptor starting at the higher
    641 	 * of want or fd_freefile.  If that fails, consider
    642 	 * expanding the ofile array.
    643 	 */
    644 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    645 	last = min(fdp->fd_nfiles, lim);
    646 	if ((i = want) < fdp->fd_freefile)
    647 		i = fdp->fd_freefile;
    648 	for (; i < last; i++) {
    649 		if (fdp->fd_ofiles[i] == NULL) {
    650 			fd_used(fdp, i);
    651 			if (want <= fdp->fd_freefile)
    652 				fdp->fd_freefile = i;
    653 			*result = i;
    654 			return (0);
    655 		}
    656 	}
    657 
    658 	/* No space in current array.  Expand? */
    659 	if (fdp->fd_nfiles >= lim)
    660 		return (EMFILE);
    661 
    662 	/* Let the caller do it. */
    663 	return (ENOSPC);
    664 }
    665 
    666 void
    667 fdexpand(struct proc *p)
    668 {
    669 	struct filedesc	*fdp;
    670 	int		i, nfiles;
    671 	struct file	**newofile;
    672 	char		*newofileflags;
    673 
    674 	fdp = p->p_fd;
    675 
    676 	if (fdp->fd_nfiles < NDEXTENT)
    677 		nfiles = NDEXTENT;
    678 	else
    679 		nfiles = 2 * fdp->fd_nfiles;
    680 	newofile = malloc(nfiles * OFILESIZE, M_FILEDESC, M_WAITOK);
    681 	newofileflags = (char *) &newofile[nfiles];
    682 	/*
    683 	 * Copy the existing ofile and ofileflags arrays
    684 	 * and zero the new portion of each array.
    685 	 */
    686 	memcpy(newofile, fdp->fd_ofiles,
    687 	    (i = sizeof(struct file *) * fdp->fd_nfiles));
    688 	memset((char *)newofile + i, 0,
    689 	    nfiles * sizeof(struct file *) - i);
    690 	memcpy(newofileflags, fdp->fd_ofileflags,
    691 	    (i = sizeof(char) * fdp->fd_nfiles));
    692 	memset(newofileflags + i, 0, nfiles * sizeof(char) - i);
    693 	if (fdp->fd_nfiles > NDFILE)
    694 		free(fdp->fd_ofiles, M_FILEDESC);
    695 	fdp->fd_ofiles = newofile;
    696 	fdp->fd_ofileflags = newofileflags;
    697 	fdp->fd_nfiles = nfiles;
    698 	fdexpanded++;
    699 }
    700 
    701 /*
    702  * Check to see whether n user file descriptors
    703  * are available to the process p.
    704  */
    705 int
    706 fdavail(struct proc *p, int n)
    707 {
    708 	struct filedesc	*fdp;
    709 	struct file	**fpp;
    710 	int		i, lim;
    711 
    712 	fdp = p->p_fd;
    713 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    714 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
    715 		return (1);
    716 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
    717 	for (i = min(lim,fdp->fd_nfiles) - fdp->fd_freefile; --i >= 0; fpp++)
    718 		if (*fpp == NULL && --n <= 0)
    719 			return (1);
    720 	return (0);
    721 }
    722 
    723 /*
    724  * Initialize the data structures necessary for managing files.
    725  */
    726 void
    727 finit(void)
    728 {
    729 
    730 	pool_init(&file_pool, sizeof(struct file), 0, 0, 0, "filepl",
    731 	    &pool_allocator_nointr);
    732 	pool_init(&cwdi_pool, sizeof(struct cwdinfo), 0, 0, 0, "cwdipl",
    733 	    &pool_allocator_nointr);
    734 	pool_init(&filedesc0_pool, sizeof(struct filedesc0), 0, 0, 0, "fdescpl",
    735 	    &pool_allocator_nointr);
    736 }
    737 
    738 /*
    739  * Create a new open file structure and allocate
    740  * a file descriptor for the process that refers to it.
    741  */
    742 int
    743 falloc(struct proc *p, struct file **resultfp, int *resultfd)
    744 {
    745 	struct file	*fp, *fq;
    746 	int		error, i;
    747 
    748  restart:
    749 	if ((error = fdalloc(p, 0, &i)) != 0) {
    750 		if (error == ENOSPC) {
    751 			fdexpand(p);
    752 			goto restart;
    753 		}
    754 		return (error);
    755 	}
    756 	if (nfiles >= maxfiles) {
    757 		tablefull("file", "increase kern.maxfiles or MAXFILES");
    758 		return (ENFILE);
    759 	}
    760 	/*
    761 	 * Allocate a new file descriptor.
    762 	 * If the process has file descriptor zero open, add to the list
    763 	 * of open files at that point, otherwise put it at the front of
    764 	 * the list of open files.
    765 	 */
    766 	nfiles++;
    767 	fp = pool_get(&file_pool, PR_WAITOK);
    768 	memset(fp, 0, sizeof(struct file));
    769 	fp->f_iflags = FIF_LARVAL;
    770 	if ((fq = p->p_fd->fd_ofiles[0]) != NULL) {
    771 		LIST_INSERT_AFTER(fq, fp, f_list);
    772 	} else {
    773 		LIST_INSERT_HEAD(&filehead, fp, f_list);
    774 	}
    775 	p->p_fd->fd_ofiles[i] = fp;
    776 	fp->f_count = 1;
    777 	fp->f_cred = p->p_ucred;
    778 	crhold(fp->f_cred);
    779 	if (resultfp) {
    780 		FILE_USE(fp);
    781 		*resultfp = fp;
    782 	}
    783 	if (resultfd)
    784 		*resultfd = i;
    785 	return (0);
    786 }
    787 
    788 /*
    789  * Free a file descriptor.
    790  */
    791 void
    792 ffree(struct file *fp)
    793 {
    794 
    795 #ifdef DIAGNOSTIC
    796 	if (fp->f_usecount)
    797 		panic("ffree");
    798 #endif
    799 
    800 	LIST_REMOVE(fp, f_list);
    801 	crfree(fp->f_cred);
    802 #ifdef DIAGNOSTIC
    803 	fp->f_count = 0;
    804 #endif
    805 	nfiles--;
    806 	pool_put(&file_pool, fp);
    807 }
    808 
    809 /*
    810  * Create an initial cwdinfo structure, using the same current and root
    811  * directories as p.
    812  */
    813 struct cwdinfo *
    814 cwdinit(struct proc *p)
    815 {
    816 	struct cwdinfo *cwdi;
    817 
    818 	cwdi = pool_get(&cwdi_pool, PR_WAITOK);
    819 
    820 	cwdi->cwdi_cdir = p->p_cwdi->cwdi_cdir;
    821 	if (cwdi->cwdi_cdir)
    822 		VREF(cwdi->cwdi_cdir);
    823 	cwdi->cwdi_rdir = p->p_cwdi->cwdi_rdir;
    824 	if (cwdi->cwdi_rdir)
    825 		VREF(cwdi->cwdi_rdir);
    826 	cwdi->cwdi_cmask =  p->p_cwdi->cwdi_cmask;
    827 	cwdi->cwdi_refcnt = 1;
    828 
    829 	return (cwdi);
    830 }
    831 
    832 /*
    833  * Make p2 share p1's cwdinfo.
    834  */
    835 void
    836 cwdshare(struct proc *p1, struct proc *p2)
    837 {
    838 
    839 	p2->p_cwdi = p1->p_cwdi;
    840 	p1->p_cwdi->cwdi_refcnt++;
    841 }
    842 
    843 /*
    844  * Make this process not share its cwdinfo structure, maintaining
    845  * all cwdinfo state.
    846  */
    847 void
    848 cwdunshare(struct proc *p)
    849 {
    850 	struct cwdinfo *newcwdi;
    851 
    852 	if (p->p_cwdi->cwdi_refcnt == 1)
    853 		return;
    854 
    855 	newcwdi = cwdinit(p);
    856 	cwdfree(p);
    857 	p->p_cwdi = newcwdi;
    858 }
    859 
    860 /*
    861  * Release a cwdinfo structure.
    862  */
    863 void
    864 cwdfree(struct proc *p)
    865 {
    866 	struct cwdinfo *cwdi;
    867 
    868 	cwdi = p->p_cwdi;
    869 	if (--cwdi->cwdi_refcnt > 0)
    870 		return;
    871 
    872 	p->p_cwdi = NULL;
    873 
    874 	vrele(cwdi->cwdi_cdir);
    875 	if (cwdi->cwdi_rdir)
    876 		vrele(cwdi->cwdi_rdir);
    877 	pool_put(&cwdi_pool, cwdi);
    878 }
    879 
    880 /*
    881  * Create an initial filedesc structure, using the same current and root
    882  * directories as p.
    883  */
    884 struct filedesc *
    885 fdinit(struct proc *p)
    886 {
    887 	struct filedesc0 *newfdp;
    888 
    889 	newfdp = pool_get(&filedesc0_pool, PR_WAITOK);
    890 	memset(newfdp, 0, sizeof(struct filedesc0));
    891 
    892 	fdinit1(newfdp);
    893 
    894 	return (&newfdp->fd_fd);
    895 }
    896 
    897 /*
    898  * Initialize a file descriptor table.
    899  */
    900 void
    901 fdinit1(struct filedesc0 *newfdp)
    902 {
    903 
    904 	newfdp->fd_fd.fd_refcnt = 1;
    905 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
    906 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
    907 	newfdp->fd_fd.fd_nfiles = NDFILE;
    908 	newfdp->fd_fd.fd_knlistsize = -1;
    909 }
    910 
    911 /*
    912  * Make p2 share p1's filedesc structure.
    913  */
    914 void
    915 fdshare(struct proc *p1, struct proc *p2)
    916 {
    917 
    918 	p2->p_fd = p1->p_fd;
    919 	p1->p_fd->fd_refcnt++;
    920 }
    921 
    922 /*
    923  * Make this process not share its filedesc structure, maintaining
    924  * all file descriptor state.
    925  */
    926 void
    927 fdunshare(struct proc *p)
    928 {
    929 	struct filedesc *newfd;
    930 
    931 	if (p->p_fd->fd_refcnt == 1)
    932 		return;
    933 
    934 	newfd = fdcopy(p);
    935 	fdfree(p);
    936 	p->p_fd = newfd;
    937 }
    938 
    939 /*
    940  * Clear a process's fd table.
    941  */
    942 void
    943 fdclear(struct proc *p)
    944 {
    945 	struct filedesc *newfd;
    946 
    947 	newfd = fdinit(p);
    948 	fdfree(p);
    949 	p->p_fd = newfd;
    950 }
    951 
    952 /*
    953  * Copy a filedesc structure.
    954  */
    955 struct filedesc *
    956 fdcopy(struct proc *p)
    957 {
    958 	struct filedesc	*newfdp, *fdp;
    959 	struct file	**fpp;
    960 	int		i;
    961 
    962 	fdp = p->p_fd;
    963 	newfdp = pool_get(&filedesc0_pool, PR_WAITOK);
    964 	memcpy(newfdp, fdp, sizeof(struct filedesc));
    965 	newfdp->fd_refcnt = 1;
    966 
    967 	/*
    968 	 * If the number of open files fits in the internal arrays
    969 	 * of the open file structure, use them, otherwise allocate
    970 	 * additional memory for the number of descriptors currently
    971 	 * in use.
    972 	 */
    973 	if (newfdp->fd_lastfile < NDFILE) {
    974 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
    975 		newfdp->fd_ofileflags =
    976 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
    977 		i = NDFILE;
    978 	} else {
    979 		/*
    980 		 * Compute the smallest multiple of NDEXTENT needed
    981 		 * for the file descriptors currently in use,
    982 		 * allowing the table to shrink.
    983 		 */
    984 		i = newfdp->fd_nfiles;
    985 		while (i >= 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
    986 			i /= 2;
    987 		newfdp->fd_ofiles = malloc(i * OFILESIZE, M_FILEDESC, M_WAITOK);
    988 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
    989 	}
    990 	newfdp->fd_nfiles = i;
    991 	memcpy(newfdp->fd_ofiles, fdp->fd_ofiles, i * sizeof(struct file **));
    992 	memcpy(newfdp->fd_ofileflags, fdp->fd_ofileflags, i * sizeof(char));
    993 	/*
    994 	 * kq descriptors cannot be copied.
    995 	 */
    996 	if (newfdp->fd_knlistsize != -1) {
    997 		fpp = newfdp->fd_ofiles;
    998 		for (i = newfdp->fd_lastfile; i-- >= 0; fpp++) {
    999 			if (*fpp != NULL && (*fpp)->f_type == DTYPE_KQUEUE)
   1000 				*fpp = NULL;
   1001 		}
   1002 		newfdp->fd_knlist = NULL;
   1003 		newfdp->fd_knlistsize = -1;
   1004 		newfdp->fd_knhash = NULL;
   1005 		newfdp->fd_knhashmask = 0;
   1006 	}
   1007 	fpp = newfdp->fd_ofiles;
   1008 	for (i = newfdp->fd_lastfile; i >= 0; i--, fpp++)
   1009 		if (*fpp != NULL)
   1010 			(*fpp)->f_count++;
   1011 	return (newfdp);
   1012 }
   1013 
   1014 /*
   1015  * Release a filedesc structure.
   1016  */
   1017 void
   1018 fdfree(struct proc *p)
   1019 {
   1020 	struct filedesc	*fdp;
   1021 	struct file	**fpp, *fp;
   1022 	int		i;
   1023 
   1024 	fdp = p->p_fd;
   1025 	if (--fdp->fd_refcnt > 0)
   1026 		return;
   1027 	fpp = fdp->fd_ofiles;
   1028 	for (i = fdp->fd_lastfile; i >= 0; i--, fpp++) {
   1029 		fp = *fpp;
   1030 		if (fp != NULL) {
   1031 			*fpp = NULL;
   1032 			FILE_USE(fp);
   1033 			if (i < fdp->fd_knlistsize)
   1034 				knote_fdclose(p, fdp->fd_lastfile - i);
   1035 			(void) closef(fp, p);
   1036 		}
   1037 	}
   1038 	p->p_fd = NULL;
   1039 	if (fdp->fd_nfiles > NDFILE)
   1040 		free(fdp->fd_ofiles, M_FILEDESC);
   1041 	if (fdp->fd_knlist)
   1042 		free(fdp->fd_knlist, M_KEVENT);
   1043 	if (fdp->fd_knhash)
   1044 		hashdone(fdp->fd_knhash, M_KEVENT);
   1045 	pool_put(&filedesc0_pool, fdp);
   1046 }
   1047 
   1048 /*
   1049  * Internal form of close.
   1050  * Decrement reference count on file structure.
   1051  * Note: p may be NULL when closing a file
   1052  * that was being passed in a message.
   1053  *
   1054  * Note: we expect the caller is holding a usecount, and expects us
   1055  * to drop it (the caller thinks the file is going away forever).
   1056  */
   1057 int
   1058 closef(struct file *fp, struct proc *p)
   1059 {
   1060 	struct vnode	*vp;
   1061 	struct flock	lf;
   1062 	int		error;
   1063 
   1064 	if (fp == NULL)
   1065 		return (0);
   1066 
   1067 	/*
   1068 	 * POSIX record locking dictates that any close releases ALL
   1069 	 * locks owned by this process.  This is handled by setting
   1070 	 * a flag in the unlock to free ONLY locks obeying POSIX
   1071 	 * semantics, and not to free BSD-style file locks.
   1072 	 * If the descriptor was in a message, POSIX-style locks
   1073 	 * aren't passed with the descriptor.
   1074 	 */
   1075 	if (p && (p->p_flag & P_ADVLOCK) && fp->f_type == DTYPE_VNODE) {
   1076 		lf.l_whence = SEEK_SET;
   1077 		lf.l_start = 0;
   1078 		lf.l_len = 0;
   1079 		lf.l_type = F_UNLCK;
   1080 		vp = (struct vnode *)fp->f_data;
   1081 		(void) VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_POSIX);
   1082 	}
   1083 
   1084 	/*
   1085 	 * If WANTCLOSE is set, then the reference count on the file
   1086 	 * is 0, but there were multiple users of the file.  This can
   1087 	 * happen if a filedesc structure is shared by multiple
   1088 	 * processes.
   1089 	 */
   1090 	if (fp->f_iflags & FIF_WANTCLOSE) {
   1091 		/*
   1092 		 * Another user of the file is already closing, and is
   1093 		 * simply waiting for other users of the file to drain.
   1094 		 * Release our usecount, and wake up the closer if it
   1095 		 * is the only remaining use.
   1096 		 */
   1097 #ifdef DIAGNOSTIC
   1098 		if (fp->f_count != 0)
   1099 			panic("closef: wantclose and count != 0");
   1100 		if (fp->f_usecount < 2)
   1101 			panic("closef: wantclose and usecount < 2");
   1102 #endif
   1103 		if (--fp->f_usecount == 1)
   1104 			wakeup(&fp->f_usecount);
   1105 		return (0);
   1106 	} else {
   1107 		/*
   1108 		 * Decrement the reference count.  If we were not the
   1109 		 * last reference, then release our use and just
   1110 		 * return.
   1111 		 */
   1112 		if (--fp->f_count > 0) {
   1113 #ifdef DIAGNOSTIC
   1114 			if (fp->f_usecount < 1)
   1115 				panic("closef: no wantclose and usecount < 1");
   1116 #endif
   1117 			fp->f_usecount--;
   1118 			return (0);
   1119 		}
   1120 	}
   1121 
   1122 	/*
   1123 	 * The reference count is now 0.  However, there may be
   1124 	 * multiple potential users of this file.  This can happen
   1125 	 * if multiple processes shared a single filedesc structure.
   1126 	 *
   1127 	 * Notify these potential users that the file is closing.
   1128 	 * This will prevent them from adding additional uses to
   1129 	 * the file.
   1130 	 */
   1131 	fp->f_iflags |= FIF_WANTCLOSE;
   1132 
   1133 	/*
   1134 	 * We expect the caller to add a use to the file.  So, if we
   1135 	 * are the last user, usecount will be 1.  If it is not, we
   1136 	 * must wait for the usecount to drain.  When it drains back
   1137 	 * to 1, we will be awakened so that we may proceed with the
   1138 	 * close.
   1139 	 */
   1140 #ifdef DIAGNOSTIC
   1141 	if (fp->f_usecount < 1)
   1142 		panic("closef: usecount < 1");
   1143 #endif
   1144 	while (fp->f_usecount > 1)
   1145 		(void) tsleep(&fp->f_usecount, PRIBIO, "closef", 0);
   1146 #ifdef DIAGNOSTIC
   1147 	if (fp->f_usecount != 1)
   1148 		panic("closef: usecount != 1");
   1149 #endif
   1150 
   1151 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
   1152 		lf.l_whence = SEEK_SET;
   1153 		lf.l_start = 0;
   1154 		lf.l_len = 0;
   1155 		lf.l_type = F_UNLCK;
   1156 		vp = (struct vnode *)fp->f_data;
   1157 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1158 	}
   1159 	if (fp->f_ops)
   1160 		error = (*fp->f_ops->fo_close)(fp, p);
   1161 	else
   1162 		error = 0;
   1163 
   1164 	/* Nothing references the file now, drop the final use (us). */
   1165 	fp->f_usecount--;
   1166 
   1167 	ffree(fp);
   1168 	return (error);
   1169 }
   1170 
   1171 /*
   1172  * Apply an advisory lock on a file descriptor.
   1173  *
   1174  * Just attempt to get a record lock of the requested type on
   1175  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
   1176  */
   1177 /* ARGSUSED */
   1178 int
   1179 sys_flock(struct lwp *l, void *v, register_t *retval)
   1180 {
   1181 	struct sys_flock_args /* {
   1182 		syscallarg(int)	fd;
   1183 		syscallarg(int)	how;
   1184 	} */ *uap = v;
   1185 	int		fd, how, error;
   1186 	struct proc	*p;
   1187 	struct filedesc	*fdp;
   1188 	struct file	*fp;
   1189 	struct vnode	*vp;
   1190 	struct flock	lf;
   1191 
   1192 	p = l->l_proc;
   1193 	fd = SCARG(uap, fd);
   1194 	how = SCARG(uap, how);
   1195 	fdp = p->p_fd;
   1196 	error = 0;
   1197 
   1198 	if ((fp = fd_getfile(fdp, fd)) == NULL)
   1199 		return (EBADF);
   1200 
   1201 	FILE_USE(fp);
   1202 
   1203 	if (fp->f_type != DTYPE_VNODE) {
   1204 		error = EOPNOTSUPP;
   1205 		goto out;
   1206 	}
   1207 
   1208 	vp = (struct vnode *)fp->f_data;
   1209 	lf.l_whence = SEEK_SET;
   1210 	lf.l_start = 0;
   1211 	lf.l_len = 0;
   1212 	if (how & LOCK_UN) {
   1213 		lf.l_type = F_UNLCK;
   1214 		fp->f_flag &= ~FHASLOCK;
   1215 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1216 		goto out;
   1217 	}
   1218 	if (how & LOCK_EX)
   1219 		lf.l_type = F_WRLCK;
   1220 	else if (how & LOCK_SH)
   1221 		lf.l_type = F_RDLCK;
   1222 	else {
   1223 		error = EINVAL;
   1224 		goto out;
   1225 	}
   1226 	fp->f_flag |= FHASLOCK;
   1227 	if (how & LOCK_NB)
   1228 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK);
   1229 	else
   1230 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
   1231 		    F_FLOCK|F_WAIT);
   1232  out:
   1233 	FILE_UNUSE(fp, p);
   1234 	return (error);
   1235 }
   1236 
   1237 /*
   1238  * File Descriptor pseudo-device driver (/dev/fd/).
   1239  *
   1240  * Opening minor device N dup()s the file (if any) connected to file
   1241  * descriptor N belonging to the calling process.  Note that this driver
   1242  * consists of only the ``open()'' routine, because all subsequent
   1243  * references to this file will be direct to the other driver.
   1244  */
   1245 /* ARGSUSED */
   1246 int
   1247 filedescopen(dev_t dev, int mode, int type, struct proc *p)
   1248 {
   1249 
   1250 	/*
   1251 	 * XXX Kludge: set p->p_dupfd to contain the value of the
   1252 	 * the file descriptor being sought for duplication. The error
   1253 	 * return ensures that the vnode for this device will be released
   1254 	 * by vn_open. Open will detect this special error and take the
   1255 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
   1256 	 * will simply report the error.
   1257 	 */
   1258 	p->p_dupfd = minor(dev);
   1259 	return (ENODEV);
   1260 }
   1261 
   1262 /*
   1263  * Duplicate the specified descriptor to a free descriptor.
   1264  */
   1265 int
   1266 dupfdopen(struct proc *p, int indx, int dfd, int mode, int error)
   1267 {
   1268 	struct filedesc	*fdp;
   1269 	struct file	*wfp, *fp;
   1270 
   1271 	fdp = p->p_fd;
   1272 	/*
   1273 	 * If the to-be-dup'd fd number is greater than the allowed number
   1274 	 * of file descriptors, or the fd to be dup'd has already been
   1275 	 * closed, reject.  Note, check for new == old is necessary as
   1276 	 * falloc could allocate an already closed to-be-dup'd descriptor
   1277 	 * as the new descriptor.
   1278 	 */
   1279 	fp = fdp->fd_ofiles[indx];
   1280 
   1281 	if ((wfp = fd_getfile(fdp, dfd)) == NULL)
   1282 		return (EBADF);
   1283 
   1284 	if (fp == wfp)
   1285 		return (EBADF);
   1286 
   1287 	FILE_USE(wfp);
   1288 
   1289 	/*
   1290 	 * There are two cases of interest here.
   1291 	 *
   1292 	 * For ENODEV simply dup (dfd) to file descriptor
   1293 	 * (indx) and return.
   1294 	 *
   1295 	 * For ENXIO steal away the file structure from (dfd) and
   1296 	 * store it in (indx).  (dfd) is effectively closed by
   1297 	 * this operation.
   1298 	 *
   1299 	 * Any other error code is just returned.
   1300 	 */
   1301 	switch (error) {
   1302 	case ENODEV:
   1303 		/*
   1304 		 * Check that the mode the file is being opened for is a
   1305 		 * subset of the mode of the existing descriptor.
   1306 		 */
   1307 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
   1308 			FILE_UNUSE(wfp, p);
   1309 			return (EACCES);
   1310 		}
   1311 		fdp->fd_ofiles[indx] = wfp;
   1312 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1313 		wfp->f_count++;
   1314 		fd_used(fdp, indx);
   1315 		FILE_UNUSE(wfp, p);
   1316 		return (0);
   1317 
   1318 	case ENXIO:
   1319 		/*
   1320 		 * Steal away the file pointer from dfd, and stuff it into indx.
   1321 		 */
   1322 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
   1323 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1324 		fdp->fd_ofiles[dfd] = NULL;
   1325 		fdp->fd_ofileflags[dfd] = 0;
   1326 		/*
   1327 		 * Complete the clean up of the filedesc structure by
   1328 		 * recomputing the various hints.
   1329 		 */
   1330 		fd_used(fdp, indx);
   1331 		fd_unused(fdp, dfd);
   1332 		FILE_UNUSE(wfp, p);
   1333 		return (0);
   1334 
   1335 	default:
   1336 		FILE_UNUSE(wfp, p);
   1337 		return (error);
   1338 	}
   1339 	/* NOTREACHED */
   1340 }
   1341 
   1342 /*
   1343  * fcntl call which is being passed to the file's fs.
   1344  */
   1345 int
   1346 fcntl_forfs(int fd, struct proc *p, int cmd, void *arg)
   1347 {
   1348 	struct file	*fp;
   1349 	struct filedesc	*fdp;
   1350 	int		error;
   1351 	u_int		size;
   1352 	caddr_t		data, memp;
   1353 #define STK_PARAMS	128
   1354 	char		stkbuf[STK_PARAMS];
   1355 
   1356 	/* fd's value was validated in sys_fcntl before calling this routine */
   1357 	fdp = p->p_fd;
   1358 	fp = fdp->fd_ofiles[fd];
   1359 
   1360 	if ((fp->f_flag & (FREAD | FWRITE)) == 0)
   1361 		return (EBADF);
   1362 
   1363 	/*
   1364 	 * Interpret high order word to find amount of data to be
   1365 	 * copied to/from the user's address space.
   1366 	 */
   1367 	size = (size_t)F_PARAM_LEN(cmd);
   1368 	if (size > F_PARAM_MAX)
   1369 		return (EINVAL);
   1370 	memp = NULL;
   1371 	if (size > sizeof(stkbuf)) {
   1372 		memp = (caddr_t)malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
   1373 		data = memp;
   1374 	} else
   1375 		data = stkbuf;
   1376 	if (cmd & F_FSIN) {
   1377 		if (size) {
   1378 			error = copyin(arg, data, size);
   1379 			if (error) {
   1380 				if (memp)
   1381 					free(memp, M_IOCTLOPS);
   1382 				return (error);
   1383 			}
   1384 		} else
   1385 			*(caddr_t *)data = arg;
   1386 	} else if ((cmd & F_FSOUT) && size)
   1387 		/*
   1388 		 * Zero the buffer so the user always
   1389 		 * gets back something deterministic.
   1390 		 */
   1391 		memset(data, 0, size);
   1392 	else if (cmd & F_FSVOID)
   1393 		*(caddr_t *)data = arg;
   1394 
   1395 
   1396 	error = (*fp->f_ops->fo_fcntl)(fp, cmd, data, p);
   1397 
   1398 	/*
   1399 	 * Copy any data to user, size was
   1400 	 * already set and checked above.
   1401 	 */
   1402 	if (error == 0 && (cmd & F_FSOUT) && size)
   1403 		error = copyout(data, arg, size);
   1404 	if (memp)
   1405 		free(memp, M_IOCTLOPS);
   1406 	return (error);
   1407 }
   1408 
   1409 /*
   1410  * Close any files on exec?
   1411  */
   1412 void
   1413 fdcloseexec(struct proc *p)
   1414 {
   1415 	struct filedesc	*fdp;
   1416 	int		fd;
   1417 
   1418 	fdunshare(p);
   1419 	cwdunshare(p);
   1420 
   1421 	fdp = p->p_fd;
   1422 	for (fd = 0; fd <= fdp->fd_lastfile; fd++)
   1423 		if (fdp->fd_ofileflags[fd] & UF_EXCLOSE)
   1424 			(void) fdrelease(p, fd);
   1425 }
   1426 
   1427 /*
   1428  * It is unsafe for set[ug]id processes to be started with file
   1429  * descriptors 0..2 closed, as these descriptors are given implicit
   1430  * significance in the Standard C library.  fdcheckstd() will create a
   1431  * descriptor referencing /dev/null for each of stdin, stdout, and
   1432  * stderr that is not already open.
   1433  */
   1434 #define CHECK_UPTO 3
   1435 int
   1436 fdcheckstd(p)
   1437 	struct proc *p;
   1438 {
   1439 	struct nameidata nd;
   1440 	struct filedesc *fdp;
   1441 	struct file *fp;
   1442 	struct file *devnullfp = NULL;	/* Quell compiler warning */
   1443 	struct proc *pp;
   1444 	register_t retval;
   1445 	int fd, i, error, flags = FREAD|FWRITE, devnull = -1;
   1446 	char closed[CHECK_UPTO * 3 + 1], which[3 + 1];
   1447 
   1448 	closed[0] = '\0';
   1449 	if ((fdp = p->p_fd) == NULL)
   1450 		return (0);
   1451 	for (i = 0; i < CHECK_UPTO; i++) {
   1452 		if (fdp->fd_ofiles[i] != NULL)
   1453 			continue;
   1454 		snprintf(which, sizeof(which), ",%d", i);
   1455 		strcat(closed, which);
   1456 		if (devnull < 0) {
   1457 			if ((error = falloc(p, &fp, &fd)) != 0)
   1458 				return (error);
   1459 			NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null",
   1460 			    p);
   1461 			if ((error = vn_open(&nd, flags, 0)) != 0) {
   1462 				FILE_UNUSE(fp, p);
   1463 				ffree(fp);
   1464 				fdremove(p->p_fd, fd);
   1465 				return (error);
   1466 			}
   1467 			fp->f_data = (caddr_t)nd.ni_vp;
   1468 			fp->f_flag = flags;
   1469 			fp->f_ops = &vnops;
   1470 			fp->f_type = DTYPE_VNODE;
   1471 			VOP_UNLOCK(nd.ni_vp, 0);
   1472 			devnull = fd;
   1473 			devnullfp = fp;
   1474 			FILE_SET_MATURE(fp);
   1475 			FILE_UNUSE(fp, p);
   1476 		} else {
   1477 restart:
   1478 			if ((error = fdalloc(p, 0, &fd)) != 0) {
   1479 				if (error == ENOSPC) {
   1480 					fdexpand(p);
   1481 					goto restart;
   1482 				}
   1483 				return (error);
   1484 			}
   1485 
   1486 			FILE_USE(devnullfp);
   1487 			/* finishdup() will unuse the descriptors for us */
   1488 			if ((error = finishdup(p, devnull, fd, &retval)) != 0)
   1489 				return (error);
   1490 		}
   1491 	}
   1492 	if (closed[0] != '\0') {
   1493 		pp = p->p_pptr;
   1494 		log(LOG_WARNING, "set{u,g}id pid %d (%s) "
   1495 		    "was invoked by uid %d ppid %d (%s) "
   1496 		    "with fd %s closed\n",
   1497 		    p->p_pid, p->p_comm, pp->p_ucred->cr_uid,
   1498 		    pp->p_pid, pp->p_comm, &closed[1]);
   1499 	}
   1500 	return (0);
   1501 }
   1502 #undef CHECK_UPTO
   1503