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