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