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