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