Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.72.2.11
      1 /*	$NetBSD: kern_descrip.c,v 1.72.2.11 2002/07/10 22:34:15 nathanw 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.72.2.11 2002/07/10 22:34:15 nathanw 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/lwp.h>
     52 #include <sys/proc.h>
     53 #include <sys/file.h>
     54 #include <sys/namei.h>
     55 #include <sys/socket.h>
     56 #include <sys/socketvar.h>
     57 #include <sys/stat.h>
     58 #include <sys/ioctl.h>
     59 #include <sys/fcntl.h>
     60 #include <sys/malloc.h>
     61 #include <sys/pool.h>
     62 #include <sys/syslog.h>
     63 #include <sys/unistd.h>
     64 #include <sys/resourcevar.h>
     65 #include <sys/conf.h>
     66 
     67 #include <sys/mount.h>
     68 #include <sys/sa.h>
     69 #include <sys/syscallargs.h>
     70 
     71 /*
     72  * Descriptor management.
     73  */
     74 struct filelist	filehead;	/* head of list of open files */
     75 int		nfiles;		/* actual number of open files */
     76 struct pool	file_pool;	/* memory pool for file structures */
     77 struct pool	cwdi_pool;	/* memory pool for cwdinfo structures */
     78 struct pool	filedesc0_pool;	/* memory pool for filedesc0 structures */
     79 
     80 static __inline void	fd_used(struct filedesc *, int);
     81 static __inline void	fd_unused(struct filedesc *, int);
     82 int			finishdup(struct proc *, int, int, register_t *);
     83 int			fcntl_forfs(int, struct proc *, int, void *);
     84 
     85 static __inline void
     86 fd_used(struct filedesc *fdp, int fd)
     87 {
     88 
     89 	if (fd > fdp->fd_lastfile)
     90 		fdp->fd_lastfile = fd;
     91 }
     92 
     93 static __inline void
     94 fd_unused(struct filedesc *fdp, int fd)
     95 {
     96 
     97 	if (fd < fdp->fd_freefile)
     98 		fdp->fd_freefile = fd;
     99 #ifdef DIAGNOSTIC
    100 	if (fd > fdp->fd_lastfile)
    101 		panic("fd_unused: fd_lastfile inconsistent");
    102 #endif
    103 	if (fd == fdp->fd_lastfile) {
    104 		do {
    105 			fd--;
    106 		} while (fd >= 0 && fdp->fd_ofiles[fd] == NULL);
    107 		fdp->fd_lastfile = fd;
    108 	}
    109 }
    110 
    111 struct file *
    112 fd_getfile(struct filedesc *fdp, int fd)
    113 {
    114 	struct file *fp;
    115 
    116 	if ((u_int) fd >= fdp->fd_nfiles || (fp = fdp->fd_ofiles[fd]) == NULL)
    117 		return (NULL);
    118 
    119 	if (FILE_IS_USABLE(fp) == 0)
    120 		return (NULL);
    121 
    122 	return (fp);
    123 }
    124 
    125 /*
    126  * System calls on descriptors.
    127  */
    128 
    129 /*
    130  * Duplicate a file descriptor.
    131  */
    132 /* ARGSUSED */
    133 int
    134 sys_dup(struct lwp *l, void *v, register_t *retval)
    135 {
    136 	struct sys_dup_args /* {
    137 		syscallarg(int)	fd;
    138 	} */ *uap = v;
    139 	struct file	*fp;
    140 	struct filedesc	*fdp;
    141 	struct proc	*p;
    142 	int		old, new, error;
    143 
    144 	p = l->l_proc;
    145 	fdp = p->p_fd;
    146 	old = SCARG(uap, fd);
    147 
    148  restart:
    149 	if ((fp = fd_getfile(fdp, old)) == NULL)
    150 		return (EBADF);
    151 
    152 	FILE_USE(fp);
    153 
    154 	if ((error = fdalloc(p, 0, &new)) != 0) {
    155 		if (error == ENOSPC) {
    156 			fdexpand(p);
    157 			FILE_UNUSE(fp, p);
    158 			goto restart;
    159 		}
    160 		FILE_UNUSE(fp, p);
    161 		return (error);
    162 	}
    163 
    164 	/* finishdup() will unuse the descriptors for us */
    165 	return (finishdup(p, old, new, retval));
    166 }
    167 
    168 /*
    169  * Duplicate a file descriptor to a particular value.
    170  */
    171 /* ARGSUSED */
    172 int
    173 sys_dup2(struct lwp *l, void *v, register_t *retval)
    174 {
    175 	struct sys_dup2_args /* {
    176 		syscallarg(int)	from;
    177 		syscallarg(int)	to;
    178 	} */ *uap = v;
    179 	struct file	*fp;
    180 	struct filedesc	*fdp;
    181 	struct proc	*p;
    182 	int		old, new, i, error;
    183 
    184 	p = l->l_proc;
    185 	fdp = p->p_fd;
    186 	old = SCARG(uap, from);
    187 	new = SCARG(uap, to);
    188 
    189  restart:
    190 	if ((fp = fd_getfile(fdp, old)) == NULL)
    191 		return (EBADF);
    192 
    193 	if ((u_int)new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    194 	    (u_int)new >= maxfiles)
    195 		return (EBADF);
    196 
    197 	if (old == new) {
    198 		*retval = new;
    199 		return (0);
    200 	}
    201 
    202 	FILE_USE(fp);
    203 
    204 	if (new >= fdp->fd_nfiles) {
    205 		if ((error = fdalloc(p, new, &i)) != 0) {
    206 			if (error == ENOSPC) {
    207 				fdexpand(p);
    208 				FILE_UNUSE(fp, p);
    209 				goto restart;
    210 			}
    211 			FILE_UNUSE(fp, p);
    212 			return (error);
    213 		}
    214 		if (new != i)
    215 			panic("dup2: fdalloc");
    216 	}
    217 
    218 	/*
    219 	 * finishdup() will close the file that's in the `new'
    220 	 * slot, if there's one there.
    221 	 */
    222 
    223 	/* finishdup() will unuse the descriptors for us */
    224 	return (finishdup(p, old, new, retval));
    225 }
    226 
    227 /*
    228  * The file control system call.
    229  */
    230 /* ARGSUSED */
    231 int
    232 sys_fcntl(struct lwp *l, void *v, register_t *retval)
    233 {
    234 	struct sys_fcntl_args /* {
    235 		syscallarg(int)		fd;
    236 		syscallarg(int)		cmd;
    237 		syscallarg(void *)	arg;
    238 	} */ *uap = v;
    239 	struct filedesc *fdp;
    240 	struct file	*fp;
    241 	struct proc	*p;
    242 	struct vnode	*vp;
    243 	int		fd, i, tmp, error, flg, cmd, newmin;
    244 	struct flock	fl;
    245 
    246 	p = l->l_proc;
    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 		(void) closef(delfp, p);
    468 	}
    469 	return (0);
    470 }
    471 
    472 void
    473 fdremove(struct filedesc *fdp, int fd)
    474 {
    475 
    476 	fdp->fd_ofiles[fd] = NULL;
    477 	fd_unused(fdp, fd);
    478 }
    479 
    480 int
    481 fdrelease(struct proc *p, int fd)
    482 {
    483 	struct filedesc	*fdp;
    484 	struct file	**fpp, *fp;
    485 
    486 	fdp = p->p_fd;
    487 	fpp = &fdp->fd_ofiles[fd];
    488 	fp = *fpp;
    489 	if (fp == NULL)
    490 		return (EBADF);
    491 
    492 	FILE_USE(fp);
    493 
    494 	*fpp = NULL;
    495 	fdp->fd_ofileflags[fd] = 0;
    496 	fd_unused(fdp, fd);
    497 	return (closef(fp, p));
    498 }
    499 
    500 /*
    501  * Close a file descriptor.
    502  */
    503 /* ARGSUSED */
    504 int
    505 sys_close(struct lwp *l, void *v, register_t *retval)
    506 {
    507 	struct sys_close_args /* {
    508 		syscallarg(int)	fd;
    509 	} */ *uap = v;
    510 	int		fd;
    511 	struct filedesc	*fdp;
    512 	struct proc *p;
    513 	struct file	*fp;
    514 
    515 	p = l->l_proc;
    516 	fd = SCARG(uap, fd);
    517 	fdp = p->p_fd;
    518 
    519 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    520 		return (EBADF);
    521 
    522 	return (fdrelease(p, fd));
    523 }
    524 
    525 /*
    526  * Return status information about a file descriptor.
    527  */
    528 /* ARGSUSED */
    529 int
    530 sys___fstat13(struct lwp *l, void *v, register_t *retval)
    531 {
    532 	struct sys___fstat13_args /* {
    533 		syscallarg(int)			fd;
    534 		syscallarg(struct stat *)	sb;
    535 	} */ *uap = v;
    536 	int		fd;
    537 	struct filedesc	*fdp;
    538 	struct file	*fp;
    539 	struct proc	*p;
    540 	struct stat	ub;
    541 	int		error;
    542 
    543 	p = l->l_proc;
    544 	fd = SCARG(uap, fd);
    545 	fdp = p->p_fd;
    546 
    547 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    548 		return (EBADF);
    549 
    550 	FILE_USE(fp);
    551 	error = (*fp->f_ops->fo_stat)(fp, &ub, p);
    552 	FILE_UNUSE(fp, p);
    553 
    554 	if (error == 0)
    555 		error = copyout(&ub, SCARG(uap, sb), sizeof(ub));
    556 
    557 	return (error);
    558 }
    559 
    560 /*
    561  * Return pathconf information about a file descriptor.
    562  */
    563 /* ARGSUSED */
    564 int
    565 sys_fpathconf(struct lwp *l, void *v, register_t *retval)
    566 {
    567 	struct sys_fpathconf_args /* {
    568 		syscallarg(int)	fd;
    569 		syscallarg(int)	name;
    570 	} */ *uap = v;
    571 	int		fd;
    572 	struct filedesc	*fdp;
    573 	struct file	*fp;
    574 	struct proc 	*p;
    575 	struct vnode	*vp;
    576 	int		error;
    577 
    578 	p = l->l_proc;
    579 	fd = SCARG(uap, fd);
    580 	fdp = p->p_fd;
    581 	error = 0;
    582 
    583 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    584 		return (EBADF);
    585 
    586 	FILE_USE(fp);
    587 
    588 	switch (fp->f_type) {
    589 
    590 	case DTYPE_SOCKET:
    591 	case DTYPE_PIPE:
    592 		if (SCARG(uap, name) != _PC_PIPE_BUF)
    593 			error = EINVAL;
    594 		else
    595 			*retval = PIPE_BUF;
    596 		break;
    597 
    598 	case DTYPE_VNODE:
    599 		vp = (struct vnode *)fp->f_data;
    600 		error = VOP_PATHCONF(vp, SCARG(uap, name), retval);
    601 		break;
    602 
    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 }
    895 
    896 /*
    897  * Make p2 share p1's filedesc structure.
    898  */
    899 void
    900 fdshare(struct proc *p1, struct proc *p2)
    901 {
    902 
    903 	p2->p_fd = p1->p_fd;
    904 	p1->p_fd->fd_refcnt++;
    905 }
    906 
    907 /*
    908  * Make this process not share its filedesc structure, maintaining
    909  * all file descriptor state.
    910  */
    911 void
    912 fdunshare(struct proc *p)
    913 {
    914 	struct filedesc *newfd;
    915 
    916 	if (p->p_fd->fd_refcnt == 1)
    917 		return;
    918 
    919 	newfd = fdcopy(p);
    920 	fdfree(p);
    921 	p->p_fd = newfd;
    922 }
    923 
    924 /*
    925  * Clear a process's fd table.
    926  */
    927 void
    928 fdclear(struct proc *p)
    929 {
    930 	struct filedesc *newfd;
    931 
    932 	newfd = fdinit(p);
    933 	fdfree(p);
    934 	p->p_fd = newfd;
    935 }
    936 
    937 /*
    938  * Copy a filedesc structure.
    939  */
    940 struct filedesc *
    941 fdcopy(struct proc *p)
    942 {
    943 	struct filedesc	*newfdp, *fdp;
    944 	struct file	**fpp;
    945 	int		i;
    946 
    947 	fdp = p->p_fd;
    948 	newfdp = pool_get(&filedesc0_pool, PR_WAITOK);
    949 	memcpy(newfdp, fdp, sizeof(struct filedesc));
    950 	newfdp->fd_refcnt = 1;
    951 
    952 	/*
    953 	 * If the number of open files fits in the internal arrays
    954 	 * of the open file structure, use them, otherwise allocate
    955 	 * additional memory for the number of descriptors currently
    956 	 * in use.
    957 	 */
    958 	if (newfdp->fd_lastfile < NDFILE) {
    959 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
    960 		newfdp->fd_ofileflags =
    961 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
    962 		i = NDFILE;
    963 	} else {
    964 		/*
    965 		 * Compute the smallest multiple of NDEXTENT needed
    966 		 * for the file descriptors currently in use,
    967 		 * allowing the table to shrink.
    968 		 */
    969 		i = newfdp->fd_nfiles;
    970 		while (i >= 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
    971 			i /= 2;
    972 		newfdp->fd_ofiles = malloc(i * OFILESIZE, M_FILEDESC, M_WAITOK);
    973 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
    974 	}
    975 	newfdp->fd_nfiles = i;
    976 	memcpy(newfdp->fd_ofiles, fdp->fd_ofiles, i * sizeof(struct file **));
    977 	memcpy(newfdp->fd_ofileflags, fdp->fd_ofileflags, i * sizeof(char));
    978 	fpp = newfdp->fd_ofiles;
    979 	for (i = newfdp->fd_lastfile; i >= 0; i--, fpp++)
    980 		if (*fpp != NULL)
    981 			(*fpp)->f_count++;
    982 	return (newfdp);
    983 }
    984 
    985 /*
    986  * Release a filedesc structure.
    987  */
    988 void
    989 fdfree(struct proc *p)
    990 {
    991 	struct filedesc	*fdp;
    992 	struct file	**fpp, *fp;
    993 	int		i;
    994 
    995 	fdp = p->p_fd;
    996 	if (--fdp->fd_refcnt > 0)
    997 		return;
    998 	fpp = fdp->fd_ofiles;
    999 	for (i = fdp->fd_lastfile; i >= 0; i--, fpp++) {
   1000 		fp = *fpp;
   1001 		if (fp != NULL) {
   1002 			*fpp = NULL;
   1003 			FILE_USE(fp);
   1004 			(void) closef(fp, p);
   1005 		}
   1006 	}
   1007 	p->p_fd = NULL;
   1008 	if (fdp->fd_nfiles > NDFILE)
   1009 		free(fdp->fd_ofiles, M_FILEDESC);
   1010 	pool_put(&filedesc0_pool, fdp);
   1011 }
   1012 
   1013 /*
   1014  * Internal form of close.
   1015  * Decrement reference count on file structure.
   1016  * Note: p may be NULL when closing a file
   1017  * that was being passed in a message.
   1018  *
   1019  * Note: we expect the caller is holding a usecount, and expects us
   1020  * to drop it (the caller thinks the file is going away forever).
   1021  */
   1022 int
   1023 closef(struct file *fp, struct proc *p)
   1024 {
   1025 	struct vnode	*vp;
   1026 	struct flock	lf;
   1027 	int		error;
   1028 
   1029 	if (fp == NULL)
   1030 		return (0);
   1031 
   1032 	/*
   1033 	 * POSIX record locking dictates that any close releases ALL
   1034 	 * locks owned by this process.  This is handled by setting
   1035 	 * a flag in the unlock to free ONLY locks obeying POSIX
   1036 	 * semantics, and not to free BSD-style file locks.
   1037 	 * If the descriptor was in a message, POSIX-style locks
   1038 	 * aren't passed with the descriptor.
   1039 	 */
   1040 	if (p && (p->p_flag & P_ADVLOCK) && fp->f_type == DTYPE_VNODE) {
   1041 		lf.l_whence = SEEK_SET;
   1042 		lf.l_start = 0;
   1043 		lf.l_len = 0;
   1044 		lf.l_type = F_UNLCK;
   1045 		vp = (struct vnode *)fp->f_data;
   1046 		(void) VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_POSIX);
   1047 	}
   1048 
   1049 	/*
   1050 	 * If WANTCLOSE is set, then the reference count on the file
   1051 	 * is 0, but there were multiple users of the file.  This can
   1052 	 * happen if a filedesc structure is shared by multiple
   1053 	 * processes.
   1054 	 */
   1055 	if (fp->f_iflags & FIF_WANTCLOSE) {
   1056 		/*
   1057 		 * Another user of the file is already closing, and is
   1058 		 * simply waiting for other users of the file to drain.
   1059 		 * Release our usecount, and wake up the closer if it
   1060 		 * is the only remaining use.
   1061 		 */
   1062 #ifdef DIAGNOSTIC
   1063 		if (fp->f_count != 0)
   1064 			panic("closef: wantclose and count != 0");
   1065 		if (fp->f_usecount < 2)
   1066 			panic("closef: wantclose and usecount < 2");
   1067 #endif
   1068 		if (--fp->f_usecount == 1)
   1069 			wakeup(&fp->f_usecount);
   1070 		return (0);
   1071 	} else {
   1072 		/*
   1073 		 * Decrement the reference count.  If we were not the
   1074 		 * last reference, then release our use and just
   1075 		 * return.
   1076 		 */
   1077 		if (--fp->f_count > 0) {
   1078 #ifdef DIAGNOSTIC
   1079 			if (fp->f_usecount < 1)
   1080 				panic("closef: no wantclose and usecount < 1");
   1081 #endif
   1082 			fp->f_usecount--;
   1083 			return (0);
   1084 		}
   1085 		if (fp->f_count < 0)
   1086 			panic("closef: count < 0");
   1087 	}
   1088 
   1089 	/*
   1090 	 * The reference count is now 0.  However, there may be
   1091 	 * multiple potential users of this file.  This can happen
   1092 	 * if multiple processes shared a single filedesc structure.
   1093 	 *
   1094 	 * Notify these potential users that the file is closing.
   1095 	 * This will prevent them from adding additional uses to
   1096 	 * the file.
   1097 	 */
   1098 	fp->f_iflags |= FIF_WANTCLOSE;
   1099 
   1100 	/*
   1101 	 * We expect the caller to add a use to the file.  So, if we
   1102 	 * are the last user, usecount will be 1.  If it is not, we
   1103 	 * must wait for the usecount to drain.  When it drains back
   1104 	 * to 1, we will be awakened so that we may proceed with the
   1105 	 * close.
   1106 	 */
   1107 #ifdef DIAGNOSTIC
   1108 	if (fp->f_usecount < 1)
   1109 		panic("closef: usecount < 1");
   1110 #endif
   1111 	while (fp->f_usecount > 1)
   1112 		(void) tsleep(&fp->f_usecount, PRIBIO, "closef", 0);
   1113 #ifdef DIAGNOSTIC
   1114 	if (fp->f_usecount != 1)
   1115 		panic("closef: usecount != 1");
   1116 #endif
   1117 
   1118 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
   1119 		lf.l_whence = SEEK_SET;
   1120 		lf.l_start = 0;
   1121 		lf.l_len = 0;
   1122 		lf.l_type = F_UNLCK;
   1123 		vp = (struct vnode *)fp->f_data;
   1124 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1125 	}
   1126 	if (fp->f_ops)
   1127 		error = (*fp->f_ops->fo_close)(fp, p);
   1128 	else
   1129 		error = 0;
   1130 
   1131 	/* Nothing references the file now, drop the final use (us). */
   1132 	fp->f_usecount--;
   1133 
   1134 	ffree(fp);
   1135 	return (error);
   1136 }
   1137 
   1138 /*
   1139  * Apply an advisory lock on a file descriptor.
   1140  *
   1141  * Just attempt to get a record lock of the requested type on
   1142  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
   1143  */
   1144 /* ARGSUSED */
   1145 int
   1146 sys_flock(struct lwp *l, void *v, register_t *retval)
   1147 {
   1148 	struct sys_flock_args /* {
   1149 		syscallarg(int)	fd;
   1150 		syscallarg(int)	how;
   1151 	} */ *uap = v;
   1152 	int		fd, how, error;
   1153 	struct proc	*p;
   1154 	struct filedesc	*fdp;
   1155 	struct file	*fp;
   1156 	struct vnode	*vp;
   1157 	struct flock	lf;
   1158 
   1159 	p = l->l_proc;
   1160 	fd = SCARG(uap, fd);
   1161 	how = SCARG(uap, how);
   1162 	fdp = p->p_fd;
   1163 	error = 0;
   1164 
   1165 	if ((fp = fd_getfile(fdp, fd)) == NULL)
   1166 		return (EBADF);
   1167 
   1168 	FILE_USE(fp);
   1169 
   1170 	if (fp->f_type != DTYPE_VNODE) {
   1171 		error = EOPNOTSUPP;
   1172 		goto out;
   1173 	}
   1174 
   1175 	vp = (struct vnode *)fp->f_data;
   1176 	lf.l_whence = SEEK_SET;
   1177 	lf.l_start = 0;
   1178 	lf.l_len = 0;
   1179 	if (how & LOCK_UN) {
   1180 		lf.l_type = F_UNLCK;
   1181 		fp->f_flag &= ~FHASLOCK;
   1182 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1183 		goto out;
   1184 	}
   1185 	if (how & LOCK_EX)
   1186 		lf.l_type = F_WRLCK;
   1187 	else if (how & LOCK_SH)
   1188 		lf.l_type = F_RDLCK;
   1189 	else {
   1190 		error = EINVAL;
   1191 		goto out;
   1192 	}
   1193 	fp->f_flag |= FHASLOCK;
   1194 	if (how & LOCK_NB)
   1195 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK);
   1196 	else
   1197 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
   1198 		    F_FLOCK|F_WAIT);
   1199  out:
   1200 	FILE_UNUSE(fp, p);
   1201 	return (error);
   1202 }
   1203 
   1204 /*
   1205  * File Descriptor pseudo-device driver (/dev/fd/).
   1206  *
   1207  * Opening minor device N dup()s the file (if any) connected to file
   1208  * descriptor N belonging to the calling process.  Note that this driver
   1209  * consists of only the ``open()'' routine, because all subsequent
   1210  * references to this file will be direct to the other driver.
   1211  */
   1212 /* ARGSUSED */
   1213 int
   1214 filedescopen(dev_t dev, int mode, int type, struct proc *p)
   1215 {
   1216 
   1217 	/*
   1218 	 * XXX Kludge: set p->p_dupfd to contain the value of the
   1219 	 * the file descriptor being sought for duplication. The error
   1220 	 * return ensures that the vnode for this device will be released
   1221 	 * by vn_open. Open will detect this special error and take the
   1222 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
   1223 	 * will simply report the error.
   1224 	 */
   1225 	p->p_dupfd = minor(dev);
   1226 	return (ENODEV);
   1227 }
   1228 
   1229 /*
   1230  * Duplicate the specified descriptor to a free descriptor.
   1231  */
   1232 int
   1233 dupfdopen(struct proc *p, int indx, int dfd, int mode, int error)
   1234 {
   1235 	struct filedesc	*fdp;
   1236 	struct file	*wfp, *fp;
   1237 
   1238 	fdp = p->p_fd;
   1239 	/*
   1240 	 * If the to-be-dup'd fd number is greater than the allowed number
   1241 	 * of file descriptors, or the fd to be dup'd has already been
   1242 	 * closed, reject.  Note, check for new == old is necessary as
   1243 	 * falloc could allocate an already closed to-be-dup'd descriptor
   1244 	 * as the new descriptor.
   1245 	 */
   1246 	fp = fdp->fd_ofiles[indx];
   1247 
   1248 	if ((wfp = fd_getfile(fdp, dfd)) == NULL)
   1249 		return (EBADF);
   1250 
   1251 	if (fp == wfp)
   1252 		return (EBADF);
   1253 
   1254 	FILE_USE(wfp);
   1255 
   1256 	/*
   1257 	 * There are two cases of interest here.
   1258 	 *
   1259 	 * For ENODEV simply dup (dfd) to file descriptor
   1260 	 * (indx) and return.
   1261 	 *
   1262 	 * For ENXIO steal away the file structure from (dfd) and
   1263 	 * store it in (indx).  (dfd) is effectively closed by
   1264 	 * this operation.
   1265 	 *
   1266 	 * Any other error code is just returned.
   1267 	 */
   1268 	switch (error) {
   1269 	case ENODEV:
   1270 		/*
   1271 		 * Check that the mode the file is being opened for is a
   1272 		 * subset of the mode of the existing descriptor.
   1273 		 */
   1274 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
   1275 			FILE_UNUSE(wfp, p);
   1276 			return (EACCES);
   1277 		}
   1278 		fdp->fd_ofiles[indx] = wfp;
   1279 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1280 		wfp->f_count++;
   1281 		fd_used(fdp, indx);
   1282 		FILE_UNUSE(wfp, p);
   1283 		return (0);
   1284 
   1285 	case ENXIO:
   1286 		/*
   1287 		 * Steal away the file pointer from dfd, and stuff it into indx.
   1288 		 */
   1289 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
   1290 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1291 		fdp->fd_ofiles[dfd] = NULL;
   1292 		fdp->fd_ofileflags[dfd] = 0;
   1293 		/*
   1294 		 * Complete the clean up of the filedesc structure by
   1295 		 * recomputing the various hints.
   1296 		 */
   1297 		fd_used(fdp, indx);
   1298 		fd_unused(fdp, dfd);
   1299 		FILE_UNUSE(wfp, p);
   1300 		return (0);
   1301 
   1302 	default:
   1303 		FILE_UNUSE(wfp, p);
   1304 		return (error);
   1305 	}
   1306 	/* NOTREACHED */
   1307 }
   1308 
   1309 /*
   1310  * fcntl call which is being passed to the file's fs.
   1311  */
   1312 int
   1313 fcntl_forfs(int fd, struct proc *p, int cmd, void *arg)
   1314 {
   1315 	struct file	*fp;
   1316 	struct filedesc	*fdp;
   1317 	int		error;
   1318 	u_int		size;
   1319 	caddr_t		data, memp;
   1320 #define STK_PARAMS	128
   1321 	char		stkbuf[STK_PARAMS];
   1322 
   1323 	/* fd's value was validated in sys_fcntl before calling this routine */
   1324 	fdp = p->p_fd;
   1325 	fp = fdp->fd_ofiles[fd];
   1326 
   1327 	if ((fp->f_flag & (FREAD | FWRITE)) == 0)
   1328 		return (EBADF);
   1329 
   1330 	/*
   1331 	 * Interpret high order word to find amount of data to be
   1332 	 * copied to/from the user's address space.
   1333 	 */
   1334 	size = (size_t)F_PARAM_LEN(cmd);
   1335 	if (size > F_PARAM_MAX)
   1336 		return (EINVAL);
   1337 	memp = NULL;
   1338 	if (size > sizeof(stkbuf)) {
   1339 		memp = (caddr_t)malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
   1340 		data = memp;
   1341 	} else
   1342 		data = stkbuf;
   1343 	if (cmd & F_FSIN) {
   1344 		if (size) {
   1345 			error = copyin(arg, data, size);
   1346 			if (error) {
   1347 				if (memp)
   1348 					free(memp, M_IOCTLOPS);
   1349 				return (error);
   1350 			}
   1351 		} else
   1352 			*(caddr_t *)data = arg;
   1353 	} else if ((cmd & F_FSOUT) && size)
   1354 		/*
   1355 		 * Zero the buffer so the user always
   1356 		 * gets back something deterministic.
   1357 		 */
   1358 		memset(data, 0, size);
   1359 	else if (cmd & F_FSVOID)
   1360 		*(caddr_t *)data = arg;
   1361 
   1362 
   1363 	error = (*fp->f_ops->fo_fcntl)(fp, cmd, data, p);
   1364 
   1365 	/*
   1366 	 * Copy any data to user, size was
   1367 	 * already set and checked above.
   1368 	 */
   1369 	if (error == 0 && (cmd & F_FSOUT) && size)
   1370 		error = copyout(data, arg, size);
   1371 	if (memp)
   1372 		free(memp, M_IOCTLOPS);
   1373 	return (error);
   1374 }
   1375 
   1376 /*
   1377  * Close any files on exec?
   1378  */
   1379 void
   1380 fdcloseexec(struct proc *p)
   1381 {
   1382 	struct filedesc	*fdp;
   1383 	int		fd;
   1384 
   1385 	fdunshare(p);
   1386 	cwdunshare(p);
   1387 
   1388 	fdp = p->p_fd;
   1389 	for (fd = 0; fd <= fdp->fd_lastfile; fd++)
   1390 		if (fdp->fd_ofileflags[fd] & UF_EXCLOSE)
   1391 			(void) fdrelease(p, fd);
   1392 }
   1393 
   1394 /*
   1395  * It is unsafe for set[ug]id processes to be started with file
   1396  * descriptors 0..2 closed, as these descriptors are given implicit
   1397  * significance in the Standard C library.  fdcheckstd() will create a
   1398  * descriptor referencing /dev/null for each of stdin, stdout, and
   1399  * stderr that is not already open.
   1400  */
   1401 #define CHECK_UPTO 3
   1402 int
   1403 fdcheckstd(p)
   1404 	struct proc *p;
   1405 {
   1406 	struct nameidata nd;
   1407 	struct filedesc *fdp;
   1408 	struct file *fp;
   1409 	struct file *devnullfp;
   1410 	struct proc *pp;
   1411 	register_t retval;
   1412 	int fd, i, error, flags = FREAD|FWRITE, devnull = -1;
   1413 	char closed[CHECK_UPTO * 3 + 1], which[3 + 1];
   1414 
   1415 	closed[0] = '\0';
   1416 	if ((fdp = p->p_fd) == NULL)
   1417 		return (0);
   1418 	for (i = 0; i < CHECK_UPTO; i++) {
   1419 		if (fdp->fd_ofiles[i] != NULL)
   1420 			continue;
   1421 		snprintf(which, sizeof(which), ",%d", i);
   1422 		strcat(closed, which);
   1423 		if (devnull < 0) {
   1424 			if ((error = falloc(p, &fp, &fd)) != 0)
   1425 				return (error);
   1426 			NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null",
   1427 			    p);
   1428 			if ((error = vn_open(&nd, flags, 0)) != 0) {
   1429 				FILE_UNUSE(fp, p);
   1430 				ffree(fp);
   1431 				fdremove(p->p_fd, fd);
   1432 				return (error);
   1433 			}
   1434 			fp->f_data = (caddr_t)nd.ni_vp;
   1435 			fp->f_flag = flags;
   1436 			fp->f_ops = &vnops;
   1437 			fp->f_type = DTYPE_VNODE;
   1438 			VOP_UNLOCK(nd.ni_vp, 0);
   1439 			devnull = fd;
   1440 			devnullfp = fp;
   1441 			FILE_SET_MATURE(fp);
   1442 			FILE_UNUSE(fp, p);
   1443 		} else {
   1444 restart:
   1445 			if ((error = fdalloc(p, 0, &fd)) != 0) {
   1446 				if (error == ENOSPC) {
   1447 					fdexpand(p);
   1448 					goto restart;
   1449 				}
   1450 				return (error);
   1451 			}
   1452 
   1453 			FILE_USE(devnullfp);
   1454 			/* finishdup() will unuse the descriptors for us */
   1455 			if ((error = finishdup(p, devnull, fd, &retval)) != 0)
   1456 				return (error);
   1457 		}
   1458 	}
   1459 	if (closed[0] != '\0') {
   1460 		pp = p->p_pptr;
   1461 		log(LOG_WARNING, "set{u,g}id pid %d (%s) "
   1462 		    "was invoked by uid %d ppid %d (%s) "
   1463 		    "with fd %s closed\n",
   1464 		    p->p_pid, p->p_comm, pp->p_ucred->cr_uid,
   1465 		    pp->p_pid, pp->p_comm, &closed[1]);
   1466 	}
   1467 	return (0);
   1468 }
   1469 #undef CHECK_UPTO
   1470