Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.209.2.1
      1 /*	$NetBSD: kern_descrip.c,v 1.209.2.1 2011/06/06 09:09:27 jruoho Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008, 2009 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  * (c) UNIX System Laboratories, Inc.
     36  * All or some portions of this file are derived from material licensed
     37  * to the University of California by American Telephone and Telegraph
     38  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     39  * the permission of UNIX System Laboratories, Inc.
     40  *
     41  * Redistribution and use in source and binary forms, with or without
     42  * modification, are permitted provided that the following conditions
     43  * are met:
     44  * 1. Redistributions of source code must retain the above copyright
     45  *    notice, this list of conditions and the following disclaimer.
     46  * 2. Redistributions in binary form must reproduce the above copyright
     47  *    notice, this list of conditions and the following disclaimer in the
     48  *    documentation and/or other materials provided with the distribution.
     49  * 3. Neither the name of the University nor the names of its contributors
     50  *    may be used to endorse or promote products derived from this software
     51  *    without specific prior written permission.
     52  *
     53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     63  * SUCH DAMAGE.
     64  *
     65  *	@(#)kern_descrip.c	8.8 (Berkeley) 2/14/95
     66  */
     67 
     68 /*
     69  * File descriptor management.
     70  */
     71 
     72 #include <sys/cdefs.h>
     73 __KERNEL_RCSID(0, "$NetBSD: kern_descrip.c,v 1.209.2.1 2011/06/06 09:09:27 jruoho Exp $");
     74 
     75 #include <sys/param.h>
     76 #include <sys/systm.h>
     77 #include <sys/filedesc.h>
     78 #include <sys/kernel.h>
     79 #include <sys/proc.h>
     80 #include <sys/file.h>
     81 #include <sys/socket.h>
     82 #include <sys/socketvar.h>
     83 #include <sys/stat.h>
     84 #include <sys/ioctl.h>
     85 #include <sys/fcntl.h>
     86 #include <sys/pool.h>
     87 #include <sys/unistd.h>
     88 #include <sys/resourcevar.h>
     89 #include <sys/conf.h>
     90 #include <sys/event.h>
     91 #include <sys/kauth.h>
     92 #include <sys/atomic.h>
     93 #include <sys/syscallargs.h>
     94 #include <sys/cpu.h>
     95 #include <sys/kmem.h>
     96 #include <sys/vnode.h>
     97 #include <sys/sysctl.h>
     98 #include <sys/ktrace.h>
     99 
    100 /*
    101  * A list (head) of open files, counter, and lock protecting them.
    102  */
    103 struct filelist		filehead	__cacheline_aligned;
    104 static u_int		nfiles		__cacheline_aligned;
    105 kmutex_t		filelist_lock	__cacheline_aligned;
    106 
    107 static pool_cache_t	filedesc_cache	__read_mostly;
    108 static pool_cache_t	file_cache	__read_mostly;
    109 static pool_cache_t	fdfile_cache	__read_mostly;
    110 
    111 static int	file_ctor(void *, void *, int);
    112 static void	file_dtor(void *, void *);
    113 static int	fdfile_ctor(void *, void *, int);
    114 static void	fdfile_dtor(void *, void *);
    115 static int	filedesc_ctor(void *, void *, int);
    116 static void	filedesc_dtor(void *, void *);
    117 static int	filedescopen(dev_t, int, int, lwp_t *);
    118 
    119 static int sysctl_kern_file(SYSCTLFN_PROTO);
    120 static int sysctl_kern_file2(SYSCTLFN_PROTO);
    121 static void fill_file(struct kinfo_file *, const file_t *, const fdfile_t *,
    122 		      int, pid_t);
    123 
    124 const struct cdevsw filedesc_cdevsw = {
    125 	filedescopen, noclose, noread, nowrite, noioctl,
    126 	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER | D_MPSAFE,
    127 };
    128 
    129 /* For ease of reading. */
    130 __strong_alias(fd_putvnode,fd_putfile)
    131 __strong_alias(fd_putsock,fd_putfile)
    132 
    133 /*
    134  * Initialize the descriptor system.
    135  */
    136 void
    137 fd_sys_init(void)
    138 {
    139 	static struct sysctllog *clog;
    140 
    141 	mutex_init(&filelist_lock, MUTEX_DEFAULT, IPL_NONE);
    142 
    143 	file_cache = pool_cache_init(sizeof(file_t), coherency_unit, 0,
    144 	    0, "file", NULL, IPL_NONE, file_ctor, file_dtor, NULL);
    145 	KASSERT(file_cache != NULL);
    146 
    147 	fdfile_cache = pool_cache_init(sizeof(fdfile_t), coherency_unit, 0,
    148 	    PR_LARGECACHE, "fdfile", NULL, IPL_NONE, fdfile_ctor, fdfile_dtor,
    149 	    NULL);
    150 	KASSERT(fdfile_cache != NULL);
    151 
    152 	filedesc_cache = pool_cache_init(sizeof(filedesc_t), coherency_unit,
    153 	    0, 0, "filedesc", NULL, IPL_NONE, filedesc_ctor, filedesc_dtor,
    154 	    NULL);
    155 	KASSERT(filedesc_cache != NULL);
    156 
    157 	sysctl_createv(&clog, 0, NULL, NULL,
    158 		       CTLFLAG_PERMANENT, CTLTYPE_NODE, "kern", NULL,
    159 		       NULL, 0, NULL, 0, CTL_KERN, CTL_EOL);
    160 	sysctl_createv(&clog, 0, NULL, NULL,
    161 		       CTLFLAG_PERMANENT,
    162 		       CTLTYPE_STRUCT, "file",
    163 		       SYSCTL_DESCR("System open file table"),
    164 		       sysctl_kern_file, 0, NULL, 0,
    165 		       CTL_KERN, KERN_FILE, CTL_EOL);
    166 	sysctl_createv(&clog, 0, NULL, NULL,
    167 		       CTLFLAG_PERMANENT,
    168 		       CTLTYPE_STRUCT, "file2",
    169 		       SYSCTL_DESCR("System open file table"),
    170 		       sysctl_kern_file2, 0, NULL, 0,
    171 		       CTL_KERN, KERN_FILE2, CTL_EOL);
    172 }
    173 
    174 static bool
    175 fd_isused(filedesc_t *fdp, unsigned fd)
    176 {
    177 	u_int off = fd >> NDENTRYSHIFT;
    178 
    179 	KASSERT(fd < fdp->fd_dt->dt_nfiles);
    180 
    181 	return (fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0;
    182 }
    183 
    184 /*
    185  * Verify that the bitmaps match the descriptor table.
    186  */
    187 static inline void
    188 fd_checkmaps(filedesc_t *fdp)
    189 {
    190 #ifdef DEBUG
    191 	fdtab_t *dt;
    192 	u_int fd;
    193 
    194 	dt = fdp->fd_dt;
    195 	if (fdp->fd_refcnt == -1) {
    196 		/*
    197 		 * fd_free tears down the table without maintaining its bitmap.
    198 		 */
    199 		return;
    200 	}
    201 	for (fd = 0; fd < dt->dt_nfiles; fd++) {
    202 		if (fd < NDFDFILE) {
    203 			KASSERT(dt->dt_ff[fd] ==
    204 			    (fdfile_t *)fdp->fd_dfdfile[fd]);
    205 		}
    206 		if (dt->dt_ff[fd] == NULL) {
    207 			KASSERT(!fd_isused(fdp, fd));
    208 		} else if (dt->dt_ff[fd]->ff_file != NULL) {
    209 			KASSERT(fd_isused(fdp, fd));
    210 		}
    211 	}
    212 #endif
    213 }
    214 
    215 static int
    216 fd_next_zero(filedesc_t *fdp, uint32_t *bitmap, int want, u_int bits)
    217 {
    218 	int i, off, maxoff;
    219 	uint32_t sub;
    220 
    221 	KASSERT(mutex_owned(&fdp->fd_lock));
    222 
    223 	fd_checkmaps(fdp);
    224 
    225 	if (want > bits)
    226 		return -1;
    227 
    228 	off = want >> NDENTRYSHIFT;
    229 	i = want & NDENTRYMASK;
    230 	if (i) {
    231 		sub = bitmap[off] | ((u_int)~0 >> (NDENTRIES - i));
    232 		if (sub != ~0)
    233 			goto found;
    234 		off++;
    235 	}
    236 
    237 	maxoff = NDLOSLOTS(bits);
    238 	while (off < maxoff) {
    239 		if ((sub = bitmap[off]) != ~0)
    240 			goto found;
    241 		off++;
    242 	}
    243 
    244 	return -1;
    245 
    246  found:
    247 	return (off << NDENTRYSHIFT) + ffs(~sub) - 1;
    248 }
    249 
    250 static int
    251 fd_last_set(filedesc_t *fd, int last)
    252 {
    253 	int off, i;
    254 	fdfile_t **ff = fd->fd_dt->dt_ff;
    255 	uint32_t *bitmap = fd->fd_lomap;
    256 
    257 	KASSERT(mutex_owned(&fd->fd_lock));
    258 
    259 	fd_checkmaps(fd);
    260 
    261 	off = (last - 1) >> NDENTRYSHIFT;
    262 
    263 	while (off >= 0 && !bitmap[off])
    264 		off--;
    265 
    266 	if (off < 0)
    267 		return -1;
    268 
    269 	i = ((off + 1) << NDENTRYSHIFT) - 1;
    270 	if (i >= last)
    271 		i = last - 1;
    272 
    273 	/* XXX should use bitmap */
    274 	while (i > 0 && (ff[i] == NULL || !ff[i]->ff_allocated))
    275 		i--;
    276 
    277 	return i;
    278 }
    279 
    280 static inline void
    281 fd_used(filedesc_t *fdp, unsigned fd)
    282 {
    283 	u_int off = fd >> NDENTRYSHIFT;
    284 	fdfile_t *ff;
    285 
    286 	ff = fdp->fd_dt->dt_ff[fd];
    287 
    288 	KASSERT(mutex_owned(&fdp->fd_lock));
    289 	KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) == 0);
    290 	KASSERT(ff != NULL);
    291 	KASSERT(ff->ff_file == NULL);
    292 	KASSERT(!ff->ff_allocated);
    293 
    294 	ff->ff_allocated = 1;
    295 	fdp->fd_lomap[off] |= 1 << (fd & NDENTRYMASK);
    296 	if (__predict_false(fdp->fd_lomap[off] == ~0)) {
    297 		KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
    298 		    (1 << (off & NDENTRYMASK))) == 0);
    299 		fdp->fd_himap[off >> NDENTRYSHIFT] |= 1 << (off & NDENTRYMASK);
    300 	}
    301 
    302 	if ((int)fd > fdp->fd_lastfile) {
    303 		fdp->fd_lastfile = fd;
    304 	}
    305 
    306 	fd_checkmaps(fdp);
    307 }
    308 
    309 static inline void
    310 fd_unused(filedesc_t *fdp, unsigned fd)
    311 {
    312 	u_int off = fd >> NDENTRYSHIFT;
    313 	fdfile_t *ff;
    314 
    315 	ff = fdp->fd_dt->dt_ff[fd];
    316 
    317 	/*
    318 	 * Don't assert the lock is held here, as we may be copying
    319 	 * the table during exec() and it is not needed there.
    320 	 * procfs and sysctl are locked out by proc::p_reflock.
    321 	 *
    322 	 * KASSERT(mutex_owned(&fdp->fd_lock));
    323 	 */
    324 	KASSERT(ff != NULL);
    325 	KASSERT(ff->ff_file == NULL);
    326 	KASSERT(ff->ff_allocated);
    327 
    328 	if (fd < fdp->fd_freefile) {
    329 		fdp->fd_freefile = fd;
    330 	}
    331 
    332 	if (fdp->fd_lomap[off] == ~0) {
    333 		KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
    334 		    (1 << (off & NDENTRYMASK))) != 0);
    335 		fdp->fd_himap[off >> NDENTRYSHIFT] &=
    336 		    ~(1 << (off & NDENTRYMASK));
    337 	}
    338 	KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0);
    339 	fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
    340 	ff->ff_allocated = 0;
    341 
    342 	KASSERT(fd <= fdp->fd_lastfile);
    343 	if (fd == fdp->fd_lastfile) {
    344 		fdp->fd_lastfile = fd_last_set(fdp, fd);
    345 	}
    346 	fd_checkmaps(fdp);
    347 }
    348 
    349 /*
    350  * Look up the file structure corresponding to a file descriptor
    351  * and return the file, holding a reference on the descriptor.
    352  */
    353 file_t *
    354 fd_getfile(unsigned fd)
    355 {
    356 	filedesc_t *fdp;
    357 	fdfile_t *ff;
    358 	file_t *fp;
    359 	fdtab_t *dt;
    360 
    361 	/*
    362 	 * Look up the fdfile structure representing this descriptor.
    363 	 * We are doing this unlocked.  See fd_tryexpand().
    364 	 */
    365 	fdp = curlwp->l_fd;
    366 	dt = fdp->fd_dt;
    367 	if (__predict_false(fd >= dt->dt_nfiles)) {
    368 		return NULL;
    369 	}
    370 	ff = dt->dt_ff[fd];
    371 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
    372 	if (__predict_false(ff == NULL)) {
    373 		return NULL;
    374 	}
    375 
    376 	/* Now get a reference to the descriptor. */
    377 	if (fdp->fd_refcnt == 1) {
    378 		/*
    379 		 * Single threaded: don't need to worry about concurrent
    380 		 * access (other than earlier calls to kqueue, which may
    381 		 * hold a reference to the descriptor).
    382 		 */
    383 		ff->ff_refcnt++;
    384 	} else {
    385 		/*
    386 		 * Multi threaded: issue a memory barrier to ensure that we
    387 		 * acquire the file pointer _after_ adding a reference.  If
    388 		 * no memory barrier, we could fetch a stale pointer.
    389 		 */
    390 		atomic_inc_uint(&ff->ff_refcnt);
    391 #ifndef __HAVE_ATOMIC_AS_MEMBAR
    392 		membar_enter();
    393 #endif
    394 	}
    395 
    396 	/*
    397 	 * If the file is not open or is being closed then put the
    398 	 * reference back.
    399 	 */
    400 	fp = ff->ff_file;
    401 	if (__predict_true(fp != NULL)) {
    402 		return fp;
    403 	}
    404 	fd_putfile(fd);
    405 	return NULL;
    406 }
    407 
    408 /*
    409  * Release a reference to a file descriptor acquired with fd_getfile().
    410  */
    411 void
    412 fd_putfile(unsigned fd)
    413 {
    414 	filedesc_t *fdp;
    415 	fdfile_t *ff;
    416 	u_int u, v;
    417 
    418 	fdp = curlwp->l_fd;
    419 	ff = fdp->fd_dt->dt_ff[fd];
    420 
    421 	KASSERT(fd < fdp->fd_dt->dt_nfiles);
    422 	KASSERT(ff != NULL);
    423 	KASSERT((ff->ff_refcnt & FR_MASK) > 0);
    424 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
    425 
    426 	if (fdp->fd_refcnt == 1) {
    427 		/*
    428 		 * Single threaded: don't need to worry about concurrent
    429 		 * access (other than earlier calls to kqueue, which may
    430 		 * hold a reference to the descriptor).
    431 		 */
    432 		if (__predict_false((ff->ff_refcnt & FR_CLOSING) != 0)) {
    433 			fd_close(fd);
    434 			return;
    435 		}
    436 		ff->ff_refcnt--;
    437 		return;
    438 	}
    439 
    440 	/*
    441 	 * Ensure that any use of the file is complete and globally
    442 	 * visible before dropping the final reference.  If no membar,
    443 	 * the current CPU could still access memory associated with
    444 	 * the file after it has been freed or recycled by another
    445 	 * CPU.
    446 	 */
    447 #ifndef __HAVE_ATOMIC_AS_MEMBAR
    448 	membar_exit();
    449 #endif
    450 
    451 	/*
    452 	 * Be optimistic and start out with the assumption that no other
    453 	 * threads are trying to close the descriptor.  If the CAS fails,
    454 	 * we lost a race and/or it's being closed.
    455 	 */
    456 	for (u = ff->ff_refcnt & FR_MASK;; u = v) {
    457 		v = atomic_cas_uint(&ff->ff_refcnt, u, u - 1);
    458 		if (__predict_true(u == v)) {
    459 			return;
    460 		}
    461 		if (__predict_false((v & FR_CLOSING) != 0)) {
    462 			break;
    463 		}
    464 	}
    465 
    466 	/* Another thread is waiting to close the file: join it. */
    467 	(void)fd_close(fd);
    468 }
    469 
    470 /*
    471  * Convenience wrapper around fd_getfile() that returns reference
    472  * to a vnode.
    473  */
    474 int
    475 fd_getvnode(unsigned fd, file_t **fpp)
    476 {
    477 	vnode_t *vp;
    478 	file_t *fp;
    479 
    480 	fp = fd_getfile(fd);
    481 	if (__predict_false(fp == NULL)) {
    482 		return EBADF;
    483 	}
    484 	if (__predict_false(fp->f_type != DTYPE_VNODE)) {
    485 		fd_putfile(fd);
    486 		return EINVAL;
    487 	}
    488 	vp = fp->f_data;
    489 	if (__predict_false(vp->v_type == VBAD)) {
    490 		/* XXX Is this case really necessary? */
    491 		fd_putfile(fd);
    492 		return EBADF;
    493 	}
    494 	*fpp = fp;
    495 	return 0;
    496 }
    497 
    498 /*
    499  * Convenience wrapper around fd_getfile() that returns reference
    500  * to a socket.
    501  */
    502 int
    503 fd_getsock(unsigned fd, struct socket **sop)
    504 {
    505 	file_t *fp;
    506 
    507 	fp = fd_getfile(fd);
    508 	if (__predict_false(fp == NULL)) {
    509 		return EBADF;
    510 	}
    511 	if (__predict_false(fp->f_type != DTYPE_SOCKET)) {
    512 		fd_putfile(fd);
    513 		return ENOTSOCK;
    514 	}
    515 	*sop = fp->f_data;
    516 	return 0;
    517 }
    518 
    519 /*
    520  * Look up the file structure corresponding to a file descriptor
    521  * and return it with a reference held on the file, not the
    522  * descriptor.
    523  *
    524  * This is heavyweight and only used when accessing descriptors
    525  * from a foreign process.  The caller must ensure that `p' does
    526  * not exit or fork across this call.
    527  *
    528  * To release the file (not descriptor) reference, use closef().
    529  */
    530 file_t *
    531 fd_getfile2(proc_t *p, unsigned fd)
    532 {
    533 	filedesc_t *fdp;
    534 	fdfile_t *ff;
    535 	file_t *fp;
    536 	fdtab_t *dt;
    537 
    538 	fdp = p->p_fd;
    539 	mutex_enter(&fdp->fd_lock);
    540 	dt = fdp->fd_dt;
    541 	if (fd >= dt->dt_nfiles) {
    542 		mutex_exit(&fdp->fd_lock);
    543 		return NULL;
    544 	}
    545 	if ((ff = dt->dt_ff[fd]) == NULL) {
    546 		mutex_exit(&fdp->fd_lock);
    547 		return NULL;
    548 	}
    549 	if ((fp = ff->ff_file) == NULL) {
    550 		mutex_exit(&fdp->fd_lock);
    551 		return NULL;
    552 	}
    553 	mutex_enter(&fp->f_lock);
    554 	fp->f_count++;
    555 	mutex_exit(&fp->f_lock);
    556 	mutex_exit(&fdp->fd_lock);
    557 
    558 	return fp;
    559 }
    560 
    561 /*
    562  * Internal form of close.  Must be called with a reference to the
    563  * descriptor, and will drop the reference.  When all descriptor
    564  * references are dropped, releases the descriptor slot and a single
    565  * reference to the file structure.
    566  */
    567 int
    568 fd_close(unsigned fd)
    569 {
    570 	struct flock lf;
    571 	filedesc_t *fdp;
    572 	fdfile_t *ff;
    573 	file_t *fp;
    574 	proc_t *p;
    575 	lwp_t *l;
    576 	u_int refcnt;
    577 
    578 	l = curlwp;
    579 	p = l->l_proc;
    580 	fdp = l->l_fd;
    581 	ff = fdp->fd_dt->dt_ff[fd];
    582 
    583 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
    584 
    585 	mutex_enter(&fdp->fd_lock);
    586 	KASSERT((ff->ff_refcnt & FR_MASK) > 0);
    587 	if (__predict_false(ff->ff_file == NULL)) {
    588 		/*
    589 		 * Another user of the file is already closing, and is
    590 		 * waiting for other users of the file to drain.  Release
    591 		 * our reference, and wake up the closer.
    592 		 */
    593 		atomic_dec_uint(&ff->ff_refcnt);
    594 		cv_broadcast(&ff->ff_closing);
    595 		mutex_exit(&fdp->fd_lock);
    596 
    597 		/*
    598 		 * An application error, so pretend that the descriptor
    599 		 * was already closed.  We can't safely wait for it to
    600 		 * be closed without potentially deadlocking.
    601 		 */
    602 		return (EBADF);
    603 	}
    604 	KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
    605 
    606 	/*
    607 	 * There may be multiple users of this file within the process.
    608 	 * Notify existing and new users that the file is closing.  This
    609 	 * will prevent them from adding additional uses to this file
    610 	 * while we are closing it.
    611 	 */
    612 	fp = ff->ff_file;
    613 	ff->ff_file = NULL;
    614 	ff->ff_exclose = false;
    615 
    616 	/*
    617 	 * We expect the caller to hold a descriptor reference - drop it.
    618 	 * The reference count may increase beyond zero at this point due
    619 	 * to an erroneous descriptor reference by an application, but
    620 	 * fd_getfile() will notice that the file is being closed and drop
    621 	 * the reference again.
    622 	 */
    623 	if (fdp->fd_refcnt == 1) {
    624 		/* Single threaded. */
    625 		refcnt = --(ff->ff_refcnt);
    626 	} else {
    627 		/* Multi threaded. */
    628 #ifndef __HAVE_ATOMIC_AS_MEMBAR
    629 		membar_producer();
    630 #endif
    631 		refcnt = atomic_dec_uint_nv(&ff->ff_refcnt);
    632 	}
    633 	if (__predict_false(refcnt != 0)) {
    634 		/*
    635 		 * Wait for other references to drain.  This is typically
    636 		 * an application error - the descriptor is being closed
    637 		 * while still in use.
    638 		 * (Or just a threaded application trying to unblock its
    639 		 * thread that sleeps in (say) accept()).
    640 		 */
    641 		atomic_or_uint(&ff->ff_refcnt, FR_CLOSING);
    642 
    643 		/*
    644 		 * Remove any knotes attached to the file.  A knote
    645 		 * attached to the descriptor can hold references on it.
    646 		 */
    647 		mutex_exit(&fdp->fd_lock);
    648 		if (!SLIST_EMPTY(&ff->ff_knlist)) {
    649 			knote_fdclose(fd);
    650 		}
    651 
    652 		/*
    653 		 * Since the file system code doesn't know which fd
    654 		 * each request came from (think dup()), we have to
    655 		 * ask it to return ERESTART for any long-term blocks.
    656 		 * The re-entry through read/write/etc will detect the
    657 		 * closed fd and return EBAFD.
    658 		 * Blocked partial writes may return a short length.
    659 		 */
    660 		(*fp->f_ops->fo_restart)(fp);
    661 		mutex_enter(&fdp->fd_lock);
    662 
    663 		/*
    664 		 * We need to see the count drop to zero at least once,
    665 		 * in order to ensure that all pre-existing references
    666 		 * have been drained.  New references past this point are
    667 		 * of no interest.
    668 		 * XXX (dsl) this may need to call fo_restart() after a
    669 		 * timeout to guarantee that all the system calls exit.
    670 		 */
    671 		while ((ff->ff_refcnt & FR_MASK) != 0) {
    672 			cv_wait(&ff->ff_closing, &fdp->fd_lock);
    673 		}
    674 		atomic_and_uint(&ff->ff_refcnt, ~FR_CLOSING);
    675 	} else {
    676 		/* If no references, there must be no knotes. */
    677 		KASSERT(SLIST_EMPTY(&ff->ff_knlist));
    678 	}
    679 
    680 	/*
    681 	 * POSIX record locking dictates that any close releases ALL
    682 	 * locks owned by this process.  This is handled by setting
    683 	 * a flag in the unlock to free ONLY locks obeying POSIX
    684 	 * semantics, and not to free BSD-style file locks.
    685 	 * If the descriptor was in a message, POSIX-style locks
    686 	 * aren't passed with the descriptor.
    687 	 */
    688 	if (__predict_false((p->p_flag & PK_ADVLOCK) != 0 &&
    689 	    fp->f_type == DTYPE_VNODE)) {
    690 		lf.l_whence = SEEK_SET;
    691 		lf.l_start = 0;
    692 		lf.l_len = 0;
    693 		lf.l_type = F_UNLCK;
    694 		mutex_exit(&fdp->fd_lock);
    695 		(void)VOP_ADVLOCK(fp->f_data, p, F_UNLCK, &lf, F_POSIX);
    696 		mutex_enter(&fdp->fd_lock);
    697 	}
    698 
    699 	/* Free descriptor slot. */
    700 	fd_unused(fdp, fd);
    701 	mutex_exit(&fdp->fd_lock);
    702 
    703 	/* Now drop reference to the file itself. */
    704 	return closef(fp);
    705 }
    706 
    707 /*
    708  * Duplicate a file descriptor.
    709  */
    710 int
    711 fd_dup(file_t *fp, int minfd, int *newp, bool exclose)
    712 {
    713 	proc_t *p = curproc;
    714 	int error;
    715 
    716 	while ((error = fd_alloc(p, minfd, newp)) != 0) {
    717 		if (error != ENOSPC) {
    718 			return error;
    719 		}
    720 		fd_tryexpand(p);
    721 	}
    722 
    723 	curlwp->l_fd->fd_dt->dt_ff[*newp]->ff_exclose = exclose;
    724 	fd_affix(p, fp, *newp);
    725 	return 0;
    726 }
    727 
    728 /*
    729  * dup2 operation.
    730  */
    731 int
    732 fd_dup2(file_t *fp, unsigned new)
    733 {
    734 	filedesc_t *fdp = curlwp->l_fd;
    735 	fdfile_t *ff;
    736 	fdtab_t *dt;
    737 
    738 	/*
    739 	 * Ensure there are enough slots in the descriptor table,
    740 	 * and allocate an fdfile_t up front in case we need it.
    741 	 */
    742 	while (new >= fdp->fd_dt->dt_nfiles) {
    743 		fd_tryexpand(curproc);
    744 	}
    745 	ff = pool_cache_get(fdfile_cache, PR_WAITOK);
    746 
    747 	/*
    748 	 * If there is already a file open, close it.  If the file is
    749 	 * half open, wait for it to be constructed before closing it.
    750 	 * XXX Potential for deadlock here?
    751 	 */
    752 	mutex_enter(&fdp->fd_lock);
    753 	while (fd_isused(fdp, new)) {
    754 		mutex_exit(&fdp->fd_lock);
    755 		if (fd_getfile(new) != NULL) {
    756 			(void)fd_close(new);
    757 		} else {
    758 			/*
    759 			 * Crummy, but unlikely to happen.
    760 			 * Can occur if we interrupt another
    761 			 * thread while it is opening a file.
    762 			 */
    763 			kpause("dup2", false, 1, NULL);
    764 		}
    765 		mutex_enter(&fdp->fd_lock);
    766 	}
    767 	dt = fdp->fd_dt;
    768 	if (dt->dt_ff[new] == NULL) {
    769 		KASSERT(new >= NDFDFILE);
    770 		dt->dt_ff[new] = ff;
    771 		ff = NULL;
    772 	}
    773 	fd_used(fdp, new);
    774 	mutex_exit(&fdp->fd_lock);
    775 
    776 	/* Slot is now allocated.  Insert copy of the file. */
    777 	fd_affix(curproc, fp, new);
    778 	if (ff != NULL) {
    779 		pool_cache_put(fdfile_cache, ff);
    780 	}
    781 	return 0;
    782 }
    783 
    784 /*
    785  * Drop reference to a file structure.
    786  */
    787 int
    788 closef(file_t *fp)
    789 {
    790 	struct flock lf;
    791 	int error;
    792 
    793 	/*
    794 	 * Drop reference.  If referenced elsewhere it's still open
    795 	 * and we have nothing more to do.
    796 	 */
    797 	mutex_enter(&fp->f_lock);
    798 	KASSERT(fp->f_count > 0);
    799 	if (--fp->f_count > 0) {
    800 		mutex_exit(&fp->f_lock);
    801 		return 0;
    802 	}
    803 	KASSERT(fp->f_count == 0);
    804 	mutex_exit(&fp->f_lock);
    805 
    806 	/* We held the last reference - release locks, close and free. */
    807 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
    808 		lf.l_whence = SEEK_SET;
    809 		lf.l_start = 0;
    810 		lf.l_len = 0;
    811 		lf.l_type = F_UNLCK;
    812 		(void)VOP_ADVLOCK(fp->f_data, fp, F_UNLCK, &lf, F_FLOCK);
    813 	}
    814 	if (fp->f_ops != NULL) {
    815 		error = (*fp->f_ops->fo_close)(fp);
    816 	} else {
    817 		error = 0;
    818 	}
    819 	KASSERT(fp->f_count == 0);
    820 	KASSERT(fp->f_cred != NULL);
    821 	pool_cache_put(file_cache, fp);
    822 
    823 	return error;
    824 }
    825 
    826 /*
    827  * Allocate a file descriptor for the process.
    828  */
    829 int
    830 fd_alloc(proc_t *p, int want, int *result)
    831 {
    832 	filedesc_t *fdp = p->p_fd;
    833 	int i, lim, last, error;
    834 	u_int off, new;
    835 	fdtab_t *dt;
    836 
    837 	KASSERT(p == curproc || p == &proc0);
    838 
    839 	/*
    840 	 * Search for a free descriptor starting at the higher
    841 	 * of want or fd_freefile.
    842 	 */
    843 	mutex_enter(&fdp->fd_lock);
    844 	fd_checkmaps(fdp);
    845 	dt = fdp->fd_dt;
    846 	KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
    847 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    848 	last = min(dt->dt_nfiles, lim);
    849 	for (;;) {
    850 		if ((i = want) < fdp->fd_freefile)
    851 			i = fdp->fd_freefile;
    852 		off = i >> NDENTRYSHIFT;
    853 		new = fd_next_zero(fdp, fdp->fd_himap, off,
    854 		    (last + NDENTRIES - 1) >> NDENTRYSHIFT);
    855 		if (new == -1)
    856 			break;
    857 		i = fd_next_zero(fdp, &fdp->fd_lomap[new],
    858 		    new > off ? 0 : i & NDENTRYMASK, NDENTRIES);
    859 		if (i == -1) {
    860 			/*
    861 			 * Free file descriptor in this block was
    862 			 * below want, try again with higher want.
    863 			 */
    864 			want = (new + 1) << NDENTRYSHIFT;
    865 			continue;
    866 		}
    867 		i += (new << NDENTRYSHIFT);
    868 		if (i >= last) {
    869 			break;
    870 		}
    871 		if (dt->dt_ff[i] == NULL) {
    872 			KASSERT(i >= NDFDFILE);
    873 			dt->dt_ff[i] = pool_cache_get(fdfile_cache, PR_WAITOK);
    874 		}
    875 		KASSERT(dt->dt_ff[i]->ff_file == NULL);
    876 		fd_used(fdp, i);
    877 		if (want <= fdp->fd_freefile) {
    878 			fdp->fd_freefile = i;
    879 		}
    880 		*result = i;
    881 		KASSERT(i >= NDFDFILE ||
    882 		    dt->dt_ff[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
    883 		fd_checkmaps(fdp);
    884 		mutex_exit(&fdp->fd_lock);
    885 		return 0;
    886 	}
    887 
    888 	/* No space in current array.  Let the caller expand and retry. */
    889 	error = (dt->dt_nfiles >= lim) ? EMFILE : ENOSPC;
    890 	mutex_exit(&fdp->fd_lock);
    891 	return error;
    892 }
    893 
    894 /*
    895  * Allocate memory for a descriptor table.
    896  */
    897 static fdtab_t *
    898 fd_dtab_alloc(int n)
    899 {
    900 	fdtab_t *dt;
    901 	size_t sz;
    902 
    903 	KASSERT(n > NDFILE);
    904 
    905 	sz = sizeof(*dt) + (n - NDFILE) * sizeof(dt->dt_ff[0]);
    906 	dt = kmem_alloc(sz, KM_SLEEP);
    907 #ifdef DIAGNOSTIC
    908 	memset(dt, 0xff, sz);
    909 #endif
    910 	dt->dt_nfiles = n;
    911 	dt->dt_link = NULL;
    912 	return dt;
    913 }
    914 
    915 /*
    916  * Free a descriptor table, and all tables linked for deferred free.
    917  */
    918 static void
    919 fd_dtab_free(fdtab_t *dt)
    920 {
    921 	fdtab_t *next;
    922 	size_t sz;
    923 
    924 	do {
    925 		next = dt->dt_link;
    926 		KASSERT(dt->dt_nfiles > NDFILE);
    927 		sz = sizeof(*dt) +
    928 		    (dt->dt_nfiles - NDFILE) * sizeof(dt->dt_ff[0]);
    929 #ifdef DIAGNOSTIC
    930 		memset(dt, 0xff, sz);
    931 #endif
    932 		kmem_free(dt, sz);
    933 		dt = next;
    934 	} while (dt != NULL);
    935 }
    936 
    937 /*
    938  * Allocate descriptor bitmap.
    939  */
    940 static void
    941 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
    942 {
    943 	uint8_t *ptr;
    944 	size_t szlo, szhi;
    945 
    946 	KASSERT(n > NDENTRIES);
    947 
    948 	szlo = NDLOSLOTS(n) * sizeof(uint32_t);
    949 	szhi = NDHISLOTS(n) * sizeof(uint32_t);
    950 	ptr = kmem_alloc(szlo + szhi, KM_SLEEP);
    951 	*lo = (uint32_t *)ptr;
    952 	*hi = (uint32_t *)(ptr + szlo);
    953 }
    954 
    955 /*
    956  * Free descriptor bitmap.
    957  */
    958 static void
    959 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
    960 {
    961 	size_t szlo, szhi;
    962 
    963 	KASSERT(n > NDENTRIES);
    964 
    965 	szlo = NDLOSLOTS(n) * sizeof(uint32_t);
    966 	szhi = NDHISLOTS(n) * sizeof(uint32_t);
    967 	KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo));
    968 	kmem_free(lo, szlo + szhi);
    969 }
    970 
    971 /*
    972  * Expand a process' descriptor table.
    973  */
    974 void
    975 fd_tryexpand(proc_t *p)
    976 {
    977 	filedesc_t *fdp;
    978 	int i, numfiles, oldnfiles;
    979 	fdtab_t *newdt, *dt;
    980 	uint32_t *newhimap, *newlomap;
    981 
    982 	KASSERT(p == curproc || p == &proc0);
    983 
    984 	fdp = p->p_fd;
    985 	newhimap = NULL;
    986 	newlomap = NULL;
    987 	oldnfiles = fdp->fd_dt->dt_nfiles;
    988 
    989 	if (oldnfiles < NDEXTENT)
    990 		numfiles = NDEXTENT;
    991 	else
    992 		numfiles = 2 * oldnfiles;
    993 
    994 	newdt = fd_dtab_alloc(numfiles);
    995 	if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
    996 		fd_map_alloc(numfiles, &newlomap, &newhimap);
    997 	}
    998 
    999 	mutex_enter(&fdp->fd_lock);
   1000 	dt = fdp->fd_dt;
   1001 	KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
   1002 	if (dt->dt_nfiles != oldnfiles) {
   1003 		/* fdp changed; caller must retry */
   1004 		mutex_exit(&fdp->fd_lock);
   1005 		fd_dtab_free(newdt);
   1006 		if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
   1007 			fd_map_free(numfiles, newlomap, newhimap);
   1008 		}
   1009 		return;
   1010 	}
   1011 
   1012 	/* Copy the existing descriptor table and zero the new portion. */
   1013 	i = sizeof(fdfile_t *) * oldnfiles;
   1014 	memcpy(newdt->dt_ff, dt->dt_ff, i);
   1015 	memset((uint8_t *)newdt->dt_ff + i, 0,
   1016 	    numfiles * sizeof(fdfile_t *) - i);
   1017 
   1018 	/*
   1019 	 * Link old descriptor array into list to be discarded.  We defer
   1020 	 * freeing until the last reference to the descriptor table goes
   1021 	 * away (usually process exit).  This allows us to do lockless
   1022 	 * lookups in fd_getfile().
   1023 	 */
   1024 	if (oldnfiles > NDFILE) {
   1025 		if (fdp->fd_refcnt > 1) {
   1026 			newdt->dt_link = dt;
   1027 		} else {
   1028 			fd_dtab_free(dt);
   1029 		}
   1030 	}
   1031 
   1032 	if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
   1033 		i = NDHISLOTS(oldnfiles) * sizeof(uint32_t);
   1034 		memcpy(newhimap, fdp->fd_himap, i);
   1035 		memset((uint8_t *)newhimap + i, 0,
   1036 		    NDHISLOTS(numfiles) * sizeof(uint32_t) - i);
   1037 
   1038 		i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t);
   1039 		memcpy(newlomap, fdp->fd_lomap, i);
   1040 		memset((uint8_t *)newlomap + i, 0,
   1041 		    NDLOSLOTS(numfiles) * sizeof(uint32_t) - i);
   1042 
   1043 		if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
   1044 			fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
   1045 		}
   1046 		fdp->fd_himap = newhimap;
   1047 		fdp->fd_lomap = newlomap;
   1048 	}
   1049 
   1050 	/*
   1051 	 * All other modifications must become globally visible before
   1052 	 * the change to fd_dt.  See fd_getfile().
   1053 	 */
   1054 	membar_producer();
   1055 	fdp->fd_dt = newdt;
   1056 	KASSERT(newdt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
   1057 	fd_checkmaps(fdp);
   1058 	mutex_exit(&fdp->fd_lock);
   1059 }
   1060 
   1061 /*
   1062  * Create a new open file structure and allocate a file descriptor
   1063  * for the current process.
   1064  */
   1065 int
   1066 fd_allocfile(file_t **resultfp, int *resultfd)
   1067 {
   1068 	proc_t *p = curproc;
   1069 	kauth_cred_t cred;
   1070 	file_t *fp;
   1071 	int error;
   1072 
   1073 	while ((error = fd_alloc(p, 0, resultfd)) != 0) {
   1074 		if (error != ENOSPC) {
   1075 			return error;
   1076 		}
   1077 		fd_tryexpand(p);
   1078 	}
   1079 
   1080 	fp = pool_cache_get(file_cache, PR_WAITOK);
   1081 	if (fp == NULL) {
   1082 		return ENFILE;
   1083 	}
   1084 	KASSERT(fp->f_count == 0);
   1085 	KASSERT(fp->f_msgcount == 0);
   1086 	KASSERT(fp->f_unpcount == 0);
   1087 
   1088 	/* Replace cached credentials if not what we need. */
   1089 	cred = curlwp->l_cred;
   1090 	if (__predict_false(cred != fp->f_cred)) {
   1091 		kauth_cred_free(fp->f_cred);
   1092 		kauth_cred_hold(cred);
   1093 		fp->f_cred = cred;
   1094 	}
   1095 
   1096 	/*
   1097 	 * Don't allow recycled files to be scanned.
   1098 	 * See uipc_usrreq.c.
   1099 	 */
   1100 	if (__predict_false((fp->f_flag & FSCAN) != 0)) {
   1101 		mutex_enter(&fp->f_lock);
   1102 		atomic_and_uint(&fp->f_flag, ~FSCAN);
   1103 		mutex_exit(&fp->f_lock);
   1104 	}
   1105 
   1106 	fp->f_advice = 0;
   1107 	fp->f_offset = 0;
   1108 	*resultfp = fp;
   1109 
   1110 	return 0;
   1111 }
   1112 
   1113 /*
   1114  * Successful creation of a new descriptor: make visible to the process.
   1115  */
   1116 void
   1117 fd_affix(proc_t *p, file_t *fp, unsigned fd)
   1118 {
   1119 	fdfile_t *ff;
   1120 	filedesc_t *fdp;
   1121 
   1122 	KASSERT(p == curproc || p == &proc0);
   1123 
   1124 	/* Add a reference to the file structure. */
   1125 	mutex_enter(&fp->f_lock);
   1126 	fp->f_count++;
   1127 	mutex_exit(&fp->f_lock);
   1128 
   1129 	/*
   1130 	 * Insert the new file into the descriptor slot.
   1131 	 *
   1132 	 * The memory barriers provided by lock activity in this routine
   1133 	 * ensure that any updates to the file structure become globally
   1134 	 * visible before the file becomes visible to other LWPs in the
   1135 	 * current process.
   1136 	 */
   1137 	fdp = p->p_fd;
   1138 	ff = fdp->fd_dt->dt_ff[fd];
   1139 
   1140 	KASSERT(ff != NULL);
   1141 	KASSERT(ff->ff_file == NULL);
   1142 	KASSERT(ff->ff_allocated);
   1143 	KASSERT(fd_isused(fdp, fd));
   1144 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1145 
   1146 	/* No need to lock in order to make file initially visible. */
   1147 	ff->ff_file = fp;
   1148 }
   1149 
   1150 /*
   1151  * Abort creation of a new descriptor: free descriptor slot and file.
   1152  */
   1153 void
   1154 fd_abort(proc_t *p, file_t *fp, unsigned fd)
   1155 {
   1156 	filedesc_t *fdp;
   1157 	fdfile_t *ff;
   1158 
   1159 	KASSERT(p == curproc || p == &proc0);
   1160 
   1161 	fdp = p->p_fd;
   1162 	ff = fdp->fd_dt->dt_ff[fd];
   1163 
   1164 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1165 
   1166 	mutex_enter(&fdp->fd_lock);
   1167 	KASSERT(fd_isused(fdp, fd));
   1168 	fd_unused(fdp, fd);
   1169 	mutex_exit(&fdp->fd_lock);
   1170 
   1171 	if (fp != NULL) {
   1172 		KASSERT(fp->f_count == 0);
   1173 		KASSERT(fp->f_cred != NULL);
   1174 		pool_cache_put(file_cache, fp);
   1175 	}
   1176 }
   1177 
   1178 static int
   1179 file_ctor(void *arg, void *obj, int flags)
   1180 {
   1181 	file_t *fp = obj;
   1182 
   1183 	memset(fp, 0, sizeof(*fp));
   1184 
   1185 	mutex_enter(&filelist_lock);
   1186 	if (__predict_false(nfiles >= maxfiles)) {
   1187 		mutex_exit(&filelist_lock);
   1188 		tablefull("file", "increase kern.maxfiles or MAXFILES");
   1189 		return ENFILE;
   1190 	}
   1191 	nfiles++;
   1192 	LIST_INSERT_HEAD(&filehead, fp, f_list);
   1193 	mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
   1194 	fp->f_cred = curlwp->l_cred;
   1195 	kauth_cred_hold(fp->f_cred);
   1196 	mutex_exit(&filelist_lock);
   1197 
   1198 	return 0;
   1199 }
   1200 
   1201 static void
   1202 file_dtor(void *arg, void *obj)
   1203 {
   1204 	file_t *fp = obj;
   1205 
   1206 	mutex_enter(&filelist_lock);
   1207 	nfiles--;
   1208 	LIST_REMOVE(fp, f_list);
   1209 	mutex_exit(&filelist_lock);
   1210 
   1211 	kauth_cred_free(fp->f_cred);
   1212 	mutex_destroy(&fp->f_lock);
   1213 }
   1214 
   1215 static int
   1216 fdfile_ctor(void *arg, void *obj, int flags)
   1217 {
   1218 	fdfile_t *ff = obj;
   1219 
   1220 	memset(ff, 0, sizeof(*ff));
   1221 	cv_init(&ff->ff_closing, "fdclose");
   1222 
   1223 	return 0;
   1224 }
   1225 
   1226 static void
   1227 fdfile_dtor(void *arg, void *obj)
   1228 {
   1229 	fdfile_t *ff = obj;
   1230 
   1231 	cv_destroy(&ff->ff_closing);
   1232 }
   1233 
   1234 file_t *
   1235 fgetdummy(void)
   1236 {
   1237 	file_t *fp;
   1238 
   1239 	fp = kmem_zalloc(sizeof(*fp), KM_SLEEP);
   1240 	if (fp != NULL) {
   1241 		mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
   1242 	}
   1243 	return fp;
   1244 }
   1245 
   1246 void
   1247 fputdummy(file_t *fp)
   1248 {
   1249 
   1250 	mutex_destroy(&fp->f_lock);
   1251 	kmem_free(fp, sizeof(*fp));
   1252 }
   1253 
   1254 /*
   1255  * Create an initial filedesc structure.
   1256  */
   1257 filedesc_t *
   1258 fd_init(filedesc_t *fdp)
   1259 {
   1260 #ifdef DIAGNOSTIC
   1261 	unsigned fd;
   1262 #endif
   1263 
   1264 	if (__predict_true(fdp == NULL)) {
   1265 		fdp = pool_cache_get(filedesc_cache, PR_WAITOK);
   1266 	} else {
   1267 		KASSERT(fdp == &filedesc0);
   1268 		filedesc_ctor(NULL, fdp, PR_WAITOK);
   1269 	}
   1270 
   1271 #ifdef DIAGNOSTIC
   1272 	KASSERT(fdp->fd_lastfile == -1);
   1273 	KASSERT(fdp->fd_lastkqfile == -1);
   1274 	KASSERT(fdp->fd_knhash == NULL);
   1275 	KASSERT(fdp->fd_freefile == 0);
   1276 	KASSERT(fdp->fd_exclose == false);
   1277 	KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
   1278 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1279 	for (fd = 0; fd < NDFDFILE; fd++) {
   1280 		KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] ==
   1281 		    (fdfile_t *)fdp->fd_dfdfile[fd]);
   1282 	}
   1283 	for (fd = NDFDFILE; fd < NDFILE; fd++) {
   1284 		KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL);
   1285 	}
   1286 	KASSERT(fdp->fd_himap == fdp->fd_dhimap);
   1287 	KASSERT(fdp->fd_lomap == fdp->fd_dlomap);
   1288 #endif	/* DIAGNOSTIC */
   1289 
   1290 	fdp->fd_refcnt = 1;
   1291 	fd_checkmaps(fdp);
   1292 
   1293 	return fdp;
   1294 }
   1295 
   1296 /*
   1297  * Initialize a file descriptor table.
   1298  */
   1299 static int
   1300 filedesc_ctor(void *arg, void *obj, int flag)
   1301 {
   1302 	filedesc_t *fdp = obj;
   1303 	fdfile_t **ffp;
   1304 	int i;
   1305 
   1306 	memset(fdp, 0, sizeof(*fdp));
   1307 	mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE);
   1308 	fdp->fd_lastfile = -1;
   1309 	fdp->fd_lastkqfile = -1;
   1310 	fdp->fd_dt = &fdp->fd_dtbuiltin;
   1311 	fdp->fd_dtbuiltin.dt_nfiles = NDFILE;
   1312 	fdp->fd_himap = fdp->fd_dhimap;
   1313 	fdp->fd_lomap = fdp->fd_dlomap;
   1314 
   1315 	CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t));
   1316 	for (i = 0, ffp = fdp->fd_dt->dt_ff; i < NDFDFILE; i++, ffp++) {
   1317 		*ffp = (fdfile_t *)fdp->fd_dfdfile[i];
   1318 		(void)fdfile_ctor(NULL, fdp->fd_dfdfile[i], PR_WAITOK);
   1319 	}
   1320 
   1321 	return 0;
   1322 }
   1323 
   1324 static void
   1325 filedesc_dtor(void *arg, void *obj)
   1326 {
   1327 	filedesc_t *fdp = obj;
   1328 	int i;
   1329 
   1330 	for (i = 0; i < NDFDFILE; i++) {
   1331 		fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
   1332 	}
   1333 
   1334 	mutex_destroy(&fdp->fd_lock);
   1335 }
   1336 
   1337 /*
   1338  * Make p share curproc's filedesc structure.
   1339  */
   1340 void
   1341 fd_share(struct proc *p)
   1342 {
   1343 	filedesc_t *fdp;
   1344 
   1345 	fdp = curlwp->l_fd;
   1346 	p->p_fd = fdp;
   1347 	atomic_inc_uint(&fdp->fd_refcnt);
   1348 }
   1349 
   1350 /*
   1351  * Acquire a hold on a filedesc structure.
   1352  */
   1353 void
   1354 fd_hold(lwp_t *l)
   1355 {
   1356 	filedesc_t *fdp = l->l_fd;
   1357 
   1358 	atomic_inc_uint(&fdp->fd_refcnt);
   1359 }
   1360 
   1361 /*
   1362  * Copy a filedesc structure.
   1363  */
   1364 filedesc_t *
   1365 fd_copy(void)
   1366 {
   1367 	filedesc_t *newfdp, *fdp;
   1368 	fdfile_t *ff, **ffp, **nffp, *ff2;
   1369 	int i, j, numfiles, lastfile, newlast;
   1370 	file_t *fp;
   1371 	fdtab_t *newdt;
   1372 
   1373 	fdp = curproc->p_fd;
   1374 	newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
   1375 	newfdp->fd_refcnt = 1;
   1376 
   1377 #ifdef DIAGNOSTIC
   1378 	KASSERT(newfdp->fd_lastfile == -1);
   1379 	KASSERT(newfdp->fd_lastkqfile == -1);
   1380 	KASSERT(newfdp->fd_knhash == NULL);
   1381 	KASSERT(newfdp->fd_freefile == 0);
   1382 	KASSERT(newfdp->fd_exclose == false);
   1383 	KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
   1384 	KASSERT(newfdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1385 	for (i = 0; i < NDFDFILE; i++) {
   1386 		KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] ==
   1387 		    (fdfile_t *)&newfdp->fd_dfdfile[i]);
   1388 	}
   1389 	for (i = NDFDFILE; i < NDFILE; i++) {
   1390 		KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL);
   1391 	}
   1392 #endif	/* DIAGNOSTIC */
   1393 
   1394 	mutex_enter(&fdp->fd_lock);
   1395 	fd_checkmaps(fdp);
   1396 	numfiles = fdp->fd_dt->dt_nfiles;
   1397 	lastfile = fdp->fd_lastfile;
   1398 
   1399 	/*
   1400 	 * If the number of open files fits in the internal arrays
   1401 	 * of the open file structure, use them, otherwise allocate
   1402 	 * additional memory for the number of descriptors currently
   1403 	 * in use.
   1404 	 */
   1405 	if (lastfile < NDFILE) {
   1406 		i = NDFILE;
   1407 		newdt = newfdp->fd_dt;
   1408 		KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
   1409 	} else {
   1410 		/*
   1411 		 * Compute the smallest multiple of NDEXTENT needed
   1412 		 * for the file descriptors currently in use,
   1413 		 * allowing the table to shrink.
   1414 		 */
   1415 		i = numfiles;
   1416 		while (i >= 2 * NDEXTENT && i > lastfile * 2) {
   1417 			i /= 2;
   1418 		}
   1419 		KASSERT(i > NDFILE);
   1420 		newdt = fd_dtab_alloc(i);
   1421 		newfdp->fd_dt = newdt;
   1422 		memcpy(newdt->dt_ff, newfdp->fd_dtbuiltin.dt_ff,
   1423 		    NDFDFILE * sizeof(fdfile_t **));
   1424 		memset(newdt->dt_ff + NDFDFILE, 0,
   1425 		    (i - NDFDFILE) * sizeof(fdfile_t **));
   1426 	}
   1427 	if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
   1428 		newfdp->fd_himap = newfdp->fd_dhimap;
   1429 		newfdp->fd_lomap = newfdp->fd_dlomap;
   1430 	} else {
   1431 		fd_map_alloc(i, &newfdp->fd_lomap, &newfdp->fd_himap);
   1432 		KASSERT(i >= NDENTRIES * NDENTRIES);
   1433 		memset(newfdp->fd_himap, 0, NDHISLOTS(i)*sizeof(uint32_t));
   1434 		memset(newfdp->fd_lomap, 0, NDLOSLOTS(i)*sizeof(uint32_t));
   1435 	}
   1436 	newfdp->fd_freefile = fdp->fd_freefile;
   1437 	newfdp->fd_exclose = fdp->fd_exclose;
   1438 
   1439 	ffp = fdp->fd_dt->dt_ff;
   1440 	nffp = newdt->dt_ff;
   1441 	newlast = -1;
   1442 	for (i = 0; i <= (int)lastfile; i++, ffp++, nffp++) {
   1443 		KASSERT(i >= NDFDFILE ||
   1444 		    *nffp == (fdfile_t *)newfdp->fd_dfdfile[i]);
   1445 		ff = *ffp;
   1446 		if (ff == NULL || (fp = ff->ff_file) == NULL) {
   1447 			/* Descriptor unused, or descriptor half open. */
   1448 			KASSERT(!fd_isused(newfdp, i));
   1449 			continue;
   1450 		}
   1451 		if (__predict_false(fp->f_type == DTYPE_KQUEUE)) {
   1452 			/* kqueue descriptors cannot be copied. */
   1453 			if (i < newfdp->fd_freefile) {
   1454 				newfdp->fd_freefile = i;
   1455 			}
   1456 			continue;
   1457 		}
   1458 		/* It's active: add a reference to the file. */
   1459 		mutex_enter(&fp->f_lock);
   1460 		fp->f_count++;
   1461 		mutex_exit(&fp->f_lock);
   1462 
   1463 		/* Allocate an fdfile_t to represent it. */
   1464 		if (i >= NDFDFILE) {
   1465 			ff2 = pool_cache_get(fdfile_cache, PR_WAITOK);
   1466 			*nffp = ff2;
   1467 		} else {
   1468 			ff2 = newdt->dt_ff[i];
   1469 		}
   1470 		ff2->ff_file = fp;
   1471 		ff2->ff_exclose = ff->ff_exclose;
   1472 		ff2->ff_allocated = true;
   1473 
   1474 		/* Fix up bitmaps. */
   1475 		j = i >> NDENTRYSHIFT;
   1476 		KASSERT((newfdp->fd_lomap[j] & (1 << (i & NDENTRYMASK))) == 0);
   1477 		newfdp->fd_lomap[j] |= 1 << (i & NDENTRYMASK);
   1478 		if (__predict_false(newfdp->fd_lomap[j] == ~0)) {
   1479 			KASSERT((newfdp->fd_himap[j >> NDENTRYSHIFT] &
   1480 			    (1 << (j & NDENTRYMASK))) == 0);
   1481 			newfdp->fd_himap[j >> NDENTRYSHIFT] |=
   1482 			    1 << (j & NDENTRYMASK);
   1483 		}
   1484 		newlast = i;
   1485 	}
   1486 	KASSERT(newdt->dt_ff[0] == (fdfile_t *)newfdp->fd_dfdfile[0]);
   1487 	newfdp->fd_lastfile = newlast;
   1488 	fd_checkmaps(newfdp);
   1489 	mutex_exit(&fdp->fd_lock);
   1490 
   1491 	return newfdp;
   1492 }
   1493 
   1494 /*
   1495  * Release a filedesc structure.
   1496  */
   1497 void
   1498 fd_free(void)
   1499 {
   1500 	fdfile_t *ff;
   1501 	file_t *fp;
   1502 	int fd, nf;
   1503 	fdtab_t *dt;
   1504 	lwp_t * const l = curlwp;
   1505 	filedesc_t * const fdp = l->l_fd;
   1506 	const bool noadvlock = (l->l_proc->p_flag & PK_ADVLOCK) == 0;
   1507 
   1508 	KASSERT(fdp->fd_dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
   1509 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1510 	KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
   1511 
   1512 #ifndef __HAVE_ATOMIC_AS_MEMBAR
   1513 	membar_exit();
   1514 #endif
   1515 	if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
   1516 		return;
   1517 
   1518 	/*
   1519 	 * Close any files that the process holds open.
   1520 	 */
   1521 	dt = fdp->fd_dt;
   1522 	fd_checkmaps(fdp);
   1523 #ifdef DEBUG
   1524 	fdp->fd_refcnt = -1; /* see fd_checkmaps */
   1525 #endif
   1526 	for (fd = 0, nf = dt->dt_nfiles; fd < nf; fd++) {
   1527 		ff = dt->dt_ff[fd];
   1528 		KASSERT(fd >= NDFDFILE ||
   1529 		    ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1530 		if (ff == NULL)
   1531 			continue;
   1532 		if ((fp = ff->ff_file) != NULL) {
   1533 			/*
   1534 			 * Must use fd_close() here if there is
   1535 			 * a reference from kqueue or we might have posix
   1536 			 * advisory locks.
   1537 			 */
   1538 			if (__predict_true(ff->ff_refcnt == 0) &&
   1539 			    (noadvlock || fp->f_type != DTYPE_VNODE)) {
   1540 				ff->ff_file = NULL;
   1541 				ff->ff_exclose = false;
   1542 				ff->ff_allocated = false;
   1543 				closef(fp);
   1544 			} else {
   1545 				ff->ff_refcnt++;
   1546 				fd_close(fd);
   1547 			}
   1548 		}
   1549 		KASSERT(ff->ff_refcnt == 0);
   1550 		KASSERT(ff->ff_file == NULL);
   1551 		KASSERT(!ff->ff_exclose);
   1552 		KASSERT(!ff->ff_allocated);
   1553 		if (fd >= NDFDFILE) {
   1554 			pool_cache_put(fdfile_cache, ff);
   1555 			dt->dt_ff[fd] = NULL;
   1556 		}
   1557 	}
   1558 
   1559 	/*
   1560 	 * Clean out the descriptor table for the next user and return
   1561 	 * to the cache.
   1562 	 */
   1563 	if (__predict_false(dt != &fdp->fd_dtbuiltin)) {
   1564 		fd_dtab_free(fdp->fd_dt);
   1565 		/* Otherwise, done above. */
   1566 		memset(&fdp->fd_dtbuiltin.dt_ff[NDFDFILE], 0,
   1567 		    (NDFILE - NDFDFILE) * sizeof(fdp->fd_dtbuiltin.dt_ff[0]));
   1568 		fdp->fd_dt = &fdp->fd_dtbuiltin;
   1569 	}
   1570 	if (__predict_false(NDHISLOTS(nf) > NDHISLOTS(NDFILE))) {
   1571 		KASSERT(fdp->fd_himap != fdp->fd_dhimap);
   1572 		KASSERT(fdp->fd_lomap != fdp->fd_dlomap);
   1573 		fd_map_free(nf, fdp->fd_lomap, fdp->fd_himap);
   1574 	}
   1575 	if (__predict_false(fdp->fd_knhash != NULL)) {
   1576 		hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask);
   1577 		fdp->fd_knhash = NULL;
   1578 		fdp->fd_knhashmask = 0;
   1579 	} else {
   1580 		KASSERT(fdp->fd_knhashmask == 0);
   1581 	}
   1582 	fdp->fd_dt = &fdp->fd_dtbuiltin;
   1583 	fdp->fd_lastkqfile = -1;
   1584 	fdp->fd_lastfile = -1;
   1585 	fdp->fd_freefile = 0;
   1586 	fdp->fd_exclose = false;
   1587 	memset(&fdp->fd_startzero, 0, sizeof(*fdp) -
   1588 	    offsetof(filedesc_t, fd_startzero));
   1589 	fdp->fd_himap = fdp->fd_dhimap;
   1590 	fdp->fd_lomap = fdp->fd_dlomap;
   1591 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1592 	KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
   1593 	KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
   1594 #ifdef DEBUG
   1595 	fdp->fd_refcnt = 0; /* see fd_checkmaps */
   1596 #endif
   1597 	fd_checkmaps(fdp);
   1598 	pool_cache_put(filedesc_cache, fdp);
   1599 }
   1600 
   1601 /*
   1602  * File Descriptor pseudo-device driver (/dev/fd/).
   1603  *
   1604  * Opening minor device N dup()s the file (if any) connected to file
   1605  * descriptor N belonging to the calling process.  Note that this driver
   1606  * consists of only the ``open()'' routine, because all subsequent
   1607  * references to this file will be direct to the other driver.
   1608  */
   1609 static int
   1610 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
   1611 {
   1612 
   1613 	/*
   1614 	 * XXX Kludge: set dupfd to contain the value of the
   1615 	 * the file descriptor being sought for duplication. The error
   1616 	 * return ensures that the vnode for this device will be released
   1617 	 * by vn_open. Open will detect this special error and take the
   1618 	 * actions in fd_dupopen below. Other callers of vn_open or VOP_OPEN
   1619 	 * will simply report the error.
   1620 	 */
   1621 	l->l_dupfd = minor(dev);	/* XXX */
   1622 	return EDUPFD;
   1623 }
   1624 
   1625 /*
   1626  * Duplicate the specified descriptor to a free descriptor.
   1627  */
   1628 int
   1629 fd_dupopen(int old, int *new, int mode, int error)
   1630 {
   1631 	filedesc_t *fdp;
   1632 	fdfile_t *ff;
   1633 	file_t *fp;
   1634 	fdtab_t *dt;
   1635 
   1636 	if ((fp = fd_getfile(old)) == NULL) {
   1637 		return EBADF;
   1638 	}
   1639 	fdp = curlwp->l_fd;
   1640 	dt = fdp->fd_dt;
   1641 	ff = dt->dt_ff[old];
   1642 
   1643 	/*
   1644 	 * There are two cases of interest here.
   1645 	 *
   1646 	 * For EDUPFD simply dup (old) to file descriptor
   1647 	 * (new) and return.
   1648 	 *
   1649 	 * For EMOVEFD steal away the file structure from (old) and
   1650 	 * store it in (new).  (old) is effectively closed by
   1651 	 * this operation.
   1652 	 *
   1653 	 * Any other error code is just returned.
   1654 	 */
   1655 	switch (error) {
   1656 	case EDUPFD:
   1657 		/*
   1658 		 * Check that the mode the file is being opened for is a
   1659 		 * subset of the mode of the existing descriptor.
   1660 		 */
   1661 		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
   1662 			error = EACCES;
   1663 			break;
   1664 		}
   1665 
   1666 		/* Copy it. */
   1667 		error = fd_dup(fp, 0, new, ff->ff_exclose);
   1668 		break;
   1669 
   1670 	case EMOVEFD:
   1671 		/* Copy it. */
   1672 		error = fd_dup(fp, 0, new, ff->ff_exclose);
   1673 		if (error != 0) {
   1674 			break;
   1675 		}
   1676 
   1677 		/* Steal away the file pointer from 'old'. */
   1678 		(void)fd_close(old);
   1679 		return 0;
   1680 	}
   1681 
   1682 	fd_putfile(old);
   1683 	return error;
   1684 }
   1685 
   1686 /*
   1687  * Close open files on exec.
   1688  */
   1689 void
   1690 fd_closeexec(void)
   1691 {
   1692 	proc_t *p;
   1693 	filedesc_t *fdp;
   1694 	fdfile_t *ff;
   1695 	lwp_t *l;
   1696 	fdtab_t *dt;
   1697 	int fd;
   1698 
   1699 	l = curlwp;
   1700 	p = l->l_proc;
   1701 	fdp = p->p_fd;
   1702 
   1703 	if (fdp->fd_refcnt > 1) {
   1704 		fdp = fd_copy();
   1705 		fd_free();
   1706 		p->p_fd = fdp;
   1707 		l->l_fd = fdp;
   1708 	}
   1709 	if (!fdp->fd_exclose) {
   1710 		return;
   1711 	}
   1712 	fdp->fd_exclose = false;
   1713 	dt = fdp->fd_dt;
   1714 
   1715 	for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
   1716 		if ((ff = dt->dt_ff[fd]) == NULL) {
   1717 			KASSERT(fd >= NDFDFILE);
   1718 			continue;
   1719 		}
   1720 		KASSERT(fd >= NDFDFILE ||
   1721 		    ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1722 		if (ff->ff_file == NULL)
   1723 			continue;
   1724 		if (ff->ff_exclose) {
   1725 			/*
   1726 			 * We need a reference to close the file.
   1727 			 * No other threads can see the fdfile_t at
   1728 			 * this point, so don't bother locking.
   1729 			 */
   1730 			KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
   1731 			ff->ff_refcnt++;
   1732 			fd_close(fd);
   1733 		}
   1734 	}
   1735 }
   1736 
   1737 /*
   1738  * Sets descriptor owner. If the owner is a process, 'pgid'
   1739  * is set to positive value, process ID. If the owner is process group,
   1740  * 'pgid' is set to -pg_id.
   1741  */
   1742 int
   1743 fsetown(pid_t *pgid, u_long cmd, const void *data)
   1744 {
   1745 	pid_t id = *(const pid_t *)data;
   1746 	int error;
   1747 
   1748 	switch (cmd) {
   1749 	case TIOCSPGRP:
   1750 		if (id < 0)
   1751 			return EINVAL;
   1752 		id = -id;
   1753 		break;
   1754 	default:
   1755 		break;
   1756 	}
   1757 	if (id > 0) {
   1758 		mutex_enter(proc_lock);
   1759 		error = proc_find(id) ? 0 : ESRCH;
   1760 		mutex_exit(proc_lock);
   1761 	} else if (id < 0) {
   1762 		error = pgid_in_session(curproc, -id);
   1763 	} else {
   1764 		error = 0;
   1765 	}
   1766 	if (!error) {
   1767 		*pgid = id;
   1768 	}
   1769 	return error;
   1770 }
   1771 
   1772 void
   1773 fd_set_exclose(struct lwp *l, int fd, bool exclose)
   1774 {
   1775 	filedesc_t *fdp = l->l_fd;
   1776 	fdfile_t *ff = fdp->fd_dt->dt_ff[fd];
   1777 
   1778 	ff->ff_exclose = exclose;
   1779 	if (exclose)
   1780 		fdp->fd_exclose = true;
   1781 }
   1782 
   1783 /*
   1784  * Return descriptor owner information. If the value is positive,
   1785  * it's process ID. If it's negative, it's process group ID and
   1786  * needs the sign removed before use.
   1787  */
   1788 int
   1789 fgetown(pid_t pgid, u_long cmd, void *data)
   1790 {
   1791 
   1792 	switch (cmd) {
   1793 	case TIOCGPGRP:
   1794 		*(int *)data = -pgid;
   1795 		break;
   1796 	default:
   1797 		*(int *)data = pgid;
   1798 		break;
   1799 	}
   1800 	return 0;
   1801 }
   1802 
   1803 /*
   1804  * Send signal to descriptor owner, either process or process group.
   1805  */
   1806 void
   1807 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
   1808 {
   1809 	ksiginfo_t ksi;
   1810 
   1811 	KASSERT(!cpu_intr_p());
   1812 
   1813 	if (pgid == 0) {
   1814 		return;
   1815 	}
   1816 
   1817 	KSI_INIT(&ksi);
   1818 	ksi.ksi_signo = signo;
   1819 	ksi.ksi_code = code;
   1820 	ksi.ksi_band = band;
   1821 
   1822 	mutex_enter(proc_lock);
   1823 	if (pgid > 0) {
   1824 		struct proc *p1;
   1825 
   1826 		p1 = proc_find(pgid);
   1827 		if (p1 != NULL) {
   1828 			kpsignal(p1, &ksi, fdescdata);
   1829 		}
   1830 	} else {
   1831 		struct pgrp *pgrp;
   1832 
   1833 		KASSERT(pgid < 0);
   1834 		pgrp = pgrp_find(-pgid);
   1835 		if (pgrp != NULL) {
   1836 			kpgsignal(pgrp, &ksi, fdescdata, 0);
   1837 		}
   1838 	}
   1839 	mutex_exit(proc_lock);
   1840 }
   1841 
   1842 int
   1843 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
   1844 	 void *data)
   1845 {
   1846 
   1847 	fp->f_flag = flag;
   1848 	fp->f_type = DTYPE_MISC;
   1849 	fp->f_ops = fops;
   1850 	fp->f_data = data;
   1851 	curlwp->l_dupfd = fd;
   1852 	fd_affix(curproc, fp, fd);
   1853 
   1854 	return EMOVEFD;
   1855 }
   1856 
   1857 int
   1858 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
   1859 {
   1860 
   1861 	if (cmd == F_SETFL)
   1862 		return 0;
   1863 
   1864 	return EOPNOTSUPP;
   1865 }
   1866 
   1867 int
   1868 fnullop_poll(file_t *fp, int which)
   1869 {
   1870 
   1871 	return 0;
   1872 }
   1873 
   1874 int
   1875 fnullop_kqfilter(file_t *fp, struct knote *kn)
   1876 {
   1877 
   1878 	return 0;
   1879 }
   1880 
   1881 void
   1882 fnullop_restart(file_t *fp)
   1883 {
   1884 
   1885 }
   1886 
   1887 int
   1888 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
   1889 	    kauth_cred_t cred, int flags)
   1890 {
   1891 
   1892 	return EOPNOTSUPP;
   1893 }
   1894 
   1895 int
   1896 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
   1897 	     kauth_cred_t cred, int flags)
   1898 {
   1899 
   1900 	return EOPNOTSUPP;
   1901 }
   1902 
   1903 int
   1904 fbadop_ioctl(file_t *fp, u_long com, void *data)
   1905 {
   1906 
   1907 	return EOPNOTSUPP;
   1908 }
   1909 
   1910 int
   1911 fbadop_stat(file_t *fp, struct stat *sb)
   1912 {
   1913 
   1914 	return EOPNOTSUPP;
   1915 }
   1916 
   1917 int
   1918 fbadop_close(file_t *fp)
   1919 {
   1920 
   1921 	return EOPNOTSUPP;
   1922 }
   1923 
   1924 /*
   1925  * sysctl routines pertaining to file descriptors
   1926  */
   1927 
   1928 /* Initialized in sysctl_init() for now... */
   1929 extern kmutex_t sysctl_file_marker_lock;
   1930 static u_int sysctl_file_marker = 1;
   1931 
   1932 /*
   1933  * Expects to be called with proc_lock and sysctl_file_marker_lock locked.
   1934  */
   1935 static void
   1936 sysctl_file_marker_reset(void)
   1937 {
   1938 	struct proc *p;
   1939 
   1940 	PROCLIST_FOREACH(p, &allproc) {
   1941 		struct filedesc *fd = p->p_fd;
   1942 		fdtab_t *dt;
   1943 		u_int i;
   1944 
   1945 		mutex_enter(&fd->fd_lock);
   1946 		dt = fd->fd_dt;
   1947 		for (i = 0; i < dt->dt_nfiles; i++) {
   1948 			struct file *fp;
   1949 			fdfile_t *ff;
   1950 
   1951 			if ((ff = dt->dt_ff[i]) == NULL) {
   1952 				continue;
   1953 			}
   1954 			if ((fp = ff->ff_file) == NULL) {
   1955 				continue;
   1956 			}
   1957 			fp->f_marker = 0;
   1958 		}
   1959 		mutex_exit(&fd->fd_lock);
   1960 	}
   1961 }
   1962 
   1963 /*
   1964  * sysctl helper routine for kern.file pseudo-subtree.
   1965  */
   1966 static int
   1967 sysctl_kern_file(SYSCTLFN_ARGS)
   1968 {
   1969 	int error;
   1970 	size_t buflen;
   1971 	struct file *fp, fbuf;
   1972 	char *start, *where;
   1973 	struct proc *p;
   1974 
   1975 	start = where = oldp;
   1976 	buflen = *oldlenp;
   1977 
   1978 	if (where == NULL) {
   1979 		/*
   1980 		 * overestimate by 10 files
   1981 		 */
   1982 		*oldlenp = sizeof(filehead) + (nfiles + 10) *
   1983 		    sizeof(struct file);
   1984 		return 0;
   1985 	}
   1986 
   1987 	/*
   1988 	 * first sysctl_copyout filehead
   1989 	 */
   1990 	if (buflen < sizeof(filehead)) {
   1991 		*oldlenp = 0;
   1992 		return 0;
   1993 	}
   1994 	sysctl_unlock();
   1995 	error = sysctl_copyout(l, &filehead, where, sizeof(filehead));
   1996 	if (error) {
   1997 		sysctl_relock();
   1998 		return error;
   1999 	}
   2000 	buflen -= sizeof(filehead);
   2001 	where += sizeof(filehead);
   2002 
   2003 	/*
   2004 	 * followed by an array of file structures
   2005 	 */
   2006 	mutex_enter(&sysctl_file_marker_lock);
   2007 	mutex_enter(proc_lock);
   2008 	PROCLIST_FOREACH(p, &allproc) {
   2009 		struct filedesc *fd;
   2010 		fdtab_t *dt;
   2011 		u_int i;
   2012 
   2013 		if (p->p_stat == SIDL) {
   2014 			/* skip embryonic processes */
   2015 			continue;
   2016 		}
   2017 		mutex_enter(p->p_lock);
   2018 		error = kauth_authorize_process(l->l_cred,
   2019 		    KAUTH_PROCESS_CANSEE, p,
   2020 		    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES),
   2021 		    NULL, NULL);
   2022 		mutex_exit(p->p_lock);
   2023 		if (error != 0) {
   2024 			/*
   2025 			 * Don't leak kauth retval if we're silently
   2026 			 * skipping this entry.
   2027 			 */
   2028 			error = 0;
   2029 			continue;
   2030 		}
   2031 
   2032 		/*
   2033 		 * Grab a hold on the process.
   2034 		 */
   2035 		if (!rw_tryenter(&p->p_reflock, RW_READER)) {
   2036 			continue;
   2037 		}
   2038 		mutex_exit(proc_lock);
   2039 
   2040 		fd = p->p_fd;
   2041 		mutex_enter(&fd->fd_lock);
   2042 		dt = fd->fd_dt;
   2043 		for (i = 0; i < dt->dt_nfiles; i++) {
   2044 			fdfile_t *ff;
   2045 
   2046 			if ((ff = dt->dt_ff[i]) == NULL) {
   2047 				continue;
   2048 			}
   2049 			if ((fp = ff->ff_file) == NULL) {
   2050 				continue;
   2051 			}
   2052 
   2053 			mutex_enter(&fp->f_lock);
   2054 
   2055 			if ((fp->f_count == 0) ||
   2056 			    (fp->f_marker == sysctl_file_marker)) {
   2057 				mutex_exit(&fp->f_lock);
   2058 				continue;
   2059 			}
   2060 
   2061 			/* Check that we have enough space. */
   2062 			if (buflen < sizeof(struct file)) {
   2063 				*oldlenp = where - start;
   2064 				mutex_exit(&fp->f_lock);
   2065 				error = ENOMEM;
   2066 				break;
   2067 			}
   2068 
   2069 			memcpy(&fbuf, fp, sizeof(fbuf));
   2070 			mutex_exit(&fp->f_lock);
   2071 			error = sysctl_copyout(l, &fbuf, where, sizeof(fbuf));
   2072 			if (error) {
   2073 				break;
   2074 			}
   2075 			buflen -= sizeof(struct file);
   2076 			where += sizeof(struct file);
   2077 
   2078 			fp->f_marker = sysctl_file_marker;
   2079 		}
   2080 		mutex_exit(&fd->fd_lock);
   2081 
   2082 		/*
   2083 		 * Release reference to process.
   2084 		 */
   2085 		mutex_enter(proc_lock);
   2086 		rw_exit(&p->p_reflock);
   2087 
   2088 		if (error)
   2089 			break;
   2090 	}
   2091 
   2092 	sysctl_file_marker++;
   2093 	/* Reset all markers if wrapped. */
   2094 	if (sysctl_file_marker == 0) {
   2095 		sysctl_file_marker_reset();
   2096 		sysctl_file_marker++;
   2097 	}
   2098 
   2099 	mutex_exit(proc_lock);
   2100 	mutex_exit(&sysctl_file_marker_lock);
   2101 
   2102 	*oldlenp = where - start;
   2103 	sysctl_relock();
   2104 	return error;
   2105 }
   2106 
   2107 /*
   2108  * sysctl helper function for kern.file2
   2109  */
   2110 static int
   2111 sysctl_kern_file2(SYSCTLFN_ARGS)
   2112 {
   2113 	struct proc *p;
   2114 	struct file *fp;
   2115 	struct filedesc *fd;
   2116 	struct kinfo_file kf;
   2117 	char *dp;
   2118 	u_int i, op;
   2119 	size_t len, needed, elem_size, out_size;
   2120 	int error, arg, elem_count;
   2121 	fdfile_t *ff;
   2122 	fdtab_t *dt;
   2123 
   2124 	if (namelen == 1 && name[0] == CTL_QUERY)
   2125 		return sysctl_query(SYSCTLFN_CALL(rnode));
   2126 
   2127 	if (namelen != 4)
   2128 		return EINVAL;
   2129 
   2130 	error = 0;
   2131 	dp = oldp;
   2132 	len = (oldp != NULL) ? *oldlenp : 0;
   2133 	op = name[0];
   2134 	arg = name[1];
   2135 	elem_size = name[2];
   2136 	elem_count = name[3];
   2137 	out_size = MIN(sizeof(kf), elem_size);
   2138 	needed = 0;
   2139 
   2140 	if (elem_size < 1 || elem_count < 0)
   2141 		return EINVAL;
   2142 
   2143 	switch (op) {
   2144 	case KERN_FILE_BYFILE:
   2145 	case KERN_FILE_BYPID:
   2146 		/*
   2147 		 * We're traversing the process list in both cases; the BYFILE
   2148 		 * case does additional work of keeping track of files already
   2149 		 * looked at.
   2150 		 */
   2151 
   2152 		/* doesn't use arg so it must be zero */
   2153 		if ((op == KERN_FILE_BYFILE) && (arg != 0))
   2154 			return EINVAL;
   2155 
   2156 		if ((op == KERN_FILE_BYPID) && (arg < -1))
   2157 			/* -1 means all processes */
   2158 			return EINVAL;
   2159 
   2160 		sysctl_unlock();
   2161 		if (op == KERN_FILE_BYFILE)
   2162 			mutex_enter(&sysctl_file_marker_lock);
   2163 		mutex_enter(proc_lock);
   2164 		PROCLIST_FOREACH(p, &allproc) {
   2165 			if (p->p_stat == SIDL) {
   2166 				/* skip embryonic processes */
   2167 				continue;
   2168 			}
   2169 			if (arg > 0 && p->p_pid != arg) {
   2170 				/* pick only the one we want */
   2171 				/* XXX want 0 to mean "kernel files" */
   2172 				continue;
   2173 			}
   2174 			mutex_enter(p->p_lock);
   2175 			error = kauth_authorize_process(l->l_cred,
   2176 			    KAUTH_PROCESS_CANSEE, p,
   2177 			    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES),
   2178 			    NULL, NULL);
   2179 			mutex_exit(p->p_lock);
   2180 			if (error != 0) {
   2181 				/*
   2182 				 * Don't leak kauth retval if we're silently
   2183 				 * skipping this entry.
   2184 				 */
   2185 				error = 0;
   2186 				continue;
   2187 			}
   2188 
   2189 			/*
   2190 			 * Grab a hold on the process.
   2191 			 */
   2192 			if (!rw_tryenter(&p->p_reflock, RW_READER)) {
   2193 				continue;
   2194 			}
   2195 			mutex_exit(proc_lock);
   2196 
   2197 			fd = p->p_fd;
   2198 			mutex_enter(&fd->fd_lock);
   2199 			dt = fd->fd_dt;
   2200 			for (i = 0; i < dt->dt_nfiles; i++) {
   2201 				if ((ff = dt->dt_ff[i]) == NULL) {
   2202 					continue;
   2203 				}
   2204 				if ((fp = ff->ff_file) == NULL) {
   2205 					continue;
   2206 				}
   2207 
   2208 				if ((op == KERN_FILE_BYFILE) &&
   2209 				    (fp->f_marker == sysctl_file_marker)) {
   2210 					continue;
   2211 				}
   2212 				if (len >= elem_size && elem_count > 0) {
   2213 					mutex_enter(&fp->f_lock);
   2214 					fill_file(&kf, fp, ff, i, p->p_pid);
   2215 					mutex_exit(&fp->f_lock);
   2216 					mutex_exit(&fd->fd_lock);
   2217 					error = sysctl_copyout(l,
   2218 					    &kf, dp, out_size);
   2219 					mutex_enter(&fd->fd_lock);
   2220 					if (error)
   2221 						break;
   2222 					dp += elem_size;
   2223 					len -= elem_size;
   2224 				}
   2225 				if (op == KERN_FILE_BYFILE)
   2226 					fp->f_marker = sysctl_file_marker;
   2227 				needed += elem_size;
   2228 				if (elem_count > 0 && elem_count != INT_MAX)
   2229 					elem_count--;
   2230 			}
   2231 			mutex_exit(&fd->fd_lock);
   2232 
   2233 			/*
   2234 			 * Release reference to process.
   2235 			 */
   2236 			mutex_enter(proc_lock);
   2237 			rw_exit(&p->p_reflock);
   2238 		}
   2239 		if (op == KERN_FILE_BYFILE) {
   2240 			sysctl_file_marker++;
   2241 
   2242 			/* Reset all markers if wrapped. */
   2243 			if (sysctl_file_marker == 0) {
   2244 				sysctl_file_marker_reset();
   2245 				sysctl_file_marker++;
   2246 			}
   2247 		}
   2248 		mutex_exit(proc_lock);
   2249 		if (op == KERN_FILE_BYFILE)
   2250 			mutex_exit(&sysctl_file_marker_lock);
   2251 		sysctl_relock();
   2252 		break;
   2253 	default:
   2254 		return EINVAL;
   2255 	}
   2256 
   2257 	if (oldp == NULL)
   2258 		needed += KERN_FILESLOP * elem_size;
   2259 	*oldlenp = needed;
   2260 
   2261 	return error;
   2262 }
   2263 
   2264 static void
   2265 fill_file(struct kinfo_file *kp, const file_t *fp, const fdfile_t *ff,
   2266 	  int i, pid_t pid)
   2267 {
   2268 
   2269 	memset(kp, 0, sizeof(*kp));
   2270 
   2271 	kp->ki_fileaddr =	PTRTOUINT64(fp);
   2272 	kp->ki_flag =		fp->f_flag;
   2273 	kp->ki_iflags =		0;
   2274 	kp->ki_ftype =		fp->f_type;
   2275 	kp->ki_count =		fp->f_count;
   2276 	kp->ki_msgcount =	fp->f_msgcount;
   2277 	kp->ki_fucred =		PTRTOUINT64(fp->f_cred);
   2278 	kp->ki_fuid =		kauth_cred_geteuid(fp->f_cred);
   2279 	kp->ki_fgid =		kauth_cred_getegid(fp->f_cred);
   2280 	kp->ki_fops =		PTRTOUINT64(fp->f_ops);
   2281 	kp->ki_foffset =	fp->f_offset;
   2282 	kp->ki_fdata =		PTRTOUINT64(fp->f_data);
   2283 
   2284 	/* vnode information to glue this file to something */
   2285 	if (fp->f_type == DTYPE_VNODE) {
   2286 		struct vnode *vp = (struct vnode *)fp->f_data;
   2287 
   2288 		kp->ki_vun =	PTRTOUINT64(vp->v_un.vu_socket);
   2289 		kp->ki_vsize =	vp->v_size;
   2290 		kp->ki_vtype =	vp->v_type;
   2291 		kp->ki_vtag =	vp->v_tag;
   2292 		kp->ki_vdata =	PTRTOUINT64(vp->v_data);
   2293 	}
   2294 
   2295 	/* process information when retrieved via KERN_FILE_BYPID */
   2296 	if (ff != NULL) {
   2297 		kp->ki_pid =		pid;
   2298 		kp->ki_fd =		i;
   2299 		kp->ki_ofileflags =	ff->ff_exclose;
   2300 		kp->ki_usecount =	ff->ff_refcnt;
   2301 	}
   2302 }
   2303