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 accomodate (at least) nfd descriptors.
1531 fdgrowtable(struct filedesc *fdp, int nfd)
1533 struct filedesc0 *fdp0;
1534 struct freetable *ft;
1535 struct filedescent *ntable;
1536 struct filedescent *otable;
1537 int nnfiles, onfiles;
1538 NDSLOTTYPE *nmap, *omap;
1540 FILEDESC_XLOCK_ASSERT(fdp);
1542 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1544 /* save old values */
1545 onfiles = fdp->fd_nfiles;
1546 otable = fdp->fd_ofiles;
1549 /* compute the size of the new table */
1550 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1551 if (nnfiles <= onfiles)
1552 /* the table is already large enough */
1556 * Allocate a new table. We need enough space for the
1557 * file entries themselves and the struct freetable we will use
1558 * when we decommission the table and place it on the freelist.
1559 * We place the struct freetable in the middle so we don't have
1560 * to worry about padding.
1562 ntable = malloc(nnfiles * sizeof(ntable[0]) + sizeof(struct freetable),
1563 M_FILEDESC, M_ZERO | M_WAITOK);
1564 /* copy the old data over and point at the new tables */
1565 memcpy(ntable, otable, onfiles * sizeof(*otable));
1566 fdp->fd_ofiles = ntable;
1569 * Allocate a new map only if the old is not large enough. It will
1570 * grow at a slower rate than the table as it can map more
1571 * entries than the table can hold.
1573 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1574 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1576 /* copy over the old data and update the pointer */
1577 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1582 * In order to have a valid pattern for fget_unlocked()
1583 * fdp->fd_nfiles must be the last member to be updated, otherwise
1584 * fget_unlocked() consumers may reference a new, higher value for
1585 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1586 * resulting in OOB accesses.
1588 atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1591 * Do not free the old file table, as some threads may still
1592 * reference entries within it. Instead, place it on a freelist
1593 * which will be processed when the struct filedesc is released.
1595 * Note that if onfiles == NDFILE, we're dealing with the original
1596 * static allocation contained within (struct filedesc0 *)fdp,
1597 * which must not be freed.
1599 if (onfiles > NDFILE) {
1600 ft = (struct freetable *)&otable[onfiles];
1601 fdp0 = (struct filedesc0 *)fdp;
1602 ft->ft_table = otable;
1603 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1606 * The map does not have the same possibility of threads still
1607 * holding references to it. So always free it as long as it
1608 * does not reference the original static allocation.
1610 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1611 free(omap, M_FILEDESC);
1615 * Allocate a file descriptor for the process.
1618 fdalloc(struct thread *td, int minfd, int *result)
1620 struct proc *p = td->td_proc;
1621 struct filedesc *fdp = p->p_fd;
1622 int fd = -1, maxfd, allocfd;
1627 FILEDESC_XLOCK_ASSERT(fdp);
1629 if (fdp->fd_freefile > minfd)
1630 minfd = fdp->fd_freefile;
1632 maxfd = getmaxfd(p);
1635 * Search the bitmap for a free descriptor starting at minfd.
1636 * If none is found, grow the file table.
1638 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1641 if (fd >= fdp->fd_nfiles) {
1642 allocfd = min(fd * 2, maxfd);
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 decriptor 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, "
1784 "please see tuning(7).\n", td->td_ucred->cr_ruid);
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 filedesc *fdp, struct file *fp, int idx, struct thread *td)
2190 FILEDESC_XLOCK(fdp);
2191 if (fdp->fd_ofiles[idx].fde_file == fp) {
2193 FILEDESC_XUNLOCK(fdp);
2196 FILEDESC_XUNLOCK(fdp);
2200 * Close any files on exec?
2203 fdcloseexec(struct thread *td)
2205 struct filedesc *fdp;
2206 struct filedescent *fde;
2210 fdp = td->td_proc->p_fd;
2211 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2212 FILEDESC_XLOCK(fdp);
2213 for (i = 0; i <= fdp->fd_lastfile; i++) {
2214 fde = &fdp->fd_ofiles[i];
2216 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2217 (fde->fde_flags & UF_EXCLOSE))) {
2219 (void) closefp(fdp, i, fp, td, 0);
2220 /* closefp() drops the FILEDESC lock. */
2221 FILEDESC_XLOCK(fdp);
2224 FILEDESC_XUNLOCK(fdp);
2228 * It is unsafe for set[ug]id processes to be started with file
2229 * descriptors 0..2 closed, as these descriptors are given implicit
2230 * significance in the Standard C library. fdcheckstd() will create a
2231 * descriptor referencing /dev/null for each of stdin, stdout, and
2232 * stderr that is not already open.
2235 fdcheckstd(struct thread *td)
2237 struct filedesc *fdp;
2238 register_t retval, save;
2239 int i, error, devnull;
2241 fdp = td->td_proc->p_fd;
2242 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2245 for (i = 0; i < 3; i++) {
2246 if (fdp->fd_ofiles[i].fde_file != NULL)
2249 save = td->td_retval[0];
2250 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2252 devnull = td->td_retval[0];
2253 td->td_retval[0] = save;
2256 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2258 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2267 * Internal form of close. Decrement reference count on file structure.
2268 * Note: td may be NULL when closing a file that was being passed in a
2271 * XXXRW: Giant is not required for the caller, but often will be held; this
2272 * makes it moderately likely the Giant will be recursed in the VFS case.
2275 closef(struct file *fp, struct thread *td)
2279 struct filedesc_to_leader *fdtol;
2280 struct filedesc *fdp;
2283 * POSIX record locking dictates that any close releases ALL
2284 * locks owned by this process. This is handled by setting
2285 * a flag in the unlock to free ONLY locks obeying POSIX
2286 * semantics, and not to free BSD-style file locks.
2287 * If the descriptor was in a message, POSIX-style locks
2288 * aren't passed with the descriptor, and the thread pointer
2289 * will be NULL. Callers should be careful only to pass a
2290 * NULL thread pointer when there really is no owning
2291 * context that might have locks, or the locks will be
2294 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2296 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2297 lf.l_whence = SEEK_SET;
2300 lf.l_type = F_UNLCK;
2301 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2302 F_UNLCK, &lf, F_POSIX);
2304 fdtol = td->td_proc->p_fdtol;
2305 if (fdtol != NULL) {
2307 * Handle special case where file descriptor table is
2308 * shared between multiple process leaders.
2310 fdp = td->td_proc->p_fd;
2311 FILEDESC_XLOCK(fdp);
2312 for (fdtol = fdtol->fdl_next;
2313 fdtol != td->td_proc->p_fdtol;
2314 fdtol = fdtol->fdl_next) {
2315 if ((fdtol->fdl_leader->p_flag &
2318 fdtol->fdl_holdcount++;
2319 FILEDESC_XUNLOCK(fdp);
2320 lf.l_whence = SEEK_SET;
2323 lf.l_type = F_UNLCK;
2325 (void) VOP_ADVLOCK(vp,
2326 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2328 FILEDESC_XLOCK(fdp);
2329 fdtol->fdl_holdcount--;
2330 if (fdtol->fdl_holdcount == 0 &&
2331 fdtol->fdl_wakeup != 0) {
2332 fdtol->fdl_wakeup = 0;
2336 FILEDESC_XUNLOCK(fdp);
2339 return (fdrop(fp, td));
2343 * Initialize the file pointer with the specified properties.
2345 * The ops are set with release semantics to be certain that the flags, type,
2346 * and data are visible when ops is. This is to prevent ops methods from being
2347 * called with bad data.
2350 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2355 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2359 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2360 int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2363 struct filedescent fde;
2369 cap_rights_t haverights;
2374 * Avoid reads reordering and then a first access to the
2375 * fdp->fd_ofiles table which could result in OOB operation.
2377 if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2380 * Fetch the descriptor locklessly. We avoid fdrop() races by
2381 * never raising a refcount above 0. To accomplish this we have
2382 * to use a cmpset loop rather than an atomic_add. The descriptor
2383 * must be re-verified once we acquire a reference to be certain
2384 * that the identity is still correct and we did not lose a race
2385 * due to preemption.
2389 seq = seq_read(fd_seq(fdp, fd));
2390 fde = fdp->fd_ofiles[fd];
2391 if (!seq_consistent(fd_seq(fdp, fd), seq)) {
2397 fp = fdp->fd_ofiles[fd].fde_file;
2402 haverights = *cap_rights_fde(&fde);
2403 if (needrightsp != NULL) {
2404 error = cap_check(&haverights, needrightsp);
2407 if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2408 error = cap_fcntl_check_fde(&fde, needfcntl);
2414 count = fp->f_count;
2418 * Use an acquire barrier to prevent caching of fd_ofiles
2419 * so it is refreshed for verification.
2421 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2424 if (seq_consistent_nomb(fd_seq(fdp, fd), seq))
2426 if (fp == fdp->fd_ofiles[fd].fde_file)
2429 fdrop(fp, curthread);
2432 if (haverightsp != NULL) {
2434 *haverightsp = haverights;
2436 CAP_ALL(haverightsp);
2443 * Extract the file pointer associated with the specified descriptor for the
2444 * current user process.
2446 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2449 * File's rights will be checked against the capability rights mask.
2451 * If an error occured the non-zero error is returned and *fpp is set to
2452 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2453 * responsible for fdrop().
2456 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2457 cap_rights_t *needrightsp, u_char *maxprotp)
2459 struct filedesc *fdp;
2461 cap_rights_t haverights, needrights;
2465 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2467 if (needrightsp != NULL)
2468 needrights = *needrightsp;
2470 cap_rights_init(&needrights);
2471 if (maxprotp != NULL)
2472 cap_rights_set(&needrights, CAP_MMAP);
2473 error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2476 if (fp->f_ops == &badfileops) {
2483 * If requested, convert capability rights to access flags.
2485 if (maxprotp != NULL)
2486 *maxprotp = cap_rights_to_vmprot(&haverights);
2487 #else /* !CAPABILITIES */
2488 if (maxprotp != NULL)
2489 *maxprotp = VM_PROT_ALL;
2490 #endif /* CAPABILITIES */
2493 * FREAD and FWRITE failure return EBADF as per POSIX.
2499 if ((fp->f_flag & flags) == 0)
2503 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2504 ((fp->f_flag & FWRITE) != 0))
2510 KASSERT(0, ("wrong flags"));
2523 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2526 return(_fget(td, fd, fpp, 0, rightsp, NULL));
2530 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2534 return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2538 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2541 return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2545 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2548 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2552 * Like fget() but loads the underlying vnode, or returns an error if the
2553 * descriptor does not represent a vnode. Note that pipes use vnodes but
2554 * never have VM objects. The returned vnode will be vref()'d.
2556 * XXX: what about the unused flags ?
2559 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2566 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2569 if (fp->f_vnode == NULL) {
2581 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2584 return (_fgetvp(td, fd, 0, rightsp, vpp));
2588 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2589 struct filecaps *havecaps, struct vnode **vpp)
2591 struct filedesc *fdp;
2597 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2600 fp = fget_locked(fdp, fd);
2601 if (fp == NULL || fp->f_ops == &badfileops)
2605 if (needrightsp != NULL) {
2606 error = cap_check(cap_rights(fdp, fd), needrightsp);
2612 if (fp->f_vnode == NULL)
2617 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2623 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2626 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2630 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2633 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2638 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2642 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2647 * Like fget() but loads the underlying socket, or returns an error if the
2648 * descriptor does not represent a socket.
2650 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2653 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2654 * on their file descriptor reference to prevent the socket from being free'd
2658 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2667 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2669 if (fp->f_type != DTYPE_SOCKET) {
2674 *fflagp = fp->f_flag;
2685 * Drop the reference count on the socket and XXX release the SX lock in the
2686 * future. The last reference closes the socket.
2688 * Note: fputsock() is deprecated, see comment for fgetsock().
2691 fputsock(struct socket *so)
2696 CURVNET_SET(so->so_vnet);
2702 * Handle the last reference to a file being closed.
2705 _fdrop(struct file *fp, struct thread *td)
2710 if (fp->f_count != 0)
2711 panic("fdrop: count %d", fp->f_count);
2712 if (fp->f_ops != &badfileops)
2713 error = fo_close(fp, td);
2714 atomic_subtract_int(&openfiles, 1);
2716 free(fp->f_advice, M_FADVISE);
2717 uma_zfree(file_zone, fp);
2723 * Apply an advisory lock on a file descriptor.
2725 * Just attempt to get a record lock of the requested type on the entire file
2726 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2728 #ifndef _SYS_SYSPROTO_H_
2736 sys_flock(struct thread *td, struct flock_args *uap)
2741 cap_rights_t rights;
2744 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2747 if (fp->f_type != DTYPE_VNODE) {
2749 return (EOPNOTSUPP);
2753 lf.l_whence = SEEK_SET;
2756 if (uap->how & LOCK_UN) {
2757 lf.l_type = F_UNLCK;
2758 atomic_clear_int(&fp->f_flag, FHASLOCK);
2759 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2762 if (uap->how & LOCK_EX)
2763 lf.l_type = F_WRLCK;
2764 else if (uap->how & LOCK_SH)
2765 lf.l_type = F_RDLCK;
2770 atomic_set_int(&fp->f_flag, FHASLOCK);
2771 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2772 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2778 * Duplicate the specified descriptor to a free descriptor.
2781 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2782 int openerror, int *indxp)
2784 struct filedescent *newfde, *oldfde;
2788 KASSERT(openerror == ENODEV || openerror == ENXIO,
2789 ("unexpected error %d in %s", openerror, __func__));
2792 * If the to-be-dup'd fd number is greater than the allowed number
2793 * of file descriptors, or the fd to be dup'd has already been
2794 * closed, then reject.
2796 FILEDESC_XLOCK(fdp);
2797 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2798 FILEDESC_XUNLOCK(fdp);
2802 error = fdalloc(td, 0, &indx);
2804 FILEDESC_XUNLOCK(fdp);
2809 * There are two cases of interest here.
2811 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2813 * For ENXIO steal away the file structure from (dfd) and store it in
2814 * (indx). (dfd) is effectively closed by this operation.
2816 switch (openerror) {
2819 * Check that the mode the file is being opened for is a
2820 * subset of the mode of the existing descriptor.
2822 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2823 fdunused(fdp, indx);
2824 FILEDESC_XUNLOCK(fdp);
2828 newfde = &fdp->fd_ofiles[indx];
2829 oldfde = &fdp->fd_ofiles[dfd];
2831 seq_write_begin(&newfde->fde_seq);
2833 memcpy(newfde, oldfde, fde_change_size);
2834 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
2836 seq_write_end(&newfde->fde_seq);
2841 * Steal away the file pointer from dfd and stuff it into indx.
2843 newfde = &fdp->fd_ofiles[indx];
2844 oldfde = &fdp->fd_ofiles[dfd];
2846 seq_write_begin(&newfde->fde_seq);
2848 memcpy(newfde, oldfde, fde_change_size);
2849 bzero(oldfde, fde_change_size);
2852 seq_write_end(&newfde->fde_seq);
2856 FILEDESC_XUNLOCK(fdp);
2862 * Scan all active processes and prisons to see if any of them have a current
2863 * or root directory of `olddp'. If so, replace them with the new mount point.
2866 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2868 struct filedesc *fdp;
2873 if (vrefcnt(olddp) == 1)
2876 sx_slock(&allproc_lock);
2877 FOREACH_PROC_IN_SYSTEM(p) {
2881 FILEDESC_XLOCK(fdp);
2882 if (fdp->fd_cdir == olddp) {
2884 fdp->fd_cdir = newdp;
2887 if (fdp->fd_rdir == olddp) {
2889 fdp->fd_rdir = newdp;
2892 if (fdp->fd_jdir == olddp) {
2894 fdp->fd_jdir = newdp;
2897 FILEDESC_XUNLOCK(fdp);
2900 sx_sunlock(&allproc_lock);
2901 if (rootvnode == olddp) {
2906 mtx_lock(&prison0.pr_mtx);
2907 if (prison0.pr_root == olddp) {
2909 prison0.pr_root = newdp;
2912 mtx_unlock(&prison0.pr_mtx);
2913 sx_slock(&allprison_lock);
2914 TAILQ_FOREACH(pr, &allprison, pr_list) {
2915 mtx_lock(&pr->pr_mtx);
2916 if (pr->pr_root == olddp) {
2918 pr->pr_root = newdp;
2921 mtx_unlock(&pr->pr_mtx);
2923 sx_sunlock(&allprison_lock);
2928 struct filedesc_to_leader *
2929 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2931 struct filedesc_to_leader *fdtol;
2933 fdtol = malloc(sizeof(struct filedesc_to_leader),
2934 M_FILEDESC_TO_LEADER, M_WAITOK);
2935 fdtol->fdl_refcount = 1;
2936 fdtol->fdl_holdcount = 0;
2937 fdtol->fdl_wakeup = 0;
2938 fdtol->fdl_leader = leader;
2940 FILEDESC_XLOCK(fdp);
2941 fdtol->fdl_next = old->fdl_next;
2942 fdtol->fdl_prev = old;
2943 old->fdl_next = fdtol;
2944 fdtol->fdl_next->fdl_prev = fdtol;
2945 FILEDESC_XUNLOCK(fdp);
2947 fdtol->fdl_next = fdtol;
2948 fdtol->fdl_prev = fdtol;
2954 * Get file structures globally.
2957 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2960 struct filedesc *fdp;
2965 error = sysctl_wire_old_buffer(req, 0);
2968 if (req->oldptr == NULL) {
2970 sx_slock(&allproc_lock);
2971 FOREACH_PROC_IN_SYSTEM(p) {
2972 if (p->p_state == PRS_NEW)
2977 /* overestimates sparse tables. */
2978 if (fdp->fd_lastfile > 0)
2979 n += fdp->fd_lastfile;
2982 sx_sunlock(&allproc_lock);
2983 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2986 bzero(&xf, sizeof(xf));
2987 xf.xf_size = sizeof(xf);
2988 sx_slock(&allproc_lock);
2989 FOREACH_PROC_IN_SYSTEM(p) {
2991 if (p->p_state == PRS_NEW) {
2995 if (p_cansee(req->td, p) != 0) {
2999 xf.xf_pid = p->p_pid;
3000 xf.xf_uid = p->p_ucred->cr_uid;
3005 FILEDESC_SLOCK(fdp);
3006 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3007 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3011 xf.xf_data = fp->f_data;
3012 xf.xf_vnode = fp->f_vnode;
3013 xf.xf_type = fp->f_type;
3014 xf.xf_count = fp->f_count;
3016 xf.xf_offset = foffset_get(fp);
3017 xf.xf_flag = fp->f_flag;
3018 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3022 FILEDESC_SUNLOCK(fdp);
3027 sx_sunlock(&allproc_lock);
3031 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3032 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3034 #ifdef KINFO_OFILE_SIZE
3035 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3038 #ifdef COMPAT_FREEBSD7
3040 export_vnode_for_osysctl(struct vnode *vp, int type,
3041 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
3044 char *fullpath, *freepath;
3046 bzero(kif, sizeof(*kif));
3047 kif->kf_structsize = sizeof(*kif);
3051 kif->kf_type = KF_TYPE_VNODE;
3052 /* This function only handles directories. */
3053 if (vp->v_type != VDIR) {
3057 kif->kf_vnode_type = KF_VTYPE_VDIR;
3060 * This is not a true file descriptor, so we set a bogus refcount
3061 * and offset to indicate these fields should be ignored.
3063 kif->kf_ref_count = -1;
3064 kif->kf_offset = -1;
3068 FILEDESC_SUNLOCK(fdp);
3069 vn_fullpath(curthread, vp, &fullpath, &freepath);
3071 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3072 if (freepath != NULL)
3073 free(freepath, M_TEMP);
3074 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3075 FILEDESC_SLOCK(fdp);
3080 * Get per-process file descriptors for use by procstat(1), et al.
3083 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3085 char *fullpath, *freepath;
3086 struct kinfo_ofile *kif;
3087 struct filedesc *fdp;
3088 int error, i, *name;
3089 struct shmfd *shmfd;
3098 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3105 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3106 FILEDESC_SLOCK(fdp);
3107 if (fdp->fd_cdir != NULL)
3108 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3110 if (fdp->fd_rdir != NULL)
3111 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3113 if (fdp->fd_jdir != NULL)
3114 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3116 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3117 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3119 bzero(kif, sizeof(*kif));
3120 kif->kf_structsize = sizeof(*kif);
3128 switch (fp->f_type) {
3130 kif->kf_type = KF_TYPE_VNODE;
3135 kif->kf_type = KF_TYPE_SOCKET;
3140 kif->kf_type = KF_TYPE_PIPE;
3144 kif->kf_type = KF_TYPE_FIFO;
3149 kif->kf_type = KF_TYPE_KQUEUE;
3153 kif->kf_type = KF_TYPE_CRYPTO;
3157 kif->kf_type = KF_TYPE_MQUEUE;
3161 kif->kf_type = KF_TYPE_SHM;
3166 kif->kf_type = KF_TYPE_SEM;
3171 kif->kf_type = KF_TYPE_PTS;
3176 case DTYPE_PROCDESC:
3177 kif->kf_type = KF_TYPE_PROCDESC;
3182 kif->kf_type = KF_TYPE_UNKNOWN;
3185 kif->kf_ref_count = fp->f_count;
3186 if (fp->f_flag & FREAD)
3187 kif->kf_flags |= KF_FLAG_READ;
3188 if (fp->f_flag & FWRITE)
3189 kif->kf_flags |= KF_FLAG_WRITE;
3190 if (fp->f_flag & FAPPEND)
3191 kif->kf_flags |= KF_FLAG_APPEND;
3192 if (fp->f_flag & FASYNC)
3193 kif->kf_flags |= KF_FLAG_ASYNC;
3194 if (fp->f_flag & FFSYNC)
3195 kif->kf_flags |= KF_FLAG_FSYNC;
3196 if (fp->f_flag & FNONBLOCK)
3197 kif->kf_flags |= KF_FLAG_NONBLOCK;
3198 if (fp->f_flag & O_DIRECT)
3199 kif->kf_flags |= KF_FLAG_DIRECT;
3200 if (fp->f_flag & FHASLOCK)
3201 kif->kf_flags |= KF_FLAG_HASLOCK;
3202 kif->kf_offset = foffset_get(fp);
3205 switch (vp->v_type) {
3207 kif->kf_vnode_type = KF_VTYPE_VNON;
3210 kif->kf_vnode_type = KF_VTYPE_VREG;
3213 kif->kf_vnode_type = KF_VTYPE_VDIR;
3216 kif->kf_vnode_type = KF_VTYPE_VBLK;
3219 kif->kf_vnode_type = KF_VTYPE_VCHR;
3222 kif->kf_vnode_type = KF_VTYPE_VLNK;
3225 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3228 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3231 kif->kf_vnode_type = KF_VTYPE_VBAD;
3234 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3238 * It is OK to drop the filedesc lock here as we will
3239 * re-validate and re-evaluate its properties when
3240 * the loop continues.
3244 FILEDESC_SUNLOCK(fdp);
3245 vn_fullpath(curthread, vp, &fullpath, &freepath);
3247 strlcpy(kif->kf_path, fullpath,
3248 sizeof(kif->kf_path));
3249 if (freepath != NULL)
3250 free(freepath, M_TEMP);
3251 FILEDESC_SLOCK(fdp);
3254 struct sockaddr *sa;
3256 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3257 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3258 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3261 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3262 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3263 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3266 kif->kf_sock_domain =
3267 so->so_proto->pr_domain->dom_family;
3268 kif->kf_sock_type = so->so_type;
3269 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3272 strlcpy(kif->kf_path, tty_devname(tp),
3273 sizeof(kif->kf_path));
3276 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3277 if (ks != NULL && ksem_info != NULL)
3278 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3279 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3283 FILEDESC_SUNLOCK(fdp);
3289 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3290 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3291 "Process ofiledesc entries");
3292 #endif /* COMPAT_FREEBSD7 */
3294 #ifdef KINFO_FILE_SIZE
3295 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3298 struct export_fd_buf {
3299 struct filedesc *fdp;
3302 struct kinfo_file kif;
3307 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3308 int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3313 } fflags_table[] = {
3314 { FAPPEND, KF_FLAG_APPEND },
3315 { FASYNC, KF_FLAG_ASYNC },
3316 { FFSYNC, KF_FLAG_FSYNC },
3317 { FHASLOCK, KF_FLAG_HASLOCK },
3318 { FNONBLOCK, KF_FLAG_NONBLOCK },
3319 { FREAD, KF_FLAG_READ },
3320 { FWRITE, KF_FLAG_WRITE },
3321 { O_CREAT, KF_FLAG_CREAT },
3322 { O_DIRECT, KF_FLAG_DIRECT },
3323 { O_EXCL, KF_FLAG_EXCL },
3324 { O_EXEC, KF_FLAG_EXEC },
3325 { O_EXLOCK, KF_FLAG_EXLOCK },
3326 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3327 { O_SHLOCK, KF_FLAG_SHLOCK },
3328 { O_TRUNC, KF_FLAG_TRUNC }
3330 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3331 struct kinfo_file *kif;
3336 if (efbuf->remainder == 0)
3339 bzero(kif, sizeof(*kif));
3340 locked = efbuf->fdp != NULL;
3345 FILEDESC_SUNLOCK(efbuf->fdp);
3348 vp = (struct vnode *)data;
3349 error = fill_vnode_info(vp, kif);
3352 case KF_TYPE_SOCKET:
3353 error = fill_socket_info((struct socket *)data, kif);
3356 error = fill_pipe_info((struct pipe *)data, kif);
3359 error = fill_pts_info((struct tty *)data, kif);
3361 case KF_TYPE_PROCDESC:
3362 error = fill_procdesc_info((struct procdesc *)data, kif);
3365 error = fill_sem_info((struct file *)data, kif);
3368 error = fill_shm_info((struct file *)data, kif);
3374 kif->kf_status |= KF_ATTR_VALID;
3377 * Translate file access flags.
3379 for (i = 0; i < NFFLAGS; i++)
3380 if (fflags & fflags_table[i].fflag)
3381 kif->kf_flags |= fflags_table[i].kf_fflag;
3382 if (rightsp != NULL)
3383 kif->kf_cap_rights = *rightsp;
3385 cap_rights_init(&kif->kf_cap_rights);
3387 kif->kf_type = type;
3388 kif->kf_ref_count = refcnt;
3389 kif->kf_offset = offset;
3390 if ((efbuf->flags & KERN_FILEDESC_PACK_KINFO) != 0)
3391 /* Pack record size down */
3392 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3393 strlen(kif->kf_path) + 1;
3395 kif->kf_structsize = sizeof(*kif);
3396 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3397 if (efbuf->remainder != -1) {
3398 if (efbuf->remainder < kif->kf_structsize) {
3399 /* Terminate export. */
3400 efbuf->remainder = 0;
3401 if (efbuf->fdp != NULL && !locked)
3402 FILEDESC_SLOCK(efbuf->fdp);
3405 efbuf->remainder -= kif->kf_structsize;
3408 FILEDESC_SUNLOCK(efbuf->fdp);
3409 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM;
3410 if (efbuf->fdp != NULL)
3411 FILEDESC_SLOCK(efbuf->fdp);
3416 * Store a process file descriptor information to sbuf.
3418 * Takes a locked proc as argument, and returns with the proc unlocked.
3421 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3425 struct filedesc *fdp;
3426 struct export_fd_buf *efbuf;
3427 struct vnode *cttyvp, *textvp, *tracevp;
3431 int type, refcnt, fflags;
3432 cap_rights_t rights;
3434 PROC_LOCK_ASSERT(p, MA_OWNED);
3437 tracevp = p->p_tracevp;
3438 if (tracevp != NULL)
3441 textvp = p->p_textvp;
3444 /* Controlling tty. */
3446 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3447 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3453 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3456 efbuf->remainder = maxlen;
3457 efbuf->flags = flags;
3458 if (tracevp != NULL)
3459 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3460 FREAD | FWRITE, -1, -1, NULL, efbuf);
3462 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3463 FREAD, -1, -1, NULL, efbuf);
3465 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3466 FREAD | FWRITE, -1, -1, NULL, efbuf);
3471 FILEDESC_SLOCK(fdp);
3472 /* working directory */
3473 if (fdp->fd_cdir != NULL) {
3475 data = fdp->fd_cdir;
3476 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3477 FREAD, -1, -1, NULL, efbuf);
3479 /* root directory */
3480 if (fdp->fd_rdir != NULL) {
3482 data = fdp->fd_rdir;
3483 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3484 FREAD, -1, -1, NULL, efbuf);
3486 /* jail directory */
3487 if (fdp->fd_jdir != NULL) {
3489 data = fdp->fd_jdir;
3490 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3491 FREAD, -1, -1, NULL, efbuf);
3493 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3494 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3498 rights = *cap_rights(fdp, i);
3499 #else /* !CAPABILITIES */
3500 cap_rights_init(&rights);
3502 switch (fp->f_type) {
3504 type = KF_TYPE_VNODE;
3510 type = KF_TYPE_SOCKET;
3515 type = KF_TYPE_PIPE;
3520 type = KF_TYPE_FIFO;
3526 type = KF_TYPE_KQUEUE;
3530 type = KF_TYPE_CRYPTO;
3534 type = KF_TYPE_MQUEUE;
3553 case DTYPE_PROCDESC:
3554 type = KF_TYPE_PROCDESC;
3560 type = KF_TYPE_UNKNOWN;
3563 refcnt = fp->f_count;
3564 fflags = fp->f_flag;
3565 offset = foffset_get(fp);
3568 * Create sysctl entry.
3569 * It is OK to drop the filedesc lock here as we will
3570 * re-validate and re-evaluate its properties when
3571 * the loop continues.
3573 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3574 offset, &rights, efbuf);
3578 FILEDESC_SUNLOCK(fdp);
3581 free(efbuf, M_TEMP);
3585 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3588 * Get per-process file descriptors for use by procstat(1), et al.
3591 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3596 int error, error2, *name;
3600 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3601 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3606 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3607 error = kern_proc_filedesc_out(p, &sb, maxlen,
3608 KERN_FILEDESC_PACK_KINFO);
3609 error2 = sbuf_finish(&sb);
3611 return (error != 0 ? error : error2);
3615 vntype_to_kinfo(int vtype)
3620 } vtypes_table[] = {
3621 { VBAD, KF_VTYPE_VBAD },
3622 { VBLK, KF_VTYPE_VBLK },
3623 { VCHR, KF_VTYPE_VCHR },
3624 { VDIR, KF_VTYPE_VDIR },
3625 { VFIFO, KF_VTYPE_VFIFO },
3626 { VLNK, KF_VTYPE_VLNK },
3627 { VNON, KF_VTYPE_VNON },
3628 { VREG, KF_VTYPE_VREG },
3629 { VSOCK, KF_VTYPE_VSOCK }
3631 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3635 * Perform vtype translation.
3637 for (i = 0; i < NVTYPES; i++)
3638 if (vtypes_table[i].vtype == vtype)
3641 return (vtypes_table[i].kf_vtype);
3643 return (KF_VTYPE_UNKNOWN);
3647 vn_fill_junk(struct kinfo_file *kif)
3652 * Simulate vn_fullpath returning changing values for a given
3653 * vp during e.g. coredump.
3655 len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
3656 olen = strlen(kif->kf_path);
3658 strcpy(&kif->kf_path[len - 1], "$");
3660 for (; olen < len; olen++)
3661 strcpy(&kif->kf_path[olen], "A");
3665 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3668 char *fullpath, *freepath;
3673 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3676 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3678 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3680 if (freepath != NULL)
3681 free(freepath, M_TEMP);
3683 KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
3688 * Retrieve vnode attributes.
3690 va.va_fsid = VNOVAL;
3692 vn_lock(vp, LK_SHARED | LK_RETRY);
3693 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3697 if (va.va_fsid != VNOVAL)
3698 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3700 kif->kf_un.kf_file.kf_file_fsid =
3701 vp->v_mount->mnt_stat.f_fsid.val[0];
3702 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3703 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3704 kif->kf_un.kf_file.kf_file_size = va.va_size;
3705 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3710 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3712 struct sockaddr *sa;
3713 struct inpcb *inpcb;
3714 struct unpcb *unpcb;
3719 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3720 kif->kf_sock_type = so->so_type;
3721 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3722 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3723 switch(kif->kf_sock_domain) {
3726 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3727 if (so->so_pcb != NULL) {
3728 inpcb = (struct inpcb *)(so->so_pcb);
3729 kif->kf_un.kf_sock.kf_sock_inpcb =
3730 (uintptr_t)inpcb->inp_ppcb;
3735 if (so->so_pcb != NULL) {
3736 unpcb = (struct unpcb *)(so->so_pcb);
3737 if (unpcb->unp_conn) {
3738 kif->kf_un.kf_sock.kf_sock_unpconn =
3739 (uintptr_t)unpcb->unp_conn;
3740 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3741 so->so_rcv.sb_state;
3742 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3743 so->so_snd.sb_state;
3748 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3749 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3750 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3753 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3754 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3755 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3758 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3759 sizeof(kif->kf_path));
3764 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3769 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3770 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3775 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3780 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3781 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3782 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3787 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3792 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3797 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3803 if (fp->f_data == NULL)
3805 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3807 if (ksem_info == NULL)
3809 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3810 &kif->kf_un.kf_sem.kf_sem_value);
3811 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3816 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3822 if (fp->f_data == NULL)
3824 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3826 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3827 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3828 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3832 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3833 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3834 "Process filedesc entries");
3838 * For the purposes of debugging, generate a human-readable string for the
3842 file_type_to_name(short type)
3872 * For the purposes of debugging, identify a process (if any, perhaps one of
3873 * many) that references the passed file in its file descriptor array. Return
3876 static struct proc *
3877 file_to_first_proc(struct file *fp)
3879 struct filedesc *fdp;
3883 FOREACH_PROC_IN_SYSTEM(p) {
3884 if (p->p_state == PRS_NEW)
3889 for (n = 0; n <= fdp->fd_lastfile; n++) {
3890 if (fp == fdp->fd_ofiles[n].fde_file)
3898 db_print_file(struct file *fp, int header)
3903 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3904 "File", "Type", "Data", "Flag", "GCFl", "Count",
3905 "MCount", "Vnode", "FPID", "FCmd");
3906 p = file_to_first_proc(fp);
3907 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3908 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3909 0, fp->f_count, 0, fp->f_vnode,
3910 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3913 DB_SHOW_COMMAND(file, db_show_file)
3918 db_printf("usage: show file <addr>\n");
3921 fp = (struct file *)addr;
3922 db_print_file(fp, 1);
3925 DB_SHOW_COMMAND(files, db_show_files)
3927 struct filedesc *fdp;
3934 FOREACH_PROC_IN_SYSTEM(p) {
3935 if (p->p_state == PRS_NEW)
3937 if ((fdp = p->p_fd) == NULL)
3939 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3940 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3942 db_print_file(fp, header);
3949 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3950 &maxfilesperproc, 0, "Maximum files allowed open per process");
3952 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3953 &maxfiles, 0, "Maximum number of files");
3955 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3956 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3960 filelistinit(void *dummy)
3963 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3964 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3965 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3966 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3968 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3970 /*-------------------------------------------------------------------*/
3973 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3974 int flags, struct thread *td)
3981 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3989 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3997 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4005 badfo_kqfilter(struct file *fp, struct knote *kn)
4012 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4020 badfo_close(struct file *fp, struct thread *td)
4027 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4035 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4043 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4044 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4045 int kflags, struct thread *td)
4051 struct fileops badfileops = {
4052 .fo_read = badfo_readwrite,
4053 .fo_write = badfo_readwrite,
4054 .fo_truncate = badfo_truncate,
4055 .fo_ioctl = badfo_ioctl,
4056 .fo_poll = badfo_poll,
4057 .fo_kqfilter = badfo_kqfilter,
4058 .fo_stat = badfo_stat,
4059 .fo_close = badfo_close,
4060 .fo_chmod = badfo_chmod,
4061 .fo_chown = badfo_chown,
4062 .fo_sendfile = badfo_sendfile,
4066 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4074 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4082 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4083 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4084 int kflags, struct thread *td)
4090 /*-------------------------------------------------------------------*/
4093 * File Descriptor pseudo-device driver (/dev/fd/).
4095 * Opening minor device N dup()s the file (if any) connected to file
4096 * descriptor N belonging to the calling process. Note that this driver
4097 * consists of only the ``open()'' routine, because all subsequent
4098 * references to this file will be direct to the other driver.
4100 * XXX: we could give this one a cloning event handler if necessary.
4105 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4109 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4110 * the file descriptor being sought for duplication. The error
4111 * return ensures that the vnode for this device will be released
4112 * by vn_open. Open will detect this special error and take the
4113 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4114 * will simply report the error.
4116 td->td_dupfd = dev2unit(dev);
4120 static struct cdevsw fildesc_cdevsw = {
4121 .d_version = D_VERSION,
4127 fildesc_drvinit(void *unused)
4131 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4132 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4133 make_dev_alias(dev, "stdin");
4134 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4135 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4136 make_dev_alias(dev, "stdout");
4137 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4138 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4139 make_dev_alias(dev, "stderr");
4142 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);