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