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