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/capsicum.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.
879 error = racct_set(p, RACCT_NOFILE, new + 1);
882 FILEDESC_XUNLOCK(fdp);
888 fdgrowtable_exp(fdp, new + 1);
889 oldfde = &fdp->fd_ofiles[old];
891 newfde = &fdp->fd_ofiles[new];
892 if (newfde->fde_file == NULL)
895 if ((error = fdalloc(td, new, &new)) != 0) {
896 FILEDESC_XUNLOCK(fdp);
900 newfde = &fdp->fd_ofiles[new];
903 KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
904 KASSERT(old != new, ("new fd is same as old"));
906 delfp = newfde->fde_file;
909 * Duplicate the source descriptor.
912 seq_write_begin(&newfde->fde_seq);
914 filecaps_free(&newfde->fde_caps);
915 memcpy(newfde, oldfde, fde_change_size);
916 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
917 if ((flags & DUP_CLOEXEC) != 0)
918 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
920 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
922 seq_write_end(&newfde->fde_seq);
927 (void) closefp(fdp, new, delfp, td, 1);
928 /* closefp() drops the FILEDESC lock for us. */
930 FILEDESC_XUNLOCK(fdp);
937 * If sigio is on the list associated with a process or process group,
938 * disable signalling from the device, remove sigio from the list and
942 funsetown(struct sigio **sigiop)
952 *(sigio->sio_myref) = NULL;
953 if ((sigio)->sio_pgid < 0) {
954 struct pgrp *pg = (sigio)->sio_pgrp;
956 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
960 struct proc *p = (sigio)->sio_proc;
962 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
967 crfree(sigio->sio_ucred);
968 free(sigio, M_SIGIO);
972 * Free a list of sigio structures.
973 * We only need to lock the SIGIO_LOCK because we have made ourselves
974 * inaccessible to callers of fsetown and therefore do not need to lock
975 * the proc or pgrp struct for the list manipulation.
978 funsetownlst(struct sigiolst *sigiolst)
984 sigio = SLIST_FIRST(sigiolst);
991 * Every entry of the list should belong
992 * to a single proc or pgrp.
994 if (sigio->sio_pgid < 0) {
995 pg = sigio->sio_pgrp;
996 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
997 } else /* if (sigio->sio_pgid > 0) */ {
999 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1003 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1004 *(sigio->sio_myref) = NULL;
1006 KASSERT(sigio->sio_pgid < 0,
1007 ("Proc sigio in pgrp sigio list"));
1008 KASSERT(sigio->sio_pgrp == pg,
1009 ("Bogus pgrp in sigio list"));
1011 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1014 } else /* if (p != NULL) */ {
1015 KASSERT(sigio->sio_pgid > 0,
1016 ("Pgrp sigio in proc sigio list"));
1017 KASSERT(sigio->sio_proc == p,
1018 ("Bogus proc in sigio list"));
1020 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1025 crfree(sigio->sio_ucred);
1026 free(sigio, M_SIGIO);
1033 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1035 * After permission checking, add a sigio structure to the sigio list for
1036 * the process or process group.
1039 fsetown(pid_t pgid, struct sigio **sigiop)
1043 struct sigio *sigio;
1053 /* Allocate and fill in the new sigio out of locks. */
1054 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1055 sigio->sio_pgid = pgid;
1056 sigio->sio_ucred = crhold(curthread->td_ucred);
1057 sigio->sio_myref = sigiop;
1059 sx_slock(&proctree_lock);
1068 * Policy - Don't allow a process to FSETOWN a process
1069 * in another session.
1071 * Remove this test to allow maximum flexibility or
1072 * restrict FSETOWN to the current process or process
1073 * group for maximum safety.
1076 if (proc->p_session != curthread->td_proc->p_session) {
1082 } else /* if (pgid < 0) */ {
1083 pgrp = pgfind(-pgid);
1091 * Policy - Don't allow a process to FSETOWN a process
1092 * in another session.
1094 * Remove this test to allow maximum flexibility or
1095 * restrict FSETOWN to the current process or process
1096 * group for maximum safety.
1098 if (pgrp->pg_session != curthread->td_proc->p_session) {
1109 * Since funsetownlst() is called without the proctree
1110 * locked, we need to check for P_WEXIT.
1111 * XXX: is ESRCH correct?
1113 if ((proc->p_flag & P_WEXIT) != 0) {
1118 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1119 sigio->sio_proc = proc;
1123 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1124 sigio->sio_pgrp = pgrp;
1127 sx_sunlock(&proctree_lock);
1134 sx_sunlock(&proctree_lock);
1135 crfree(sigio->sio_ucred);
1136 free(sigio, M_SIGIO);
1141 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1145 struct sigio **sigiop;
1150 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1156 * Function drops the filedesc lock on return.
1159 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1164 FILEDESC_XLOCK_ASSERT(fdp);
1167 if (td->td_proc->p_fdtol != NULL) {
1169 * Ask fdfree() to sleep to ensure that all relevant
1170 * process leaders can be traversed in closef().
1172 fdp->fd_holdleaderscount++;
1179 * We now hold the fp reference that used to be owned by the
1180 * descriptor array. We have to unlock the FILEDESC *AFTER*
1181 * knote_fdclose to prevent a race of the fd getting opened, a knote
1182 * added, and deleteing a knote for the new fd.
1184 knote_fdclose(td, fd);
1187 * We need to notify mqueue if the object is of type mqueue.
1189 if (fp->f_type == DTYPE_MQUEUE)
1190 mq_fdclose(td, fd, fp);
1191 FILEDESC_XUNLOCK(fdp);
1193 error = closef(fp, td);
1195 FILEDESC_XLOCK(fdp);
1196 fdp->fd_holdleaderscount--;
1197 if (fdp->fd_holdleaderscount == 0 &&
1198 fdp->fd_holdleaderswakeup != 0) {
1199 fdp->fd_holdleaderswakeup = 0;
1200 wakeup(&fdp->fd_holdleaderscount);
1202 FILEDESC_XUNLOCK(fdp);
1208 * Close a file descriptor.
1210 #ifndef _SYS_SYSPROTO_H_
1219 struct close_args *uap;
1222 return (kern_close(td, uap->fd));
1230 struct filedesc *fdp;
1233 fdp = td->td_proc->p_fd;
1235 AUDIT_SYSCLOSE(td, fd);
1237 FILEDESC_XLOCK(fdp);
1238 if ((fp = fget_locked(fdp, fd)) == NULL) {
1239 FILEDESC_XUNLOCK(fdp);
1244 /* closefp() drops the FILEDESC lock for us. */
1245 return (closefp(fdp, fd, fp, td, 1));
1249 * Close open file descriptors.
1251 #ifndef _SYS_SYSPROTO_H_
1252 struct closefrom_args {
1258 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1260 struct filedesc *fdp;
1263 fdp = td->td_proc->p_fd;
1264 AUDIT_ARG_FD(uap->lowfd);
1267 * Treat negative starting file descriptor values identical to
1268 * closefrom(0) which closes all files.
1272 FILEDESC_SLOCK(fdp);
1273 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1274 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1275 FILEDESC_SUNLOCK(fdp);
1276 (void)kern_close(td, fd);
1277 FILEDESC_SLOCK(fdp);
1280 FILEDESC_SUNLOCK(fdp);
1284 #if defined(COMPAT_43)
1286 * Return status information about a file descriptor.
1288 #ifndef _SYS_SYSPROTO_H_
1289 struct ofstat_args {
1296 ofstat(struct thread *td, struct ofstat_args *uap)
1302 error = kern_fstat(td, uap->fd, &ub);
1305 error = copyout(&oub, uap->sb, sizeof(oub));
1309 #endif /* COMPAT_43 */
1312 * Return status information about a file descriptor.
1314 #ifndef _SYS_SYSPROTO_H_
1322 sys_fstat(struct thread *td, struct fstat_args *uap)
1327 error = kern_fstat(td, uap->fd, &ub);
1329 error = copyout(&ub, uap->sb, sizeof(ub));
1334 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1337 cap_rights_t rights;
1342 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1346 AUDIT_ARG_FILE(td->td_proc, fp);
1348 error = fo_stat(fp, sbp, td->td_ucred, td);
1351 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1358 * Return status information about a file descriptor.
1360 #ifndef _SYS_SYSPROTO_H_
1361 struct nfstat_args {
1368 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1374 error = kern_fstat(td, uap->fd, &ub);
1376 cvtnstat(&ub, &nub);
1377 error = copyout(&nub, uap->sb, sizeof(nub));
1383 * Return pathconf information about a file descriptor.
1385 #ifndef _SYS_SYSPROTO_H_
1386 struct fpathconf_args {
1393 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1397 cap_rights_t rights;
1400 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1404 /* If asynchronous I/O is available, it works for all descriptors. */
1405 if (uap->name == _PC_ASYNC_IO) {
1406 td->td_retval[0] = async_io_version;
1411 vn_lock(vp, LK_SHARED | LK_RETRY);
1412 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1414 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1415 if (uap->name != _PC_PIPE_BUF) {
1418 td->td_retval[0] = PIPE_BUF;
1430 * Initialize filecaps structure.
1433 filecaps_init(struct filecaps *fcaps)
1436 bzero(fcaps, sizeof(*fcaps));
1437 fcaps->fc_nioctls = -1;
1441 * Copy filecaps structure allocating memory for ioctls array if needed.
1444 filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1449 if (src->fc_ioctls != NULL) {
1450 KASSERT(src->fc_nioctls > 0,
1451 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1453 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1454 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1455 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1460 * Move filecaps structure to the new place and clear the old place.
1463 filecaps_move(struct filecaps *src, struct filecaps *dst)
1467 bzero(src, sizeof(*src));
1471 * Fill the given filecaps structure with full rights.
1474 filecaps_fill(struct filecaps *fcaps)
1477 CAP_ALL(&fcaps->fc_rights);
1478 fcaps->fc_ioctls = NULL;
1479 fcaps->fc_nioctls = -1;
1480 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1484 * Free memory allocated within filecaps structure.
1487 filecaps_free(struct filecaps *fcaps)
1490 free(fcaps->fc_ioctls, M_FILECAPS);
1491 bzero(fcaps, sizeof(*fcaps));
1495 * Validate the given filecaps structure.
1498 filecaps_validate(const struct filecaps *fcaps, const char *func)
1501 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1502 ("%s: invalid rights", func));
1503 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1504 ("%s: invalid fcntls", func));
1505 KASSERT(fcaps->fc_fcntls == 0 ||
1506 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1507 ("%s: fcntls without CAP_FCNTL", func));
1508 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1509 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1510 ("%s: invalid ioctls", func));
1511 KASSERT(fcaps->fc_nioctls == 0 ||
1512 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1513 ("%s: ioctls without CAP_IOCTL", func));
1517 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1521 FILEDESC_XLOCK_ASSERT(fdp);
1523 nfd1 = fdp->fd_nfiles * 2;
1526 fdgrowtable(fdp, nfd1);
1530 * Grow the file table to accomodate (at least) nfd descriptors.
1533 fdgrowtable(struct filedesc *fdp, int nfd)
1535 struct filedesc0 *fdp0;
1536 struct freetable *ft;
1537 struct filedescent *ntable;
1538 struct filedescent *otable;
1539 int nnfiles, onfiles;
1540 NDSLOTTYPE *nmap, *omap;
1542 FILEDESC_XLOCK_ASSERT(fdp);
1544 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1546 /* save old values */
1547 onfiles = fdp->fd_nfiles;
1548 otable = fdp->fd_ofiles;
1551 /* compute the size of the new table */
1552 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1553 if (nnfiles <= onfiles)
1554 /* the table is already large enough */
1558 * Allocate a new table. We need enough space for the
1559 * file entries themselves and the struct freetable we will use
1560 * when we decommission the table and place it on the freelist.
1561 * We place the struct freetable in the middle so we don't have
1562 * to worry about padding.
1564 ntable = malloc(nnfiles * sizeof(ntable[0]) + sizeof(struct freetable),
1565 M_FILEDESC, M_ZERO | M_WAITOK);
1566 /* copy the old data over and point at the new tables */
1567 memcpy(ntable, otable, onfiles * sizeof(*otable));
1568 fdp->fd_ofiles = ntable;
1571 * Allocate a new map only if the old is not large enough. It will
1572 * grow at a slower rate than the table as it can map more
1573 * entries than the table can hold.
1575 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1576 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1578 /* copy over the old data and update the pointer */
1579 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1584 * In order to have a valid pattern for fget_unlocked()
1585 * fdp->fd_nfiles must be the last member to be updated, otherwise
1586 * fget_unlocked() consumers may reference a new, higher value for
1587 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1588 * resulting in OOB accesses.
1590 atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1593 * Do not free the old file table, as some threads may still
1594 * reference entries within it. Instead, place it on a freelist
1595 * which will be processed when the struct filedesc is released.
1597 * Note that if onfiles == NDFILE, we're dealing with the original
1598 * static allocation contained within (struct filedesc0 *)fdp,
1599 * which must not be freed.
1601 if (onfiles > NDFILE) {
1602 ft = (struct freetable *)&otable[onfiles];
1603 fdp0 = (struct filedesc0 *)fdp;
1604 ft->ft_table = otable;
1605 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1608 * The map does not have the same possibility of threads still
1609 * holding references to it. So always free it as long as it
1610 * does not reference the original static allocation.
1612 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1613 free(omap, M_FILEDESC);
1617 * Allocate a file descriptor for the process.
1620 fdalloc(struct thread *td, int minfd, int *result)
1622 struct proc *p = td->td_proc;
1623 struct filedesc *fdp = p->p_fd;
1624 int fd = -1, maxfd, allocfd;
1629 FILEDESC_XLOCK_ASSERT(fdp);
1631 if (fdp->fd_freefile > minfd)
1632 minfd = fdp->fd_freefile;
1634 maxfd = getmaxfd(p);
1637 * Search the bitmap for a free descriptor starting at minfd.
1638 * If none is found, grow the file table.
1640 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1643 if (fd >= fdp->fd_nfiles) {
1644 allocfd = min(fd * 2, maxfd);
1648 error = racct_set(p, RACCT_NOFILE, allocfd);
1655 * fd is already equal to first free descriptor >= minfd, so
1656 * we only need to grow the table and we are done.
1658 fdgrowtable_exp(fdp, allocfd);
1662 * Perform some sanity checks, then mark the file descriptor as
1663 * used and return it to the caller.
1665 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1666 ("invalid descriptor %d", fd));
1667 KASSERT(!fdisused(fdp, fd),
1668 ("fd_first_free() returned non-free descriptor"));
1669 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1670 ("file descriptor isn't free"));
1671 KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1678 * Allocate n file descriptors for the process.
1681 fdallocn(struct thread *td, int minfd, int *fds, int n)
1683 struct proc *p = td->td_proc;
1684 struct filedesc *fdp = p->p_fd;
1687 FILEDESC_XLOCK_ASSERT(fdp);
1689 if (!fdavail(td, n))
1692 for (i = 0; i < n; i++)
1693 if (fdalloc(td, 0, &fds[i]) != 0)
1697 for (i--; i >= 0; i--)
1698 fdunused(fdp, fds[i]);
1706 * Check to see whether n user file descriptors are available to the process
1710 fdavail(struct thread *td, int n)
1712 struct proc *p = td->td_proc;
1713 struct filedesc *fdp = td->td_proc->p_fd;
1716 FILEDESC_LOCK_ASSERT(fdp);
1719 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1720 * call racct_add() from there instead of dealing with containers
1724 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1726 last = min(fdp->fd_nfiles, lim);
1727 for (i = fdp->fd_freefile; i < last; i++) {
1728 if (fdp->fd_ofiles[i].fde_file == NULL && --n <= 0)
1735 * Create a new open file structure and allocate a file decriptor for the
1736 * process that refers to it. We add one reference to the file for the
1737 * descriptor table and one reference for resultfp. This is to prevent us
1738 * being preempted and the entry in the descriptor table closed after we
1739 * release the FILEDESC lock.
1742 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1747 error = falloc_noinstall(td, &fp);
1749 return (error); /* no reference held on error */
1751 error = finstall(td, fp, &fd, flags, NULL);
1753 fdrop(fp, td); /* one reference (fp only) */
1757 if (resultfp != NULL)
1758 *resultfp = fp; /* copy out result */
1760 fdrop(fp, td); /* release local reference */
1762 if (resultfd != NULL)
1769 * Create a new open file structure without allocating a file descriptor.
1772 falloc_noinstall(struct thread *td, struct file **resultfp)
1775 int maxuserfiles = maxfiles - (maxfiles / 20);
1776 static struct timeval lastfail;
1779 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1781 if ((openfiles >= maxuserfiles &&
1782 priv_check(td, PRIV_MAXFILES) != 0) ||
1783 openfiles >= maxfiles) {
1784 if (ppsratecheck(&lastfail, &curfail, 1)) {
1785 printf("kern.maxfiles limit exceeded by uid %i, "
1786 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1790 atomic_add_int(&openfiles, 1);
1791 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1792 refcount_init(&fp->f_count, 1);
1793 fp->f_cred = crhold(td->td_ucred);
1794 fp->f_ops = &badfileops;
1802 * Install a file in a file descriptor table.
1805 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1806 struct filecaps *fcaps)
1808 struct filedesc *fdp = td->td_proc->p_fd;
1809 struct filedescent *fde;
1812 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1813 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1815 filecaps_validate(fcaps, __func__);
1817 FILEDESC_XLOCK(fdp);
1818 if ((error = fdalloc(td, 0, fd))) {
1819 FILEDESC_XUNLOCK(fdp);
1823 fde = &fdp->fd_ofiles[*fd];
1825 seq_write_begin(&fde->fde_seq);
1828 if ((flags & O_CLOEXEC) != 0)
1829 fde->fde_flags |= UF_EXCLOSE;
1831 filecaps_move(fcaps, &fde->fde_caps);
1833 filecaps_fill(&fde->fde_caps);
1835 seq_write_end(&fde->fde_seq);
1837 FILEDESC_XUNLOCK(fdp);
1842 * Build a new filedesc structure from another.
1843 * Copy the current, root, and jail root vnode references.
1846 fdinit(struct filedesc *fdp)
1848 struct filedesc0 *newfdp;
1850 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1851 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1853 FILEDESC_SLOCK(fdp);
1854 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1855 if (newfdp->fd_fd.fd_cdir)
1856 VREF(newfdp->fd_fd.fd_cdir);
1857 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1858 if (newfdp->fd_fd.fd_rdir)
1859 VREF(newfdp->fd_fd.fd_rdir);
1860 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1861 if (newfdp->fd_fd.fd_jdir)
1862 VREF(newfdp->fd_fd.fd_jdir);
1863 FILEDESC_SUNLOCK(fdp);
1866 /* Create the file descriptor table. */
1867 newfdp->fd_fd.fd_refcnt = 1;
1868 newfdp->fd_fd.fd_holdcnt = 1;
1869 newfdp->fd_fd.fd_cmask = CMASK;
1870 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1871 newfdp->fd_fd.fd_nfiles = NDFILE;
1872 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1873 newfdp->fd_fd.fd_lastfile = -1;
1874 return (&newfdp->fd_fd);
1877 static struct filedesc *
1878 fdhold(struct proc *p)
1880 struct filedesc *fdp;
1882 mtx_lock(&fdesc_mtx);
1886 mtx_unlock(&fdesc_mtx);
1891 fddrop(struct filedesc *fdp)
1893 struct filedesc0 *fdp0;
1894 struct freetable *ft;
1897 mtx_lock(&fdesc_mtx);
1898 i = --fdp->fd_holdcnt;
1899 mtx_unlock(&fdesc_mtx);
1903 FILEDESC_LOCK_DESTROY(fdp);
1904 fdp0 = (struct filedesc0 *)fdp;
1905 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1906 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1907 free(ft->ft_table, M_FILEDESC);
1909 free(fdp, M_FILEDESC);
1913 * Share a filedesc structure.
1916 fdshare(struct filedesc *fdp)
1919 FILEDESC_XLOCK(fdp);
1921 FILEDESC_XUNLOCK(fdp);
1926 * Unshare a filedesc structure, if necessary by making a copy
1929 fdunshare(struct thread *td)
1931 struct filedesc *tmp;
1932 struct proc *p = td->td_proc;
1934 if (p->p_fd->fd_refcnt == 1)
1937 tmp = fdcopy(p->p_fd);
1943 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1944 * this is to ease callers, not catch errors.
1947 fdcopy(struct filedesc *fdp)
1949 struct filedesc *newfdp;
1950 struct filedescent *nfde, *ofde;
1953 /* Certain daemons might not have file descriptors. */
1957 newfdp = fdinit(fdp);
1958 FILEDESC_SLOCK(fdp);
1959 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1960 FILEDESC_SUNLOCK(fdp);
1961 FILEDESC_XLOCK(newfdp);
1962 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1963 FILEDESC_XUNLOCK(newfdp);
1964 FILEDESC_SLOCK(fdp);
1966 /* copy all passable descriptors (i.e. not kqueue) */
1967 newfdp->fd_freefile = -1;
1968 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1969 ofde = &fdp->fd_ofiles[i];
1970 if (fdisused(fdp, i) &&
1971 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1972 ofde->fde_file->f_ops != &badfileops) {
1973 nfde = &newfdp->fd_ofiles[i];
1975 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1976 fhold(nfde->fde_file);
1977 newfdp->fd_lastfile = i;
1979 if (newfdp->fd_freefile == -1)
1980 newfdp->fd_freefile = i;
1983 newfdp->fd_cmask = fdp->fd_cmask;
1984 FILEDESC_SUNLOCK(fdp);
1985 FILEDESC_XLOCK(newfdp);
1986 for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1987 if (newfdp->fd_ofiles[i].fde_file != NULL)
1990 if (newfdp->fd_freefile == -1)
1991 newfdp->fd_freefile = i;
1992 FILEDESC_XUNLOCK(newfdp);
1997 * Release a filedesc structure.
2000 fdescfree(struct thread *td)
2002 struct filedesc *fdp;
2004 struct filedesc_to_leader *fdtol;
2006 struct vnode *cdir, *jdir, *rdir, *vp;
2009 /* Certain daemons might not have file descriptors. */
2010 fdp = td->td_proc->p_fd;
2016 PROC_LOCK(td->td_proc);
2017 racct_set(td->td_proc, RACCT_NOFILE, 0);
2018 PROC_UNLOCK(td->td_proc);
2022 /* Check for special need to clear POSIX style locks */
2023 fdtol = td->td_proc->p_fdtol;
2024 if (fdtol != NULL) {
2025 FILEDESC_XLOCK(fdp);
2026 KASSERT(fdtol->fdl_refcount > 0,
2027 ("filedesc_to_refcount botch: fdl_refcount=%d",
2028 fdtol->fdl_refcount));
2029 if (fdtol->fdl_refcount == 1 &&
2030 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2031 for (i = 0; i <= fdp->fd_lastfile; i++) {
2032 fp = fdp->fd_ofiles[i].fde_file;
2033 if (fp == NULL || fp->f_type != DTYPE_VNODE)
2036 FILEDESC_XUNLOCK(fdp);
2037 lf.l_whence = SEEK_SET;
2040 lf.l_type = F_UNLCK;
2042 (void) VOP_ADVLOCK(vp,
2043 (caddr_t)td->td_proc->p_leader, F_UNLCK,
2045 FILEDESC_XLOCK(fdp);
2050 if (fdtol->fdl_refcount == 1) {
2051 if (fdp->fd_holdleaderscount > 0 &&
2052 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2054 * close() or do_dup() has cleared a reference
2055 * in a shared file descriptor table.
2057 fdp->fd_holdleaderswakeup = 1;
2058 sx_sleep(&fdp->fd_holdleaderscount,
2059 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2062 if (fdtol->fdl_holdcount > 0) {
2064 * Ensure that fdtol->fdl_leader remains
2065 * valid in closef().
2067 fdtol->fdl_wakeup = 1;
2068 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2073 fdtol->fdl_refcount--;
2074 if (fdtol->fdl_refcount == 0 &&
2075 fdtol->fdl_holdcount == 0) {
2076 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2077 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2080 td->td_proc->p_fdtol = NULL;
2081 FILEDESC_XUNLOCK(fdp);
2083 free(fdtol, M_FILEDESC_TO_LEADER);
2086 mtx_lock(&fdesc_mtx);
2087 td->td_proc->p_fd = NULL;
2088 mtx_unlock(&fdesc_mtx);
2090 FILEDESC_XLOCK(fdp);
2091 i = --fdp->fd_refcnt;
2093 FILEDESC_XUNLOCK(fdp);
2097 cdir = fdp->fd_cdir;
2098 fdp->fd_cdir = NULL;
2099 rdir = fdp->fd_rdir;
2100 fdp->fd_rdir = NULL;
2101 jdir = fdp->fd_jdir;
2102 fdp->fd_jdir = NULL;
2103 FILEDESC_XUNLOCK(fdp);
2105 for (i = 0; i <= fdp->fd_lastfile; i++) {
2106 fp = fdp->fd_ofiles[i].fde_file;
2108 fdfree_last(fdp, i);
2109 (void) closef(fp, td);
2113 if (fdp->fd_nfiles > NDFILE)
2114 free(fdp->fd_ofiles, M_FILEDESC);
2115 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2116 free(fdp->fd_map, M_FILEDESC);
2129 * For setugid programs, we don't want to people to use that setugidness
2130 * to generate error messages which write to a file which otherwise would
2131 * otherwise be off-limits to the process. We check for filesystems where
2132 * the vnode can change out from under us after execve (like [lin]procfs).
2134 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2135 * sufficient. We also don't check for setugidness since we know we are.
2138 is_unsafe(struct file *fp)
2140 if (fp->f_type == DTYPE_VNODE) {
2141 struct vnode *vp = fp->f_vnode;
2143 if ((vp->v_vflag & VV_PROCDEP) != 0)
2150 * Make this setguid thing safe, if at all possible.
2153 setugidsafety(struct thread *td)
2155 struct filedesc *fdp;
2159 fdp = td->td_proc->p_fd;
2160 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2161 FILEDESC_XLOCK(fdp);
2162 for (i = 0; i <= fdp->fd_lastfile; i++) {
2165 fp = fdp->fd_ofiles[i].fde_file;
2166 if (fp != NULL && is_unsafe(fp)) {
2167 knote_fdclose(td, i);
2169 * NULL-out descriptor prior to close to avoid
2170 * a race while close blocks.
2173 FILEDESC_XUNLOCK(fdp);
2174 (void) closef(fp, td);
2175 FILEDESC_XLOCK(fdp);
2178 FILEDESC_XUNLOCK(fdp);
2182 * If a specific file object occupies a specific file descriptor, close the
2183 * file descriptor entry and drop a reference on the file object. This is a
2184 * convenience function to handle a subsequent error in a function that calls
2185 * falloc() that handles the race that another thread might have closed the
2186 * file descriptor out from under the thread creating the file object.
2189 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2192 FILEDESC_XLOCK(fdp);
2193 if (fdp->fd_ofiles[idx].fde_file == fp) {
2195 FILEDESC_XUNLOCK(fdp);
2198 FILEDESC_XUNLOCK(fdp);
2202 * Close any files on exec?
2205 fdcloseexec(struct thread *td)
2207 struct filedesc *fdp;
2208 struct filedescent *fde;
2212 fdp = td->td_proc->p_fd;
2213 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2214 FILEDESC_XLOCK(fdp);
2215 for (i = 0; i <= fdp->fd_lastfile; i++) {
2216 fde = &fdp->fd_ofiles[i];
2218 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2219 (fde->fde_flags & UF_EXCLOSE))) {
2221 (void) closefp(fdp, i, fp, td, 0);
2222 /* closefp() drops the FILEDESC lock. */
2223 FILEDESC_XLOCK(fdp);
2226 FILEDESC_XUNLOCK(fdp);
2230 * It is unsafe for set[ug]id processes to be started with file
2231 * descriptors 0..2 closed, as these descriptors are given implicit
2232 * significance in the Standard C library. fdcheckstd() will create a
2233 * descriptor referencing /dev/null for each of stdin, stdout, and
2234 * stderr that is not already open.
2237 fdcheckstd(struct thread *td)
2239 struct filedesc *fdp;
2240 register_t retval, save;
2241 int i, error, devnull;
2243 fdp = td->td_proc->p_fd;
2244 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2247 for (i = 0; i < 3; i++) {
2248 if (fdp->fd_ofiles[i].fde_file != NULL)
2251 save = td->td_retval[0];
2252 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2254 devnull = td->td_retval[0];
2255 td->td_retval[0] = save;
2258 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2260 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2269 * Internal form of close. Decrement reference count on file structure.
2270 * Note: td may be NULL when closing a file that was being passed in a
2273 * XXXRW: Giant is not required for the caller, but often will be held; this
2274 * makes it moderately likely the Giant will be recursed in the VFS case.
2277 closef(struct file *fp, struct thread *td)
2281 struct filedesc_to_leader *fdtol;
2282 struct filedesc *fdp;
2285 * POSIX record locking dictates that any close releases ALL
2286 * locks owned by this process. This is handled by setting
2287 * a flag in the unlock to free ONLY locks obeying POSIX
2288 * semantics, and not to free BSD-style file locks.
2289 * If the descriptor was in a message, POSIX-style locks
2290 * aren't passed with the descriptor, and the thread pointer
2291 * will be NULL. Callers should be careful only to pass a
2292 * NULL thread pointer when there really is no owning
2293 * context that might have locks, or the locks will be
2296 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2298 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2299 lf.l_whence = SEEK_SET;
2302 lf.l_type = F_UNLCK;
2303 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2304 F_UNLCK, &lf, F_POSIX);
2306 fdtol = td->td_proc->p_fdtol;
2307 if (fdtol != NULL) {
2309 * Handle special case where file descriptor table is
2310 * shared between multiple process leaders.
2312 fdp = td->td_proc->p_fd;
2313 FILEDESC_XLOCK(fdp);
2314 for (fdtol = fdtol->fdl_next;
2315 fdtol != td->td_proc->p_fdtol;
2316 fdtol = fdtol->fdl_next) {
2317 if ((fdtol->fdl_leader->p_flag &
2320 fdtol->fdl_holdcount++;
2321 FILEDESC_XUNLOCK(fdp);
2322 lf.l_whence = SEEK_SET;
2325 lf.l_type = F_UNLCK;
2327 (void) VOP_ADVLOCK(vp,
2328 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2330 FILEDESC_XLOCK(fdp);
2331 fdtol->fdl_holdcount--;
2332 if (fdtol->fdl_holdcount == 0 &&
2333 fdtol->fdl_wakeup != 0) {
2334 fdtol->fdl_wakeup = 0;
2338 FILEDESC_XUNLOCK(fdp);
2341 return (fdrop(fp, td));
2345 * Initialize the file pointer with the specified properties.
2347 * The ops are set with release semantics to be certain that the flags, type,
2348 * and data are visible when ops is. This is to prevent ops methods from being
2349 * called with bad data.
2352 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2357 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2361 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2362 int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2365 struct filedescent fde;
2371 cap_rights_t haverights;
2376 * Avoid reads reordering and then a first access to the
2377 * fdp->fd_ofiles table which could result in OOB operation.
2379 if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2382 * Fetch the descriptor locklessly. We avoid fdrop() races by
2383 * never raising a refcount above 0. To accomplish this we have
2384 * to use a cmpset loop rather than an atomic_add. The descriptor
2385 * must be re-verified once we acquire a reference to be certain
2386 * that the identity is still correct and we did not lose a race
2387 * due to preemption.
2391 seq = seq_read(fd_seq(fdp, fd));
2392 fde = fdp->fd_ofiles[fd];
2393 if (!seq_consistent(fd_seq(fdp, fd), seq)) {
2399 fp = fdp->fd_ofiles[fd].fde_file;
2404 haverights = *cap_rights_fde(&fde);
2405 if (needrightsp != NULL) {
2406 error = cap_check(&haverights, needrightsp);
2409 if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2410 error = cap_fcntl_check_fde(&fde, needfcntl);
2416 count = fp->f_count;
2420 * Use an acquire barrier to prevent caching of fd_ofiles
2421 * so it is refreshed for verification.
2423 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2426 if (seq_consistent_nomb(fd_seq(fdp, fd), seq))
2428 if (fp == fdp->fd_ofiles[fd].fde_file)
2431 fdrop(fp, curthread);
2434 if (haverightsp != NULL) {
2436 *haverightsp = haverights;
2438 CAP_ALL(haverightsp);
2445 * Extract the file pointer associated with the specified descriptor for the
2446 * current user process.
2448 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2451 * File's rights will be checked against the capability rights mask.
2453 * If an error occured the non-zero error is returned and *fpp is set to
2454 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2455 * responsible for fdrop().
2458 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2459 cap_rights_t *needrightsp, u_char *maxprotp)
2461 struct filedesc *fdp;
2463 cap_rights_t haverights, needrights;
2467 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2469 if (needrightsp != NULL)
2470 needrights = *needrightsp;
2472 cap_rights_init(&needrights);
2473 if (maxprotp != NULL)
2474 cap_rights_set(&needrights, CAP_MMAP);
2475 error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2478 if (fp->f_ops == &badfileops) {
2485 * If requested, convert capability rights to access flags.
2487 if (maxprotp != NULL)
2488 *maxprotp = cap_rights_to_vmprot(&haverights);
2489 #else /* !CAPABILITIES */
2490 if (maxprotp != NULL)
2491 *maxprotp = VM_PROT_ALL;
2492 #endif /* CAPABILITIES */
2495 * FREAD and FWRITE failure return EBADF as per POSIX.
2501 if ((fp->f_flag & flags) == 0)
2505 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2506 ((fp->f_flag & FWRITE) != 0))
2512 KASSERT(0, ("wrong flags"));
2525 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2528 return(_fget(td, fd, fpp, 0, rightsp, NULL));
2532 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2536 return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2540 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2543 return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2547 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2550 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2554 * Like fget() but loads the underlying vnode, or returns an error if the
2555 * descriptor does not represent a vnode. Note that pipes use vnodes but
2556 * never have VM objects. The returned vnode will be vref()'d.
2558 * XXX: what about the unused flags ?
2561 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2568 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2571 if (fp->f_vnode == NULL) {
2583 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2586 return (_fgetvp(td, fd, 0, rightsp, vpp));
2590 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2591 struct filecaps *havecaps, struct vnode **vpp)
2593 struct filedesc *fdp;
2599 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2602 fp = fget_locked(fdp, fd);
2603 if (fp == NULL || fp->f_ops == &badfileops)
2607 if (needrightsp != NULL) {
2608 error = cap_check(cap_rights(fdp, fd), needrightsp);
2614 if (fp->f_vnode == NULL)
2619 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2625 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2628 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2632 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2635 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2640 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2644 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2649 * Like fget() but loads the underlying socket, or returns an error if the
2650 * descriptor does not represent a socket.
2652 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2655 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2656 * on their file descriptor reference to prevent the socket from being free'd
2660 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2669 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2671 if (fp->f_type != DTYPE_SOCKET) {
2676 *fflagp = fp->f_flag;
2687 * Drop the reference count on the socket and XXX release the SX lock in the
2688 * future. The last reference closes the socket.
2690 * Note: fputsock() is deprecated, see comment for fgetsock().
2693 fputsock(struct socket *so)
2698 CURVNET_SET(so->so_vnet);
2704 * Handle the last reference to a file being closed.
2707 _fdrop(struct file *fp, struct thread *td)
2712 if (fp->f_count != 0)
2713 panic("fdrop: count %d", fp->f_count);
2714 if (fp->f_ops != &badfileops)
2715 error = fo_close(fp, td);
2716 atomic_subtract_int(&openfiles, 1);
2718 free(fp->f_advice, M_FADVISE);
2719 uma_zfree(file_zone, fp);
2725 * Apply an advisory lock on a file descriptor.
2727 * Just attempt to get a record lock of the requested type on the entire file
2728 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2730 #ifndef _SYS_SYSPROTO_H_
2738 sys_flock(struct thread *td, struct flock_args *uap)
2743 cap_rights_t rights;
2746 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2749 if (fp->f_type != DTYPE_VNODE) {
2751 return (EOPNOTSUPP);
2755 lf.l_whence = SEEK_SET;
2758 if (uap->how & LOCK_UN) {
2759 lf.l_type = F_UNLCK;
2760 atomic_clear_int(&fp->f_flag, FHASLOCK);
2761 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2764 if (uap->how & LOCK_EX)
2765 lf.l_type = F_WRLCK;
2766 else if (uap->how & LOCK_SH)
2767 lf.l_type = F_RDLCK;
2772 atomic_set_int(&fp->f_flag, FHASLOCK);
2773 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2774 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2780 * Duplicate the specified descriptor to a free descriptor.
2783 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2784 int openerror, int *indxp)
2786 struct filedescent *newfde, *oldfde;
2790 KASSERT(openerror == ENODEV || openerror == ENXIO,
2791 ("unexpected error %d in %s", openerror, __func__));
2794 * If the to-be-dup'd fd number is greater than the allowed number
2795 * of file descriptors, or the fd to be dup'd has already been
2796 * closed, then reject.
2798 FILEDESC_XLOCK(fdp);
2799 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2800 FILEDESC_XUNLOCK(fdp);
2804 error = fdalloc(td, 0, &indx);
2806 FILEDESC_XUNLOCK(fdp);
2811 * There are two cases of interest here.
2813 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2815 * For ENXIO steal away the file structure from (dfd) and store it in
2816 * (indx). (dfd) is effectively closed by this operation.
2818 switch (openerror) {
2821 * Check that the mode the file is being opened for is a
2822 * subset of the mode of the existing descriptor.
2824 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2825 fdunused(fdp, indx);
2826 FILEDESC_XUNLOCK(fdp);
2830 newfde = &fdp->fd_ofiles[indx];
2831 oldfde = &fdp->fd_ofiles[dfd];
2833 seq_write_begin(&newfde->fde_seq);
2835 memcpy(newfde, oldfde, fde_change_size);
2836 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
2838 seq_write_end(&newfde->fde_seq);
2843 * Steal away the file pointer from dfd and stuff it into indx.
2845 newfde = &fdp->fd_ofiles[indx];
2846 oldfde = &fdp->fd_ofiles[dfd];
2848 seq_write_begin(&newfde->fde_seq);
2850 memcpy(newfde, oldfde, fde_change_size);
2851 bzero(oldfde, fde_change_size);
2854 seq_write_end(&newfde->fde_seq);
2858 FILEDESC_XUNLOCK(fdp);
2864 * Scan all active processes and prisons to see if any of them have a current
2865 * or root directory of `olddp'. If so, replace them with the new mount point.
2868 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2870 struct filedesc *fdp;
2875 if (vrefcnt(olddp) == 1)
2878 sx_slock(&allproc_lock);
2879 FOREACH_PROC_IN_SYSTEM(p) {
2883 FILEDESC_XLOCK(fdp);
2884 if (fdp->fd_cdir == olddp) {
2886 fdp->fd_cdir = newdp;
2889 if (fdp->fd_rdir == olddp) {
2891 fdp->fd_rdir = newdp;
2894 if (fdp->fd_jdir == olddp) {
2896 fdp->fd_jdir = newdp;
2899 FILEDESC_XUNLOCK(fdp);
2902 sx_sunlock(&allproc_lock);
2903 if (rootvnode == olddp) {
2908 mtx_lock(&prison0.pr_mtx);
2909 if (prison0.pr_root == olddp) {
2911 prison0.pr_root = newdp;
2914 mtx_unlock(&prison0.pr_mtx);
2915 sx_slock(&allprison_lock);
2916 TAILQ_FOREACH(pr, &allprison, pr_list) {
2917 mtx_lock(&pr->pr_mtx);
2918 if (pr->pr_root == olddp) {
2920 pr->pr_root = newdp;
2923 mtx_unlock(&pr->pr_mtx);
2925 sx_sunlock(&allprison_lock);
2930 struct filedesc_to_leader *
2931 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2933 struct filedesc_to_leader *fdtol;
2935 fdtol = malloc(sizeof(struct filedesc_to_leader),
2936 M_FILEDESC_TO_LEADER,
2938 fdtol->fdl_refcount = 1;
2939 fdtol->fdl_holdcount = 0;
2940 fdtol->fdl_wakeup = 0;
2941 fdtol->fdl_leader = leader;
2943 FILEDESC_XLOCK(fdp);
2944 fdtol->fdl_next = old->fdl_next;
2945 fdtol->fdl_prev = old;
2946 old->fdl_next = fdtol;
2947 fdtol->fdl_next->fdl_prev = fdtol;
2948 FILEDESC_XUNLOCK(fdp);
2950 fdtol->fdl_next = fdtol;
2951 fdtol->fdl_prev = fdtol;
2957 * Get file structures globally.
2960 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2963 struct filedesc *fdp;
2968 error = sysctl_wire_old_buffer(req, 0);
2971 if (req->oldptr == NULL) {
2973 sx_slock(&allproc_lock);
2974 FOREACH_PROC_IN_SYSTEM(p) {
2975 if (p->p_state == PRS_NEW)
2980 /* overestimates sparse tables. */
2981 if (fdp->fd_lastfile > 0)
2982 n += fdp->fd_lastfile;
2985 sx_sunlock(&allproc_lock);
2986 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2989 bzero(&xf, sizeof(xf));
2990 xf.xf_size = sizeof(xf);
2991 sx_slock(&allproc_lock);
2992 FOREACH_PROC_IN_SYSTEM(p) {
2994 if (p->p_state == PRS_NEW) {
2998 if (p_cansee(req->td, p) != 0) {
3002 xf.xf_pid = p->p_pid;
3003 xf.xf_uid = p->p_ucred->cr_uid;
3008 FILEDESC_SLOCK(fdp);
3009 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3010 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3014 xf.xf_data = fp->f_data;
3015 xf.xf_vnode = fp->f_vnode;
3016 xf.xf_type = fp->f_type;
3017 xf.xf_count = fp->f_count;
3019 xf.xf_offset = foffset_get(fp);
3020 xf.xf_flag = fp->f_flag;
3021 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3025 FILEDESC_SUNLOCK(fdp);
3030 sx_sunlock(&allproc_lock);
3034 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3035 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3037 #ifdef KINFO_OFILE_SIZE
3038 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3041 #ifdef COMPAT_FREEBSD7
3043 export_vnode_for_osysctl(struct vnode *vp, int type,
3044 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
3047 char *fullpath, *freepath;
3049 bzero(kif, sizeof(*kif));
3050 kif->kf_structsize = sizeof(*kif);
3054 kif->kf_type = KF_TYPE_VNODE;
3055 /* This function only handles directories. */
3056 if (vp->v_type != VDIR) {
3060 kif->kf_vnode_type = KF_VTYPE_VDIR;
3063 * This is not a true file descriptor, so we set a bogus refcount
3064 * and offset to indicate these fields should be ignored.
3066 kif->kf_ref_count = -1;
3067 kif->kf_offset = -1;
3071 FILEDESC_SUNLOCK(fdp);
3072 vn_fullpath(curthread, vp, &fullpath, &freepath);
3074 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3075 if (freepath != NULL)
3076 free(freepath, M_TEMP);
3077 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3078 FILEDESC_SLOCK(fdp);
3083 * Get per-process file descriptors for use by procstat(1), et al.
3086 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3088 char *fullpath, *freepath;
3089 struct kinfo_ofile *kif;
3090 struct filedesc *fdp;
3091 int error, i, *name;
3092 struct shmfd *shmfd;
3101 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3108 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3109 FILEDESC_SLOCK(fdp);
3110 if (fdp->fd_cdir != NULL)
3111 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3113 if (fdp->fd_rdir != NULL)
3114 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3116 if (fdp->fd_jdir != NULL)
3117 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3119 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3120 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3122 bzero(kif, sizeof(*kif));
3123 kif->kf_structsize = sizeof(*kif);
3131 switch (fp->f_type) {
3133 kif->kf_type = KF_TYPE_VNODE;
3138 kif->kf_type = KF_TYPE_SOCKET;
3143 kif->kf_type = KF_TYPE_PIPE;
3147 kif->kf_type = KF_TYPE_FIFO;
3152 kif->kf_type = KF_TYPE_KQUEUE;
3156 kif->kf_type = KF_TYPE_CRYPTO;
3160 kif->kf_type = KF_TYPE_MQUEUE;
3164 kif->kf_type = KF_TYPE_SHM;
3169 kif->kf_type = KF_TYPE_SEM;
3174 kif->kf_type = KF_TYPE_PTS;
3179 case DTYPE_PROCDESC:
3180 kif->kf_type = KF_TYPE_PROCDESC;
3185 kif->kf_type = KF_TYPE_UNKNOWN;
3188 kif->kf_ref_count = fp->f_count;
3189 if (fp->f_flag & FREAD)
3190 kif->kf_flags |= KF_FLAG_READ;
3191 if (fp->f_flag & FWRITE)
3192 kif->kf_flags |= KF_FLAG_WRITE;
3193 if (fp->f_flag & FAPPEND)
3194 kif->kf_flags |= KF_FLAG_APPEND;
3195 if (fp->f_flag & FASYNC)
3196 kif->kf_flags |= KF_FLAG_ASYNC;
3197 if (fp->f_flag & FFSYNC)
3198 kif->kf_flags |= KF_FLAG_FSYNC;
3199 if (fp->f_flag & FNONBLOCK)
3200 kif->kf_flags |= KF_FLAG_NONBLOCK;
3201 if (fp->f_flag & O_DIRECT)
3202 kif->kf_flags |= KF_FLAG_DIRECT;
3203 if (fp->f_flag & FHASLOCK)
3204 kif->kf_flags |= KF_FLAG_HASLOCK;
3205 kif->kf_offset = foffset_get(fp);
3208 switch (vp->v_type) {
3210 kif->kf_vnode_type = KF_VTYPE_VNON;
3213 kif->kf_vnode_type = KF_VTYPE_VREG;
3216 kif->kf_vnode_type = KF_VTYPE_VDIR;
3219 kif->kf_vnode_type = KF_VTYPE_VBLK;
3222 kif->kf_vnode_type = KF_VTYPE_VCHR;
3225 kif->kf_vnode_type = KF_VTYPE_VLNK;
3228 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3231 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3234 kif->kf_vnode_type = KF_VTYPE_VBAD;
3237 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3241 * It is OK to drop the filedesc lock here as we will
3242 * re-validate and re-evaluate its properties when
3243 * the loop continues.
3247 FILEDESC_SUNLOCK(fdp);
3248 vn_fullpath(curthread, vp, &fullpath, &freepath);
3250 strlcpy(kif->kf_path, fullpath,
3251 sizeof(kif->kf_path));
3252 if (freepath != NULL)
3253 free(freepath, M_TEMP);
3254 FILEDESC_SLOCK(fdp);
3257 struct sockaddr *sa;
3259 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3260 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3261 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3264 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3265 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3266 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3269 kif->kf_sock_domain =
3270 so->so_proto->pr_domain->dom_family;
3271 kif->kf_sock_type = so->so_type;
3272 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3275 strlcpy(kif->kf_path, tty_devname(tp),
3276 sizeof(kif->kf_path));
3279 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3280 if (ks != NULL && ksem_info != NULL)
3281 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3282 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3286 FILEDESC_SUNLOCK(fdp);
3292 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3293 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3294 "Process ofiledesc entries");
3295 #endif /* COMPAT_FREEBSD7 */
3297 #ifdef KINFO_FILE_SIZE
3298 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3301 struct export_fd_buf {
3302 struct filedesc *fdp;
3305 struct kinfo_file kif;
3309 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3310 int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3315 } fflags_table[] = {
3316 { FAPPEND, KF_FLAG_APPEND },
3317 { FASYNC, KF_FLAG_ASYNC },
3318 { FFSYNC, KF_FLAG_FSYNC },
3319 { FHASLOCK, KF_FLAG_HASLOCK },
3320 { FNONBLOCK, KF_FLAG_NONBLOCK },
3321 { FREAD, KF_FLAG_READ },
3322 { FWRITE, KF_FLAG_WRITE },
3323 { O_CREAT, KF_FLAG_CREAT },
3324 { O_DIRECT, KF_FLAG_DIRECT },
3325 { O_EXCL, KF_FLAG_EXCL },
3326 { O_EXEC, KF_FLAG_EXEC },
3327 { O_EXLOCK, KF_FLAG_EXLOCK },
3328 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3329 { O_SHLOCK, KF_FLAG_SHLOCK },
3330 { O_TRUNC, KF_FLAG_TRUNC }
3332 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3333 struct kinfo_file *kif;
3338 if (efbuf->remainder == 0)
3341 bzero(kif, sizeof(*kif));
3342 locked = efbuf->fdp != NULL;
3347 FILEDESC_SUNLOCK(efbuf->fdp);
3350 vp = (struct vnode *)data;
3351 error = fill_vnode_info(vp, kif);
3354 case KF_TYPE_SOCKET:
3355 error = fill_socket_info((struct socket *)data, kif);
3358 error = fill_pipe_info((struct pipe *)data, kif);
3361 error = fill_pts_info((struct tty *)data, kif);
3363 case KF_TYPE_PROCDESC:
3364 error = fill_procdesc_info((struct procdesc *)data, kif);
3367 error = fill_sem_info((struct file *)data, kif);
3370 error = fill_shm_info((struct file *)data, kif);
3376 kif->kf_status |= KF_ATTR_VALID;
3379 * Translate file access flags.
3381 for (i = 0; i < NFFLAGS; i++)
3382 if (fflags & fflags_table[i].fflag)
3383 kif->kf_flags |= fflags_table[i].kf_fflag;
3384 if (rightsp != NULL)
3385 kif->kf_cap_rights = *rightsp;
3387 cap_rights_init(&kif->kf_cap_rights);
3389 kif->kf_type = type;
3390 kif->kf_ref_count = refcnt;
3391 kif->kf_offset = offset;
3392 /* Pack record size down */
3393 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3394 strlen(kif->kf_path) + 1;
3395 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3396 if (efbuf->remainder != -1) {
3397 if (efbuf->remainder < kif->kf_structsize) {
3398 /* Terminate export. */
3399 efbuf->remainder = 0;
3400 if (efbuf->fdp != NULL && !locked)
3401 FILEDESC_SLOCK(efbuf->fdp);
3404 efbuf->remainder -= kif->kf_structsize;
3407 FILEDESC_SUNLOCK(efbuf->fdp);
3408 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM;
3409 if (efbuf->fdp != NULL)
3410 FILEDESC_SLOCK(efbuf->fdp);
3415 * Store a process file descriptor information to sbuf.
3417 * Takes a locked proc as argument, and returns with the proc unlocked.
3420 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3423 struct filedesc *fdp;
3424 struct export_fd_buf *efbuf;
3425 struct vnode *cttyvp, *textvp, *tracevp;
3429 int type, refcnt, fflags;
3430 cap_rights_t rights;
3432 PROC_LOCK_ASSERT(p, MA_OWNED);
3435 tracevp = p->p_tracevp;
3436 if (tracevp != NULL)
3439 textvp = p->p_textvp;
3442 /* Controlling tty. */
3444 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3445 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3451 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3454 efbuf->remainder = maxlen;
3455 if (tracevp != NULL)
3456 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3457 FREAD | FWRITE, -1, -1, NULL, efbuf);
3459 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3460 FREAD, -1, -1, NULL, efbuf);
3462 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3463 FREAD | FWRITE, -1, -1, NULL, efbuf);
3468 FILEDESC_SLOCK(fdp);
3469 /* working directory */
3470 if (fdp->fd_cdir != NULL) {
3472 data = fdp->fd_cdir;
3473 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3474 FREAD, -1, -1, NULL, efbuf);
3476 /* root directory */
3477 if (fdp->fd_rdir != NULL) {
3479 data = fdp->fd_rdir;
3480 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3481 FREAD, -1, -1, NULL, efbuf);
3483 /* jail directory */
3484 if (fdp->fd_jdir != NULL) {
3486 data = fdp->fd_jdir;
3487 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3488 FREAD, -1, -1, NULL, efbuf);
3490 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3491 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3495 rights = *cap_rights(fdp, i);
3496 #else /* !CAPABILITIES */
3497 cap_rights_init(&rights);
3499 switch (fp->f_type) {
3501 type = KF_TYPE_VNODE;
3507 type = KF_TYPE_SOCKET;
3512 type = KF_TYPE_PIPE;
3517 type = KF_TYPE_FIFO;
3523 type = KF_TYPE_KQUEUE;
3527 type = KF_TYPE_CRYPTO;
3531 type = KF_TYPE_MQUEUE;
3550 case DTYPE_PROCDESC:
3551 type = KF_TYPE_PROCDESC;
3557 type = KF_TYPE_UNKNOWN;
3560 refcnt = fp->f_count;
3561 fflags = fp->f_flag;
3562 offset = foffset_get(fp);
3565 * Create sysctl entry.
3566 * It is OK to drop the filedesc lock here as we will
3567 * re-validate and re-evaluate its properties when
3568 * the loop continues.
3570 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3571 offset, &rights, efbuf);
3575 FILEDESC_SUNLOCK(fdp);
3578 free(efbuf, M_TEMP);
3582 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3585 * Get per-process file descriptors for use by procstat(1), et al.
3588 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3593 int error, error2, *name;
3597 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3598 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3603 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3604 error = kern_proc_filedesc_out(p, &sb, maxlen);
3605 error2 = sbuf_finish(&sb);
3607 return (error != 0 ? error : error2);
3611 vntype_to_kinfo(int vtype)
3616 } vtypes_table[] = {
3617 { VBAD, KF_VTYPE_VBAD },
3618 { VBLK, KF_VTYPE_VBLK },
3619 { VCHR, KF_VTYPE_VCHR },
3620 { VDIR, KF_VTYPE_VDIR },
3621 { VFIFO, KF_VTYPE_VFIFO },
3622 { VLNK, KF_VTYPE_VLNK },
3623 { VNON, KF_VTYPE_VNON },
3624 { VREG, KF_VTYPE_VREG },
3625 { VSOCK, KF_VTYPE_VSOCK }
3627 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3631 * Perform vtype translation.
3633 for (i = 0; i < NVTYPES; i++)
3634 if (vtypes_table[i].vtype == vtype)
3637 return (vtypes_table[i].kf_vtype);
3639 return (KF_VTYPE_UNKNOWN);
3643 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3646 char *fullpath, *freepath;
3651 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3654 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3656 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3658 if (freepath != NULL)
3659 free(freepath, M_TEMP);
3662 * Retrieve vnode attributes.
3664 va.va_fsid = VNOVAL;
3666 vn_lock(vp, LK_SHARED | LK_RETRY);
3667 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3671 if (va.va_fsid != VNOVAL)
3672 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3674 kif->kf_un.kf_file.kf_file_fsid =
3675 vp->v_mount->mnt_stat.f_fsid.val[0];
3676 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3677 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3678 kif->kf_un.kf_file.kf_file_size = va.va_size;
3679 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3684 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3686 struct sockaddr *sa;
3687 struct inpcb *inpcb;
3688 struct unpcb *unpcb;
3693 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3694 kif->kf_sock_type = so->so_type;
3695 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3696 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3697 switch(kif->kf_sock_domain) {
3700 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3701 if (so->so_pcb != NULL) {
3702 inpcb = (struct inpcb *)(so->so_pcb);
3703 kif->kf_un.kf_sock.kf_sock_inpcb =
3704 (uintptr_t)inpcb->inp_ppcb;
3709 if (so->so_pcb != NULL) {
3710 unpcb = (struct unpcb *)(so->so_pcb);
3711 if (unpcb->unp_conn) {
3712 kif->kf_un.kf_sock.kf_sock_unpconn =
3713 (uintptr_t)unpcb->unp_conn;
3714 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3715 so->so_rcv.sb_state;
3716 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3717 so->so_snd.sb_state;
3722 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3723 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3724 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3727 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3728 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3729 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3732 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3733 sizeof(kif->kf_path));
3738 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3743 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3744 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3749 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3754 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3755 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3756 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3761 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3766 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3771 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3777 if (fp->f_data == NULL)
3779 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3781 if (ksem_info == NULL)
3783 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3784 &kif->kf_un.kf_sem.kf_sem_value);
3785 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3790 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3796 if (fp->f_data == NULL)
3798 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3800 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3801 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3802 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3806 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3807 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3808 "Process filedesc entries");
3812 * For the purposes of debugging, generate a human-readable string for the
3816 file_type_to_name(short type)
3846 * For the purposes of debugging, identify a process (if any, perhaps one of
3847 * many) that references the passed file in its file descriptor array. Return
3850 static struct proc *
3851 file_to_first_proc(struct file *fp)
3853 struct filedesc *fdp;
3857 FOREACH_PROC_IN_SYSTEM(p) {
3858 if (p->p_state == PRS_NEW)
3863 for (n = 0; n <= fdp->fd_lastfile; n++) {
3864 if (fp == fdp->fd_ofiles[n].fde_file)
3872 db_print_file(struct file *fp, int header)
3877 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3878 "File", "Type", "Data", "Flag", "GCFl", "Count",
3879 "MCount", "Vnode", "FPID", "FCmd");
3880 p = file_to_first_proc(fp);
3881 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3882 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3883 0, fp->f_count, 0, fp->f_vnode,
3884 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3887 DB_SHOW_COMMAND(file, db_show_file)
3892 db_printf("usage: show file <addr>\n");
3895 fp = (struct file *)addr;
3896 db_print_file(fp, 1);
3899 DB_SHOW_COMMAND(files, db_show_files)
3901 struct filedesc *fdp;
3908 FOREACH_PROC_IN_SYSTEM(p) {
3909 if (p->p_state == PRS_NEW)
3911 if ((fdp = p->p_fd) == NULL)
3913 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3914 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3916 db_print_file(fp, header);
3923 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3924 &maxfilesperproc, 0, "Maximum files allowed open per process");
3926 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3927 &maxfiles, 0, "Maximum number of files");
3929 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3930 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3934 filelistinit(void *dummy)
3937 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3938 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3939 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3940 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3942 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3944 /*-------------------------------------------------------------------*/
3947 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3948 int flags, struct thread *td)
3955 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3963 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3971 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3979 badfo_kqfilter(struct file *fp, struct knote *kn)
3986 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3994 badfo_close(struct file *fp, struct thread *td)
4001 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4009 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4017 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4018 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4019 int kflags, struct thread *td)
4025 struct fileops badfileops = {
4026 .fo_read = badfo_readwrite,
4027 .fo_write = badfo_readwrite,
4028 .fo_truncate = badfo_truncate,
4029 .fo_ioctl = badfo_ioctl,
4030 .fo_poll = badfo_poll,
4031 .fo_kqfilter = badfo_kqfilter,
4032 .fo_stat = badfo_stat,
4033 .fo_close = badfo_close,
4034 .fo_chmod = badfo_chmod,
4035 .fo_chown = badfo_chown,
4036 .fo_sendfile = badfo_sendfile,
4040 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4048 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4056 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4057 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4058 int kflags, struct thread *td)
4064 /*-------------------------------------------------------------------*/
4067 * File Descriptor pseudo-device driver (/dev/fd/).
4069 * Opening minor device N dup()s the file (if any) connected to file
4070 * descriptor N belonging to the calling process. Note that this driver
4071 * consists of only the ``open()'' routine, because all subsequent
4072 * references to this file will be direct to the other driver.
4074 * XXX: we could give this one a cloning event handler if necessary.
4079 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4083 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4084 * the file descriptor being sought for duplication. The error
4085 * return ensures that the vnode for this device will be released
4086 * by vn_open. Open will detect this special error and take the
4087 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4088 * will simply report the error.
4090 td->td_dupfd = dev2unit(dev);
4094 static struct cdevsw fildesc_cdevsw = {
4095 .d_version = D_VERSION,
4101 fildesc_drvinit(void *unused)
4105 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4106 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4107 make_dev_alias(dev, "stdin");
4108 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4109 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4110 make_dev_alias(dev, "stdout");
4111 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4112 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4113 make_dev_alias(dev, "stderr");
4116 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);