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