2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_capsicum.h"
41 #include "opt_compat.h"
43 #include "opt_ktrace.h"
44 #include "opt_procdesc.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/capability.h>
51 #include <sys/domain.h>
52 #include <sys/fcntl.h>
54 #include <sys/filedesc.h>
55 #include <sys/filio.h>
57 #include <sys/kernel.h>
59 #include <sys/limits.h>
61 #include <sys/malloc.h>
63 #include <sys/mount.h>
64 #include <sys/mqueue.h>
65 #include <sys/mutex.h>
66 #include <sys/namei.h>
67 #include <sys/selinfo.h>
71 #include <sys/procdesc.h>
72 #include <sys/protosw.h>
73 #include <sys/racct.h>
74 #include <sys/resourcevar.h>
76 #include <sys/signalvar.h>
77 #include <sys/socketvar.h>
80 #include <sys/syscallsubr.h>
81 #include <sys/sysctl.h>
82 #include <sys/sysproto.h>
84 #include <sys/unistd.h>
86 #include <sys/unpcb.h>
88 #include <sys/vnode.h>
90 #include <sys/ktrace.h>
95 #include <netinet/in.h>
96 #include <netinet/in_pcb.h>
98 #include <security/audit/audit.h>
105 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
106 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
107 "file desc to leader structures");
108 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
109 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
111 MALLOC_DECLARE(M_FADVISE);
113 static uma_zone_t file_zone;
115 void (*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
117 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
118 struct thread *td, int holdleaders);
119 static int fd_first_free(struct filedesc *fdp, int low, int size);
120 static int fd_last_used(struct filedesc *fdp, int size);
121 static void fdgrowtable(struct filedesc *fdp, int nfd);
122 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
123 static void fdunused(struct filedesc *fdp, int fd);
124 static void fdused(struct filedesc *fdp, int fd);
125 static int fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
126 static int fill_procdesc_info(struct procdesc *pdp,
127 struct kinfo_file *kif);
128 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
129 static int fill_sem_info(struct file *fp, struct kinfo_file *kif);
130 static int fill_shm_info(struct file *fp, struct kinfo_file *kif);
131 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
132 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
133 static int getmaxfd(struct proc *p);
138 * - An array of open file descriptors (fd_ofiles)
139 * - An array of file flags (fd_ofileflags)
140 * - A bitmap recording which descriptors are in use (fd_map)
142 * A process starts out with NDFILE descriptors. The value of NDFILE has
143 * been selected based the historical limit of 20 open files, and an
144 * assumption that the majority of processes, especially short-lived
145 * processes like shells, will never need more.
147 * If this initial allocation is exhausted, a larger descriptor table and
148 * map are allocated dynamically, and the pointers in the process's struct
149 * filedesc are updated to point to those. This is repeated every time
150 * the process runs out of file descriptors (provided it hasn't hit its
153 * Since threads may hold references to individual descriptor table
154 * entries, the tables are never freed. Instead, they are placed on a
155 * linked list and freed only when the struct filedesc is released.
158 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
159 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
160 #define NDSLOT(x) ((x) / NDENTRIES)
161 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
162 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
165 * SLIST entry used to keep track of ofiles which must be reclaimed when
169 struct filedescent *ft_table;
170 SLIST_ENTRY(freetable) ft_next;
174 * Initial allocation: a filedesc structure + the head of SLIST used to
175 * keep track of old ofiles + enough space for NDFILE descriptors.
178 struct filedesc fd_fd;
179 SLIST_HEAD(, freetable) fd_free;
180 struct filedescent fd_dfiles[NDFILE];
181 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
185 * Descriptor management.
187 volatile int openfiles; /* actual number of open files */
188 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
189 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
191 /* A mutex to protect the association between a proc and filedesc. */
192 static struct mtx fdesc_mtx;
195 * If low >= size, just return low. Otherwise find the first zero bit in the
196 * given bitmap, starting at low and not exceeding size - 1. Return size if
200 fd_first_free(struct filedesc *fdp, int low, int size)
202 NDSLOTTYPE *map = fdp->fd_map;
210 if (low % NDENTRIES) {
211 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
212 if ((mask &= ~map[off]) != 0UL)
213 return (off * NDENTRIES + ffsl(mask) - 1);
216 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
217 if (map[off] != ~0UL)
218 return (off * NDENTRIES + ffsl(~map[off]) - 1);
223 * Find the highest non-zero bit in the given bitmap, starting at 0 and
224 * not exceeding size - 1. Return -1 if not found.
227 fd_last_used(struct filedesc *fdp, int size)
229 NDSLOTTYPE *map = fdp->fd_map;
234 if (size % NDENTRIES) {
235 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
236 if ((mask &= map[off]) != 0)
237 return (off * NDENTRIES + flsl(mask) - 1);
240 for (minoff = NDSLOT(0); off >= minoff; --off)
242 return (off * NDENTRIES + flsl(map[off]) - 1);
247 fdisused(struct filedesc *fdp, int fd)
250 FILEDESC_LOCK_ASSERT(fdp);
252 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
253 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
255 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
259 * Mark a file descriptor as used.
262 fdused(struct filedesc *fdp, int fd)
265 FILEDESC_XLOCK_ASSERT(fdp);
267 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
269 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
270 if (fd > fdp->fd_lastfile)
271 fdp->fd_lastfile = fd;
272 if (fd == fdp->fd_freefile)
273 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
277 * Mark a file descriptor as unused.
280 fdunused(struct filedesc *fdp, int fd)
283 FILEDESC_XLOCK_ASSERT(fdp);
285 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
286 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
287 ("fd=%d is still in use", fd));
289 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
290 if (fd < fdp->fd_freefile)
291 fdp->fd_freefile = fd;
292 if (fd == fdp->fd_lastfile)
293 fdp->fd_lastfile = fd_last_used(fdp, fd);
297 * Free a file descriptor.
299 * Avoid some work if fdp is about to be destroyed.
302 _fdfree(struct filedesc *fdp, int fd, int last)
304 struct filedescent *fde;
306 fde = &fdp->fd_ofiles[fd];
309 seq_write_begin(&fde->fde_seq);
311 filecaps_free(&fde->fde_caps);
314 bzero(fde, fde_change_size);
317 seq_write_end(&fde->fde_seq);
322 fdfree(struct filedesc *fdp, int fd)
329 fdfree_last(struct filedesc *fdp, int fd)
336 * System calls on descriptors.
338 #ifndef _SYS_SYSPROTO_H_
339 struct getdtablesize_args {
345 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
347 struct proc *p = td->td_proc;
352 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
353 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
355 if (lim < td->td_retval[0])
356 td->td_retval[0] = lim;
361 * Duplicate a file descriptor to a particular value.
363 * Note: keep in mind that a potential race condition exists when closing
364 * descriptors from a shared descriptor table (via rfork).
366 #ifndef _SYS_SYSPROTO_H_
374 sys_dup2(struct thread *td, struct dup2_args *uap)
377 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
382 * Duplicate a file descriptor.
384 #ifndef _SYS_SYSPROTO_H_
391 sys_dup(struct thread *td, struct dup_args *uap)
394 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
398 * The file control system call.
400 #ifndef _SYS_SYSPROTO_H_
409 sys_fcntl(struct thread *td, struct fcntl_args *uap)
412 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
416 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
429 * Convert old flock structure to new.
431 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
432 fl.l_start = ofl.l_start;
433 fl.l_len = ofl.l_len;
434 fl.l_pid = ofl.l_pid;
435 fl.l_type = ofl.l_type;
436 fl.l_whence = ofl.l_whence;
450 arg1 = (intptr_t)&fl;
456 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
457 arg1 = (intptr_t)&fl;
465 error = kern_fcntl(td, fd, cmd, arg1);
468 if (cmd == F_OGETLK) {
469 ofl.l_start = fl.l_start;
470 ofl.l_len = fl.l_len;
471 ofl.l_pid = fl.l_pid;
472 ofl.l_type = fl.l_type;
473 ofl.l_whence = fl.l_whence;
474 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
475 } else if (cmd == F_GETLK) {
476 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
482 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
484 struct filedesc *fdp;
486 struct file *fp, *fp2;
487 struct filedescent *fde;
503 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
506 case F_DUPFD_CLOEXEC:
508 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
514 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
517 case F_DUP2FD_CLOEXEC:
519 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
525 if ((fp = fget_locked(fdp, fd)) == NULL) {
526 FILEDESC_SUNLOCK(fdp);
530 fde = &fdp->fd_ofiles[fd];
532 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
533 FILEDESC_SUNLOCK(fdp);
538 if ((fp = fget_locked(fdp, fd)) == NULL) {
539 FILEDESC_XUNLOCK(fdp);
543 fde = &fdp->fd_ofiles[fd];
544 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
545 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
546 FILEDESC_XUNLOCK(fdp);
550 error = fget_unlocked(fdp, fd,
551 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
554 td->td_retval[0] = OFLAGS(fp->f_flag);
559 error = fget_unlocked(fdp, fd,
560 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
564 tmp = flg = fp->f_flag;
566 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
567 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
568 tmp = fp->f_flag & FNONBLOCK;
569 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
574 tmp = fp->f_flag & FASYNC;
575 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
580 atomic_clear_int(&fp->f_flag, FNONBLOCK);
582 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
587 error = fget_unlocked(fdp, fd,
588 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
591 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
593 td->td_retval[0] = tmp;
598 error = fget_unlocked(fdp, fd,
599 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
603 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
608 error = priv_check(td, PRIV_NFS_LOCKD);
616 /* FALLTHROUGH F_SETLK */
620 cap_rights_init(&rights, CAP_FLOCK);
621 error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
624 if (fp->f_type != DTYPE_VNODE) {
630 flp = (struct flock *)arg;
631 if (flp->l_whence == SEEK_CUR) {
632 foffset = foffset_get(fp);
635 foffset > OFF_MAX - flp->l_start)) {
636 FILEDESC_SUNLOCK(fdp);
641 flp->l_start += foffset;
645 switch (flp->l_type) {
647 if ((fp->f_flag & FREAD) == 0) {
651 PROC_LOCK(p->p_leader);
652 p->p_leader->p_flag |= P_ADVLOCK;
653 PROC_UNLOCK(p->p_leader);
654 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
658 if ((fp->f_flag & FWRITE) == 0) {
662 PROC_LOCK(p->p_leader);
663 p->p_leader->p_flag |= P_ADVLOCK;
664 PROC_UNLOCK(p->p_leader);
665 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
669 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
674 * Temporary api for testing remote lock
677 if (flg != F_REMOTE) {
681 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
682 F_UNLCKSYS, flp, flg);
688 if (error != 0 || flp->l_type == F_UNLCK ||
689 flp->l_type == F_UNLCKSYS) {
695 * Check for a race with close.
697 * The vnode is now advisory locked (or unlocked, but this case
698 * is not really important) as the caller requested.
699 * We had to drop the filedesc lock, so we need to recheck if
700 * the descriptor is still valid, because if it was closed
701 * in the meantime we need to remove advisory lock from the
702 * vnode - close on any descriptor leading to an advisory
703 * locked vnode, removes that lock.
704 * We will return 0 on purpose in that case, as the result of
705 * successful advisory lock might have been externally visible
706 * already. This is fine - effectively we pretend to the caller
707 * that the closing thread was a bit slower and that the
708 * advisory lock succeeded before the close.
710 error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
716 flp->l_whence = SEEK_SET;
719 flp->l_type = F_UNLCK;
720 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
721 F_UNLCK, flp, F_POSIX);
728 error = fget_unlocked(fdp, fd,
729 cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
732 if (fp->f_type != DTYPE_VNODE) {
737 flp = (struct flock *)arg;
738 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
739 flp->l_type != F_UNLCK) {
744 if (flp->l_whence == SEEK_CUR) {
745 foffset = foffset_get(fp);
746 if ((flp->l_start > 0 &&
747 foffset > OFF_MAX - flp->l_start) ||
749 foffset < OFF_MIN - flp->l_start)) {
750 FILEDESC_SUNLOCK(fdp);
755 flp->l_start += foffset;
758 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
764 arg = arg ? 128 * 1024: 0;
767 error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
770 if (fp->f_type != DTYPE_VNODE) {
777 * Exclusive lock synchronizes against f_seqcount reads and
778 * writes in sequential_heuristic().
780 error = vn_lock(vp, LK_EXCLUSIVE);
786 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
787 fp->f_seqcount = (arg + bsize - 1) / bsize;
788 atomic_set_int(&fp->f_flag, FRDAHEAD);
790 atomic_clear_int(&fp->f_flag, FRDAHEAD);
804 getmaxfd(struct proc *p)
809 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
816 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
819 do_dup(struct thread *td, int flags, int old, int new,
822 struct filedesc *fdp;
823 struct filedescent *oldfde, *newfde;
833 * Verify we have a valid descriptor to dup from and possibly to
834 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
835 * return EINVAL when the new descriptor is out of bounds.
840 return (flags & DUP_FCNTL ? EINVAL : EBADF);
843 return (flags & DUP_FCNTL ? EINVAL : EBADF);
846 if (fget_locked(fdp, old) == NULL) {
847 FILEDESC_XUNLOCK(fdp);
850 oldfde = &fdp->fd_ofiles[old];
851 if (flags & DUP_FIXED && old == new) {
853 if (flags & DUP_CLOEXEC)
854 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
855 FILEDESC_XUNLOCK(fdp);
858 fp = oldfde->fde_file;
862 * If the caller specified a file descriptor, make sure the file
863 * table is large enough to hold it, and grab it. Otherwise, just
864 * allocate a new descriptor the usual way.
866 if (flags & DUP_FIXED) {
867 if (new >= fdp->fd_nfiles) {
869 * The resource limits are here instead of e.g.
870 * fdalloc(), because the file descriptor table may be
871 * shared between processes, so we can't really use
872 * racct_add()/racct_sub(). Instead of counting the
873 * number of actually allocated descriptors, just put
874 * the limit on the size of the file descriptor table.
878 error = racct_set(p, RACCT_NOFILE, new + 1);
881 FILEDESC_XUNLOCK(fdp);
886 fdgrowtable_exp(fdp, new + 1);
887 oldfde = &fdp->fd_ofiles[old];
889 newfde = &fdp->fd_ofiles[new];
890 if (newfde->fde_file == NULL)
893 if ((error = fdalloc(td, new, &new)) != 0) {
894 FILEDESC_XUNLOCK(fdp);
898 newfde = &fdp->fd_ofiles[new];
901 KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
902 KASSERT(old != new, ("new fd is same as old"));
904 delfp = newfde->fde_file;
907 * Duplicate the source descriptor.
910 seq_write_begin(&newfde->fde_seq);
912 filecaps_free(&newfde->fde_caps);
913 memcpy(newfde, oldfde, fde_change_size);
914 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
915 if ((flags & DUP_CLOEXEC) != 0)
916 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
918 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
920 seq_write_end(&newfde->fde_seq);
925 (void) closefp(fdp, new, delfp, td, 1);
926 /* closefp() drops the FILEDESC lock for us. */
928 FILEDESC_XUNLOCK(fdp);
935 * If sigio is on the list associated with a process or process group,
936 * disable signalling from the device, remove sigio from the list and
940 funsetown(struct sigio **sigiop)
950 *(sigio->sio_myref) = NULL;
951 if ((sigio)->sio_pgid < 0) {
952 struct pgrp *pg = (sigio)->sio_pgrp;
954 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
958 struct proc *p = (sigio)->sio_proc;
960 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
965 crfree(sigio->sio_ucred);
966 free(sigio, M_SIGIO);
970 * Free a list of sigio structures.
971 * We only need to lock the SIGIO_LOCK because we have made ourselves
972 * inaccessible to callers of fsetown and therefore do not need to lock
973 * the proc or pgrp struct for the list manipulation.
976 funsetownlst(struct sigiolst *sigiolst)
982 sigio = SLIST_FIRST(sigiolst);
989 * Every entry of the list should belong
990 * to a single proc or pgrp.
992 if (sigio->sio_pgid < 0) {
993 pg = sigio->sio_pgrp;
994 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
995 } else /* if (sigio->sio_pgid > 0) */ {
997 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1001 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1002 *(sigio->sio_myref) = NULL;
1004 KASSERT(sigio->sio_pgid < 0,
1005 ("Proc sigio in pgrp sigio list"));
1006 KASSERT(sigio->sio_pgrp == pg,
1007 ("Bogus pgrp in sigio list"));
1009 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1012 } else /* if (p != NULL) */ {
1013 KASSERT(sigio->sio_pgid > 0,
1014 ("Pgrp sigio in proc sigio list"));
1015 KASSERT(sigio->sio_proc == p,
1016 ("Bogus proc in sigio list"));
1018 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1023 crfree(sigio->sio_ucred);
1024 free(sigio, M_SIGIO);
1031 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1033 * After permission checking, add a sigio structure to the sigio list for
1034 * the process or process group.
1037 fsetown(pid_t pgid, struct sigio **sigiop)
1041 struct sigio *sigio;
1051 /* Allocate and fill in the new sigio out of locks. */
1052 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1053 sigio->sio_pgid = pgid;
1054 sigio->sio_ucred = crhold(curthread->td_ucred);
1055 sigio->sio_myref = sigiop;
1057 sx_slock(&proctree_lock);
1066 * Policy - Don't allow a process to FSETOWN a process
1067 * in another session.
1069 * Remove this test to allow maximum flexibility or
1070 * restrict FSETOWN to the current process or process
1071 * group for maximum safety.
1074 if (proc->p_session != curthread->td_proc->p_session) {
1080 } else /* if (pgid < 0) */ {
1081 pgrp = pgfind(-pgid);
1089 * Policy - Don't allow a process to FSETOWN a process
1090 * in another session.
1092 * Remove this test to allow maximum flexibility or
1093 * restrict FSETOWN to the current process or process
1094 * group for maximum safety.
1096 if (pgrp->pg_session != curthread->td_proc->p_session) {
1107 * Since funsetownlst() is called without the proctree
1108 * locked, we need to check for P_WEXIT.
1109 * XXX: is ESRCH correct?
1111 if ((proc->p_flag & P_WEXIT) != 0) {
1116 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1117 sigio->sio_proc = proc;
1121 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1122 sigio->sio_pgrp = pgrp;
1125 sx_sunlock(&proctree_lock);
1132 sx_sunlock(&proctree_lock);
1133 crfree(sigio->sio_ucred);
1134 free(sigio, M_SIGIO);
1139 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1143 struct sigio **sigiop;
1148 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1154 * Function drops the filedesc lock on return.
1157 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1162 FILEDESC_XLOCK_ASSERT(fdp);
1165 if (td->td_proc->p_fdtol != NULL) {
1167 * Ask fdfree() to sleep to ensure that all relevant
1168 * process leaders can be traversed in closef().
1170 fdp->fd_holdleaderscount++;
1177 * We now hold the fp reference that used to be owned by the
1178 * descriptor array. We have to unlock the FILEDESC *AFTER*
1179 * knote_fdclose to prevent a race of the fd getting opened, a knote
1180 * added, and deleteing a knote for the new fd.
1182 knote_fdclose(td, fd);
1185 * We need to notify mqueue if the object is of type mqueue.
1187 if (fp->f_type == DTYPE_MQUEUE)
1188 mq_fdclose(td, fd, fp);
1189 FILEDESC_XUNLOCK(fdp);
1191 error = closef(fp, td);
1193 FILEDESC_XLOCK(fdp);
1194 fdp->fd_holdleaderscount--;
1195 if (fdp->fd_holdleaderscount == 0 &&
1196 fdp->fd_holdleaderswakeup != 0) {
1197 fdp->fd_holdleaderswakeup = 0;
1198 wakeup(&fdp->fd_holdleaderscount);
1200 FILEDESC_XUNLOCK(fdp);
1206 * Close a file descriptor.
1208 #ifndef _SYS_SYSPROTO_H_
1217 struct close_args *uap;
1220 return (kern_close(td, uap->fd));
1228 struct filedesc *fdp;
1231 fdp = td->td_proc->p_fd;
1233 AUDIT_SYSCLOSE(td, fd);
1235 FILEDESC_XLOCK(fdp);
1236 if ((fp = fget_locked(fdp, fd)) == NULL) {
1237 FILEDESC_XUNLOCK(fdp);
1242 /* closefp() drops the FILEDESC lock for us. */
1243 return (closefp(fdp, fd, fp, td, 1));
1247 * Close open file descriptors.
1249 #ifndef _SYS_SYSPROTO_H_
1250 struct closefrom_args {
1256 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1258 struct filedesc *fdp;
1261 fdp = td->td_proc->p_fd;
1262 AUDIT_ARG_FD(uap->lowfd);
1265 * Treat negative starting file descriptor values identical to
1266 * closefrom(0) which closes all files.
1270 FILEDESC_SLOCK(fdp);
1271 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1272 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1273 FILEDESC_SUNLOCK(fdp);
1274 (void)kern_close(td, fd);
1275 FILEDESC_SLOCK(fdp);
1278 FILEDESC_SUNLOCK(fdp);
1282 #if defined(COMPAT_43)
1284 * Return status information about a file descriptor.
1286 #ifndef _SYS_SYSPROTO_H_
1287 struct ofstat_args {
1294 ofstat(struct thread *td, struct ofstat_args *uap)
1300 error = kern_fstat(td, uap->fd, &ub);
1303 error = copyout(&oub, uap->sb, sizeof(oub));
1307 #endif /* COMPAT_43 */
1310 * Return status information about a file descriptor.
1312 #ifndef _SYS_SYSPROTO_H_
1320 sys_fstat(struct thread *td, struct fstat_args *uap)
1325 error = kern_fstat(td, uap->fd, &ub);
1327 error = copyout(&ub, uap->sb, sizeof(ub));
1332 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1335 cap_rights_t rights;
1340 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1344 AUDIT_ARG_FILE(td->td_proc, fp);
1346 error = fo_stat(fp, sbp, td->td_ucred, td);
1349 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1356 * Return status information about a file descriptor.
1358 #ifndef _SYS_SYSPROTO_H_
1359 struct nfstat_args {
1366 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1372 error = kern_fstat(td, uap->fd, &ub);
1374 cvtnstat(&ub, &nub);
1375 error = copyout(&nub, uap->sb, sizeof(nub));
1381 * Return pathconf information about a file descriptor.
1383 #ifndef _SYS_SYSPROTO_H_
1384 struct fpathconf_args {
1391 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1395 cap_rights_t rights;
1398 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1402 /* If asynchronous I/O is available, it works for all descriptors. */
1403 if (uap->name == _PC_ASYNC_IO) {
1404 td->td_retval[0] = async_io_version;
1409 vn_lock(vp, LK_SHARED | LK_RETRY);
1410 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1412 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1413 if (uap->name != _PC_PIPE_BUF) {
1416 td->td_retval[0] = PIPE_BUF;
1428 * Initialize filecaps structure.
1431 filecaps_init(struct filecaps *fcaps)
1434 bzero(fcaps, sizeof(*fcaps));
1435 fcaps->fc_nioctls = -1;
1439 * Copy filecaps structure allocating memory for ioctls array if needed.
1442 filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1447 if (src->fc_ioctls != NULL) {
1448 KASSERT(src->fc_nioctls > 0,
1449 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1451 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1452 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1453 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1458 * Move filecaps structure to the new place and clear the old place.
1461 filecaps_move(struct filecaps *src, struct filecaps *dst)
1465 bzero(src, sizeof(*src));
1469 * Fill the given filecaps structure with full rights.
1472 filecaps_fill(struct filecaps *fcaps)
1475 CAP_ALL(&fcaps->fc_rights);
1476 fcaps->fc_ioctls = NULL;
1477 fcaps->fc_nioctls = -1;
1478 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1482 * Free memory allocated within filecaps structure.
1485 filecaps_free(struct filecaps *fcaps)
1488 free(fcaps->fc_ioctls, M_FILECAPS);
1489 bzero(fcaps, sizeof(*fcaps));
1493 * Validate the given filecaps structure.
1496 filecaps_validate(const struct filecaps *fcaps, const char *func)
1499 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1500 ("%s: invalid rights", func));
1501 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1502 ("%s: invalid fcntls", func));
1503 KASSERT(fcaps->fc_fcntls == 0 ||
1504 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1505 ("%s: fcntls without CAP_FCNTL", func));
1506 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1507 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1508 ("%s: invalid ioctls", func));
1509 KASSERT(fcaps->fc_nioctls == 0 ||
1510 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1511 ("%s: ioctls without CAP_IOCTL", func));
1515 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1519 FILEDESC_XLOCK_ASSERT(fdp);
1521 nfd1 = fdp->fd_nfiles * 2;
1524 fdgrowtable(fdp, nfd1);
1528 * Grow the file table to accomodate (at least) nfd descriptors.
1531 fdgrowtable(struct filedesc *fdp, int nfd)
1533 struct filedesc0 *fdp0;
1534 struct freetable *ft;
1535 struct filedescent *ntable;
1536 struct filedescent *otable;
1537 int nnfiles, onfiles;
1538 NDSLOTTYPE *nmap, *omap;
1540 FILEDESC_XLOCK_ASSERT(fdp);
1542 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1544 /* save old values */
1545 onfiles = fdp->fd_nfiles;
1546 otable = fdp->fd_ofiles;
1549 /* compute the size of the new table */
1550 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1551 if (nnfiles <= onfiles)
1552 /* the table is already large enough */
1556 * Allocate a new table. We need enough space for the
1557 * file entries themselves and the struct freetable we will use
1558 * when we decommission the table and place it on the freelist.
1559 * We place the struct freetable in the middle so we don't have
1560 * to worry about padding.
1562 ntable = malloc(nnfiles * sizeof(ntable[0]) + sizeof(struct freetable),
1563 M_FILEDESC, M_ZERO | M_WAITOK);
1564 /* copy the old data over and point at the new tables */
1565 memcpy(ntable, otable, onfiles * sizeof(*otable));
1566 fdp->fd_ofiles = ntable;
1569 * Allocate a new map only if the old is not large enough. It will
1570 * grow at a slower rate than the table as it can map more
1571 * entries than the table can hold.
1573 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1574 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1576 /* copy over the old data and update the pointer */
1577 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1582 * In order to have a valid pattern for fget_unlocked()
1583 * fdp->fd_nfiles must be the last member to be updated, otherwise
1584 * fget_unlocked() consumers may reference a new, higher value for
1585 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1586 * resulting in OOB accesses.
1588 atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1591 * Do not free the old file table, as some threads may still
1592 * reference entries within it. Instead, place it on a freelist
1593 * which will be processed when the struct filedesc is released.
1595 * Note that if onfiles == NDFILE, we're dealing with the original
1596 * static allocation contained within (struct filedesc0 *)fdp,
1597 * which must not be freed.
1599 if (onfiles > NDFILE) {
1600 ft = (struct freetable *)&otable[onfiles];
1601 fdp0 = (struct filedesc0 *)fdp;
1602 ft->ft_table = otable;
1603 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1606 * The map does not have the same possibility of threads still
1607 * holding references to it. So always free it as long as it
1608 * does not reference the original static allocation.
1610 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1611 free(omap, M_FILEDESC);
1615 * Allocate a file descriptor for the process.
1618 fdalloc(struct thread *td, int minfd, int *result)
1620 struct proc *p = td->td_proc;
1621 struct filedesc *fdp = p->p_fd;
1622 int fd = -1, maxfd, allocfd;
1627 FILEDESC_XLOCK_ASSERT(fdp);
1629 if (fdp->fd_freefile > minfd)
1630 minfd = fdp->fd_freefile;
1632 maxfd = getmaxfd(p);
1635 * Search the bitmap for a free descriptor starting at minfd.
1636 * If none is found, grow the file table.
1638 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1641 if (fd >= fdp->fd_nfiles) {
1642 allocfd = min(fd * 2, maxfd);
1645 error = racct_set(p, RACCT_NOFILE, allocfd);
1651 * fd is already equal to first free descriptor >= minfd, so
1652 * we only need to grow the table and we are done.
1654 fdgrowtable_exp(fdp, allocfd);
1658 * Perform some sanity checks, then mark the file descriptor as
1659 * used and return it to the caller.
1661 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1662 ("invalid descriptor %d", fd));
1663 KASSERT(!fdisused(fdp, fd),
1664 ("fd_first_free() returned non-free descriptor"));
1665 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1666 ("file descriptor isn't free"));
1667 KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1674 * Allocate n file descriptors for the process.
1677 fdallocn(struct thread *td, int minfd, int *fds, int n)
1679 struct proc *p = td->td_proc;
1680 struct filedesc *fdp = p->p_fd;
1683 FILEDESC_XLOCK_ASSERT(fdp);
1685 if (!fdavail(td, n))
1688 for (i = 0; i < n; i++)
1689 if (fdalloc(td, 0, &fds[i]) != 0)
1693 for (i--; i >= 0; i--)
1694 fdunused(fdp, fds[i]);
1702 * Check to see whether n user file descriptors are available to the process
1706 fdavail(struct thread *td, int n)
1708 struct proc *p = td->td_proc;
1709 struct filedesc *fdp = td->td_proc->p_fd;
1712 FILEDESC_LOCK_ASSERT(fdp);
1715 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1716 * call racct_add() from there instead of dealing with containers
1720 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1722 last = min(fdp->fd_nfiles, lim);
1723 for (i = fdp->fd_freefile; i < last; i++) {
1724 if (fdp->fd_ofiles[i].fde_file == NULL && --n <= 0)
1731 * Create a new open file structure and allocate a file decriptor for the
1732 * process that refers to it. We add one reference to the file for the
1733 * descriptor table and one reference for resultfp. This is to prevent us
1734 * being preempted and the entry in the descriptor table closed after we
1735 * release the FILEDESC lock.
1738 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1743 error = falloc_noinstall(td, &fp);
1745 return (error); /* no reference held on error */
1747 error = finstall(td, fp, &fd, flags, NULL);
1749 fdrop(fp, td); /* one reference (fp only) */
1753 if (resultfp != NULL)
1754 *resultfp = fp; /* copy out result */
1756 fdrop(fp, td); /* release local reference */
1758 if (resultfd != NULL)
1765 * Create a new open file structure without allocating a file descriptor.
1768 falloc_noinstall(struct thread *td, struct file **resultfp)
1771 int maxuserfiles = maxfiles - (maxfiles / 20);
1772 static struct timeval lastfail;
1775 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1777 if ((openfiles >= maxuserfiles &&
1778 priv_check(td, PRIV_MAXFILES) != 0) ||
1779 openfiles >= maxfiles) {
1780 if (ppsratecheck(&lastfail, &curfail, 1)) {
1781 printf("kern.maxfiles limit exceeded by uid %i, "
1782 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1786 atomic_add_int(&openfiles, 1);
1787 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1788 refcount_init(&fp->f_count, 1);
1789 fp->f_cred = crhold(td->td_ucred);
1790 fp->f_ops = &badfileops;
1798 * Install a file in a file descriptor table.
1801 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1802 struct filecaps *fcaps)
1804 struct filedesc *fdp = td->td_proc->p_fd;
1805 struct filedescent *fde;
1808 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1809 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1811 filecaps_validate(fcaps, __func__);
1813 FILEDESC_XLOCK(fdp);
1814 if ((error = fdalloc(td, 0, fd))) {
1815 FILEDESC_XUNLOCK(fdp);
1819 fde = &fdp->fd_ofiles[*fd];
1821 seq_write_begin(&fde->fde_seq);
1824 if ((flags & O_CLOEXEC) != 0)
1825 fde->fde_flags |= UF_EXCLOSE;
1827 filecaps_move(fcaps, &fde->fde_caps);
1829 filecaps_fill(&fde->fde_caps);
1831 seq_write_end(&fde->fde_seq);
1833 FILEDESC_XUNLOCK(fdp);
1838 * Build a new filedesc structure from another.
1839 * Copy the current, root, and jail root vnode references.
1842 fdinit(struct filedesc *fdp)
1844 struct filedesc0 *newfdp;
1846 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1847 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1849 FILEDESC_SLOCK(fdp);
1850 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1851 if (newfdp->fd_fd.fd_cdir)
1852 VREF(newfdp->fd_fd.fd_cdir);
1853 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1854 if (newfdp->fd_fd.fd_rdir)
1855 VREF(newfdp->fd_fd.fd_rdir);
1856 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1857 if (newfdp->fd_fd.fd_jdir)
1858 VREF(newfdp->fd_fd.fd_jdir);
1859 FILEDESC_SUNLOCK(fdp);
1862 /* Create the file descriptor table. */
1863 newfdp->fd_fd.fd_refcnt = 1;
1864 newfdp->fd_fd.fd_holdcnt = 1;
1865 newfdp->fd_fd.fd_cmask = CMASK;
1866 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1867 newfdp->fd_fd.fd_nfiles = NDFILE;
1868 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1869 newfdp->fd_fd.fd_lastfile = -1;
1870 return (&newfdp->fd_fd);
1873 static struct filedesc *
1874 fdhold(struct proc *p)
1876 struct filedesc *fdp;
1878 mtx_lock(&fdesc_mtx);
1882 mtx_unlock(&fdesc_mtx);
1887 fddrop(struct filedesc *fdp)
1889 struct filedesc0 *fdp0;
1890 struct freetable *ft;
1893 mtx_lock(&fdesc_mtx);
1894 i = --fdp->fd_holdcnt;
1895 mtx_unlock(&fdesc_mtx);
1899 FILEDESC_LOCK_DESTROY(fdp);
1900 fdp0 = (struct filedesc0 *)fdp;
1901 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1902 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1903 free(ft->ft_table, M_FILEDESC);
1905 free(fdp, M_FILEDESC);
1909 * Share a filedesc structure.
1912 fdshare(struct filedesc *fdp)
1915 FILEDESC_XLOCK(fdp);
1917 FILEDESC_XUNLOCK(fdp);
1922 * Unshare a filedesc structure, if necessary by making a copy
1925 fdunshare(struct thread *td)
1927 struct filedesc *tmp;
1928 struct proc *p = td->td_proc;
1930 if (p->p_fd->fd_refcnt == 1)
1933 tmp = fdcopy(p->p_fd);
1939 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1940 * this is to ease callers, not catch errors.
1943 fdcopy(struct filedesc *fdp)
1945 struct filedesc *newfdp;
1946 struct filedescent *nfde, *ofde;
1949 /* Certain daemons might not have file descriptors. */
1953 newfdp = fdinit(fdp);
1954 FILEDESC_SLOCK(fdp);
1955 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1956 FILEDESC_SUNLOCK(fdp);
1957 FILEDESC_XLOCK(newfdp);
1958 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1959 FILEDESC_XUNLOCK(newfdp);
1960 FILEDESC_SLOCK(fdp);
1962 /* copy all passable descriptors (i.e. not kqueue) */
1963 newfdp->fd_freefile = -1;
1964 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1965 ofde = &fdp->fd_ofiles[i];
1966 if (fdisused(fdp, i) &&
1967 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1968 ofde->fde_file->f_ops != &badfileops) {
1969 nfde = &newfdp->fd_ofiles[i];
1971 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1972 fhold(nfde->fde_file);
1973 newfdp->fd_lastfile = i;
1975 if (newfdp->fd_freefile == -1)
1976 newfdp->fd_freefile = i;
1979 newfdp->fd_cmask = fdp->fd_cmask;
1980 FILEDESC_SUNLOCK(fdp);
1981 FILEDESC_XLOCK(newfdp);
1982 for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1983 if (newfdp->fd_ofiles[i].fde_file != NULL)
1986 if (newfdp->fd_freefile == -1)
1987 newfdp->fd_freefile = i;
1988 FILEDESC_XUNLOCK(newfdp);
1993 * Release a filedesc structure.
1996 fdescfree(struct thread *td)
1998 struct filedesc *fdp;
2000 struct filedesc_to_leader *fdtol;
2002 struct vnode *cdir, *jdir, *rdir, *vp;
2005 /* Certain daemons might not have file descriptors. */
2006 fdp = td->td_proc->p_fd;
2011 PROC_LOCK(td->td_proc);
2012 racct_set(td->td_proc, RACCT_NOFILE, 0);
2013 PROC_UNLOCK(td->td_proc);
2016 /* Check for special need to clear POSIX style locks */
2017 fdtol = td->td_proc->p_fdtol;
2018 if (fdtol != NULL) {
2019 FILEDESC_XLOCK(fdp);
2020 KASSERT(fdtol->fdl_refcount > 0,
2021 ("filedesc_to_refcount botch: fdl_refcount=%d",
2022 fdtol->fdl_refcount));
2023 if (fdtol->fdl_refcount == 1 &&
2024 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2025 for (i = 0; i <= fdp->fd_lastfile; i++) {
2026 fp = fdp->fd_ofiles[i].fde_file;
2027 if (fp == NULL || fp->f_type != DTYPE_VNODE)
2030 FILEDESC_XUNLOCK(fdp);
2031 lf.l_whence = SEEK_SET;
2034 lf.l_type = F_UNLCK;
2036 (void) VOP_ADVLOCK(vp,
2037 (caddr_t)td->td_proc->p_leader, F_UNLCK,
2039 FILEDESC_XLOCK(fdp);
2044 if (fdtol->fdl_refcount == 1) {
2045 if (fdp->fd_holdleaderscount > 0 &&
2046 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2048 * close() or do_dup() has cleared a reference
2049 * in a shared file descriptor table.
2051 fdp->fd_holdleaderswakeup = 1;
2052 sx_sleep(&fdp->fd_holdleaderscount,
2053 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2056 if (fdtol->fdl_holdcount > 0) {
2058 * Ensure that fdtol->fdl_leader remains
2059 * valid in closef().
2061 fdtol->fdl_wakeup = 1;
2062 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2067 fdtol->fdl_refcount--;
2068 if (fdtol->fdl_refcount == 0 &&
2069 fdtol->fdl_holdcount == 0) {
2070 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2071 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2074 td->td_proc->p_fdtol = NULL;
2075 FILEDESC_XUNLOCK(fdp);
2077 free(fdtol, M_FILEDESC_TO_LEADER);
2080 mtx_lock(&fdesc_mtx);
2081 td->td_proc->p_fd = NULL;
2082 mtx_unlock(&fdesc_mtx);
2084 FILEDESC_XLOCK(fdp);
2085 i = --fdp->fd_refcnt;
2087 FILEDESC_XUNLOCK(fdp);
2091 cdir = fdp->fd_cdir;
2092 fdp->fd_cdir = NULL;
2093 rdir = fdp->fd_rdir;
2094 fdp->fd_rdir = NULL;
2095 jdir = fdp->fd_jdir;
2096 fdp->fd_jdir = NULL;
2097 FILEDESC_XUNLOCK(fdp);
2099 for (i = 0; i <= fdp->fd_lastfile; i++) {
2100 fp = fdp->fd_ofiles[i].fde_file;
2102 fdfree_last(fdp, i);
2103 (void) closef(fp, td);
2107 if (fdp->fd_nfiles > NDFILE)
2108 free(fdp->fd_ofiles, M_FILEDESC);
2109 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2110 free(fdp->fd_map, M_FILEDESC);
2123 * For setugid programs, we don't want to people to use that setugidness
2124 * to generate error messages which write to a file which otherwise would
2125 * otherwise be off-limits to the process. We check for filesystems where
2126 * the vnode can change out from under us after execve (like [lin]procfs).
2128 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2129 * sufficient. We also don't check for setugidness since we know we are.
2132 is_unsafe(struct file *fp)
2134 if (fp->f_type == DTYPE_VNODE) {
2135 struct vnode *vp = fp->f_vnode;
2137 if ((vp->v_vflag & VV_PROCDEP) != 0)
2144 * Make this setguid thing safe, if at all possible.
2147 setugidsafety(struct thread *td)
2149 struct filedesc *fdp;
2153 fdp = td->td_proc->p_fd;
2154 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2155 FILEDESC_XLOCK(fdp);
2156 for (i = 0; i <= fdp->fd_lastfile; i++) {
2159 fp = fdp->fd_ofiles[i].fde_file;
2160 if (fp != NULL && is_unsafe(fp)) {
2161 knote_fdclose(td, i);
2163 * NULL-out descriptor prior to close to avoid
2164 * a race while close blocks.
2167 FILEDESC_XUNLOCK(fdp);
2168 (void) closef(fp, td);
2169 FILEDESC_XLOCK(fdp);
2172 FILEDESC_XUNLOCK(fdp);
2176 * If a specific file object occupies a specific file descriptor, close the
2177 * file descriptor entry and drop a reference on the file object. This is a
2178 * convenience function to handle a subsequent error in a function that calls
2179 * falloc() that handles the race that another thread might have closed the
2180 * file descriptor out from under the thread creating the file object.
2183 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2186 FILEDESC_XLOCK(fdp);
2187 if (fdp->fd_ofiles[idx].fde_file == fp) {
2189 FILEDESC_XUNLOCK(fdp);
2192 FILEDESC_XUNLOCK(fdp);
2196 * Close any files on exec?
2199 fdcloseexec(struct thread *td)
2201 struct filedesc *fdp;
2202 struct filedescent *fde;
2206 fdp = td->td_proc->p_fd;
2207 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2208 FILEDESC_XLOCK(fdp);
2209 for (i = 0; i <= fdp->fd_lastfile; i++) {
2210 fde = &fdp->fd_ofiles[i];
2212 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2213 (fde->fde_flags & UF_EXCLOSE))) {
2215 (void) closefp(fdp, i, fp, td, 0);
2216 /* closefp() drops the FILEDESC lock. */
2217 FILEDESC_XLOCK(fdp);
2220 FILEDESC_XUNLOCK(fdp);
2224 * It is unsafe for set[ug]id processes to be started with file
2225 * descriptors 0..2 closed, as these descriptors are given implicit
2226 * significance in the Standard C library. fdcheckstd() will create a
2227 * descriptor referencing /dev/null for each of stdin, stdout, and
2228 * stderr that is not already open.
2231 fdcheckstd(struct thread *td)
2233 struct filedesc *fdp;
2234 register_t retval, save;
2235 int i, error, devnull;
2237 fdp = td->td_proc->p_fd;
2238 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2241 for (i = 0; i < 3; i++) {
2242 if (fdp->fd_ofiles[i].fde_file != NULL)
2245 save = td->td_retval[0];
2246 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2248 devnull = td->td_retval[0];
2249 td->td_retval[0] = save;
2252 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2254 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2263 * Internal form of close. Decrement reference count on file structure.
2264 * Note: td may be NULL when closing a file that was being passed in a
2267 * XXXRW: Giant is not required for the caller, but often will be held; this
2268 * makes it moderately likely the Giant will be recursed in the VFS case.
2271 closef(struct file *fp, struct thread *td)
2275 struct filedesc_to_leader *fdtol;
2276 struct filedesc *fdp;
2279 * POSIX record locking dictates that any close releases ALL
2280 * locks owned by this process. This is handled by setting
2281 * a flag in the unlock to free ONLY locks obeying POSIX
2282 * semantics, and not to free BSD-style file locks.
2283 * If the descriptor was in a message, POSIX-style locks
2284 * aren't passed with the descriptor, and the thread pointer
2285 * will be NULL. Callers should be careful only to pass a
2286 * NULL thread pointer when there really is no owning
2287 * context that might have locks, or the locks will be
2290 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2292 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2293 lf.l_whence = SEEK_SET;
2296 lf.l_type = F_UNLCK;
2297 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2298 F_UNLCK, &lf, F_POSIX);
2300 fdtol = td->td_proc->p_fdtol;
2301 if (fdtol != NULL) {
2303 * Handle special case where file descriptor table is
2304 * shared between multiple process leaders.
2306 fdp = td->td_proc->p_fd;
2307 FILEDESC_XLOCK(fdp);
2308 for (fdtol = fdtol->fdl_next;
2309 fdtol != td->td_proc->p_fdtol;
2310 fdtol = fdtol->fdl_next) {
2311 if ((fdtol->fdl_leader->p_flag &
2314 fdtol->fdl_holdcount++;
2315 FILEDESC_XUNLOCK(fdp);
2316 lf.l_whence = SEEK_SET;
2319 lf.l_type = F_UNLCK;
2321 (void) VOP_ADVLOCK(vp,
2322 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2324 FILEDESC_XLOCK(fdp);
2325 fdtol->fdl_holdcount--;
2326 if (fdtol->fdl_holdcount == 0 &&
2327 fdtol->fdl_wakeup != 0) {
2328 fdtol->fdl_wakeup = 0;
2332 FILEDESC_XUNLOCK(fdp);
2335 return (fdrop(fp, td));
2339 * Initialize the file pointer with the specified properties.
2341 * The ops are set with release semantics to be certain that the flags, type,
2342 * and data are visible when ops is. This is to prevent ops methods from being
2343 * called with bad data.
2346 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2351 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2355 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2356 int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2359 struct filedescent fde;
2365 cap_rights_t haverights;
2370 * Avoid reads reordering and then a first access to the
2371 * fdp->fd_ofiles table which could result in OOB operation.
2373 if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2376 * Fetch the descriptor locklessly. We avoid fdrop() races by
2377 * never raising a refcount above 0. To accomplish this we have
2378 * to use a cmpset loop rather than an atomic_add. The descriptor
2379 * must be re-verified once we acquire a reference to be certain
2380 * that the identity is still correct and we did not lose a race
2381 * due to preemption.
2385 seq = seq_read(fd_seq(fdp, fd));
2386 fde = fdp->fd_ofiles[fd];
2387 if (!seq_consistent(fd_seq(fdp, fd), seq)) {
2393 fp = fdp->fd_ofiles[fd].fde_file;
2398 haverights = *cap_rights_fde(&fde);
2399 if (needrightsp != NULL) {
2400 error = cap_check(&haverights, needrightsp);
2403 if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2404 error = cap_fcntl_check_fde(&fde, needfcntl);
2410 count = fp->f_count;
2414 * Use an acquire barrier to prevent caching of fd_ofiles
2415 * so it is refreshed for verification.
2417 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2420 if (seq_consistent_nomb(fd_seq(fdp, fd), seq))
2422 if (fp == fdp->fd_ofiles[fd].fde_file)
2425 fdrop(fp, curthread);
2428 if (haverightsp != NULL) {
2430 *haverightsp = haverights;
2432 CAP_ALL(haverightsp);
2439 * Extract the file pointer associated with the specified descriptor for the
2440 * current user process.
2442 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2445 * File's rights will be checked against the capability rights mask.
2447 * If an error occured the non-zero error is returned and *fpp is set to
2448 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2449 * responsible for fdrop().
2452 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2453 cap_rights_t *needrightsp, u_char *maxprotp)
2455 struct filedesc *fdp;
2457 cap_rights_t haverights, needrights;
2461 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2463 if (needrightsp != NULL)
2464 needrights = *needrightsp;
2466 cap_rights_init(&needrights);
2467 if (maxprotp != NULL)
2468 cap_rights_set(&needrights, CAP_MMAP);
2469 error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2472 if (fp->f_ops == &badfileops) {
2479 * If requested, convert capability rights to access flags.
2481 if (maxprotp != NULL)
2482 *maxprotp = cap_rights_to_vmprot(&haverights);
2483 #else /* !CAPABILITIES */
2484 if (maxprotp != NULL)
2485 *maxprotp = VM_PROT_ALL;
2486 #endif /* CAPABILITIES */
2489 * FREAD and FWRITE failure return EBADF as per POSIX.
2495 if ((fp->f_flag & flags) == 0)
2499 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2500 ((fp->f_flag & FWRITE) != 0))
2506 KASSERT(0, ("wrong flags"));
2519 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2522 return(_fget(td, fd, fpp, 0, rightsp, NULL));
2526 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2530 return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2534 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2537 return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2541 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2544 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2548 * Like fget() but loads the underlying vnode, or returns an error if the
2549 * descriptor does not represent a vnode. Note that pipes use vnodes but
2550 * never have VM objects. The returned vnode will be vref()'d.
2552 * XXX: what about the unused flags ?
2555 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2562 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2565 if (fp->f_vnode == NULL) {
2577 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2580 return (_fgetvp(td, fd, 0, rightsp, vpp));
2584 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2585 struct filecaps *havecaps, struct vnode **vpp)
2587 struct filedesc *fdp;
2593 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2596 fp = fget_locked(fdp, fd);
2597 if (fp == NULL || fp->f_ops == &badfileops)
2601 if (needrightsp != NULL) {
2602 error = cap_check(cap_rights(fdp, fd), needrightsp);
2608 if (fp->f_vnode == NULL)
2613 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2619 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2622 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2626 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2629 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2634 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2638 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2643 * Like fget() but loads the underlying socket, or returns an error if the
2644 * descriptor does not represent a socket.
2646 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2649 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2650 * on their file descriptor reference to prevent the socket from being free'd
2654 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2663 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2665 if (fp->f_type != DTYPE_SOCKET) {
2670 *fflagp = fp->f_flag;
2681 * Drop the reference count on the socket and XXX release the SX lock in the
2682 * future. The last reference closes the socket.
2684 * Note: fputsock() is deprecated, see comment for fgetsock().
2687 fputsock(struct socket *so)
2692 CURVNET_SET(so->so_vnet);
2698 * Handle the last reference to a file being closed.
2701 _fdrop(struct file *fp, struct thread *td)
2706 if (fp->f_count != 0)
2707 panic("fdrop: count %d", fp->f_count);
2708 if (fp->f_ops != &badfileops)
2709 error = fo_close(fp, td);
2710 atomic_subtract_int(&openfiles, 1);
2712 free(fp->f_advice, M_FADVISE);
2713 uma_zfree(file_zone, fp);
2719 * Apply an advisory lock on a file descriptor.
2721 * Just attempt to get a record lock of the requested type on the entire file
2722 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2724 #ifndef _SYS_SYSPROTO_H_
2732 sys_flock(struct thread *td, struct flock_args *uap)
2737 cap_rights_t rights;
2740 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2743 if (fp->f_type != DTYPE_VNODE) {
2745 return (EOPNOTSUPP);
2749 lf.l_whence = SEEK_SET;
2752 if (uap->how & LOCK_UN) {
2753 lf.l_type = F_UNLCK;
2754 atomic_clear_int(&fp->f_flag, FHASLOCK);
2755 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2758 if (uap->how & LOCK_EX)
2759 lf.l_type = F_WRLCK;
2760 else if (uap->how & LOCK_SH)
2761 lf.l_type = F_RDLCK;
2766 atomic_set_int(&fp->f_flag, FHASLOCK);
2767 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2768 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2774 * Duplicate the specified descriptor to a free descriptor.
2777 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2778 int openerror, int *indxp)
2780 struct filedescent *newfde, *oldfde;
2784 KASSERT(openerror == ENODEV || openerror == ENXIO,
2785 ("unexpected error %d in %s", openerror, __func__));
2788 * If the to-be-dup'd fd number is greater than the allowed number
2789 * of file descriptors, or the fd to be dup'd has already been
2790 * closed, then reject.
2792 FILEDESC_XLOCK(fdp);
2793 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2794 FILEDESC_XUNLOCK(fdp);
2798 error = fdalloc(td, 0, &indx);
2800 FILEDESC_XUNLOCK(fdp);
2805 * There are two cases of interest here.
2807 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2809 * For ENXIO steal away the file structure from (dfd) and store it in
2810 * (indx). (dfd) is effectively closed by this operation.
2812 switch (openerror) {
2815 * Check that the mode the file is being opened for is a
2816 * subset of the mode of the existing descriptor.
2818 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2819 fdunused(fdp, indx);
2820 FILEDESC_XUNLOCK(fdp);
2824 newfde = &fdp->fd_ofiles[indx];
2825 oldfde = &fdp->fd_ofiles[dfd];
2827 seq_write_begin(&newfde->fde_seq);
2829 memcpy(newfde, oldfde, fde_change_size);
2830 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
2832 seq_write_end(&newfde->fde_seq);
2837 * Steal away the file pointer from dfd and stuff it into indx.
2839 newfde = &fdp->fd_ofiles[indx];
2840 oldfde = &fdp->fd_ofiles[dfd];
2842 seq_write_begin(&newfde->fde_seq);
2844 memcpy(newfde, oldfde, fde_change_size);
2845 bzero(oldfde, fde_change_size);
2848 seq_write_end(&newfde->fde_seq);
2852 FILEDESC_XUNLOCK(fdp);
2858 * Scan all active processes and prisons to see if any of them have a current
2859 * or root directory of `olddp'. If so, replace them with the new mount point.
2862 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2864 struct filedesc *fdp;
2869 if (vrefcnt(olddp) == 1)
2872 sx_slock(&allproc_lock);
2873 FOREACH_PROC_IN_SYSTEM(p) {
2877 FILEDESC_XLOCK(fdp);
2878 if (fdp->fd_cdir == olddp) {
2880 fdp->fd_cdir = newdp;
2883 if (fdp->fd_rdir == olddp) {
2885 fdp->fd_rdir = newdp;
2888 if (fdp->fd_jdir == olddp) {
2890 fdp->fd_jdir = newdp;
2893 FILEDESC_XUNLOCK(fdp);
2896 sx_sunlock(&allproc_lock);
2897 if (rootvnode == olddp) {
2902 mtx_lock(&prison0.pr_mtx);
2903 if (prison0.pr_root == olddp) {
2905 prison0.pr_root = newdp;
2908 mtx_unlock(&prison0.pr_mtx);
2909 sx_slock(&allprison_lock);
2910 TAILQ_FOREACH(pr, &allprison, pr_list) {
2911 mtx_lock(&pr->pr_mtx);
2912 if (pr->pr_root == olddp) {
2914 pr->pr_root = newdp;
2917 mtx_unlock(&pr->pr_mtx);
2919 sx_sunlock(&allprison_lock);
2924 struct filedesc_to_leader *
2925 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2927 struct filedesc_to_leader *fdtol;
2929 fdtol = malloc(sizeof(struct filedesc_to_leader),
2930 M_FILEDESC_TO_LEADER,
2932 fdtol->fdl_refcount = 1;
2933 fdtol->fdl_holdcount = 0;
2934 fdtol->fdl_wakeup = 0;
2935 fdtol->fdl_leader = leader;
2937 FILEDESC_XLOCK(fdp);
2938 fdtol->fdl_next = old->fdl_next;
2939 fdtol->fdl_prev = old;
2940 old->fdl_next = fdtol;
2941 fdtol->fdl_next->fdl_prev = fdtol;
2942 FILEDESC_XUNLOCK(fdp);
2944 fdtol->fdl_next = fdtol;
2945 fdtol->fdl_prev = fdtol;
2951 * Get file structures globally.
2954 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2957 struct filedesc *fdp;
2962 error = sysctl_wire_old_buffer(req, 0);
2965 if (req->oldptr == NULL) {
2967 sx_slock(&allproc_lock);
2968 FOREACH_PROC_IN_SYSTEM(p) {
2969 if (p->p_state == PRS_NEW)
2974 /* overestimates sparse tables. */
2975 if (fdp->fd_lastfile > 0)
2976 n += fdp->fd_lastfile;
2979 sx_sunlock(&allproc_lock);
2980 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2983 bzero(&xf, sizeof(xf));
2984 xf.xf_size = sizeof(xf);
2985 sx_slock(&allproc_lock);
2986 FOREACH_PROC_IN_SYSTEM(p) {
2988 if (p->p_state == PRS_NEW) {
2992 if (p_cansee(req->td, p) != 0) {
2996 xf.xf_pid = p->p_pid;
2997 xf.xf_uid = p->p_ucred->cr_uid;
3002 FILEDESC_SLOCK(fdp);
3003 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3004 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3008 xf.xf_data = fp->f_data;
3009 xf.xf_vnode = fp->f_vnode;
3010 xf.xf_type = fp->f_type;
3011 xf.xf_count = fp->f_count;
3013 xf.xf_offset = foffset_get(fp);
3014 xf.xf_flag = fp->f_flag;
3015 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3019 FILEDESC_SUNLOCK(fdp);
3024 sx_sunlock(&allproc_lock);
3028 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3029 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3031 #ifdef KINFO_OFILE_SIZE
3032 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3035 #ifdef COMPAT_FREEBSD7
3037 export_vnode_for_osysctl(struct vnode *vp, int type,
3038 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
3041 char *fullpath, *freepath;
3043 bzero(kif, sizeof(*kif));
3044 kif->kf_structsize = sizeof(*kif);
3048 kif->kf_type = KF_TYPE_VNODE;
3049 /* This function only handles directories. */
3050 if (vp->v_type != VDIR) {
3054 kif->kf_vnode_type = KF_VTYPE_VDIR;
3057 * This is not a true file descriptor, so we set a bogus refcount
3058 * and offset to indicate these fields should be ignored.
3060 kif->kf_ref_count = -1;
3061 kif->kf_offset = -1;
3065 FILEDESC_SUNLOCK(fdp);
3066 vn_fullpath(curthread, vp, &fullpath, &freepath);
3068 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3069 if (freepath != NULL)
3070 free(freepath, M_TEMP);
3071 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3072 FILEDESC_SLOCK(fdp);
3077 * Get per-process file descriptors for use by procstat(1), et al.
3080 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3082 char *fullpath, *freepath;
3083 struct kinfo_ofile *kif;
3084 struct filedesc *fdp;
3085 int error, i, *name;
3086 struct shmfd *shmfd;
3095 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3102 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3103 FILEDESC_SLOCK(fdp);
3104 if (fdp->fd_cdir != NULL)
3105 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3107 if (fdp->fd_rdir != NULL)
3108 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3110 if (fdp->fd_jdir != NULL)
3111 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3113 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3114 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3116 bzero(kif, sizeof(*kif));
3117 kif->kf_structsize = sizeof(*kif);
3125 switch (fp->f_type) {
3127 kif->kf_type = KF_TYPE_VNODE;
3132 kif->kf_type = KF_TYPE_SOCKET;
3137 kif->kf_type = KF_TYPE_PIPE;
3141 kif->kf_type = KF_TYPE_FIFO;
3146 kif->kf_type = KF_TYPE_KQUEUE;
3150 kif->kf_type = KF_TYPE_CRYPTO;
3154 kif->kf_type = KF_TYPE_MQUEUE;
3158 kif->kf_type = KF_TYPE_SHM;
3163 kif->kf_type = KF_TYPE_SEM;
3168 kif->kf_type = KF_TYPE_PTS;
3173 case DTYPE_PROCDESC:
3174 kif->kf_type = KF_TYPE_PROCDESC;
3179 kif->kf_type = KF_TYPE_UNKNOWN;
3182 kif->kf_ref_count = fp->f_count;
3183 if (fp->f_flag & FREAD)
3184 kif->kf_flags |= KF_FLAG_READ;
3185 if (fp->f_flag & FWRITE)
3186 kif->kf_flags |= KF_FLAG_WRITE;
3187 if (fp->f_flag & FAPPEND)
3188 kif->kf_flags |= KF_FLAG_APPEND;
3189 if (fp->f_flag & FASYNC)
3190 kif->kf_flags |= KF_FLAG_ASYNC;
3191 if (fp->f_flag & FFSYNC)
3192 kif->kf_flags |= KF_FLAG_FSYNC;
3193 if (fp->f_flag & FNONBLOCK)
3194 kif->kf_flags |= KF_FLAG_NONBLOCK;
3195 if (fp->f_flag & O_DIRECT)
3196 kif->kf_flags |= KF_FLAG_DIRECT;
3197 if (fp->f_flag & FHASLOCK)
3198 kif->kf_flags |= KF_FLAG_HASLOCK;
3199 kif->kf_offset = foffset_get(fp);
3202 switch (vp->v_type) {
3204 kif->kf_vnode_type = KF_VTYPE_VNON;
3207 kif->kf_vnode_type = KF_VTYPE_VREG;
3210 kif->kf_vnode_type = KF_VTYPE_VDIR;
3213 kif->kf_vnode_type = KF_VTYPE_VBLK;
3216 kif->kf_vnode_type = KF_VTYPE_VCHR;
3219 kif->kf_vnode_type = KF_VTYPE_VLNK;
3222 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3225 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3228 kif->kf_vnode_type = KF_VTYPE_VBAD;
3231 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3235 * It is OK to drop the filedesc lock here as we will
3236 * re-validate and re-evaluate its properties when
3237 * the loop continues.
3241 FILEDESC_SUNLOCK(fdp);
3242 vn_fullpath(curthread, vp, &fullpath, &freepath);
3244 strlcpy(kif->kf_path, fullpath,
3245 sizeof(kif->kf_path));
3246 if (freepath != NULL)
3247 free(freepath, M_TEMP);
3248 FILEDESC_SLOCK(fdp);
3251 struct sockaddr *sa;
3253 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3254 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3255 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3258 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3259 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3260 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3263 kif->kf_sock_domain =
3264 so->so_proto->pr_domain->dom_family;
3265 kif->kf_sock_type = so->so_type;
3266 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3269 strlcpy(kif->kf_path, tty_devname(tp),
3270 sizeof(kif->kf_path));
3273 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3274 if (ks != NULL && ksem_info != NULL)
3275 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3276 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3280 FILEDESC_SUNLOCK(fdp);
3286 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3287 CTLFLAG_RD||CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3288 "Process ofiledesc entries");
3289 #endif /* COMPAT_FREEBSD7 */
3291 #ifdef KINFO_FILE_SIZE
3292 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3295 struct export_fd_buf {
3296 struct filedesc *fdp;
3299 struct kinfo_file kif;
3303 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3304 int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3309 } fflags_table[] = {
3310 { FAPPEND, KF_FLAG_APPEND },
3311 { FASYNC, KF_FLAG_ASYNC },
3312 { FFSYNC, KF_FLAG_FSYNC },
3313 { FHASLOCK, KF_FLAG_HASLOCK },
3314 { FNONBLOCK, KF_FLAG_NONBLOCK },
3315 { FREAD, KF_FLAG_READ },
3316 { FWRITE, KF_FLAG_WRITE },
3317 { O_CREAT, KF_FLAG_CREAT },
3318 { O_DIRECT, KF_FLAG_DIRECT },
3319 { O_EXCL, KF_FLAG_EXCL },
3320 { O_EXEC, KF_FLAG_EXEC },
3321 { O_EXLOCK, KF_FLAG_EXLOCK },
3322 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3323 { O_SHLOCK, KF_FLAG_SHLOCK },
3324 { O_TRUNC, KF_FLAG_TRUNC }
3326 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3327 struct kinfo_file *kif;
3332 if (efbuf->remainder == 0)
3335 bzero(kif, sizeof(*kif));
3336 locked = efbuf->fdp != NULL;
3341 FILEDESC_SUNLOCK(efbuf->fdp);
3344 vp = (struct vnode *)data;
3345 error = fill_vnode_info(vp, kif);
3348 case KF_TYPE_SOCKET:
3349 error = fill_socket_info((struct socket *)data, kif);
3352 error = fill_pipe_info((struct pipe *)data, kif);
3355 error = fill_pts_info((struct tty *)data, kif);
3357 case KF_TYPE_PROCDESC:
3358 error = fill_procdesc_info((struct procdesc *)data, kif);
3361 error = fill_sem_info((struct file *)data, kif);
3364 error = fill_shm_info((struct file *)data, kif);
3370 kif->kf_status |= KF_ATTR_VALID;
3373 * Translate file access flags.
3375 for (i = 0; i < NFFLAGS; i++)
3376 if (fflags & fflags_table[i].fflag)
3377 kif->kf_flags |= fflags_table[i].kf_fflag;
3378 if (rightsp != NULL)
3379 kif->kf_cap_rights = *rightsp;
3381 cap_rights_init(&kif->kf_cap_rights);
3383 kif->kf_type = type;
3384 kif->kf_ref_count = refcnt;
3385 kif->kf_offset = offset;
3386 /* Pack record size down */
3387 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3388 strlen(kif->kf_path) + 1;
3389 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3390 if (efbuf->remainder != -1) {
3391 if (efbuf->remainder < kif->kf_structsize) {
3392 /* Terminate export. */
3393 efbuf->remainder = 0;
3394 if (efbuf->fdp != NULL && !locked)
3395 FILEDESC_SLOCK(efbuf->fdp);
3398 efbuf->remainder -= kif->kf_structsize;
3401 FILEDESC_SUNLOCK(efbuf->fdp);
3402 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3403 if (efbuf->fdp != NULL)
3404 FILEDESC_SLOCK(efbuf->fdp);
3409 * Store a process file descriptor information to sbuf.
3411 * Takes a locked proc as argument, and returns with the proc unlocked.
3414 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3417 struct filedesc *fdp;
3418 struct export_fd_buf *efbuf;
3419 struct vnode *cttyvp, *textvp, *tracevp;
3423 int type, refcnt, fflags;
3424 cap_rights_t rights;
3426 PROC_LOCK_ASSERT(p, MA_OWNED);
3429 tracevp = p->p_tracevp;
3430 if (tracevp != NULL)
3433 textvp = p->p_textvp;
3436 /* Controlling tty. */
3438 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3439 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3445 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3448 efbuf->remainder = maxlen;
3449 if (tracevp != NULL)
3450 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3451 FREAD | FWRITE, -1, -1, NULL, efbuf);
3453 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3454 FREAD, -1, -1, NULL, efbuf);
3456 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3457 FREAD | FWRITE, -1, -1, NULL, efbuf);
3462 FILEDESC_SLOCK(fdp);
3463 /* working directory */
3464 if (fdp->fd_cdir != NULL) {
3466 data = fdp->fd_cdir;
3467 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3468 FREAD, -1, -1, NULL, efbuf);
3470 /* root directory */
3471 if (fdp->fd_rdir != NULL) {
3473 data = fdp->fd_rdir;
3474 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3475 FREAD, -1, -1, NULL, efbuf);
3477 /* jail directory */
3478 if (fdp->fd_jdir != NULL) {
3480 data = fdp->fd_jdir;
3481 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3482 FREAD, -1, -1, NULL, efbuf);
3484 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3485 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3489 rights = *cap_rights(fdp, i);
3490 #else /* !CAPABILITIES */
3491 cap_rights_init(&rights);
3493 switch (fp->f_type) {
3495 type = KF_TYPE_VNODE;
3501 type = KF_TYPE_SOCKET;
3506 type = KF_TYPE_PIPE;
3511 type = KF_TYPE_FIFO;
3517 type = KF_TYPE_KQUEUE;
3521 type = KF_TYPE_CRYPTO;
3525 type = KF_TYPE_MQUEUE;
3544 case DTYPE_PROCDESC:
3545 type = KF_TYPE_PROCDESC;
3551 type = KF_TYPE_UNKNOWN;
3554 refcnt = fp->f_count;
3555 fflags = fp->f_flag;
3556 offset = foffset_get(fp);
3559 * Create sysctl entry.
3560 * It is OK to drop the filedesc lock here as we will
3561 * re-validate and re-evaluate its properties when
3562 * the loop continues.
3564 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3565 offset, &rights, efbuf);
3569 FILEDESC_SUNLOCK(fdp);
3572 free(efbuf, M_TEMP);
3576 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3579 * Get per-process file descriptors for use by procstat(1), et al.
3582 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3587 int error, error2, *name;
3591 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3592 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3597 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3598 error = kern_proc_filedesc_out(p, &sb, maxlen);
3599 error2 = sbuf_finish(&sb);
3601 return (error != 0 ? error : error2);
3605 vntype_to_kinfo(int vtype)
3610 } vtypes_table[] = {
3611 { VBAD, KF_VTYPE_VBAD },
3612 { VBLK, KF_VTYPE_VBLK },
3613 { VCHR, KF_VTYPE_VCHR },
3614 { VDIR, KF_VTYPE_VDIR },
3615 { VFIFO, KF_VTYPE_VFIFO },
3616 { VLNK, KF_VTYPE_VLNK },
3617 { VNON, KF_VTYPE_VNON },
3618 { VREG, KF_VTYPE_VREG },
3619 { VSOCK, KF_VTYPE_VSOCK }
3621 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3625 * Perform vtype translation.
3627 for (i = 0; i < NVTYPES; i++)
3628 if (vtypes_table[i].vtype == vtype)
3631 return (vtypes_table[i].kf_vtype);
3633 return (KF_VTYPE_UNKNOWN);
3637 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3640 char *fullpath, *freepath;
3645 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3648 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3650 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3652 if (freepath != NULL)
3653 free(freepath, M_TEMP);
3656 * Retrieve vnode attributes.
3658 va.va_fsid = VNOVAL;
3660 vn_lock(vp, LK_SHARED | LK_RETRY);
3661 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3665 if (va.va_fsid != VNOVAL)
3666 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3668 kif->kf_un.kf_file.kf_file_fsid =
3669 vp->v_mount->mnt_stat.f_fsid.val[0];
3670 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3671 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3672 kif->kf_un.kf_file.kf_file_size = va.va_size;
3673 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3678 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3680 struct sockaddr *sa;
3681 struct inpcb *inpcb;
3682 struct unpcb *unpcb;
3687 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3688 kif->kf_sock_type = so->so_type;
3689 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3690 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3691 switch(kif->kf_sock_domain) {
3694 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3695 if (so->so_pcb != NULL) {
3696 inpcb = (struct inpcb *)(so->so_pcb);
3697 kif->kf_un.kf_sock.kf_sock_inpcb =
3698 (uintptr_t)inpcb->inp_ppcb;
3703 if (so->so_pcb != NULL) {
3704 unpcb = (struct unpcb *)(so->so_pcb);
3705 if (unpcb->unp_conn) {
3706 kif->kf_un.kf_sock.kf_sock_unpconn =
3707 (uintptr_t)unpcb->unp_conn;
3708 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3709 so->so_rcv.sb_state;
3710 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3711 so->so_snd.sb_state;
3716 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3717 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3718 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3721 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3722 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3723 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3726 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3727 sizeof(kif->kf_path));
3732 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3737 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3738 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3743 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3748 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3749 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3750 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3755 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3760 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3765 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3771 if (fp->f_data == NULL)
3773 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3775 if (ksem_info == NULL)
3777 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3778 &kif->kf_un.kf_sem.kf_sem_value);
3779 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3784 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3790 if (fp->f_data == NULL)
3792 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3794 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3795 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3796 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3800 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3801 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3802 "Process filedesc entries");
3806 * For the purposes of debugging, generate a human-readable string for the
3810 file_type_to_name(short type)
3840 * For the purposes of debugging, identify a process (if any, perhaps one of
3841 * many) that references the passed file in its file descriptor array. Return
3844 static struct proc *
3845 file_to_first_proc(struct file *fp)
3847 struct filedesc *fdp;
3851 FOREACH_PROC_IN_SYSTEM(p) {
3852 if (p->p_state == PRS_NEW)
3857 for (n = 0; n <= fdp->fd_lastfile; n++) {
3858 if (fp == fdp->fd_ofiles[n].fde_file)
3866 db_print_file(struct file *fp, int header)
3871 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3872 "File", "Type", "Data", "Flag", "GCFl", "Count",
3873 "MCount", "Vnode", "FPID", "FCmd");
3874 p = file_to_first_proc(fp);
3875 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3876 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3877 0, fp->f_count, 0, fp->f_vnode,
3878 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3881 DB_SHOW_COMMAND(file, db_show_file)
3886 db_printf("usage: show file <addr>\n");
3889 fp = (struct file *)addr;
3890 db_print_file(fp, 1);
3893 DB_SHOW_COMMAND(files, db_show_files)
3895 struct filedesc *fdp;
3902 FOREACH_PROC_IN_SYSTEM(p) {
3903 if (p->p_state == PRS_NEW)
3905 if ((fdp = p->p_fd) == NULL)
3907 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3908 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3910 db_print_file(fp, header);
3917 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3918 &maxfilesperproc, 0, "Maximum files allowed open per process");
3920 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3921 &maxfiles, 0, "Maximum number of files");
3923 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3924 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3928 filelistinit(void *dummy)
3931 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3932 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3933 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3934 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3936 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3938 /*-------------------------------------------------------------------*/
3941 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3942 int flags, struct thread *td)
3949 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3957 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3965 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3973 badfo_kqfilter(struct file *fp, struct knote *kn)
3980 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3988 badfo_close(struct file *fp, struct thread *td)
3995 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4003 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4011 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4012 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4013 int kflags, struct thread *td)
4019 struct fileops badfileops = {
4020 .fo_read = badfo_readwrite,
4021 .fo_write = badfo_readwrite,
4022 .fo_truncate = badfo_truncate,
4023 .fo_ioctl = badfo_ioctl,
4024 .fo_poll = badfo_poll,
4025 .fo_kqfilter = badfo_kqfilter,
4026 .fo_stat = badfo_stat,
4027 .fo_close = badfo_close,
4028 .fo_chmod = badfo_chmod,
4029 .fo_chown = badfo_chown,
4030 .fo_sendfile = badfo_sendfile,
4034 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4042 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4050 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4051 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4052 int kflags, struct thread *td)
4058 /*-------------------------------------------------------------------*/
4061 * File Descriptor pseudo-device driver (/dev/fd/).
4063 * Opening minor device N dup()s the file (if any) connected to file
4064 * descriptor N belonging to the calling process. Note that this driver
4065 * consists of only the ``open()'' routine, because all subsequent
4066 * references to this file will be direct to the other driver.
4068 * XXX: we could give this one a cloning event handler if necessary.
4073 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4077 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4078 * the file descriptor being sought for duplication. The error
4079 * return ensures that the vnode for this device will be released
4080 * by vn_open. Open will detect this special error and take the
4081 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4082 * will simply report the error.
4084 td->td_dupfd = dev2unit(dev);
4088 static struct cdevsw fildesc_cdevsw = {
4089 .d_version = D_VERSION,
4095 fildesc_drvinit(void *unused)
4099 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4100 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4101 make_dev_alias(dev, "stdin");
4102 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4103 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4104 make_dev_alias(dev, "stdout");
4105 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4106 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4107 make_dev_alias(dev, "stderr");
4110 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);