No empty .Rs/.Re
[netbsd-mini2440.git] / sys / kern / kern_descrip.c
blobe9d288850811c9dacffc2107efe5700485f9b2bb
1 /* $NetBSD: kern_descrip.c,v 1.201 2009/12/09 21:32:59 dsl Exp $ */
3 /*-
4 * Copyright (c) 2008, 2009 The NetBSD Foundation, Inc.
5 * All rights reserved.
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
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.
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.
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.
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.
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.
65 * @(#)kern_descrip.c 8.8 (Berkeley) 2/14/95
69 * File descriptor management.
72 #include <sys/cdefs.h>
73 __KERNEL_RCSID(0, "$NetBSD: kern_descrip.c,v 1.201 2009/12/09 21:32:59 dsl Exp $");
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>
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 *);
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 */
110 static pool_cache_t filedesc_cache;
111 static pool_cache_t file_cache;
112 static pool_cache_t fdfile_cache;
114 const struct cdevsw filedesc_cdevsw = {
115 filedescopen, noclose, noread, nowrite, noioctl,
116 nostop, notty, nopoll, nommap, nokqfilter, D_OTHER | D_MPSAFE,
119 /* For ease of reading. */
120 __strong_alias(fd_putvnode,fd_putfile)
121 __strong_alias(fd_putsock,fd_putfile)
124 * Initialize the descriptor system.
126 void
127 fd_sys_init(void)
130 mutex_init(&filelist_lock, MUTEX_DEFAULT, IPL_NONE);
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);
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);
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);
147 static bool
148 fd_isused(filedesc_t *fdp, unsigned fd)
150 u_int off = fd >> NDENTRYSHIFT;
152 KASSERT(fd < fdp->fd_dt->dt_nfiles);
154 return (fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0;
158 * Verify that the bitmaps match the descriptor table.
160 static inline void
161 fd_checkmaps(filedesc_t *fdp)
163 #ifdef DEBUG
164 fdtab_t *dt;
165 u_int fd;
167 dt = fdp->fd_dt;
168 if (fdp->fd_refcnt == -1) {
170 * fd_free tears down the table without maintaining its bitmap.
172 return;
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]);
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));
185 #else /* DEBUG */
186 /* nothing */
187 #endif /* DEBUG */
190 static int
191 fd_next_zero(filedesc_t *fdp, uint32_t *bitmap, int want, u_int bits)
193 int i, off, maxoff;
194 uint32_t sub;
196 KASSERT(mutex_owned(&fdp->fd_lock));
198 fd_checkmaps(fdp);
200 if (want > bits)
201 return -1;
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++;
212 maxoff = NDLOSLOTS(bits);
213 while (off < maxoff) {
214 if ((sub = bitmap[off]) != ~0)
215 goto found;
216 off++;
219 return (-1);
221 found:
222 return (off << NDENTRYSHIFT) + ffs(~sub) - 1;
225 static int
226 fd_last_set(filedesc_t *fd, int last)
228 int off, i;
229 fdfile_t **ff = fd->fd_dt->dt_ff;
230 uint32_t *bitmap = fd->fd_lomap;
232 KASSERT(mutex_owned(&fd->fd_lock));
234 fd_checkmaps(fd);
236 off = (last - 1) >> NDENTRYSHIFT;
238 while (off >= 0 && !bitmap[off])
239 off--;
241 if (off < 0)
242 return (-1);
244 i = ((off + 1) << NDENTRYSHIFT) - 1;
245 if (i >= last)
246 i = last - 1;
248 /* XXX should use bitmap */
249 while (i > 0 && (ff[i] == NULL || !ff[i]->ff_allocated))
250 i--;
252 return (i);
255 static inline void
256 fd_used(filedesc_t *fdp, unsigned fd)
258 u_int off = fd >> NDENTRYSHIFT;
259 fdfile_t *ff;
261 ff = fdp->fd_dt->dt_ff[fd];
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);
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);
277 if ((int)fd > fdp->fd_lastfile) {
278 fdp->fd_lastfile = fd;
281 fd_checkmaps(fdp);
284 static inline void
285 fd_unused(filedesc_t *fdp, unsigned fd)
287 u_int off = fd >> NDENTRYSHIFT;
288 fdfile_t *ff;
290 ff = fdp->fd_dt->dt_ff[fd];
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.
297 * KASSERT(mutex_owned(&fdp->fd_lock));
299 KASSERT(ff != NULL);
300 KASSERT(ff->ff_file == NULL);
301 KASSERT(ff->ff_allocated);
303 if (fd < fdp->fd_freefile) {
304 fdp->fd_freefile = fd;
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));
313 KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0);
314 fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
315 ff->ff_allocated = 0;
317 KASSERT(fd <= fdp->fd_lastfile);
318 if (fd == fdp->fd_lastfile) {
319 fdp->fd_lastfile = fd_last_set(fdp, fd);
321 fd_checkmaps(fdp);
325 * Look up the file structure corresponding to a file descriptor
326 * and return the file, holding a reference on the descriptor.
328 inline file_t *
329 fd_getfile(unsigned fd)
331 filedesc_t *fdp;
332 fdfile_t *ff;
333 file_t *fp;
334 fdtab_t *dt;
337 * Look up the fdfile structure representing this descriptor.
338 * We are doing this unlocked. See fd_tryexpand().
340 fdp = curlwp->l_fd;
341 dt = fdp->fd_dt;
342 if (__predict_false(fd >= dt->dt_nfiles)) {
343 return NULL;
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;
351 /* Now get a reference to the descriptor. */
352 if (fdp->fd_refcnt == 1) {
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).
358 ff->ff_refcnt++;
359 } else {
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.
365 atomic_inc_uint(&ff->ff_refcnt);
366 #ifndef __HAVE_ATOMIC_AS_MEMBAR
367 membar_enter();
368 #endif
372 * If the file is not open or is being closed then put the
373 * reference back.
375 fp = ff->ff_file;
376 if (__predict_true(fp != NULL)) {
377 return fp;
379 fd_putfile(fd);
380 return NULL;
384 * Release a reference to a file descriptor acquired with fd_getfile().
386 void
387 fd_putfile(unsigned fd)
389 filedesc_t *fdp;
390 fdfile_t *ff;
391 u_int u, v;
393 fdp = curlwp->l_fd;
394 ff = fdp->fd_dt->dt_ff[fd];
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]);
401 if (fdp->fd_refcnt == 1) {
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).
407 if (__predict_false((ff->ff_refcnt & FR_CLOSING) != 0)) {
408 fd_close(fd);
409 return;
411 ff->ff_refcnt--;
412 return;
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.
422 #ifndef __HAVE_ATOMIC_AS_MEMBAR
423 membar_exit();
424 #endif
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.
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;
436 if (__predict_false((v & FR_CLOSING) != 0)) {
437 break;
441 /* Another thread is waiting to close the file: join it. */
442 (void)fd_close(fd);
446 * Convenience wrapper around fd_getfile() that returns reference
447 * to a vnode.
450 fd_getvnode(unsigned fd, file_t **fpp)
452 vnode_t *vp;
453 file_t *fp;
455 fp = fd_getfile(fd);
456 if (__predict_false(fp == NULL)) {
457 return EBADF;
459 if (__predict_false(fp->f_type != DTYPE_VNODE)) {
460 fd_putfile(fd);
461 return EINVAL;
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;
469 *fpp = fp;
470 return 0;
474 * Convenience wrapper around fd_getfile() that returns reference
475 * to a socket.
478 fd_getsock(unsigned fd, struct socket **sop)
480 file_t *fp;
482 fp = fd_getfile(fd);
483 if (__predict_false(fp == NULL)) {
484 return EBADF;
486 if (__predict_false(fp->f_type != DTYPE_SOCKET)) {
487 fd_putfile(fd);
488 return ENOTSOCK;
490 *sop = fp->f_data;
491 return 0;
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.
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.
503 * To release the file (not descriptor) reference, use closef().
505 file_t *
506 fd_getfile2(proc_t *p, unsigned fd)
508 filedesc_t *fdp;
509 fdfile_t *ff;
510 file_t *fp;
511 fdtab_t *dt;
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;
520 if ((ff = dt->dt_ff[fd]) == NULL) {
521 mutex_exit(&fdp->fd_lock);
522 return NULL;
524 if ((fp = ff->ff_file) == NULL) {
525 mutex_exit(&fdp->fd_lock);
526 return NULL;
528 mutex_enter(&fp->f_lock);
529 fp->f_count++;
530 mutex_exit(&fp->f_lock);
531 mutex_exit(&fdp->fd_lock);
533 return fp;
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.
543 fd_close(unsigned fd)
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;
553 l = curlwp;
554 p = l->l_proc;
555 fdp = l->l_fd;
556 ff = fdp->fd_dt->dt_ff[fd];
558 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
560 mutex_enter(&fdp->fd_lock);
561 KASSERT((ff->ff_refcnt & FR_MASK) > 0);
562 if (__predict_false(ff->ff_file == NULL)) {
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.
568 atomic_dec_uint(&ff->ff_refcnt);
569 cv_broadcast(&ff->ff_closing);
570 mutex_exit(&fdp->fd_lock);
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.
577 return (EBADF);
579 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
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.
587 fp = ff->ff_file;
588 ff->ff_file = NULL;
589 ff->ff_exclose = false;
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.
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);
608 if (__predict_false(refcnt != 0)) {
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()).
616 atomic_or_uint(&ff->ff_refcnt, FR_CLOSING);
619 * Remove any knotes attached to the file. A knote
620 * attached to the descriptor can hold references on it.
622 mutex_exit(&fdp->fd_lock);
623 if (!SLIST_EMPTY(&ff->ff_knlist)) {
624 knote_fdclose(fd);
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.
635 (*fp->f_ops->fo_restart)(fp);
636 mutex_enter(&fdp->fd_lock);
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.
646 while ((ff->ff_refcnt & FR_MASK) != 0) {
647 cv_wait(&ff->ff_closing, &fdp->fd_lock);
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));
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.
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);
674 /* Free descriptor slot. */
675 fd_unused(fdp, fd);
676 mutex_exit(&fdp->fd_lock);
678 /* Now drop reference to the file itself. */
679 return closef(fp);
683 * Duplicate a file descriptor.
686 fd_dup(file_t *fp, int minfd, int *newp, bool exclose)
688 proc_t *p;
689 int error;
691 p = curproc;
693 while ((error = fd_alloc(p, minfd, newp)) != 0) {
694 if (error != ENOSPC) {
695 return error;
697 fd_tryexpand(p);
700 curlwp->l_fd->fd_dt->dt_ff[*newp]->ff_exclose = exclose;
701 fd_affix(p, fp, *newp);
702 return 0;
706 * dup2 operation.
709 fd_dup2(file_t *fp, unsigned new)
711 filedesc_t *fdp;
712 fdfile_t *ff;
713 fdtab_t *dt;
715 fdp = curlwp->l_fd;
718 * Ensure there are enough slots in the descriptor table,
719 * and allocate an fdfile_t up front in case we need it.
721 while (new >= fdp->fd_dt->dt_nfiles) {
722 fd_tryexpand(curproc);
724 ff = pool_cache_get(fdfile_cache, PR_WAITOK);
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?
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 {
738 * Crummy, but unlikely to happen.
739 * Can occur if we interrupt another
740 * thread while it is opening a file.
742 kpause("dup2", false, 1, NULL);
744 mutex_enter(&fdp->fd_lock);
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;
752 fd_used(fdp, new);
753 mutex_exit(&fdp->fd_lock);
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);
760 return 0;
764 * Drop reference to a file structure.
767 closef(file_t *fp)
769 struct flock lf;
770 int error;
773 * Drop reference. If referenced elsewhere it's still open
774 * and we have nothing more to do.
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;
782 KASSERT(fp->f_count == 0);
783 mutex_exit(&fp->f_lock);
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);
793 if (fp->f_ops != NULL) {
794 error = (*fp->f_ops->fo_close)(fp);
795 } else {
796 error = 0;
798 KASSERT(fp->f_count == 0);
799 KASSERT(fp->f_cred != NULL);
800 pool_cache_put(file_cache, fp);
802 return error;
806 * Allocate a file descriptor for the process.
809 fd_alloc(proc_t *p, int want, int *result)
811 filedesc_t *fdp;
812 int i, lim, last, error;
813 u_int off, new;
814 fdtab_t *dt;
816 KASSERT(p == curproc || p == &proc0);
818 fdp = p->p_fd;
821 * Search for a free descriptor starting at the higher
822 * of want or fd_freefile.
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) {
842 * Free file descriptor in this block was
843 * below want, try again with higher want.
845 want = (new + 1) << NDENTRYSHIFT;
846 continue;
848 i += (new << NDENTRYSHIFT);
849 if (i >= last) {
850 break;
852 if (dt->dt_ff[i] == NULL) {
853 KASSERT(i >= NDFDFILE);
854 dt->dt_ff[i] = pool_cache_get(fdfile_cache, PR_WAITOK);
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;
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;
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;
877 * Allocate memory for a descriptor table.
879 static fdtab_t *
880 fd_dtab_alloc(int n)
882 fdtab_t *dt;
883 size_t sz;
885 KASSERT(n > NDFILE);
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;
898 * Free a descriptor table, and all tables linked for deferred free.
900 static void
901 fd_dtab_free(fdtab_t *dt)
903 fdtab_t *next;
904 size_t sz;
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);
920 * Allocate descriptor bitmap.
922 static void
923 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
925 uint8_t *ptr;
926 size_t szlo, szhi;
928 KASSERT(n > NDENTRIES);
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);
938 * Free descriptor bitmap.
940 static void
941 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
943 size_t szlo, szhi;
945 KASSERT(n > NDENTRIES);
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);
954 * Expand a process' descriptor table.
956 void
957 fd_tryexpand(proc_t *p)
959 filedesc_t *fdp;
960 int i, numfiles, oldnfiles;
961 fdtab_t *newdt, *dt;
962 uint32_t *newhimap, *newlomap;
964 KASSERT(p == curproc || p == &proc0);
966 fdp = p->p_fd;
967 newhimap = NULL;
968 newlomap = NULL;
969 oldnfiles = fdp->fd_dt->dt_nfiles;
971 if (oldnfiles < NDEXTENT)
972 numfiles = NDEXTENT;
973 else
974 numfiles = 2 * oldnfiles;
976 newdt = fd_dtab_alloc(numfiles);
977 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
978 fd_map_alloc(numfiles, &newlomap, &newhimap);
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);
991 return;
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);
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().
1006 if (oldnfiles > NDFILE) {
1007 if (fdp->fd_refcnt > 1) {
1008 newdt->dt_link = dt;
1009 } else {
1010 fd_dtab_free(dt);
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);
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);
1025 if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
1026 fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
1028 fdp->fd_himap = newhimap;
1029 fdp->fd_lomap = newlomap;
1033 * All other modifications must become globally visible before
1034 * the change to fd_dt. See fd_getfile().
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);
1044 * Create a new open file structure and allocate a file descriptor
1045 * for the current process.
1048 fd_allocfile(file_t **resultfp, int *resultfd)
1050 kauth_cred_t cred;
1051 file_t *fp;
1052 proc_t *p;
1053 int error;
1055 p = curproc;
1057 while ((error = fd_alloc(p, 0, resultfd)) != 0) {
1058 if (error != ENOSPC) {
1059 return error;
1061 fd_tryexpand(p);
1064 fp = pool_cache_get(file_cache, PR_WAITOK);
1065 if (fp == NULL) {
1066 return ENFILE;
1068 KASSERT(fp->f_count == 0);
1069 KASSERT(fp->f_msgcount == 0);
1070 KASSERT(fp->f_unpcount == 0);
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;
1081 * Don't allow recycled files to be scanned.
1082 * See uipc_usrreq.c.
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);
1090 fp->f_advice = 0;
1091 fp->f_offset = 0;
1092 *resultfp = fp;
1094 return 0;
1098 * Successful creation of a new descriptor: make visible to the process.
1100 void
1101 fd_affix(proc_t *p, file_t *fp, unsigned fd)
1103 fdfile_t *ff;
1104 filedesc_t *fdp;
1106 KASSERT(p == curproc || p == &proc0);
1108 /* Add a reference to the file structure. */
1109 mutex_enter(&fp->f_lock);
1110 fp->f_count++;
1111 mutex_exit(&fp->f_lock);
1114 * Insert the new file into the descriptor slot.
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.
1121 fdp = p->p_fd;
1122 ff = fdp->fd_dt->dt_ff[fd];
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]);
1130 /* No need to lock in order to make file initially visible. */
1131 ff->ff_file = fp;
1135 * Abort creation of a new descriptor: free descriptor slot and file.
1137 void
1138 fd_abort(proc_t *p, file_t *fp, unsigned fd)
1140 filedesc_t *fdp;
1141 fdfile_t *ff;
1143 KASSERT(p == curproc || p == &proc0);
1145 fdp = p->p_fd;
1146 ff = fdp->fd_dt->dt_ff[fd];
1148 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1150 mutex_enter(&fdp->fd_lock);
1151 KASSERT(fd_isused(fdp, fd));
1152 fd_unused(fdp, fd);
1153 mutex_exit(&fdp->fd_lock);
1155 if (fp != NULL) {
1156 KASSERT(fp->f_count == 0);
1157 KASSERT(fp->f_cred != NULL);
1158 pool_cache_put(file_cache, fp);
1162 static int
1163 file_ctor(void *arg, void *obj, int flags)
1165 file_t *fp = obj;
1167 memset(fp, 0, sizeof(*fp));
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;
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);
1182 return 0;
1185 static void
1186 file_dtor(void *arg, void *obj)
1188 file_t *fp = obj;
1190 mutex_enter(&filelist_lock);
1191 nfiles--;
1192 LIST_REMOVE(fp, f_list);
1193 mutex_exit(&filelist_lock);
1195 kauth_cred_free(fp->f_cred);
1196 mutex_destroy(&fp->f_lock);
1199 static int
1200 fdfile_ctor(void *arg, void *obj, int flags)
1202 fdfile_t *ff = obj;
1204 memset(ff, 0, sizeof(*ff));
1205 cv_init(&ff->ff_closing, "fdclose");
1207 return 0;
1210 static void
1211 fdfile_dtor(void *arg, void *obj)
1213 fdfile_t *ff = obj;
1215 cv_destroy(&ff->ff_closing);
1218 file_t *
1219 fgetdummy(void)
1221 file_t *fp;
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);
1228 return fp;
1231 void
1232 fputdummy(file_t *fp)
1235 mutex_destroy(&fp->f_lock);
1236 kmem_free(fp, sizeof(*fp));
1240 * Create an initial filedesc structure.
1242 filedesc_t *
1243 fd_init(filedesc_t *fdp)
1245 #ifdef DIAGNOSTIC
1246 unsigned fd;
1247 #endif
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);
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]);
1268 for (fd = NDFDFILE; fd < NDFILE; fd++) {
1269 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL);
1271 KASSERT(fdp->fd_himap == fdp->fd_dhimap);
1272 KASSERT(fdp->fd_lomap == fdp->fd_dlomap);
1273 #endif /* DIAGNOSTIC */
1275 fdp->fd_refcnt = 1;
1276 fd_checkmaps(fdp);
1278 return fdp;
1282 * Initialize a file descriptor table.
1284 static int
1285 filedesc_ctor(void *arg, void *obj, int flag)
1287 filedesc_t *fdp = obj;
1288 fdfile_t **ffp;
1289 int i;
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;
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);
1306 return 0;
1309 static void
1310 filedesc_dtor(void *arg, void *obj)
1312 filedesc_t *fdp = obj;
1313 int i;
1315 for (i = 0; i < NDFDFILE; i++) {
1316 fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
1319 mutex_destroy(&fdp->fd_lock);
1323 * Make p2 share p1's filedesc structure.
1325 void
1326 fd_share(struct proc *p2)
1328 filedesc_t *fdp;
1330 fdp = curlwp->l_fd;
1331 p2->p_fd = fdp;
1332 atomic_inc_uint(&fdp->fd_refcnt);
1336 * Acquire a hold on a filedesc structure.
1338 void
1339 fd_hold(lwp_t *l)
1341 filedesc_t *fdp = l->l_fd;
1343 KASSERT(fdp == curlwp->l_fd || fdp == lwp0.l_fd);
1344 atomic_inc_uint(&fdp->fd_refcnt);
1348 * Copy a filedesc structure.
1350 filedesc_t *
1351 fd_copy(void)
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;
1359 fdp = curproc->p_fd;
1360 newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1361 newfdp->fd_refcnt = 1;
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]);
1375 for (i = NDFDFILE; i < NDFILE; i++) {
1376 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL);
1378 #endif /* DIAGNOSTIC */
1380 mutex_enter(&fdp->fd_lock);
1381 fd_checkmaps(fdp);
1382 numfiles = fdp->fd_dt->dt_nfiles;
1383 lastfile = fdp->fd_lastfile;
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.
1391 if (lastfile < NDFILE) {
1392 i = NDFILE;
1393 newdt = newfdp->fd_dt;
1394 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1395 } else {
1397 * Compute the smallest multiple of NDEXTENT needed
1398 * for the file descriptors currently in use,
1399 * allowing the table to shrink.
1401 i = numfiles;
1402 while (i >= 2 * NDEXTENT && i > lastfile * 2) {
1403 i /= 2;
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 **));
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));
1422 newfdp->fd_freefile = fdp->fd_freefile;
1423 newfdp->fd_exclose = fdp->fd_exclose;
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;
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;
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);
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];
1455 ff2->ff_file = fp;
1456 ff2->ff_exclose = ff->ff_exclose;
1457 ff2->ff_allocated = true;
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);
1469 newlast = i;
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);
1476 return (newfdp);
1480 * Release a filedesc structure.
1482 void
1483 fd_free(void)
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;
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);
1497 #ifndef __HAVE_ATOMIC_AS_MEMBAR
1498 membar_exit();
1499 #endif
1500 if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
1501 return;
1504 * Close any files that the process holds open.
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) {
1519 * Must use fd_close() here if there is
1520 * a reference from kqueue or we might have posix
1521 * advisory locks.
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);
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;
1545 * Clean out the descriptor table for the next user and return
1546 * to the cache.
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;
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);
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);
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);
1587 * File Descriptor pseudo-device driver (/dev/fd/).
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.
1594 static int
1595 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
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.
1606 l->l_dupfd = minor(dev); /* XXX */
1607 return EDUPFD;
1611 * Duplicate the specified descriptor to a free descriptor.
1614 fd_dupopen(int old, int *new, int mode, int error)
1616 filedesc_t *fdp;
1617 fdfile_t *ff;
1618 file_t *fp;
1619 fdtab_t *dt;
1621 if ((fp = fd_getfile(old)) == NULL) {
1622 return EBADF;
1624 fdp = curlwp->l_fd;
1625 dt = fdp->fd_dt;
1626 ff = dt->dt_ff[old];
1629 * There are two cases of interest here.
1631 * For EDUPFD simply dup (dfd) to file descriptor
1632 * (indx) and return.
1634 * For EMOVEFD steal away the file structure from (dfd) and
1635 * store it in (indx). (dfd) is effectively closed by
1636 * this operation.
1638 * Any other error code is just returned.
1640 switch (error) {
1641 case EDUPFD:
1643 * Check that the mode the file is being opened for is a
1644 * subset of the mode of the existing descriptor.
1646 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
1647 error = EACCES;
1648 break;
1651 /* Copy it. */
1652 error = fd_dup(fp, 0, new, ff->ff_exclose);
1653 break;
1655 case EMOVEFD:
1656 /* Copy it. */
1657 error = fd_dup(fp, 0, new, ff->ff_exclose);
1658 if (error != 0) {
1659 break;
1662 /* Steal away the file pointer from 'old'. */
1663 (void)fd_close(old);
1664 return 0;
1667 fd_putfile(old);
1668 return error;
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.
1677 fsetown(pid_t *pgid, u_long cmd, const void *data)
1679 int id = *(const int *)data;
1680 int error;
1682 switch (cmd) {
1683 case TIOCSPGRP:
1684 if (id < 0)
1685 return (EINVAL);
1686 id = -id;
1687 break;
1688 default:
1689 break;
1692 if (id > 0 && !pfind(id))
1693 return (ESRCH);
1694 else if (id < 0 && (error = pgid_in_session(curproc, -id)))
1695 return (error);
1697 *pgid = id;
1698 return (0);
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.
1707 fgetown(pid_t pgid, u_long cmd, void *data)
1710 switch (cmd) {
1711 case TIOCGPGRP:
1712 *(int *)data = -pgid;
1713 break;
1714 default:
1715 *(int *)data = pgid;
1716 break;
1718 return (0);
1722 * Send signal to descriptor owner, either process or process group.
1724 void
1725 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
1727 ksiginfo_t ksi;
1729 KASSERT(!cpu_intr_p());
1731 if (pgid == 0) {
1732 return;
1735 KSI_INIT(&ksi);
1736 ksi.ksi_signo = signo;
1737 ksi.ksi_code = code;
1738 ksi.ksi_band = band;
1740 mutex_enter(proc_lock);
1741 if (pgid > 0) {
1742 struct proc *p1;
1744 p1 = p_find(pgid, PFIND_LOCKED);
1745 if (p1 != NULL) {
1746 kpsignal(p1, &ksi, fdescdata);
1748 } else {
1749 struct pgrp *pgrp;
1751 KASSERT(pgid < 0);
1752 pgrp = pg_find(-pgid, PFIND_LOCKED);
1753 if (pgrp != NULL) {
1754 kpgsignal(pgrp, &ksi, fdescdata, 0);
1757 mutex_exit(proc_lock);
1761 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
1762 void *data)
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);
1772 return EMOVEFD;
1776 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
1779 if (cmd == F_SETFL)
1780 return 0;
1782 return EOPNOTSUPP;
1786 fnullop_poll(file_t *fp, int which)
1789 return 0;
1793 fnullop_kqfilter(file_t *fp, struct knote *kn)
1796 return 0;
1799 void
1800 fnullop_restart(file_t *fp)
1806 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
1807 kauth_cred_t cred, int flags)
1810 return EOPNOTSUPP;
1814 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
1815 kauth_cred_t cred, int flags)
1818 return EOPNOTSUPP;
1822 fbadop_ioctl(file_t *fp, u_long com, void *data)
1825 return EOPNOTSUPP;
1829 fbadop_stat(file_t *fp, struct stat *sb)
1832 return EOPNOTSUPP;
1836 fbadop_close(file_t *fp)
1839 return EOPNOTSUPP;