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