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