Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.196
      1 /*	$NetBSD: kern_descrip.c,v 1.196 2009/06/07 09:39:02 yamt 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.196 2009/06/07 09:39:02 yamt 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 
     98 static int	file_ctor(void *, void *, int);
     99 static void	file_dtor(void *, void *);
    100 static int	fdfile_ctor(void *, void *, int);
    101 static void	fdfile_dtor(void *, void *);
    102 static int	filedesc_ctor(void *, void *, int);
    103 static void	filedesc_dtor(void *, void *);
    104 static int	filedescopen(dev_t, int, int, lwp_t *);
    105 
    106 kmutex_t	filelist_lock;	/* lock on filehead */
    107 struct filelist	filehead;	/* head of list of open files */
    108 u_int		nfiles;		/* actual number of open files */
    109 
    110 static pool_cache_t filedesc_cache;
    111 static pool_cache_t file_cache;
    112 static pool_cache_t fdfile_cache;
    113 
    114 const struct cdevsw filedesc_cdevsw = {
    115 	filedescopen, noclose, noread, nowrite, noioctl,
    116 	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER | D_MPSAFE,
    117 };
    118 
    119 /* For ease of reading. */
    120 __strong_alias(fd_putvnode,fd_putfile)
    121 __strong_alias(fd_putsock,fd_putfile)
    122 
    123 /*
    124  * Initialize the descriptor system.
    125  */
    126 void
    127 fd_sys_init(void)
    128 {
    129 
    130 	mutex_init(&filelist_lock, MUTEX_DEFAULT, IPL_NONE);
    131 
    132 	file_cache = pool_cache_init(sizeof(file_t), coherency_unit, 0,
    133 	    0, "file", NULL, IPL_NONE, file_ctor, file_dtor, NULL);
    134 	KASSERT(file_cache != NULL);
    135 
    136 	fdfile_cache = pool_cache_init(sizeof(fdfile_t), coherency_unit, 0,
    137 	    PR_LARGECACHE, "fdfile", NULL, IPL_NONE, fdfile_ctor, fdfile_dtor,
    138 	    NULL);
    139 	KASSERT(fdfile_cache != NULL);
    140 
    141 	filedesc_cache = pool_cache_init(sizeof(filedesc_t), coherency_unit,
    142 	    0, 0, "filedesc", NULL, IPL_NONE, filedesc_ctor, filedesc_dtor,
    143 	    NULL);
    144 	KASSERT(filedesc_cache != NULL);
    145 }
    146 
    147 static bool
    148 fd_isused(filedesc_t *fdp, unsigned fd)
    149 {
    150 	u_int off = fd >> NDENTRYSHIFT;
    151 
    152 	KASSERT(fd < fdp->fd_dt->dt_nfiles);
    153 
    154 	return (fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0;
    155 }
    156 
    157 /*
    158  * Verify that the bitmaps match the descriptor table.
    159  */
    160 static inline void
    161 fd_checkmaps(filedesc_t *fdp)
    162 {
    163 #ifdef DEBUG
    164 	fdtab_t *dt;
    165 	u_int fd;
    166 
    167 	dt = fdp->fd_dt;
    168 	if (fdp->fd_refcnt == -1) {
    169 		/*
    170 		 * fd_free tears down the table without maintaining its bitmap.
    171 		 */
    172 		return;
    173 	}
    174 	for (fd = 0; fd < dt->dt_nfiles; fd++) {
    175 		if (fd < NDFDFILE) {
    176 			KASSERT(dt->dt_ff[fd] ==
    177 			    (fdfile_t *)fdp->fd_dfdfile[fd]);
    178 		}
    179 		if (dt->dt_ff[fd] == NULL) {
    180 			KASSERT(!fd_isused(fdp, fd));
    181 		} else if (dt->dt_ff[fd]->ff_file != NULL) {
    182 			KASSERT(fd_isused(fdp, fd));
    183 		}
    184 	}
    185 #else	/* DEBUG */
    186 	/* nothing */
    187 #endif	/* DEBUG */
    188 }
    189 
    190 static int
    191 fd_next_zero(filedesc_t *fdp, uint32_t *bitmap, int want, u_int bits)
    192 {
    193 	int i, off, maxoff;
    194 	uint32_t sub;
    195 
    196 	KASSERT(mutex_owned(&fdp->fd_lock));
    197 
    198 	fd_checkmaps(fdp);
    199 
    200 	if (want > bits)
    201 		return -1;
    202 
    203 	off = want >> NDENTRYSHIFT;
    204 	i = want & NDENTRYMASK;
    205 	if (i) {
    206 		sub = bitmap[off] | ((u_int)~0 >> (NDENTRIES - i));
    207 		if (sub != ~0)
    208 			goto found;
    209 		off++;
    210 	}
    211 
    212 	maxoff = NDLOSLOTS(bits);
    213 	while (off < maxoff) {
    214 		if ((sub = bitmap[off]) != ~0)
    215 			goto found;
    216 		off++;
    217 	}
    218 
    219 	return (-1);
    220 
    221  found:
    222 	return (off << NDENTRYSHIFT) + ffs(~sub) - 1;
    223 }
    224 
    225 static int
    226 fd_last_set(filedesc_t *fd, int last)
    227 {
    228 	int off, i;
    229 	fdfile_t **ff = fd->fd_dt->dt_ff;
    230 	uint32_t *bitmap = fd->fd_lomap;
    231 
    232 	KASSERT(mutex_owned(&fd->fd_lock));
    233 
    234 	fd_checkmaps(fd);
    235 
    236 	off = (last - 1) >> NDENTRYSHIFT;
    237 
    238 	while (off >= 0 && !bitmap[off])
    239 		off--;
    240 
    241 	if (off < 0)
    242 		return (-1);
    243 
    244 	i = ((off + 1) << NDENTRYSHIFT) - 1;
    245 	if (i >= last)
    246 		i = last - 1;
    247 
    248 	/* XXX should use bitmap */
    249 	while (i > 0 && (ff[i] == NULL || !ff[i]->ff_allocated))
    250 		i--;
    251 
    252 	return (i);
    253 }
    254 
    255 static inline void
    256 fd_used(filedesc_t *fdp, unsigned fd)
    257 {
    258 	u_int off = fd >> NDENTRYSHIFT;
    259 	fdfile_t *ff;
    260 
    261 	ff = fdp->fd_dt->dt_ff[fd];
    262 
    263 	KASSERT(mutex_owned(&fdp->fd_lock));
    264 	KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) == 0);
    265 	KASSERT(ff != NULL);
    266 	KASSERT(ff->ff_file == NULL);
    267    	KASSERT(!ff->ff_allocated);
    268 
    269    	ff->ff_allocated = 1;
    270 	fdp->fd_lomap[off] |= 1 << (fd & NDENTRYMASK);
    271 	if (__predict_false(fdp->fd_lomap[off] == ~0)) {
    272 		KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
    273 		    (1 << (off & NDENTRYMASK))) == 0);
    274 		fdp->fd_himap[off >> NDENTRYSHIFT] |= 1 << (off & NDENTRYMASK);
    275 	}
    276 
    277 	if ((int)fd > fdp->fd_lastfile) {
    278 		fdp->fd_lastfile = fd;
    279 	}
    280 
    281 	fd_checkmaps(fdp);
    282 }
    283 
    284 static inline void
    285 fd_unused(filedesc_t *fdp, unsigned fd)
    286 {
    287 	u_int off = fd >> NDENTRYSHIFT;
    288 	fdfile_t *ff;
    289 
    290 	ff = fdp->fd_dt->dt_ff[fd];
    291 
    292 	/*
    293 	 * Don't assert the lock is held here, as we may be copying
    294 	 * the table during exec() and it is not needed there.
    295 	 * procfs and sysctl are locked out by proc::p_reflock.
    296 	 *
    297 	 * KASSERT(mutex_owned(&fdp->fd_lock));
    298 	 */
    299 	KASSERT(ff != NULL);
    300 	KASSERT(ff->ff_file == NULL);
    301    	KASSERT(ff->ff_allocated);
    302 
    303 	if (fd < fdp->fd_freefile) {
    304 		fdp->fd_freefile = fd;
    305 	}
    306 
    307 	if (fdp->fd_lomap[off] == ~0) {
    308 		KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
    309 		    (1 << (off & NDENTRYMASK))) != 0);
    310 		fdp->fd_himap[off >> NDENTRYSHIFT] &=
    311 		    ~(1 << (off & NDENTRYMASK));
    312 	}
    313 	KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0);
    314 	fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
    315 	ff->ff_allocated = 0;
    316 
    317 	KASSERT(fd <= fdp->fd_lastfile);
    318 	if (fd == fdp->fd_lastfile) {
    319 		fdp->fd_lastfile = fd_last_set(fdp, fd);
    320 	}
    321 	fd_checkmaps(fdp);
    322 }
    323 
    324 /*
    325  * Look up the file structure corresponding to a file descriptor
    326  * and return the file, holding a reference on the descriptor.
    327  */
    328 inline file_t *
    329 fd_getfile(unsigned fd)
    330 {
    331 	filedesc_t *fdp;
    332 	fdfile_t *ff;
    333 	file_t *fp;
    334 	fdtab_t *dt;
    335 
    336 	/*
    337 	 * Look up the fdfile structure representing this descriptor.
    338 	 * We are doing this unlocked.  See fd_tryexpand().
    339 	 */
    340 	fdp = curlwp->l_fd;
    341 	dt = fdp->fd_dt;
    342 	if (__predict_false(fd >= dt->dt_nfiles)) {
    343 		return NULL;
    344 	}
    345 	ff = dt->dt_ff[fd];
    346 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
    347 	if (__predict_false(ff == NULL)) {
    348 		return NULL;
    349 	}
    350 
    351 	/* Now get a reference to the descriptor. */
    352 	if (fdp->fd_refcnt == 1) {
    353 		/*
    354 		 * Single threaded: don't need to worry about concurrent
    355 		 * access (other than earlier calls to kqueue, which may
    356 		 * hold a reference to the descriptor).
    357 		 */
    358 		ff->ff_refcnt++;
    359 	} else {
    360 		/*
    361 		 * Multi threaded: issue a memory barrier to ensure that we
    362 		 * acquire the file pointer _after_ adding a reference.  If
    363 		 * no memory barrier, we could fetch a stale pointer.
    364 		 */
    365 		atomic_inc_uint(&ff->ff_refcnt);
    366 #ifndef __HAVE_ATOMIC_AS_MEMBAR
    367 		membar_enter();
    368 #endif
    369 	}
    370 
    371 	/*
    372 	 * If the file is not open or is being closed then put the
    373 	 * reference back.
    374 	 */
    375 	fp = ff->ff_file;
    376 	if (__predict_true(fp != NULL)) {
    377 		return fp;
    378 	}
    379 	fd_putfile(fd);
    380 	return NULL;
    381 }
    382 
    383 /*
    384  * Release a reference to a file descriptor acquired with fd_getfile().
    385  */
    386 void
    387 fd_putfile(unsigned fd)
    388 {
    389 	filedesc_t *fdp;
    390 	fdfile_t *ff;
    391 	u_int u, v;
    392 
    393 	fdp = curlwp->l_fd;
    394 	ff = fdp->fd_dt->dt_ff[fd];
    395 
    396 	KASSERT(fd < fdp->fd_dt->dt_nfiles);
    397 	KASSERT(ff != NULL);
    398 	KASSERT((ff->ff_refcnt & FR_MASK) > 0);
    399 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
    400 
    401 	if (fdp->fd_refcnt == 1) {
    402 		/*
    403 		 * Single threaded: don't need to worry about concurrent
    404 		 * access (other than earlier calls to kqueue, which may
    405 		 * hold a reference to the descriptor).
    406 		 */
    407 		if (__predict_false((ff->ff_refcnt & FR_CLOSING) != 0)) {
    408 			fd_close(fd);
    409 			return;
    410 		}
    411 		ff->ff_refcnt--;
    412 		return;
    413 	}
    414 
    415 	/*
    416 	 * Ensure that any use of the file is complete and globally
    417 	 * visible before dropping the final reference.  If no membar,
    418 	 * the current CPU could still access memory associated with
    419 	 * the file after it has been freed or recycled by another
    420 	 * CPU.
    421 	 */
    422 #ifndef __HAVE_ATOMIC_AS_MEMBAR
    423 	membar_exit();
    424 #endif
    425 
    426 	/*
    427 	 * Be optimistic and start out with the assumption that no other
    428 	 * threads are trying to close the descriptor.  If the CAS fails,
    429 	 * we lost a race and/or it's being closed.
    430 	 */
    431 	for (u = ff->ff_refcnt & FR_MASK;; u = v) {
    432 		v = atomic_cas_uint(&ff->ff_refcnt, u, u - 1);
    433 		if (__predict_true(u == v)) {
    434 			return;
    435 		}
    436 		if (__predict_false((v & FR_CLOSING) != 0)) {
    437 			break;
    438 		}
    439 	}
    440 
    441 	/* Another thread is waiting to close the file: join it. */
    442 	(void)fd_close(fd);
    443 }
    444 
    445 /*
    446  * Convenience wrapper around fd_getfile() that returns reference
    447  * to a vnode.
    448  */
    449 int
    450 fd_getvnode(unsigned fd, file_t **fpp)
    451 {
    452 	vnode_t *vp;
    453 	file_t *fp;
    454 
    455 	fp = fd_getfile(fd);
    456 	if (__predict_false(fp == NULL)) {
    457 		return EBADF;
    458 	}
    459 	if (__predict_false(fp->f_type != DTYPE_VNODE)) {
    460 		fd_putfile(fd);
    461 		return EINVAL;
    462 	}
    463 	vp = fp->f_data;
    464 	if (__predict_false(vp->v_type == VBAD)) {
    465 		/* XXX Is this case really necessary? */
    466 		fd_putfile(fd);
    467 		return EBADF;
    468 	}
    469 	*fpp = fp;
    470 	return 0;
    471 }
    472 
    473 /*
    474  * Convenience wrapper around fd_getfile() that returns reference
    475  * to a socket.
    476  */
    477 int
    478 fd_getsock(unsigned fd, struct socket **sop)
    479 {
    480 	file_t *fp;
    481 
    482 	fp = fd_getfile(fd);
    483 	if (__predict_false(fp == NULL)) {
    484 		return EBADF;
    485 	}
    486 	if (__predict_false(fp->f_type != DTYPE_SOCKET)) {
    487 		fd_putfile(fd);
    488 		return ENOTSOCK;
    489 	}
    490 	*sop = fp->f_data;
    491 	return 0;
    492 }
    493 
    494 /*
    495  * Look up the file structure corresponding to a file descriptor
    496  * and return it with a reference held on the file, not the
    497  * descriptor.
    498  *
    499  * This is heavyweight and only used when accessing descriptors
    500  * from a foreign process.  The caller must ensure that `p' does
    501  * not exit or fork across this call.
    502  *
    503  * To release the file (not descriptor) reference, use closef().
    504  */
    505 file_t *
    506 fd_getfile2(proc_t *p, unsigned fd)
    507 {
    508 	filedesc_t *fdp;
    509 	fdfile_t *ff;
    510 	file_t *fp;
    511 	fdtab_t *dt;
    512 
    513 	fdp = p->p_fd;
    514 	mutex_enter(&fdp->fd_lock);
    515 	dt = fdp->fd_dt;
    516 	if (fd >= dt->dt_nfiles) {
    517 		mutex_exit(&fdp->fd_lock);
    518 		return NULL;
    519 	}
    520 	if ((ff = dt->dt_ff[fd]) == NULL) {
    521 		mutex_exit(&fdp->fd_lock);
    522 		return NULL;
    523 	}
    524 	if ((fp = ff->ff_file) == NULL) {
    525 		mutex_exit(&fdp->fd_lock);
    526 		return NULL;
    527 	}
    528 	mutex_enter(&fp->f_lock);
    529 	fp->f_count++;
    530 	mutex_exit(&fp->f_lock);
    531 	mutex_exit(&fdp->fd_lock);
    532 
    533 	return fp;
    534 }
    535 
    536 /*
    537  * Internal form of close.  Must be called with a reference to the
    538  * descriptor, and will drop the reference.  When all descriptor
    539  * references are dropped, releases the descriptor slot and a single
    540  * reference to the file structure.
    541  */
    542 int
    543 fd_close(unsigned fd)
    544 {
    545 	struct flock lf;
    546 	filedesc_t *fdp;
    547 	fdfile_t *ff;
    548 	file_t *fp;
    549 	proc_t *p;
    550 	lwp_t *l;
    551 	u_int refcnt;
    552 
    553 	l = curlwp;
    554 	p = l->l_proc;
    555 	fdp = l->l_fd;
    556 	ff = fdp->fd_dt->dt_ff[fd];
    557 
    558 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
    559 
    560 	mutex_enter(&fdp->fd_lock);
    561 	KASSERT((ff->ff_refcnt & FR_MASK) > 0);
    562 	if (__predict_false(ff->ff_file == NULL)) {
    563 		/*
    564 		 * Another user of the file is already closing, and is
    565 		 * waiting for other users of the file to drain.  Release
    566 		 * our reference, and wake up the closer.
    567 		 */
    568 		atomic_dec_uint(&ff->ff_refcnt);
    569 		cv_broadcast(&ff->ff_closing);
    570 		mutex_exit(&fdp->fd_lock);
    571 
    572 		/*
    573 		 * An application error, so pretend that the descriptor
    574 		 * was already closed.  We can't safely wait for it to
    575 		 * be closed without potentially deadlocking.
    576 		 */
    577 		return (EBADF);
    578 	}
    579 	KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
    580 
    581 	/*
    582 	 * There may be multiple users of this file within the process.
    583 	 * Notify existing and new users that the file is closing.  This
    584 	 * will prevent them from adding additional uses to this file
    585 	 * while we are closing it.
    586 	 */
    587 	fp = ff->ff_file;
    588 	ff->ff_file = NULL;
    589 	ff->ff_exclose = false;
    590 
    591 	/*
    592 	 * We expect the caller to hold a descriptor reference - drop it.
    593 	 * The reference count may increase beyond zero at this point due
    594 	 * to an erroneous descriptor reference by an application, but
    595 	 * fd_getfile() will notice that the file is being closed and drop
    596 	 * the reference again.
    597 	 */
    598 	if (fdp->fd_refcnt == 1) {
    599 		/* Single threaded. */
    600 		refcnt = --(ff->ff_refcnt);
    601 	} else {
    602 		/* Multi threaded. */
    603 #ifndef __HAVE_ATOMIC_AS_MEMBAR
    604 		membar_producer();
    605 #endif
    606 		refcnt = atomic_dec_uint_nv(&ff->ff_refcnt);
    607 	}
    608 	if (__predict_false(refcnt != 0)) {
    609 		/*
    610 		 * Wait for other references to drain.  This is typically
    611 		 * an application error - the descriptor is being closed
    612 		 * while still in use.
    613 		 *
    614 		 */
    615 		atomic_or_uint(&ff->ff_refcnt, FR_CLOSING);
    616 
    617 		/*
    618 		 * Remove any knotes attached to the file.  A knote
    619 		 * attached to the descriptor can hold references on it.
    620 		 */
    621 		mutex_exit(&fdp->fd_lock);
    622 		if (!SLIST_EMPTY(&ff->ff_knlist)) {
    623 			knote_fdclose(fd);
    624 		}
    625 
    626 		/* Try to drain out descriptor references. */
    627 		(*fp->f_ops->fo_drain)(fp);
    628 		mutex_enter(&fdp->fd_lock);
    629 
    630 		/*
    631 		 * We need to see the count drop to zero at least once,
    632 		 * in order to ensure that all pre-existing references
    633 		 * have been drained.  New references past this point are
    634 		 * of no interest.
    635 		 */
    636 		while ((ff->ff_refcnt & FR_MASK) != 0) {
    637 			cv_wait(&ff->ff_closing, &fdp->fd_lock);
    638 		}
    639 		atomic_and_uint(&ff->ff_refcnt, ~FR_CLOSING);
    640 	} else {
    641 		/* If no references, there must be no knotes. */
    642 		KASSERT(SLIST_EMPTY(&ff->ff_knlist));
    643 	}
    644 
    645 	/*
    646 	 * POSIX record locking dictates that any close releases ALL
    647 	 * locks owned by this process.  This is handled by setting
    648 	 * a flag in the unlock to free ONLY locks obeying POSIX
    649 	 * semantics, and not to free BSD-style file locks.
    650 	 * If the descriptor was in a message, POSIX-style locks
    651 	 * aren't passed with the descriptor.
    652 	 */
    653 	if (__predict_false((p->p_flag & PK_ADVLOCK) != 0 &&
    654 	    fp->f_type == DTYPE_VNODE)) {
    655 		lf.l_whence = SEEK_SET;
    656 		lf.l_start = 0;
    657 		lf.l_len = 0;
    658 		lf.l_type = F_UNLCK;
    659 		mutex_exit(&fdp->fd_lock);
    660 		(void)VOP_ADVLOCK(fp->f_data, p, F_UNLCK, &lf, F_POSIX);
    661 		mutex_enter(&fdp->fd_lock);
    662 	}
    663 
    664 	/* Free descriptor slot. */
    665 	fd_unused(fdp, fd);
    666 	mutex_exit(&fdp->fd_lock);
    667 
    668 	/* Now drop reference to the file itself. */
    669 	return closef(fp);
    670 }
    671 
    672 /*
    673  * Duplicate a file descriptor.
    674  */
    675 int
    676 fd_dup(file_t *fp, int minfd, int *newp, bool exclose)
    677 {
    678 	proc_t *p;
    679 	int error;
    680 
    681 	p = curproc;
    682 
    683 	while ((error = fd_alloc(p, minfd, newp)) != 0) {
    684 		if (error != ENOSPC) {
    685 			return error;
    686 		}
    687 		fd_tryexpand(p);
    688 	}
    689 
    690 	curlwp->l_fd->fd_dt->dt_ff[*newp]->ff_exclose = exclose;
    691 	fd_affix(p, fp, *newp);
    692 	return 0;
    693 }
    694 
    695 /*
    696  * dup2 operation.
    697  */
    698 int
    699 fd_dup2(file_t *fp, unsigned new)
    700 {
    701 	filedesc_t *fdp;
    702 	fdfile_t *ff;
    703 	fdtab_t *dt;
    704 
    705 	fdp = curlwp->l_fd;
    706 
    707 	/*
    708 	 * Ensure there are enough slots in the descriptor table,
    709 	 * and allocate an fdfile_t up front in case we need it.
    710 	 */
    711 	while (new >= fdp->fd_dt->dt_nfiles) {
    712 		fd_tryexpand(curproc);
    713 	}
    714 	ff = pool_cache_get(fdfile_cache, PR_WAITOK);
    715 
    716 	/*
    717 	 * If there is already a file open, close it.  If the file is
    718 	 * half open, wait for it to be constructed before closing it.
    719 	 * XXX Potential for deadlock here?
    720 	 */
    721 	mutex_enter(&fdp->fd_lock);
    722 	while (fd_isused(fdp, new)) {
    723 		mutex_exit(&fdp->fd_lock);
    724 		if (fd_getfile(new) != NULL) {
    725 			(void)fd_close(new);
    726 		} else {
    727 			/*
    728 			 * Crummy, but unlikely to happen.
    729 			 * Can occur if we interrupt another
    730 			 * thread while it is opening a file.
    731 			 */
    732 			kpause("dup2", false, 1, NULL);
    733 		}
    734 		mutex_enter(&fdp->fd_lock);
    735 	}
    736 	dt = fdp->fd_dt;
    737 	if (dt->dt_ff[new] == NULL) {
    738 		KASSERT(new >= NDFDFILE);
    739 		dt->dt_ff[new] = ff;
    740 		ff = NULL;
    741 	}
    742 	fd_used(fdp, new);
    743 	mutex_exit(&fdp->fd_lock);
    744 
    745 	/* Slot is now allocated.  Insert copy of the file. */
    746 	fd_affix(curproc, fp, new);
    747 	if (ff != NULL) {
    748 		pool_cache_put(fdfile_cache, ff);
    749 	}
    750 	return 0;
    751 }
    752 
    753 /*
    754  * Drop reference to a file structure.
    755  */
    756 int
    757 closef(file_t *fp)
    758 {
    759 	struct flock lf;
    760 	int error;
    761 
    762 	/*
    763 	 * Drop reference.  If referenced elsewhere it's still open
    764 	 * and we have nothing more to do.
    765 	 */
    766 	mutex_enter(&fp->f_lock);
    767 	KASSERT(fp->f_count > 0);
    768 	if (--fp->f_count > 0) {
    769 		mutex_exit(&fp->f_lock);
    770 		return 0;
    771 	}
    772 	KASSERT(fp->f_count == 0);
    773 	mutex_exit(&fp->f_lock);
    774 
    775 	/* We held the last reference - release locks, close and free. */
    776         if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
    777         	lf.l_whence = SEEK_SET;
    778 		lf.l_start = 0;
    779 		lf.l_len = 0;
    780 		lf.l_type = F_UNLCK;
    781 		(void)VOP_ADVLOCK(fp->f_data, fp, F_UNLCK, &lf, F_FLOCK);
    782 	}
    783 	if (fp->f_ops != NULL) {
    784 		error = (*fp->f_ops->fo_close)(fp);
    785 	} else {
    786 		error = 0;
    787 	}
    788 	KASSERT(fp->f_count == 0);
    789 	KASSERT(fp->f_cred != NULL);
    790 	pool_cache_put(file_cache, fp);
    791 
    792 	return error;
    793 }
    794 
    795 /*
    796  * Allocate a file descriptor for the process.
    797  */
    798 int
    799 fd_alloc(proc_t *p, int want, int *result)
    800 {
    801 	filedesc_t *fdp;
    802 	int i, lim, last, error;
    803 	u_int off, new;
    804 	fdtab_t *dt;
    805 
    806 	KASSERT(p == curproc || p == &proc0);
    807 
    808 	fdp = p->p_fd;
    809 
    810 	/*
    811 	 * Search for a free descriptor starting at the higher
    812 	 * of want or fd_freefile.
    813 	 */
    814 	mutex_enter(&fdp->fd_lock);
    815 	fd_checkmaps(fdp);
    816 	dt = fdp->fd_dt;
    817 	KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
    818 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    819 	last = min(dt->dt_nfiles, lim);
    820 	for (;;) {
    821 		if ((i = want) < fdp->fd_freefile)
    822 			i = fdp->fd_freefile;
    823 		off = i >> NDENTRYSHIFT;
    824 		new = fd_next_zero(fdp, fdp->fd_himap, off,
    825 		    (last + NDENTRIES - 1) >> NDENTRYSHIFT);
    826 		if (new == -1)
    827 			break;
    828 		i = fd_next_zero(fdp, &fdp->fd_lomap[new],
    829 		    new > off ? 0 : i & NDENTRYMASK, NDENTRIES);
    830 		if (i == -1) {
    831 			/*
    832 			 * Free file descriptor in this block was
    833 			 * below want, try again with higher want.
    834 			 */
    835 			want = (new + 1) << NDENTRYSHIFT;
    836 			continue;
    837 		}
    838 		i += (new << NDENTRYSHIFT);
    839 		if (i >= last) {
    840 			break;
    841 		}
    842 		if (dt->dt_ff[i] == NULL) {
    843 			KASSERT(i >= NDFDFILE);
    844 			dt->dt_ff[i] = pool_cache_get(fdfile_cache, PR_WAITOK);
    845 		}
    846 		KASSERT(dt->dt_ff[i]->ff_refcnt == 0);
    847 		KASSERT(dt->dt_ff[i]->ff_file == NULL);
    848 		fd_used(fdp, i);
    849 		if (want <= fdp->fd_freefile) {
    850 			fdp->fd_freefile = i;
    851 		}
    852 		*result = i;
    853 		KASSERT(i >= NDFDFILE ||
    854 		    dt->dt_ff[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
    855 		fd_checkmaps(fdp);
    856 		mutex_exit(&fdp->fd_lock);
    857 		return 0;
    858 	}
    859 
    860 	/* No space in current array.  Let the caller expand and retry. */
    861 	error = (dt->dt_nfiles >= lim) ? EMFILE : ENOSPC;
    862 	mutex_exit(&fdp->fd_lock);
    863 	return error;
    864 }
    865 
    866 /*
    867  * Allocate memory for a descriptor table.
    868  */
    869 static fdtab_t *
    870 fd_dtab_alloc(int n)
    871 {
    872 	fdtab_t *dt;
    873 	size_t sz;
    874 
    875 	KASSERT(n > NDFILE);
    876 
    877 	sz = sizeof(*dt) + (n - NDFILE) * sizeof(dt->dt_ff[0]);
    878 	dt = kmem_alloc(sz, KM_SLEEP);
    879 #ifdef DIAGNOSTIC
    880 	memset(dt, 0xff, sz);
    881 #endif
    882 	dt->dt_nfiles = n;
    883 	dt->dt_link = NULL;
    884 	return dt;
    885 }
    886 
    887 /*
    888  * Free a descriptor table, and all tables linked for deferred free.
    889  */
    890 static void
    891 fd_dtab_free(fdtab_t *dt)
    892 {
    893 	fdtab_t *next;
    894 	size_t sz;
    895 
    896 	do {
    897 		next = dt->dt_link;
    898 		KASSERT(dt->dt_nfiles > NDFILE);
    899 		sz = sizeof(*dt) +
    900 		    (dt->dt_nfiles - NDFILE) * sizeof(dt->dt_ff[0]);
    901 #ifdef DIAGNOSTIC
    902 		memset(dt, 0xff, sz);
    903 #endif
    904 		kmem_free(dt, sz);
    905 		dt = next;
    906 	} while (dt != NULL);
    907 }
    908 
    909 /*
    910  * Allocate descriptor bitmap.
    911  */
    912 static void
    913 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
    914 {
    915 	uint8_t *ptr;
    916 	size_t szlo, szhi;
    917 
    918 	KASSERT(n > NDENTRIES);
    919 
    920 	szlo = NDLOSLOTS(n) * sizeof(uint32_t);
    921 	szhi = NDHISLOTS(n) * sizeof(uint32_t);
    922 	ptr = kmem_alloc(szlo + szhi, KM_SLEEP);
    923 	*lo = (uint32_t *)ptr;
    924 	*hi = (uint32_t *)(ptr + szlo);
    925 }
    926 
    927 /*
    928  * Free descriptor bitmap.
    929  */
    930 static void
    931 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
    932 {
    933 	size_t szlo, szhi;
    934 
    935 	KASSERT(n > NDENTRIES);
    936 
    937 	szlo = NDLOSLOTS(n) * sizeof(uint32_t);
    938 	szhi = NDHISLOTS(n) * sizeof(uint32_t);
    939 	KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo));
    940 	kmem_free(lo, szlo + szhi);
    941 }
    942 
    943 /*
    944  * Expand a process' descriptor table.
    945  */
    946 void
    947 fd_tryexpand(proc_t *p)
    948 {
    949 	filedesc_t *fdp;
    950 	int i, numfiles, oldnfiles;
    951 	fdtab_t *newdt, *dt;
    952 	uint32_t *newhimap, *newlomap;
    953 
    954 	KASSERT(p == curproc || p == &proc0);
    955 
    956 	fdp = p->p_fd;
    957 	newhimap = NULL;
    958 	newlomap = NULL;
    959 	oldnfiles = fdp->fd_dt->dt_nfiles;
    960 
    961 	if (oldnfiles < NDEXTENT)
    962 		numfiles = NDEXTENT;
    963 	else
    964 		numfiles = 2 * oldnfiles;
    965 
    966 	newdt = fd_dtab_alloc(numfiles);
    967 	if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
    968 		fd_map_alloc(numfiles, &newlomap, &newhimap);
    969 	}
    970 
    971 	mutex_enter(&fdp->fd_lock);
    972 	dt = fdp->fd_dt;
    973 	KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
    974 	if (dt->dt_nfiles != oldnfiles) {
    975 		/* fdp changed; caller must retry */
    976 		mutex_exit(&fdp->fd_lock);
    977 		fd_dtab_free(newdt);
    978 		if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
    979 			fd_map_free(numfiles, newlomap, newhimap);
    980 		}
    981 		return;
    982 	}
    983 
    984 	/* Copy the existing descriptor table and zero the new portion. */
    985 	i = sizeof(fdfile_t *) * oldnfiles;
    986 	memcpy(newdt->dt_ff, dt->dt_ff, i);
    987 	memset((uint8_t *)newdt->dt_ff + i, 0,
    988 	    numfiles * sizeof(fdfile_t *) - i);
    989 
    990 	/*
    991 	 * Link old descriptor array into list to be discarded.  We defer
    992 	 * freeing until the last reference to the descriptor table goes
    993 	 * away (usually process exit).  This allows us to do lockless
    994 	 * lookups in fd_getfile().
    995 	 */
    996 	if (oldnfiles > NDFILE) {
    997 		if (fdp->fd_refcnt > 1) {
    998 			newdt->dt_link = dt;
    999 		} else {
   1000 			fd_dtab_free(dt);
   1001 		}
   1002 	}
   1003 
   1004 	if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
   1005 		i = NDHISLOTS(oldnfiles) * sizeof(uint32_t);
   1006 		memcpy(newhimap, fdp->fd_himap, i);
   1007 		memset((uint8_t *)newhimap + i, 0,
   1008 		    NDHISLOTS(numfiles) * sizeof(uint32_t) - i);
   1009 
   1010 		i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t);
   1011 		memcpy(newlomap, fdp->fd_lomap, i);
   1012 		memset((uint8_t *)newlomap + i, 0,
   1013 		    NDLOSLOTS(numfiles) * sizeof(uint32_t) - i);
   1014 
   1015 		if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
   1016 			fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
   1017 		}
   1018 		fdp->fd_himap = newhimap;
   1019 		fdp->fd_lomap = newlomap;
   1020 	}
   1021 
   1022 	/*
   1023 	 * All other modifications must become globally visible before
   1024 	 * the change to fd_dt.  See fd_getfile().
   1025 	 */
   1026 	membar_producer();
   1027 	fdp->fd_dt = newdt;
   1028 	KASSERT(newdt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
   1029 	fd_checkmaps(fdp);
   1030 	mutex_exit(&fdp->fd_lock);
   1031 }
   1032 
   1033 /*
   1034  * Create a new open file structure and allocate a file descriptor
   1035  * for the current process.
   1036  */
   1037 int
   1038 fd_allocfile(file_t **resultfp, int *resultfd)
   1039 {
   1040 	kauth_cred_t cred;
   1041 	file_t *fp;
   1042 	proc_t *p;
   1043 	int error;
   1044 
   1045 	p = curproc;
   1046 
   1047 	while ((error = fd_alloc(p, 0, resultfd)) != 0) {
   1048 		if (error != ENOSPC) {
   1049 			return error;
   1050 		}
   1051 		fd_tryexpand(p);
   1052 	}
   1053 
   1054 	fp = pool_cache_get(file_cache, PR_WAITOK);
   1055 	if (fp == NULL) {
   1056 		return ENFILE;
   1057 	}
   1058 	KASSERT(fp->f_count == 0);
   1059 	KASSERT(fp->f_msgcount == 0);
   1060 	KASSERT(fp->f_unpcount == 0);
   1061 
   1062 	/* Replace cached credentials if not what we need. */
   1063 	cred = curlwp->l_cred;
   1064 	if (__predict_false(cred != fp->f_cred)) {
   1065 		kauth_cred_free(fp->f_cred);
   1066 		kauth_cred_hold(cred);
   1067 		fp->f_cred = cred;
   1068 	}
   1069 
   1070 	/*
   1071 	 * Don't allow recycled files to be scanned.
   1072 	 * See uipc_usrreq.c.
   1073 	 */
   1074 	if (__predict_false((fp->f_flag & FSCAN) != 0)) {
   1075 		mutex_enter(&fp->f_lock);
   1076 		atomic_and_uint(&fp->f_flag, ~FSCAN);
   1077 		mutex_exit(&fp->f_lock);
   1078 	}
   1079 
   1080 	fp->f_advice = 0;
   1081 	fp->f_offset = 0;
   1082 	*resultfp = fp;
   1083 
   1084 	return 0;
   1085 }
   1086 
   1087 /*
   1088  * Successful creation of a new descriptor: make visible to the process.
   1089  */
   1090 void
   1091 fd_affix(proc_t *p, file_t *fp, unsigned fd)
   1092 {
   1093 	fdfile_t *ff;
   1094 	filedesc_t *fdp;
   1095 
   1096 	KASSERT(p == curproc || p == &proc0);
   1097 
   1098 	/* Add a reference to the file structure. */
   1099 	mutex_enter(&fp->f_lock);
   1100 	fp->f_count++;
   1101 	mutex_exit(&fp->f_lock);
   1102 
   1103 	/*
   1104 	 * Insert the new file into the descriptor slot.
   1105 	 *
   1106 	 * The memory barriers provided by lock activity in this routine
   1107 	 * ensure that any updates to the file structure become globally
   1108 	 * visible before the file becomes visible to other LWPs in the
   1109 	 * current process.
   1110 	 */
   1111 	fdp = p->p_fd;
   1112 	ff = fdp->fd_dt->dt_ff[fd];
   1113 
   1114 	KASSERT(ff != NULL);
   1115 	KASSERT(ff->ff_file == NULL);
   1116 	KASSERT(ff->ff_allocated);
   1117 	KASSERT(fd_isused(fdp, fd));
   1118 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1119 
   1120 	/* No need to lock in order to make file initially visible. */
   1121 	ff->ff_file = fp;
   1122 }
   1123 
   1124 /*
   1125  * Abort creation of a new descriptor: free descriptor slot and file.
   1126  */
   1127 void
   1128 fd_abort(proc_t *p, file_t *fp, unsigned fd)
   1129 {
   1130 	filedesc_t *fdp;
   1131 	fdfile_t *ff;
   1132 
   1133 	KASSERT(p == curproc || p == &proc0);
   1134 
   1135 	fdp = p->p_fd;
   1136 	ff = fdp->fd_dt->dt_ff[fd];
   1137 
   1138 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1139 
   1140 	mutex_enter(&fdp->fd_lock);
   1141 	KASSERT(fd_isused(fdp, fd));
   1142 	fd_unused(fdp, fd);
   1143 	mutex_exit(&fdp->fd_lock);
   1144 
   1145 	if (fp != NULL) {
   1146 		KASSERT(fp->f_count == 0);
   1147 		KASSERT(fp->f_cred != NULL);
   1148 		pool_cache_put(file_cache, fp);
   1149 	}
   1150 }
   1151 
   1152 static int
   1153 file_ctor(void *arg, void *obj, int flags)
   1154 {
   1155 	file_t *fp = obj;
   1156 
   1157 	memset(fp, 0, sizeof(*fp));
   1158 
   1159 	mutex_enter(&filelist_lock);
   1160 	if (__predict_false(nfiles >= maxfiles)) {
   1161 		mutex_exit(&filelist_lock);
   1162 		tablefull("file", "increase kern.maxfiles or MAXFILES");
   1163 		return ENFILE;
   1164 	}
   1165 	nfiles++;
   1166 	LIST_INSERT_HEAD(&filehead, fp, f_list);
   1167 	mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
   1168 	fp->f_cred = curlwp->l_cred;
   1169 	kauth_cred_hold(fp->f_cred);
   1170 	mutex_exit(&filelist_lock);
   1171 
   1172 	return 0;
   1173 }
   1174 
   1175 static void
   1176 file_dtor(void *arg, void *obj)
   1177 {
   1178 	file_t *fp = obj;
   1179 
   1180 	mutex_enter(&filelist_lock);
   1181 	nfiles--;
   1182 	LIST_REMOVE(fp, f_list);
   1183 	mutex_exit(&filelist_lock);
   1184 
   1185 	kauth_cred_free(fp->f_cred);
   1186 	mutex_destroy(&fp->f_lock);
   1187 }
   1188 
   1189 static int
   1190 fdfile_ctor(void *arg, void *obj, int flags)
   1191 {
   1192 	fdfile_t *ff = obj;
   1193 
   1194 	memset(ff, 0, sizeof(*ff));
   1195 	cv_init(&ff->ff_closing, "fdclose");
   1196 
   1197 	return 0;
   1198 }
   1199 
   1200 static void
   1201 fdfile_dtor(void *arg, void *obj)
   1202 {
   1203 	fdfile_t *ff = obj;
   1204 
   1205 	cv_destroy(&ff->ff_closing);
   1206 }
   1207 
   1208 file_t *
   1209 fgetdummy(void)
   1210 {
   1211 	file_t *fp;
   1212 
   1213 	fp = kmem_alloc(sizeof(*fp), KM_SLEEP);
   1214 	if (fp != NULL) {
   1215 		memset(fp, 0, sizeof(*fp));
   1216 		mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
   1217 	}
   1218 	return fp;
   1219 }
   1220 
   1221 void
   1222 fputdummy(file_t *fp)
   1223 {
   1224 
   1225 	mutex_destroy(&fp->f_lock);
   1226 	kmem_free(fp, sizeof(*fp));
   1227 }
   1228 
   1229 /*
   1230  * Create an initial filedesc structure.
   1231  */
   1232 filedesc_t *
   1233 fd_init(filedesc_t *fdp)
   1234 {
   1235 #ifdef DIAGNOSTIC
   1236 	unsigned fd;
   1237 #endif
   1238 
   1239 	if (__predict_true(fdp == NULL)) {
   1240 		fdp = pool_cache_get(filedesc_cache, PR_WAITOK);
   1241 	} else {
   1242 		/* XXXRUMP KASSERT(fdp == &filedesc0); */
   1243 		filedesc_ctor(NULL, fdp, PR_WAITOK);
   1244 	}
   1245 
   1246 #ifdef DIAGNOSTIC
   1247 	KASSERT(fdp->fd_lastfile == -1);
   1248 	KASSERT(fdp->fd_lastkqfile == -1);
   1249 	KASSERT(fdp->fd_knhash == NULL);
   1250 	KASSERT(fdp->fd_freefile == 0);
   1251 	KASSERT(fdp->fd_exclose == false);
   1252 	KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
   1253 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1254 	for (fd = 0; fd < NDFDFILE; fd++) {
   1255 		KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] ==
   1256 		    (fdfile_t *)fdp->fd_dfdfile[fd]);
   1257 	}
   1258 	for (fd = NDFDFILE; fd < NDFILE; fd++) {
   1259 		KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL);
   1260 	}
   1261 	KASSERT(fdp->fd_himap == fdp->fd_dhimap);
   1262 	KASSERT(fdp->fd_lomap == fdp->fd_dlomap);
   1263 #endif	/* DIAGNOSTIC */
   1264 
   1265 	fdp->fd_refcnt = 1;
   1266 
   1267 	return fdp;
   1268 }
   1269 
   1270 /*
   1271  * Initialize a file descriptor table.
   1272  */
   1273 static int
   1274 filedesc_ctor(void *arg, void *obj, int flag)
   1275 {
   1276 	filedesc_t *fdp = obj;
   1277 	fdfile_t **ffp;
   1278 	int i;
   1279 
   1280 	memset(fdp, 0, sizeof(*fdp));
   1281 	mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE);
   1282 	fdp->fd_lastfile = -1;
   1283 	fdp->fd_lastkqfile = -1;
   1284 	fdp->fd_dt = &fdp->fd_dtbuiltin;
   1285 	fdp->fd_dtbuiltin.dt_nfiles = NDFILE;
   1286 	fdp->fd_himap = fdp->fd_dhimap;
   1287 	fdp->fd_lomap = fdp->fd_dlomap;
   1288 
   1289 	CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t));
   1290 	for (i = 0, ffp = fdp->fd_dt->dt_ff; i < NDFDFILE; i++, ffp++) {
   1291 		*ffp = (fdfile_t *)fdp->fd_dfdfile[i];
   1292 		(void)fdfile_ctor(NULL, fdp->fd_dfdfile[i], PR_WAITOK);
   1293 	}
   1294 
   1295 	return 0;
   1296 }
   1297 
   1298 static void
   1299 filedesc_dtor(void *arg, void *obj)
   1300 {
   1301 	filedesc_t *fdp = obj;
   1302 	int i;
   1303 
   1304 	for (i = 0; i < NDFDFILE; i++) {
   1305 		fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
   1306 	}
   1307 
   1308 	mutex_destroy(&fdp->fd_lock);
   1309 }
   1310 
   1311 /*
   1312  * Make p2 share p1's filedesc structure.
   1313  */
   1314 void
   1315 fd_share(struct proc *p2)
   1316 {
   1317 	filedesc_t *fdp;
   1318 
   1319 	fdp = curlwp->l_fd;
   1320 	p2->p_fd = fdp;
   1321 	atomic_inc_uint(&fdp->fd_refcnt);
   1322 }
   1323 
   1324 /*
   1325  * Acquire a hold on a filedesc structure.
   1326  */
   1327 void
   1328 fd_hold(void)
   1329 {
   1330 
   1331 	atomic_inc_uint(&curlwp->l_fd->fd_refcnt);
   1332 }
   1333 
   1334 /*
   1335  * Copy a filedesc structure.
   1336  */
   1337 filedesc_t *
   1338 fd_copy(void)
   1339 {
   1340 	filedesc_t *newfdp, *fdp;
   1341 	fdfile_t *ff, **ffp, **nffp, *ff2;
   1342 	int i, j, numfiles, lastfile, newlast;
   1343 	file_t *fp;
   1344 	fdtab_t *newdt;
   1345 
   1346 	fdp = curproc->p_fd;
   1347 	newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
   1348 	newfdp->fd_refcnt = 1;
   1349 
   1350 #ifdef DIAGNOSTIC
   1351 	KASSERT(newfdp->fd_lastfile == -1);
   1352 	KASSERT(newfdp->fd_lastkqfile == -1);
   1353 	KASSERT(newfdp->fd_knhash == NULL);
   1354 	KASSERT(newfdp->fd_freefile == 0);
   1355 	KASSERT(newfdp->fd_exclose == false);
   1356 	KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
   1357 	KASSERT(newfdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1358 	for (i = 0; i < NDFDFILE; i++) {
   1359 		KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] ==
   1360 		    (fdfile_t *)&newfdp->fd_dfdfile[i]);
   1361 	}
   1362 	for (i = NDFDFILE; i < NDFILE; i++) {
   1363 		KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL);
   1364 	}
   1365 #endif	/* DIAGNOSTIC */
   1366 
   1367 	mutex_enter(&fdp->fd_lock);
   1368 	fd_checkmaps(fdp);
   1369 	numfiles = fdp->fd_dt->dt_nfiles;
   1370 	lastfile = fdp->fd_lastfile;
   1371 
   1372 	/*
   1373 	 * If the number of open files fits in the internal arrays
   1374 	 * of the open file structure, use them, otherwise allocate
   1375 	 * additional memory for the number of descriptors currently
   1376 	 * in use.
   1377 	 */
   1378 	if (lastfile < NDFILE) {
   1379 		i = NDFILE;
   1380 		newdt = newfdp->fd_dt;
   1381 		KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
   1382 	} else {
   1383 		/*
   1384 		 * Compute the smallest multiple of NDEXTENT needed
   1385 		 * for the file descriptors currently in use,
   1386 		 * allowing the table to shrink.
   1387 		 */
   1388 		i = numfiles;
   1389 		while (i >= 2 * NDEXTENT && i > lastfile * 2) {
   1390 			i /= 2;
   1391 		}
   1392 		KASSERT(i > NDFILE);
   1393 		newdt = fd_dtab_alloc(i);
   1394 		newfdp->fd_dt = newdt;
   1395 		memcpy(newdt->dt_ff, newfdp->fd_dtbuiltin.dt_ff,
   1396 		    NDFDFILE * sizeof(fdfile_t **));
   1397 		memset(newdt->dt_ff + NDFDFILE, 0,
   1398 		    (i - NDFDFILE) * sizeof(fdfile_t **));
   1399 	}
   1400 	if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
   1401 		newfdp->fd_himap = newfdp->fd_dhimap;
   1402 		newfdp->fd_lomap = newfdp->fd_dlomap;
   1403 	} else {
   1404 		fd_map_alloc(i, &newfdp->fd_lomap, &newfdp->fd_himap);
   1405 		KASSERT(i >= NDENTRIES * NDENTRIES);
   1406 		memset(newfdp->fd_himap, 0, NDHISLOTS(i)*sizeof(uint32_t));
   1407 		memset(newfdp->fd_lomap, 0, NDLOSLOTS(i)*sizeof(uint32_t));
   1408 	}
   1409 	newfdp->fd_freefile = fdp->fd_freefile;
   1410 	newfdp->fd_exclose = fdp->fd_exclose;
   1411 
   1412 	ffp = fdp->fd_dt->dt_ff;
   1413 	nffp = newdt->dt_ff;
   1414 	newlast = -1;
   1415 	for (i = 0; i <= (int)lastfile; i++, ffp++, nffp++) {
   1416 		KASSERT(i >= NDFDFILE ||
   1417 		    *nffp == (fdfile_t *)newfdp->fd_dfdfile[i]);
   1418 		ff = *ffp;
   1419 		if (ff == NULL || (fp = ff->ff_file) == NULL) {
   1420 			/* Descriptor unused, or descriptor half open. */
   1421 			KASSERT(!fd_isused(newfdp, i));
   1422 			continue;
   1423 		}
   1424 		if (__predict_false(fp->f_type == DTYPE_KQUEUE)) {
   1425 			/* kqueue descriptors cannot be copied. */
   1426 			continue;
   1427 		}
   1428 		/* It's active: add a reference to the file. */
   1429 		mutex_enter(&fp->f_lock);
   1430 		fp->f_count++;
   1431 		mutex_exit(&fp->f_lock);
   1432 
   1433 		/* Allocate an fdfile_t to represent it. */
   1434 		if (i >= NDFDFILE) {
   1435 			ff2 = pool_cache_get(fdfile_cache, PR_WAITOK);
   1436 			*nffp = ff2;
   1437 		} else {
   1438 			ff2 = newdt->dt_ff[i];
   1439 		}
   1440 		ff2->ff_file = fp;
   1441 		ff2->ff_exclose = ff->ff_exclose;
   1442 		ff2->ff_allocated = true;
   1443 
   1444 		/* Fix up bitmaps. */
   1445 		j = i >> NDENTRYSHIFT;
   1446 		KASSERT((newfdp->fd_lomap[j] & (1 << (i & NDENTRYMASK))) == 0);
   1447 		newfdp->fd_lomap[j] |= 1 << (i & NDENTRYMASK);
   1448 		if (__predict_false(newfdp->fd_lomap[j] == ~0)) {
   1449 			KASSERT((newfdp->fd_himap[j >> NDENTRYSHIFT] &
   1450 			    (1 << (j & NDENTRYMASK))) == 0);
   1451 			newfdp->fd_himap[j >> NDENTRYSHIFT] |=
   1452 			    1 << (j & NDENTRYMASK);
   1453 		}
   1454 		newlast = i;
   1455 	}
   1456 	KASSERT(newdt->dt_ff[0] == (fdfile_t *)newfdp->fd_dfdfile[0]);
   1457 	newfdp->fd_lastfile = newlast;
   1458 	fd_checkmaps(newfdp);
   1459 	mutex_exit(&fdp->fd_lock);
   1460 
   1461 	return (newfdp);
   1462 }
   1463 
   1464 /*
   1465  * Release a filedesc structure.
   1466  */
   1467 void
   1468 fd_free(void)
   1469 {
   1470 	filedesc_t *fdp;
   1471 	fdfile_t *ff;
   1472 	file_t *fp;
   1473 	int fd, nf;
   1474 	fdtab_t *dt;
   1475 
   1476 	fdp = curlwp->l_fd;
   1477 
   1478 	KASSERT(fdp->fd_dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
   1479 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1480 	KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
   1481 
   1482 #ifndef __HAVE_ATOMIC_AS_MEMBAR
   1483 	membar_exit();
   1484 #endif
   1485 	if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
   1486 		return;
   1487 
   1488 	/*
   1489 	 * Close any files that the process holds open.
   1490 	 */
   1491 	dt = fdp->fd_dt;
   1492 	fd_checkmaps(fdp);
   1493 #ifdef DEBUG
   1494 	fdp->fd_refcnt = -1; /* see fd_checkmaps */
   1495 #endif
   1496 	for (fd = 0, nf = dt->dt_nfiles; fd < nf; fd++) {
   1497 		ff = dt->dt_ff[fd];
   1498 		KASSERT(fd >= NDFDFILE ||
   1499 		    ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
   1500 		if (ff == NULL)
   1501 			continue;
   1502 		if ((fp = ff->ff_file) != NULL) {
   1503 			/*
   1504 			 * Must use fd_close() here if there is
   1505 			 * a reference from kqueue.
   1506 			 */
   1507 			if (__predict_true(ff->ff_refcnt == 0)) {
   1508 				ff->ff_file = NULL;
   1509 				ff->ff_exclose = false;
   1510 				ff->ff_allocated = false;
   1511 				closef(fp);
   1512 			} else {
   1513 				ff->ff_refcnt++;
   1514 				fd_close(fd);
   1515 			}
   1516 		}
   1517 		KASSERT(ff->ff_refcnt == 0);
   1518 		KASSERT(ff->ff_file == NULL);
   1519 		KASSERT(!ff->ff_exclose);
   1520 		KASSERT(!ff->ff_allocated);
   1521 		if (fd >= NDFDFILE) {
   1522 			pool_cache_put(fdfile_cache, ff);
   1523 			dt->dt_ff[fd] = NULL;
   1524 		}
   1525 	}
   1526 
   1527 	/*
   1528 	 * Clean out the descriptor table for the next user and return
   1529 	 * to the cache.
   1530 	 */
   1531 	if (__predict_false(dt != &fdp->fd_dtbuiltin)) {
   1532 		fd_dtab_free(fdp->fd_dt);
   1533 		/* Otherwise, done above. */
   1534 		memset(&fdp->fd_dtbuiltin.dt_ff[NDFDFILE], 0,
   1535 		    (NDFILE - NDFDFILE) * sizeof(fdp->fd_dtbuiltin.dt_ff[0]));
   1536 		fdp->fd_dt = &fdp->fd_dtbuiltin;
   1537 	}
   1538 	if (__predict_false(NDHISLOTS(nf) > NDHISLOTS(NDFILE))) {
   1539 		KASSERT(fdp->fd_himap != fdp->fd_dhimap);
   1540 		KASSERT(fdp->fd_lomap != fdp->fd_dlomap);
   1541 		fd_map_free(nf, fdp->fd_lomap, fdp->fd_himap);
   1542 	}
   1543 	if (__predict_false(fdp->fd_knhash != NULL)) {
   1544 		hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask);
   1545 		fdp->fd_knhash = NULL;
   1546 		fdp->fd_knhashmask = 0;
   1547 	} else {
   1548 		KASSERT(fdp->fd_knhashmask == 0);
   1549 	}
   1550 	fdp->fd_dt = &fdp->fd_dtbuiltin;
   1551 	fdp->fd_lastkqfile = -1;
   1552 	fdp->fd_lastfile = -1;
   1553 	fdp->fd_freefile = 0;
   1554 	fdp->fd_exclose = false;
   1555 	memset(&fdp->fd_startzero, 0, sizeof(*fdp) -
   1556 	    offsetof(filedesc_t, fd_startzero));
   1557 	fdp->fd_himap = fdp->fd_dhimap;
   1558 	fdp->fd_lomap = fdp->fd_dlomap;
   1559 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
   1560 	KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
   1561 	KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
   1562 #ifdef DEBUG
   1563 	fdp->fd_refcnt = 0; /* see fd_checkmaps */
   1564 #endif
   1565 	fd_checkmaps(fdp);
   1566 	pool_cache_put(filedesc_cache, fdp);
   1567 }
   1568 
   1569 /*
   1570  * File Descriptor pseudo-device driver (/dev/fd/).
   1571  *
   1572  * Opening minor device N dup()s the file (if any) connected to file
   1573  * descriptor N belonging to the calling process.  Note that this driver
   1574  * consists of only the ``open()'' routine, because all subsequent
   1575  * references to this file will be direct to the other driver.
   1576  */
   1577 static int
   1578 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
   1579 {
   1580 
   1581 	/*
   1582 	 * XXX Kludge: set dupfd to contain the value of the
   1583 	 * the file descriptor being sought for duplication. The error
   1584 	 * return ensures that the vnode for this device will be released
   1585 	 * by vn_open. Open will detect this special error and take the
   1586 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
   1587 	 * will simply report the error.
   1588 	 */
   1589 	l->l_dupfd = minor(dev);	/* XXX */
   1590 	return EDUPFD;
   1591 }
   1592 
   1593 /*
   1594  * Duplicate the specified descriptor to a free descriptor.
   1595  */
   1596 int
   1597 fd_dupopen(int old, int *new, int mode, int error)
   1598 {
   1599 	filedesc_t *fdp;
   1600 	fdfile_t *ff;
   1601 	file_t *fp;
   1602 	fdtab_t *dt;
   1603 
   1604 	if ((fp = fd_getfile(old)) == NULL) {
   1605 		return EBADF;
   1606 	}
   1607 	fdp = curlwp->l_fd;
   1608 	dt = fdp->fd_dt;
   1609 	ff = dt->dt_ff[old];
   1610 
   1611 	/*
   1612 	 * There are two cases of interest here.
   1613 	 *
   1614 	 * For EDUPFD simply dup (dfd) to file descriptor
   1615 	 * (indx) and return.
   1616 	 *
   1617 	 * For EMOVEFD steal away the file structure from (dfd) and
   1618 	 * store it in (indx).  (dfd) is effectively closed by
   1619 	 * this operation.
   1620 	 *
   1621 	 * Any other error code is just returned.
   1622 	 */
   1623 	switch (error) {
   1624 	case EDUPFD:
   1625 		/*
   1626 		 * Check that the mode the file is being opened for is a
   1627 		 * subset of the mode of the existing descriptor.
   1628 		 */
   1629 		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
   1630 			error = EACCES;
   1631 			break;
   1632 		}
   1633 
   1634 		/* Copy it. */
   1635 		error = fd_dup(fp, 0, new, ff->ff_exclose);
   1636 		break;
   1637 
   1638 	case EMOVEFD:
   1639 		/* Copy it. */
   1640 		error = fd_dup(fp, 0, new, ff->ff_exclose);
   1641 		if (error != 0) {
   1642 			break;
   1643 		}
   1644 
   1645 		/* Steal away the file pointer from 'old'. */
   1646 		(void)fd_close(old);
   1647 		return 0;
   1648 	}
   1649 
   1650 	fd_putfile(old);
   1651 	return error;
   1652 }
   1653 
   1654 /*
   1655  * Sets descriptor owner. If the owner is a process, 'pgid'
   1656  * is set to positive value, process ID. If the owner is process group,
   1657  * 'pgid' is set to -pg_id.
   1658  */
   1659 int
   1660 fsetown(pid_t *pgid, u_long cmd, const void *data)
   1661 {
   1662 	int id = *(const int *)data;
   1663 	int error;
   1664 
   1665 	switch (cmd) {
   1666 	case TIOCSPGRP:
   1667 		if (id < 0)
   1668 			return (EINVAL);
   1669 		id = -id;
   1670 		break;
   1671 	default:
   1672 		break;
   1673 	}
   1674 
   1675 	if (id > 0 && !pfind(id))
   1676 		return (ESRCH);
   1677 	else if (id < 0 && (error = pgid_in_session(curproc, -id)))
   1678 		return (error);
   1679 
   1680 	*pgid = id;
   1681 	return (0);
   1682 }
   1683 
   1684 /*
   1685  * Return descriptor owner information. If the value is positive,
   1686  * it's process ID. If it's negative, it's process group ID and
   1687  * needs the sign removed before use.
   1688  */
   1689 int
   1690 fgetown(pid_t pgid, u_long cmd, void *data)
   1691 {
   1692 
   1693 	switch (cmd) {
   1694 	case TIOCGPGRP:
   1695 		*(int *)data = -pgid;
   1696 		break;
   1697 	default:
   1698 		*(int *)data = pgid;
   1699 		break;
   1700 	}
   1701 	return (0);
   1702 }
   1703 
   1704 /*
   1705  * Send signal to descriptor owner, either process or process group.
   1706  */
   1707 void
   1708 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
   1709 {
   1710 	ksiginfo_t ksi;
   1711 
   1712 	KASSERT(!cpu_intr_p());
   1713 
   1714 	if (pgid == 0) {
   1715 		return;
   1716 	}
   1717 
   1718 	KSI_INIT(&ksi);
   1719 	ksi.ksi_signo = signo;
   1720 	ksi.ksi_code = code;
   1721 	ksi.ksi_band = band;
   1722 
   1723 	mutex_enter(proc_lock);
   1724 	if (pgid > 0) {
   1725 		struct proc *p1;
   1726 
   1727 		p1 = p_find(pgid, PFIND_LOCKED);
   1728 		if (p1 != NULL) {
   1729 			kpsignal(p1, &ksi, fdescdata);
   1730 		}
   1731 	} else {
   1732 		struct pgrp *pgrp;
   1733 
   1734 		KASSERT(pgid < 0);
   1735 		pgrp = pg_find(-pgid, PFIND_LOCKED);
   1736 		if (pgrp != NULL) {
   1737 			kpgsignal(pgrp, &ksi, fdescdata, 0);
   1738 		}
   1739 	}
   1740 	mutex_exit(proc_lock);
   1741 }
   1742 
   1743 int
   1744 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
   1745 	 void *data)
   1746 {
   1747 
   1748 	fp->f_flag = flag;
   1749 	fp->f_type = DTYPE_MISC;
   1750 	fp->f_ops = fops;
   1751 	fp->f_data = data;
   1752 	curlwp->l_dupfd = fd;
   1753 	fd_affix(curproc, fp, fd);
   1754 
   1755 	return EMOVEFD;
   1756 }
   1757 
   1758 int
   1759 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
   1760 {
   1761 
   1762 	if (cmd == F_SETFL)
   1763 		return 0;
   1764 
   1765 	return EOPNOTSUPP;
   1766 }
   1767 
   1768 int
   1769 fnullop_poll(file_t *fp, int which)
   1770 {
   1771 
   1772 	return 0;
   1773 }
   1774 
   1775 int
   1776 fnullop_kqfilter(file_t *fp, struct knote *kn)
   1777 {
   1778 
   1779 	return 0;
   1780 }
   1781 
   1782 void
   1783 fnullop_drain(file_t *fp)
   1784 {
   1785 
   1786 }
   1787 
   1788 int
   1789 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
   1790 	    kauth_cred_t cred, int flags)
   1791 {
   1792 
   1793 	return EOPNOTSUPP;
   1794 }
   1795 
   1796 int
   1797 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
   1798 	     kauth_cred_t cred, int flags)
   1799 {
   1800 
   1801 	return EOPNOTSUPP;
   1802 }
   1803 
   1804 int
   1805 fbadop_ioctl(file_t *fp, u_long com, void *data)
   1806 {
   1807 
   1808 	return EOPNOTSUPP;
   1809 }
   1810 
   1811 int
   1812 fbadop_stat(file_t *fp, struct stat *sb)
   1813 {
   1814 
   1815 	return EOPNOTSUPP;
   1816 }
   1817 
   1818 int
   1819 fbadop_close(file_t *fp)
   1820 {
   1821 
   1822 	return EOPNOTSUPP;
   1823 }
   1824