Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.217
      1 /*	$NetBSD: kern_descrip.c,v 1.217 2011/09/25 13:40:37 chs 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.217 2011/09/25 13:40:37 chs 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 = true;
    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 = false;
    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, int flags)
    733 {
    734 	filedesc_t *fdp = curlwp->l_fd;
    735 	fdfile_t *ff;
    736 	fdtab_t *dt;
    737 
    738 	if (flags & ~(O_CLOEXEC|O_NONBLOCK))
    739 		return EINVAL;
    740 	/*
    741 	 * Ensure there are enough slots in the descriptor table,
    742 	 * and allocate an fdfile_t up front in case we need it.
    743 	 */
    744 	while (new >= fdp->fd_dt->dt_nfiles) {
    745 		fd_tryexpand(curproc);
    746 	}
    747 	ff = pool_cache_get(fdfile_cache, PR_WAITOK);
    748 
    749 	/*
    750 	 * If there is already a file open, close it.  If the file is
    751 	 * half open, wait for it to be constructed before closing it.
    752 	 * XXX Potential for deadlock here?
    753 	 */
    754 	mutex_enter(&fdp->fd_lock);
    755 	while (fd_isused(fdp, new)) {
    756 		mutex_exit(&fdp->fd_lock);
    757 		if (fd_getfile(new) != NULL) {
    758 			(void)fd_close(new);
    759 		} else {
    760 			/*
    761 			 * Crummy, but unlikely to happen.
    762 			 * Can occur if we interrupt another
    763 			 * thread while it is opening a file.
    764 			 */
    765 			kpause("dup2", false, 1, NULL);
    766 		}
    767 		mutex_enter(&fdp->fd_lock);
    768 	}
    769 	dt = fdp->fd_dt;
    770 	if (dt->dt_ff[new] == NULL) {
    771 		KASSERT(new >= NDFDFILE);
    772 		dt->dt_ff[new] = ff;
    773 		ff = NULL;
    774 	}
    775 	fd_used(fdp, new);
    776 	mutex_exit(&fdp->fd_lock);
    777 
    778 	dt->dt_ff[new]->ff_exclose = (flags & O_CLOEXEC) != 0;
    779 	fp->f_flag |= flags & FNONBLOCK;
    780 	/* Slot is now allocated.  Insert copy of the file. */
    781 	fd_affix(curproc, fp, new);
    782 	if (ff != NULL) {
    783 		pool_cache_put(fdfile_cache, ff);
    784 	}
    785 	return 0;
    786 }
    787 
    788 /*
    789  * Drop reference to a file structure.
    790  */
    791 int
    792 closef(file_t *fp)
    793 {
    794 	struct flock lf;
    795 	int error;
    796 
    797 	/*
    798 	 * Drop reference.  If referenced elsewhere it's still open
    799 	 * and we have nothing more to do.
    800 	 */
    801 	mutex_enter(&fp->f_lock);
    802 	KASSERT(fp->f_count > 0);
    803 	if (--fp->f_count > 0) {
    804 		mutex_exit(&fp->f_lock);
    805 		return 0;
    806 	}
    807 	KASSERT(fp->f_count == 0);
    808 	mutex_exit(&fp->f_lock);
    809 
    810 	/* We held the last reference - release locks, close and free. */
    811 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
    812 		lf.l_whence = SEEK_SET;
    813 		lf.l_start = 0;
    814 		lf.l_len = 0;
    815 		lf.l_type = F_UNLCK;
    816 		(void)VOP_ADVLOCK(fp->f_data, fp, F_UNLCK, &lf, F_FLOCK);
    817 	}
    818 	if (fp->f_ops != NULL) {
    819 		error = (*fp->f_ops->fo_close)(fp);
    820 	} else {
    821 		error = 0;
    822 	}
    823 	KASSERT(fp->f_count == 0);
    824 	KASSERT(fp->f_cred != NULL);
    825 	pool_cache_put(file_cache, fp);
    826 
    827 	return error;
    828 }
    829 
    830 /*
    831  * Allocate a file descriptor for the process.
    832  */
    833 int
    834 fd_alloc(proc_t *p, int want, int *result)
    835 {
    836 	filedesc_t *fdp = p->p_fd;
    837 	int i, lim, last, error;
    838 	u_int off, new;
    839 	fdtab_t *dt;
    840 
    841 	KASSERT(p == curproc || p == &proc0);
    842 
    843 	/*
    844 	 * Search for a free descriptor starting at the higher
    845 	 * of want or fd_freefile.
    846 	 */
    847 	mutex_enter(&fdp->fd_lock);
    848 	fd_checkmaps(fdp);
    849 	dt = fdp->fd_dt;
    850 	KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
    851 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    852 	last = min(dt->dt_nfiles, lim);
    853 	for (;;) {
    854 		if ((i = want) < fdp->fd_freefile)
    855 			i = fdp->fd_freefile;
    856 		off = i >> NDENTRYSHIFT;
    857 		new = fd_next_zero(fdp, fdp->fd_himap, off,
    858 		    (last + NDENTRIES - 1) >> NDENTRYSHIFT);
    859 		if (new == -1)
    860 			break;
    861 		i = fd_next_zero(fdp, &fdp->fd_lomap[new],
    862 		    new > off ? 0 : i & NDENTRYMASK, NDENTRIES);
    863 		if (i == -1) {
    864 			/*
    865 			 * Free file descriptor in this block was
    866 			 * below want, try again with higher want.
    867 			 */
    868 			want = (new + 1) << NDENTRYSHIFT;
    869 			continue;
    870 		}
    871 		i += (new << NDENTRYSHIFT);
    872 		if (i >= last) {
    873 			break;
    874 		}
    875 		if (dt->dt_ff[i] == NULL) {
    876 			KASSERT(i >= NDFDFILE);
    877 			dt->dt_ff[i] = pool_cache_get(fdfile_cache, PR_WAITOK);
    878 		}
    879 		KASSERT(dt->dt_ff[i]->ff_file == NULL);
    880 		fd_used(fdp, i);
    881 		if (want <= fdp->fd_freefile) {
    882 			fdp->fd_freefile = i;
    883 		}
    884 		*result = i;
    885 		KASSERT(i >= NDFDFILE ||
    886 		    dt->dt_ff[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
    887 		fd_checkmaps(fdp);
    888 		mutex_exit(&fdp->fd_lock);
    889 		return 0;
    890 	}
    891 
    892 	/* No space in current array.  Let the caller expand and retry. */
    893 	error = (dt->dt_nfiles >= lim) ? EMFILE : ENOSPC;
    894 	mutex_exit(&fdp->fd_lock);
    895 	return error;
    896 }
    897 
    898 /*
    899  * Allocate memory for a descriptor table.
    900  */
    901 static fdtab_t *
    902 fd_dtab_alloc(int n)
    903 {
    904 	fdtab_t *dt;
    905 	size_t sz;
    906 
    907 	KASSERT(n > NDFILE);
    908 
    909 	sz = sizeof(*dt) + (n - NDFILE) * sizeof(dt->dt_ff[0]);
    910 	dt = kmem_alloc(sz, KM_SLEEP);
    911 #ifdef DIAGNOSTIC
    912 	memset(dt, 0xff, sz);
    913 #endif
    914 	dt->dt_nfiles = n;
    915 	dt->dt_link = NULL;
    916 	return dt;
    917 }
    918 
    919 /*
    920  * Free a descriptor table, and all tables linked for deferred free.
    921  */
    922 static void
    923 fd_dtab_free(fdtab_t *dt)
    924 {
    925 	fdtab_t *next;
    926 	size_t sz;
    927 
    928 	do {
    929 		next = dt->dt_link;
    930 		KASSERT(dt->dt_nfiles > NDFILE);
    931 		sz = sizeof(*dt) +
    932 		    (dt->dt_nfiles - NDFILE) * sizeof(dt->dt_ff[0]);
    933 #ifdef DIAGNOSTIC
    934 		memset(dt, 0xff, sz);
    935 #endif
    936 		kmem_free(dt, sz);
    937 		dt = next;
    938 	} while (dt != NULL);
    939 }
    940 
    941 /*
    942  * Allocate descriptor bitmap.
    943  */
    944 static void
    945 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
    946 {
    947 	uint8_t *ptr;
    948 	size_t szlo, szhi;
    949 
    950 	KASSERT(n > NDENTRIES);
    951 
    952 	szlo = NDLOSLOTS(n) * sizeof(uint32_t);
    953 	szhi = NDHISLOTS(n) * sizeof(uint32_t);
    954 	ptr = kmem_alloc(szlo + szhi, KM_SLEEP);
    955 	*lo = (uint32_t *)ptr;
    956 	*hi = (uint32_t *)(ptr + szlo);
    957 }
    958 
    959 /*
    960  * Free descriptor bitmap.
    961  */
    962 static void
    963 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
    964 {
    965 	size_t szlo, szhi;
    966 
    967 	KASSERT(n > NDENTRIES);
    968 
    969 	szlo = NDLOSLOTS(n) * sizeof(uint32_t);
    970 	szhi = NDHISLOTS(n) * sizeof(uint32_t);
    971 	KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo));
    972 	kmem_free(lo, szlo + szhi);
    973 }
    974 
    975 /*
    976  * Expand a process' descriptor table.
    977  */
    978 void
    979 fd_tryexpand(proc_t *p)
    980 {
    981 	filedesc_t *fdp;
    982 	int i, numfiles, oldnfiles;
    983 	fdtab_t *newdt, *dt;
    984 	uint32_t *newhimap, *newlomap;
    985 
    986 	KASSERT(p == curproc || p == &proc0);
    987 
    988 	fdp = p->p_fd;
    989 	newhimap = NULL;
    990 	newlomap = NULL;
    991 	oldnfiles = fdp->fd_dt->dt_nfiles;
    992 
    993 	if (oldnfiles < NDEXTENT)
    994 		numfiles = NDEXTENT;
    995 	else
    996 		numfiles = 2 * oldnfiles;
    997 
    998 	newdt = fd_dtab_alloc(numfiles);
    999 	if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
   1000 		fd_map_alloc(numfiles, &newlomap, &newhimap);
   1001 	}
   1002 
   1003 	mutex_enter(&fdp->fd_lock);
   1004 	dt = fdp->fd_dt;
   1005 	KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
   1006 	if (dt->dt_nfiles != oldnfiles) {
   1007 		/* fdp changed; caller must retry */
   1008 		mutex_exit(&fdp->fd_lock);
   1009 		fd_dtab_free(newdt);
   1010 		if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
   1011 			fd_map_free(numfiles, newlomap, newhimap);
   1012 		}
   1013 		return;
   1014 	}
   1015 
   1016 	/* Copy the existing descriptor table and zero the new portion. */
   1017 	i = sizeof(fdfile_t *) * oldnfiles;
   1018 	memcpy(newdt->dt_ff, dt->dt_ff, i);
   1019 	memset((uint8_t *)newdt->dt_ff + i, 0,
   1020 	    numfiles * sizeof(fdfile_t *) - i);
   1021 
   1022 	/*
   1023 	 * Link old descriptor array into list to be discarded.  We defer
   1024 	 * freeing until the last reference to the descriptor table goes
   1025 	 * away (usually process exit).  This allows us to do lockless
   1026 	 * lookups in fd_getfile().
   1027 	 */
   1028 	if (oldnfiles > NDFILE) {
   1029 		if (fdp->fd_refcnt > 1) {
   1030 			newdt->dt_link = dt;
   1031 		} else {
   1032 			fd_dtab_free(dt);
   1033 		}
   1034 	}
   1035 
   1036 	if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
   1037 		i = NDHISLOTS(oldnfiles) * sizeof(uint32_t);
   1038 		memcpy(newhimap, fdp->fd_himap, i);
   1039 		memset((uint8_t *)newhimap + i, 0,
   1040 		    NDHISLOTS(numfiles) * sizeof(uint32_t) - i);
   1041 
   1042 		i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t);
   1043 		memcpy(newlomap, fdp->fd_lomap, i);
   1044 		memset((uint8_t *)newlomap + i, 0,
   1045 		    NDLOSLOTS(numfiles) * sizeof(uint32_t) - i);
   1046 
   1047 		if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
   1048 			fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
   1049 		}
   1050 		fdp->fd_himap = newhimap;
   1051 		fdp->fd_lomap = newlomap;
   1052 	}
   1053 
   1054 	/*
   1055 	 * All other modifications must become globally visible before
   1056 	 * the change to fd_dt.  See fd_getfile().
   1057 	 */
   1058 	membar_producer();
   1059 	fdp->fd_dt = newdt;
   1060 	KASSERT(newdt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
   1061 	fd_checkmaps(fdp);
   1062 	mutex_exit(&fdp->fd_lock);
   1063 }
   1064 
   1065 /*
   1066  * Create a new open file structure and allocate a file descriptor
   1067  * for the current process.
   1068  */
   1069 int
   1070 fd_allocfile(file_t **resultfp, int *resultfd)
   1071 {
   1072 	proc_t *p = curproc;
   1073 	kauth_cred_t cred;
   1074 	file_t *fp;
   1075 	int error;
   1076 
   1077 	while ((error = fd_alloc(p, 0, resultfd)) != 0) {
   1078 		if (error != ENOSPC) {
   1079 			return error;
   1080 		}
   1081 		fd_tryexpand(p);
   1082 	}
   1083 
   1084 	fp = pool_cache_get(file_cache, PR_WAITOK);
   1085 	if (fp == NULL) {
   1086 		fd_abort(p, NULL, *resultfd);
   1087 		return ENFILE;
   1088 	}
   1089 	KASSERT(fp->f_count == 0);
   1090 	KASSERT(fp->f_msgcount == 0);
   1091 	KASSERT(fp->f_unpcount == 0);
   1092 
   1093 	/* Replace cached credentials if not what we need. */
   1094 	cred = curlwp->l_cred;
   1095 	if (__predict_false(cred != fp->f_cred)) {
   1096 		kauth_cred_free(fp->f_cred);
   1097 		kauth_cred_hold(cred);
   1098 		fp->f_cred = cred;
   1099 	}
   1100 
   1101 	/*
   1102 	 * Don't allow recycled files to be scanned.
   1103 	 * See uipc_usrreq.c.
   1104 	 */
   1105 	if (__predict_false((fp->f_flag & FSCAN) != 0)) {
   1106 		mutex_enter(&fp->f_lock);
   1107 		atomic_and_uint(&fp->f_flag, ~FSCAN);
   1108 		mutex_exit(&fp->f_lock);
   1109 	}
   1110 
   1111 	fp->f_advice = 0;
   1112 	fp->f_offset = 0;
   1113 	*resultfp = fp;
   1114 
   1115 	return 0;
   1116 }
   1117 
   1118 /*
   1119  * Successful creation of a new descriptor: make visible to the process.
   1120  */
   1121 void
   1122 fd_affix(proc_t *p, file_t *fp, unsigned fd)
   1123 {
   1124 	fdfile_t *ff;
   1125 	filedesc_t *fdp;
   1126 
   1127 	KASSERT(p == curproc || p == &proc0);
   1128 
   1129 	/* Add a reference to the file structure. */
   1130 	mutex_enter(&fp->f_lock);
   1131 	fp->f_count++;
   1132 	mutex_exit(&fp->f_lock);
   1133 
   1134 	/*
   1135 	 * Insert the new file into the descriptor slot.
   1136 	 *
   1137 	 * The memory barriers provided by lock activity in this routine
   1138 	 * ensure that any updates to the file structure become globally
   1139 	 * visible before the file becomes visible to other LWPs in the
   1140 	 * current process.
   1141 	 */
   1142 	fdp = p->p_fd;
   1143 	ff = fdp->fd_dt->dt_ff[fd];
   1144 
   1145 	KASSERT(ff != NULL);
   1146 	KASSERT(ff->ff_file == NULL);
   1147 	KASSERT(ff->ff_allocated);
   1148 	KASSERT(fd_isused(fdp, fd));
   1149 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1150 
   1151 	/* No need to lock in order to make file initially visible. */
   1152 	ff->ff_file = fp;
   1153 }
   1154 
   1155 /*
   1156  * Abort creation of a new descriptor: free descriptor slot and file.
   1157  */
   1158 void
   1159 fd_abort(proc_t *p, file_t *fp, unsigned fd)
   1160 {
   1161 	filedesc_t *fdp;
   1162 	fdfile_t *ff;
   1163 
   1164 	KASSERT(p == curproc || p == &proc0);
   1165 
   1166 	fdp = p->p_fd;
   1167 	ff = fdp->fd_dt->dt_ff[fd];
   1168 
   1169 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1170 
   1171 	mutex_enter(&fdp->fd_lock);
   1172 	KASSERT(fd_isused(fdp, fd));
   1173 	fd_unused(fdp, fd);
   1174 	mutex_exit(&fdp->fd_lock);
   1175 
   1176 	if (fp != NULL) {
   1177 		KASSERT(fp->f_count == 0);
   1178 		KASSERT(fp->f_cred != NULL);
   1179 		pool_cache_put(file_cache, fp);
   1180 	}
   1181 }
   1182 
   1183 static int
   1184 file_ctor(void *arg, void *obj, int flags)
   1185 {
   1186 	file_t *fp = obj;
   1187 
   1188 	memset(fp, 0, sizeof(*fp));
   1189 
   1190 	mutex_enter(&filelist_lock);
   1191 	if (__predict_false(nfiles >= maxfiles)) {
   1192 		mutex_exit(&filelist_lock);
   1193 		tablefull("file", "increase kern.maxfiles or MAXFILES");
   1194 		return ENFILE;
   1195 	}
   1196 	nfiles++;
   1197 	LIST_INSERT_HEAD(&filehead, fp, f_list);
   1198 	mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
   1199 	fp->f_cred = curlwp->l_cred;
   1200 	kauth_cred_hold(fp->f_cred);
   1201 	mutex_exit(&filelist_lock);
   1202 
   1203 	return 0;
   1204 }
   1205 
   1206 static void
   1207 file_dtor(void *arg, void *obj)
   1208 {
   1209 	file_t *fp = obj;
   1210 
   1211 	mutex_enter(&filelist_lock);
   1212 	nfiles--;
   1213 	LIST_REMOVE(fp, f_list);
   1214 	mutex_exit(&filelist_lock);
   1215 
   1216 	kauth_cred_free(fp->f_cred);
   1217 	mutex_destroy(&fp->f_lock);
   1218 }
   1219 
   1220 static int
   1221 fdfile_ctor(void *arg, void *obj, int flags)
   1222 {
   1223 	fdfile_t *ff = obj;
   1224 
   1225 	memset(ff, 0, sizeof(*ff));
   1226 	cv_init(&ff->ff_closing, "fdclose");
   1227 
   1228 	return 0;
   1229 }
   1230 
   1231 static void
   1232 fdfile_dtor(void *arg, void *obj)
   1233 {
   1234 	fdfile_t *ff = obj;
   1235 
   1236 	cv_destroy(&ff->ff_closing);
   1237 }
   1238 
   1239 file_t *
   1240 fgetdummy(void)
   1241 {
   1242 	file_t *fp;
   1243 
   1244 	fp = kmem_zalloc(sizeof(*fp), KM_SLEEP);
   1245 	if (fp != NULL) {
   1246 		mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
   1247 	}
   1248 	return fp;
   1249 }
   1250 
   1251 void
   1252 fputdummy(file_t *fp)
   1253 {
   1254 
   1255 	mutex_destroy(&fp->f_lock);
   1256 	kmem_free(fp, sizeof(*fp));
   1257 }
   1258 
   1259 /*
   1260  * Create an initial filedesc structure.
   1261  */
   1262 filedesc_t *
   1263 fd_init(filedesc_t *fdp)
   1264 {
   1265 #ifdef DIAGNOSTIC
   1266 	unsigned fd;
   1267 #endif
   1268 
   1269 	if (__predict_true(fdp == NULL)) {
   1270 		fdp = pool_cache_get(filedesc_cache, PR_WAITOK);
   1271 	} else {
   1272 		KASSERT(fdp == &filedesc0);
   1273 		filedesc_ctor(NULL, fdp, PR_WAITOK);
   1274 	}
   1275 
   1276 #ifdef DIAGNOSTIC
   1277 	KASSERT(fdp->fd_lastfile == -1);
   1278 	KASSERT(fdp->fd_lastkqfile == -1);
   1279 	KASSERT(fdp->fd_knhash == NULL);
   1280 	KASSERT(fdp->fd_freefile == 0);
   1281 	KASSERT(fdp->fd_exclose == false);
   1282 	KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
   1283 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1284 	for (fd = 0; fd < NDFDFILE; fd++) {
   1285 		KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] ==
   1286 		    (fdfile_t *)fdp->fd_dfdfile[fd]);
   1287 	}
   1288 	for (fd = NDFDFILE; fd < NDFILE; fd++) {
   1289 		KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL);
   1290 	}
   1291 	KASSERT(fdp->fd_himap == fdp->fd_dhimap);
   1292 	KASSERT(fdp->fd_lomap == fdp->fd_dlomap);
   1293 #endif	/* DIAGNOSTIC */
   1294 
   1295 	fdp->fd_refcnt = 1;
   1296 	fd_checkmaps(fdp);
   1297 
   1298 	return fdp;
   1299 }
   1300 
   1301 /*
   1302  * Initialize a file descriptor table.
   1303  */
   1304 static int
   1305 filedesc_ctor(void *arg, void *obj, int flag)
   1306 {
   1307 	filedesc_t *fdp = obj;
   1308 	fdfile_t **ffp;
   1309 	int i;
   1310 
   1311 	memset(fdp, 0, sizeof(*fdp));
   1312 	mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE);
   1313 	fdp->fd_lastfile = -1;
   1314 	fdp->fd_lastkqfile = -1;
   1315 	fdp->fd_dt = &fdp->fd_dtbuiltin;
   1316 	fdp->fd_dtbuiltin.dt_nfiles = NDFILE;
   1317 	fdp->fd_himap = fdp->fd_dhimap;
   1318 	fdp->fd_lomap = fdp->fd_dlomap;
   1319 
   1320 	CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t));
   1321 	for (i = 0, ffp = fdp->fd_dt->dt_ff; i < NDFDFILE; i++, ffp++) {
   1322 		*ffp = (fdfile_t *)fdp->fd_dfdfile[i];
   1323 		(void)fdfile_ctor(NULL, fdp->fd_dfdfile[i], PR_WAITOK);
   1324 	}
   1325 
   1326 	return 0;
   1327 }
   1328 
   1329 static void
   1330 filedesc_dtor(void *arg, void *obj)
   1331 {
   1332 	filedesc_t *fdp = obj;
   1333 	int i;
   1334 
   1335 	for (i = 0; i < NDFDFILE; i++) {
   1336 		fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
   1337 	}
   1338 
   1339 	mutex_destroy(&fdp->fd_lock);
   1340 }
   1341 
   1342 /*
   1343  * Make p share curproc's filedesc structure.
   1344  */
   1345 void
   1346 fd_share(struct proc *p)
   1347 {
   1348 	filedesc_t *fdp;
   1349 
   1350 	fdp = curlwp->l_fd;
   1351 	p->p_fd = fdp;
   1352 	atomic_inc_uint(&fdp->fd_refcnt);
   1353 }
   1354 
   1355 /*
   1356  * Acquire a hold on a filedesc structure.
   1357  */
   1358 void
   1359 fd_hold(lwp_t *l)
   1360 {
   1361 	filedesc_t *fdp = l->l_fd;
   1362 
   1363 	atomic_inc_uint(&fdp->fd_refcnt);
   1364 }
   1365 
   1366 /*
   1367  * Copy a filedesc structure.
   1368  */
   1369 filedesc_t *
   1370 fd_copy(void)
   1371 {
   1372 	filedesc_t *newfdp, *fdp;
   1373 	fdfile_t *ff, **ffp, **nffp, *ff2;
   1374 	int i, j, numfiles, lastfile, newlast;
   1375 	file_t *fp;
   1376 	fdtab_t *newdt;
   1377 
   1378 	fdp = curproc->p_fd;
   1379 	newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
   1380 	newfdp->fd_refcnt = 1;
   1381 
   1382 #ifdef DIAGNOSTIC
   1383 	KASSERT(newfdp->fd_lastfile == -1);
   1384 	KASSERT(newfdp->fd_lastkqfile == -1);
   1385 	KASSERT(newfdp->fd_knhash == NULL);
   1386 	KASSERT(newfdp->fd_freefile == 0);
   1387 	KASSERT(newfdp->fd_exclose == false);
   1388 	KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
   1389 	KASSERT(newfdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1390 	for (i = 0; i < NDFDFILE; i++) {
   1391 		KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] ==
   1392 		    (fdfile_t *)&newfdp->fd_dfdfile[i]);
   1393 	}
   1394 	for (i = NDFDFILE; i < NDFILE; i++) {
   1395 		KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL);
   1396 	}
   1397 #endif	/* DIAGNOSTIC */
   1398 
   1399 	mutex_enter(&fdp->fd_lock);
   1400 	fd_checkmaps(fdp);
   1401 	numfiles = fdp->fd_dt->dt_nfiles;
   1402 	lastfile = fdp->fd_lastfile;
   1403 
   1404 	/*
   1405 	 * If the number of open files fits in the internal arrays
   1406 	 * of the open file structure, use them, otherwise allocate
   1407 	 * additional memory for the number of descriptors currently
   1408 	 * in use.
   1409 	 */
   1410 	if (lastfile < NDFILE) {
   1411 		i = NDFILE;
   1412 		newdt = newfdp->fd_dt;
   1413 		KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
   1414 	} else {
   1415 		/*
   1416 		 * Compute the smallest multiple of NDEXTENT needed
   1417 		 * for the file descriptors currently in use,
   1418 		 * allowing the table to shrink.
   1419 		 */
   1420 		i = numfiles;
   1421 		while (i >= 2 * NDEXTENT && i > lastfile * 2) {
   1422 			i /= 2;
   1423 		}
   1424 		KASSERT(i > NDFILE);
   1425 		newdt = fd_dtab_alloc(i);
   1426 		newfdp->fd_dt = newdt;
   1427 		memcpy(newdt->dt_ff, newfdp->fd_dtbuiltin.dt_ff,
   1428 		    NDFDFILE * sizeof(fdfile_t **));
   1429 		memset(newdt->dt_ff + NDFDFILE, 0,
   1430 		    (i - NDFDFILE) * sizeof(fdfile_t **));
   1431 	}
   1432 	if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
   1433 		newfdp->fd_himap = newfdp->fd_dhimap;
   1434 		newfdp->fd_lomap = newfdp->fd_dlomap;
   1435 	} else {
   1436 		fd_map_alloc(i, &newfdp->fd_lomap, &newfdp->fd_himap);
   1437 		KASSERT(i >= NDENTRIES * NDENTRIES);
   1438 		memset(newfdp->fd_himap, 0, NDHISLOTS(i)*sizeof(uint32_t));
   1439 		memset(newfdp->fd_lomap, 0, NDLOSLOTS(i)*sizeof(uint32_t));
   1440 	}
   1441 	newfdp->fd_freefile = fdp->fd_freefile;
   1442 	newfdp->fd_exclose = fdp->fd_exclose;
   1443 
   1444 	ffp = fdp->fd_dt->dt_ff;
   1445 	nffp = newdt->dt_ff;
   1446 	newlast = -1;
   1447 	for (i = 0; i <= (int)lastfile; i++, ffp++, nffp++) {
   1448 		KASSERT(i >= NDFDFILE ||
   1449 		    *nffp == (fdfile_t *)newfdp->fd_dfdfile[i]);
   1450 		ff = *ffp;
   1451 		if (ff == NULL || (fp = ff->ff_file) == NULL) {
   1452 			/* Descriptor unused, or descriptor half open. */
   1453 			KASSERT(!fd_isused(newfdp, i));
   1454 			continue;
   1455 		}
   1456 		if (__predict_false(fp->f_type == DTYPE_KQUEUE)) {
   1457 			/* kqueue descriptors cannot be copied. */
   1458 			if (i < newfdp->fd_freefile) {
   1459 				newfdp->fd_freefile = i;
   1460 			}
   1461 			continue;
   1462 		}
   1463 		/* It's active: add a reference to the file. */
   1464 		mutex_enter(&fp->f_lock);
   1465 		fp->f_count++;
   1466 		mutex_exit(&fp->f_lock);
   1467 
   1468 		/* Allocate an fdfile_t to represent it. */
   1469 		if (i >= NDFDFILE) {
   1470 			ff2 = pool_cache_get(fdfile_cache, PR_WAITOK);
   1471 			*nffp = ff2;
   1472 		} else {
   1473 			ff2 = newdt->dt_ff[i];
   1474 		}
   1475 		ff2->ff_file = fp;
   1476 		ff2->ff_exclose = ff->ff_exclose;
   1477 		ff2->ff_allocated = true;
   1478 
   1479 		/* Fix up bitmaps. */
   1480 		j = i >> NDENTRYSHIFT;
   1481 		KASSERT((newfdp->fd_lomap[j] & (1 << (i & NDENTRYMASK))) == 0);
   1482 		newfdp->fd_lomap[j] |= 1 << (i & NDENTRYMASK);
   1483 		if (__predict_false(newfdp->fd_lomap[j] == ~0)) {
   1484 			KASSERT((newfdp->fd_himap[j >> NDENTRYSHIFT] &
   1485 			    (1 << (j & NDENTRYMASK))) == 0);
   1486 			newfdp->fd_himap[j >> NDENTRYSHIFT] |=
   1487 			    1 << (j & NDENTRYMASK);
   1488 		}
   1489 		newlast = i;
   1490 	}
   1491 	KASSERT(newdt->dt_ff[0] == (fdfile_t *)newfdp->fd_dfdfile[0]);
   1492 	newfdp->fd_lastfile = newlast;
   1493 	fd_checkmaps(newfdp);
   1494 	mutex_exit(&fdp->fd_lock);
   1495 
   1496 	return newfdp;
   1497 }
   1498 
   1499 /*
   1500  * Release a filedesc structure.
   1501  */
   1502 void
   1503 fd_free(void)
   1504 {
   1505 	fdfile_t *ff;
   1506 	file_t *fp;
   1507 	int fd, nf;
   1508 	fdtab_t *dt;
   1509 	lwp_t * const l = curlwp;
   1510 	filedesc_t * const fdp = l->l_fd;
   1511 	const bool noadvlock = (l->l_proc->p_flag & PK_ADVLOCK) == 0;
   1512 
   1513 	KASSERT(fdp->fd_dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
   1514 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1515 	KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
   1516 
   1517 #ifndef __HAVE_ATOMIC_AS_MEMBAR
   1518 	membar_exit();
   1519 #endif
   1520 	if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
   1521 		return;
   1522 
   1523 	/*
   1524 	 * Close any files that the process holds open.
   1525 	 */
   1526 	dt = fdp->fd_dt;
   1527 	fd_checkmaps(fdp);
   1528 #ifdef DEBUG
   1529 	fdp->fd_refcnt = -1; /* see fd_checkmaps */
   1530 #endif
   1531 	for (fd = 0, nf = dt->dt_nfiles; fd < nf; fd++) {
   1532 		ff = dt->dt_ff[fd];
   1533 		KASSERT(fd >= NDFDFILE ||
   1534 		    ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1535 		if (ff == NULL)
   1536 			continue;
   1537 		if ((fp = ff->ff_file) != NULL) {
   1538 			/*
   1539 			 * Must use fd_close() here if there is
   1540 			 * a reference from kqueue or we might have posix
   1541 			 * advisory locks.
   1542 			 */
   1543 			if (__predict_true(ff->ff_refcnt == 0) &&
   1544 			    (noadvlock || fp->f_type != DTYPE_VNODE)) {
   1545 				ff->ff_file = NULL;
   1546 				ff->ff_exclose = false;
   1547 				ff->ff_allocated = false;
   1548 				closef(fp);
   1549 			} else {
   1550 				ff->ff_refcnt++;
   1551 				fd_close(fd);
   1552 			}
   1553 		}
   1554 		KASSERT(ff->ff_refcnt == 0);
   1555 		KASSERT(ff->ff_file == NULL);
   1556 		KASSERT(!ff->ff_exclose);
   1557 		KASSERT(!ff->ff_allocated);
   1558 		if (fd >= NDFDFILE) {
   1559 			pool_cache_put(fdfile_cache, ff);
   1560 			dt->dt_ff[fd] = NULL;
   1561 		}
   1562 	}
   1563 
   1564 	/*
   1565 	 * Clean out the descriptor table for the next user and return
   1566 	 * to the cache.
   1567 	 */
   1568 	if (__predict_false(dt != &fdp->fd_dtbuiltin)) {
   1569 		fd_dtab_free(fdp->fd_dt);
   1570 		/* Otherwise, done above. */
   1571 		memset(&fdp->fd_dtbuiltin.dt_ff[NDFDFILE], 0,
   1572 		    (NDFILE - NDFDFILE) * sizeof(fdp->fd_dtbuiltin.dt_ff[0]));
   1573 		fdp->fd_dt = &fdp->fd_dtbuiltin;
   1574 	}
   1575 	if (__predict_false(NDHISLOTS(nf) > NDHISLOTS(NDFILE))) {
   1576 		KASSERT(fdp->fd_himap != fdp->fd_dhimap);
   1577 		KASSERT(fdp->fd_lomap != fdp->fd_dlomap);
   1578 		fd_map_free(nf, fdp->fd_lomap, fdp->fd_himap);
   1579 	}
   1580 	if (__predict_false(fdp->fd_knhash != NULL)) {
   1581 		hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask);
   1582 		fdp->fd_knhash = NULL;
   1583 		fdp->fd_knhashmask = 0;
   1584 	} else {
   1585 		KASSERT(fdp->fd_knhashmask == 0);
   1586 	}
   1587 	fdp->fd_dt = &fdp->fd_dtbuiltin;
   1588 	fdp->fd_lastkqfile = -1;
   1589 	fdp->fd_lastfile = -1;
   1590 	fdp->fd_freefile = 0;
   1591 	fdp->fd_exclose = false;
   1592 	memset(&fdp->fd_startzero, 0, sizeof(*fdp) -
   1593 	    offsetof(filedesc_t, fd_startzero));
   1594 	fdp->fd_himap = fdp->fd_dhimap;
   1595 	fdp->fd_lomap = fdp->fd_dlomap;
   1596 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1597 	KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
   1598 	KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
   1599 #ifdef DEBUG
   1600 	fdp->fd_refcnt = 0; /* see fd_checkmaps */
   1601 #endif
   1602 	fd_checkmaps(fdp);
   1603 	pool_cache_put(filedesc_cache, fdp);
   1604 }
   1605 
   1606 /*
   1607  * File Descriptor pseudo-device driver (/dev/fd/).
   1608  *
   1609  * Opening minor device N dup()s the file (if any) connected to file
   1610  * descriptor N belonging to the calling process.  Note that this driver
   1611  * consists of only the ``open()'' routine, because all subsequent
   1612  * references to this file will be direct to the other driver.
   1613  */
   1614 static int
   1615 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
   1616 {
   1617 
   1618 	/*
   1619 	 * XXX Kludge: set dupfd to contain the value of the
   1620 	 * the file descriptor being sought for duplication. The error
   1621 	 * return ensures that the vnode for this device will be released
   1622 	 * by vn_open. Open will detect this special error and take the
   1623 	 * actions in fd_dupopen below. Other callers of vn_open or VOP_OPEN
   1624 	 * will simply report the error.
   1625 	 */
   1626 	l->l_dupfd = minor(dev);	/* XXX */
   1627 	return EDUPFD;
   1628 }
   1629 
   1630 /*
   1631  * Duplicate the specified descriptor to a free descriptor.
   1632  */
   1633 int
   1634 fd_dupopen(int old, int *new, int mode, int error)
   1635 {
   1636 	filedesc_t *fdp;
   1637 	fdfile_t *ff;
   1638 	file_t *fp;
   1639 	fdtab_t *dt;
   1640 
   1641 	if ((fp = fd_getfile(old)) == NULL) {
   1642 		return EBADF;
   1643 	}
   1644 	fdp = curlwp->l_fd;
   1645 	dt = fdp->fd_dt;
   1646 	ff = dt->dt_ff[old];
   1647 
   1648 	/*
   1649 	 * There are two cases of interest here.
   1650 	 *
   1651 	 * For EDUPFD simply dup (old) to file descriptor
   1652 	 * (new) and return.
   1653 	 *
   1654 	 * For EMOVEFD steal away the file structure from (old) and
   1655 	 * store it in (new).  (old) is effectively closed by
   1656 	 * this operation.
   1657 	 *
   1658 	 * Any other error code is just returned.
   1659 	 */
   1660 	switch (error) {
   1661 	case EDUPFD:
   1662 		/*
   1663 		 * Check that the mode the file is being opened for is a
   1664 		 * subset of the mode of the existing descriptor.
   1665 		 */
   1666 		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
   1667 			error = EACCES;
   1668 			break;
   1669 		}
   1670 
   1671 		/* Copy it. */
   1672 		error = fd_dup(fp, 0, new, ff->ff_exclose);
   1673 		break;
   1674 
   1675 	case EMOVEFD:
   1676 		/* Copy it. */
   1677 		error = fd_dup(fp, 0, new, ff->ff_exclose);
   1678 		if (error != 0) {
   1679 			break;
   1680 		}
   1681 
   1682 		/* Steal away the file pointer from 'old'. */
   1683 		(void)fd_close(old);
   1684 		return 0;
   1685 	}
   1686 
   1687 	fd_putfile(old);
   1688 	return error;
   1689 }
   1690 
   1691 /*
   1692  * Close open files on exec.
   1693  */
   1694 void
   1695 fd_closeexec(void)
   1696 {
   1697 	proc_t *p;
   1698 	filedesc_t *fdp;
   1699 	fdfile_t *ff;
   1700 	lwp_t *l;
   1701 	fdtab_t *dt;
   1702 	int fd;
   1703 
   1704 	l = curlwp;
   1705 	p = l->l_proc;
   1706 	fdp = p->p_fd;
   1707 
   1708 	if (fdp->fd_refcnt > 1) {
   1709 		fdp = fd_copy();
   1710 		fd_free();
   1711 		p->p_fd = fdp;
   1712 		l->l_fd = fdp;
   1713 	}
   1714 	if (!fdp->fd_exclose) {
   1715 		return;
   1716 	}
   1717 	fdp->fd_exclose = false;
   1718 	dt = fdp->fd_dt;
   1719 
   1720 	for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
   1721 		if ((ff = dt->dt_ff[fd]) == NULL) {
   1722 			KASSERT(fd >= NDFDFILE);
   1723 			continue;
   1724 		}
   1725 		KASSERT(fd >= NDFDFILE ||
   1726 		    ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1727 		if (ff->ff_file == NULL)
   1728 			continue;
   1729 		if (ff->ff_exclose) {
   1730 			/*
   1731 			 * We need a reference to close the file.
   1732 			 * No other threads can see the fdfile_t at
   1733 			 * this point, so don't bother locking.
   1734 			 */
   1735 			KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
   1736 			ff->ff_refcnt++;
   1737 			fd_close(fd);
   1738 		}
   1739 	}
   1740 }
   1741 
   1742 /*
   1743  * Sets descriptor owner. If the owner is a process, 'pgid'
   1744  * is set to positive value, process ID. If the owner is process group,
   1745  * 'pgid' is set to -pg_id.
   1746  */
   1747 int
   1748 fsetown(pid_t *pgid, u_long cmd, const void *data)
   1749 {
   1750 	pid_t id = *(const pid_t *)data;
   1751 	int error;
   1752 
   1753 	switch (cmd) {
   1754 	case TIOCSPGRP:
   1755 		if (id < 0)
   1756 			return EINVAL;
   1757 		id = -id;
   1758 		break;
   1759 	default:
   1760 		break;
   1761 	}
   1762 	if (id > 0) {
   1763 		mutex_enter(proc_lock);
   1764 		error = proc_find(id) ? 0 : ESRCH;
   1765 		mutex_exit(proc_lock);
   1766 	} else if (id < 0) {
   1767 		error = pgid_in_session(curproc, -id);
   1768 	} else {
   1769 		error = 0;
   1770 	}
   1771 	if (!error) {
   1772 		*pgid = id;
   1773 	}
   1774 	return error;
   1775 }
   1776 
   1777 void
   1778 fd_set_exclose(struct lwp *l, int fd, bool exclose)
   1779 {
   1780 	filedesc_t *fdp = l->l_fd;
   1781 	fdfile_t *ff = fdp->fd_dt->dt_ff[fd];
   1782 
   1783 	ff->ff_exclose = exclose;
   1784 	if (exclose)
   1785 		fdp->fd_exclose = true;
   1786 }
   1787 
   1788 /*
   1789  * Return descriptor owner information. If the value is positive,
   1790  * it's process ID. If it's negative, it's process group ID and
   1791  * needs the sign removed before use.
   1792  */
   1793 int
   1794 fgetown(pid_t pgid, u_long cmd, void *data)
   1795 {
   1796 
   1797 	switch (cmd) {
   1798 	case TIOCGPGRP:
   1799 		*(int *)data = -pgid;
   1800 		break;
   1801 	default:
   1802 		*(int *)data = pgid;
   1803 		break;
   1804 	}
   1805 	return 0;
   1806 }
   1807 
   1808 /*
   1809  * Send signal to descriptor owner, either process or process group.
   1810  */
   1811 void
   1812 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
   1813 {
   1814 	ksiginfo_t ksi;
   1815 
   1816 	KASSERT(!cpu_intr_p());
   1817 
   1818 	if (pgid == 0) {
   1819 		return;
   1820 	}
   1821 
   1822 	KSI_INIT(&ksi);
   1823 	ksi.ksi_signo = signo;
   1824 	ksi.ksi_code = code;
   1825 	ksi.ksi_band = band;
   1826 
   1827 	mutex_enter(proc_lock);
   1828 	if (pgid > 0) {
   1829 		struct proc *p1;
   1830 
   1831 		p1 = proc_find(pgid);
   1832 		if (p1 != NULL) {
   1833 			kpsignal(p1, &ksi, fdescdata);
   1834 		}
   1835 	} else {
   1836 		struct pgrp *pgrp;
   1837 
   1838 		KASSERT(pgid < 0);
   1839 		pgrp = pgrp_find(-pgid);
   1840 		if (pgrp != NULL) {
   1841 			kpgsignal(pgrp, &ksi, fdescdata, 0);
   1842 		}
   1843 	}
   1844 	mutex_exit(proc_lock);
   1845 }
   1846 
   1847 int
   1848 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
   1849 	 void *data)
   1850 {
   1851 
   1852 	fp->f_flag = flag;
   1853 	fp->f_type = DTYPE_MISC;
   1854 	fp->f_ops = fops;
   1855 	fp->f_data = data;
   1856 	curlwp->l_dupfd = fd;
   1857 	fd_affix(curproc, fp, fd);
   1858 
   1859 	return EMOVEFD;
   1860 }
   1861 
   1862 int
   1863 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
   1864 {
   1865 
   1866 	if (cmd == F_SETFL)
   1867 		return 0;
   1868 
   1869 	return EOPNOTSUPP;
   1870 }
   1871 
   1872 int
   1873 fnullop_poll(file_t *fp, int which)
   1874 {
   1875 
   1876 	return 0;
   1877 }
   1878 
   1879 int
   1880 fnullop_kqfilter(file_t *fp, struct knote *kn)
   1881 {
   1882 
   1883 	return 0;
   1884 }
   1885 
   1886 void
   1887 fnullop_restart(file_t *fp)
   1888 {
   1889 
   1890 }
   1891 
   1892 int
   1893 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
   1894 	    kauth_cred_t cred, int flags)
   1895 {
   1896 
   1897 	return EOPNOTSUPP;
   1898 }
   1899 
   1900 int
   1901 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
   1902 	     kauth_cred_t cred, int flags)
   1903 {
   1904 
   1905 	return EOPNOTSUPP;
   1906 }
   1907 
   1908 int
   1909 fbadop_ioctl(file_t *fp, u_long com, void *data)
   1910 {
   1911 
   1912 	return EOPNOTSUPP;
   1913 }
   1914 
   1915 int
   1916 fbadop_stat(file_t *fp, struct stat *sb)
   1917 {
   1918 
   1919 	return EOPNOTSUPP;
   1920 }
   1921 
   1922 int
   1923 fbadop_close(file_t *fp)
   1924 {
   1925 
   1926 	return EOPNOTSUPP;
   1927 }
   1928 
   1929 /*
   1930  * sysctl routines pertaining to file descriptors
   1931  */
   1932 
   1933 /* Initialized in sysctl_init() for now... */
   1934 extern kmutex_t sysctl_file_marker_lock;
   1935 static u_int sysctl_file_marker = 1;
   1936 
   1937 /*
   1938  * Expects to be called with proc_lock and sysctl_file_marker_lock locked.
   1939  */
   1940 static void
   1941 sysctl_file_marker_reset(void)
   1942 {
   1943 	struct proc *p;
   1944 
   1945 	PROCLIST_FOREACH(p, &allproc) {
   1946 		struct filedesc *fd = p->p_fd;
   1947 		fdtab_t *dt;
   1948 		u_int i;
   1949 
   1950 		mutex_enter(&fd->fd_lock);
   1951 		dt = fd->fd_dt;
   1952 		for (i = 0; i < dt->dt_nfiles; i++) {
   1953 			struct file *fp;
   1954 			fdfile_t *ff;
   1955 
   1956 			if ((ff = dt->dt_ff[i]) == NULL) {
   1957 				continue;
   1958 			}
   1959 			if ((fp = ff->ff_file) == NULL) {
   1960 				continue;
   1961 			}
   1962 			fp->f_marker = 0;
   1963 		}
   1964 		mutex_exit(&fd->fd_lock);
   1965 	}
   1966 }
   1967 
   1968 /*
   1969  * sysctl helper routine for kern.file pseudo-subtree.
   1970  */
   1971 static int
   1972 sysctl_kern_file(SYSCTLFN_ARGS)
   1973 {
   1974 	int error;
   1975 	size_t buflen;
   1976 	struct file *fp, fbuf;
   1977 	char *start, *where;
   1978 	struct proc *p;
   1979 
   1980 	start = where = oldp;
   1981 	buflen = *oldlenp;
   1982 
   1983 	if (where == NULL) {
   1984 		/*
   1985 		 * overestimate by 10 files
   1986 		 */
   1987 		*oldlenp = sizeof(filehead) + (nfiles + 10) *
   1988 		    sizeof(struct file);
   1989 		return 0;
   1990 	}
   1991 
   1992 	/*
   1993 	 * first sysctl_copyout filehead
   1994 	 */
   1995 	if (buflen < sizeof(filehead)) {
   1996 		*oldlenp = 0;
   1997 		return 0;
   1998 	}
   1999 	sysctl_unlock();
   2000 	error = sysctl_copyout(l, &filehead, where, sizeof(filehead));
   2001 	if (error) {
   2002 		sysctl_relock();
   2003 		return error;
   2004 	}
   2005 	buflen -= sizeof(filehead);
   2006 	where += sizeof(filehead);
   2007 
   2008 	/*
   2009 	 * followed by an array of file structures
   2010 	 */
   2011 	mutex_enter(&sysctl_file_marker_lock);
   2012 	mutex_enter(proc_lock);
   2013 	PROCLIST_FOREACH(p, &allproc) {
   2014 		struct filedesc *fd;
   2015 		fdtab_t *dt;
   2016 		u_int i;
   2017 
   2018 		if (p->p_stat == SIDL) {
   2019 			/* skip embryonic processes */
   2020 			continue;
   2021 		}
   2022 		mutex_enter(p->p_lock);
   2023 		error = kauth_authorize_process(l->l_cred,
   2024 		    KAUTH_PROCESS_CANSEE, p,
   2025 		    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES),
   2026 		    NULL, NULL);
   2027 		mutex_exit(p->p_lock);
   2028 		if (error != 0) {
   2029 			/*
   2030 			 * Don't leak kauth retval if we're silently
   2031 			 * skipping this entry.
   2032 			 */
   2033 			error = 0;
   2034 			continue;
   2035 		}
   2036 
   2037 		/*
   2038 		 * Grab a hold on the process.
   2039 		 */
   2040 		if (!rw_tryenter(&p->p_reflock, RW_READER)) {
   2041 			continue;
   2042 		}
   2043 		mutex_exit(proc_lock);
   2044 
   2045 		fd = p->p_fd;
   2046 		mutex_enter(&fd->fd_lock);
   2047 		dt = fd->fd_dt;
   2048 		for (i = 0; i < dt->dt_nfiles; i++) {
   2049 			fdfile_t *ff;
   2050 
   2051 			if ((ff = dt->dt_ff[i]) == NULL) {
   2052 				continue;
   2053 			}
   2054 			if ((fp = ff->ff_file) == NULL) {
   2055 				continue;
   2056 			}
   2057 
   2058 			mutex_enter(&fp->f_lock);
   2059 
   2060 			if ((fp->f_count == 0) ||
   2061 			    (fp->f_marker == sysctl_file_marker)) {
   2062 				mutex_exit(&fp->f_lock);
   2063 				continue;
   2064 			}
   2065 
   2066 			/* Check that we have enough space. */
   2067 			if (buflen < sizeof(struct file)) {
   2068 				*oldlenp = where - start;
   2069 				mutex_exit(&fp->f_lock);
   2070 				error = ENOMEM;
   2071 				break;
   2072 			}
   2073 
   2074 			memcpy(&fbuf, fp, sizeof(fbuf));
   2075 			mutex_exit(&fp->f_lock);
   2076 			error = sysctl_copyout(l, &fbuf, where, sizeof(fbuf));
   2077 			if (error) {
   2078 				break;
   2079 			}
   2080 			buflen -= sizeof(struct file);
   2081 			where += sizeof(struct file);
   2082 
   2083 			fp->f_marker = sysctl_file_marker;
   2084 		}
   2085 		mutex_exit(&fd->fd_lock);
   2086 
   2087 		/*
   2088 		 * Release reference to process.
   2089 		 */
   2090 		mutex_enter(proc_lock);
   2091 		rw_exit(&p->p_reflock);
   2092 
   2093 		if (error)
   2094 			break;
   2095 	}
   2096 
   2097 	sysctl_file_marker++;
   2098 	/* Reset all markers if wrapped. */
   2099 	if (sysctl_file_marker == 0) {
   2100 		sysctl_file_marker_reset();
   2101 		sysctl_file_marker++;
   2102 	}
   2103 
   2104 	mutex_exit(proc_lock);
   2105 	mutex_exit(&sysctl_file_marker_lock);
   2106 
   2107 	*oldlenp = where - start;
   2108 	sysctl_relock();
   2109 	return error;
   2110 }
   2111 
   2112 /*
   2113  * sysctl helper function for kern.file2
   2114  */
   2115 static int
   2116 sysctl_kern_file2(SYSCTLFN_ARGS)
   2117 {
   2118 	struct proc *p;
   2119 	struct file *fp;
   2120 	struct filedesc *fd;
   2121 	struct kinfo_file kf;
   2122 	char *dp;
   2123 	u_int i, op;
   2124 	size_t len, needed, elem_size, out_size;
   2125 	int error, arg, elem_count;
   2126 	fdfile_t *ff;
   2127 	fdtab_t *dt;
   2128 
   2129 	if (namelen == 1 && name[0] == CTL_QUERY)
   2130 		return sysctl_query(SYSCTLFN_CALL(rnode));
   2131 
   2132 	if (namelen != 4)
   2133 		return EINVAL;
   2134 
   2135 	error = 0;
   2136 	dp = oldp;
   2137 	len = (oldp != NULL) ? *oldlenp : 0;
   2138 	op = name[0];
   2139 	arg = name[1];
   2140 	elem_size = name[2];
   2141 	elem_count = name[3];
   2142 	out_size = MIN(sizeof(kf), elem_size);
   2143 	needed = 0;
   2144 
   2145 	if (elem_size < 1 || elem_count < 0)
   2146 		return EINVAL;
   2147 
   2148 	switch (op) {
   2149 	case KERN_FILE_BYFILE:
   2150 	case KERN_FILE_BYPID:
   2151 		/*
   2152 		 * We're traversing the process list in both cases; the BYFILE
   2153 		 * case does additional work of keeping track of files already
   2154 		 * looked at.
   2155 		 */
   2156 
   2157 		/* doesn't use arg so it must be zero */
   2158 		if ((op == KERN_FILE_BYFILE) && (arg != 0))
   2159 			return EINVAL;
   2160 
   2161 		if ((op == KERN_FILE_BYPID) && (arg < -1))
   2162 			/* -1 means all processes */
   2163 			return EINVAL;
   2164 
   2165 		sysctl_unlock();
   2166 		if (op == KERN_FILE_BYFILE)
   2167 			mutex_enter(&sysctl_file_marker_lock);
   2168 		mutex_enter(proc_lock);
   2169 		PROCLIST_FOREACH(p, &allproc) {
   2170 			if (p->p_stat == SIDL) {
   2171 				/* skip embryonic processes */
   2172 				continue;
   2173 			}
   2174 			if (arg > 0 && p->p_pid != arg) {
   2175 				/* pick only the one we want */
   2176 				/* XXX want 0 to mean "kernel files" */
   2177 				continue;
   2178 			}
   2179 			mutex_enter(p->p_lock);
   2180 			error = kauth_authorize_process(l->l_cred,
   2181 			    KAUTH_PROCESS_CANSEE, p,
   2182 			    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES),
   2183 			    NULL, NULL);
   2184 			mutex_exit(p->p_lock);
   2185 			if (error != 0) {
   2186 				/*
   2187 				 * Don't leak kauth retval if we're silently
   2188 				 * skipping this entry.
   2189 				 */
   2190 				error = 0;
   2191 				continue;
   2192 			}
   2193 
   2194 			/*
   2195 			 * Grab a hold on the process.
   2196 			 */
   2197 			if (!rw_tryenter(&p->p_reflock, RW_READER)) {
   2198 				continue;
   2199 			}
   2200 			mutex_exit(proc_lock);
   2201 
   2202 			fd = p->p_fd;
   2203 			mutex_enter(&fd->fd_lock);
   2204 			dt = fd->fd_dt;
   2205 			for (i = 0; i < dt->dt_nfiles; i++) {
   2206 				if ((ff = dt->dt_ff[i]) == NULL) {
   2207 					continue;
   2208 				}
   2209 				if ((fp = ff->ff_file) == NULL) {
   2210 					continue;
   2211 				}
   2212 
   2213 				if ((op == KERN_FILE_BYFILE) &&
   2214 				    (fp->f_marker == sysctl_file_marker)) {
   2215 					continue;
   2216 				}
   2217 				if (len >= elem_size && elem_count > 0) {
   2218 					mutex_enter(&fp->f_lock);
   2219 					fill_file(&kf, fp, ff, i, p->p_pid);
   2220 					mutex_exit(&fp->f_lock);
   2221 					mutex_exit(&fd->fd_lock);
   2222 					error = sysctl_copyout(l,
   2223 					    &kf, dp, out_size);
   2224 					mutex_enter(&fd->fd_lock);
   2225 					if (error)
   2226 						break;
   2227 					dp += elem_size;
   2228 					len -= elem_size;
   2229 				}
   2230 				if (op == KERN_FILE_BYFILE)
   2231 					fp->f_marker = sysctl_file_marker;
   2232 				needed += elem_size;
   2233 				if (elem_count > 0 && elem_count != INT_MAX)
   2234 					elem_count--;
   2235 			}
   2236 			mutex_exit(&fd->fd_lock);
   2237 
   2238 			/*
   2239 			 * Release reference to process.
   2240 			 */
   2241 			mutex_enter(proc_lock);
   2242 			rw_exit(&p->p_reflock);
   2243 		}
   2244 		if (op == KERN_FILE_BYFILE) {
   2245 			sysctl_file_marker++;
   2246 
   2247 			/* Reset all markers if wrapped. */
   2248 			if (sysctl_file_marker == 0) {
   2249 				sysctl_file_marker_reset();
   2250 				sysctl_file_marker++;
   2251 			}
   2252 		}
   2253 		mutex_exit(proc_lock);
   2254 		if (op == KERN_FILE_BYFILE)
   2255 			mutex_exit(&sysctl_file_marker_lock);
   2256 		sysctl_relock();
   2257 		break;
   2258 	default:
   2259 		return EINVAL;
   2260 	}
   2261 
   2262 	if (oldp == NULL)
   2263 		needed += KERN_FILESLOP * elem_size;
   2264 	*oldlenp = needed;
   2265 
   2266 	return error;
   2267 }
   2268 
   2269 static void
   2270 fill_file(struct kinfo_file *kp, const file_t *fp, const fdfile_t *ff,
   2271 	  int i, pid_t pid)
   2272 {
   2273 
   2274 	memset(kp, 0, sizeof(*kp));
   2275 
   2276 	kp->ki_fileaddr =	PTRTOUINT64(fp);
   2277 	kp->ki_flag =		fp->f_flag;
   2278 	kp->ki_iflags =		0;
   2279 	kp->ki_ftype =		fp->f_type;
   2280 	kp->ki_count =		fp->f_count;
   2281 	kp->ki_msgcount =	fp->f_msgcount;
   2282 	kp->ki_fucred =		PTRTOUINT64(fp->f_cred);
   2283 	kp->ki_fuid =		kauth_cred_geteuid(fp->f_cred);
   2284 	kp->ki_fgid =		kauth_cred_getegid(fp->f_cred);
   2285 	kp->ki_fops =		PTRTOUINT64(fp->f_ops);
   2286 	kp->ki_foffset =	fp->f_offset;
   2287 	kp->ki_fdata =		PTRTOUINT64(fp->f_data);
   2288 
   2289 	/* vnode information to glue this file to something */
   2290 	if (fp->f_type == DTYPE_VNODE) {
   2291 		struct vnode *vp = (struct vnode *)fp->f_data;
   2292 
   2293 		kp->ki_vun =	PTRTOUINT64(vp->v_un.vu_socket);
   2294 		kp->ki_vsize =	vp->v_size;
   2295 		kp->ki_vtype =	vp->v_type;
   2296 		kp->ki_vtag =	vp->v_tag;
   2297 		kp->ki_vdata =	PTRTOUINT64(vp->v_data);
   2298 	}
   2299 
   2300 	/* process information when retrieved via KERN_FILE_BYPID */
   2301 	if (ff != NULL) {
   2302 		kp->ki_pid =		pid;
   2303 		kp->ki_fd =		i;
   2304 		kp->ki_ofileflags =	ff->ff_exclose;
   2305 		kp->ki_usecount =	ff->ff_refcnt;
   2306 	}
   2307 }
   2308