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