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