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