xref: /netbsd-src/sys/kern/kern_descrip.c (revision 3816d47b2c42fcd6e549e3407f842a5b1a1d23ad)
1 /*	$NetBSD: kern_descrip.c,v 1.202 2009/12/20 09:36:05 dsl 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.202 2009/12/20 09:36:05 dsl 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_refcnt == 0);
857 		KASSERT(dt->dt_ff[i]->ff_file == NULL);
858 		fd_used(fdp, i);
859 		if (want <= fdp->fd_freefile) {
860 			fdp->fd_freefile = i;
861 		}
862 		*result = i;
863 		KASSERT(i >= NDFDFILE ||
864 		    dt->dt_ff[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
865 		fd_checkmaps(fdp);
866 		mutex_exit(&fdp->fd_lock);
867 		return 0;
868 	}
869 
870 	/* No space in current array.  Let the caller expand and retry. */
871 	error = (dt->dt_nfiles >= lim) ? EMFILE : ENOSPC;
872 	mutex_exit(&fdp->fd_lock);
873 	return error;
874 }
875 
876 /*
877  * Allocate memory for a descriptor table.
878  */
879 static fdtab_t *
880 fd_dtab_alloc(int n)
881 {
882 	fdtab_t *dt;
883 	size_t sz;
884 
885 	KASSERT(n > NDFILE);
886 
887 	sz = sizeof(*dt) + (n - NDFILE) * sizeof(dt->dt_ff[0]);
888 	dt = kmem_alloc(sz, KM_SLEEP);
889 #ifdef DIAGNOSTIC
890 	memset(dt, 0xff, sz);
891 #endif
892 	dt->dt_nfiles = n;
893 	dt->dt_link = NULL;
894 	return dt;
895 }
896 
897 /*
898  * Free a descriptor table, and all tables linked for deferred free.
899  */
900 static void
901 fd_dtab_free(fdtab_t *dt)
902 {
903 	fdtab_t *next;
904 	size_t sz;
905 
906 	do {
907 		next = dt->dt_link;
908 		KASSERT(dt->dt_nfiles > NDFILE);
909 		sz = sizeof(*dt) +
910 		    (dt->dt_nfiles - NDFILE) * sizeof(dt->dt_ff[0]);
911 #ifdef DIAGNOSTIC
912 		memset(dt, 0xff, sz);
913 #endif
914 		kmem_free(dt, sz);
915 		dt = next;
916 	} while (dt != NULL);
917 }
918 
919 /*
920  * Allocate descriptor bitmap.
921  */
922 static void
923 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
924 {
925 	uint8_t *ptr;
926 	size_t szlo, szhi;
927 
928 	KASSERT(n > NDENTRIES);
929 
930 	szlo = NDLOSLOTS(n) * sizeof(uint32_t);
931 	szhi = NDHISLOTS(n) * sizeof(uint32_t);
932 	ptr = kmem_alloc(szlo + szhi, KM_SLEEP);
933 	*lo = (uint32_t *)ptr;
934 	*hi = (uint32_t *)(ptr + szlo);
935 }
936 
937 /*
938  * Free descriptor bitmap.
939  */
940 static void
941 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
942 {
943 	size_t szlo, szhi;
944 
945 	KASSERT(n > NDENTRIES);
946 
947 	szlo = NDLOSLOTS(n) * sizeof(uint32_t);
948 	szhi = NDHISLOTS(n) * sizeof(uint32_t);
949 	KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo));
950 	kmem_free(lo, szlo + szhi);
951 }
952 
953 /*
954  * Expand a process' descriptor table.
955  */
956 void
957 fd_tryexpand(proc_t *p)
958 {
959 	filedesc_t *fdp;
960 	int i, numfiles, oldnfiles;
961 	fdtab_t *newdt, *dt;
962 	uint32_t *newhimap, *newlomap;
963 
964 	KASSERT(p == curproc || p == &proc0);
965 
966 	fdp = p->p_fd;
967 	newhimap = NULL;
968 	newlomap = NULL;
969 	oldnfiles = fdp->fd_dt->dt_nfiles;
970 
971 	if (oldnfiles < NDEXTENT)
972 		numfiles = NDEXTENT;
973 	else
974 		numfiles = 2 * oldnfiles;
975 
976 	newdt = fd_dtab_alloc(numfiles);
977 	if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
978 		fd_map_alloc(numfiles, &newlomap, &newhimap);
979 	}
980 
981 	mutex_enter(&fdp->fd_lock);
982 	dt = fdp->fd_dt;
983 	KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
984 	if (dt->dt_nfiles != oldnfiles) {
985 		/* fdp changed; caller must retry */
986 		mutex_exit(&fdp->fd_lock);
987 		fd_dtab_free(newdt);
988 		if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
989 			fd_map_free(numfiles, newlomap, newhimap);
990 		}
991 		return;
992 	}
993 
994 	/* Copy the existing descriptor table and zero the new portion. */
995 	i = sizeof(fdfile_t *) * oldnfiles;
996 	memcpy(newdt->dt_ff, dt->dt_ff, i);
997 	memset((uint8_t *)newdt->dt_ff + i, 0,
998 	    numfiles * sizeof(fdfile_t *) - i);
999 
1000 	/*
1001 	 * Link old descriptor array into list to be discarded.  We defer
1002 	 * freeing until the last reference to the descriptor table goes
1003 	 * away (usually process exit).  This allows us to do lockless
1004 	 * lookups in fd_getfile().
1005 	 */
1006 	if (oldnfiles > NDFILE) {
1007 		if (fdp->fd_refcnt > 1) {
1008 			newdt->dt_link = dt;
1009 		} else {
1010 			fd_dtab_free(dt);
1011 		}
1012 	}
1013 
1014 	if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
1015 		i = NDHISLOTS(oldnfiles) * sizeof(uint32_t);
1016 		memcpy(newhimap, fdp->fd_himap, i);
1017 		memset((uint8_t *)newhimap + i, 0,
1018 		    NDHISLOTS(numfiles) * sizeof(uint32_t) - i);
1019 
1020 		i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t);
1021 		memcpy(newlomap, fdp->fd_lomap, i);
1022 		memset((uint8_t *)newlomap + i, 0,
1023 		    NDLOSLOTS(numfiles) * sizeof(uint32_t) - i);
1024 
1025 		if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
1026 			fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
1027 		}
1028 		fdp->fd_himap = newhimap;
1029 		fdp->fd_lomap = newlomap;
1030 	}
1031 
1032 	/*
1033 	 * All other modifications must become globally visible before
1034 	 * the change to fd_dt.  See fd_getfile().
1035 	 */
1036 	membar_producer();
1037 	fdp->fd_dt = newdt;
1038 	KASSERT(newdt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1039 	fd_checkmaps(fdp);
1040 	mutex_exit(&fdp->fd_lock);
1041 }
1042 
1043 /*
1044  * Create a new open file structure and allocate a file descriptor
1045  * for the current process.
1046  */
1047 int
1048 fd_allocfile(file_t **resultfp, int *resultfd)
1049 {
1050 	kauth_cred_t cred;
1051 	file_t *fp;
1052 	proc_t *p;
1053 	int error;
1054 
1055 	p = curproc;
1056 
1057 	while ((error = fd_alloc(p, 0, resultfd)) != 0) {
1058 		if (error != ENOSPC) {
1059 			return error;
1060 		}
1061 		fd_tryexpand(p);
1062 	}
1063 
1064 	fp = pool_cache_get(file_cache, PR_WAITOK);
1065 	if (fp == NULL) {
1066 		return ENFILE;
1067 	}
1068 	KASSERT(fp->f_count == 0);
1069 	KASSERT(fp->f_msgcount == 0);
1070 	KASSERT(fp->f_unpcount == 0);
1071 
1072 	/* Replace cached credentials if not what we need. */
1073 	cred = curlwp->l_cred;
1074 	if (__predict_false(cred != fp->f_cred)) {
1075 		kauth_cred_free(fp->f_cred);
1076 		kauth_cred_hold(cred);
1077 		fp->f_cred = cred;
1078 	}
1079 
1080 	/*
1081 	 * Don't allow recycled files to be scanned.
1082 	 * See uipc_usrreq.c.
1083 	 */
1084 	if (__predict_false((fp->f_flag & FSCAN) != 0)) {
1085 		mutex_enter(&fp->f_lock);
1086 		atomic_and_uint(&fp->f_flag, ~FSCAN);
1087 		mutex_exit(&fp->f_lock);
1088 	}
1089 
1090 	fp->f_advice = 0;
1091 	fp->f_offset = 0;
1092 	*resultfp = fp;
1093 
1094 	return 0;
1095 }
1096 
1097 /*
1098  * Successful creation of a new descriptor: make visible to the process.
1099  */
1100 void
1101 fd_affix(proc_t *p, file_t *fp, unsigned fd)
1102 {
1103 	fdfile_t *ff;
1104 	filedesc_t *fdp;
1105 
1106 	KASSERT(p == curproc || p == &proc0);
1107 
1108 	/* Add a reference to the file structure. */
1109 	mutex_enter(&fp->f_lock);
1110 	fp->f_count++;
1111 	mutex_exit(&fp->f_lock);
1112 
1113 	/*
1114 	 * Insert the new file into the descriptor slot.
1115 	 *
1116 	 * The memory barriers provided by lock activity in this routine
1117 	 * ensure that any updates to the file structure become globally
1118 	 * visible before the file becomes visible to other LWPs in the
1119 	 * current process.
1120 	 */
1121 	fdp = p->p_fd;
1122 	ff = fdp->fd_dt->dt_ff[fd];
1123 
1124 	KASSERT(ff != NULL);
1125 	KASSERT(ff->ff_file == NULL);
1126 	KASSERT(ff->ff_allocated);
1127 	KASSERT(fd_isused(fdp, fd));
1128 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1129 
1130 	/* No need to lock in order to make file initially visible. */
1131 	ff->ff_file = fp;
1132 }
1133 
1134 /*
1135  * Abort creation of a new descriptor: free descriptor slot and file.
1136  */
1137 void
1138 fd_abort(proc_t *p, file_t *fp, unsigned fd)
1139 {
1140 	filedesc_t *fdp;
1141 	fdfile_t *ff;
1142 
1143 	KASSERT(p == curproc || p == &proc0);
1144 
1145 	fdp = p->p_fd;
1146 	ff = fdp->fd_dt->dt_ff[fd];
1147 
1148 	KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1149 
1150 	mutex_enter(&fdp->fd_lock);
1151 	KASSERT(fd_isused(fdp, fd));
1152 	fd_unused(fdp, fd);
1153 	mutex_exit(&fdp->fd_lock);
1154 
1155 	if (fp != NULL) {
1156 		KASSERT(fp->f_count == 0);
1157 		KASSERT(fp->f_cred != NULL);
1158 		pool_cache_put(file_cache, fp);
1159 	}
1160 }
1161 
1162 static int
1163 file_ctor(void *arg, void *obj, int flags)
1164 {
1165 	file_t *fp = obj;
1166 
1167 	memset(fp, 0, sizeof(*fp));
1168 
1169 	mutex_enter(&filelist_lock);
1170 	if (__predict_false(nfiles >= maxfiles)) {
1171 		mutex_exit(&filelist_lock);
1172 		tablefull("file", "increase kern.maxfiles or MAXFILES");
1173 		return ENFILE;
1174 	}
1175 	nfiles++;
1176 	LIST_INSERT_HEAD(&filehead, fp, f_list);
1177 	mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1178 	fp->f_cred = curlwp->l_cred;
1179 	kauth_cred_hold(fp->f_cred);
1180 	mutex_exit(&filelist_lock);
1181 
1182 	return 0;
1183 }
1184 
1185 static void
1186 file_dtor(void *arg, void *obj)
1187 {
1188 	file_t *fp = obj;
1189 
1190 	mutex_enter(&filelist_lock);
1191 	nfiles--;
1192 	LIST_REMOVE(fp, f_list);
1193 	mutex_exit(&filelist_lock);
1194 
1195 	kauth_cred_free(fp->f_cred);
1196 	mutex_destroy(&fp->f_lock);
1197 }
1198 
1199 static int
1200 fdfile_ctor(void *arg, void *obj, int flags)
1201 {
1202 	fdfile_t *ff = obj;
1203 
1204 	memset(ff, 0, sizeof(*ff));
1205 	cv_init(&ff->ff_closing, "fdclose");
1206 
1207 	return 0;
1208 }
1209 
1210 static void
1211 fdfile_dtor(void *arg, void *obj)
1212 {
1213 	fdfile_t *ff = obj;
1214 
1215 	cv_destroy(&ff->ff_closing);
1216 }
1217 
1218 file_t *
1219 fgetdummy(void)
1220 {
1221 	file_t *fp;
1222 
1223 	fp = kmem_alloc(sizeof(*fp), KM_SLEEP);
1224 	if (fp != NULL) {
1225 		memset(fp, 0, sizeof(*fp));
1226 		mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1227 	}
1228 	return fp;
1229 }
1230 
1231 void
1232 fputdummy(file_t *fp)
1233 {
1234 
1235 	mutex_destroy(&fp->f_lock);
1236 	kmem_free(fp, sizeof(*fp));
1237 }
1238 
1239 /*
1240  * Create an initial filedesc structure.
1241  */
1242 filedesc_t *
1243 fd_init(filedesc_t *fdp)
1244 {
1245 #ifdef DIAGNOSTIC
1246 	unsigned fd;
1247 #endif
1248 
1249 	if (__predict_true(fdp == NULL)) {
1250 		fdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1251 	} else {
1252 		/* XXXRUMP KASSERT(fdp == &filedesc0); */
1253 		filedesc_ctor(NULL, fdp, PR_WAITOK);
1254 	}
1255 
1256 #ifdef DIAGNOSTIC
1257 	KASSERT(fdp->fd_lastfile == -1);
1258 	KASSERT(fdp->fd_lastkqfile == -1);
1259 	KASSERT(fdp->fd_knhash == NULL);
1260 	KASSERT(fdp->fd_freefile == 0);
1261 	KASSERT(fdp->fd_exclose == false);
1262 	KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
1263 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1264 	for (fd = 0; fd < NDFDFILE; fd++) {
1265 		KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] ==
1266 		    (fdfile_t *)fdp->fd_dfdfile[fd]);
1267 	}
1268 	for (fd = NDFDFILE; fd < NDFILE; fd++) {
1269 		KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL);
1270 	}
1271 	KASSERT(fdp->fd_himap == fdp->fd_dhimap);
1272 	KASSERT(fdp->fd_lomap == fdp->fd_dlomap);
1273 #endif	/* DIAGNOSTIC */
1274 
1275 	fdp->fd_refcnt = 1;
1276 	fd_checkmaps(fdp);
1277 
1278 	return fdp;
1279 }
1280 
1281 /*
1282  * Initialize a file descriptor table.
1283  */
1284 static int
1285 filedesc_ctor(void *arg, void *obj, int flag)
1286 {
1287 	filedesc_t *fdp = obj;
1288 	fdfile_t **ffp;
1289 	int i;
1290 
1291 	memset(fdp, 0, sizeof(*fdp));
1292 	mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE);
1293 	fdp->fd_lastfile = -1;
1294 	fdp->fd_lastkqfile = -1;
1295 	fdp->fd_dt = &fdp->fd_dtbuiltin;
1296 	fdp->fd_dtbuiltin.dt_nfiles = NDFILE;
1297 	fdp->fd_himap = fdp->fd_dhimap;
1298 	fdp->fd_lomap = fdp->fd_dlomap;
1299 
1300 	CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t));
1301 	for (i = 0, ffp = fdp->fd_dt->dt_ff; i < NDFDFILE; i++, ffp++) {
1302 		*ffp = (fdfile_t *)fdp->fd_dfdfile[i];
1303 		(void)fdfile_ctor(NULL, fdp->fd_dfdfile[i], PR_WAITOK);
1304 	}
1305 
1306 	return 0;
1307 }
1308 
1309 static void
1310 filedesc_dtor(void *arg, void *obj)
1311 {
1312 	filedesc_t *fdp = obj;
1313 	int i;
1314 
1315 	for (i = 0; i < NDFDFILE; i++) {
1316 		fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
1317 	}
1318 
1319 	mutex_destroy(&fdp->fd_lock);
1320 }
1321 
1322 /*
1323  * Make p2 share p1's filedesc structure.
1324  */
1325 void
1326 fd_share(struct proc *p2)
1327 {
1328 	filedesc_t *fdp;
1329 
1330 	fdp = curlwp->l_fd;
1331 	p2->p_fd = fdp;
1332 	atomic_inc_uint(&fdp->fd_refcnt);
1333 }
1334 
1335 /*
1336  * Acquire a hold on a filedesc structure.
1337  */
1338 void
1339 fd_hold(lwp_t *l)
1340 {
1341 	filedesc_t *fdp = l->l_fd;
1342 
1343 	KASSERT(fdp == curlwp->l_fd || fdp == lwp0.l_fd);
1344 	atomic_inc_uint(&fdp->fd_refcnt);
1345 }
1346 
1347 /*
1348  * Copy a filedesc structure.
1349  */
1350 filedesc_t *
1351 fd_copy(void)
1352 {
1353 	filedesc_t *newfdp, *fdp;
1354 	fdfile_t *ff, **ffp, **nffp, *ff2;
1355 	int i, j, numfiles, lastfile, newlast;
1356 	file_t *fp;
1357 	fdtab_t *newdt;
1358 
1359 	fdp = curproc->p_fd;
1360 	newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1361 	newfdp->fd_refcnt = 1;
1362 
1363 #ifdef DIAGNOSTIC
1364 	KASSERT(newfdp->fd_lastfile == -1);
1365 	KASSERT(newfdp->fd_lastkqfile == -1);
1366 	KASSERT(newfdp->fd_knhash == NULL);
1367 	KASSERT(newfdp->fd_freefile == 0);
1368 	KASSERT(newfdp->fd_exclose == false);
1369 	KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1370 	KASSERT(newfdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1371 	for (i = 0; i < NDFDFILE; i++) {
1372 		KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] ==
1373 		    (fdfile_t *)&newfdp->fd_dfdfile[i]);
1374 	}
1375 	for (i = NDFDFILE; i < NDFILE; i++) {
1376 		KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL);
1377 	}
1378 #endif	/* DIAGNOSTIC */
1379 
1380 	mutex_enter(&fdp->fd_lock);
1381 	fd_checkmaps(fdp);
1382 	numfiles = fdp->fd_dt->dt_nfiles;
1383 	lastfile = fdp->fd_lastfile;
1384 
1385 	/*
1386 	 * If the number of open files fits in the internal arrays
1387 	 * of the open file structure, use them, otherwise allocate
1388 	 * additional memory for the number of descriptors currently
1389 	 * in use.
1390 	 */
1391 	if (lastfile < NDFILE) {
1392 		i = NDFILE;
1393 		newdt = newfdp->fd_dt;
1394 		KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1395 	} else {
1396 		/*
1397 		 * Compute the smallest multiple of NDEXTENT needed
1398 		 * for the file descriptors currently in use,
1399 		 * allowing the table to shrink.
1400 		 */
1401 		i = numfiles;
1402 		while (i >= 2 * NDEXTENT && i > lastfile * 2) {
1403 			i /= 2;
1404 		}
1405 		KASSERT(i > NDFILE);
1406 		newdt = fd_dtab_alloc(i);
1407 		newfdp->fd_dt = newdt;
1408 		memcpy(newdt->dt_ff, newfdp->fd_dtbuiltin.dt_ff,
1409 		    NDFDFILE * sizeof(fdfile_t **));
1410 		memset(newdt->dt_ff + NDFDFILE, 0,
1411 		    (i - NDFDFILE) * sizeof(fdfile_t **));
1412 	}
1413 	if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
1414 		newfdp->fd_himap = newfdp->fd_dhimap;
1415 		newfdp->fd_lomap = newfdp->fd_dlomap;
1416 	} else {
1417 		fd_map_alloc(i, &newfdp->fd_lomap, &newfdp->fd_himap);
1418 		KASSERT(i >= NDENTRIES * NDENTRIES);
1419 		memset(newfdp->fd_himap, 0, NDHISLOTS(i)*sizeof(uint32_t));
1420 		memset(newfdp->fd_lomap, 0, NDLOSLOTS(i)*sizeof(uint32_t));
1421 	}
1422 	newfdp->fd_freefile = fdp->fd_freefile;
1423 	newfdp->fd_exclose = fdp->fd_exclose;
1424 
1425 	ffp = fdp->fd_dt->dt_ff;
1426 	nffp = newdt->dt_ff;
1427 	newlast = -1;
1428 	for (i = 0; i <= (int)lastfile; i++, ffp++, nffp++) {
1429 		KASSERT(i >= NDFDFILE ||
1430 		    *nffp == (fdfile_t *)newfdp->fd_dfdfile[i]);
1431 		ff = *ffp;
1432 		if (ff == NULL || (fp = ff->ff_file) == NULL) {
1433 			/* Descriptor unused, or descriptor half open. */
1434 			KASSERT(!fd_isused(newfdp, i));
1435 			continue;
1436 		}
1437 		if (__predict_false(fp->f_type == DTYPE_KQUEUE)) {
1438 			/* kqueue descriptors cannot be copied. */
1439                        if (i < newfdp->fd_freefile)
1440                                newfdp->fd_freefile = i;
1441 			continue;
1442 		}
1443 		/* It's active: add a reference to the file. */
1444 		mutex_enter(&fp->f_lock);
1445 		fp->f_count++;
1446 		mutex_exit(&fp->f_lock);
1447 
1448 		/* Allocate an fdfile_t to represent it. */
1449 		if (i >= NDFDFILE) {
1450 			ff2 = pool_cache_get(fdfile_cache, PR_WAITOK);
1451 			*nffp = ff2;
1452 		} else {
1453 			ff2 = newdt->dt_ff[i];
1454 		}
1455 		ff2->ff_file = fp;
1456 		ff2->ff_exclose = ff->ff_exclose;
1457 		ff2->ff_allocated = true;
1458 
1459 		/* Fix up bitmaps. */
1460 		j = i >> NDENTRYSHIFT;
1461 		KASSERT((newfdp->fd_lomap[j] & (1 << (i & NDENTRYMASK))) == 0);
1462 		newfdp->fd_lomap[j] |= 1 << (i & NDENTRYMASK);
1463 		if (__predict_false(newfdp->fd_lomap[j] == ~0)) {
1464 			KASSERT((newfdp->fd_himap[j >> NDENTRYSHIFT] &
1465 			    (1 << (j & NDENTRYMASK))) == 0);
1466 			newfdp->fd_himap[j >> NDENTRYSHIFT] |=
1467 			    1 << (j & NDENTRYMASK);
1468 		}
1469 		newlast = i;
1470 	}
1471 	KASSERT(newdt->dt_ff[0] == (fdfile_t *)newfdp->fd_dfdfile[0]);
1472 	newfdp->fd_lastfile = newlast;
1473 	fd_checkmaps(newfdp);
1474 	mutex_exit(&fdp->fd_lock);
1475 
1476 	return (newfdp);
1477 }
1478 
1479 /*
1480  * Release a filedesc structure.
1481  */
1482 void
1483 fd_free(void)
1484 {
1485 	fdfile_t *ff;
1486 	file_t *fp;
1487 	int fd, nf;
1488 	fdtab_t *dt;
1489 	lwp_t * const l = curlwp;
1490 	filedesc_t * const fdp = l->l_fd;
1491 	const bool noadvlock = (l->l_proc->p_flag & PK_ADVLOCK) == 0;
1492 
1493 	KASSERT(fdp->fd_dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1494 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1495 	KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
1496 
1497 #ifndef __HAVE_ATOMIC_AS_MEMBAR
1498 	membar_exit();
1499 #endif
1500 	if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
1501 		return;
1502 
1503 	/*
1504 	 * Close any files that the process holds open.
1505 	 */
1506 	dt = fdp->fd_dt;
1507 	fd_checkmaps(fdp);
1508 #ifdef DEBUG
1509 	fdp->fd_refcnt = -1; /* see fd_checkmaps */
1510 #endif
1511 	for (fd = 0, nf = dt->dt_nfiles; fd < nf; fd++) {
1512 		ff = dt->dt_ff[fd];
1513 		KASSERT(fd >= NDFDFILE ||
1514 		    ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1515 		if (ff == NULL)
1516 			continue;
1517 		if ((fp = ff->ff_file) != NULL) {
1518 			/*
1519 			 * Must use fd_close() here if there is
1520 			 * a reference from kqueue or we might have posix
1521 			 * advisory locks.
1522 			 */
1523 			if (__predict_true(ff->ff_refcnt == 0) &&
1524 			    (noadvlock || fp->f_type != DTYPE_VNODE)) {
1525 				ff->ff_file = NULL;
1526 				ff->ff_exclose = false;
1527 				ff->ff_allocated = false;
1528 				closef(fp);
1529 			} else {
1530 				ff->ff_refcnt++;
1531 				fd_close(fd);
1532 			}
1533 		}
1534 		KASSERT(ff->ff_refcnt == 0);
1535 		KASSERT(ff->ff_file == NULL);
1536 		KASSERT(!ff->ff_exclose);
1537 		KASSERT(!ff->ff_allocated);
1538 		if (fd >= NDFDFILE) {
1539 			pool_cache_put(fdfile_cache, ff);
1540 			dt->dt_ff[fd] = NULL;
1541 		}
1542 	}
1543 
1544 	/*
1545 	 * Clean out the descriptor table for the next user and return
1546 	 * to the cache.
1547 	 */
1548 	if (__predict_false(dt != &fdp->fd_dtbuiltin)) {
1549 		fd_dtab_free(fdp->fd_dt);
1550 		/* Otherwise, done above. */
1551 		memset(&fdp->fd_dtbuiltin.dt_ff[NDFDFILE], 0,
1552 		    (NDFILE - NDFDFILE) * sizeof(fdp->fd_dtbuiltin.dt_ff[0]));
1553 		fdp->fd_dt = &fdp->fd_dtbuiltin;
1554 	}
1555 	if (__predict_false(NDHISLOTS(nf) > NDHISLOTS(NDFILE))) {
1556 		KASSERT(fdp->fd_himap != fdp->fd_dhimap);
1557 		KASSERT(fdp->fd_lomap != fdp->fd_dlomap);
1558 		fd_map_free(nf, fdp->fd_lomap, fdp->fd_himap);
1559 	}
1560 	if (__predict_false(fdp->fd_knhash != NULL)) {
1561 		hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask);
1562 		fdp->fd_knhash = NULL;
1563 		fdp->fd_knhashmask = 0;
1564 	} else {
1565 		KASSERT(fdp->fd_knhashmask == 0);
1566 	}
1567 	fdp->fd_dt = &fdp->fd_dtbuiltin;
1568 	fdp->fd_lastkqfile = -1;
1569 	fdp->fd_lastfile = -1;
1570 	fdp->fd_freefile = 0;
1571 	fdp->fd_exclose = false;
1572 	memset(&fdp->fd_startzero, 0, sizeof(*fdp) -
1573 	    offsetof(filedesc_t, fd_startzero));
1574 	fdp->fd_himap = fdp->fd_dhimap;
1575 	fdp->fd_lomap = fdp->fd_dlomap;
1576 	KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1577 	KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
1578 	KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
1579 #ifdef DEBUG
1580 	fdp->fd_refcnt = 0; /* see fd_checkmaps */
1581 #endif
1582 	fd_checkmaps(fdp);
1583 	pool_cache_put(filedesc_cache, fdp);
1584 }
1585 
1586 /*
1587  * File Descriptor pseudo-device driver (/dev/fd/).
1588  *
1589  * Opening minor device N dup()s the file (if any) connected to file
1590  * descriptor N belonging to the calling process.  Note that this driver
1591  * consists of only the ``open()'' routine, because all subsequent
1592  * references to this file will be direct to the other driver.
1593  */
1594 static int
1595 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
1596 {
1597 
1598 	/*
1599 	 * XXX Kludge: set dupfd to contain the value of the
1600 	 * the file descriptor being sought for duplication. The error
1601 	 * return ensures that the vnode for this device will be released
1602 	 * by vn_open. Open will detect this special error and take the
1603 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1604 	 * will simply report the error.
1605 	 */
1606 	l->l_dupfd = minor(dev);	/* XXX */
1607 	return EDUPFD;
1608 }
1609 
1610 /*
1611  * Duplicate the specified descriptor to a free descriptor.
1612  */
1613 int
1614 fd_dupopen(int old, int *new, int mode, int error)
1615 {
1616 	filedesc_t *fdp;
1617 	fdfile_t *ff;
1618 	file_t *fp;
1619 	fdtab_t *dt;
1620 
1621 	if ((fp = fd_getfile(old)) == NULL) {
1622 		return EBADF;
1623 	}
1624 	fdp = curlwp->l_fd;
1625 	dt = fdp->fd_dt;
1626 	ff = dt->dt_ff[old];
1627 
1628 	/*
1629 	 * There are two cases of interest here.
1630 	 *
1631 	 * For EDUPFD simply dup (dfd) to file descriptor
1632 	 * (indx) and return.
1633 	 *
1634 	 * For EMOVEFD steal away the file structure from (dfd) and
1635 	 * store it in (indx).  (dfd) is effectively closed by
1636 	 * this operation.
1637 	 *
1638 	 * Any other error code is just returned.
1639 	 */
1640 	switch (error) {
1641 	case EDUPFD:
1642 		/*
1643 		 * Check that the mode the file is being opened for is a
1644 		 * subset of the mode of the existing descriptor.
1645 		 */
1646 		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
1647 			error = EACCES;
1648 			break;
1649 		}
1650 
1651 		/* Copy it. */
1652 		error = fd_dup(fp, 0, new, ff->ff_exclose);
1653 		break;
1654 
1655 	case EMOVEFD:
1656 		/* Copy it. */
1657 		error = fd_dup(fp, 0, new, ff->ff_exclose);
1658 		if (error != 0) {
1659 			break;
1660 		}
1661 
1662 		/* Steal away the file pointer from 'old'. */
1663 		(void)fd_close(old);
1664 		return 0;
1665 	}
1666 
1667 	fd_putfile(old);
1668 	return error;
1669 }
1670 
1671 /*
1672  * Sets descriptor owner. If the owner is a process, 'pgid'
1673  * is set to positive value, process ID. If the owner is process group,
1674  * 'pgid' is set to -pg_id.
1675  */
1676 int
1677 fsetown(pid_t *pgid, u_long cmd, const void *data)
1678 {
1679 	int id = *(const int *)data;
1680 	int error;
1681 
1682 	switch (cmd) {
1683 	case TIOCSPGRP:
1684 		if (id < 0)
1685 			return (EINVAL);
1686 		id = -id;
1687 		break;
1688 	default:
1689 		break;
1690 	}
1691 
1692 	if (id > 0 && !pfind(id))
1693 		return (ESRCH);
1694 	else if (id < 0 && (error = pgid_in_session(curproc, -id)))
1695 		return (error);
1696 
1697 	*pgid = id;
1698 	return (0);
1699 }
1700 
1701 /*
1702  * Return descriptor owner information. If the value is positive,
1703  * it's process ID. If it's negative, it's process group ID and
1704  * needs the sign removed before use.
1705  */
1706 int
1707 fgetown(pid_t pgid, u_long cmd, void *data)
1708 {
1709 
1710 	switch (cmd) {
1711 	case TIOCGPGRP:
1712 		*(int *)data = -pgid;
1713 		break;
1714 	default:
1715 		*(int *)data = pgid;
1716 		break;
1717 	}
1718 	return (0);
1719 }
1720 
1721 /*
1722  * Send signal to descriptor owner, either process or process group.
1723  */
1724 void
1725 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
1726 {
1727 	ksiginfo_t ksi;
1728 
1729 	KASSERT(!cpu_intr_p());
1730 
1731 	if (pgid == 0) {
1732 		return;
1733 	}
1734 
1735 	KSI_INIT(&ksi);
1736 	ksi.ksi_signo = signo;
1737 	ksi.ksi_code = code;
1738 	ksi.ksi_band = band;
1739 
1740 	mutex_enter(proc_lock);
1741 	if (pgid > 0) {
1742 		struct proc *p1;
1743 
1744 		p1 = p_find(pgid, PFIND_LOCKED);
1745 		if (p1 != NULL) {
1746 			kpsignal(p1, &ksi, fdescdata);
1747 		}
1748 	} else {
1749 		struct pgrp *pgrp;
1750 
1751 		KASSERT(pgid < 0);
1752 		pgrp = pg_find(-pgid, PFIND_LOCKED);
1753 		if (pgrp != NULL) {
1754 			kpgsignal(pgrp, &ksi, fdescdata, 0);
1755 		}
1756 	}
1757 	mutex_exit(proc_lock);
1758 }
1759 
1760 int
1761 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
1762 	 void *data)
1763 {
1764 
1765 	fp->f_flag = flag;
1766 	fp->f_type = DTYPE_MISC;
1767 	fp->f_ops = fops;
1768 	fp->f_data = data;
1769 	curlwp->l_dupfd = fd;
1770 	fd_affix(curproc, fp, fd);
1771 
1772 	return EMOVEFD;
1773 }
1774 
1775 int
1776 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
1777 {
1778 
1779 	if (cmd == F_SETFL)
1780 		return 0;
1781 
1782 	return EOPNOTSUPP;
1783 }
1784 
1785 int
1786 fnullop_poll(file_t *fp, int which)
1787 {
1788 
1789 	return 0;
1790 }
1791 
1792 int
1793 fnullop_kqfilter(file_t *fp, struct knote *kn)
1794 {
1795 
1796 	return 0;
1797 }
1798 
1799 void
1800 fnullop_restart(file_t *fp)
1801 {
1802 
1803 }
1804 
1805 int
1806 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
1807 	    kauth_cred_t cred, int flags)
1808 {
1809 
1810 	return EOPNOTSUPP;
1811 }
1812 
1813 int
1814 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
1815 	     kauth_cred_t cred, int flags)
1816 {
1817 
1818 	return EOPNOTSUPP;
1819 }
1820 
1821 int
1822 fbadop_ioctl(file_t *fp, u_long com, void *data)
1823 {
1824 
1825 	return EOPNOTSUPP;
1826 }
1827 
1828 int
1829 fbadop_stat(file_t *fp, struct stat *sb)
1830 {
1831 
1832 	return EOPNOTSUPP;
1833 }
1834 
1835 int
1836 fbadop_close(file_t *fp)
1837 {
1838 
1839 	return EOPNOTSUPP;
1840 }
1841