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