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