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>
53 #include <sys/fcntl.h>
55 #include <sys/filedesc.h>
56 #include <sys/filio.h>
58 #include <sys/kernel.h>
60 #include <sys/limits.h>
62 #include <sys/malloc.h>
64 #include <sys/mount.h>
65 #include <sys/mqueue.h>
66 #include <sys/mutex.h>
67 #include <sys/namei.h>
68 #include <sys/selinfo.h>
72 #include <sys/procdesc.h>
73 #include <sys/protosw.h>
74 #include <sys/racct.h>
75 #include <sys/resourcevar.h>
77 #include <sys/signalvar.h>
78 #include <sys/socketvar.h>
81 #include <sys/syscallsubr.h>
82 #include <sys/sysctl.h>
83 #include <sys/sysproto.h>
85 #include <sys/unistd.h>
87 #include <sys/unpcb.h>
89 #include <sys/vnode.h>
91 #include <sys/ktrace.h>
96 #include <netinet/in.h>
97 #include <netinet/in_pcb.h>
99 #include <security/audit/audit.h>
106 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
107 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
108 "file desc to leader structures");
109 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
110 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
112 MALLOC_DECLARE(M_FADVISE);
114 static uma_zone_t file_zone;
116 void (*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
118 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
119 struct thread *td, int holdleaders);
120 static int fd_first_free(struct filedesc *fdp, int low, int size);
121 static int fd_last_used(struct filedesc *fdp, int size);
122 static void fdgrowtable(struct filedesc *fdp, int nfd);
123 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
124 static void fdunused(struct filedesc *fdp, int fd);
125 static void fdused(struct filedesc *fdp, int fd);
126 static int fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
127 static int fill_procdesc_info(struct procdesc *pdp,
128 struct kinfo_file *kif);
129 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
130 static int fill_sem_info(struct file *fp, struct kinfo_file *kif);
131 static int fill_shm_info(struct file *fp, struct kinfo_file *kif);
132 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
133 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
134 static int getmaxfd(struct proc *p);
139 * - An array of open file descriptors (fd_ofiles)
140 * - An array of file flags (fd_ofileflags)
141 * - A bitmap recording which descriptors are in use (fd_map)
143 * A process starts out with NDFILE descriptors. The value of NDFILE has
144 * been selected based the historical limit of 20 open files, and an
145 * assumption that the majority of processes, especially short-lived
146 * processes like shells, will never need more.
148 * If this initial allocation is exhausted, a larger descriptor table and
149 * map are allocated dynamically, and the pointers in the process's struct
150 * filedesc are updated to point to those. This is repeated every time
151 * the process runs out of file descriptors (provided it hasn't hit its
154 * Since threads may hold references to individual descriptor table
155 * entries, the tables are never freed. Instead, they are placed on a
156 * linked list and freed only when the struct filedesc is released.
159 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
160 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
161 #define NDSLOT(x) ((x) / NDENTRIES)
162 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
163 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
166 * SLIST entry used to keep track of ofiles which must be reclaimed when
170 struct filedescent *ft_table;
171 SLIST_ENTRY(freetable) ft_next;
175 * Initial allocation: a filedesc structure + the head of SLIST used to
176 * keep track of old ofiles + enough space for NDFILE descriptors.
179 struct filedesc fd_fd;
180 SLIST_HEAD(, freetable) fd_free;
181 struct filedescent fd_dfiles[NDFILE];
182 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
186 * Descriptor management.
188 volatile int openfiles; /* actual number of open files */
189 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
190 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
192 /* A mutex to protect the association between a proc and filedesc. */
193 static struct mtx fdesc_mtx;
196 * If low >= size, just return low. Otherwise find the first zero bit in the
197 * given bitmap, starting at low and not exceeding size - 1. Return size if
201 fd_first_free(struct filedesc *fdp, int low, int size)
203 NDSLOTTYPE *map = fdp->fd_map;
211 if (low % NDENTRIES) {
212 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
213 if ((mask &= ~map[off]) != 0UL)
214 return (off * NDENTRIES + ffsl(mask) - 1);
217 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
218 if (map[off] != ~0UL)
219 return (off * NDENTRIES + ffsl(~map[off]) - 1);
224 * Find the highest non-zero bit in the given bitmap, starting at 0 and
225 * not exceeding size - 1. Return -1 if not found.
228 fd_last_used(struct filedesc *fdp, int size)
230 NDSLOTTYPE *map = fdp->fd_map;
235 if (size % NDENTRIES) {
236 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
237 if ((mask &= map[off]) != 0)
238 return (off * NDENTRIES + flsl(mask) - 1);
241 for (minoff = NDSLOT(0); off >= minoff; --off)
243 return (off * NDENTRIES + flsl(map[off]) - 1);
248 fdisused(struct filedesc *fdp, int fd)
251 FILEDESC_LOCK_ASSERT(fdp);
253 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
254 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
256 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
260 * Mark a file descriptor as used.
263 fdused(struct filedesc *fdp, int fd)
266 FILEDESC_XLOCK_ASSERT(fdp);
268 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
270 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
271 if (fd > fdp->fd_lastfile)
272 fdp->fd_lastfile = fd;
273 if (fd == fdp->fd_freefile)
274 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
278 * Mark a file descriptor as unused.
281 fdunused(struct filedesc *fdp, int fd)
284 FILEDESC_XLOCK_ASSERT(fdp);
286 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
287 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
288 ("fd=%d is still in use", fd));
290 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
291 if (fd < fdp->fd_freefile)
292 fdp->fd_freefile = fd;
293 if (fd == fdp->fd_lastfile)
294 fdp->fd_lastfile = fd_last_used(fdp, fd);
298 * Free a file descriptor.
300 * Avoid some work if fdp is about to be destroyed.
303 _fdfree(struct filedesc *fdp, int fd, int last)
305 struct filedescent *fde;
307 fde = &fdp->fd_ofiles[fd];
310 seq_write_begin(&fde->fde_seq);
312 filecaps_free(&fde->fde_caps);
315 bzero(fde, fde_change_size);
318 seq_write_end(&fde->fde_seq);
323 fdfree(struct filedesc *fdp, int fd)
330 fdfree_last(struct filedesc *fdp, int fd)
337 * System calls on descriptors.
339 #ifndef _SYS_SYSPROTO_H_
340 struct getdtablesize_args {
346 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
348 struct proc *p = td->td_proc;
353 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
354 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
356 if (lim < td->td_retval[0])
357 td->td_retval[0] = lim;
362 * Duplicate a file descriptor to a particular value.
364 * Note: keep in mind that a potential race condition exists when closing
365 * descriptors from a shared descriptor table (via rfork).
367 #ifndef _SYS_SYSPROTO_H_
375 sys_dup2(struct thread *td, struct dup2_args *uap)
378 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
383 * Duplicate a file descriptor.
385 #ifndef _SYS_SYSPROTO_H_
392 sys_dup(struct thread *td, struct dup_args *uap)
395 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
399 * The file control system call.
401 #ifndef _SYS_SYSPROTO_H_
410 sys_fcntl(struct thread *td, struct fcntl_args *uap)
413 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
417 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
431 * Convert old flock structure to new.
433 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
434 fl.l_start = ofl.l_start;
435 fl.l_len = ofl.l_len;
436 fl.l_pid = ofl.l_pid;
437 fl.l_type = ofl.l_type;
438 fl.l_whence = ofl.l_whence;
452 arg1 = (intptr_t)&fl;
458 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
459 arg1 = (intptr_t)&fl;
467 error = kern_fcntl(td, fd, newcmd, arg1);
470 if (cmd == F_OGETLK) {
471 ofl.l_start = fl.l_start;
472 ofl.l_len = fl.l_len;
473 ofl.l_pid = fl.l_pid;
474 ofl.l_type = fl.l_type;
475 ofl.l_whence = fl.l_whence;
476 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
477 } else if (cmd == F_GETLK) {
478 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
484 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
486 struct filedesc *fdp;
488 struct file *fp, *fp2;
489 struct filedescent *fde;
505 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
508 case F_DUPFD_CLOEXEC:
510 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
516 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
519 case F_DUP2FD_CLOEXEC:
521 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
527 if ((fp = fget_locked(fdp, fd)) == NULL) {
528 FILEDESC_SUNLOCK(fdp);
532 fde = &fdp->fd_ofiles[fd];
534 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
535 FILEDESC_SUNLOCK(fdp);
540 if ((fp = fget_locked(fdp, fd)) == NULL) {
541 FILEDESC_XUNLOCK(fdp);
545 fde = &fdp->fd_ofiles[fd];
546 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
547 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
548 FILEDESC_XUNLOCK(fdp);
552 error = fget_unlocked(fdp, fd,
553 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
556 td->td_retval[0] = OFLAGS(fp->f_flag);
561 error = fget_unlocked(fdp, fd,
562 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
566 tmp = flg = fp->f_flag;
568 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
569 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
570 tmp = fp->f_flag & FNONBLOCK;
571 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
576 tmp = fp->f_flag & FASYNC;
577 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
582 atomic_clear_int(&fp->f_flag, FNONBLOCK);
584 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
589 error = fget_unlocked(fdp, fd,
590 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
593 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
595 td->td_retval[0] = tmp;
600 error = fget_unlocked(fdp, fd,
601 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
605 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
610 error = priv_check(td, PRIV_NFS_LOCKD);
618 /* FALLTHROUGH F_SETLK */
622 cap_rights_init(&rights, CAP_FLOCK);
623 error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
626 if (fp->f_type != DTYPE_VNODE) {
632 flp = (struct flock *)arg;
633 if (flp->l_whence == SEEK_CUR) {
634 foffset = foffset_get(fp);
637 foffset > OFF_MAX - flp->l_start)) {
638 FILEDESC_SUNLOCK(fdp);
643 flp->l_start += foffset;
647 switch (flp->l_type) {
649 if ((fp->f_flag & FREAD) == 0) {
653 PROC_LOCK(p->p_leader);
654 p->p_leader->p_flag |= P_ADVLOCK;
655 PROC_UNLOCK(p->p_leader);
656 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
660 if ((fp->f_flag & FWRITE) == 0) {
664 PROC_LOCK(p->p_leader);
665 p->p_leader->p_flag |= P_ADVLOCK;
666 PROC_UNLOCK(p->p_leader);
667 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
671 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
676 * Temporary api for testing remote lock
679 if (flg != F_REMOTE) {
683 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
684 F_UNLCKSYS, flp, flg);
690 if (error != 0 || flp->l_type == F_UNLCK ||
691 flp->l_type == F_UNLCKSYS) {
697 * Check for a race with close.
699 * The vnode is now advisory locked (or unlocked, but this case
700 * is not really important) as the caller requested.
701 * We had to drop the filedesc lock, so we need to recheck if
702 * the descriptor is still valid, because if it was closed
703 * in the meantime we need to remove advisory lock from the
704 * vnode - close on any descriptor leading to an advisory
705 * locked vnode, removes that lock.
706 * We will return 0 on purpose in that case, as the result of
707 * successful advisory lock might have been externally visible
708 * already. This is fine - effectively we pretend to the caller
709 * that the closing thread was a bit slower and that the
710 * advisory lock succeeded before the close.
712 error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
718 flp->l_whence = SEEK_SET;
721 flp->l_type = F_UNLCK;
722 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
723 F_UNLCK, flp, F_POSIX);
730 error = fget_unlocked(fdp, fd,
731 cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
734 if (fp->f_type != DTYPE_VNODE) {
739 flp = (struct flock *)arg;
740 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
741 flp->l_type != F_UNLCK) {
746 if (flp->l_whence == SEEK_CUR) {
747 foffset = foffset_get(fp);
748 if ((flp->l_start > 0 &&
749 foffset > OFF_MAX - flp->l_start) ||
751 foffset < OFF_MIN - flp->l_start)) {
752 FILEDESC_SUNLOCK(fdp);
757 flp->l_start += foffset;
760 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
766 arg = arg ? 128 * 1024: 0;
769 error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
772 if (fp->f_type != DTYPE_VNODE) {
779 * Exclusive lock synchronizes against f_seqcount reads and
780 * writes in sequential_heuristic().
782 error = vn_lock(vp, LK_EXCLUSIVE);
788 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
789 fp->f_seqcount = (arg + bsize - 1) / bsize;
790 atomic_set_int(&fp->f_flag, FRDAHEAD);
792 atomic_clear_int(&fp->f_flag, FRDAHEAD);
806 getmaxfd(struct proc *p)
811 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
818 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
821 do_dup(struct thread *td, int flags, int old, int new,
824 struct filedesc *fdp;
825 struct filedescent *oldfde, *newfde;
835 * Verify we have a valid descriptor to dup from and possibly to
836 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
837 * return EINVAL when the new descriptor is out of bounds.
842 return (flags & DUP_FCNTL ? EINVAL : EBADF);
845 return (flags & DUP_FCNTL ? EINVAL : EBADF);
848 if (fget_locked(fdp, old) == NULL) {
849 FILEDESC_XUNLOCK(fdp);
852 oldfde = &fdp->fd_ofiles[old];
853 if (flags & DUP_FIXED && old == new) {
855 if (flags & DUP_CLOEXEC)
856 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
857 FILEDESC_XUNLOCK(fdp);
860 fp = oldfde->fde_file;
864 * If the caller specified a file descriptor, make sure the file
865 * table is large enough to hold it, and grab it. Otherwise, just
866 * allocate a new descriptor the usual way.
868 if (flags & DUP_FIXED) {
869 if (new >= fdp->fd_nfiles) {
871 * The resource limits are here instead of e.g.
872 * fdalloc(), because the file descriptor table may be
873 * shared between processes, so we can't really use
874 * racct_add()/racct_sub(). Instead of counting the
875 * number of actually allocated descriptors, just put
876 * the limit on the size of the file descriptor table.
881 error = racct_set(p, RACCT_NOFILE, new + 1);
884 FILEDESC_XUNLOCK(fdp);
890 fdgrowtable_exp(fdp, new + 1);
891 oldfde = &fdp->fd_ofiles[old];
893 newfde = &fdp->fd_ofiles[new];
894 if (newfde->fde_file == NULL)
897 if ((error = fdalloc(td, new, &new)) != 0) {
898 FILEDESC_XUNLOCK(fdp);
902 newfde = &fdp->fd_ofiles[new];
905 KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
906 KASSERT(old != new, ("new fd is same as old"));
908 delfp = newfde->fde_file;
911 * Duplicate the source descriptor.
914 seq_write_begin(&newfde->fde_seq);
916 filecaps_free(&newfde->fde_caps);
917 memcpy(newfde, oldfde, fde_change_size);
918 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
919 if ((flags & DUP_CLOEXEC) != 0)
920 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
922 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
924 seq_write_end(&newfde->fde_seq);
929 (void) closefp(fdp, new, delfp, td, 1);
930 /* closefp() drops the FILEDESC lock for us. */
932 FILEDESC_XUNLOCK(fdp);
939 * If sigio is on the list associated with a process or process group,
940 * disable signalling from the device, remove sigio from the list and
944 funsetown(struct sigio **sigiop)
954 *(sigio->sio_myref) = NULL;
955 if ((sigio)->sio_pgid < 0) {
956 struct pgrp *pg = (sigio)->sio_pgrp;
958 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
962 struct proc *p = (sigio)->sio_proc;
964 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
969 crfree(sigio->sio_ucred);
970 free(sigio, M_SIGIO);
974 * Free a list of sigio structures.
975 * We only need to lock the SIGIO_LOCK because we have made ourselves
976 * inaccessible to callers of fsetown and therefore do not need to lock
977 * the proc or pgrp struct for the list manipulation.
980 funsetownlst(struct sigiolst *sigiolst)
986 sigio = SLIST_FIRST(sigiolst);
993 * Every entry of the list should belong
994 * to a single proc or pgrp.
996 if (sigio->sio_pgid < 0) {
997 pg = sigio->sio_pgrp;
998 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
999 } else /* if (sigio->sio_pgid > 0) */ {
1000 p = sigio->sio_proc;
1001 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1005 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1006 *(sigio->sio_myref) = NULL;
1008 KASSERT(sigio->sio_pgid < 0,
1009 ("Proc sigio in pgrp sigio list"));
1010 KASSERT(sigio->sio_pgrp == pg,
1011 ("Bogus pgrp in sigio list"));
1013 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1016 } else /* if (p != NULL) */ {
1017 KASSERT(sigio->sio_pgid > 0,
1018 ("Pgrp sigio in proc sigio list"));
1019 KASSERT(sigio->sio_proc == p,
1020 ("Bogus proc in sigio list"));
1022 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1027 crfree(sigio->sio_ucred);
1028 free(sigio, M_SIGIO);
1035 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1037 * After permission checking, add a sigio structure to the sigio list for
1038 * the process or process group.
1041 fsetown(pid_t pgid, struct sigio **sigiop)
1045 struct sigio *sigio;
1055 /* Allocate and fill in the new sigio out of locks. */
1056 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1057 sigio->sio_pgid = pgid;
1058 sigio->sio_ucred = crhold(curthread->td_ucred);
1059 sigio->sio_myref = sigiop;
1061 sx_slock(&proctree_lock);
1070 * Policy - Don't allow a process to FSETOWN a process
1071 * in another session.
1073 * Remove this test to allow maximum flexibility or
1074 * restrict FSETOWN to the current process or process
1075 * group for maximum safety.
1078 if (proc->p_session != curthread->td_proc->p_session) {
1084 } else /* if (pgid < 0) */ {
1085 pgrp = pgfind(-pgid);
1093 * Policy - Don't allow a process to FSETOWN a process
1094 * in another session.
1096 * Remove this test to allow maximum flexibility or
1097 * restrict FSETOWN to the current process or process
1098 * group for maximum safety.
1100 if (pgrp->pg_session != curthread->td_proc->p_session) {
1111 * Since funsetownlst() is called without the proctree
1112 * locked, we need to check for P_WEXIT.
1113 * XXX: is ESRCH correct?
1115 if ((proc->p_flag & P_WEXIT) != 0) {
1120 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1121 sigio->sio_proc = proc;
1125 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1126 sigio->sio_pgrp = pgrp;
1129 sx_sunlock(&proctree_lock);
1136 sx_sunlock(&proctree_lock);
1137 crfree(sigio->sio_ucred);
1138 free(sigio, M_SIGIO);
1143 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1147 struct sigio **sigiop;
1152 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1158 * Function drops the filedesc lock on return.
1161 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1166 FILEDESC_XLOCK_ASSERT(fdp);
1169 if (td->td_proc->p_fdtol != NULL) {
1171 * Ask fdfree() to sleep to ensure that all relevant
1172 * process leaders can be traversed in closef().
1174 fdp->fd_holdleaderscount++;
1181 * We now hold the fp reference that used to be owned by the
1182 * descriptor array. We have to unlock the FILEDESC *AFTER*
1183 * knote_fdclose to prevent a race of the fd getting opened, a knote
1184 * added, and deleteing a knote for the new fd.
1186 knote_fdclose(td, fd);
1189 * We need to notify mqueue if the object is of type mqueue.
1191 if (fp->f_type == DTYPE_MQUEUE)
1192 mq_fdclose(td, fd, fp);
1193 FILEDESC_XUNLOCK(fdp);
1195 error = closef(fp, td);
1197 FILEDESC_XLOCK(fdp);
1198 fdp->fd_holdleaderscount--;
1199 if (fdp->fd_holdleaderscount == 0 &&
1200 fdp->fd_holdleaderswakeup != 0) {
1201 fdp->fd_holdleaderswakeup = 0;
1202 wakeup(&fdp->fd_holdleaderscount);
1204 FILEDESC_XUNLOCK(fdp);
1210 * Close a file descriptor.
1212 #ifndef _SYS_SYSPROTO_H_
1219 sys_close(struct thread *td, struct close_args *uap)
1222 return (kern_close(td, uap->fd));
1226 kern_close(struct thread *td, int 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 accommodate (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);
1646 error = racct_set(p, RACCT_NOFILE, allocfd);
1653 * fd is already equal to first free descriptor >= minfd, so
1654 * we only need to grow the table and we are done.
1656 fdgrowtable_exp(fdp, allocfd);
1660 * Perform some sanity checks, then mark the file descriptor as
1661 * used and return it to the caller.
1663 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1664 ("invalid descriptor %d", fd));
1665 KASSERT(!fdisused(fdp, fd),
1666 ("fd_first_free() returned non-free descriptor"));
1667 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1668 ("file descriptor isn't free"));
1669 KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1676 * Allocate n file descriptors for the process.
1679 fdallocn(struct thread *td, int minfd, int *fds, int n)
1681 struct proc *p = td->td_proc;
1682 struct filedesc *fdp = p->p_fd;
1685 FILEDESC_XLOCK_ASSERT(fdp);
1687 if (!fdavail(td, n))
1690 for (i = 0; i < n; i++)
1691 if (fdalloc(td, 0, &fds[i]) != 0)
1695 for (i--; i >= 0; i--)
1696 fdunused(fdp, fds[i]);
1704 * Check to see whether n user file descriptors are available to the process
1708 fdavail(struct thread *td, int n)
1710 struct proc *p = td->td_proc;
1711 struct filedesc *fdp = td->td_proc->p_fd;
1714 FILEDESC_LOCK_ASSERT(fdp);
1717 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1718 * call racct_add() from there instead of dealing with containers
1722 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1724 last = min(fdp->fd_nfiles, lim);
1725 for (i = fdp->fd_freefile; i < last; i++) {
1726 if (fdp->fd_ofiles[i].fde_file == NULL && --n <= 0)
1733 * Create a new open file structure and allocate a file descriptor for the
1734 * process that refers to it. We add one reference to the file for the
1735 * descriptor table and one reference for resultfp. This is to prevent us
1736 * being preempted and the entry in the descriptor table closed after we
1737 * release the FILEDESC lock.
1740 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1745 error = falloc_noinstall(td, &fp);
1747 return (error); /* no reference held on error */
1749 error = finstall(td, fp, &fd, flags, NULL);
1751 fdrop(fp, td); /* one reference (fp only) */
1755 if (resultfp != NULL)
1756 *resultfp = fp; /* copy out result */
1758 fdrop(fp, td); /* release local reference */
1760 if (resultfd != NULL)
1767 * Create a new open file structure without allocating a file descriptor.
1770 falloc_noinstall(struct thread *td, struct file **resultfp)
1773 int maxuserfiles = maxfiles - (maxfiles / 20);
1774 static struct timeval lastfail;
1777 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1779 if ((openfiles >= maxuserfiles &&
1780 priv_check(td, PRIV_MAXFILES) != 0) ||
1781 openfiles >= maxfiles) {
1782 if (ppsratecheck(&lastfail, &curfail, 1)) {
1783 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1784 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1788 atomic_add_int(&openfiles, 1);
1789 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1790 refcount_init(&fp->f_count, 1);
1791 fp->f_cred = crhold(td->td_ucred);
1792 fp->f_ops = &badfileops;
1800 * Install a file in a file descriptor table.
1803 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1804 struct filecaps *fcaps)
1806 struct filedesc *fdp = td->td_proc->p_fd;
1807 struct filedescent *fde;
1810 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1811 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1813 filecaps_validate(fcaps, __func__);
1815 FILEDESC_XLOCK(fdp);
1816 if ((error = fdalloc(td, 0, fd))) {
1817 FILEDESC_XUNLOCK(fdp);
1821 fde = &fdp->fd_ofiles[*fd];
1823 seq_write_begin(&fde->fde_seq);
1826 if ((flags & O_CLOEXEC) != 0)
1827 fde->fde_flags |= UF_EXCLOSE;
1829 filecaps_move(fcaps, &fde->fde_caps);
1831 filecaps_fill(&fde->fde_caps);
1833 seq_write_end(&fde->fde_seq);
1835 FILEDESC_XUNLOCK(fdp);
1840 * Build a new filedesc structure from another.
1841 * Copy the current, root, and jail root vnode references.
1844 fdinit(struct filedesc *fdp)
1846 struct filedesc0 *newfdp;
1848 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1849 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1851 FILEDESC_SLOCK(fdp);
1852 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1853 if (newfdp->fd_fd.fd_cdir)
1854 VREF(newfdp->fd_fd.fd_cdir);
1855 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1856 if (newfdp->fd_fd.fd_rdir)
1857 VREF(newfdp->fd_fd.fd_rdir);
1858 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1859 if (newfdp->fd_fd.fd_jdir)
1860 VREF(newfdp->fd_fd.fd_jdir);
1861 FILEDESC_SUNLOCK(fdp);
1864 /* Create the file descriptor table. */
1865 newfdp->fd_fd.fd_refcnt = 1;
1866 newfdp->fd_fd.fd_holdcnt = 1;
1867 newfdp->fd_fd.fd_cmask = CMASK;
1868 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1869 newfdp->fd_fd.fd_nfiles = NDFILE;
1870 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1871 newfdp->fd_fd.fd_lastfile = -1;
1872 return (&newfdp->fd_fd);
1875 static struct filedesc *
1876 fdhold(struct proc *p)
1878 struct filedesc *fdp;
1880 mtx_lock(&fdesc_mtx);
1884 mtx_unlock(&fdesc_mtx);
1889 fddrop(struct filedesc *fdp)
1891 struct filedesc0 *fdp0;
1892 struct freetable *ft;
1895 mtx_lock(&fdesc_mtx);
1896 i = --fdp->fd_holdcnt;
1897 mtx_unlock(&fdesc_mtx);
1901 FILEDESC_LOCK_DESTROY(fdp);
1902 fdp0 = (struct filedesc0 *)fdp;
1903 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1904 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1905 free(ft->ft_table, M_FILEDESC);
1907 free(fdp, M_FILEDESC);
1911 * Share a filedesc structure.
1914 fdshare(struct filedesc *fdp)
1917 FILEDESC_XLOCK(fdp);
1919 FILEDESC_XUNLOCK(fdp);
1924 * Unshare a filedesc structure, if necessary by making a copy
1927 fdunshare(struct thread *td)
1929 struct filedesc *tmp;
1930 struct proc *p = td->td_proc;
1932 if (p->p_fd->fd_refcnt == 1)
1935 tmp = fdcopy(p->p_fd);
1941 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1942 * this is to ease callers, not catch errors.
1945 fdcopy(struct filedesc *fdp)
1947 struct filedesc *newfdp;
1948 struct filedescent *nfde, *ofde;
1951 /* Certain daemons might not have file descriptors. */
1955 newfdp = fdinit(fdp);
1956 FILEDESC_SLOCK(fdp);
1957 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1958 FILEDESC_SUNLOCK(fdp);
1959 FILEDESC_XLOCK(newfdp);
1960 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1961 FILEDESC_XUNLOCK(newfdp);
1962 FILEDESC_SLOCK(fdp);
1964 /* copy all passable descriptors (i.e. not kqueue) */
1965 newfdp->fd_freefile = -1;
1966 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1967 ofde = &fdp->fd_ofiles[i];
1968 if (fdisused(fdp, i) &&
1969 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1970 ofde->fde_file->f_ops != &badfileops) {
1971 nfde = &newfdp->fd_ofiles[i];
1973 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1974 fhold(nfde->fde_file);
1975 newfdp->fd_lastfile = i;
1977 if (newfdp->fd_freefile == -1)
1978 newfdp->fd_freefile = i;
1981 newfdp->fd_cmask = fdp->fd_cmask;
1982 FILEDESC_SUNLOCK(fdp);
1983 FILEDESC_XLOCK(newfdp);
1984 for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1985 if (newfdp->fd_ofiles[i].fde_file != NULL)
1988 if (newfdp->fd_freefile == -1)
1989 newfdp->fd_freefile = i;
1990 FILEDESC_XUNLOCK(newfdp);
1995 * Release a filedesc structure.
1998 fdescfree(struct thread *td)
2000 struct filedesc *fdp;
2002 struct filedesc_to_leader *fdtol;
2004 struct vnode *cdir, *jdir, *rdir, *vp;
2007 /* Certain daemons might not have file descriptors. */
2008 fdp = td->td_proc->p_fd;
2014 PROC_LOCK(td->td_proc);
2015 racct_set(td->td_proc, RACCT_NOFILE, 0);
2016 PROC_UNLOCK(td->td_proc);
2020 /* Check for special need to clear POSIX style locks */
2021 fdtol = td->td_proc->p_fdtol;
2022 if (fdtol != NULL) {
2023 FILEDESC_XLOCK(fdp);
2024 KASSERT(fdtol->fdl_refcount > 0,
2025 ("filedesc_to_refcount botch: fdl_refcount=%d",
2026 fdtol->fdl_refcount));
2027 if (fdtol->fdl_refcount == 1 &&
2028 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2029 for (i = 0; i <= fdp->fd_lastfile; i++) {
2030 fp = fdp->fd_ofiles[i].fde_file;
2031 if (fp == NULL || fp->f_type != DTYPE_VNODE)
2034 FILEDESC_XUNLOCK(fdp);
2035 lf.l_whence = SEEK_SET;
2038 lf.l_type = F_UNLCK;
2040 (void) VOP_ADVLOCK(vp,
2041 (caddr_t)td->td_proc->p_leader, F_UNLCK,
2043 FILEDESC_XLOCK(fdp);
2048 if (fdtol->fdl_refcount == 1) {
2049 if (fdp->fd_holdleaderscount > 0 &&
2050 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2052 * close() or do_dup() has cleared a reference
2053 * in a shared file descriptor table.
2055 fdp->fd_holdleaderswakeup = 1;
2056 sx_sleep(&fdp->fd_holdleaderscount,
2057 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2060 if (fdtol->fdl_holdcount > 0) {
2062 * Ensure that fdtol->fdl_leader remains
2063 * valid in closef().
2065 fdtol->fdl_wakeup = 1;
2066 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2071 fdtol->fdl_refcount--;
2072 if (fdtol->fdl_refcount == 0 &&
2073 fdtol->fdl_holdcount == 0) {
2074 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2075 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2078 td->td_proc->p_fdtol = NULL;
2079 FILEDESC_XUNLOCK(fdp);
2081 free(fdtol, M_FILEDESC_TO_LEADER);
2084 mtx_lock(&fdesc_mtx);
2085 td->td_proc->p_fd = NULL;
2086 mtx_unlock(&fdesc_mtx);
2088 FILEDESC_XLOCK(fdp);
2089 i = --fdp->fd_refcnt;
2091 FILEDESC_XUNLOCK(fdp);
2095 cdir = fdp->fd_cdir;
2096 fdp->fd_cdir = NULL;
2097 rdir = fdp->fd_rdir;
2098 fdp->fd_rdir = NULL;
2099 jdir = fdp->fd_jdir;
2100 fdp->fd_jdir = NULL;
2101 FILEDESC_XUNLOCK(fdp);
2103 for (i = 0; i <= fdp->fd_lastfile; i++) {
2104 fp = fdp->fd_ofiles[i].fde_file;
2106 fdfree_last(fdp, i);
2107 (void) closef(fp, td);
2111 if (fdp->fd_nfiles > NDFILE)
2112 free(fdp->fd_ofiles, M_FILEDESC);
2113 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2114 free(fdp->fd_map, M_FILEDESC);
2127 * For setugid programs, we don't want to people to use that setugidness
2128 * to generate error messages which write to a file which otherwise would
2129 * otherwise be off-limits to the process. We check for filesystems where
2130 * the vnode can change out from under us after execve (like [lin]procfs).
2132 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2133 * sufficient. We also don't check for setugidness since we know we are.
2136 is_unsafe(struct file *fp)
2138 if (fp->f_type == DTYPE_VNODE) {
2139 struct vnode *vp = fp->f_vnode;
2141 if ((vp->v_vflag & VV_PROCDEP) != 0)
2148 * Make this setguid thing safe, if at all possible.
2151 setugidsafety(struct thread *td)
2153 struct filedesc *fdp;
2157 fdp = td->td_proc->p_fd;
2158 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2159 FILEDESC_XLOCK(fdp);
2160 for (i = 0; i <= fdp->fd_lastfile; i++) {
2163 fp = fdp->fd_ofiles[i].fde_file;
2164 if (fp != NULL && is_unsafe(fp)) {
2165 knote_fdclose(td, i);
2167 * NULL-out descriptor prior to close to avoid
2168 * a race while close blocks.
2171 FILEDESC_XUNLOCK(fdp);
2172 (void) closef(fp, td);
2173 FILEDESC_XLOCK(fdp);
2176 FILEDESC_XUNLOCK(fdp);
2180 * If a specific file object occupies a specific file descriptor, close the
2181 * file descriptor entry and drop a reference on the file object. This is a
2182 * convenience function to handle a subsequent error in a function that calls
2183 * falloc() that handles the race that another thread might have closed the
2184 * file descriptor out from under the thread creating the file object.
2187 fdclose(struct thread *td, struct file *fp, int idx)
2189 struct filedesc *fdp = td->td_proc->p_fd;
2191 FILEDESC_XLOCK(fdp);
2192 if (fdp->fd_ofiles[idx].fde_file == fp) {
2194 FILEDESC_XUNLOCK(fdp);
2197 FILEDESC_XUNLOCK(fdp);
2201 * Close any files on exec?
2204 fdcloseexec(struct thread *td)
2206 struct filedesc *fdp;
2207 struct filedescent *fde;
2211 fdp = td->td_proc->p_fd;
2212 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2213 FILEDESC_XLOCK(fdp);
2214 for (i = 0; i <= fdp->fd_lastfile; i++) {
2215 fde = &fdp->fd_ofiles[i];
2217 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2218 (fde->fde_flags & UF_EXCLOSE))) {
2220 (void) closefp(fdp, i, fp, td, 0);
2221 /* closefp() drops the FILEDESC lock. */
2222 FILEDESC_XLOCK(fdp);
2225 FILEDESC_XUNLOCK(fdp);
2229 * It is unsafe for set[ug]id processes to be started with file
2230 * descriptors 0..2 closed, as these descriptors are given implicit
2231 * significance in the Standard C library. fdcheckstd() will create a
2232 * descriptor referencing /dev/null for each of stdin, stdout, and
2233 * stderr that is not already open.
2236 fdcheckstd(struct thread *td)
2238 struct filedesc *fdp;
2239 register_t retval, save;
2240 int i, error, devnull;
2242 fdp = td->td_proc->p_fd;
2243 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2246 for (i = 0; i < 3; i++) {
2247 if (fdp->fd_ofiles[i].fde_file != NULL)
2250 save = td->td_retval[0];
2251 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2253 devnull = td->td_retval[0];
2254 td->td_retval[0] = save;
2257 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2259 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2268 * Internal form of close. Decrement reference count on file structure.
2269 * Note: td may be NULL when closing a file that was being passed in a
2272 * XXXRW: Giant is not required for the caller, but often will be held; this
2273 * makes it moderately likely the Giant will be recursed in the VFS case.
2276 closef(struct file *fp, struct thread *td)
2280 struct filedesc_to_leader *fdtol;
2281 struct filedesc *fdp;
2284 * POSIX record locking dictates that any close releases ALL
2285 * locks owned by this process. This is handled by setting
2286 * a flag in the unlock to free ONLY locks obeying POSIX
2287 * semantics, and not to free BSD-style file locks.
2288 * If the descriptor was in a message, POSIX-style locks
2289 * aren't passed with the descriptor, and the thread pointer
2290 * will be NULL. Callers should be careful only to pass a
2291 * NULL thread pointer when there really is no owning
2292 * context that might have locks, or the locks will be
2295 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2297 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2298 lf.l_whence = SEEK_SET;
2301 lf.l_type = F_UNLCK;
2302 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2303 F_UNLCK, &lf, F_POSIX);
2305 fdtol = td->td_proc->p_fdtol;
2306 if (fdtol != NULL) {
2308 * Handle special case where file descriptor table is
2309 * shared between multiple process leaders.
2311 fdp = td->td_proc->p_fd;
2312 FILEDESC_XLOCK(fdp);
2313 for (fdtol = fdtol->fdl_next;
2314 fdtol != td->td_proc->p_fdtol;
2315 fdtol = fdtol->fdl_next) {
2316 if ((fdtol->fdl_leader->p_flag &
2319 fdtol->fdl_holdcount++;
2320 FILEDESC_XUNLOCK(fdp);
2321 lf.l_whence = SEEK_SET;
2324 lf.l_type = F_UNLCK;
2326 (void) VOP_ADVLOCK(vp,
2327 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2329 FILEDESC_XLOCK(fdp);
2330 fdtol->fdl_holdcount--;
2331 if (fdtol->fdl_holdcount == 0 &&
2332 fdtol->fdl_wakeup != 0) {
2333 fdtol->fdl_wakeup = 0;
2337 FILEDESC_XUNLOCK(fdp);
2340 return (fdrop(fp, td));
2344 * Initialize the file pointer with the specified properties.
2346 * The ops are set with release semantics to be certain that the flags, type,
2347 * and data are visible when ops is. This is to prevent ops methods from being
2348 * called with bad data.
2351 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2356 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2360 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2361 int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2364 struct filedescent fde;
2370 cap_rights_t haverights;
2375 * Avoid reads reordering and then a first access to the
2376 * fdp->fd_ofiles table which could result in OOB operation.
2378 if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2381 * Fetch the descriptor locklessly. We avoid fdrop() races by
2382 * never raising a refcount above 0. To accomplish this we have
2383 * to use a cmpset loop rather than an atomic_add. The descriptor
2384 * must be re-verified once we acquire a reference to be certain
2385 * that the identity is still correct and we did not lose a race
2386 * due to preemption.
2390 seq = seq_read(fd_seq(fdp, fd));
2391 fde = fdp->fd_ofiles[fd];
2392 if (!seq_consistent(fd_seq(fdp, fd), seq)) {
2398 fp = fdp->fd_ofiles[fd].fde_file;
2403 haverights = *cap_rights_fde(&fde);
2404 if (needrightsp != NULL) {
2405 error = cap_check(&haverights, needrightsp);
2408 if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2409 error = cap_fcntl_check_fde(&fde, needfcntl);
2415 count = fp->f_count;
2419 * Use an acquire barrier to prevent caching of fd_ofiles
2420 * so it is refreshed for verification.
2422 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2425 if (seq_consistent_nomb(fd_seq(fdp, fd), seq))
2427 if (fp == fdp->fd_ofiles[fd].fde_file)
2430 fdrop(fp, curthread);
2433 if (haverightsp != NULL) {
2435 *haverightsp = haverights;
2437 CAP_ALL(haverightsp);
2444 * Extract the file pointer associated with the specified descriptor for the
2445 * current user process.
2447 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2450 * File's rights will be checked against the capability rights mask.
2452 * If an error occurred the non-zero error is returned and *fpp is set to
2453 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2454 * responsible for fdrop().
2457 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2458 cap_rights_t *needrightsp, u_char *maxprotp)
2460 struct filedesc *fdp;
2462 cap_rights_t haverights, needrights;
2466 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2468 if (needrightsp != NULL)
2469 needrights = *needrightsp;
2471 cap_rights_init(&needrights);
2472 if (maxprotp != NULL)
2473 cap_rights_set(&needrights, CAP_MMAP);
2474 error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2477 if (fp->f_ops == &badfileops) {
2484 * If requested, convert capability rights to access flags.
2486 if (maxprotp != NULL)
2487 *maxprotp = cap_rights_to_vmprot(&haverights);
2488 #else /* !CAPABILITIES */
2489 if (maxprotp != NULL)
2490 *maxprotp = VM_PROT_ALL;
2491 #endif /* CAPABILITIES */
2494 * FREAD and FWRITE failure return EBADF as per POSIX.
2500 if ((fp->f_flag & flags) == 0)
2504 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2505 ((fp->f_flag & FWRITE) != 0))
2511 KASSERT(0, ("wrong flags"));
2524 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2527 return(_fget(td, fd, fpp, 0, rightsp, NULL));
2531 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2535 return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2539 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2542 return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2546 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2549 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2553 * Like fget() but loads the underlying vnode, or returns an error if the
2554 * descriptor does not represent a vnode. Note that pipes use vnodes but
2555 * never have VM objects. The returned vnode will be vref()'d.
2557 * XXX: what about the unused flags ?
2560 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2567 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2570 if (fp->f_vnode == NULL) {
2582 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2585 return (_fgetvp(td, fd, 0, rightsp, vpp));
2589 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2590 struct filecaps *havecaps, struct vnode **vpp)
2592 struct filedesc *fdp;
2598 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2601 fp = fget_locked(fdp, fd);
2602 if (fp == NULL || fp->f_ops == &badfileops)
2606 if (needrightsp != NULL) {
2607 error = cap_check(cap_rights(fdp, fd), needrightsp);
2613 if (fp->f_vnode == NULL)
2618 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2624 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2627 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2631 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2634 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2639 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2643 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2648 * Like fget() but loads the underlying socket, or returns an error if the
2649 * descriptor does not represent a socket.
2651 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2654 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2655 * on their file descriptor reference to prevent the socket from being free'd
2659 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2668 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2670 if (fp->f_type != DTYPE_SOCKET) {
2675 *fflagp = fp->f_flag;
2686 * Drop the reference count on the socket and XXX release the SX lock in the
2687 * future. The last reference closes the socket.
2689 * Note: fputsock() is deprecated, see comment for fgetsock().
2692 fputsock(struct socket *so)
2697 CURVNET_SET(so->so_vnet);
2703 * Handle the last reference to a file being closed.
2706 _fdrop(struct file *fp, struct thread *td)
2711 if (fp->f_count != 0)
2712 panic("fdrop: count %d", fp->f_count);
2713 if (fp->f_ops != &badfileops)
2714 error = fo_close(fp, td);
2715 atomic_subtract_int(&openfiles, 1);
2717 free(fp->f_advice, M_FADVISE);
2718 uma_zfree(file_zone, fp);
2724 * Apply an advisory lock on a file descriptor.
2726 * Just attempt to get a record lock of the requested type on the entire file
2727 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2729 #ifndef _SYS_SYSPROTO_H_
2737 sys_flock(struct thread *td, struct flock_args *uap)
2742 cap_rights_t rights;
2745 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2748 if (fp->f_type != DTYPE_VNODE) {
2750 return (EOPNOTSUPP);
2754 lf.l_whence = SEEK_SET;
2757 if (uap->how & LOCK_UN) {
2758 lf.l_type = F_UNLCK;
2759 atomic_clear_int(&fp->f_flag, FHASLOCK);
2760 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2763 if (uap->how & LOCK_EX)
2764 lf.l_type = F_WRLCK;
2765 else if (uap->how & LOCK_SH)
2766 lf.l_type = F_RDLCK;
2771 atomic_set_int(&fp->f_flag, FHASLOCK);
2772 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2773 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2779 * Duplicate the specified descriptor to a free descriptor.
2782 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2783 int openerror, int *indxp)
2785 struct filedescent *newfde, *oldfde;
2789 KASSERT(openerror == ENODEV || openerror == ENXIO,
2790 ("unexpected error %d in %s", openerror, __func__));
2793 * If the to-be-dup'd fd number is greater than the allowed number
2794 * of file descriptors, or the fd to be dup'd has already been
2795 * closed, then reject.
2797 FILEDESC_XLOCK(fdp);
2798 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2799 FILEDESC_XUNLOCK(fdp);
2803 error = fdalloc(td, 0, &indx);
2805 FILEDESC_XUNLOCK(fdp);
2810 * There are two cases of interest here.
2812 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2814 * For ENXIO steal away the file structure from (dfd) and store it in
2815 * (indx). (dfd) is effectively closed by this operation.
2817 switch (openerror) {
2820 * Check that the mode the file is being opened for is a
2821 * subset of the mode of the existing descriptor.
2823 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2824 fdunused(fdp, indx);
2825 FILEDESC_XUNLOCK(fdp);
2829 newfde = &fdp->fd_ofiles[indx];
2830 oldfde = &fdp->fd_ofiles[dfd];
2832 seq_write_begin(&newfde->fde_seq);
2834 memcpy(newfde, oldfde, fde_change_size);
2835 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
2837 seq_write_end(&newfde->fde_seq);
2842 * Steal away the file pointer from dfd and stuff it into indx.
2844 newfde = &fdp->fd_ofiles[indx];
2845 oldfde = &fdp->fd_ofiles[dfd];
2847 seq_write_begin(&newfde->fde_seq);
2849 memcpy(newfde, oldfde, fde_change_size);
2850 bzero(oldfde, fde_change_size);
2853 seq_write_end(&newfde->fde_seq);
2857 FILEDESC_XUNLOCK(fdp);
2863 * Scan all active processes and prisons to see if any of them have a current
2864 * or root directory of `olddp'. If so, replace them with the new mount point.
2867 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2869 struct filedesc *fdp;
2874 if (vrefcnt(olddp) == 1)
2877 sx_slock(&allproc_lock);
2878 FOREACH_PROC_IN_SYSTEM(p) {
2882 FILEDESC_XLOCK(fdp);
2883 if (fdp->fd_cdir == olddp) {
2885 fdp->fd_cdir = newdp;
2888 if (fdp->fd_rdir == olddp) {
2890 fdp->fd_rdir = newdp;
2893 if (fdp->fd_jdir == olddp) {
2895 fdp->fd_jdir = newdp;
2898 FILEDESC_XUNLOCK(fdp);
2901 sx_sunlock(&allproc_lock);
2902 if (rootvnode == olddp) {
2907 mtx_lock(&prison0.pr_mtx);
2908 if (prison0.pr_root == olddp) {
2910 prison0.pr_root = newdp;
2913 mtx_unlock(&prison0.pr_mtx);
2914 sx_slock(&allprison_lock);
2915 TAILQ_FOREACH(pr, &allprison, pr_list) {
2916 mtx_lock(&pr->pr_mtx);
2917 if (pr->pr_root == olddp) {
2919 pr->pr_root = newdp;
2922 mtx_unlock(&pr->pr_mtx);
2924 sx_sunlock(&allprison_lock);
2929 struct filedesc_to_leader *
2930 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2932 struct filedesc_to_leader *fdtol;
2934 fdtol = malloc(sizeof(struct filedesc_to_leader),
2935 M_FILEDESC_TO_LEADER, M_WAITOK);
2936 fdtol->fdl_refcount = 1;
2937 fdtol->fdl_holdcount = 0;
2938 fdtol->fdl_wakeup = 0;
2939 fdtol->fdl_leader = leader;
2941 FILEDESC_XLOCK(fdp);
2942 fdtol->fdl_next = old->fdl_next;
2943 fdtol->fdl_prev = old;
2944 old->fdl_next = fdtol;
2945 fdtol->fdl_next->fdl_prev = fdtol;
2946 FILEDESC_XUNLOCK(fdp);
2948 fdtol->fdl_next = fdtol;
2949 fdtol->fdl_prev = fdtol;
2955 * Get file structures globally.
2958 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2961 struct filedesc *fdp;
2966 error = sysctl_wire_old_buffer(req, 0);
2969 if (req->oldptr == NULL) {
2971 sx_slock(&allproc_lock);
2972 FOREACH_PROC_IN_SYSTEM(p) {
2973 if (p->p_state == PRS_NEW)
2978 /* overestimates sparse tables. */
2979 if (fdp->fd_lastfile > 0)
2980 n += fdp->fd_lastfile;
2983 sx_sunlock(&allproc_lock);
2984 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2987 bzero(&xf, sizeof(xf));
2988 xf.xf_size = sizeof(xf);
2989 sx_slock(&allproc_lock);
2990 FOREACH_PROC_IN_SYSTEM(p) {
2992 if (p->p_state == PRS_NEW) {
2996 if (p_cansee(req->td, p) != 0) {
3000 xf.xf_pid = p->p_pid;
3001 xf.xf_uid = p->p_ucred->cr_uid;
3006 FILEDESC_SLOCK(fdp);
3007 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3008 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3012 xf.xf_data = fp->f_data;
3013 xf.xf_vnode = fp->f_vnode;
3014 xf.xf_type = fp->f_type;
3015 xf.xf_count = fp->f_count;
3017 xf.xf_offset = foffset_get(fp);
3018 xf.xf_flag = fp->f_flag;
3019 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3023 FILEDESC_SUNLOCK(fdp);
3028 sx_sunlock(&allproc_lock);
3032 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3033 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3035 #ifdef KINFO_OFILE_SIZE
3036 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3039 #ifdef COMPAT_FREEBSD7
3041 export_vnode_for_osysctl(struct vnode *vp, int type,
3042 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
3045 char *fullpath, *freepath;
3047 bzero(kif, sizeof(*kif));
3048 kif->kf_structsize = sizeof(*kif);
3052 kif->kf_type = KF_TYPE_VNODE;
3053 /* This function only handles directories. */
3054 if (vp->v_type != VDIR) {
3058 kif->kf_vnode_type = KF_VTYPE_VDIR;
3061 * This is not a true file descriptor, so we set a bogus refcount
3062 * and offset to indicate these fields should be ignored.
3064 kif->kf_ref_count = -1;
3065 kif->kf_offset = -1;
3069 FILEDESC_SUNLOCK(fdp);
3070 vn_fullpath(curthread, vp, &fullpath, &freepath);
3072 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3073 if (freepath != NULL)
3074 free(freepath, M_TEMP);
3075 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3076 FILEDESC_SLOCK(fdp);
3081 * Get per-process file descriptors for use by procstat(1), et al.
3084 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3086 char *fullpath, *freepath;
3087 struct kinfo_ofile *kif;
3088 struct filedesc *fdp;
3089 int error, i, *name;
3090 struct shmfd *shmfd;
3099 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3106 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3107 FILEDESC_SLOCK(fdp);
3108 if (fdp->fd_cdir != NULL)
3109 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3111 if (fdp->fd_rdir != NULL)
3112 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3114 if (fdp->fd_jdir != NULL)
3115 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3117 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3118 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3120 bzero(kif, sizeof(*kif));
3121 kif->kf_structsize = sizeof(*kif);
3129 switch (fp->f_type) {
3131 kif->kf_type = KF_TYPE_VNODE;
3136 kif->kf_type = KF_TYPE_SOCKET;
3141 kif->kf_type = KF_TYPE_PIPE;
3145 kif->kf_type = KF_TYPE_FIFO;
3150 kif->kf_type = KF_TYPE_KQUEUE;
3154 kif->kf_type = KF_TYPE_CRYPTO;
3158 kif->kf_type = KF_TYPE_MQUEUE;
3162 kif->kf_type = KF_TYPE_SHM;
3167 kif->kf_type = KF_TYPE_SEM;
3172 kif->kf_type = KF_TYPE_PTS;
3177 case DTYPE_PROCDESC:
3178 kif->kf_type = KF_TYPE_PROCDESC;
3183 kif->kf_type = KF_TYPE_UNKNOWN;
3186 kif->kf_ref_count = fp->f_count;
3187 if (fp->f_flag & FREAD)
3188 kif->kf_flags |= KF_FLAG_READ;
3189 if (fp->f_flag & FWRITE)
3190 kif->kf_flags |= KF_FLAG_WRITE;
3191 if (fp->f_flag & FAPPEND)
3192 kif->kf_flags |= KF_FLAG_APPEND;
3193 if (fp->f_flag & FASYNC)
3194 kif->kf_flags |= KF_FLAG_ASYNC;
3195 if (fp->f_flag & FFSYNC)
3196 kif->kf_flags |= KF_FLAG_FSYNC;
3197 if (fp->f_flag & FNONBLOCK)
3198 kif->kf_flags |= KF_FLAG_NONBLOCK;
3199 if (fp->f_flag & O_DIRECT)
3200 kif->kf_flags |= KF_FLAG_DIRECT;
3201 if (fp->f_flag & FHASLOCK)
3202 kif->kf_flags |= KF_FLAG_HASLOCK;
3203 kif->kf_offset = foffset_get(fp);
3206 switch (vp->v_type) {
3208 kif->kf_vnode_type = KF_VTYPE_VNON;
3211 kif->kf_vnode_type = KF_VTYPE_VREG;
3214 kif->kf_vnode_type = KF_VTYPE_VDIR;
3217 kif->kf_vnode_type = KF_VTYPE_VBLK;
3220 kif->kf_vnode_type = KF_VTYPE_VCHR;
3223 kif->kf_vnode_type = KF_VTYPE_VLNK;
3226 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3229 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3232 kif->kf_vnode_type = KF_VTYPE_VBAD;
3235 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3239 * It is OK to drop the filedesc lock here as we will
3240 * re-validate and re-evaluate its properties when
3241 * the loop continues.
3245 FILEDESC_SUNLOCK(fdp);
3246 vn_fullpath(curthread, vp, &fullpath, &freepath);
3248 strlcpy(kif->kf_path, fullpath,
3249 sizeof(kif->kf_path));
3250 if (freepath != NULL)
3251 free(freepath, M_TEMP);
3252 FILEDESC_SLOCK(fdp);
3255 struct sockaddr *sa;
3257 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3258 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3259 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3262 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3263 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3264 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3267 kif->kf_sock_domain =
3268 so->so_proto->pr_domain->dom_family;
3269 kif->kf_sock_type = so->so_type;
3270 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3273 strlcpy(kif->kf_path, tty_devname(tp),
3274 sizeof(kif->kf_path));
3277 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3278 if (ks != NULL && ksem_info != NULL)
3279 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3280 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3284 FILEDESC_SUNLOCK(fdp);
3290 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3291 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3292 "Process ofiledesc entries");
3293 #endif /* COMPAT_FREEBSD7 */
3295 #ifdef KINFO_FILE_SIZE
3296 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3299 struct export_fd_buf {
3300 struct filedesc *fdp;
3303 struct kinfo_file kif;
3308 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3309 int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3314 } fflags_table[] = {
3315 { FAPPEND, KF_FLAG_APPEND },
3316 { FASYNC, KF_FLAG_ASYNC },
3317 { FFSYNC, KF_FLAG_FSYNC },
3318 { FHASLOCK, KF_FLAG_HASLOCK },
3319 { FNONBLOCK, KF_FLAG_NONBLOCK },
3320 { FREAD, KF_FLAG_READ },
3321 { FWRITE, KF_FLAG_WRITE },
3322 { O_CREAT, KF_FLAG_CREAT },
3323 { O_DIRECT, KF_FLAG_DIRECT },
3324 { O_EXCL, KF_FLAG_EXCL },
3325 { O_EXEC, KF_FLAG_EXEC },
3326 { O_EXLOCK, KF_FLAG_EXLOCK },
3327 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3328 { O_SHLOCK, KF_FLAG_SHLOCK },
3329 { O_TRUNC, KF_FLAG_TRUNC }
3331 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3332 struct kinfo_file *kif;
3337 if (efbuf->remainder == 0)
3340 bzero(kif, sizeof(*kif));
3341 locked = efbuf->fdp != NULL;
3346 FILEDESC_SUNLOCK(efbuf->fdp);
3349 vp = (struct vnode *)data;
3350 error = fill_vnode_info(vp, kif);
3353 case KF_TYPE_SOCKET:
3354 error = fill_socket_info((struct socket *)data, kif);
3357 error = fill_pipe_info((struct pipe *)data, kif);
3360 error = fill_pts_info((struct tty *)data, kif);
3362 case KF_TYPE_PROCDESC:
3363 error = fill_procdesc_info((struct procdesc *)data, kif);
3366 error = fill_sem_info((struct file *)data, kif);
3369 error = fill_shm_info((struct file *)data, kif);
3375 kif->kf_status |= KF_ATTR_VALID;
3378 * Translate file access flags.
3380 for (i = 0; i < NFFLAGS; i++)
3381 if (fflags & fflags_table[i].fflag)
3382 kif->kf_flags |= fflags_table[i].kf_fflag;
3383 if (rightsp != NULL)
3384 kif->kf_cap_rights = *rightsp;
3386 cap_rights_init(&kif->kf_cap_rights);
3388 kif->kf_type = type;
3389 kif->kf_ref_count = refcnt;
3390 kif->kf_offset = offset;
3391 if ((efbuf->flags & KERN_FILEDESC_PACK_KINFO) != 0)
3392 /* Pack record size down */
3393 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3394 strlen(kif->kf_path) + 1;
3396 kif->kf_structsize = sizeof(*kif);
3397 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3398 if (efbuf->remainder != -1) {
3399 if (efbuf->remainder < kif->kf_structsize) {
3400 /* Terminate export. */
3401 efbuf->remainder = 0;
3402 if (efbuf->fdp != NULL && !locked)
3403 FILEDESC_SLOCK(efbuf->fdp);
3406 efbuf->remainder -= kif->kf_structsize;
3409 FILEDESC_SUNLOCK(efbuf->fdp);
3410 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM;
3411 if (efbuf->fdp != NULL)
3412 FILEDESC_SLOCK(efbuf->fdp);
3417 * Store a process file descriptor information to sbuf.
3419 * Takes a locked proc as argument, and returns with the proc unlocked.
3422 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3426 struct filedesc *fdp;
3427 struct export_fd_buf *efbuf;
3428 struct vnode *cttyvp, *textvp, *tracevp;
3432 int type, refcnt, fflags;
3433 cap_rights_t rights;
3435 PROC_LOCK_ASSERT(p, MA_OWNED);
3438 tracevp = p->p_tracevp;
3439 if (tracevp != NULL)
3442 textvp = p->p_textvp;
3445 /* Controlling tty. */
3447 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3448 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3454 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3457 efbuf->remainder = maxlen;
3458 efbuf->flags = flags;
3459 if (tracevp != NULL)
3460 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3461 FREAD | FWRITE, -1, -1, NULL, efbuf);
3463 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3464 FREAD, -1, -1, NULL, efbuf);
3466 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3467 FREAD | FWRITE, -1, -1, NULL, efbuf);
3472 FILEDESC_SLOCK(fdp);
3473 /* working directory */
3474 if (fdp->fd_cdir != NULL) {
3476 data = fdp->fd_cdir;
3477 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3478 FREAD, -1, -1, NULL, efbuf);
3480 /* root directory */
3481 if (fdp->fd_rdir != NULL) {
3483 data = fdp->fd_rdir;
3484 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3485 FREAD, -1, -1, NULL, efbuf);
3487 /* jail directory */
3488 if (fdp->fd_jdir != NULL) {
3490 data = fdp->fd_jdir;
3491 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3492 FREAD, -1, -1, NULL, efbuf);
3494 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3495 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3499 rights = *cap_rights(fdp, i);
3500 #else /* !CAPABILITIES */
3501 cap_rights_init(&rights);
3503 switch (fp->f_type) {
3505 type = KF_TYPE_VNODE;
3511 type = KF_TYPE_SOCKET;
3516 type = KF_TYPE_PIPE;
3521 type = KF_TYPE_FIFO;
3527 type = KF_TYPE_KQUEUE;
3531 type = KF_TYPE_CRYPTO;
3535 type = KF_TYPE_MQUEUE;
3554 case DTYPE_PROCDESC:
3555 type = KF_TYPE_PROCDESC;
3561 type = KF_TYPE_UNKNOWN;
3564 refcnt = fp->f_count;
3565 fflags = fp->f_flag;
3566 offset = foffset_get(fp);
3569 * Create sysctl entry.
3570 * It is OK to drop the filedesc lock here as we will
3571 * re-validate and re-evaluate its properties when
3572 * the loop continues.
3574 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3575 offset, &rights, efbuf);
3579 FILEDESC_SUNLOCK(fdp);
3582 free(efbuf, M_TEMP);
3586 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3589 * Get per-process file descriptors for use by procstat(1), et al.
3592 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3597 int error, error2, *name;
3601 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3602 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3607 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3608 error = kern_proc_filedesc_out(p, &sb, maxlen,
3609 KERN_FILEDESC_PACK_KINFO);
3610 error2 = sbuf_finish(&sb);
3612 return (error != 0 ? error : error2);
3616 vntype_to_kinfo(int vtype)
3621 } vtypes_table[] = {
3622 { VBAD, KF_VTYPE_VBAD },
3623 { VBLK, KF_VTYPE_VBLK },
3624 { VCHR, KF_VTYPE_VCHR },
3625 { VDIR, KF_VTYPE_VDIR },
3626 { VFIFO, KF_VTYPE_VFIFO },
3627 { VLNK, KF_VTYPE_VLNK },
3628 { VNON, KF_VTYPE_VNON },
3629 { VREG, KF_VTYPE_VREG },
3630 { VSOCK, KF_VTYPE_VSOCK }
3632 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3636 * Perform vtype translation.
3638 for (i = 0; i < NVTYPES; i++)
3639 if (vtypes_table[i].vtype == vtype)
3642 return (vtypes_table[i].kf_vtype);
3644 return (KF_VTYPE_UNKNOWN);
3648 vn_fill_junk(struct kinfo_file *kif)
3653 * Simulate vn_fullpath returning changing values for a given
3654 * vp during e.g. coredump.
3656 len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
3657 olen = strlen(kif->kf_path);
3659 strcpy(&kif->kf_path[len - 1], "$");
3661 for (; olen < len; olen++)
3662 strcpy(&kif->kf_path[olen], "A");
3666 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3669 char *fullpath, *freepath;
3674 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3677 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3679 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3681 if (freepath != NULL)
3682 free(freepath, M_TEMP);
3684 KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
3689 * Retrieve vnode attributes.
3691 va.va_fsid = VNOVAL;
3693 vn_lock(vp, LK_SHARED | LK_RETRY);
3694 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3698 if (va.va_fsid != VNOVAL)
3699 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3701 kif->kf_un.kf_file.kf_file_fsid =
3702 vp->v_mount->mnt_stat.f_fsid.val[0];
3703 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3704 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3705 kif->kf_un.kf_file.kf_file_size = va.va_size;
3706 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3711 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3713 struct sockaddr *sa;
3714 struct inpcb *inpcb;
3715 struct unpcb *unpcb;
3720 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3721 kif->kf_sock_type = so->so_type;
3722 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3723 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3724 switch(kif->kf_sock_domain) {
3727 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3728 if (so->so_pcb != NULL) {
3729 inpcb = (struct inpcb *)(so->so_pcb);
3730 kif->kf_un.kf_sock.kf_sock_inpcb =
3731 (uintptr_t)inpcb->inp_ppcb;
3736 if (so->so_pcb != NULL) {
3737 unpcb = (struct unpcb *)(so->so_pcb);
3738 if (unpcb->unp_conn) {
3739 kif->kf_un.kf_sock.kf_sock_unpconn =
3740 (uintptr_t)unpcb->unp_conn;
3741 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3742 so->so_rcv.sb_state;
3743 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3744 so->so_snd.sb_state;
3749 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3750 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3751 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3754 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3755 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3756 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3759 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3760 sizeof(kif->kf_path));
3765 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3770 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3771 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3776 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3781 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3782 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3783 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3788 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3793 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3798 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3804 if (fp->f_data == NULL)
3806 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3808 if (ksem_info == NULL)
3810 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3811 &kif->kf_un.kf_sem.kf_sem_value);
3812 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3817 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3823 if (fp->f_data == NULL)
3825 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3827 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3828 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3829 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3833 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3834 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3835 "Process filedesc entries");
3839 * For the purposes of debugging, generate a human-readable string for the
3843 file_type_to_name(short type)
3873 * For the purposes of debugging, identify a process (if any, perhaps one of
3874 * many) that references the passed file in its file descriptor array. Return
3877 static struct proc *
3878 file_to_first_proc(struct file *fp)
3880 struct filedesc *fdp;
3884 FOREACH_PROC_IN_SYSTEM(p) {
3885 if (p->p_state == PRS_NEW)
3890 for (n = 0; n <= fdp->fd_lastfile; n++) {
3891 if (fp == fdp->fd_ofiles[n].fde_file)
3899 db_print_file(struct file *fp, int header)
3904 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3905 "File", "Type", "Data", "Flag", "GCFl", "Count",
3906 "MCount", "Vnode", "FPID", "FCmd");
3907 p = file_to_first_proc(fp);
3908 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3909 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3910 0, fp->f_count, 0, fp->f_vnode,
3911 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3914 DB_SHOW_COMMAND(file, db_show_file)
3919 db_printf("usage: show file <addr>\n");
3922 fp = (struct file *)addr;
3923 db_print_file(fp, 1);
3926 DB_SHOW_COMMAND(files, db_show_files)
3928 struct filedesc *fdp;
3935 FOREACH_PROC_IN_SYSTEM(p) {
3936 if (p->p_state == PRS_NEW)
3938 if ((fdp = p->p_fd) == NULL)
3940 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3941 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3943 db_print_file(fp, header);
3950 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3951 &maxfilesperproc, 0, "Maximum files allowed open per process");
3953 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3954 &maxfiles, 0, "Maximum number of files");
3956 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3957 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3961 filelistinit(void *dummy)
3964 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3965 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3966 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3967 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3969 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3971 /*-------------------------------------------------------------------*/
3974 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3975 int flags, struct thread *td)
3982 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3990 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3998 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4006 badfo_kqfilter(struct file *fp, struct knote *kn)
4013 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4021 badfo_close(struct file *fp, struct thread *td)
4028 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4036 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4044 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4045 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4046 int kflags, struct thread *td)
4052 struct fileops badfileops = {
4053 .fo_read = badfo_readwrite,
4054 .fo_write = badfo_readwrite,
4055 .fo_truncate = badfo_truncate,
4056 .fo_ioctl = badfo_ioctl,
4057 .fo_poll = badfo_poll,
4058 .fo_kqfilter = badfo_kqfilter,
4059 .fo_stat = badfo_stat,
4060 .fo_close = badfo_close,
4061 .fo_chmod = badfo_chmod,
4062 .fo_chown = badfo_chown,
4063 .fo_sendfile = badfo_sendfile,
4067 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4075 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4083 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4084 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4085 int kflags, struct thread *td)
4091 /*-------------------------------------------------------------------*/
4094 * File Descriptor pseudo-device driver (/dev/fd/).
4096 * Opening minor device N dup()s the file (if any) connected to file
4097 * descriptor N belonging to the calling process. Note that this driver
4098 * consists of only the ``open()'' routine, because all subsequent
4099 * references to this file will be direct to the other driver.
4101 * XXX: we could give this one a cloning event handler if necessary.
4106 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4110 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4111 * the file descriptor being sought for duplication. The error
4112 * return ensures that the vnode for this device will be released
4113 * by vn_open. Open will detect this special error and take the
4114 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4115 * will simply report the error.
4117 td->td_dupfd = dev2unit(dev);
4121 static struct cdevsw fildesc_cdevsw = {
4122 .d_version = D_VERSION,
4128 fildesc_drvinit(void *unused)
4132 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4133 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4134 make_dev_alias(dev, "stdin");
4135 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4136 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4137 make_dev_alias(dev, "stdout");
4138 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4139 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4140 make_dev_alias(dev, "stderr");
4143 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);