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"
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/capsicum.h>
50 #include <sys/fcntl.h>
52 #include <sys/filedesc.h>
53 #include <sys/filio.h>
55 #include <sys/kernel.h>
56 #include <sys/limits.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mutex.h>
61 #include <sys/namei.h>
62 #include <sys/selinfo.h>
65 #include <sys/protosw.h>
66 #include <sys/racct.h>
67 #include <sys/resourcevar.h>
69 #include <sys/signalvar.h>
70 #include <sys/socketvar.h>
73 #include <sys/syscallsubr.h>
74 #include <sys/sysctl.h>
75 #include <sys/sysproto.h>
76 #include <sys/unistd.h>
78 #include <sys/vnode.h>
80 #include <sys/ktrace.h>
85 #include <security/audit/audit.h>
92 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
93 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
94 "file desc to leader structures");
95 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
96 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
98 MALLOC_DECLARE(M_FADVISE);
100 static uma_zone_t file_zone;
101 static uma_zone_t filedesc0_zone;
103 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
104 struct thread *td, int holdleaders);
105 static int do_dup(struct thread *td, int flags, int old, int new);
106 static int fd_first_free(struct filedesc *fdp, int low, int size);
107 static int fd_last_used(struct filedesc *fdp, int size);
108 static void fdgrowtable(struct filedesc *fdp, int nfd);
109 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
110 static void fdunused(struct filedesc *fdp, int fd);
111 static void fdused(struct filedesc *fdp, int fd);
112 static int getmaxfd(struct proc *p);
114 /* Flags for do_dup() */
115 #define DUP_FIXED 0x1 /* Force fixed allocation. */
116 #define DUP_FCNTL 0x2 /* fcntl()-style errors. */
117 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
122 * - An array of open file descriptors (fd_ofiles)
123 * - An array of file flags (fd_ofileflags)
124 * - A bitmap recording which descriptors are in use (fd_map)
126 * A process starts out with NDFILE descriptors. The value of NDFILE has
127 * been selected based the historical limit of 20 open files, and an
128 * assumption that the majority of processes, especially short-lived
129 * processes like shells, will never need more.
131 * If this initial allocation is exhausted, a larger descriptor table and
132 * map are allocated dynamically, and the pointers in the process's struct
133 * filedesc are updated to point to those. This is repeated every time
134 * the process runs out of file descriptors (provided it hasn't hit its
137 * Since threads may hold references to individual descriptor table
138 * entries, the tables are never freed. Instead, they are placed on a
139 * linked list and freed only when the struct filedesc is released.
142 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
143 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
144 #define NDSLOT(x) ((x) / NDENTRIES)
145 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
146 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
149 * SLIST entry used to keep track of ofiles which must be reclaimed when
153 struct fdescenttbl *ft_table;
154 SLIST_ENTRY(freetable) ft_next;
158 * Initial allocation: a filedesc structure + the head of SLIST used to
159 * keep track of old ofiles + enough space for NDFILE descriptors.
162 struct fdescenttbl0 {
164 struct filedescent fdt_ofiles[NDFILE];
168 struct filedesc fd_fd;
169 SLIST_HEAD(, freetable) fd_free;
170 struct fdescenttbl0 fd_dfiles;
171 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
175 * Descriptor management.
177 volatile int openfiles; /* actual number of open files */
178 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
179 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
181 /* A mutex to protect the association between a proc and filedesc. */
182 static struct mtx fdesc_mtx;
185 * If low >= size, just return low. Otherwise find the first zero bit in the
186 * given bitmap, starting at low and not exceeding size - 1. Return size if
190 fd_first_free(struct filedesc *fdp, int low, int size)
192 NDSLOTTYPE *map = fdp->fd_map;
200 if (low % NDENTRIES) {
201 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
202 if ((mask &= ~map[off]) != 0UL)
203 return (off * NDENTRIES + ffsl(mask) - 1);
206 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
207 if (map[off] != ~0UL)
208 return (off * NDENTRIES + ffsl(~map[off]) - 1);
213 * Find the highest non-zero bit in the given bitmap, starting at 0 and
214 * not exceeding size - 1. Return -1 if not found.
217 fd_last_used(struct filedesc *fdp, int size)
219 NDSLOTTYPE *map = fdp->fd_map;
224 if (size % NDENTRIES) {
225 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
226 if ((mask &= map[off]) != 0)
227 return (off * NDENTRIES + flsl(mask) - 1);
230 for (minoff = NDSLOT(0); off >= minoff; --off)
232 return (off * NDENTRIES + flsl(map[off]) - 1);
238 fdisused(struct filedesc *fdp, int fd)
241 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
242 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
244 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
249 * Mark a file descriptor as used.
252 fdused_init(struct filedesc *fdp, int fd)
255 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
257 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
261 fdused(struct filedesc *fdp, int fd)
264 FILEDESC_XLOCK_ASSERT(fdp);
266 fdused_init(fdp, fd);
267 if (fd > fdp->fd_lastfile)
268 fdp->fd_lastfile = fd;
269 if (fd == fdp->fd_freefile)
270 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
274 * Mark a file descriptor as unused.
277 fdunused(struct filedesc *fdp, int fd)
280 FILEDESC_XLOCK_ASSERT(fdp);
282 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
283 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
284 ("fd=%d is still in use", fd));
286 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
287 if (fd < fdp->fd_freefile)
288 fdp->fd_freefile = fd;
289 if (fd == fdp->fd_lastfile)
290 fdp->fd_lastfile = fd_last_used(fdp, fd);
294 * Free a file descriptor.
296 * Avoid some work if fdp is about to be destroyed.
299 fdefree_last(struct filedescent *fde)
302 filecaps_free(&fde->fde_caps);
306 fdfree(struct filedesc *fdp, int fd)
308 struct filedescent *fde;
310 fde = &fdp->fd_ofiles[fd];
312 seq_write_begin(&fde->fde_seq);
315 bzero(fde, fde_change_size);
318 seq_write_end(&fde->fde_seq);
323 * System calls on descriptors.
325 #ifndef _SYS_SYSPROTO_H_
326 struct getdtablesize_args {
332 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
334 struct proc *p = td->td_proc;
339 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
340 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
342 if (lim < td->td_retval[0])
343 td->td_retval[0] = lim;
348 * Duplicate a file descriptor to a particular value.
350 * Note: keep in mind that a potential race condition exists when closing
351 * descriptors from a shared descriptor table (via rfork).
353 #ifndef _SYS_SYSPROTO_H_
361 sys_dup2(struct thread *td, struct dup2_args *uap)
364 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to));
368 * Duplicate a file descriptor.
370 #ifndef _SYS_SYSPROTO_H_
377 sys_dup(struct thread *td, struct dup_args *uap)
380 return (do_dup(td, 0, (int)uap->fd, 0));
384 * The file control system call.
386 #ifndef _SYS_SYSPROTO_H_
395 sys_fcntl(struct thread *td, struct fcntl_args *uap)
398 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
402 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
415 * Convert old flock structure to new.
417 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
418 fl.l_start = ofl.l_start;
419 fl.l_len = ofl.l_len;
420 fl.l_pid = ofl.l_pid;
421 fl.l_type = ofl.l_type;
422 fl.l_whence = ofl.l_whence;
436 arg1 = (intptr_t)&fl;
442 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
443 arg1 = (intptr_t)&fl;
451 error = kern_fcntl(td, fd, cmd, arg1);
454 if (cmd == F_OGETLK) {
455 ofl.l_start = fl.l_start;
456 ofl.l_len = fl.l_len;
457 ofl.l_pid = fl.l_pid;
458 ofl.l_type = fl.l_type;
459 ofl.l_whence = fl.l_whence;
460 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
461 } else if (cmd == F_GETLK) {
462 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
468 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
470 struct filedesc *fdp;
472 struct file *fp, *fp2;
473 struct filedescent *fde;
489 error = do_dup(td, DUP_FCNTL, fd, tmp);
492 case F_DUPFD_CLOEXEC:
494 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp);
499 error = do_dup(td, DUP_FIXED, fd, tmp);
502 case F_DUP2FD_CLOEXEC:
504 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp);
509 if (fget_locked(fdp, fd) == NULL) {
510 FILEDESC_SUNLOCK(fdp);
514 fde = &fdp->fd_ofiles[fd];
516 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
517 FILEDESC_SUNLOCK(fdp);
522 if (fget_locked(fdp, fd) == NULL) {
523 FILEDESC_XUNLOCK(fdp);
527 fde = &fdp->fd_ofiles[fd];
528 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
529 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
530 FILEDESC_XUNLOCK(fdp);
534 error = fget_fcntl(td, fd,
535 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp);
538 td->td_retval[0] = OFLAGS(fp->f_flag);
543 error = fget_fcntl(td, fd,
544 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp);
548 tmp = flg = fp->f_flag;
550 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
551 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
552 tmp = fp->f_flag & FNONBLOCK;
553 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
558 tmp = fp->f_flag & FASYNC;
559 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
564 atomic_clear_int(&fp->f_flag, FNONBLOCK);
566 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
571 error = fget_fcntl(td, fd,
572 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp);
575 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
577 td->td_retval[0] = tmp;
582 error = fget_fcntl(td, fd,
583 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp);
587 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
592 error = priv_check(td, PRIV_NFS_LOCKD);
600 /* FALLTHROUGH F_SETLK */
604 cap_rights_init(&rights, CAP_FLOCK);
605 error = fget_unlocked(fdp, fd, &rights, &fp, NULL);
608 if (fp->f_type != DTYPE_VNODE) {
614 flp = (struct flock *)arg;
615 if (flp->l_whence == SEEK_CUR) {
616 foffset = foffset_get(fp);
619 foffset > OFF_MAX - flp->l_start)) {
624 flp->l_start += foffset;
628 switch (flp->l_type) {
630 if ((fp->f_flag & FREAD) == 0) {
634 PROC_LOCK(p->p_leader);
635 p->p_leader->p_flag |= P_ADVLOCK;
636 PROC_UNLOCK(p->p_leader);
637 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
641 if ((fp->f_flag & FWRITE) == 0) {
645 PROC_LOCK(p->p_leader);
646 p->p_leader->p_flag |= P_ADVLOCK;
647 PROC_UNLOCK(p->p_leader);
648 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
652 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
657 * Temporary api for testing remote lock
660 if (flg != F_REMOTE) {
664 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
665 F_UNLCKSYS, flp, flg);
671 if (error != 0 || flp->l_type == F_UNLCK ||
672 flp->l_type == F_UNLCKSYS) {
678 * Check for a race with close.
680 * The vnode is now advisory locked (or unlocked, but this case
681 * is not really important) as the caller requested.
682 * We had to drop the filedesc lock, so we need to recheck if
683 * the descriptor is still valid, because if it was closed
684 * in the meantime we need to remove advisory lock from the
685 * vnode - close on any descriptor leading to an advisory
686 * locked vnode, removes that lock.
687 * We will return 0 on purpose in that case, as the result of
688 * successful advisory lock might have been externally visible
689 * already. This is fine - effectively we pretend to the caller
690 * that the closing thread was a bit slower and that the
691 * advisory lock succeeded before the close.
693 error = fget_unlocked(fdp, fd, &rights, &fp2, NULL);
699 flp->l_whence = SEEK_SET;
702 flp->l_type = F_UNLCK;
703 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
704 F_UNLCK, flp, F_POSIX);
711 error = fget_unlocked(fdp, fd,
712 cap_rights_init(&rights, CAP_FLOCK), &fp, NULL);
715 if (fp->f_type != DTYPE_VNODE) {
720 flp = (struct flock *)arg;
721 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
722 flp->l_type != F_UNLCK) {
727 if (flp->l_whence == SEEK_CUR) {
728 foffset = foffset_get(fp);
729 if ((flp->l_start > 0 &&
730 foffset > OFF_MAX - flp->l_start) ||
732 foffset < OFF_MIN - flp->l_start)) {
737 flp->l_start += foffset;
740 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
746 arg = arg ? 128 * 1024: 0;
749 error = fget_unlocked(fdp, fd, NULL, &fp, NULL);
752 if (fp->f_type != DTYPE_VNODE) {
759 * Exclusive lock synchronizes against f_seqcount reads and
760 * writes in sequential_heuristic().
762 error = vn_lock(vp, LK_EXCLUSIVE);
768 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
769 fp->f_seqcount = (arg + bsize - 1) / bsize;
770 atomic_set_int(&fp->f_flag, FRDAHEAD);
772 atomic_clear_int(&fp->f_flag, FRDAHEAD);
786 getmaxfd(struct proc *p)
791 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
798 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
801 do_dup(struct thread *td, int flags, int old, int new)
803 struct filedesc *fdp;
804 struct filedescent *oldfde, *newfde;
814 * Verify we have a valid descriptor to dup from and possibly to
815 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
816 * return EINVAL when the new descriptor is out of bounds.
821 return (flags & DUP_FCNTL ? EINVAL : EBADF);
824 return (flags & DUP_FCNTL ? EINVAL : EBADF);
827 if (fget_locked(fdp, old) == NULL) {
828 FILEDESC_XUNLOCK(fdp);
831 oldfde = &fdp->fd_ofiles[old];
832 if (flags & DUP_FIXED && old == new) {
833 td->td_retval[0] = new;
834 if (flags & DUP_CLOEXEC)
835 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
836 FILEDESC_XUNLOCK(fdp);
839 fp = oldfde->fde_file;
843 * If the caller specified a file descriptor, make sure the file
844 * table is large enough to hold it, and grab it. Otherwise, just
845 * allocate a new descriptor the usual way.
847 if (flags & DUP_FIXED) {
848 if (new >= fdp->fd_nfiles) {
850 * The resource limits are here instead of e.g.
851 * fdalloc(), because the file descriptor table may be
852 * shared between processes, so we can't really use
853 * racct_add()/racct_sub(). Instead of counting the
854 * number of actually allocated descriptors, just put
855 * the limit on the size of the file descriptor table.
860 error = racct_set(p, RACCT_NOFILE, new + 1);
863 FILEDESC_XUNLOCK(fdp);
869 fdgrowtable_exp(fdp, new + 1);
870 oldfde = &fdp->fd_ofiles[old];
872 newfde = &fdp->fd_ofiles[new];
873 if (newfde->fde_file == NULL)
876 if ((error = fdalloc(td, new, &new)) != 0) {
877 FILEDESC_XUNLOCK(fdp);
881 newfde = &fdp->fd_ofiles[new];
884 KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
885 KASSERT(old != new, ("new fd is same as old"));
887 delfp = newfde->fde_file;
890 * Duplicate the source descriptor.
893 seq_write_begin(&newfde->fde_seq);
895 filecaps_free(&newfde->fde_caps);
896 memcpy(newfde, oldfde, fde_change_size);
897 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
898 if ((flags & DUP_CLOEXEC) != 0)
899 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
901 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
903 seq_write_end(&newfde->fde_seq);
905 td->td_retval[0] = new;
908 (void) closefp(fdp, new, delfp, td, 1);
909 /* closefp() drops the FILEDESC lock for us. */
911 FILEDESC_XUNLOCK(fdp);
918 * If sigio is on the list associated with a process or process group,
919 * disable signalling from the device, remove sigio from the list and
923 funsetown(struct sigio **sigiop)
933 *(sigio->sio_myref) = NULL;
934 if ((sigio)->sio_pgid < 0) {
935 struct pgrp *pg = (sigio)->sio_pgrp;
937 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
941 struct proc *p = (sigio)->sio_proc;
943 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
948 crfree(sigio->sio_ucred);
949 free(sigio, M_SIGIO);
953 * Free a list of sigio structures.
954 * We only need to lock the SIGIO_LOCK because we have made ourselves
955 * inaccessible to callers of fsetown and therefore do not need to lock
956 * the proc or pgrp struct for the list manipulation.
959 funsetownlst(struct sigiolst *sigiolst)
965 sigio = SLIST_FIRST(sigiolst);
972 * Every entry of the list should belong
973 * to a single proc or pgrp.
975 if (sigio->sio_pgid < 0) {
976 pg = sigio->sio_pgrp;
977 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
978 } else /* if (sigio->sio_pgid > 0) */ {
980 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
984 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
985 *(sigio->sio_myref) = NULL;
987 KASSERT(sigio->sio_pgid < 0,
988 ("Proc sigio in pgrp sigio list"));
989 KASSERT(sigio->sio_pgrp == pg,
990 ("Bogus pgrp in sigio list"));
992 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
995 } else /* if (p != NULL) */ {
996 KASSERT(sigio->sio_pgid > 0,
997 ("Pgrp sigio in proc sigio list"));
998 KASSERT(sigio->sio_proc == p,
999 ("Bogus proc in sigio list"));
1001 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1006 crfree(sigio->sio_ucred);
1007 free(sigio, M_SIGIO);
1014 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1016 * After permission checking, add a sigio structure to the sigio list for
1017 * the process or process group.
1020 fsetown(pid_t pgid, struct sigio **sigiop)
1024 struct sigio *sigio;
1034 /* Allocate and fill in the new sigio out of locks. */
1035 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1036 sigio->sio_pgid = pgid;
1037 sigio->sio_ucred = crhold(curthread->td_ucred);
1038 sigio->sio_myref = sigiop;
1040 sx_slock(&proctree_lock);
1049 * Policy - Don't allow a process to FSETOWN a process
1050 * in another session.
1052 * Remove this test to allow maximum flexibility or
1053 * restrict FSETOWN to the current process or process
1054 * group for maximum safety.
1057 if (proc->p_session != curthread->td_proc->p_session) {
1063 } else /* if (pgid < 0) */ {
1064 pgrp = pgfind(-pgid);
1072 * Policy - Don't allow a process to FSETOWN a process
1073 * in another session.
1075 * Remove this test to allow maximum flexibility or
1076 * restrict FSETOWN to the current process or process
1077 * group for maximum safety.
1079 if (pgrp->pg_session != curthread->td_proc->p_session) {
1090 * Since funsetownlst() is called without the proctree
1091 * locked, we need to check for P_WEXIT.
1092 * XXX: is ESRCH correct?
1094 if ((proc->p_flag & P_WEXIT) != 0) {
1099 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1100 sigio->sio_proc = proc;
1104 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1105 sigio->sio_pgrp = pgrp;
1108 sx_sunlock(&proctree_lock);
1115 sx_sunlock(&proctree_lock);
1116 crfree(sigio->sio_ucred);
1117 free(sigio, M_SIGIO);
1122 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1126 struct sigio **sigiop;
1131 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1137 * Function drops the filedesc lock on return.
1140 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1145 FILEDESC_XLOCK_ASSERT(fdp);
1148 if (td->td_proc->p_fdtol != NULL) {
1150 * Ask fdfree() to sleep to ensure that all relevant
1151 * process leaders can be traversed in closef().
1153 fdp->fd_holdleaderscount++;
1160 * We now hold the fp reference that used to be owned by the
1161 * descriptor array. We have to unlock the FILEDESC *AFTER*
1162 * knote_fdclose to prevent a race of the fd getting opened, a knote
1163 * added, and deleteing a knote for the new fd.
1165 knote_fdclose(td, fd);
1168 * We need to notify mqueue if the object is of type mqueue.
1170 if (fp->f_type == DTYPE_MQUEUE)
1171 mq_fdclose(td, fd, fp);
1172 FILEDESC_XUNLOCK(fdp);
1174 error = closef(fp, td);
1176 FILEDESC_XLOCK(fdp);
1177 fdp->fd_holdleaderscount--;
1178 if (fdp->fd_holdleaderscount == 0 &&
1179 fdp->fd_holdleaderswakeup != 0) {
1180 fdp->fd_holdleaderswakeup = 0;
1181 wakeup(&fdp->fd_holdleaderscount);
1183 FILEDESC_XUNLOCK(fdp);
1189 * Close a file descriptor.
1191 #ifndef _SYS_SYSPROTO_H_
1200 struct close_args *uap;
1203 return (kern_close(td, uap->fd));
1211 struct filedesc *fdp;
1214 fdp = td->td_proc->p_fd;
1216 AUDIT_SYSCLOSE(td, fd);
1218 FILEDESC_XLOCK(fdp);
1219 if ((fp = fget_locked(fdp, fd)) == NULL) {
1220 FILEDESC_XUNLOCK(fdp);
1225 /* closefp() drops the FILEDESC lock for us. */
1226 return (closefp(fdp, fd, fp, td, 1));
1230 * Close open file descriptors.
1232 #ifndef _SYS_SYSPROTO_H_
1233 struct closefrom_args {
1239 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1241 struct filedesc *fdp;
1244 fdp = td->td_proc->p_fd;
1245 AUDIT_ARG_FD(uap->lowfd);
1248 * Treat negative starting file descriptor values identical to
1249 * closefrom(0) which closes all files.
1253 FILEDESC_SLOCK(fdp);
1254 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1255 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1256 FILEDESC_SUNLOCK(fdp);
1257 (void)kern_close(td, fd);
1258 FILEDESC_SLOCK(fdp);
1261 FILEDESC_SUNLOCK(fdp);
1265 #if defined(COMPAT_43)
1267 * Return status information about a file descriptor.
1269 #ifndef _SYS_SYSPROTO_H_
1270 struct ofstat_args {
1277 ofstat(struct thread *td, struct ofstat_args *uap)
1283 error = kern_fstat(td, uap->fd, &ub);
1286 error = copyout(&oub, uap->sb, sizeof(oub));
1290 #endif /* COMPAT_43 */
1293 * Return status information about a file descriptor.
1295 #ifndef _SYS_SYSPROTO_H_
1303 sys_fstat(struct thread *td, struct fstat_args *uap)
1308 error = kern_fstat(td, uap->fd, &ub);
1310 error = copyout(&ub, uap->sb, sizeof(ub));
1315 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1318 cap_rights_t rights;
1323 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1327 AUDIT_ARG_FILE(td->td_proc, fp);
1329 error = fo_stat(fp, sbp, td->td_ucred, td);
1332 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1339 * Return status information about a file descriptor.
1341 #ifndef _SYS_SYSPROTO_H_
1342 struct nfstat_args {
1349 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1355 error = kern_fstat(td, uap->fd, &ub);
1357 cvtnstat(&ub, &nub);
1358 error = copyout(&nub, uap->sb, sizeof(nub));
1364 * Return pathconf information about a file descriptor.
1366 #ifndef _SYS_SYSPROTO_H_
1367 struct fpathconf_args {
1374 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1378 cap_rights_t rights;
1381 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1385 /* If asynchronous I/O is available, it works for all descriptors. */
1386 if (uap->name == _PC_ASYNC_IO) {
1387 td->td_retval[0] = async_io_version;
1392 vn_lock(vp, LK_SHARED | LK_RETRY);
1393 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1395 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1396 if (uap->name != _PC_PIPE_BUF) {
1399 td->td_retval[0] = PIPE_BUF;
1411 * Initialize filecaps structure.
1414 filecaps_init(struct filecaps *fcaps)
1417 bzero(fcaps, sizeof(*fcaps));
1418 fcaps->fc_nioctls = -1;
1422 * Copy filecaps structure allocating memory for ioctls array if needed.
1425 filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1430 if (src->fc_ioctls != NULL) {
1431 KASSERT(src->fc_nioctls > 0,
1432 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1434 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1435 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1436 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1441 * Move filecaps structure to the new place and clear the old place.
1444 filecaps_move(struct filecaps *src, struct filecaps *dst)
1448 bzero(src, sizeof(*src));
1452 * Fill the given filecaps structure with full rights.
1455 filecaps_fill(struct filecaps *fcaps)
1458 CAP_ALL(&fcaps->fc_rights);
1459 fcaps->fc_ioctls = NULL;
1460 fcaps->fc_nioctls = -1;
1461 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1465 * Free memory allocated within filecaps structure.
1468 filecaps_free(struct filecaps *fcaps)
1471 free(fcaps->fc_ioctls, M_FILECAPS);
1472 bzero(fcaps, sizeof(*fcaps));
1476 * Validate the given filecaps structure.
1479 filecaps_validate(const struct filecaps *fcaps, const char *func)
1482 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1483 ("%s: invalid rights", func));
1484 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1485 ("%s: invalid fcntls", func));
1486 KASSERT(fcaps->fc_fcntls == 0 ||
1487 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1488 ("%s: fcntls without CAP_FCNTL", func));
1489 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1490 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1491 ("%s: invalid ioctls", func));
1492 KASSERT(fcaps->fc_nioctls == 0 ||
1493 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1494 ("%s: ioctls without CAP_IOCTL", func));
1498 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1502 FILEDESC_XLOCK_ASSERT(fdp);
1504 nfd1 = fdp->fd_nfiles * 2;
1507 fdgrowtable(fdp, nfd1);
1511 * Grow the file table to accomodate (at least) nfd descriptors.
1514 fdgrowtable(struct filedesc *fdp, int nfd)
1516 struct filedesc0 *fdp0;
1517 struct freetable *ft;
1518 struct fdescenttbl *ntable;
1519 struct fdescenttbl *otable;
1520 int nnfiles, onfiles;
1521 NDSLOTTYPE *nmap, *omap;
1524 * If lastfile is -1 this struct filedesc was just allocated and we are
1525 * growing it to accomodate for the one we are going to copy from. There
1526 * is no need to have a lock on this one as it's not visible to anyone.
1528 if (fdp->fd_lastfile != -1)
1529 FILEDESC_XLOCK_ASSERT(fdp);
1531 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1533 /* save old values */
1534 onfiles = fdp->fd_nfiles;
1535 otable = fdp->fd_files;
1538 /* compute the size of the new table */
1539 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1540 if (nnfiles <= onfiles)
1541 /* the table is already large enough */
1545 * Allocate a new table. We need enough space for the number of
1546 * entries, file entries themselves and the struct freetable we will use
1547 * when we decommission the table and place it on the freelist.
1548 * We place the struct freetable in the middle so we don't have
1549 * to worry about padding.
1551 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1552 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1553 sizeof(struct freetable),
1554 M_FILEDESC, M_ZERO | M_WAITOK);
1555 /* copy the old data */
1556 ntable->fdt_nfiles = nnfiles;
1557 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1558 onfiles * sizeof(ntable->fdt_ofiles[0]));
1561 * Allocate a new map only if the old is not large enough. It will
1562 * grow at a slower rate than the table as it can map more
1563 * entries than the table can hold.
1565 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1566 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1568 /* copy over the old data and update the pointer */
1569 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1574 * Make sure that ntable is correctly initialized before we replace
1575 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1578 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1581 * Do not free the old file table, as some threads may still
1582 * reference entries within it. Instead, place it on a freelist
1583 * which will be processed when the struct filedesc is released.
1585 * Note that if onfiles == NDFILE, we're dealing with the original
1586 * static allocation contained within (struct filedesc0 *)fdp,
1587 * which must not be freed.
1589 if (onfiles > NDFILE) {
1590 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1591 fdp0 = (struct filedesc0 *)fdp;
1592 ft->ft_table = otable;
1593 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1596 * The map does not have the same possibility of threads still
1597 * holding references to it. So always free it as long as it
1598 * does not reference the original static allocation.
1600 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1601 free(omap, M_FILEDESC);
1605 * Allocate a file descriptor for the process.
1608 fdalloc(struct thread *td, int minfd, int *result)
1610 struct proc *p = td->td_proc;
1611 struct filedesc *fdp = p->p_fd;
1612 int fd, maxfd, allocfd;
1617 FILEDESC_XLOCK_ASSERT(fdp);
1619 if (fdp->fd_freefile > minfd)
1620 minfd = fdp->fd_freefile;
1622 maxfd = getmaxfd(p);
1625 * Search the bitmap for a free descriptor starting at minfd.
1626 * If none is found, grow the file table.
1628 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1631 if (fd >= fdp->fd_nfiles) {
1632 allocfd = min(fd * 2, maxfd);
1636 error = racct_set(p, RACCT_NOFILE, allocfd);
1643 * fd is already equal to first free descriptor >= minfd, so
1644 * we only need to grow the table and we are done.
1646 fdgrowtable_exp(fdp, allocfd);
1650 * Perform some sanity checks, then mark the file descriptor as
1651 * used and return it to the caller.
1653 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1654 ("invalid descriptor %d", fd));
1655 KASSERT(!fdisused(fdp, fd),
1656 ("fd_first_free() returned non-free descriptor"));
1657 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1658 ("file descriptor isn't free"));
1659 KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1666 * Allocate n file descriptors for the process.
1669 fdallocn(struct thread *td, int minfd, int *fds, int n)
1671 struct proc *p = td->td_proc;
1672 struct filedesc *fdp = p->p_fd;
1675 FILEDESC_XLOCK_ASSERT(fdp);
1677 for (i = 0; i < n; i++)
1678 if (fdalloc(td, 0, &fds[i]) != 0)
1682 for (i--; i >= 0; i--)
1683 fdunused(fdp, fds[i]);
1691 * Create a new open file structure and allocate a file decriptor for the
1692 * process that refers to it. We add one reference to the file for the
1693 * descriptor table and one reference for resultfp. This is to prevent us
1694 * being preempted and the entry in the descriptor table closed after we
1695 * release the FILEDESC lock.
1698 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1703 error = falloc_noinstall(td, &fp);
1705 return (error); /* no reference held on error */
1707 error = finstall(td, fp, &fd, flags, NULL);
1709 fdrop(fp, td); /* one reference (fp only) */
1713 if (resultfp != NULL)
1714 *resultfp = fp; /* copy out result */
1716 fdrop(fp, td); /* release local reference */
1718 if (resultfd != NULL)
1725 * Create a new open file structure without allocating a file descriptor.
1728 falloc_noinstall(struct thread *td, struct file **resultfp)
1731 int maxuserfiles = maxfiles - (maxfiles / 20);
1732 static struct timeval lastfail;
1735 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1737 if ((openfiles >= maxuserfiles &&
1738 priv_check(td, PRIV_MAXFILES) != 0) ||
1739 openfiles >= maxfiles) {
1740 if (ppsratecheck(&lastfail, &curfail, 1)) {
1741 printf("kern.maxfiles limit exceeded by uid %i, "
1742 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1746 atomic_add_int(&openfiles, 1);
1747 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1748 refcount_init(&fp->f_count, 1);
1749 fp->f_cred = crhold(td->td_ucred);
1750 fp->f_ops = &badfileops;
1756 * Install a file in a file descriptor table.
1759 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1760 struct filecaps *fcaps)
1762 struct filedesc *fdp = td->td_proc->p_fd;
1763 struct filedescent *fde;
1766 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1767 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1769 filecaps_validate(fcaps, __func__);
1771 FILEDESC_XLOCK(fdp);
1772 if ((error = fdalloc(td, 0, fd))) {
1773 FILEDESC_XUNLOCK(fdp);
1777 fde = &fdp->fd_ofiles[*fd];
1779 seq_write_begin(&fde->fde_seq);
1782 if ((flags & O_CLOEXEC) != 0)
1783 fde->fde_flags |= UF_EXCLOSE;
1785 filecaps_move(fcaps, &fde->fde_caps);
1787 filecaps_fill(&fde->fde_caps);
1789 seq_write_end(&fde->fde_seq);
1791 FILEDESC_XUNLOCK(fdp);
1796 * Build a new filedesc structure from another.
1797 * Copy the current, root, and jail root vnode references.
1799 * If fdp is not NULL, return with it shared locked.
1802 fdinit(struct filedesc *fdp, bool prepfiles)
1804 struct filedesc0 *newfdp0;
1805 struct filedesc *newfdp;
1807 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1808 newfdp = &newfdp0->fd_fd;
1810 /* Create the file descriptor table. */
1811 FILEDESC_LOCK_INIT(newfdp);
1812 newfdp->fd_refcnt = 1;
1813 newfdp->fd_holdcnt = 1;
1814 newfdp->fd_cmask = CMASK;
1815 newfdp->fd_map = newfdp0->fd_dmap;
1816 newfdp->fd_lastfile = -1;
1817 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
1818 newfdp->fd_files->fdt_nfiles = NDFILE;
1823 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
1824 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1826 FILEDESC_SLOCK(fdp);
1827 newfdp->fd_cdir = fdp->fd_cdir;
1828 if (newfdp->fd_cdir)
1829 VREF(newfdp->fd_cdir);
1830 newfdp->fd_rdir = fdp->fd_rdir;
1831 if (newfdp->fd_rdir)
1832 VREF(newfdp->fd_rdir);
1833 newfdp->fd_jdir = fdp->fd_jdir;
1834 if (newfdp->fd_jdir)
1835 VREF(newfdp->fd_jdir);
1838 FILEDESC_SUNLOCK(fdp);
1840 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1841 FILEDESC_SUNLOCK(fdp);
1842 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1843 FILEDESC_SLOCK(fdp);
1850 static struct filedesc *
1851 fdhold(struct proc *p)
1853 struct filedesc *fdp;
1855 mtx_lock(&fdesc_mtx);
1859 mtx_unlock(&fdesc_mtx);
1864 fddrop(struct filedesc *fdp)
1868 if (fdp->fd_holdcnt > 1) {
1869 mtx_lock(&fdesc_mtx);
1870 i = --fdp->fd_holdcnt;
1871 mtx_unlock(&fdesc_mtx);
1876 FILEDESC_LOCK_DESTROY(fdp);
1877 uma_zfree(filedesc0_zone, fdp);
1881 * Share a filedesc structure.
1884 fdshare(struct filedesc *fdp)
1887 FILEDESC_XLOCK(fdp);
1889 FILEDESC_XUNLOCK(fdp);
1894 * Unshare a filedesc structure, if necessary by making a copy
1897 fdunshare(struct thread *td)
1899 struct filedesc *tmp;
1900 struct proc *p = td->td_proc;
1902 if (p->p_fd->fd_refcnt == 1)
1905 tmp = fdcopy(p->p_fd);
1911 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1912 * this is to ease callers, not catch errors.
1915 fdcopy(struct filedesc *fdp)
1917 struct filedesc *newfdp;
1918 struct filedescent *nfde, *ofde;
1923 newfdp = fdinit(fdp, true);
1924 /* copy all passable descriptors (i.e. not kqueue) */
1925 newfdp->fd_freefile = -1;
1926 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1927 ofde = &fdp->fd_ofiles[i];
1928 if (ofde->fde_file == NULL ||
1929 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
1930 if (newfdp->fd_freefile == -1)
1931 newfdp->fd_freefile = i;
1934 nfde = &newfdp->fd_ofiles[i];
1936 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1937 fhold(nfde->fde_file);
1938 fdused_init(newfdp, i);
1939 newfdp->fd_lastfile = i;
1941 if (newfdp->fd_freefile == -1)
1942 newfdp->fd_freefile = i;
1943 newfdp->fd_cmask = fdp->fd_cmask;
1944 FILEDESC_SUNLOCK(fdp);
1949 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
1950 * one of processes using it exits) and the table used to be shared.
1953 fdclearlocks(struct thread *td)
1955 struct filedesc *fdp;
1956 struct filedesc_to_leader *fdtol;
1966 MPASS(fdtol != NULL);
1968 FILEDESC_XLOCK(fdp);
1969 KASSERT(fdtol->fdl_refcount > 0,
1970 ("filedesc_to_refcount botch: fdl_refcount=%d",
1971 fdtol->fdl_refcount));
1972 if (fdtol->fdl_refcount == 1 &&
1973 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1974 for (i = 0; i <= fdp->fd_lastfile; i++) {
1975 fp = fdp->fd_ofiles[i].fde_file;
1976 if (fp == NULL || fp->f_type != DTYPE_VNODE)
1979 FILEDESC_XUNLOCK(fdp);
1980 lf.l_whence = SEEK_SET;
1983 lf.l_type = F_UNLCK;
1985 (void) VOP_ADVLOCK(vp,
1986 (caddr_t)p->p_leader, F_UNLCK,
1988 FILEDESC_XLOCK(fdp);
1993 if (fdtol->fdl_refcount == 1) {
1994 if (fdp->fd_holdleaderscount > 0 &&
1995 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1997 * close() or do_dup() has cleared a reference
1998 * in a shared file descriptor table.
2000 fdp->fd_holdleaderswakeup = 1;
2001 sx_sleep(&fdp->fd_holdleaderscount,
2002 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2005 if (fdtol->fdl_holdcount > 0) {
2007 * Ensure that fdtol->fdl_leader remains
2008 * valid in closef().
2010 fdtol->fdl_wakeup = 1;
2011 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2016 fdtol->fdl_refcount--;
2017 if (fdtol->fdl_refcount == 0 &&
2018 fdtol->fdl_holdcount == 0) {
2019 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2020 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2024 FILEDESC_XUNLOCK(fdp);
2026 free(fdtol, M_FILEDESC_TO_LEADER);
2030 * Release a filedesc structure.
2033 fdescfree(struct thread *td)
2035 struct filedesc0 *fdp0;
2036 struct filedesc *fdp;
2037 struct freetable *ft, *tft;
2038 struct filedescent *fde;
2040 struct vnode *cdir, *jdir, *rdir;
2043 fdp = td->td_proc->p_fd;
2048 PROC_LOCK(td->td_proc);
2049 racct_set(td->td_proc, RACCT_NOFILE, 0);
2050 PROC_UNLOCK(td->td_proc);
2054 if (td->td_proc->p_fdtol != NULL)
2057 mtx_lock(&fdesc_mtx);
2058 td->td_proc->p_fd = NULL;
2059 mtx_unlock(&fdesc_mtx);
2061 FILEDESC_XLOCK(fdp);
2062 i = --fdp->fd_refcnt;
2064 FILEDESC_XUNLOCK(fdp);
2068 cdir = fdp->fd_cdir;
2069 fdp->fd_cdir = NULL;
2070 rdir = fdp->fd_rdir;
2071 fdp->fd_rdir = NULL;
2072 jdir = fdp->fd_jdir;
2073 fdp->fd_jdir = NULL;
2074 FILEDESC_XUNLOCK(fdp);
2076 for (i = 0; i <= fdp->fd_lastfile; i++) {
2077 fde = &fdp->fd_ofiles[i];
2081 (void) closef(fp, td);
2085 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2086 free(fdp->fd_map, M_FILEDESC);
2087 if (fdp->fd_nfiles > NDFILE)
2088 free(fdp->fd_files, M_FILEDESC);
2090 fdp0 = (struct filedesc0 *)fdp;
2091 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2092 free(ft->ft_table, M_FILEDESC);
2105 * For setugid programs, we don't want to people to use that setugidness
2106 * to generate error messages which write to a file which otherwise would
2107 * otherwise be off-limits to the process. We check for filesystems where
2108 * the vnode can change out from under us after execve (like [lin]procfs).
2110 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2111 * sufficient. We also don't check for setugidness since we know we are.
2114 is_unsafe(struct file *fp)
2118 if (fp->f_type != DTYPE_VNODE)
2122 return ((vp->v_vflag & VV_PROCDEP) != 0);
2126 * Make this setguid thing safe, if at all possible.
2129 fdsetugidsafety(struct thread *td)
2131 struct filedesc *fdp;
2135 fdp = td->td_proc->p_fd;
2136 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2137 MPASS(fdp->fd_nfiles >= 3);
2138 for (i = 0; i <= 2; i++) {
2139 fp = fdp->fd_ofiles[i].fde_file;
2140 if (fp != NULL && is_unsafe(fp)) {
2141 FILEDESC_XLOCK(fdp);
2142 knote_fdclose(td, i);
2144 * NULL-out descriptor prior to close to avoid
2145 * a race while close blocks.
2148 FILEDESC_XUNLOCK(fdp);
2149 (void) closef(fp, td);
2155 * If a specific file object occupies a specific file descriptor, close the
2156 * file descriptor entry and drop a reference on the file object. This is a
2157 * convenience function to handle a subsequent error in a function that calls
2158 * falloc() that handles the race that another thread might have closed the
2159 * file descriptor out from under the thread creating the file object.
2162 fdclose(struct thread *td, struct file *fp, int idx)
2164 struct filedesc *fdp = td->td_proc->p_fd;
2166 FILEDESC_XLOCK(fdp);
2167 if (fdp->fd_ofiles[idx].fde_file == fp) {
2169 FILEDESC_XUNLOCK(fdp);
2172 FILEDESC_XUNLOCK(fdp);
2176 * Close any files on exec?
2179 fdcloseexec(struct thread *td)
2181 struct filedesc *fdp;
2182 struct filedescent *fde;
2186 fdp = td->td_proc->p_fd;
2187 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2188 for (i = 0; i <= fdp->fd_lastfile; i++) {
2189 fde = &fdp->fd_ofiles[i];
2191 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2192 (fde->fde_flags & UF_EXCLOSE))) {
2193 FILEDESC_XLOCK(fdp);
2195 (void) closefp(fdp, i, fp, td, 0);
2196 /* closefp() drops the FILEDESC lock. */
2202 * It is unsafe for set[ug]id processes to be started with file
2203 * descriptors 0..2 closed, as these descriptors are given implicit
2204 * significance in the Standard C library. fdcheckstd() will create a
2205 * descriptor referencing /dev/null for each of stdin, stdout, and
2206 * stderr that is not already open.
2209 fdcheckstd(struct thread *td)
2211 struct filedesc *fdp;
2213 int i, error, devnull;
2215 fdp = td->td_proc->p_fd;
2216 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2217 MPASS(fdp->fd_nfiles >= 3);
2219 for (i = 0; i <= 2; i++) {
2220 if (fdp->fd_ofiles[i].fde_file != NULL)
2223 save = td->td_retval[0];
2224 if (devnull != -1) {
2225 error = do_dup(td, DUP_FIXED, devnull, i);
2227 error = kern_openat(td, AT_FDCWD, "/dev/null",
2228 UIO_SYSSPACE, O_RDWR, 0);
2230 devnull = td->td_retval[0];
2231 KASSERT(devnull == i, ("we didn't get our fd"));
2234 td->td_retval[0] = save;
2242 * Internal form of close. Decrement reference count on file structure.
2243 * Note: td may be NULL when closing a file that was being passed in a
2246 * XXXRW: Giant is not required for the caller, but often will be held; this
2247 * makes it moderately likely the Giant will be recursed in the VFS case.
2250 closef(struct file *fp, struct thread *td)
2254 struct filedesc_to_leader *fdtol;
2255 struct filedesc *fdp;
2258 * POSIX record locking dictates that any close releases ALL
2259 * locks owned by this process. This is handled by setting
2260 * a flag in the unlock to free ONLY locks obeying POSIX
2261 * semantics, and not to free BSD-style file locks.
2262 * If the descriptor was in a message, POSIX-style locks
2263 * aren't passed with the descriptor, and the thread pointer
2264 * will be NULL. Callers should be careful only to pass a
2265 * NULL thread pointer when there really is no owning
2266 * context that might have locks, or the locks will be
2269 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2271 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2272 lf.l_whence = SEEK_SET;
2275 lf.l_type = F_UNLCK;
2276 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2277 F_UNLCK, &lf, F_POSIX);
2279 fdtol = td->td_proc->p_fdtol;
2280 if (fdtol != NULL) {
2282 * Handle special case where file descriptor table is
2283 * shared between multiple process leaders.
2285 fdp = td->td_proc->p_fd;
2286 FILEDESC_XLOCK(fdp);
2287 for (fdtol = fdtol->fdl_next;
2288 fdtol != td->td_proc->p_fdtol;
2289 fdtol = fdtol->fdl_next) {
2290 if ((fdtol->fdl_leader->p_flag &
2293 fdtol->fdl_holdcount++;
2294 FILEDESC_XUNLOCK(fdp);
2295 lf.l_whence = SEEK_SET;
2298 lf.l_type = F_UNLCK;
2300 (void) VOP_ADVLOCK(vp,
2301 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2303 FILEDESC_XLOCK(fdp);
2304 fdtol->fdl_holdcount--;
2305 if (fdtol->fdl_holdcount == 0 &&
2306 fdtol->fdl_wakeup != 0) {
2307 fdtol->fdl_wakeup = 0;
2311 FILEDESC_XUNLOCK(fdp);
2314 return (fdrop(fp, td));
2318 * Initialize the file pointer with the specified properties.
2320 * The ops are set with release semantics to be certain that the flags, type,
2321 * and data are visible when ops is. This is to prevent ops methods from being
2322 * called with bad data.
2325 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2330 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2334 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2335 struct file **fpp, seq_t *seqp)
2338 struct filedescent *fde;
2340 struct fdescenttbl *fdt;
2345 cap_rights_t haverights;
2349 fdt = fdp->fd_files;
2350 if ((u_int)fd >= fdt->fdt_nfiles)
2353 * Fetch the descriptor locklessly. We avoid fdrop() races by
2354 * never raising a refcount above 0. To accomplish this we have
2355 * to use a cmpset loop rather than an atomic_add. The descriptor
2356 * must be re-verified once we acquire a reference to be certain
2357 * that the identity is still correct and we did not lose a race
2358 * due to preemption.
2362 seq = seq_read(fd_seq(fdt, fd));
2363 fde = &fdt->fdt_ofiles[fd];
2364 haverights = *cap_rights_fde(fde);
2366 if (!seq_consistent(fd_seq(fdt, fd), seq)) {
2371 fp = fdt->fdt_ofiles[fd].fde_file;
2376 if (needrightsp != NULL) {
2377 error = cap_check(&haverights, needrightsp);
2383 count = fp->f_count;
2386 * Force a reload. Other thread could reallocate the
2387 * table before this fd was closed, so it possible that
2388 * there is a stale fp pointer in cached version.
2390 fdt = *(struct fdescenttbl * volatile *)&(fdp->fd_files);
2394 * Use an acquire barrier to force re-reading of fdt so it is
2395 * refreshed for verification.
2397 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) == 0)
2399 fdt = fdp->fd_files;
2401 if (seq_consistent_nomb(fd_seq(fdt, fd), seq))
2403 if (fp == fdt->fdt_ofiles[fd].fde_file)
2406 fdrop(fp, curthread);
2418 * Extract the file pointer associated with the specified descriptor for the
2419 * current user process.
2421 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2424 * File's rights will be checked against the capability rights mask.
2426 * If an error occured the non-zero error is returned and *fpp is set to
2427 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2428 * responsible for fdrop().
2431 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2432 cap_rights_t *needrightsp, seq_t *seqp)
2434 struct filedesc *fdp;
2436 cap_rights_t needrights;
2440 fdp = td->td_proc->p_fd;
2441 if (needrightsp != NULL)
2442 needrights = *needrightsp;
2444 cap_rights_init(&needrights);
2445 error = fget_unlocked(fdp, fd, &needrights, &fp, seqp);
2448 if (fp->f_ops == &badfileops) {
2454 * FREAD and FWRITE failure return EBADF as per POSIX.
2460 if ((fp->f_flag & flags) == 0)
2464 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2465 ((fp->f_flag & FWRITE) != 0))
2471 KASSERT(0, ("wrong flags"));
2484 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2487 return (_fget(td, fd, fpp, 0, rightsp, NULL));
2491 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2495 #ifndef CAPABILITIES
2496 error = _fget(td, fd, fpp, 0, rightsp, NULL);
2497 if (maxprotp != NULL)
2498 *maxprotp = VM_PROT_ALL;
2500 struct filedesc *fdp = td->td_proc->p_fd;
2503 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2505 error = _fget(td, fd, fpp, 0, rightsp, &seq);
2509 * If requested, convert capability rights to access flags.
2511 if (maxprotp != NULL)
2512 *maxprotp = cap_rights_to_vmprot(cap_rights(fdp, fd));
2513 if (!fd_modified(fdp, fd, seq))
2522 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2525 return (_fget(td, fd, fpp, FREAD, rightsp, NULL));
2529 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2532 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2536 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2539 struct filedesc *fdp = td->td_proc->p_fd;
2540 #ifndef CAPABILITIES
2541 return (fget_unlocked(fdp, fd, rightsp, fpp, NULL));
2546 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2548 error = fget_unlocked(fdp, fd, rightsp, fpp, &seq);
2551 error = cap_fcntl_check(fdp, fd, needfcntl);
2552 if (!fd_modified(fdp, fd, seq))
2565 * Like fget() but loads the underlying vnode, or returns an error if the
2566 * descriptor does not represent a vnode. Note that pipes use vnodes but
2567 * never have VM objects. The returned vnode will be vref()'d.
2569 * XXX: what about the unused flags ?
2572 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2579 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2582 if (fp->f_vnode == NULL) {
2594 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2597 return (_fgetvp(td, fd, 0, rightsp, vpp));
2601 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2602 struct filecaps *havecaps, struct vnode **vpp)
2604 struct filedesc *fdp;
2610 fdp = td->td_proc->p_fd;
2611 fp = fget_locked(fdp, fd);
2612 if (fp == NULL || fp->f_ops == &badfileops)
2616 if (needrightsp != NULL) {
2617 error = cap_check(cap_rights(fdp, fd), needrightsp);
2623 if (fp->f_vnode == NULL)
2628 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2634 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2637 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2641 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2644 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2649 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2653 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2658 * Like fget() but loads the underlying socket, or returns an error if the
2659 * descriptor does not represent a socket.
2661 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2664 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2665 * on their file descriptor reference to prevent the socket from being free'd
2669 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2678 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2680 if (fp->f_type != DTYPE_SOCKET) {
2685 *fflagp = fp->f_flag;
2696 * Drop the reference count on the socket and XXX release the SX lock in the
2697 * future. The last reference closes the socket.
2699 * Note: fputsock() is deprecated, see comment for fgetsock().
2702 fputsock(struct socket *so)
2707 CURVNET_SET(so->so_vnet);
2713 * Handle the last reference to a file being closed.
2716 _fdrop(struct file *fp, struct thread *td)
2720 if (fp->f_count != 0)
2721 panic("fdrop: count %d", fp->f_count);
2722 error = fo_close(fp, td);
2723 atomic_subtract_int(&openfiles, 1);
2725 free(fp->f_advice, M_FADVISE);
2726 uma_zfree(file_zone, fp);
2732 * Apply an advisory lock on a file descriptor.
2734 * Just attempt to get a record lock of the requested type on the entire file
2735 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2737 #ifndef _SYS_SYSPROTO_H_
2745 sys_flock(struct thread *td, struct flock_args *uap)
2750 cap_rights_t rights;
2753 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2756 if (fp->f_type != DTYPE_VNODE) {
2758 return (EOPNOTSUPP);
2762 lf.l_whence = SEEK_SET;
2765 if (uap->how & LOCK_UN) {
2766 lf.l_type = F_UNLCK;
2767 atomic_clear_int(&fp->f_flag, FHASLOCK);
2768 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2771 if (uap->how & LOCK_EX)
2772 lf.l_type = F_WRLCK;
2773 else if (uap->how & LOCK_SH)
2774 lf.l_type = F_RDLCK;
2779 atomic_set_int(&fp->f_flag, FHASLOCK);
2780 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2781 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2787 * Duplicate the specified descriptor to a free descriptor.
2790 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2791 int openerror, int *indxp)
2793 struct filedescent *newfde, *oldfde;
2797 KASSERT(openerror == ENODEV || openerror == ENXIO,
2798 ("unexpected error %d in %s", openerror, __func__));
2801 * If the to-be-dup'd fd number is greater than the allowed number
2802 * of file descriptors, or the fd to be dup'd has already been
2803 * closed, then reject.
2805 FILEDESC_XLOCK(fdp);
2806 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2807 FILEDESC_XUNLOCK(fdp);
2811 error = fdalloc(td, 0, &indx);
2813 FILEDESC_XUNLOCK(fdp);
2818 * There are two cases of interest here.
2820 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2822 * For ENXIO steal away the file structure from (dfd) and store it in
2823 * (indx). (dfd) is effectively closed by this operation.
2825 switch (openerror) {
2828 * Check that the mode the file is being opened for is a
2829 * subset of the mode of the existing descriptor.
2831 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2832 fdunused(fdp, indx);
2833 FILEDESC_XUNLOCK(fdp);
2837 newfde = &fdp->fd_ofiles[indx];
2838 oldfde = &fdp->fd_ofiles[dfd];
2840 seq_write_begin(&newfde->fde_seq);
2842 memcpy(newfde, oldfde, fde_change_size);
2843 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
2845 seq_write_end(&newfde->fde_seq);
2850 * Steal away the file pointer from dfd and stuff it into indx.
2852 newfde = &fdp->fd_ofiles[indx];
2853 oldfde = &fdp->fd_ofiles[dfd];
2855 seq_write_begin(&newfde->fde_seq);
2857 memcpy(newfde, oldfde, fde_change_size);
2858 bzero(oldfde, fde_change_size);
2861 seq_write_end(&newfde->fde_seq);
2865 FILEDESC_XUNLOCK(fdp);
2871 * Scan all active processes and prisons to see if any of them have a current
2872 * or root directory of `olddp'. If so, replace them with the new mount point.
2875 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2877 struct filedesc *fdp;
2882 if (vrefcnt(olddp) == 1)
2885 sx_slock(&allproc_lock);
2886 FOREACH_PROC_IN_SYSTEM(p) {
2890 FILEDESC_XLOCK(fdp);
2891 if (fdp->fd_cdir == olddp) {
2893 fdp->fd_cdir = newdp;
2896 if (fdp->fd_rdir == olddp) {
2898 fdp->fd_rdir = newdp;
2901 if (fdp->fd_jdir == olddp) {
2903 fdp->fd_jdir = newdp;
2906 FILEDESC_XUNLOCK(fdp);
2909 sx_sunlock(&allproc_lock);
2910 if (rootvnode == olddp) {
2915 mtx_lock(&prison0.pr_mtx);
2916 if (prison0.pr_root == olddp) {
2918 prison0.pr_root = newdp;
2921 mtx_unlock(&prison0.pr_mtx);
2922 sx_slock(&allprison_lock);
2923 TAILQ_FOREACH(pr, &allprison, pr_list) {
2924 mtx_lock(&pr->pr_mtx);
2925 if (pr->pr_root == olddp) {
2927 pr->pr_root = newdp;
2930 mtx_unlock(&pr->pr_mtx);
2932 sx_sunlock(&allprison_lock);
2937 struct filedesc_to_leader *
2938 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2940 struct filedesc_to_leader *fdtol;
2942 fdtol = malloc(sizeof(struct filedesc_to_leader),
2943 M_FILEDESC_TO_LEADER,
2945 fdtol->fdl_refcount = 1;
2946 fdtol->fdl_holdcount = 0;
2947 fdtol->fdl_wakeup = 0;
2948 fdtol->fdl_leader = leader;
2950 FILEDESC_XLOCK(fdp);
2951 fdtol->fdl_next = old->fdl_next;
2952 fdtol->fdl_prev = old;
2953 old->fdl_next = fdtol;
2954 fdtol->fdl_next->fdl_prev = fdtol;
2955 FILEDESC_XUNLOCK(fdp);
2957 fdtol->fdl_next = fdtol;
2958 fdtol->fdl_prev = fdtol;
2964 * Get file structures globally.
2967 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2970 struct filedesc *fdp;
2975 error = sysctl_wire_old_buffer(req, 0);
2978 if (req->oldptr == NULL) {
2980 sx_slock(&allproc_lock);
2981 FOREACH_PROC_IN_SYSTEM(p) {
2982 if (p->p_state == PRS_NEW)
2987 /* overestimates sparse tables. */
2988 if (fdp->fd_lastfile > 0)
2989 n += fdp->fd_lastfile;
2992 sx_sunlock(&allproc_lock);
2993 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2996 bzero(&xf, sizeof(xf));
2997 xf.xf_size = sizeof(xf);
2998 sx_slock(&allproc_lock);
2999 FOREACH_PROC_IN_SYSTEM(p) {
3001 if (p->p_state == PRS_NEW) {
3005 if (p_cansee(req->td, p) != 0) {
3009 xf.xf_pid = p->p_pid;
3010 xf.xf_uid = p->p_ucred->cr_uid;
3015 FILEDESC_SLOCK(fdp);
3016 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3017 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3021 xf.xf_data = fp->f_data;
3022 xf.xf_vnode = fp->f_vnode;
3023 xf.xf_type = fp->f_type;
3024 xf.xf_count = fp->f_count;
3026 xf.xf_offset = foffset_get(fp);
3027 xf.xf_flag = fp->f_flag;
3028 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3032 FILEDESC_SUNLOCK(fdp);
3037 sx_sunlock(&allproc_lock);
3041 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3042 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3044 #ifdef KINFO_FILE_SIZE
3045 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3049 xlate_fflags(int fflags)
3051 static const struct {
3054 } fflags_table[] = {
3055 { FAPPEND, KF_FLAG_APPEND },
3056 { FASYNC, KF_FLAG_ASYNC },
3057 { FFSYNC, KF_FLAG_FSYNC },
3058 { FHASLOCK, KF_FLAG_HASLOCK },
3059 { FNONBLOCK, KF_FLAG_NONBLOCK },
3060 { FREAD, KF_FLAG_READ },
3061 { FWRITE, KF_FLAG_WRITE },
3062 { O_CREAT, KF_FLAG_CREAT },
3063 { O_DIRECT, KF_FLAG_DIRECT },
3064 { O_EXCL, KF_FLAG_EXCL },
3065 { O_EXEC, KF_FLAG_EXEC },
3066 { O_EXLOCK, KF_FLAG_EXLOCK },
3067 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3068 { O_SHLOCK, KF_FLAG_SHLOCK },
3069 { O_TRUNC, KF_FLAG_TRUNC }
3075 for (i = 0; i < nitems(fflags_table); i++)
3076 if (fflags & fflags_table[i].fflag)
3077 kflags |= fflags_table[i].kf_fflag;
3081 /* Trim unused data from kf_path by truncating the structure size. */
3083 pack_kinfo(struct kinfo_file *kif)
3086 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3087 strlen(kif->kf_path) + 1;
3088 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3092 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3093 struct kinfo_file *kif, struct filedesc *fdp)
3097 bzero(kif, sizeof(*kif));
3099 /* Set a default type to allow for empty fill_kinfo() methods. */
3100 kif->kf_type = KF_TYPE_UNKNOWN;
3101 kif->kf_flags = xlate_fflags(fp->f_flag);
3102 if (rightsp != NULL)
3103 kif->kf_cap_rights = *rightsp;
3105 cap_rights_init(&kif->kf_cap_rights);
3107 kif->kf_ref_count = fp->f_count;
3108 kif->kf_offset = foffset_get(fp);
3111 * This may drop the filedesc lock, so the 'fp' cannot be
3112 * accessed after this call.
3114 error = fo_fill_kinfo(fp, kif, fdp);
3116 kif->kf_status |= KF_ATTR_VALID;
3121 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3122 struct kinfo_file *kif)
3126 bzero(kif, sizeof(*kif));
3128 kif->kf_type = KF_TYPE_VNODE;
3129 error = vn_fill_kinfo_vnode(vp, kif);
3131 kif->kf_status |= KF_ATTR_VALID;
3132 kif->kf_flags = xlate_fflags(fflags);
3133 cap_rights_init(&kif->kf_cap_rights);
3135 kif->kf_ref_count = -1;
3136 kif->kf_offset = -1;
3141 struct export_fd_buf {
3142 struct filedesc *fdp;
3145 struct kinfo_file kif;
3149 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3151 struct kinfo_file *kif;
3154 if (efbuf->remainder != -1) {
3155 if (efbuf->remainder < kif->kf_structsize) {
3156 /* Terminate export. */
3157 efbuf->remainder = 0;
3160 efbuf->remainder -= kif->kf_structsize;
3162 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3166 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3167 struct export_fd_buf *efbuf)
3171 if (efbuf->remainder == 0)
3173 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp);
3174 FILEDESC_SUNLOCK(efbuf->fdp);
3175 error = export_kinfo_to_sb(efbuf);
3176 FILEDESC_SLOCK(efbuf->fdp);
3181 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3182 struct export_fd_buf *efbuf)
3186 if (efbuf->remainder == 0)
3188 if (efbuf->fdp != NULL)
3189 FILEDESC_SUNLOCK(efbuf->fdp);
3190 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif);
3191 error = export_kinfo_to_sb(efbuf);
3192 if (efbuf->fdp != NULL)
3193 FILEDESC_SLOCK(efbuf->fdp);
3198 * Store a process file descriptor information to sbuf.
3200 * Takes a locked proc as argument, and returns with the proc unlocked.
3203 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3206 struct filedesc *fdp;
3207 struct export_fd_buf *efbuf;
3208 struct vnode *cttyvp, *textvp, *tracevp;
3210 cap_rights_t rights;
3212 PROC_LOCK_ASSERT(p, MA_OWNED);
3215 tracevp = p->p_tracevp;
3216 if (tracevp != NULL)
3219 textvp = p->p_textvp;
3222 /* Controlling tty. */
3224 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3225 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3231 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3234 efbuf->remainder = maxlen;
3235 if (tracevp != NULL)
3236 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3239 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3241 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3247 FILEDESC_SLOCK(fdp);
3248 /* working directory */
3249 if (fdp->fd_cdir != NULL) {
3251 export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3253 /* root directory */
3254 if (fdp->fd_rdir != NULL) {
3256 export_vnode_to_sb(fdp->fd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3258 /* jail directory */
3259 if (fdp->fd_jdir != NULL) {
3261 export_vnode_to_sb(fdp->fd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3263 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3264 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3267 rights = *cap_rights(fdp, i);
3268 #else /* !CAPABILITIES */
3269 cap_rights_init(&rights);
3272 * Create sysctl entry. It is OK to drop the filedesc
3273 * lock inside of export_file_to_sb() as we will
3274 * re-validate and re-evaluate its properties when the
3277 error = export_file_to_sb(fp, i, &rights, efbuf);
3278 if (error != 0 || efbuf->remainder == 0)
3281 FILEDESC_SUNLOCK(fdp);
3284 free(efbuf, M_TEMP);
3288 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3291 * Get per-process file descriptors for use by procstat(1), et al.
3294 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3299 int error, error2, *name;
3303 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3304 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3305 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3310 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3311 error = kern_proc_filedesc_out(p, &sb, maxlen);
3312 error2 = sbuf_finish(&sb);
3314 return (error != 0 ? error : error2);
3317 #ifdef KINFO_OFILE_SIZE
3318 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3321 #ifdef COMPAT_FREEBSD7
3323 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3326 okif->kf_structsize = sizeof(*okif);
3327 okif->kf_type = kif->kf_type;
3328 okif->kf_fd = kif->kf_fd;
3329 okif->kf_ref_count = kif->kf_ref_count;
3330 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3331 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3332 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3333 okif->kf_offset = kif->kf_offset;
3334 okif->kf_vnode_type = kif->kf_vnode_type;
3335 okif->kf_sock_domain = kif->kf_sock_domain;
3336 okif->kf_sock_type = kif->kf_sock_type;
3337 okif->kf_sock_protocol = kif->kf_sock_protocol;
3338 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3339 okif->kf_sa_local = kif->kf_sa_local;
3340 okif->kf_sa_peer = kif->kf_sa_peer;
3344 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3345 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3350 FILEDESC_SUNLOCK(fdp);
3351 export_vnode_to_kinfo(vp, type, 0, kif);
3352 kinfo_to_okinfo(kif, okif);
3353 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3354 FILEDESC_SLOCK(fdp);
3359 * Get per-process file descriptors for use by procstat(1), et al.
3362 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3364 struct kinfo_ofile *okif;
3365 struct kinfo_file *kif;
3366 struct filedesc *fdp;
3367 int error, i, *name;
3372 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3379 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3380 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
3381 FILEDESC_SLOCK(fdp);
3382 if (fdp->fd_cdir != NULL)
3383 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3385 if (fdp->fd_rdir != NULL)
3386 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3388 if (fdp->fd_jdir != NULL)
3389 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3391 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3392 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3394 export_file_to_kinfo(fp, i, NULL, kif, fdp);
3395 FILEDESC_SUNLOCK(fdp);
3396 kinfo_to_okinfo(kif, okif);
3397 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3398 FILEDESC_SLOCK(fdp);
3402 FILEDESC_SUNLOCK(fdp);
3409 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3410 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3411 "Process ofiledesc entries");
3412 #endif /* COMPAT_FREEBSD7 */
3415 vntype_to_kinfo(int vtype)
3420 } vtypes_table[] = {
3421 { VBAD, KF_VTYPE_VBAD },
3422 { VBLK, KF_VTYPE_VBLK },
3423 { VCHR, KF_VTYPE_VCHR },
3424 { VDIR, KF_VTYPE_VDIR },
3425 { VFIFO, KF_VTYPE_VFIFO },
3426 { VLNK, KF_VTYPE_VLNK },
3427 { VNON, KF_VTYPE_VNON },
3428 { VREG, KF_VTYPE_VREG },
3429 { VSOCK, KF_VTYPE_VSOCK }
3434 * Perform vtype translation.
3436 for (i = 0; i < nitems(vtypes_table); i++)
3437 if (vtypes_table[i].vtype == vtype)
3438 return (vtypes_table[i].kf_vtype);
3440 return (KF_VTYPE_UNKNOWN);
3443 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3444 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3445 "Process filedesc entries");
3448 * Store a process current working directory information to sbuf.
3450 * Takes a locked proc as argument, and returns with the proc unlocked.
3453 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3455 struct filedesc *fdp;
3456 struct export_fd_buf *efbuf;
3459 PROC_LOCK_ASSERT(p, MA_OWNED);
3466 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3469 efbuf->remainder = maxlen;
3471 FILEDESC_SLOCK(fdp);
3472 if (fdp->fd_cdir == NULL)
3476 error = export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD,
3479 FILEDESC_SUNLOCK(fdp);
3481 free(efbuf, M_TEMP);
3486 * Get per-process current working directory.
3489 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
3494 int error, error2, *name;
3498 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
3499 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3500 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3505 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3506 error = kern_proc_cwd_out(p, &sb, maxlen);
3507 error2 = sbuf_finish(&sb);
3509 return (error != 0 ? error : error2);
3512 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
3513 sysctl_kern_proc_cwd, "Process current working directory");
3517 * For the purposes of debugging, generate a human-readable string for the
3521 file_type_to_name(short type)
3551 * For the purposes of debugging, identify a process (if any, perhaps one of
3552 * many) that references the passed file in its file descriptor array. Return
3555 static struct proc *
3556 file_to_first_proc(struct file *fp)
3558 struct filedesc *fdp;
3562 FOREACH_PROC_IN_SYSTEM(p) {
3563 if (p->p_state == PRS_NEW)
3568 for (n = 0; n <= fdp->fd_lastfile; n++) {
3569 if (fp == fdp->fd_ofiles[n].fde_file)
3577 db_print_file(struct file *fp, int header)
3582 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3583 "File", "Type", "Data", "Flag", "GCFl", "Count",
3584 "MCount", "Vnode", "FPID", "FCmd");
3585 p = file_to_first_proc(fp);
3586 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3587 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3588 0, fp->f_count, 0, fp->f_vnode,
3589 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3592 DB_SHOW_COMMAND(file, db_show_file)
3597 db_printf("usage: show file <addr>\n");
3600 fp = (struct file *)addr;
3601 db_print_file(fp, 1);
3604 DB_SHOW_COMMAND(files, db_show_files)
3606 struct filedesc *fdp;
3613 FOREACH_PROC_IN_SYSTEM(p) {
3614 if (p->p_state == PRS_NEW)
3616 if ((fdp = p->p_fd) == NULL)
3618 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3619 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3621 db_print_file(fp, header);
3628 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3629 &maxfilesperproc, 0, "Maximum files allowed open per process");
3631 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3632 &maxfiles, 0, "Maximum number of files");
3634 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3635 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3639 filelistinit(void *dummy)
3642 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3643 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3644 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
3645 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
3646 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3647 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3649 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3651 /*-------------------------------------------------------------------*/
3654 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3655 int flags, struct thread *td)
3662 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3670 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3678 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3686 badfo_kqfilter(struct file *fp, struct knote *kn)
3693 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3701 badfo_close(struct file *fp, struct thread *td)
3708 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3716 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3724 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3725 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3726 int kflags, struct thread *td)
3733 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
3739 struct fileops badfileops = {
3740 .fo_read = badfo_readwrite,
3741 .fo_write = badfo_readwrite,
3742 .fo_truncate = badfo_truncate,
3743 .fo_ioctl = badfo_ioctl,
3744 .fo_poll = badfo_poll,
3745 .fo_kqfilter = badfo_kqfilter,
3746 .fo_stat = badfo_stat,
3747 .fo_close = badfo_close,
3748 .fo_chmod = badfo_chmod,
3749 .fo_chown = badfo_chown,
3750 .fo_sendfile = badfo_sendfile,
3751 .fo_fill_kinfo = badfo_fill_kinfo,
3755 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
3756 int flags, struct thread *td)
3759 return (EOPNOTSUPP);
3763 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3771 invfo_ioctl(struct file *fp, u_long com, void *data,
3772 struct ucred *active_cred, struct thread *td)
3779 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
3783 return (poll_no_poll(events));
3787 invfo_kqfilter(struct file *fp, struct knote *kn)
3794 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3802 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3810 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3811 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3812 int kflags, struct thread *td)
3818 /*-------------------------------------------------------------------*/
3821 * File Descriptor pseudo-device driver (/dev/fd/).
3823 * Opening minor device N dup()s the file (if any) connected to file
3824 * descriptor N belonging to the calling process. Note that this driver
3825 * consists of only the ``open()'' routine, because all subsequent
3826 * references to this file will be direct to the other driver.
3828 * XXX: we could give this one a cloning event handler if necessary.
3833 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3837 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3838 * the file descriptor being sought for duplication. The error
3839 * return ensures that the vnode for this device will be released
3840 * by vn_open. Open will detect this special error and take the
3841 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3842 * will simply report the error.
3844 td->td_dupfd = dev2unit(dev);
3848 static struct cdevsw fildesc_cdevsw = {
3849 .d_version = D_VERSION,
3855 fildesc_drvinit(void *unused)
3859 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3860 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3861 make_dev_alias(dev, "stdin");
3862 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3863 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3864 make_dev_alias(dev, "stdout");
3865 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3866 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3867 make_dev_alias(dev, "stderr");
3870 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);