Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.110.2.4
      1 /*	$NetBSD: kern_descrip.c,v 1.110.2.4 2004/09/21 13:35:03 skrll 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. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)kern_descrip.c	8.8 (Berkeley) 2/14/95
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: kern_descrip.c,v 1.110.2.4 2004/09/21 13:35:03 skrll Exp $");
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/filedesc.h>
     45 #include <sys/kernel.h>
     46 #include <sys/vnode.h>
     47 #include <sys/proc.h>
     48 #include <sys/file.h>
     49 #include <sys/namei.h>
     50 #include <sys/socket.h>
     51 #include <sys/socketvar.h>
     52 #include <sys/stat.h>
     53 #include <sys/ioctl.h>
     54 #include <sys/fcntl.h>
     55 #include <sys/malloc.h>
     56 #include <sys/pool.h>
     57 #include <sys/syslog.h>
     58 #include <sys/unistd.h>
     59 #include <sys/resourcevar.h>
     60 #include <sys/conf.h>
     61 #include <sys/event.h>
     62 
     63 #include <sys/mount.h>
     64 #include <sys/sa.h>
     65 #include <sys/syscallargs.h>
     66 
     67 /*
     68  * Descriptor management.
     69  */
     70 struct filelist	filehead;	/* head of list of open files */
     71 int		nfiles;		/* actual number of open files */
     72 POOL_INIT(file_pool, sizeof(struct file), 0, 0, 0, "filepl",
     73     &pool_allocator_nointr);
     74 POOL_INIT(cwdi_pool, sizeof(struct cwdinfo), 0, 0, 0, "cwdipl",
     75     &pool_allocator_nointr);
     76 POOL_INIT(filedesc0_pool, sizeof(struct filedesc0), 0, 0, 0, "fdescpl",
     77     &pool_allocator_nointr);
     78 
     79 /* Global file list lock */
     80 static struct simplelock filelist_slock = SIMPLELOCK_INITIALIZER;
     81 
     82 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
     83 MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
     84 MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
     85 
     86 static __inline void	fd_used(struct filedesc *, int);
     87 static __inline void	fd_unused(struct filedesc *, int);
     88 static __inline int	find_next_zero(uint32_t *, int, u_int);
     89 int			finishdup(struct lwp *, int, int, register_t *);
     90 int			find_last_set(struct filedesc *, int);
     91 int			fcntl_forfs(int, struct lwp *, int, void *);
     92 
     93 dev_type_open(filedescopen);
     94 
     95 const struct cdevsw filedesc_cdevsw = {
     96 	filedescopen, noclose, noread, nowrite, noioctl,
     97 	nostop, notty, nopoll, nommap, nokqfilter,
     98 };
     99 
    100 static __inline int
    101 find_next_zero(uint32_t *bitmap, int want, u_int bits)
    102 {
    103 	int i, off, maxoff;
    104 	uint32_t sub;
    105 
    106 	if (want > bits)
    107 		return -1;
    108 
    109 	off = want >> NDENTRYSHIFT;
    110 	i = want & NDENTRYMASK;
    111 	if (i) {
    112 		sub = bitmap[off] | ((u_int)~0 >> (NDENTRIES - i));
    113 		if (sub != ~0)
    114 			goto found;
    115 		off++;
    116 	}
    117 
    118 	maxoff = NDLOSLOTS(bits);
    119 	while (off < maxoff) {
    120 		if ((sub = bitmap[off]) != ~0)
    121 			goto found;
    122 		off++;
    123 	}
    124 
    125 	return (-1);
    126 
    127  found:
    128 	return (off << NDENTRYSHIFT) + ffs(~sub) - 1;
    129 }
    130 
    131 int
    132 find_last_set(struct filedesc *fd, int last)
    133 {
    134 	int off, i;
    135 	struct file **ofiles = fd->fd_ofiles;
    136 	uint32_t *bitmap = fd->fd_lomap;
    137 
    138 	off = (last - 1) >> NDENTRYSHIFT;
    139 
    140 	while (off >= 0 && !bitmap[off])
    141 		off--;
    142 
    143 	if (off < 0)
    144 		return (0);
    145 
    146 	i = ((off + 1) << NDENTRYSHIFT) - 1;
    147 	if (i >= last)
    148 		i = last - 1;
    149 
    150 	while (i > 0 && ofiles[i] == NULL)
    151 		i--;
    152 
    153 	return (i);
    154 }
    155 
    156 static __inline void
    157 fd_used(struct filedesc *fdp, int fd)
    158 {
    159 	u_int off = fd >> NDENTRYSHIFT;
    160 
    161 	LOCK_ASSERT(simple_lock_held(&fdp->fd_slock));
    162 	KDASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) == 0);
    163 
    164 	fdp->fd_lomap[off] |= 1 << (fd & NDENTRYMASK);
    165 	if (fdp->fd_lomap[off] == ~0) {
    166 		KDASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
    167 		    (1 << (off & NDENTRYMASK))) == 0);
    168 		fdp->fd_himap[off >> NDENTRYSHIFT] |= 1 << (off & NDENTRYMASK);
    169 	}
    170 
    171 	if (fd > fdp->fd_lastfile)
    172 		fdp->fd_lastfile = fd;
    173 }
    174 
    175 static __inline void
    176 fd_unused(struct filedesc *fdp, int fd)
    177 {
    178 	u_int off = fd >> NDENTRYSHIFT;
    179 
    180 	LOCK_ASSERT(simple_lock_held(&fdp->fd_slock));
    181 	if (fd < fdp->fd_freefile)
    182 		fdp->fd_freefile = fd;
    183 
    184 	if (fdp->fd_lomap[off] == ~0) {
    185 		KDASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
    186 		    (1 << (off & NDENTRYMASK))) != 0);
    187 		fdp->fd_himap[off >> NDENTRYSHIFT] &=
    188 		    ~(1 << (off & NDENTRYMASK));
    189 	}
    190 	KDASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0);
    191 	fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
    192 
    193 #ifdef DIAGNOSTIC
    194 	if (fd > fdp->fd_lastfile)
    195 		panic("fd_unused: fd_lastfile inconsistent");
    196 #endif
    197 	if (fd == fdp->fd_lastfile)
    198 		fdp->fd_lastfile = find_last_set(fdp, fd);
    199 }
    200 
    201 /*
    202  * Lookup the file structure corresponding to a file descriptor
    203  * and return it locked.
    204  * Note: typical usage is: `fp = fd_getfile(..); FILE_USE(fp);'
    205  * The locking strategy has been optimised for this case, i.e.
    206  * fd_getfile() returns the file locked while FILE_USE() will increment
    207  * the file's use count and unlock.
    208  */
    209 struct file *
    210 fd_getfile(struct filedesc *fdp, int fd)
    211 {
    212 	struct file *fp;
    213 
    214 	if ((u_int) fd >= fdp->fd_nfiles || (fp = fdp->fd_ofiles[fd]) == NULL)
    215 		return (NULL);
    216 
    217 	simple_lock(&fp->f_slock);
    218 	if (FILE_IS_USABLE(fp) == 0) {
    219 		simple_unlock(&fp->f_slock);
    220 		return (NULL);
    221 	}
    222 
    223 	return (fp);
    224 }
    225 
    226 /*
    227  * System calls on descriptors.
    228  */
    229 
    230 /*
    231  * Duplicate a file descriptor.
    232  */
    233 /* ARGSUSED */
    234 int
    235 sys_dup(struct lwp *l, void *v, register_t *retval)
    236 {
    237 	struct sys_dup_args /* {
    238 		syscallarg(int)	fd;
    239 	} */ *uap = v;
    240 	struct file	*fp;
    241 	struct filedesc	*fdp;
    242 	struct proc	*p;
    243 	int		old, new, error;
    244 
    245 	p = l->l_proc;
    246 	fdp = p->p_fd;
    247 	old = SCARG(uap, fd);
    248 
    249  restart:
    250 	if ((fp = fd_getfile(fdp, old)) == NULL)
    251 		return (EBADF);
    252 
    253 	FILE_USE(fp);
    254 
    255 	if ((error = fdalloc(p, 0, &new)) != 0) {
    256 		if (error == ENOSPC) {
    257 			fdexpand(p);
    258 			FILE_UNUSE(fp, l);
    259 			goto restart;
    260 		}
    261 		FILE_UNUSE(fp, l);
    262 		return (error);
    263 	}
    264 
    265 	/* finishdup() will unuse the descriptors for us */
    266 	return (finishdup(l, old, new, retval));
    267 }
    268 
    269 /*
    270  * Duplicate a file descriptor to a particular value.
    271  */
    272 /* ARGSUSED */
    273 int
    274 sys_dup2(struct lwp *l, void *v, register_t *retval)
    275 {
    276 	struct sys_dup2_args /* {
    277 		syscallarg(int)	from;
    278 		syscallarg(int)	to;
    279 	} */ *uap = v;
    280 	struct file	*fp;
    281 	struct filedesc	*fdp;
    282 	struct proc	*p;
    283 	int		old, new, i, error;
    284 
    285 	p = l->l_proc;
    286 	fdp = p->p_fd;
    287 	old = SCARG(uap, from);
    288 	new = SCARG(uap, to);
    289 
    290  restart:
    291 	if ((fp = fd_getfile(fdp, old)) == NULL)
    292 		return (EBADF);
    293 
    294 	if ((u_int)new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    295 	    (u_int)new >= maxfiles) {
    296 		simple_unlock(&fp->f_slock);
    297 		return (EBADF);
    298 	}
    299 
    300 	if (old == new) {
    301 		simple_unlock(&fp->f_slock);
    302 		*retval = new;
    303 		return (0);
    304 	}
    305 
    306 	FILE_USE(fp);
    307 
    308 	if (new >= fdp->fd_nfiles) {
    309 		if ((error = fdalloc(p, new, &i)) != 0) {
    310 			if (error == ENOSPC) {
    311 				fdexpand(p);
    312 				FILE_UNUSE(fp, l);
    313 				goto restart;
    314 			}
    315 			FILE_UNUSE(fp, l);
    316 			return (error);
    317 		}
    318 		if (new != i)
    319 			panic("dup2: fdalloc");
    320 	} else {
    321 		simple_lock(&fdp->fd_slock);
    322 		/*
    323 		 * Mark `new' slot "used" only if it was empty.
    324 		 */
    325 		if (fdp->fd_ofiles[new] == NULL)
    326 			fd_used(fdp, new);
    327 		simple_unlock(&fdp->fd_slock);
    328 	}
    329 
    330 	/*
    331 	 * finishdup() will close the file that's in the `new'
    332 	 * slot, if there's one there.
    333 	 */
    334 
    335 	/* finishdup() will unuse the descriptors for us */
    336 	return (finishdup(l, old, new, retval));
    337 }
    338 
    339 /*
    340  * The file control system call.
    341  */
    342 /* ARGSUSED */
    343 int
    344 sys_fcntl(struct lwp *l, void *v, register_t *retval)
    345 {
    346 	struct sys_fcntl_args /* {
    347 		syscallarg(int)		fd;
    348 		syscallarg(int)		cmd;
    349 		syscallarg(void *)	arg;
    350 	} */ *uap = v;
    351 	struct filedesc *fdp;
    352 	struct file	*fp;
    353 	struct proc	*p;
    354 	struct vnode	*vp;
    355 	int		fd, i, tmp, error, flg, cmd, newmin;
    356 	struct flock	fl;
    357 
    358 	p = l->l_proc;
    359 	fd = SCARG(uap, fd);
    360 	cmd = SCARG(uap, cmd);
    361 	fdp = p->p_fd;
    362 	error = 0;
    363 	flg = F_POSIX;
    364 
    365 	switch (cmd) {
    366 	case F_CLOSEM:
    367 		if (fd < 0)
    368 			return EBADF;
    369 		while (fdp->fd_lastfile >= fd)
    370 			fdrelease(l, fdp->fd_lastfile);
    371 		return 0;
    372 
    373 	case F_MAXFD:
    374 		*retval = fdp->fd_lastfile;
    375 		return 0;
    376 
    377 	default:
    378 		/* Handled below */
    379 		break;
    380 	}
    381 
    382  restart:
    383 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    384 		return (EBADF);
    385 
    386 	FILE_USE(fp);
    387 
    388 	if ((cmd & F_FSCTL)) {
    389 		error = fcntl_forfs(fd, l, cmd, SCARG(uap, arg));
    390 		goto out;
    391 	}
    392 
    393 	switch (cmd) {
    394 
    395 	case F_DUPFD:
    396 		newmin = (long)SCARG(uap, arg);
    397 		if ((u_int)newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    398 		    (u_int)newmin >= maxfiles) {
    399 			error = EINVAL;
    400 			goto out;
    401 		}
    402 		if ((error = fdalloc(p, newmin, &i)) != 0) {
    403 			if (error == ENOSPC) {
    404 				fdexpand(p);
    405 				FILE_UNUSE(fp, l);
    406 				goto restart;
    407 			}
    408 			goto out;
    409 		}
    410 
    411 		/* finishdup() will unuse the descriptors for us */
    412 		return (finishdup(l, fd, i, retval));
    413 
    414 	case F_GETFD:
    415 		*retval = fdp->fd_ofileflags[fd] & UF_EXCLOSE ? 1 : 0;
    416 		break;
    417 
    418 	case F_SETFD:
    419 		if ((long)SCARG(uap, arg) & 1)
    420 			fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
    421 		else
    422 			fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
    423 		break;
    424 
    425 	case F_GETFL:
    426 		*retval = OFLAGS(fp->f_flag);
    427 		break;
    428 
    429 	case F_SETFL:
    430 		tmp = FFLAGS((long)SCARG(uap, arg)) & FCNTLFLAGS;
    431 		error = (*fp->f_ops->fo_fcntl)(fp, F_SETFL, &tmp, l);
    432 		if (error)
    433 			break;
    434 		i = tmp ^ fp->f_flag;
    435 		if (i & FNONBLOCK) {
    436 			int fl = tmp & FNONBLOCK;
    437 			error = (*fp->f_ops->fo_ioctl)(fp, FIONBIO, &fl, l);
    438 			if (error)
    439 				goto reset_fcntl;
    440 		}
    441 		if (i & FASYNC) {
    442 			int fl = tmp & FASYNC;
    443 			error = (*fp->f_ops->fo_ioctl)(fp, FIOASYNC, &fl, l);
    444 			if (error) {
    445 				if (i & FNONBLOCK) {
    446 					tmp = fp->f_flag & FNONBLOCK;
    447 					(void)(*fp->f_ops->fo_ioctl)(fp,
    448 						FIONBIO, &tmp, l);
    449 				}
    450 				goto reset_fcntl;
    451 			}
    452 		}
    453 		fp->f_flag = (fp->f_flag & ~FCNTLFLAGS) | tmp;
    454 		break;
    455 	    reset_fcntl:
    456 		(void)(*fp->f_ops->fo_fcntl)(fp, F_SETFL, &fp->f_flag, l);
    457 		break;
    458 
    459 	case F_GETOWN:
    460 		error = (*fp->f_ops->fo_ioctl)(fp, FIOGETOWN, retval, l);
    461 		break;
    462 
    463 	case F_SETOWN:
    464 		tmp = (int)(intptr_t) SCARG(uap, arg);
    465 		error = (*fp->f_ops->fo_ioctl)(fp, FIOSETOWN, &tmp, l);
    466 		break;
    467 
    468 	case F_SETLKW:
    469 		flg |= F_WAIT;
    470 		/* Fall into F_SETLK */
    471 
    472 	case F_SETLK:
    473 		if (fp->f_type != DTYPE_VNODE) {
    474 			error = EINVAL;
    475 			goto out;
    476 		}
    477 		vp = (struct vnode *)fp->f_data;
    478 		/* Copy in the lock structure */
    479 		error = copyin(SCARG(uap, arg), &fl, sizeof(fl));
    480 		if (error)
    481 			goto out;
    482 		if (fl.l_whence == SEEK_CUR)
    483 			fl.l_start += fp->f_offset;
    484 		switch (fl.l_type) {
    485 		case F_RDLCK:
    486 			if ((fp->f_flag & FREAD) == 0) {
    487 				error = EBADF;
    488 				goto out;
    489 			}
    490 			p->p_flag |= P_ADVLOCK;
    491 			error = VOP_ADVLOCK(vp, p, F_SETLK, &fl, flg);
    492 			goto out;
    493 
    494 		case F_WRLCK:
    495 			if ((fp->f_flag & FWRITE) == 0) {
    496 				error = EBADF;
    497 				goto out;
    498 			}
    499 			p->p_flag |= P_ADVLOCK;
    500 			error = VOP_ADVLOCK(vp, p, F_SETLK, &fl, flg);
    501 			goto out;
    502 
    503 		case F_UNLCK:
    504 			error = VOP_ADVLOCK(vp, p, F_UNLCK, &fl, F_POSIX);
    505 			goto out;
    506 
    507 		default:
    508 			error = EINVAL;
    509 			goto out;
    510 		}
    511 
    512 	case F_GETLK:
    513 		if (fp->f_type != DTYPE_VNODE) {
    514 			error = EINVAL;
    515 			goto out;
    516 		}
    517 		vp = (struct vnode *)fp->f_data;
    518 		/* Copy in the lock structure */
    519 		error = copyin(SCARG(uap, arg), &fl, sizeof(fl));
    520 		if (error)
    521 			goto out;
    522 		if (fl.l_whence == SEEK_CUR)
    523 			fl.l_start += fp->f_offset;
    524 		if (fl.l_type != F_RDLCK &&
    525 		    fl.l_type != F_WRLCK &&
    526 		    fl.l_type != F_UNLCK) {
    527 			error = EINVAL;
    528 			goto out;
    529 		}
    530 		error = VOP_ADVLOCK(vp, p, F_GETLK, &fl, F_POSIX);
    531 		if (error)
    532 			goto out;
    533 		error = copyout(&fl, SCARG(uap, arg), sizeof(fl));
    534 		break;
    535 
    536 	default:
    537 		error = EINVAL;
    538 	}
    539 
    540  out:
    541 	FILE_UNUSE(fp, l);
    542 	return (error);
    543 }
    544 
    545 /*
    546  * Common code for dup, dup2, and fcntl(F_DUPFD).
    547  */
    548 int
    549 finishdup(struct lwp *l, int old, int new, register_t *retval)
    550 {
    551 	struct proc *p = l->l_proc;
    552 	struct file *fp, *delfp;
    553 	struct filedesc	*fdp;
    554 
    555 	fdp = p->p_fd;
    556 
    557 	/*
    558 	 * If there is a file in the new slot, remember it so we
    559 	 * can close it after we've finished the dup.  We need
    560 	 * to do it after the dup is finished, since closing
    561 	 * the file may block.
    562 	 *
    563 	 * Note: `old' is already used for us.
    564 	 * Note: Caller already marked `new' slot "used".
    565 	 */
    566 	simple_lock(&fdp->fd_slock);
    567 	delfp = fdp->fd_ofiles[new];
    568 
    569 	fp = fdp->fd_ofiles[old];
    570 	KDASSERT(fp != NULL);
    571 	fdp->fd_ofiles[new] = fp;
    572 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
    573 	simple_unlock(&fdp->fd_slock);
    574 
    575 	*retval = new;
    576 	simple_lock(&fp->f_slock);
    577 	fp->f_count++;
    578 	FILE_UNUSE_HAVELOCK(fp, l);
    579 
    580 	if (delfp != NULL) {
    581 		simple_lock(&delfp->f_slock);
    582 		FILE_USE(delfp);
    583 		if (new < fdp->fd_knlistsize)
    584 			knote_fdclose(l, new);
    585 		(void) closef(delfp, l);
    586 	}
    587 	return (0);
    588 }
    589 
    590 void
    591 fdremove(struct filedesc *fdp, int fd)
    592 {
    593 
    594 	simple_lock(&fdp->fd_slock);
    595 	fdp->fd_ofiles[fd] = NULL;
    596 	fd_unused(fdp, fd);
    597 	simple_unlock(&fdp->fd_slock);
    598 }
    599 
    600 int
    601 fdrelease(struct lwp *l, int fd)
    602 {
    603 	struct proc *p = l->l_proc;
    604 	struct file **fpp, *fp;
    605 	struct filedesc	*fdp;
    606 
    607 	fdp = p->p_fd;
    608 	simple_lock(&fdp->fd_slock);
    609 	if ((u_int) fd > fdp->fd_lastfile)
    610 		goto badf;
    611 	fpp = &fdp->fd_ofiles[fd];
    612 	fp = *fpp;
    613 	if (fp == NULL)
    614 		goto badf;
    615 
    616 	simple_lock(&fp->f_slock);
    617 	if (!FILE_IS_USABLE(fp)) {
    618 		simple_unlock(&fp->f_slock);
    619 		goto badf;
    620 	}
    621 
    622 	FILE_USE(fp);
    623 
    624 	*fpp = NULL;
    625 	fdp->fd_ofileflags[fd] = 0;
    626 	fd_unused(fdp, fd);
    627 	simple_unlock(&fdp->fd_slock);
    628 	if (fd < fdp->fd_knlistsize)
    629 		knote_fdclose(l, fd);
    630 	return (closef(fp, l));
    631 
    632 badf:
    633 	simple_unlock(&fdp->fd_slock);
    634 	return (EBADF);
    635 }
    636 
    637 /*
    638  * Close a file descriptor.
    639  */
    640 /* ARGSUSED */
    641 int
    642 sys_close(struct lwp *l, void *v, register_t *retval)
    643 {
    644 	struct sys_close_args /* {
    645 		syscallarg(int)	fd;
    646 	} */ *uap = v;
    647 	int		fd;
    648 	struct filedesc	*fdp;
    649 	struct proc *p;
    650 
    651 	p = l->l_proc;
    652 	fd = SCARG(uap, fd);
    653 	fdp = p->p_fd;
    654 
    655 #if 0
    656 	if (fd_getfile(fdp, fd) == NULL)
    657 		return (EBADF);
    658 #endif
    659 
    660 	return (fdrelease(l, fd));
    661 }
    662 
    663 /*
    664  * Return status information about a file descriptor.
    665  */
    666 /* ARGSUSED */
    667 int
    668 sys___fstat13(struct lwp *l, void *v, register_t *retval)
    669 {
    670 	struct sys___fstat13_args /* {
    671 		syscallarg(int)			fd;
    672 		syscallarg(struct stat *)	sb;
    673 	} */ *uap = v;
    674 	int		fd;
    675 	struct filedesc	*fdp;
    676 	struct file	*fp;
    677 	struct proc	*p;
    678 	struct stat	ub;
    679 	int		error;
    680 
    681 	p = l->l_proc;
    682 	fd = SCARG(uap, fd);
    683 	fdp = p->p_fd;
    684 
    685 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    686 		return (EBADF);
    687 
    688 	FILE_USE(fp);
    689 	error = (*fp->f_ops->fo_stat)(fp, &ub, l);
    690 	FILE_UNUSE(fp, l);
    691 
    692 	if (error == 0)
    693 		error = copyout(&ub, SCARG(uap, sb), sizeof(ub));
    694 
    695 	return (error);
    696 }
    697 
    698 /*
    699  * Return pathconf information about a file descriptor.
    700  */
    701 /* ARGSUSED */
    702 int
    703 sys_fpathconf(struct lwp *l, void *v, register_t *retval)
    704 {
    705 	struct sys_fpathconf_args /* {
    706 		syscallarg(int)	fd;
    707 		syscallarg(int)	name;
    708 	} */ *uap = v;
    709 	int		fd;
    710 	struct filedesc	*fdp;
    711 	struct file	*fp;
    712 	struct proc 	*p;
    713 	struct vnode	*vp;
    714 	int		error;
    715 
    716 	p = l->l_proc;
    717 	fd = SCARG(uap, fd);
    718 	fdp = p->p_fd;
    719 	error = 0;
    720 
    721 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    722 		return (EBADF);
    723 
    724 	FILE_USE(fp);
    725 
    726 	switch (fp->f_type) {
    727 
    728 	case DTYPE_SOCKET:
    729 	case DTYPE_PIPE:
    730 		if (SCARG(uap, name) != _PC_PIPE_BUF)
    731 			error = EINVAL;
    732 		else
    733 			*retval = PIPE_BUF;
    734 		break;
    735 
    736 	case DTYPE_VNODE:
    737 		vp = (struct vnode *)fp->f_data;
    738 		error = VOP_PATHCONF(vp, SCARG(uap, name), retval);
    739 		break;
    740 
    741 	case DTYPE_KQUEUE:
    742 		error = EINVAL;
    743 		break;
    744 
    745 	default:
    746 		error = EOPNOTSUPP;
    747 		break;
    748 	}
    749 
    750 	FILE_UNUSE(fp, l);
    751 	return (error);
    752 }
    753 
    754 /*
    755  * Allocate a file descriptor for the process.
    756  */
    757 int	fdexpanded;		/* XXX: what else uses this? */
    758 
    759 int
    760 fdalloc(struct proc *p, int want, int *result)
    761 {
    762 	struct filedesc	*fdp;
    763 	int i, lim, last, error;
    764 	u_int off, new;
    765 
    766 	fdp = p->p_fd;
    767 	simple_lock(&fdp->fd_slock);
    768 
    769 	/*
    770 	 * Search for a free descriptor starting at the higher
    771 	 * of want or fd_freefile.  If that fails, consider
    772 	 * expanding the ofile array.
    773 	 */
    774 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    775 	last = min(fdp->fd_nfiles, lim);
    776  again:
    777 	if ((i = want) < fdp->fd_freefile)
    778 		i = fdp->fd_freefile;
    779 	off = i >> NDENTRYSHIFT;
    780 	new = find_next_zero(fdp->fd_himap, off,
    781 	    (last + NDENTRIES - 1) >> NDENTRYSHIFT);
    782 	if (new != -1) {
    783 		i = find_next_zero(&fdp->fd_lomap[new],
    784 		    new > off ? 0 : i & NDENTRYMASK, NDENTRIES);
    785 		if (i == -1) {
    786 			/*
    787 			 * free file descriptor in this block was
    788 			 * below want, try again with higher want.
    789 			 */
    790 			want = (new + 1) << NDENTRYSHIFT;
    791 			goto again;
    792 		}
    793 		i += (new << NDENTRYSHIFT);
    794 		if (i < last) {
    795 			if (fdp->fd_ofiles[i] == NULL) {
    796 				fd_used(fdp, i);
    797 				if (want <= fdp->fd_freefile)
    798 					fdp->fd_freefile = i;
    799 				*result = i;
    800 				error = 0;
    801 				goto out;
    802 			}
    803 		}
    804 	}
    805 
    806 	/* No space in current array.  Expand or let the caller do it. */
    807 	error = (fdp->fd_nfiles >= lim) ? EMFILE : ENOSPC;
    808 
    809 out:
    810 	simple_unlock(&fdp->fd_slock);
    811 	return (error);
    812 }
    813 
    814 void
    815 fdexpand(struct proc *p)
    816 {
    817 	struct filedesc	*fdp;
    818 	int		i, nfiles, oldnfiles;
    819 	struct file	**newofile;
    820 	char		*newofileflags;
    821 	uint32_t	*newhimap = NULL, *newlomap = NULL;
    822 
    823 	fdp = p->p_fd;
    824 
    825 restart:
    826 	oldnfiles = fdp->fd_nfiles;
    827 
    828 	if (oldnfiles < NDEXTENT)
    829 		nfiles = NDEXTENT;
    830 	else
    831 		nfiles = 2 * oldnfiles;
    832 
    833 	newofile = malloc(nfiles * OFILESIZE, M_FILEDESC, M_WAITOK);
    834 	if (NDHISLOTS(nfiles) > NDHISLOTS(oldnfiles)) {
    835 		newhimap = malloc(NDHISLOTS(nfiles) * sizeof(uint32_t),
    836 		    M_FILEDESC, M_WAITOK);
    837 		newlomap = malloc(NDLOSLOTS(nfiles) * sizeof(uint32_t),
    838 		    M_FILEDESC, M_WAITOK);
    839 	}
    840 
    841 	simple_lock(&fdp->fd_slock);
    842 	/* lock fdp */
    843 	if (fdp->fd_nfiles != oldnfiles) {
    844 		/* fdp changed; retry */
    845 		simple_unlock(&fdp->fd_slock);
    846 		free(newofile, M_FILEDESC);
    847 		if (newhimap != NULL) free(newhimap, M_FILEDESC);
    848 		if (newlomap != NULL) free(newlomap, M_FILEDESC);
    849 		goto restart;
    850 	}
    851 
    852 	newofileflags = (char *) &newofile[nfiles];
    853 	/*
    854 	 * Copy the existing ofile and ofileflags arrays
    855 	 * and zero the new portion of each array.
    856 	 */
    857 	memcpy(newofile, fdp->fd_ofiles,
    858 	    (i = sizeof(struct file *) * fdp->fd_nfiles));
    859 	memset((char *)newofile + i, 0,
    860 	    nfiles * sizeof(struct file *) - i);
    861 	memcpy(newofileflags, fdp->fd_ofileflags,
    862 	    (i = sizeof(char) * fdp->fd_nfiles));
    863 	memset(newofileflags + i, 0, nfiles * sizeof(char) - i);
    864 	if (oldnfiles > NDFILE)
    865 		free(fdp->fd_ofiles, M_FILEDESC);
    866 
    867 	if (NDHISLOTS(nfiles) > NDHISLOTS(oldnfiles)) {
    868 		memcpy(newhimap, fdp->fd_himap,
    869 		    (i = NDHISLOTS(oldnfiles) * sizeof(uint32_t)));
    870 		memset((char *)newhimap + i, 0,
    871 		    NDHISLOTS(nfiles) * sizeof(uint32_t) - i);
    872 
    873 		memcpy(newlomap, fdp->fd_lomap,
    874 		    (i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t)));
    875 		memset((char *)newlomap + i, 0,
    876 		    NDLOSLOTS(nfiles) * sizeof(uint32_t) - i);
    877 
    878 		if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
    879 			free(fdp->fd_himap, M_FILEDESC);
    880 			free(fdp->fd_lomap, M_FILEDESC);
    881 		}
    882 		fdp->fd_himap = newhimap;
    883 		fdp->fd_lomap = newlomap;
    884 	}
    885 
    886 	fdp->fd_ofiles = newofile;
    887 	fdp->fd_ofileflags = newofileflags;
    888 	fdp->fd_nfiles = nfiles;
    889 
    890 	simple_unlock(&fdp->fd_slock);
    891 
    892 	fdexpanded++;
    893 }
    894 
    895 /*
    896  * Check to see whether n user file descriptors
    897  * are available to the process p.
    898  */
    899 int
    900 fdavail(struct proc *p, int n)
    901 {
    902 	struct filedesc	*fdp;
    903 	struct file	**fpp;
    904 	int		i, lim;
    905 
    906 	fdp = p->p_fd;
    907 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    908 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
    909 		return (1);
    910 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
    911 	for (i = min(lim,fdp->fd_nfiles) - fdp->fd_freefile; --i >= 0; fpp++)
    912 		if (*fpp == NULL && --n <= 0)
    913 			return (1);
    914 	return (0);
    915 }
    916 
    917 /*
    918  * Create a new open file structure and allocate
    919  * a file descriptor for the process that refers to it.
    920  */
    921 int
    922 falloc(struct proc *p, struct file **resultfp, int *resultfd)
    923 {
    924 	struct file	*fp, *fq;
    925 	int		error, i;
    926 
    927  restart:
    928 	if ((error = fdalloc(p, 0, &i)) != 0) {
    929 		if (error == ENOSPC) {
    930 			fdexpand(p);
    931 			goto restart;
    932 		}
    933 		return (error);
    934 	}
    935 
    936 	fp = pool_get(&file_pool, PR_WAITOK);
    937 	simple_lock(&filelist_slock);
    938 	if (nfiles >= maxfiles) {
    939 		tablefull("file", "increase kern.maxfiles or MAXFILES");
    940 		simple_unlock(&filelist_slock);
    941 		fd_unused(p->p_fd, i);
    942 		pool_put(&file_pool, fp);
    943 		return (ENFILE);
    944 	}
    945 	/*
    946 	 * Allocate a new file descriptor.
    947 	 * If the process has file descriptor zero open, add to the list
    948 	 * of open files at that point, otherwise put it at the front of
    949 	 * the list of open files.
    950 	 */
    951 	nfiles++;
    952 	memset(fp, 0, sizeof(struct file));
    953 	fp->f_iflags = FIF_LARVAL;
    954 	if ((fq = p->p_fd->fd_ofiles[0]) != NULL) {
    955 		LIST_INSERT_AFTER(fq, fp, f_list);
    956 	} else {
    957 		LIST_INSERT_HEAD(&filehead, fp, f_list);
    958 	}
    959 	simple_unlock(&filelist_slock);
    960 	KDASSERT(p->p_fd->fd_ofiles[i] == NULL);
    961 	p->p_fd->fd_ofiles[i] = fp;
    962 	simple_lock_init(&fp->f_slock);
    963 	fp->f_count = 1;
    964 	fp->f_cred = p->p_ucred;
    965 	crhold(fp->f_cred);
    966 	if (resultfp) {
    967 		fp->f_usecount = 1;
    968 		*resultfp = fp;
    969 	}
    970 	if (resultfd)
    971 		*resultfd = i;
    972 	return (0);
    973 }
    974 
    975 /*
    976  * Free a file descriptor.
    977  */
    978 void
    979 ffree(struct file *fp)
    980 {
    981 
    982 #ifdef DIAGNOSTIC
    983 	if (fp->f_usecount)
    984 		panic("ffree");
    985 #endif
    986 
    987 	simple_lock(&filelist_slock);
    988 	LIST_REMOVE(fp, f_list);
    989 	crfree(fp->f_cred);
    990 #ifdef DIAGNOSTIC
    991 	fp->f_count = 0; /* What's the point? */
    992 #endif
    993 	nfiles--;
    994 	simple_unlock(&filelist_slock);
    995 	pool_put(&file_pool, fp);
    996 }
    997 
    998 /*
    999  * Create an initial cwdinfo structure, using the same current and root
   1000  * directories as p.
   1001  */
   1002 struct cwdinfo *
   1003 cwdinit(struct proc *p)
   1004 {
   1005 	struct cwdinfo *cwdi;
   1006 
   1007 	cwdi = pool_get(&cwdi_pool, PR_WAITOK);
   1008 
   1009 	simple_lock_init(&cwdi->cwdi_slock);
   1010 	cwdi->cwdi_cdir = p->p_cwdi->cwdi_cdir;
   1011 	if (cwdi->cwdi_cdir)
   1012 		VREF(cwdi->cwdi_cdir);
   1013 	cwdi->cwdi_rdir = p->p_cwdi->cwdi_rdir;
   1014 	if (cwdi->cwdi_rdir)
   1015 		VREF(cwdi->cwdi_rdir);
   1016 	cwdi->cwdi_cmask =  p->p_cwdi->cwdi_cmask;
   1017 	cwdi->cwdi_refcnt = 1;
   1018 
   1019 	return (cwdi);
   1020 }
   1021 
   1022 /*
   1023  * Make p2 share p1's cwdinfo.
   1024  */
   1025 void
   1026 cwdshare(struct proc *p1, struct proc *p2)
   1027 {
   1028 	struct cwdinfo *cwdi = p1->p_cwdi;
   1029 
   1030 	simple_lock(&cwdi->cwdi_slock);
   1031 	cwdi->cwdi_refcnt++;
   1032 	simple_unlock(&cwdi->cwdi_slock);
   1033 	p2->p_cwdi = cwdi;
   1034 }
   1035 
   1036 /*
   1037  * Make this process not share its cwdinfo structure, maintaining
   1038  * all cwdinfo state.
   1039  */
   1040 void
   1041 cwdunshare(struct proc *p)
   1042 {
   1043 	struct cwdinfo *oldcwdi, *newcwdi;
   1044 
   1045 	if (p->p_cwdi->cwdi_refcnt == 1)
   1046 		return;
   1047 
   1048 	newcwdi = cwdinit(p);
   1049 	oldcwdi = p->p_cwdi;
   1050 	p->p_cwdi = newcwdi;
   1051 	cwdfree(oldcwdi);
   1052 }
   1053 
   1054 /*
   1055  * Release a cwdinfo structure.
   1056  */
   1057 void
   1058 cwdfree(struct cwdinfo *cwdi)
   1059 {
   1060 	int n;
   1061 
   1062 	simple_lock(&cwdi->cwdi_slock);
   1063 	n = --cwdi->cwdi_refcnt;
   1064 	simple_unlock(&cwdi->cwdi_slock);
   1065 	if (n > 0)
   1066 		return;
   1067 
   1068 	vrele(cwdi->cwdi_cdir);
   1069 	if (cwdi->cwdi_rdir)
   1070 		vrele(cwdi->cwdi_rdir);
   1071 	pool_put(&cwdi_pool, cwdi);
   1072 }
   1073 
   1074 /*
   1075  * Create an initial filedesc structure, using the same current and root
   1076  * directories as p.
   1077  */
   1078 struct filedesc *
   1079 fdinit(struct proc *p)
   1080 {
   1081 	struct filedesc0 *newfdp;
   1082 
   1083 	newfdp = pool_get(&filedesc0_pool, PR_WAITOK);
   1084 	memset(newfdp, 0, sizeof(struct filedesc0));
   1085 
   1086 	fdinit1(newfdp);
   1087 
   1088 	return (&newfdp->fd_fd);
   1089 }
   1090 
   1091 /*
   1092  * Initialize a file descriptor table.
   1093  */
   1094 void
   1095 fdinit1(struct filedesc0 *newfdp)
   1096 {
   1097 
   1098 	newfdp->fd_fd.fd_refcnt = 1;
   1099 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
   1100 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
   1101 	newfdp->fd_fd.fd_nfiles = NDFILE;
   1102 	newfdp->fd_fd.fd_knlistsize = -1;
   1103 	newfdp->fd_fd.fd_himap = newfdp->fd_dhimap;
   1104 	newfdp->fd_fd.fd_lomap = newfdp->fd_dlomap;
   1105 	simple_lock_init(&newfdp->fd_fd.fd_slock);
   1106 }
   1107 
   1108 /*
   1109  * Make p2 share p1's filedesc structure.
   1110  */
   1111 void
   1112 fdshare(struct proc *p1, struct proc *p2)
   1113 {
   1114 	struct filedesc *fdp = p1->p_fd;
   1115 
   1116 	simple_lock(&fdp->fd_slock);
   1117 	p2->p_fd = fdp;
   1118 	fdp->fd_refcnt++;
   1119 	simple_unlock(&fdp->fd_slock);
   1120 }
   1121 
   1122 /*
   1123  * Make this process not share its filedesc structure, maintaining
   1124  * all file descriptor state.
   1125  */
   1126 void
   1127 fdunshare(struct lwp *l)
   1128 {
   1129 	struct proc *p = l->l_proc;
   1130 	struct filedesc *newfd;
   1131 
   1132 	if (p->p_fd->fd_refcnt == 1)
   1133 		return;
   1134 
   1135 	newfd = fdcopy(p);
   1136 	fdfree(l);
   1137 	p->p_fd = newfd;
   1138 }
   1139 
   1140 /*
   1141  * Clear a process's fd table.
   1142  */
   1143 void
   1144 fdclear(struct lwp *l)
   1145 {
   1146 	struct proc *p = l->l_proc;
   1147 	struct filedesc *newfd;
   1148 
   1149 	newfd = fdinit(p);
   1150 	fdfree(l);
   1151 	p->p_fd = newfd;
   1152 }
   1153 
   1154 /*
   1155  * Copy a filedesc structure.
   1156  */
   1157 struct filedesc *
   1158 fdcopy(struct proc *p)
   1159 {
   1160 	struct filedesc	*newfdp, *fdp;
   1161 	struct file	**fpp, **nfpp;
   1162 	int		i, nfiles, lastfile;
   1163 
   1164 	fdp = p->p_fd;
   1165 	newfdp = pool_get(&filedesc0_pool, PR_WAITOK);
   1166 	newfdp->fd_refcnt = 1;
   1167 	simple_lock_init(&newfdp->fd_slock);
   1168 
   1169 restart:
   1170 	nfiles = fdp->fd_nfiles;
   1171 	lastfile = fdp->fd_lastfile;
   1172 
   1173 	/*
   1174 	 * If the number of open files fits in the internal arrays
   1175 	 * of the open file structure, use them, otherwise allocate
   1176 	 * additional memory for the number of descriptors currently
   1177 	 * in use.
   1178 	 */
   1179 	if (lastfile < NDFILE) {
   1180 		i = NDFILE;
   1181 	} else {
   1182 		/*
   1183 		 * Compute the smallest multiple of NDEXTENT needed
   1184 		 * for the file descriptors currently in use,
   1185 		 * allowing the table to shrink.
   1186 		 */
   1187 		i = nfiles;
   1188 		while (i >= 2 * NDEXTENT && i > lastfile * 2)
   1189 			i /= 2;
   1190 		newfdp->fd_ofiles = malloc(i * OFILESIZE, M_FILEDESC, M_WAITOK);
   1191 	}
   1192 	if (NDHISLOTS(i) > NDHISLOTS(NDFILE)) {
   1193 		newfdp->fd_himap = malloc(NDHISLOTS(i) * sizeof(uint32_t),
   1194 		    M_FILEDESC, M_WAITOK);
   1195 		newfdp->fd_lomap = malloc(NDLOSLOTS(i) * sizeof(uint32_t),
   1196 		    M_FILEDESC, M_WAITOK);
   1197 	}
   1198 
   1199 	simple_lock(&fdp->fd_slock);
   1200 	if (nfiles != fdp->fd_nfiles || lastfile != fdp->fd_lastfile) {
   1201 		simple_unlock(&fdp->fd_slock);
   1202 		if (i > NDFILE)
   1203 			free(newfdp->fd_ofiles, M_FILEDESC);
   1204 		if (NDHISLOTS(i) > NDHISLOTS(NDFILE)) {
   1205 			free(newfdp->fd_himap, M_FILEDESC);
   1206 			free(newfdp->fd_lomap, M_FILEDESC);
   1207 		}
   1208 		goto restart;
   1209 	}
   1210 
   1211 	if (lastfile < NDFILE) {
   1212 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
   1213 		newfdp->fd_ofileflags =
   1214 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
   1215 	} else {
   1216 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
   1217 	}
   1218 	if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
   1219 		newfdp->fd_himap =
   1220 		    ((struct filedesc0 *) newfdp)->fd_dhimap;
   1221 		newfdp->fd_lomap =
   1222 		    ((struct filedesc0 *) newfdp)->fd_dlomap;
   1223 	}
   1224 
   1225 	newfdp->fd_nfiles = i;
   1226 	newfdp->fd_lastfile = lastfile;
   1227 	newfdp->fd_freefile = fdp->fd_freefile;
   1228 
   1229 	memset(newfdp->fd_ofiles + lastfile, 0,
   1230 		(i - lastfile) * sizeof(struct file **));
   1231 	memcpy(newfdp->fd_ofileflags, fdp->fd_ofileflags, i * sizeof(char));
   1232 	if (i < NDENTRIES * NDENTRIES)
   1233 		i = NDENTRIES * NDENTRIES; /* size of inlined bitmaps */
   1234 	memcpy(newfdp->fd_himap, fdp->fd_himap, NDHISLOTS(i)*sizeof(uint32_t));
   1235 	memcpy(newfdp->fd_lomap, fdp->fd_lomap, NDLOSLOTS(i)*sizeof(uint32_t));
   1236 
   1237 	fpp = fdp->fd_ofiles;
   1238 	nfpp = newfdp->fd_ofiles;
   1239 	for (i = 0; i <= lastfile; i++, fpp++, nfpp++) {
   1240 		if ((*nfpp = *fpp) == NULL)
   1241 			continue;
   1242 
   1243 		if ((*fpp)->f_type == DTYPE_KQUEUE)
   1244 			/* kq descriptors cannot be copied. */
   1245 			fdremove(newfdp, i);
   1246 		else {
   1247 			simple_lock(&(*fpp)->f_slock);
   1248 			(*fpp)->f_count++;
   1249 			simple_unlock(&(*fpp)->f_slock);
   1250 		}
   1251 	}
   1252 
   1253 	simple_unlock(&fdp->fd_slock);
   1254 
   1255 	newfdp->fd_knlist = NULL;
   1256 	newfdp->fd_knlistsize = -1;
   1257 	newfdp->fd_knhash = NULL;
   1258 	newfdp->fd_knhashmask = 0;
   1259 
   1260 	return (newfdp);
   1261 }
   1262 
   1263 /*
   1264  * Release a filedesc structure.
   1265  */
   1266 void
   1267 fdfree(struct lwp *l)
   1268 {
   1269 	struct proc	*p = l->l_proc;
   1270 	struct filedesc	*fdp;
   1271 	struct file	**fpp, *fp;
   1272 	int		i;
   1273 
   1274 	fdp = p->p_fd;
   1275 	simple_lock(&fdp->fd_slock);
   1276 	i = --fdp->fd_refcnt;
   1277 	simple_unlock(&fdp->fd_slock);
   1278 	if (i > 0)
   1279 		return;
   1280 
   1281 	fpp = fdp->fd_ofiles;
   1282 	for (i = fdp->fd_lastfile; i >= 0; i--, fpp++) {
   1283 		fp = *fpp;
   1284 		if (fp != NULL) {
   1285 			*fpp = NULL;
   1286 			simple_lock(&fp->f_slock);
   1287 			FILE_USE(fp);
   1288 			if (i < fdp->fd_knlistsize)
   1289 				knote_fdclose(l, fdp->fd_lastfile - i);
   1290 			(void) closef(fp, l);
   1291 		}
   1292 	}
   1293 	p->p_fd = NULL;
   1294 	if (fdp->fd_nfiles > NDFILE)
   1295 		free(fdp->fd_ofiles, M_FILEDESC);
   1296 	if (NDHISLOTS(fdp->fd_nfiles) > NDHISLOTS(NDFILE)) {
   1297 		free(fdp->fd_himap, M_FILEDESC);
   1298 		free(fdp->fd_lomap, M_FILEDESC);
   1299 	}
   1300 	if (fdp->fd_knlist)
   1301 		free(fdp->fd_knlist, M_KEVENT);
   1302 	if (fdp->fd_knhash)
   1303 		hashdone(fdp->fd_knhash, M_KEVENT);
   1304 	pool_put(&filedesc0_pool, fdp);
   1305 }
   1306 
   1307 /*
   1308  * Internal form of close.
   1309  * Decrement reference count on file structure.
   1310  * Note: p may be NULL when closing a file
   1311  * that was being passed in a message.
   1312  *
   1313  * Note: we expect the caller is holding a usecount, and expects us
   1314  * to drop it (the caller thinks the file is going away forever).
   1315  */
   1316 int
   1317 closef(struct file *fp, struct lwp *l)
   1318 {
   1319 	struct proc	*p = l ? l->l_proc : NULL;
   1320 	struct vnode	*vp;
   1321 	struct flock	lf;
   1322 	int		error;
   1323 
   1324 	if (fp == NULL)
   1325 		return (0);
   1326 
   1327 	/*
   1328 	 * POSIX record locking dictates that any close releases ALL
   1329 	 * locks owned by this process.  This is handled by setting
   1330 	 * a flag in the unlock to free ONLY locks obeying POSIX
   1331 	 * semantics, and not to free BSD-style file locks.
   1332 	 * If the descriptor was in a message, POSIX-style locks
   1333 	 * aren't passed with the descriptor.
   1334 	 */
   1335 	if (p && (p->p_flag & P_ADVLOCK) && fp->f_type == DTYPE_VNODE) {
   1336 		lf.l_whence = SEEK_SET;
   1337 		lf.l_start = 0;
   1338 		lf.l_len = 0;
   1339 		lf.l_type = F_UNLCK;
   1340 		vp = (struct vnode *)fp->f_data;
   1341 		(void) VOP_ADVLOCK(vp, p, F_UNLCK, &lf, F_POSIX);
   1342 	}
   1343 
   1344 	/*
   1345 	 * If WANTCLOSE is set, then the reference count on the file
   1346 	 * is 0, but there were multiple users of the file.  This can
   1347 	 * happen if a filedesc structure is shared by multiple
   1348 	 * processes.
   1349 	 */
   1350 	simple_lock(&fp->f_slock);
   1351 	if (fp->f_iflags & FIF_WANTCLOSE) {
   1352 		/*
   1353 		 * Another user of the file is already closing, and is
   1354 		 * simply waiting for other users of the file to drain.
   1355 		 * Release our usecount, and wake up the closer if it
   1356 		 * is the only remaining use.
   1357 		 */
   1358 #ifdef DIAGNOSTIC
   1359 		if (fp->f_count != 0)
   1360 			panic("closef: wantclose and count != 0");
   1361 		if (fp->f_usecount < 2)
   1362 			panic("closef: wantclose and usecount < 2");
   1363 #endif
   1364 		if (--fp->f_usecount == 1)
   1365 			wakeup(&fp->f_usecount);
   1366 		simple_unlock(&fp->f_slock);
   1367 		return (0);
   1368 	} else {
   1369 		/*
   1370 		 * Decrement the reference count.  If we were not the
   1371 		 * last reference, then release our use and just
   1372 		 * return.
   1373 		 */
   1374 		if (--fp->f_count > 0) {
   1375 #ifdef DIAGNOSTIC
   1376 			if (fp->f_usecount < 1)
   1377 				panic("closef: no wantclose and usecount < 1");
   1378 #endif
   1379 			fp->f_usecount--;
   1380 			simple_unlock(&fp->f_slock);
   1381 			return (0);
   1382 		}
   1383 	}
   1384 
   1385 	/*
   1386 	 * The reference count is now 0.  However, there may be
   1387 	 * multiple potential users of this file.  This can happen
   1388 	 * if multiple processes shared a single filedesc structure.
   1389 	 *
   1390 	 * Notify these potential users that the file is closing.
   1391 	 * This will prevent them from adding additional uses to
   1392 	 * the file.
   1393 	 */
   1394 	fp->f_iflags |= FIF_WANTCLOSE;
   1395 
   1396 	/*
   1397 	 * We expect the caller to add a use to the file.  So, if we
   1398 	 * are the last user, usecount will be 1.  If it is not, we
   1399 	 * must wait for the usecount to drain.  When it drains back
   1400 	 * to 1, we will be awakened so that we may proceed with the
   1401 	 * close.
   1402 	 */
   1403 #ifdef DIAGNOSTIC
   1404 	if (fp->f_usecount < 1)
   1405 		panic("closef: usecount < 1");
   1406 #endif
   1407 	while (fp->f_usecount > 1)
   1408 		(void) ltsleep(&fp->f_usecount, PRIBIO, "closef", 0,
   1409 				&fp->f_slock);
   1410 #ifdef DIAGNOSTIC
   1411 	if (fp->f_usecount != 1)
   1412 		panic("closef: usecount != 1");
   1413 #endif
   1414 
   1415 	simple_unlock(&fp->f_slock);
   1416 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
   1417 		lf.l_whence = SEEK_SET;
   1418 		lf.l_start = 0;
   1419 		lf.l_len = 0;
   1420 		lf.l_type = F_UNLCK;
   1421 		vp = (struct vnode *)fp->f_data;
   1422 		(void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
   1423 	}
   1424 	if (fp->f_ops)
   1425 		error = (*fp->f_ops->fo_close)(fp, l);
   1426 	else
   1427 		error = 0;
   1428 
   1429 	/* Nothing references the file now, drop the final use (us). */
   1430 	fp->f_usecount--;
   1431 
   1432 	ffree(fp);
   1433 	return (error);
   1434 }
   1435 
   1436 /*
   1437  * Apply an advisory lock on a file descriptor.
   1438  *
   1439  * Just attempt to get a record lock of the requested type on
   1440  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
   1441  */
   1442 /* ARGSUSED */
   1443 int
   1444 sys_flock(struct lwp *l, void *v, register_t *retval)
   1445 {
   1446 	struct sys_flock_args /* {
   1447 		syscallarg(int)	fd;
   1448 		syscallarg(int)	how;
   1449 	} */ *uap = v;
   1450 	int		fd, how, error;
   1451 	struct proc	*p;
   1452 	struct filedesc	*fdp;
   1453 	struct file	*fp;
   1454 	struct vnode	*vp;
   1455 	struct flock	lf;
   1456 
   1457 	p = l->l_proc;
   1458 	fd = SCARG(uap, fd);
   1459 	how = SCARG(uap, how);
   1460 	fdp = p->p_fd;
   1461 	error = 0;
   1462 
   1463 	if ((fp = fd_getfile(fdp, fd)) == NULL)
   1464 		return (EBADF);
   1465 
   1466 	FILE_USE(fp);
   1467 
   1468 	if (fp->f_type != DTYPE_VNODE) {
   1469 		error = EOPNOTSUPP;
   1470 		goto out;
   1471 	}
   1472 
   1473 	vp = (struct vnode *)fp->f_data;
   1474 	lf.l_whence = SEEK_SET;
   1475 	lf.l_start = 0;
   1476 	lf.l_len = 0;
   1477 	if (how & LOCK_UN) {
   1478 		lf.l_type = F_UNLCK;
   1479 		fp->f_flag &= ~FHASLOCK;
   1480 		error = VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
   1481 		goto out;
   1482 	}
   1483 	if (how & LOCK_EX)
   1484 		lf.l_type = F_WRLCK;
   1485 	else if (how & LOCK_SH)
   1486 		lf.l_type = F_RDLCK;
   1487 	else {
   1488 		error = EINVAL;
   1489 		goto out;
   1490 	}
   1491 	fp->f_flag |= FHASLOCK;
   1492 	if (how & LOCK_NB)
   1493 		error = VOP_ADVLOCK(vp, fp, F_SETLK, &lf, F_FLOCK);
   1494 	else
   1495 		error = VOP_ADVLOCK(vp, fp, F_SETLK, &lf,
   1496 		    F_FLOCK|F_WAIT);
   1497  out:
   1498 	FILE_UNUSE(fp, l);
   1499 	return (error);
   1500 }
   1501 
   1502 /*
   1503  * File Descriptor pseudo-device driver (/dev/fd/).
   1504  *
   1505  * Opening minor device N dup()s the file (if any) connected to file
   1506  * descriptor N belonging to the calling process.  Note that this driver
   1507  * consists of only the ``open()'' routine, because all subsequent
   1508  * references to this file will be direct to the other driver.
   1509  */
   1510 /* ARGSUSED */
   1511 int
   1512 filedescopen(dev_t dev, int mode, int type, struct lwp *l)
   1513 {
   1514 
   1515 	/*
   1516 	 * XXX Kludge: set dupfd to contain the value of the
   1517 	 * the file descriptor being sought for duplication. The error
   1518 	 * return ensures that the vnode for this device will be released
   1519 	 * by vn_open. Open will detect this special error and take the
   1520 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
   1521 	 * will simply report the error.
   1522 	 */
   1523 	l->l_dupfd = minor(dev);
   1524 	return (ENODEV);
   1525 }
   1526 
   1527 /*
   1528  * Duplicate the specified descriptor to a free descriptor.
   1529  *
   1530  * 'indx' has been fdalloc'ed (and will be fdremove'ed on error) by the caller.
   1531  */
   1532 int
   1533 dupfdopen(struct lwp *l, int indx, int dfd, int mode, int error)
   1534 {
   1535 	struct proc	*p = l->l_proc;
   1536 	struct filedesc *fdp;
   1537 	struct file	*wfp;
   1538 
   1539 	fdp = p->p_fd;
   1540 
   1541 	/* should be cleared by the caller */
   1542 	KASSERT(fdp->fd_ofiles[indx] == NULL);
   1543 
   1544 	/*
   1545 	 * If the to-be-dup'd fd number is greater than the allowed number
   1546 	 * of file descriptors, or the fd to be dup'd has already been
   1547 	 * closed, reject.
   1548 	 */
   1549 
   1550 	/*
   1551 	 * Note, in the case of indx == dfd, fd_getfile below returns NULL.
   1552 	 */
   1553 	if ((wfp = fd_getfile(fdp, dfd)) == NULL)
   1554 		return (EBADF);
   1555 
   1556 	FILE_USE(wfp);
   1557 
   1558 	/*
   1559 	 * There are two cases of interest here.
   1560 	 *
   1561 	 * For ENODEV simply dup (dfd) to file descriptor
   1562 	 * (indx) and return.
   1563 	 *
   1564 	 * For ENXIO steal away the file structure from (dfd) and
   1565 	 * store it in (indx).  (dfd) is effectively closed by
   1566 	 * this operation.
   1567 	 *
   1568 	 * Any other error code is just returned.
   1569 	 */
   1570 	switch (error) {
   1571 	case ENODEV:
   1572 		/*
   1573 		 * Check that the mode the file is being opened for is a
   1574 		 * subset of the mode of the existing descriptor.
   1575 		 */
   1576 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
   1577 			FILE_UNUSE(wfp, l);
   1578 			return (EACCES);
   1579 		}
   1580 		simple_lock(&fdp->fd_slock);
   1581 		fdp->fd_ofiles[indx] = wfp;
   1582 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1583 		simple_unlock(&fdp->fd_slock);
   1584 		simple_lock(&wfp->f_slock);
   1585 		wfp->f_count++;
   1586 		/* 'indx' has been fd_used'ed by caller */
   1587 		FILE_UNUSE_HAVELOCK(wfp, l);
   1588 		return (0);
   1589 
   1590 	case ENXIO:
   1591 		/*
   1592 		 * Steal away the file pointer from dfd, and stuff it into indx.
   1593 		 */
   1594 		simple_lock(&fdp->fd_slock);
   1595 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
   1596 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1597 		fdp->fd_ofiles[dfd] = NULL;
   1598 		fdp->fd_ofileflags[dfd] = 0;
   1599 		/*
   1600 		 * Complete the clean up of the filedesc structure by
   1601 		 * recomputing the various hints.
   1602 		 */
   1603 		/* 'indx' has been fd_used'ed by caller */
   1604 		fd_unused(fdp, dfd);
   1605 		simple_unlock(&fdp->fd_slock);
   1606 		FILE_UNUSE(wfp, l);
   1607 		return (0);
   1608 
   1609 	default:
   1610 		FILE_UNUSE(wfp, l);
   1611 		return (error);
   1612 	}
   1613 	/* NOTREACHED */
   1614 }
   1615 
   1616 /*
   1617  * fcntl call which is being passed to the file's fs.
   1618  */
   1619 int
   1620 fcntl_forfs(int fd, struct lwp *l, int cmd, void *arg)
   1621 {
   1622 	struct proc	*p = l->l_proc;
   1623 	struct file	*fp;
   1624 	struct filedesc	*fdp;
   1625 	int		error;
   1626 	u_int		size;
   1627 	void		*data, *memp;
   1628 #define STK_PARAMS	128
   1629 	char		stkbuf[STK_PARAMS];
   1630 
   1631 	/* fd's value was validated in sys_fcntl before calling this routine */
   1632 	fdp = p->p_fd;
   1633 	fp = fdp->fd_ofiles[fd];
   1634 
   1635 	if ((fp->f_flag & (FREAD | FWRITE)) == 0)
   1636 		return (EBADF);
   1637 
   1638 	/*
   1639 	 * Interpret high order word to find amount of data to be
   1640 	 * copied to/from the user's address space.
   1641 	 */
   1642 	size = (size_t)F_PARAM_LEN(cmd);
   1643 	if (size > F_PARAM_MAX)
   1644 		return (EINVAL);
   1645 	memp = NULL;
   1646 	if (size > sizeof(stkbuf)) {
   1647 		memp = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
   1648 		data = memp;
   1649 	} else
   1650 		data = stkbuf;
   1651 	if (cmd & F_FSIN) {
   1652 		if (size) {
   1653 			error = copyin(arg, data, size);
   1654 			if (error) {
   1655 				if (memp)
   1656 					free(memp, M_IOCTLOPS);
   1657 				return (error);
   1658 			}
   1659 		} else
   1660 			*(void **)data = arg;
   1661 	} else if ((cmd & F_FSOUT) && size)
   1662 		/*
   1663 		 * Zero the buffer so the user always
   1664 		 * gets back something deterministic.
   1665 		 */
   1666 		memset(data, 0, size);
   1667 	else if (cmd & F_FSVOID)
   1668 		*(void **)data = arg;
   1669 
   1670 
   1671 	error = (*fp->f_ops->fo_fcntl)(fp, cmd, data, l);
   1672 
   1673 	/*
   1674 	 * Copy any data to user, size was
   1675 	 * already set and checked above.
   1676 	 */
   1677 	if (error == 0 && (cmd & F_FSOUT) && size)
   1678 		error = copyout(data, arg, size);
   1679 	if (memp)
   1680 		free(memp, M_IOCTLOPS);
   1681 	return (error);
   1682 }
   1683 
   1684 /*
   1685  * Close any files on exec?
   1686  */
   1687 void
   1688 fdcloseexec(struct lwp *l)
   1689 {
   1690 	struct proc	*p = l->l_proc;
   1691 	struct filedesc *fdp;
   1692 	int		fd;
   1693 
   1694 	fdunshare(l);
   1695 	cwdunshare(p);
   1696 
   1697 	fdp = p->p_fd;
   1698 	for (fd = 0; fd <= fdp->fd_lastfile; fd++)
   1699 		if (fdp->fd_ofileflags[fd] & UF_EXCLOSE)
   1700 			(void) fdrelease(l, fd);
   1701 }
   1702 
   1703 /*
   1704  * It is unsafe for set[ug]id processes to be started with file
   1705  * descriptors 0..2 closed, as these descriptors are given implicit
   1706  * significance in the Standard C library.  fdcheckstd() will create a
   1707  * descriptor referencing /dev/null for each of stdin, stdout, and
   1708  * stderr that is not already open.
   1709  */
   1710 #define CHECK_UPTO 3
   1711 int
   1712 fdcheckstd(l)
   1713 	struct lwp *l;
   1714 {
   1715 	struct proc *p;
   1716 	struct nameidata nd;
   1717 	struct filedesc *fdp;
   1718 	struct file *fp;
   1719 	struct file *devnullfp = NULL;	/* Quell compiler warning */
   1720 	struct proc *pp;
   1721 	register_t retval;
   1722 	int fd, i, error, flags = FREAD|FWRITE, devnull = -1;
   1723 	char closed[CHECK_UPTO * 3 + 1], which[3 + 1];
   1724 
   1725 	p = l->l_proc;
   1726 	closed[0] = '\0';
   1727 	if ((fdp = p->p_fd) == NULL)
   1728 		return (0);
   1729 	for (i = 0; i < CHECK_UPTO; i++) {
   1730 		if (fdp->fd_ofiles[i] != NULL)
   1731 			continue;
   1732 		snprintf(which, sizeof(which), ",%d", i);
   1733 		strlcat(closed, which, sizeof(closed));
   1734 		if (devnull < 0) {
   1735 			if ((error = falloc(p, &fp, &fd)) != 0)
   1736 				return (error);
   1737 			NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null",
   1738 			    l);
   1739 			if ((error = vn_open(&nd, flags, 0)) != 0) {
   1740 				FILE_UNUSE(fp, l);
   1741 				ffree(fp);
   1742 				fdremove(p->p_fd, fd);
   1743 				return (error);
   1744 			}
   1745 			fp->f_data = nd.ni_vp;
   1746 			fp->f_flag = flags;
   1747 			fp->f_ops = &vnops;
   1748 			fp->f_type = DTYPE_VNODE;
   1749 			VOP_UNLOCK(nd.ni_vp, 0);
   1750 			devnull = fd;
   1751 			devnullfp = fp;
   1752 			FILE_SET_MATURE(fp);
   1753 		} else {
   1754 restart:
   1755 			if ((error = fdalloc(p, 0, &fd)) != 0) {
   1756 				if (error == ENOSPC) {
   1757 					fdexpand(p);
   1758 					goto restart;
   1759 				}
   1760 				return (error);
   1761 			}
   1762 
   1763 			simple_lock(&devnullfp->f_slock);
   1764 			FILE_USE(devnullfp);
   1765 			/* finishdup() will unuse the descriptors for us */
   1766 			if ((error = finishdup(l, devnull, fd, &retval)) != 0)
   1767 				return (error);
   1768 		}
   1769 	}
   1770 	if (devnullfp)
   1771 		FILE_UNUSE(devnullfp, l);
   1772 	if (closed[0] != '\0') {
   1773 		pp = p->p_pptr;
   1774 		log(LOG_WARNING, "set{u,g}id pid %d (%s) "
   1775 		    "was invoked by uid %d ppid %d (%s) "
   1776 		    "with fd %s closed\n",
   1777 		    p->p_pid, p->p_comm, pp->p_ucred->cr_uid,
   1778 		    pp->p_pid, pp->p_comm, &closed[1]);
   1779 	}
   1780 	return (0);
   1781 }
   1782 #undef CHECK_UPTO
   1783 
   1784 /*
   1785  * Sets descriptor owner. If the owner is a process, 'pgid'
   1786  * is set to positive value, process ID. If the owner is process group,
   1787  * 'pgid' is set to -pg_id.
   1788  */
   1789 int
   1790 fsetown(struct proc *p, pid_t *pgid, int cmd, const void *data)
   1791 {
   1792 	int id = *(int *)data;
   1793 	int error;
   1794 
   1795 	switch (cmd) {
   1796 	case TIOCSPGRP:
   1797 		if (id < 0)
   1798 			return (EINVAL);
   1799 		id = -id;
   1800 		break;
   1801 	default:
   1802 		break;
   1803 	}
   1804 
   1805 	if (id > 0 && !pfind(id))
   1806 		return (ESRCH);
   1807 	else if (id < 0 && (error = pgid_in_session(p, -id)))
   1808 		return (error);
   1809 
   1810 	*pgid = id;
   1811 	return (0);
   1812 }
   1813 
   1814 /*
   1815  * Return descriptor owner information. If the value is positive,
   1816  * it's process ID. If it's negative, it's process group ID and
   1817  * needs the sign removed before use.
   1818  */
   1819 int
   1820 fgetown(struct proc *p, pid_t pgid, int cmd, void *data)
   1821 {
   1822 	switch (cmd) {
   1823 	case TIOCGPGRP:
   1824 		*(int *)data = -pgid;
   1825 		break;
   1826 	default:
   1827 		*(int *)data = pgid;
   1828 		break;
   1829 	}
   1830 	return (0);
   1831 }
   1832 
   1833 /*
   1834  * Send signal to descriptor owner, either process or process group.
   1835  */
   1836 void
   1837 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
   1838 {
   1839 	struct proc *p1;
   1840 	ksiginfo_t ksi;
   1841 
   1842 	memset(&ksi, 0, sizeof(ksi));
   1843 	ksi.ksi_signo = signo;
   1844 	ksi.ksi_code = code;
   1845 	ksi.ksi_band = band;
   1846 
   1847 	if (pgid > 0 && (p1 = pfind(pgid)))
   1848 		kpsignal(p1, &ksi, fdescdata);
   1849 	else if (pgid < 0)
   1850 		kgsignal(-pgid, &ksi, fdescdata);
   1851 }
   1852