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