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