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 * 3. 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>
74 #include <sys/syscallsubr.h>
75 #include <sys/sysctl.h>
76 #include <sys/sysproto.h>
77 #include <sys/unistd.h>
79 #include <sys/vnode.h>
81 #include <sys/ktrace.h>
86 #include <security/audit/audit.h>
93 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
94 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
95 "file desc to leader structures");
96 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
97 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
99 MALLOC_DECLARE(M_FADVISE);
101 static uma_zone_t file_zone;
102 static uma_zone_t filedesc0_zone;
104 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
105 struct thread *td, int holdleaders);
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 thread *td);
117 * - An array of open file descriptors (fd_ofiles)
118 * - An array of file flags (fd_ofileflags)
119 * - A bitmap recording which descriptors are in use (fd_map)
121 * A process starts out with NDFILE descriptors. The value of NDFILE has
122 * been selected based the historical limit of 20 open files, and an
123 * assumption that the majority of processes, especially short-lived
124 * processes like shells, will never need more.
126 * If this initial allocation is exhausted, a larger descriptor table and
127 * map are allocated dynamically, and the pointers in the process's struct
128 * filedesc are updated to point to those. This is repeated every time
129 * the process runs out of file descriptors (provided it hasn't hit its
132 * Since threads may hold references to individual descriptor table
133 * entries, the tables are never freed. Instead, they are placed on a
134 * linked list and freed only when the struct filedesc is released.
137 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
138 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
139 #define NDSLOT(x) ((x) / NDENTRIES)
140 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
141 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
144 * SLIST entry used to keep track of ofiles which must be reclaimed when
148 struct fdescenttbl *ft_table;
149 SLIST_ENTRY(freetable) ft_next;
153 * Initial allocation: a filedesc structure + the head of SLIST used to
154 * keep track of old ofiles + enough space for NDFILE descriptors.
157 struct fdescenttbl0 {
159 struct filedescent fdt_ofiles[NDFILE];
163 struct filedesc fd_fd;
164 SLIST_HEAD(, freetable) fd_free;
165 struct fdescenttbl0 fd_dfiles;
166 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
170 * Descriptor management.
172 volatile int openfiles; /* actual number of open files */
173 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
174 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
177 * If low >= size, just return low. Otherwise find the first zero bit in the
178 * given bitmap, starting at low and not exceeding size - 1. Return size if
182 fd_first_free(struct filedesc *fdp, int low, int size)
184 NDSLOTTYPE *map = fdp->fd_map;
192 if (low % NDENTRIES) {
193 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
194 if ((mask &= ~map[off]) != 0UL)
195 return (off * NDENTRIES + ffsl(mask) - 1);
198 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
199 if (map[off] != ~0UL)
200 return (off * NDENTRIES + ffsl(~map[off]) - 1);
205 * Find the highest non-zero bit in the given bitmap, starting at 0 and
206 * not exceeding size - 1. Return -1 if not found.
209 fd_last_used(struct filedesc *fdp, int size)
211 NDSLOTTYPE *map = fdp->fd_map;
216 if (size % NDENTRIES) {
217 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
218 if ((mask &= map[off]) != 0)
219 return (off * NDENTRIES + flsl(mask) - 1);
222 for (minoff = NDSLOT(0); off >= minoff; --off)
224 return (off * NDENTRIES + flsl(map[off]) - 1);
229 fdisused(struct filedesc *fdp, int fd)
232 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
233 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
235 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
239 * Mark a file descriptor as used.
242 fdused_init(struct filedesc *fdp, int fd)
245 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
247 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
251 fdused(struct filedesc *fdp, int fd)
254 FILEDESC_XLOCK_ASSERT(fdp);
256 fdused_init(fdp, fd);
257 if (fd > fdp->fd_lastfile)
258 fdp->fd_lastfile = fd;
259 if (fd == fdp->fd_freefile)
260 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
264 * Mark a file descriptor as unused.
267 fdunused(struct filedesc *fdp, int fd)
270 FILEDESC_XLOCK_ASSERT(fdp);
272 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
273 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
274 ("fd=%d is still in use", fd));
276 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
277 if (fd < fdp->fd_freefile)
278 fdp->fd_freefile = fd;
279 if (fd == fdp->fd_lastfile)
280 fdp->fd_lastfile = fd_last_used(fdp, fd);
284 * Free a file descriptor.
286 * Avoid some work if fdp is about to be destroyed.
289 fdefree_last(struct filedescent *fde)
292 filecaps_free(&fde->fde_caps);
296 fdfree(struct filedesc *fdp, int fd)
298 struct filedescent *fde;
300 fde = &fdp->fd_ofiles[fd];
302 seq_write_begin(&fde->fde_seq);
305 fde->fde_file = NULL;
308 seq_write_end(&fde->fde_seq);
313 pwd_ensure_dirs(void)
315 struct filedesc *fdp;
319 if (fdp->fd_cdir == NULL) {
320 fdp->fd_cdir = rootvnode;
323 if (fdp->fd_rdir == NULL) {
324 fdp->fd_rdir = rootvnode;
327 FILEDESC_XUNLOCK(fdp);
331 * System calls on descriptors.
333 #ifndef _SYS_SYSPROTO_H_
334 struct getdtablesize_args {
340 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
347 min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc);
349 PROC_LOCK(td->td_proc);
350 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
351 PROC_UNLOCK(td->td_proc);
352 if (lim < td->td_retval[0])
353 td->td_retval[0] = lim;
359 * Duplicate a file descriptor to a particular value.
361 * Note: keep in mind that a potential race condition exists when closing
362 * descriptors from a shared descriptor table (via rfork).
364 #ifndef _SYS_SYSPROTO_H_
372 sys_dup2(struct thread *td, struct dup2_args *uap)
375 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
379 * Duplicate a file descriptor.
381 #ifndef _SYS_SYSPROTO_H_
388 sys_dup(struct thread *td, struct dup_args *uap)
391 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
395 * The file control system call.
397 #ifndef _SYS_SYSPROTO_H_
406 sys_fcntl(struct thread *td, struct fcntl_args *uap)
409 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
413 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
427 * Convert old flock structure to new.
429 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
430 fl.l_start = ofl.l_start;
431 fl.l_len = ofl.l_len;
432 fl.l_pid = ofl.l_pid;
433 fl.l_type = ofl.l_type;
434 fl.l_whence = ofl.l_whence;
448 arg1 = (intptr_t)&fl;
454 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
455 arg1 = (intptr_t)&fl;
463 error = kern_fcntl(td, fd, newcmd, arg1);
466 if (cmd == F_OGETLK) {
467 ofl.l_start = fl.l_start;
468 ofl.l_len = fl.l_len;
469 ofl.l_pid = fl.l_pid;
470 ofl.l_type = fl.l_type;
471 ofl.l_whence = fl.l_whence;
472 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
473 } else if (cmd == F_GETLK) {
474 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
480 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
482 struct filedesc *fdp;
484 struct file *fp, *fp2;
485 struct filedescent *fde;
503 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
506 case F_DUPFD_CLOEXEC:
508 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
513 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
516 case F_DUP2FD_CLOEXEC:
518 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
524 fde = fdeget_locked(fdp, fd);
527 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
530 FILEDESC_SUNLOCK(fdp);
536 fde = fdeget_locked(fdp, fd);
538 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
539 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
542 FILEDESC_XUNLOCK(fdp);
546 error = fget_fcntl(td, fd,
547 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp);
550 td->td_retval[0] = OFLAGS(fp->f_flag);
555 error = fget_fcntl(td, fd,
556 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp);
560 tmp = flg = fp->f_flag;
562 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
563 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
564 tmp = fp->f_flag & FNONBLOCK;
565 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
570 tmp = fp->f_flag & FASYNC;
571 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
576 atomic_clear_int(&fp->f_flag, FNONBLOCK);
578 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
583 error = fget_fcntl(td, fd,
584 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp);
587 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
589 td->td_retval[0] = tmp;
594 error = fget_fcntl(td, fd,
595 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp);
599 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
604 error = priv_check(td, PRIV_NFS_LOCKD);
612 /* FALLTHROUGH F_SETLK */
616 cap_rights_init(&rights, CAP_FLOCK);
617 error = fget_unlocked(fdp, fd, &rights, &fp, NULL);
620 if (fp->f_type != DTYPE_VNODE) {
626 flp = (struct flock *)arg;
627 if (flp->l_whence == SEEK_CUR) {
628 foffset = foffset_get(fp);
631 foffset > OFF_MAX - flp->l_start)) {
636 flp->l_start += foffset;
640 switch (flp->l_type) {
642 if ((fp->f_flag & FREAD) == 0) {
646 PROC_LOCK(p->p_leader);
647 p->p_leader->p_flag |= P_ADVLOCK;
648 PROC_UNLOCK(p->p_leader);
649 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
653 if ((fp->f_flag & FWRITE) == 0) {
657 PROC_LOCK(p->p_leader);
658 p->p_leader->p_flag |= P_ADVLOCK;
659 PROC_UNLOCK(p->p_leader);
660 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
664 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
669 * Temporary api for testing remote lock
672 if (flg != F_REMOTE) {
676 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
677 F_UNLCKSYS, flp, flg);
683 if (error != 0 || flp->l_type == F_UNLCK ||
684 flp->l_type == F_UNLCKSYS) {
690 * Check for a race with close.
692 * The vnode is now advisory locked (or unlocked, but this case
693 * is not really important) as the caller requested.
694 * We had to drop the filedesc lock, so we need to recheck if
695 * the descriptor is still valid, because if it was closed
696 * in the meantime we need to remove advisory lock from the
697 * vnode - close on any descriptor leading to an advisory
698 * locked vnode, removes that lock.
699 * We will return 0 on purpose in that case, as the result of
700 * successful advisory lock might have been externally visible
701 * already. This is fine - effectively we pretend to the caller
702 * that the closing thread was a bit slower and that the
703 * advisory lock succeeded before the close.
705 error = fget_unlocked(fdp, fd, &rights, &fp2, NULL);
711 flp->l_whence = SEEK_SET;
714 flp->l_type = F_UNLCK;
715 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
716 F_UNLCK, flp, F_POSIX);
723 error = fget_unlocked(fdp, fd,
724 cap_rights_init(&rights, CAP_FLOCK), &fp, NULL);
727 if (fp->f_type != DTYPE_VNODE) {
732 flp = (struct flock *)arg;
733 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
734 flp->l_type != F_UNLCK) {
739 if (flp->l_whence == SEEK_CUR) {
740 foffset = foffset_get(fp);
741 if ((flp->l_start > 0 &&
742 foffset > OFF_MAX - flp->l_start) ||
744 foffset < OFF_MIN - flp->l_start)) {
749 flp->l_start += foffset;
752 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
758 arg = arg ? 128 * 1024: 0;
761 error = fget_unlocked(fdp, fd,
762 cap_rights_init(&rights), &fp, NULL);
765 if (fp->f_type != DTYPE_VNODE) {
772 * Exclusive lock synchronizes against f_seqcount reads and
773 * writes in sequential_heuristic().
775 error = vn_lock(vp, LK_EXCLUSIVE);
781 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
782 fp->f_seqcount = (arg + bsize - 1) / bsize;
783 atomic_set_int(&fp->f_flag, FRDAHEAD);
785 atomic_clear_int(&fp->f_flag, FRDAHEAD);
799 getmaxfd(struct thread *td)
802 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
806 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
809 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
811 struct filedesc *fdp;
812 struct filedescent *oldfde, *newfde;
820 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
821 MPASS(mode < FDDUP_LASTMODE);
824 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
827 * Verify we have a valid descriptor to dup from and possibly to
828 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
829 * return EINVAL when the new descriptor is out of bounds.
834 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
835 maxfd = getmaxfd(td);
837 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
841 if (fget_locked(fdp, old) == NULL)
843 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
844 td->td_retval[0] = new;
845 if (flags & FDDUP_FLAG_CLOEXEC)
846 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
852 * If the caller specified a file descriptor, make sure the file
853 * table is large enough to hold it, and grab it. Otherwise, just
854 * allocate a new descriptor the usual way.
859 if ((error = fdalloc(td, new, &new)) != 0)
862 case FDDUP_MUSTREPLACE:
863 /* Target file descriptor must exist. */
864 if (fget_locked(fdp, new) == NULL)
868 if (new >= fdp->fd_nfiles) {
870 * The resource limits are here instead of e.g.
871 * fdalloc(), because the file descriptor table may be
872 * shared between processes, so we can't really use
873 * racct_add()/racct_sub(). Instead of counting the
874 * number of actually allocated descriptors, just put
875 * the limit on the size of the file descriptor table.
880 error = racct_set(p, RACCT_NOFILE, new + 1);
888 fdgrowtable_exp(fdp, new + 1);
890 if (!fdisused(fdp, new))
894 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
897 KASSERT(old != new, ("new fd is same as old"));
899 oldfde = &fdp->fd_ofiles[old];
900 fhold(oldfde->fde_file);
901 newfde = &fdp->fd_ofiles[new];
902 delfp = newfde->fde_file;
905 * Duplicate the source descriptor.
908 seq_write_begin(&newfde->fde_seq);
910 filecaps_free(&newfde->fde_caps);
911 memcpy(newfde, oldfde, fde_change_size);
912 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps, true);
913 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
914 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
916 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
918 seq_write_end(&newfde->fde_seq);
920 td->td_retval[0] = new;
925 (void) closefp(fdp, new, delfp, td, 1);
926 FILEDESC_UNLOCK_ASSERT(fdp);
929 FILEDESC_XUNLOCK(fdp);
936 * If sigio is on the list associated with a process or process group,
937 * disable signalling from the device, remove sigio from the list and
941 funsetown(struct sigio **sigiop)
953 *(sigio->sio_myref) = NULL;
954 if ((sigio)->sio_pgid < 0) {
955 struct pgrp *pg = (sigio)->sio_pgrp;
957 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
961 struct proc *p = (sigio)->sio_proc;
963 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
968 crfree(sigio->sio_ucred);
969 free(sigio, M_SIGIO);
973 * Free a list of sigio structures.
974 * We only need to lock the SIGIO_LOCK because we have made ourselves
975 * inaccessible to callers of fsetown and therefore do not need to lock
976 * the proc or pgrp struct for the list manipulation.
979 funsetownlst(struct sigiolst *sigiolst)
985 sigio = SLIST_FIRST(sigiolst);
992 * Every entry of the list should belong
993 * to a single proc or pgrp.
995 if (sigio->sio_pgid < 0) {
996 pg = sigio->sio_pgrp;
997 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
998 } else /* if (sigio->sio_pgid > 0) */ {
1000 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1004 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1005 *(sigio->sio_myref) = NULL;
1007 KASSERT(sigio->sio_pgid < 0,
1008 ("Proc sigio in pgrp sigio list"));
1009 KASSERT(sigio->sio_pgrp == pg,
1010 ("Bogus pgrp in sigio list"));
1012 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1015 } else /* if (p != NULL) */ {
1016 KASSERT(sigio->sio_pgid > 0,
1017 ("Pgrp sigio in proc sigio list"));
1018 KASSERT(sigio->sio_proc == p,
1019 ("Bogus proc in sigio list"));
1021 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1026 crfree(sigio->sio_ucred);
1027 free(sigio, M_SIGIO);
1034 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1036 * After permission checking, add a sigio structure to the sigio list for
1037 * the process or process group.
1040 fsetown(pid_t pgid, struct sigio **sigiop)
1044 struct sigio *sigio;
1054 /* Allocate and fill in the new sigio out of locks. */
1055 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1056 sigio->sio_pgid = pgid;
1057 sigio->sio_ucred = crhold(curthread->td_ucred);
1058 sigio->sio_myref = sigiop;
1060 sx_slock(&proctree_lock);
1069 * Policy - Don't allow a process to FSETOWN a process
1070 * in another session.
1072 * Remove this test to allow maximum flexibility or
1073 * restrict FSETOWN to the current process or process
1074 * group for maximum safety.
1077 if (proc->p_session != curthread->td_proc->p_session) {
1083 } else /* if (pgid < 0) */ {
1084 pgrp = pgfind(-pgid);
1092 * Policy - Don't allow a process to FSETOWN a process
1093 * in another session.
1095 * Remove this test to allow maximum flexibility or
1096 * restrict FSETOWN to the current process or process
1097 * group for maximum safety.
1099 if (pgrp->pg_session != curthread->td_proc->p_session) {
1110 * Since funsetownlst() is called without the proctree
1111 * locked, we need to check for P_WEXIT.
1112 * XXX: is ESRCH correct?
1114 if ((proc->p_flag & P_WEXIT) != 0) {
1119 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1120 sigio->sio_proc = proc;
1124 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1125 sigio->sio_pgrp = pgrp;
1128 sx_sunlock(&proctree_lock);
1135 sx_sunlock(&proctree_lock);
1136 crfree(sigio->sio_ucred);
1137 free(sigio, M_SIGIO);
1142 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1146 struct sigio **sigiop;
1151 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1157 * Function drops the filedesc lock on return.
1160 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1165 FILEDESC_XLOCK_ASSERT(fdp);
1168 if (td->td_proc->p_fdtol != NULL) {
1170 * Ask fdfree() to sleep to ensure that all relevant
1171 * process leaders can be traversed in closef().
1173 fdp->fd_holdleaderscount++;
1180 * We now hold the fp reference that used to be owned by the
1181 * descriptor array. We have to unlock the FILEDESC *AFTER*
1182 * knote_fdclose to prevent a race of the fd getting opened, a knote
1183 * added, and deleteing a knote for the new fd.
1185 knote_fdclose(td, fd);
1188 * We need to notify mqueue if the object is of type mqueue.
1190 if (fp->f_type == DTYPE_MQUEUE)
1191 mq_fdclose(td, fd, fp);
1192 FILEDESC_XUNLOCK(fdp);
1194 error = closef(fp, td);
1196 FILEDESC_XLOCK(fdp);
1197 fdp->fd_holdleaderscount--;
1198 if (fdp->fd_holdleaderscount == 0 &&
1199 fdp->fd_holdleaderswakeup != 0) {
1200 fdp->fd_holdleaderswakeup = 0;
1201 wakeup(&fdp->fd_holdleaderscount);
1203 FILEDESC_XUNLOCK(fdp);
1209 * Close a file descriptor.
1211 #ifndef _SYS_SYSPROTO_H_
1218 sys_close(struct thread *td, struct close_args *uap)
1221 return (kern_close(td, uap->fd));
1225 kern_close(struct thread *td, int fd)
1227 struct filedesc *fdp;
1230 fdp = td->td_proc->p_fd;
1232 AUDIT_SYSCLOSE(td, fd);
1234 FILEDESC_XLOCK(fdp);
1235 if ((fp = fget_locked(fdp, fd)) == NULL) {
1236 FILEDESC_XUNLOCK(fdp);
1241 /* closefp() drops the FILEDESC lock for us. */
1242 return (closefp(fdp, fd, fp, td, 1));
1246 * Close open file descriptors.
1248 #ifndef _SYS_SYSPROTO_H_
1249 struct closefrom_args {
1255 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1257 struct filedesc *fdp;
1260 fdp = td->td_proc->p_fd;
1261 AUDIT_ARG_FD(uap->lowfd);
1264 * Treat negative starting file descriptor values identical to
1265 * closefrom(0) which closes all files.
1269 FILEDESC_SLOCK(fdp);
1270 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1271 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1272 FILEDESC_SUNLOCK(fdp);
1273 (void)kern_close(td, fd);
1274 FILEDESC_SLOCK(fdp);
1277 FILEDESC_SUNLOCK(fdp);
1281 #if defined(COMPAT_43)
1283 * Return status information about a file descriptor.
1285 #ifndef _SYS_SYSPROTO_H_
1286 struct ofstat_args {
1293 ofstat(struct thread *td, struct ofstat_args *uap)
1299 error = kern_fstat(td, uap->fd, &ub);
1302 error = copyout(&oub, uap->sb, sizeof(oub));
1306 #endif /* COMPAT_43 */
1309 * Return status information about a file descriptor.
1311 #ifndef _SYS_SYSPROTO_H_
1319 sys_fstat(struct thread *td, struct fstat_args *uap)
1324 error = kern_fstat(td, uap->fd, &ub);
1326 error = copyout(&ub, uap->sb, sizeof(ub));
1331 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1334 cap_rights_t rights;
1339 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1343 AUDIT_ARG_FILE(td->td_proc, fp);
1345 error = fo_stat(fp, sbp, td->td_ucred, td);
1348 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1355 * Return status information about a file descriptor.
1357 #ifndef _SYS_SYSPROTO_H_
1358 struct nfstat_args {
1365 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1371 error = kern_fstat(td, uap->fd, &ub);
1373 cvtnstat(&ub, &nub);
1374 error = copyout(&nub, uap->sb, sizeof(nub));
1380 * Return pathconf information about a file descriptor.
1382 #ifndef _SYS_SYSPROTO_H_
1383 struct fpathconf_args {
1390 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1394 cap_rights_t rights;
1397 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1401 if (uap->name == _PC_ASYNC_IO) {
1402 td->td_retval[0] = _POSIX_ASYNCHRONOUS_IO;
1407 vn_lock(vp, LK_SHARED | LK_RETRY);
1408 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1410 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1411 if (uap->name != _PC_PIPE_BUF) {
1414 td->td_retval[0] = PIPE_BUF;
1426 * Initialize filecaps structure.
1429 filecaps_init(struct filecaps *fcaps)
1432 bzero(fcaps, sizeof(*fcaps));
1433 fcaps->fc_nioctls = -1;
1437 * Copy filecaps structure allocating memory for ioctls array if needed.
1439 * The last parameter indicates whether the fdtable is locked. If it is not and
1440 * ioctls are encountered, copying fails and the caller must lock the table.
1442 * Note that if the table was not locked, the caller has to check the relevant
1443 * sequence counter to determine whether the operation was successful.
1446 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1451 if (src->fc_ioctls == NULL)
1456 KASSERT(src->fc_nioctls > 0,
1457 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1459 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1460 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1461 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1466 * Move filecaps structure to the new place and clear the old place.
1469 filecaps_move(struct filecaps *src, struct filecaps *dst)
1473 bzero(src, sizeof(*src));
1477 * Fill the given filecaps structure with full rights.
1480 filecaps_fill(struct filecaps *fcaps)
1483 CAP_ALL(&fcaps->fc_rights);
1484 fcaps->fc_ioctls = NULL;
1485 fcaps->fc_nioctls = -1;
1486 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1490 * Free memory allocated within filecaps structure.
1493 filecaps_free(struct filecaps *fcaps)
1496 free(fcaps->fc_ioctls, M_FILECAPS);
1497 bzero(fcaps, sizeof(*fcaps));
1501 * Validate the given filecaps structure.
1504 filecaps_validate(const struct filecaps *fcaps, const char *func)
1507 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1508 ("%s: invalid rights", func));
1509 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1510 ("%s: invalid fcntls", func));
1511 KASSERT(fcaps->fc_fcntls == 0 ||
1512 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1513 ("%s: fcntls without CAP_FCNTL", func));
1514 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1515 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1516 ("%s: invalid ioctls", func));
1517 KASSERT(fcaps->fc_nioctls == 0 ||
1518 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1519 ("%s: ioctls without CAP_IOCTL", func));
1523 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1527 FILEDESC_XLOCK_ASSERT(fdp);
1529 nfd1 = fdp->fd_nfiles * 2;
1532 fdgrowtable(fdp, nfd1);
1536 * Grow the file table to accommodate (at least) nfd descriptors.
1539 fdgrowtable(struct filedesc *fdp, int nfd)
1541 struct filedesc0 *fdp0;
1542 struct freetable *ft;
1543 struct fdescenttbl *ntable;
1544 struct fdescenttbl *otable;
1545 int nnfiles, onfiles;
1546 NDSLOTTYPE *nmap, *omap;
1549 * If lastfile is -1 this struct filedesc was just allocated and we are
1550 * growing it to accommodate for the one we are going to copy from. There
1551 * is no need to have a lock on this one as it's not visible to anyone.
1553 if (fdp->fd_lastfile != -1)
1554 FILEDESC_XLOCK_ASSERT(fdp);
1556 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1558 /* save old values */
1559 onfiles = fdp->fd_nfiles;
1560 otable = fdp->fd_files;
1563 /* compute the size of the new table */
1564 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1565 if (nnfiles <= onfiles)
1566 /* the table is already large enough */
1570 * Allocate a new table. We need enough space for the number of
1571 * entries, file entries themselves and the struct freetable we will use
1572 * when we decommission the table and place it on the freelist.
1573 * We place the struct freetable in the middle so we don't have
1574 * to worry about padding.
1576 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1577 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1578 sizeof(struct freetable),
1579 M_FILEDESC, M_ZERO | M_WAITOK);
1580 /* copy the old data */
1581 ntable->fdt_nfiles = nnfiles;
1582 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1583 onfiles * sizeof(ntable->fdt_ofiles[0]));
1586 * Allocate a new map only if the old is not large enough. It will
1587 * grow at a slower rate than the table as it can map more
1588 * entries than the table can hold.
1590 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1591 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1593 /* copy over the old data and update the pointer */
1594 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1599 * Make sure that ntable is correctly initialized before we replace
1600 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1603 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1606 * Do not free the old file table, as some threads may still
1607 * reference entries within it. Instead, place it on a freelist
1608 * which will be processed when the struct filedesc is released.
1610 * Note that if onfiles == NDFILE, we're dealing with the original
1611 * static allocation contained within (struct filedesc0 *)fdp,
1612 * which must not be freed.
1614 if (onfiles > NDFILE) {
1615 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1616 fdp0 = (struct filedesc0 *)fdp;
1617 ft->ft_table = otable;
1618 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1621 * The map does not have the same possibility of threads still
1622 * holding references to it. So always free it as long as it
1623 * does not reference the original static allocation.
1625 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1626 free(omap, M_FILEDESC);
1630 * Allocate a file descriptor for the process.
1633 fdalloc(struct thread *td, int minfd, int *result)
1635 struct proc *p = td->td_proc;
1636 struct filedesc *fdp = p->p_fd;
1637 int fd, maxfd, allocfd;
1642 FILEDESC_XLOCK_ASSERT(fdp);
1644 if (fdp->fd_freefile > minfd)
1645 minfd = fdp->fd_freefile;
1647 maxfd = getmaxfd(td);
1650 * Search the bitmap for a free descriptor starting at minfd.
1651 * If none is found, grow the file table.
1653 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1656 if (fd >= fdp->fd_nfiles) {
1657 allocfd = min(fd * 2, maxfd);
1661 error = racct_set(p, RACCT_NOFILE, allocfd);
1668 * fd is already equal to first free descriptor >= minfd, so
1669 * we only need to grow the table and we are done.
1671 fdgrowtable_exp(fdp, allocfd);
1675 * Perform some sanity checks, then mark the file descriptor as
1676 * used and return it to the caller.
1678 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1679 ("invalid descriptor %d", fd));
1680 KASSERT(!fdisused(fdp, fd),
1681 ("fd_first_free() returned non-free descriptor"));
1682 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1683 ("file descriptor isn't free"));
1690 * Allocate n file descriptors for the process.
1693 fdallocn(struct thread *td, int minfd, int *fds, int n)
1695 struct proc *p = td->td_proc;
1696 struct filedesc *fdp = p->p_fd;
1699 FILEDESC_XLOCK_ASSERT(fdp);
1701 for (i = 0; i < n; i++)
1702 if (fdalloc(td, 0, &fds[i]) != 0)
1706 for (i--; i >= 0; i--)
1707 fdunused(fdp, fds[i]);
1715 * Create a new open file structure and allocate a file descriptor for the
1716 * process that refers to it. We add one reference to the file for the
1717 * descriptor table and one reference for resultfp. This is to prevent us
1718 * being preempted and the entry in the descriptor table closed after we
1719 * release the FILEDESC lock.
1722 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1723 struct filecaps *fcaps)
1728 error = falloc_noinstall(td, &fp);
1730 return (error); /* no reference held on error */
1732 error = finstall(td, fp, &fd, flags, fcaps);
1734 fdrop(fp, td); /* one reference (fp only) */
1738 if (resultfp != NULL)
1739 *resultfp = fp; /* copy out result */
1741 fdrop(fp, td); /* release local reference */
1743 if (resultfd != NULL)
1750 * Create a new open file structure without allocating a file descriptor.
1753 falloc_noinstall(struct thread *td, struct file **resultfp)
1756 int maxuserfiles = maxfiles - (maxfiles / 20);
1758 static struct timeval lastfail;
1761 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1763 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
1764 if ((openfiles_new >= maxuserfiles &&
1765 priv_check(td, PRIV_MAXFILES) != 0) ||
1766 openfiles_new >= maxfiles) {
1767 atomic_subtract_int(&openfiles, 1);
1768 if (ppsratecheck(&lastfail, &curfail, 1)) {
1769 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1770 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1774 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1775 refcount_init(&fp->f_count, 1);
1776 fp->f_cred = crhold(td->td_ucred);
1777 fp->f_ops = &badfileops;
1783 * Install a file in a file descriptor table.
1786 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1787 struct filecaps *fcaps)
1789 struct filedescent *fde;
1793 filecaps_validate(fcaps, __func__);
1794 FILEDESC_XLOCK_ASSERT(fdp);
1796 fde = &fdp->fd_ofiles[fd];
1798 seq_write_begin(&fde->fde_seq);
1801 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1803 filecaps_move(fcaps, &fde->fde_caps);
1805 filecaps_fill(&fde->fde_caps);
1807 seq_write_end(&fde->fde_seq);
1812 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1813 struct filecaps *fcaps)
1815 struct filedesc *fdp = td->td_proc->p_fd;
1820 FILEDESC_XLOCK(fdp);
1821 if ((error = fdalloc(td, 0, fd))) {
1822 FILEDESC_XUNLOCK(fdp);
1826 _finstall(fdp, fp, *fd, flags, fcaps);
1827 FILEDESC_XUNLOCK(fdp);
1832 * Build a new filedesc structure from another.
1833 * Copy the current, root, and jail root vnode references.
1835 * If fdp is not NULL, return with it shared locked.
1838 fdinit(struct filedesc *fdp, bool prepfiles)
1840 struct filedesc0 *newfdp0;
1841 struct filedesc *newfdp;
1843 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1844 newfdp = &newfdp0->fd_fd;
1846 /* Create the file descriptor table. */
1847 FILEDESC_LOCK_INIT(newfdp);
1848 refcount_init(&newfdp->fd_refcnt, 1);
1849 refcount_init(&newfdp->fd_holdcnt, 1);
1850 newfdp->fd_cmask = CMASK;
1851 newfdp->fd_map = newfdp0->fd_dmap;
1852 newfdp->fd_lastfile = -1;
1853 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
1854 newfdp->fd_files->fdt_nfiles = NDFILE;
1859 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
1860 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1862 FILEDESC_SLOCK(fdp);
1863 newfdp->fd_cdir = fdp->fd_cdir;
1864 if (newfdp->fd_cdir)
1865 vrefact(newfdp->fd_cdir);
1866 newfdp->fd_rdir = fdp->fd_rdir;
1867 if (newfdp->fd_rdir)
1868 vrefact(newfdp->fd_rdir);
1869 newfdp->fd_jdir = fdp->fd_jdir;
1870 if (newfdp->fd_jdir)
1871 vrefact(newfdp->fd_jdir);
1874 FILEDESC_SUNLOCK(fdp);
1876 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1877 FILEDESC_SUNLOCK(fdp);
1878 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1879 FILEDESC_SLOCK(fdp);
1886 static struct filedesc *
1887 fdhold(struct proc *p)
1889 struct filedesc *fdp;
1891 PROC_LOCK_ASSERT(p, MA_OWNED);
1894 refcount_acquire(&fdp->fd_holdcnt);
1899 fddrop(struct filedesc *fdp)
1902 if (fdp->fd_holdcnt > 1) {
1903 if (refcount_release(&fdp->fd_holdcnt) == 0)
1907 FILEDESC_LOCK_DESTROY(fdp);
1908 uma_zfree(filedesc0_zone, fdp);
1912 * Share a filedesc structure.
1915 fdshare(struct filedesc *fdp)
1918 refcount_acquire(&fdp->fd_refcnt);
1923 * Unshare a filedesc structure, if necessary by making a copy
1926 fdunshare(struct thread *td)
1928 struct filedesc *tmp;
1929 struct proc *p = td->td_proc;
1931 if (p->p_fd->fd_refcnt == 1)
1934 tmp = fdcopy(p->p_fd);
1940 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
1944 td->td_proc->p_fd = fdp;
1948 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1949 * this is to ease callers, not catch errors.
1952 fdcopy(struct filedesc *fdp)
1954 struct filedesc *newfdp;
1955 struct filedescent *nfde, *ofde;
1960 newfdp = fdinit(fdp, true);
1961 /* copy all passable descriptors (i.e. not kqueue) */
1962 newfdp->fd_freefile = -1;
1963 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1964 ofde = &fdp->fd_ofiles[i];
1965 if (ofde->fde_file == NULL ||
1966 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
1967 if (newfdp->fd_freefile == -1)
1968 newfdp->fd_freefile = i;
1971 nfde = &newfdp->fd_ofiles[i];
1973 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
1974 fhold(nfde->fde_file);
1975 fdused_init(newfdp, i);
1976 newfdp->fd_lastfile = i;
1978 if (newfdp->fd_freefile == -1)
1979 newfdp->fd_freefile = i;
1980 newfdp->fd_cmask = fdp->fd_cmask;
1981 FILEDESC_SUNLOCK(fdp);
1986 * Copies a filedesc structure, while remapping all file descriptors
1987 * stored inside using a translation table.
1989 * File descriptors are copied over to the new file descriptor table,
1990 * regardless of whether the close-on-exec flag is set.
1993 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
1994 struct filedesc **ret)
1996 struct filedesc *newfdp;
1997 struct filedescent *nfde, *ofde;
2002 newfdp = fdinit(fdp, true);
2003 if (nfds > fdp->fd_lastfile + 1) {
2004 /* New table cannot be larger than the old one. */
2008 /* Copy all passable descriptors (i.e. not kqueue). */
2009 newfdp->fd_freefile = nfds;
2010 for (i = 0; i < nfds; ++i) {
2011 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2012 /* File descriptor out of bounds. */
2016 ofde = &fdp->fd_ofiles[fds[i]];
2017 if (ofde->fde_file == NULL) {
2018 /* Unused file descriptor. */
2022 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2023 /* File descriptor cannot be passed. */
2027 nfde = &newfdp->fd_ofiles[i];
2029 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2030 fhold(nfde->fde_file);
2031 fdused_init(newfdp, i);
2032 newfdp->fd_lastfile = i;
2034 newfdp->fd_cmask = fdp->fd_cmask;
2035 FILEDESC_SUNLOCK(fdp);
2039 FILEDESC_SUNLOCK(fdp);
2040 fdescfree_remapped(newfdp);
2045 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2046 * one of processes using it exits) and the table used to be shared.
2049 fdclearlocks(struct thread *td)
2051 struct filedesc *fdp;
2052 struct filedesc_to_leader *fdtol;
2062 MPASS(fdtol != NULL);
2064 FILEDESC_XLOCK(fdp);
2065 KASSERT(fdtol->fdl_refcount > 0,
2066 ("filedesc_to_refcount botch: fdl_refcount=%d",
2067 fdtol->fdl_refcount));
2068 if (fdtol->fdl_refcount == 1 &&
2069 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2070 for (i = 0; i <= fdp->fd_lastfile; i++) {
2071 fp = fdp->fd_ofiles[i].fde_file;
2072 if (fp == NULL || fp->f_type != DTYPE_VNODE)
2075 FILEDESC_XUNLOCK(fdp);
2076 lf.l_whence = SEEK_SET;
2079 lf.l_type = F_UNLCK;
2081 (void) VOP_ADVLOCK(vp,
2082 (caddr_t)p->p_leader, F_UNLCK,
2084 FILEDESC_XLOCK(fdp);
2089 if (fdtol->fdl_refcount == 1) {
2090 if (fdp->fd_holdleaderscount > 0 &&
2091 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2093 * close() or kern_dup() has cleared a reference
2094 * in a shared file descriptor table.
2096 fdp->fd_holdleaderswakeup = 1;
2097 sx_sleep(&fdp->fd_holdleaderscount,
2098 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2101 if (fdtol->fdl_holdcount > 0) {
2103 * Ensure that fdtol->fdl_leader remains
2104 * valid in closef().
2106 fdtol->fdl_wakeup = 1;
2107 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2112 fdtol->fdl_refcount--;
2113 if (fdtol->fdl_refcount == 0 &&
2114 fdtol->fdl_holdcount == 0) {
2115 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2116 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2120 FILEDESC_XUNLOCK(fdp);
2122 free(fdtol, M_FILEDESC_TO_LEADER);
2126 * Release a filedesc structure.
2129 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2131 struct filedesc0 *fdp0;
2132 struct freetable *ft, *tft;
2133 struct filedescent *fde;
2137 for (i = 0; i <= fdp->fd_lastfile; i++) {
2138 fde = &fdp->fd_ofiles[i];
2143 (void) closef(fp, td);
2149 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2150 free(fdp->fd_map, M_FILEDESC);
2151 if (fdp->fd_nfiles > NDFILE)
2152 free(fdp->fd_files, M_FILEDESC);
2154 fdp0 = (struct filedesc0 *)fdp;
2155 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2156 free(ft->ft_table, M_FILEDESC);
2162 fdescfree(struct thread *td)
2165 struct filedesc *fdp;
2166 struct vnode *cdir, *jdir, *rdir;
2175 racct_set(p, RACCT_NOFILE, 0);
2180 if (p->p_fdtol != NULL)
2187 if (refcount_release(&fdp->fd_refcnt) == 0)
2190 FILEDESC_XLOCK(fdp);
2191 cdir = fdp->fd_cdir;
2192 fdp->fd_cdir = NULL;
2193 rdir = fdp->fd_rdir;
2194 fdp->fd_rdir = NULL;
2195 jdir = fdp->fd_jdir;
2196 fdp->fd_jdir = NULL;
2197 FILEDESC_XUNLOCK(fdp);
2206 fdescfree_fds(td, fdp, 1);
2210 fdescfree_remapped(struct filedesc *fdp)
2213 if (fdp->fd_cdir != NULL)
2214 vrele(fdp->fd_cdir);
2215 if (fdp->fd_rdir != NULL)
2216 vrele(fdp->fd_rdir);
2217 if (fdp->fd_jdir != NULL)
2218 vrele(fdp->fd_jdir);
2220 fdescfree_fds(curthread, fdp, 0);
2224 * For setugid programs, we don't want to people to use that setugidness
2225 * to generate error messages which write to a file which otherwise would
2226 * otherwise be off-limits to the process. We check for filesystems where
2227 * the vnode can change out from under us after execve (like [lin]procfs).
2229 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2230 * sufficient. We also don't check for setugidness since we know we are.
2233 is_unsafe(struct file *fp)
2237 if (fp->f_type != DTYPE_VNODE)
2241 return ((vp->v_vflag & VV_PROCDEP) != 0);
2245 * Make this setguid thing safe, if at all possible.
2248 fdsetugidsafety(struct thread *td)
2250 struct filedesc *fdp;
2254 fdp = td->td_proc->p_fd;
2255 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2256 MPASS(fdp->fd_nfiles >= 3);
2257 for (i = 0; i <= 2; i++) {
2258 fp = fdp->fd_ofiles[i].fde_file;
2259 if (fp != NULL && is_unsafe(fp)) {
2260 FILEDESC_XLOCK(fdp);
2261 knote_fdclose(td, i);
2263 * NULL-out descriptor prior to close to avoid
2264 * a race while close blocks.
2267 FILEDESC_XUNLOCK(fdp);
2268 (void) closef(fp, td);
2274 * If a specific file object occupies a specific file descriptor, close the
2275 * file descriptor entry and drop a reference on the file object. This is a
2276 * convenience function to handle a subsequent error in a function that calls
2277 * falloc() that handles the race that another thread might have closed the
2278 * file descriptor out from under the thread creating the file object.
2281 fdclose(struct thread *td, struct file *fp, int idx)
2283 struct filedesc *fdp = td->td_proc->p_fd;
2285 FILEDESC_XLOCK(fdp);
2286 if (fdp->fd_ofiles[idx].fde_file == fp) {
2288 FILEDESC_XUNLOCK(fdp);
2291 FILEDESC_XUNLOCK(fdp);
2295 * Close any files on exec?
2298 fdcloseexec(struct thread *td)
2300 struct filedesc *fdp;
2301 struct filedescent *fde;
2305 fdp = td->td_proc->p_fd;
2306 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2307 for (i = 0; i <= fdp->fd_lastfile; i++) {
2308 fde = &fdp->fd_ofiles[i];
2310 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2311 (fde->fde_flags & UF_EXCLOSE))) {
2312 FILEDESC_XLOCK(fdp);
2314 (void) closefp(fdp, i, fp, td, 0);
2315 FILEDESC_UNLOCK_ASSERT(fdp);
2321 * It is unsafe for set[ug]id processes to be started with file
2322 * descriptors 0..2 closed, as these descriptors are given implicit
2323 * significance in the Standard C library. fdcheckstd() will create a
2324 * descriptor referencing /dev/null for each of stdin, stdout, and
2325 * stderr that is not already open.
2328 fdcheckstd(struct thread *td)
2330 struct filedesc *fdp;
2332 int i, error, devnull;
2334 fdp = td->td_proc->p_fd;
2335 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2336 MPASS(fdp->fd_nfiles >= 3);
2338 for (i = 0; i <= 2; i++) {
2339 if (fdp->fd_ofiles[i].fde_file != NULL)
2342 save = td->td_retval[0];
2343 if (devnull != -1) {
2344 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2346 error = kern_openat(td, AT_FDCWD, "/dev/null",
2347 UIO_SYSSPACE, O_RDWR, 0);
2349 devnull = td->td_retval[0];
2350 KASSERT(devnull == i, ("we didn't get our fd"));
2353 td->td_retval[0] = save;
2361 * Internal form of close. Decrement reference count on file structure.
2362 * Note: td may be NULL when closing a file that was being passed in a
2365 * XXXRW: Giant is not required for the caller, but often will be held; this
2366 * makes it moderately likely the Giant will be recursed in the VFS case.
2369 closef(struct file *fp, struct thread *td)
2373 struct filedesc_to_leader *fdtol;
2374 struct filedesc *fdp;
2377 * POSIX record locking dictates that any close releases ALL
2378 * locks owned by this process. This is handled by setting
2379 * a flag in the unlock to free ONLY locks obeying POSIX
2380 * semantics, and not to free BSD-style file locks.
2381 * If the descriptor was in a message, POSIX-style locks
2382 * aren't passed with the descriptor, and the thread pointer
2383 * will be NULL. Callers should be careful only to pass a
2384 * NULL thread pointer when there really is no owning
2385 * context that might have locks, or the locks will be
2388 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2390 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2391 lf.l_whence = SEEK_SET;
2394 lf.l_type = F_UNLCK;
2395 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2396 F_UNLCK, &lf, F_POSIX);
2398 fdtol = td->td_proc->p_fdtol;
2399 if (fdtol != NULL) {
2401 * Handle special case where file descriptor table is
2402 * shared between multiple process leaders.
2404 fdp = td->td_proc->p_fd;
2405 FILEDESC_XLOCK(fdp);
2406 for (fdtol = fdtol->fdl_next;
2407 fdtol != td->td_proc->p_fdtol;
2408 fdtol = fdtol->fdl_next) {
2409 if ((fdtol->fdl_leader->p_flag &
2412 fdtol->fdl_holdcount++;
2413 FILEDESC_XUNLOCK(fdp);
2414 lf.l_whence = SEEK_SET;
2417 lf.l_type = F_UNLCK;
2419 (void) VOP_ADVLOCK(vp,
2420 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2422 FILEDESC_XLOCK(fdp);
2423 fdtol->fdl_holdcount--;
2424 if (fdtol->fdl_holdcount == 0 &&
2425 fdtol->fdl_wakeup != 0) {
2426 fdtol->fdl_wakeup = 0;
2430 FILEDESC_XUNLOCK(fdp);
2433 return (fdrop(fp, td));
2437 * Initialize the file pointer with the specified properties.
2439 * The ops are set with release semantics to be certain that the flags, type,
2440 * and data are visible when ops is. This is to prevent ops methods from being
2441 * called with bad data.
2444 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2449 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2453 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2454 struct file **fpp, struct filecaps *havecapsp)
2456 struct filedescent *fde;
2459 FILEDESC_LOCK_ASSERT(fdp);
2461 fde = fdeget_locked(fdp, fd);
2468 error = cap_check(cap_rights_fde(fde), needrightsp);
2473 if (havecapsp != NULL)
2474 filecaps_copy(&fde->fde_caps, havecapsp, true);
2476 *fpp = fde->fde_file;
2484 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2485 struct file **fpp, struct filecaps *havecapsp)
2487 struct filedesc *fdp = td->td_proc->p_fd;
2489 #ifndef CAPABILITIES
2490 error = fget_unlocked(fdp, fd, needrightsp, fpp, NULL);
2491 if (error == 0 && havecapsp != NULL)
2492 filecaps_fill(havecapsp);
2498 error = fget_unlocked(fdp, fd, needrightsp, &fp, &seq);
2502 if (havecapsp != NULL) {
2503 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2504 havecapsp, false)) {
2510 if (!fd_modified(fdp, fd, seq))
2519 FILEDESC_SLOCK(fdp);
2520 error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2523 FILEDESC_SUNLOCK(fdp);
2529 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2530 struct file **fpp, seq_t *seqp)
2533 struct filedescent *fde;
2535 struct fdescenttbl *fdt;
2540 cap_rights_t haverights;
2544 fdt = fdp->fd_files;
2545 if ((u_int)fd >= fdt->fdt_nfiles)
2548 * Fetch the descriptor locklessly. We avoid fdrop() races by
2549 * never raising a refcount above 0. To accomplish this we have
2550 * to use a cmpset loop rather than an atomic_add. The descriptor
2551 * must be re-verified once we acquire a reference to be certain
2552 * that the identity is still correct and we did not lose a race
2553 * due to preemption.
2557 seq = seq_read(fd_seq(fdt, fd));
2558 fde = &fdt->fdt_ofiles[fd];
2559 haverights = *cap_rights_fde(fde);
2561 if (!seq_consistent(fd_seq(fdt, fd), seq))
2564 fp = fdt->fdt_ofiles[fd].fde_file;
2569 error = cap_check(&haverights, needrightsp);
2574 count = fp->f_count;
2577 * Force a reload. Other thread could reallocate the
2578 * table before this fd was closed, so it possible that
2579 * there is a stale fp pointer in cached version.
2581 fdt = *(struct fdescenttbl * volatile *)&(fdp->fd_files);
2585 * Use an acquire barrier to force re-reading of fdt so it is
2586 * refreshed for verification.
2588 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) == 0)
2590 fdt = fdp->fd_files;
2592 if (seq_consistent_nomb(fd_seq(fdt, fd), seq))
2594 if (fp == fdt->fdt_ofiles[fd].fde_file)
2597 fdrop(fp, curthread);
2609 * Extract the file pointer associated with the specified descriptor for the
2610 * current user process.
2612 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2615 * File's rights will be checked against the capability rights mask.
2617 * If an error occurred the non-zero error is returned and *fpp is set to
2618 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2619 * responsible for fdrop().
2622 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2623 cap_rights_t *needrightsp, seq_t *seqp)
2625 struct filedesc *fdp;
2630 fdp = td->td_proc->p_fd;
2631 error = fget_unlocked(fdp, fd, needrightsp, &fp, seqp);
2634 if (fp->f_ops == &badfileops) {
2640 * FREAD and FWRITE failure return EBADF as per POSIX.
2646 if ((fp->f_flag & flags) == 0)
2650 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2651 ((fp->f_flag & FWRITE) != 0))
2657 KASSERT(0, ("wrong flags"));
2670 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2673 return (_fget(td, fd, fpp, 0, rightsp, NULL));
2677 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2681 #ifndef CAPABILITIES
2682 error = _fget(td, fd, fpp, 0, rightsp, NULL);
2683 if (maxprotp != NULL)
2684 *maxprotp = VM_PROT_ALL;
2686 struct filedesc *fdp = td->td_proc->p_fd;
2689 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2691 error = _fget(td, fd, fpp, 0, rightsp, &seq);
2695 * If requested, convert capability rights to access flags.
2697 if (maxprotp != NULL)
2698 *maxprotp = cap_rights_to_vmprot(cap_rights(fdp, fd));
2699 if (!fd_modified(fdp, fd, seq))
2708 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2711 return (_fget(td, fd, fpp, FREAD, rightsp, NULL));
2715 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2718 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2722 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2725 struct filedesc *fdp = td->td_proc->p_fd;
2726 #ifndef CAPABILITIES
2727 return (fget_unlocked(fdp, fd, rightsp, fpp, NULL));
2732 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2734 error = fget_unlocked(fdp, fd, rightsp, fpp, &seq);
2737 error = cap_fcntl_check(fdp, fd, needfcntl);
2738 if (!fd_modified(fdp, fd, seq))
2751 * Like fget() but loads the underlying vnode, or returns an error if the
2752 * descriptor does not represent a vnode. Note that pipes use vnodes but
2753 * never have VM objects. The returned vnode will be vref()'d.
2755 * XXX: what about the unused flags ?
2758 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2765 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2768 if (fp->f_vnode == NULL) {
2780 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2783 return (_fgetvp(td, fd, 0, rightsp, vpp));
2787 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2788 struct filecaps *havecaps, struct vnode **vpp)
2790 struct filedesc *fdp;
2791 struct filecaps caps;
2795 fdp = td->td_proc->p_fd;
2796 error = fget_cap_locked(fdp, fd, needrightsp, &fp, &caps);
2799 if (fp->f_ops == &badfileops) {
2803 if (fp->f_vnode == NULL) {
2814 filecaps_free(&caps);
2819 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2822 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2826 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2829 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2834 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2838 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2843 * Like fget() but loads the underlying socket, or returns an error if the
2844 * descriptor does not represent a socket.
2846 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2849 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2850 * on their file descriptor reference to prevent the socket from being free'd
2854 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2863 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2865 if (fp->f_type != DTYPE_SOCKET) {
2870 *fflagp = fp->f_flag;
2881 * Drop the reference count on the socket and XXX release the SX lock in the
2882 * future. The last reference closes the socket.
2884 * Note: fputsock() is deprecated, see comment for fgetsock().
2887 fputsock(struct socket *so)
2892 CURVNET_SET(so->so_vnet);
2898 * Handle the last reference to a file being closed.
2901 _fdrop(struct file *fp, struct thread *td)
2905 if (fp->f_count != 0)
2906 panic("fdrop: count %d", fp->f_count);
2907 error = fo_close(fp, td);
2908 atomic_subtract_int(&openfiles, 1);
2910 free(fp->f_advice, M_FADVISE);
2911 uma_zfree(file_zone, fp);
2917 * Apply an advisory lock on a file descriptor.
2919 * Just attempt to get a record lock of the requested type on the entire file
2920 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2922 #ifndef _SYS_SYSPROTO_H_
2930 sys_flock(struct thread *td, struct flock_args *uap)
2935 cap_rights_t rights;
2938 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2941 if (fp->f_type != DTYPE_VNODE) {
2943 return (EOPNOTSUPP);
2947 lf.l_whence = SEEK_SET;
2950 if (uap->how & LOCK_UN) {
2951 lf.l_type = F_UNLCK;
2952 atomic_clear_int(&fp->f_flag, FHASLOCK);
2953 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2956 if (uap->how & LOCK_EX)
2957 lf.l_type = F_WRLCK;
2958 else if (uap->how & LOCK_SH)
2959 lf.l_type = F_RDLCK;
2964 atomic_set_int(&fp->f_flag, FHASLOCK);
2965 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2966 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2972 * Duplicate the specified descriptor to a free descriptor.
2975 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2976 int openerror, int *indxp)
2978 struct filedescent *newfde, *oldfde;
2982 KASSERT(openerror == ENODEV || openerror == ENXIO,
2983 ("unexpected error %d in %s", openerror, __func__));
2986 * If the to-be-dup'd fd number is greater than the allowed number
2987 * of file descriptors, or the fd to be dup'd has already been
2988 * closed, then reject.
2990 FILEDESC_XLOCK(fdp);
2991 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2992 FILEDESC_XUNLOCK(fdp);
2996 error = fdalloc(td, 0, &indx);
2998 FILEDESC_XUNLOCK(fdp);
3003 * There are two cases of interest here.
3005 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3007 * For ENXIO steal away the file structure from (dfd) and store it in
3008 * (indx). (dfd) is effectively closed by this operation.
3010 switch (openerror) {
3013 * Check that the mode the file is being opened for is a
3014 * subset of the mode of the existing descriptor.
3016 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3017 fdunused(fdp, indx);
3018 FILEDESC_XUNLOCK(fdp);
3022 newfde = &fdp->fd_ofiles[indx];
3023 oldfde = &fdp->fd_ofiles[dfd];
3025 seq_write_begin(&newfde->fde_seq);
3027 memcpy(newfde, oldfde, fde_change_size);
3028 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps, true);
3030 seq_write_end(&newfde->fde_seq);
3035 * Steal away the file pointer from dfd and stuff it into indx.
3037 newfde = &fdp->fd_ofiles[indx];
3038 oldfde = &fdp->fd_ofiles[dfd];
3040 seq_write_begin(&newfde->fde_seq);
3042 memcpy(newfde, oldfde, fde_change_size);
3043 oldfde->fde_file = NULL;
3046 seq_write_end(&newfde->fde_seq);
3050 FILEDESC_XUNLOCK(fdp);
3056 * This sysctl determines if we will allow a process to chroot(2) if it
3057 * has a directory open:
3058 * 0: disallowed for all processes.
3059 * 1: allowed for processes that were not already chroot(2)'ed.
3060 * 2: allowed for all processes.
3063 static int chroot_allow_open_directories = 1;
3065 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3066 &chroot_allow_open_directories, 0,
3067 "Allow a process to chroot(2) if it has a directory open");
3070 * Helper function for raised chroot(2) security function: Refuse if
3071 * any filedescriptors are open directories.
3074 chroot_refuse_vdir_fds(struct filedesc *fdp)
3080 FILEDESC_LOCK_ASSERT(fdp);
3082 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3083 fp = fget_locked(fdp, fd);
3086 if (fp->f_type == DTYPE_VNODE) {
3088 if (vp->v_type == VDIR)
3096 * Common routine for kern_chroot() and jail_attach(). The caller is
3097 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3098 * authorize this operation.
3101 pwd_chroot(struct thread *td, struct vnode *vp)
3103 struct filedesc *fdp;
3104 struct vnode *oldvp;
3107 fdp = td->td_proc->p_fd;
3108 FILEDESC_XLOCK(fdp);
3109 if (chroot_allow_open_directories == 0 ||
3110 (chroot_allow_open_directories == 1 && fdp->fd_rdir != rootvnode)) {
3111 error = chroot_refuse_vdir_fds(fdp);
3113 FILEDESC_XUNLOCK(fdp);
3117 oldvp = fdp->fd_rdir;
3120 if (fdp->fd_jdir == NULL) {
3124 FILEDESC_XUNLOCK(fdp);
3130 pwd_chdir(struct thread *td, struct vnode *vp)
3132 struct filedesc *fdp;
3133 struct vnode *oldvp;
3135 fdp = td->td_proc->p_fd;
3136 FILEDESC_XLOCK(fdp);
3137 VNASSERT(vp->v_usecount > 0, vp,
3138 ("chdir to a vnode with zero usecount"));
3139 oldvp = fdp->fd_cdir;
3141 FILEDESC_XUNLOCK(fdp);
3146 * Scan all active processes and prisons to see if any of them have a current
3147 * or root directory of `olddp'. If so, replace them with the new mount point.
3150 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3152 struct filedesc *fdp;
3157 if (vrefcnt(olddp) == 1)
3160 sx_slock(&allproc_lock);
3161 FOREACH_PROC_IN_SYSTEM(p) {
3167 FILEDESC_XLOCK(fdp);
3168 if (fdp->fd_cdir == olddp) {
3170 fdp->fd_cdir = newdp;
3173 if (fdp->fd_rdir == olddp) {
3175 fdp->fd_rdir = newdp;
3178 if (fdp->fd_jdir == olddp) {
3180 fdp->fd_jdir = newdp;
3183 FILEDESC_XUNLOCK(fdp);
3186 sx_sunlock(&allproc_lock);
3187 if (rootvnode == olddp) {
3192 mtx_lock(&prison0.pr_mtx);
3193 if (prison0.pr_root == olddp) {
3195 prison0.pr_root = newdp;
3198 mtx_unlock(&prison0.pr_mtx);
3199 sx_slock(&allprison_lock);
3200 TAILQ_FOREACH(pr, &allprison, pr_list) {
3201 mtx_lock(&pr->pr_mtx);
3202 if (pr->pr_root == olddp) {
3204 pr->pr_root = newdp;
3207 mtx_unlock(&pr->pr_mtx);
3209 sx_sunlock(&allprison_lock);
3214 struct filedesc_to_leader *
3215 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3217 struct filedesc_to_leader *fdtol;
3219 fdtol = malloc(sizeof(struct filedesc_to_leader),
3220 M_FILEDESC_TO_LEADER, M_WAITOK);
3221 fdtol->fdl_refcount = 1;
3222 fdtol->fdl_holdcount = 0;
3223 fdtol->fdl_wakeup = 0;
3224 fdtol->fdl_leader = leader;
3226 FILEDESC_XLOCK(fdp);
3227 fdtol->fdl_next = old->fdl_next;
3228 fdtol->fdl_prev = old;
3229 old->fdl_next = fdtol;
3230 fdtol->fdl_next->fdl_prev = fdtol;
3231 FILEDESC_XUNLOCK(fdp);
3233 fdtol->fdl_next = fdtol;
3234 fdtol->fdl_prev = fdtol;
3240 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3242 struct filedesc *fdp;
3243 int i, count, slots;
3245 if (*(int *)arg1 != 0)
3248 fdp = curproc->p_fd;
3250 FILEDESC_SLOCK(fdp);
3251 slots = NDSLOTS(fdp->fd_lastfile + 1);
3252 for (i = 0; i < slots; i++)
3253 count += bitcountl(fdp->fd_map[i]);
3254 FILEDESC_SUNLOCK(fdp);
3256 return (SYSCTL_OUT(req, &count, sizeof(count)));
3259 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3260 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3261 "Number of open file descriptors");
3264 * Get file structures globally.
3267 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3270 struct filedesc *fdp;
3275 error = sysctl_wire_old_buffer(req, 0);
3278 if (req->oldptr == NULL) {
3280 sx_slock(&allproc_lock);
3281 FOREACH_PROC_IN_SYSTEM(p) {
3283 if (p->p_state == PRS_NEW) {
3291 /* overestimates sparse tables. */
3292 if (fdp->fd_lastfile > 0)
3293 n += fdp->fd_lastfile;
3296 sx_sunlock(&allproc_lock);
3297 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3300 bzero(&xf, sizeof(xf));
3301 xf.xf_size = sizeof(xf);
3302 sx_slock(&allproc_lock);
3303 FOREACH_PROC_IN_SYSTEM(p) {
3305 if (p->p_state == PRS_NEW) {
3309 if (p_cansee(req->td, p) != 0) {
3313 xf.xf_pid = p->p_pid;
3314 xf.xf_uid = p->p_ucred->cr_uid;
3319 FILEDESC_SLOCK(fdp);
3320 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3321 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3325 xf.xf_data = fp->f_data;
3326 xf.xf_vnode = fp->f_vnode;
3327 xf.xf_type = fp->f_type;
3328 xf.xf_count = fp->f_count;
3330 xf.xf_offset = foffset_get(fp);
3331 xf.xf_flag = fp->f_flag;
3332 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3336 FILEDESC_SUNLOCK(fdp);
3341 sx_sunlock(&allproc_lock);
3345 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3346 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3348 #ifdef KINFO_FILE_SIZE
3349 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3353 xlate_fflags(int fflags)
3355 static const struct {
3358 } fflags_table[] = {
3359 { FAPPEND, KF_FLAG_APPEND },
3360 { FASYNC, KF_FLAG_ASYNC },
3361 { FFSYNC, KF_FLAG_FSYNC },
3362 { FHASLOCK, KF_FLAG_HASLOCK },
3363 { FNONBLOCK, KF_FLAG_NONBLOCK },
3364 { FREAD, KF_FLAG_READ },
3365 { FWRITE, KF_FLAG_WRITE },
3366 { O_CREAT, KF_FLAG_CREAT },
3367 { O_DIRECT, KF_FLAG_DIRECT },
3368 { O_EXCL, KF_FLAG_EXCL },
3369 { O_EXEC, KF_FLAG_EXEC },
3370 { O_EXLOCK, KF_FLAG_EXLOCK },
3371 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3372 { O_SHLOCK, KF_FLAG_SHLOCK },
3373 { O_TRUNC, KF_FLAG_TRUNC }
3379 for (i = 0; i < nitems(fflags_table); i++)
3380 if (fflags & fflags_table[i].fflag)
3381 kflags |= fflags_table[i].kf_fflag;
3385 /* Trim unused data from kf_path by truncating the structure size. */
3387 pack_kinfo(struct kinfo_file *kif)
3390 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3391 strlen(kif->kf_path) + 1;
3392 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3396 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3397 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3401 bzero(kif, sizeof(*kif));
3403 /* Set a default type to allow for empty fill_kinfo() methods. */
3404 kif->kf_type = KF_TYPE_UNKNOWN;
3405 kif->kf_flags = xlate_fflags(fp->f_flag);
3406 if (rightsp != NULL)
3407 kif->kf_cap_rights = *rightsp;
3409 cap_rights_init(&kif->kf_cap_rights);
3411 kif->kf_ref_count = fp->f_count;
3412 kif->kf_offset = foffset_get(fp);
3415 * This may drop the filedesc lock, so the 'fp' cannot be
3416 * accessed after this call.
3418 error = fo_fill_kinfo(fp, kif, fdp);
3420 kif->kf_status |= KF_ATTR_VALID;
3421 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3424 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3428 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3429 struct kinfo_file *kif, int flags)
3433 bzero(kif, sizeof(*kif));
3435 kif->kf_type = KF_TYPE_VNODE;
3436 error = vn_fill_kinfo_vnode(vp, kif);
3438 kif->kf_status |= KF_ATTR_VALID;
3439 kif->kf_flags = xlate_fflags(fflags);
3440 cap_rights_init(&kif->kf_cap_rights);
3442 kif->kf_ref_count = -1;
3443 kif->kf_offset = -1;
3444 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3447 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3451 struct export_fd_buf {
3452 struct filedesc *fdp;
3455 struct kinfo_file kif;
3460 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3462 struct kinfo_file *kif;
3465 if (efbuf->remainder != -1) {
3466 if (efbuf->remainder < kif->kf_structsize) {
3467 /* Terminate export. */
3468 efbuf->remainder = 0;
3471 efbuf->remainder -= kif->kf_structsize;
3473 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3477 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3478 struct export_fd_buf *efbuf)
3482 if (efbuf->remainder == 0)
3484 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3486 FILEDESC_SUNLOCK(efbuf->fdp);
3487 error = export_kinfo_to_sb(efbuf);
3488 FILEDESC_SLOCK(efbuf->fdp);
3493 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3494 struct export_fd_buf *efbuf)
3498 if (efbuf->remainder == 0)
3500 if (efbuf->fdp != NULL)
3501 FILEDESC_SUNLOCK(efbuf->fdp);
3502 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3503 error = export_kinfo_to_sb(efbuf);
3504 if (efbuf->fdp != NULL)
3505 FILEDESC_SLOCK(efbuf->fdp);
3510 * Store a process file descriptor information to sbuf.
3512 * Takes a locked proc as argument, and returns with the proc unlocked.
3515 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3519 struct filedesc *fdp;
3520 struct export_fd_buf *efbuf;
3521 struct vnode *cttyvp, *textvp, *tracevp;
3523 cap_rights_t rights;
3525 PROC_LOCK_ASSERT(p, MA_OWNED);
3528 tracevp = p->p_tracevp;
3529 if (tracevp != NULL)
3532 textvp = p->p_textvp;
3535 /* Controlling tty. */
3537 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3538 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3544 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3547 efbuf->remainder = maxlen;
3548 efbuf->flags = flags;
3549 if (tracevp != NULL)
3550 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3553 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3555 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3561 FILEDESC_SLOCK(fdp);
3562 /* working directory */
3563 if (fdp->fd_cdir != NULL) {
3564 vrefact(fdp->fd_cdir);
3565 export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3567 /* root directory */
3568 if (fdp->fd_rdir != NULL) {
3569 vrefact(fdp->fd_rdir);
3570 export_vnode_to_sb(fdp->fd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3572 /* jail directory */
3573 if (fdp->fd_jdir != NULL) {
3574 vrefact(fdp->fd_jdir);
3575 export_vnode_to_sb(fdp->fd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3577 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3578 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3581 rights = *cap_rights(fdp, i);
3582 #else /* !CAPABILITIES */
3583 cap_rights_init(&rights);
3586 * Create sysctl entry. It is OK to drop the filedesc
3587 * lock inside of export_file_to_sb() as we will
3588 * re-validate and re-evaluate its properties when the
3591 error = export_file_to_sb(fp, i, &rights, efbuf);
3592 if (error != 0 || efbuf->remainder == 0)
3595 FILEDESC_SUNLOCK(fdp);
3598 free(efbuf, M_TEMP);
3602 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3605 * Get per-process file descriptors for use by procstat(1), et al.
3608 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3613 int error, error2, *name;
3617 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3618 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3619 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3624 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3625 error = kern_proc_filedesc_out(p, &sb, maxlen,
3626 KERN_FILEDESC_PACK_KINFO);
3627 error2 = sbuf_finish(&sb);
3629 return (error != 0 ? error : error2);
3632 #ifdef KINFO_OFILE_SIZE
3633 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3636 #ifdef COMPAT_FREEBSD7
3638 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3641 okif->kf_structsize = sizeof(*okif);
3642 okif->kf_type = kif->kf_type;
3643 okif->kf_fd = kif->kf_fd;
3644 okif->kf_ref_count = kif->kf_ref_count;
3645 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3646 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3647 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3648 okif->kf_offset = kif->kf_offset;
3649 okif->kf_vnode_type = kif->kf_vnode_type;
3650 okif->kf_sock_domain = kif->kf_sock_domain;
3651 okif->kf_sock_type = kif->kf_sock_type;
3652 okif->kf_sock_protocol = kif->kf_sock_protocol;
3653 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3654 okif->kf_sa_local = kif->kf_sa_local;
3655 okif->kf_sa_peer = kif->kf_sa_peer;
3659 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3660 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3665 FILEDESC_SUNLOCK(fdp);
3666 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
3667 kinfo_to_okinfo(kif, okif);
3668 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3669 FILEDESC_SLOCK(fdp);
3674 * Get per-process file descriptors for use by procstat(1), et al.
3677 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3679 struct kinfo_ofile *okif;
3680 struct kinfo_file *kif;
3681 struct filedesc *fdp;
3682 int error, i, *name;
3687 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3694 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3695 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
3696 FILEDESC_SLOCK(fdp);
3697 if (fdp->fd_cdir != NULL)
3698 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3700 if (fdp->fd_rdir != NULL)
3701 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3703 if (fdp->fd_jdir != NULL)
3704 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3706 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3707 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3709 export_file_to_kinfo(fp, i, NULL, kif, fdp,
3710 KERN_FILEDESC_PACK_KINFO);
3711 FILEDESC_SUNLOCK(fdp);
3712 kinfo_to_okinfo(kif, okif);
3713 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3714 FILEDESC_SLOCK(fdp);
3718 FILEDESC_SUNLOCK(fdp);
3725 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3726 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3727 "Process ofiledesc entries");
3728 #endif /* COMPAT_FREEBSD7 */
3731 vntype_to_kinfo(int vtype)
3736 } vtypes_table[] = {
3737 { VBAD, KF_VTYPE_VBAD },
3738 { VBLK, KF_VTYPE_VBLK },
3739 { VCHR, KF_VTYPE_VCHR },
3740 { VDIR, KF_VTYPE_VDIR },
3741 { VFIFO, KF_VTYPE_VFIFO },
3742 { VLNK, KF_VTYPE_VLNK },
3743 { VNON, KF_VTYPE_VNON },
3744 { VREG, KF_VTYPE_VREG },
3745 { VSOCK, KF_VTYPE_VSOCK }
3750 * Perform vtype translation.
3752 for (i = 0; i < nitems(vtypes_table); i++)
3753 if (vtypes_table[i].vtype == vtype)
3754 return (vtypes_table[i].kf_vtype);
3756 return (KF_VTYPE_UNKNOWN);
3759 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3760 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3761 "Process filedesc entries");
3764 * Store a process current working directory information to sbuf.
3766 * Takes a locked proc as argument, and returns with the proc unlocked.
3769 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3771 struct filedesc *fdp;
3772 struct export_fd_buf *efbuf;
3775 PROC_LOCK_ASSERT(p, MA_OWNED);
3782 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3785 efbuf->remainder = maxlen;
3787 FILEDESC_SLOCK(fdp);
3788 if (fdp->fd_cdir == NULL)
3791 vrefact(fdp->fd_cdir);
3792 error = export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD,
3795 FILEDESC_SUNLOCK(fdp);
3797 free(efbuf, M_TEMP);
3802 * Get per-process current working directory.
3805 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
3810 int error, error2, *name;
3814 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
3815 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3816 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3821 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3822 error = kern_proc_cwd_out(p, &sb, maxlen);
3823 error2 = sbuf_finish(&sb);
3825 return (error != 0 ? error : error2);
3828 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
3829 sysctl_kern_proc_cwd, "Process current working directory");
3833 * For the purposes of debugging, generate a human-readable string for the
3837 file_type_to_name(short type)
3867 * For the purposes of debugging, identify a process (if any, perhaps one of
3868 * many) that references the passed file in its file descriptor array. Return
3871 static struct proc *
3872 file_to_first_proc(struct file *fp)
3874 struct filedesc *fdp;
3878 FOREACH_PROC_IN_SYSTEM(p) {
3879 if (p->p_state == PRS_NEW)
3884 for (n = 0; n <= fdp->fd_lastfile; n++) {
3885 if (fp == fdp->fd_ofiles[n].fde_file)
3893 db_print_file(struct file *fp, int header)
3898 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3899 "File", "Type", "Data", "Flag", "GCFl", "Count",
3900 "MCount", "Vnode", "FPID", "FCmd");
3901 p = file_to_first_proc(fp);
3902 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3903 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3904 0, fp->f_count, 0, fp->f_vnode,
3905 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3908 DB_SHOW_COMMAND(file, db_show_file)
3913 db_printf("usage: show file <addr>\n");
3916 fp = (struct file *)addr;
3917 db_print_file(fp, 1);
3920 DB_SHOW_COMMAND(files, db_show_files)
3922 struct filedesc *fdp;
3929 FOREACH_PROC_IN_SYSTEM(p) {
3930 if (p->p_state == PRS_NEW)
3932 if ((fdp = p->p_fd) == NULL)
3934 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3935 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3937 db_print_file(fp, header);
3944 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3945 &maxfilesperproc, 0, "Maximum files allowed open per process");
3947 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3948 &maxfiles, 0, "Maximum number of files");
3950 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3951 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3955 filelistinit(void *dummy)
3958 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3959 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3960 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
3961 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
3962 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3964 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3966 /*-------------------------------------------------------------------*/
3969 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3970 int flags, struct thread *td)
3977 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3985 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3993 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4001 badfo_kqfilter(struct file *fp, struct knote *kn)
4008 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4016 badfo_close(struct file *fp, struct thread *td)
4023 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4031 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4039 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4040 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4048 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4054 struct fileops badfileops = {
4055 .fo_read = badfo_readwrite,
4056 .fo_write = badfo_readwrite,
4057 .fo_truncate = badfo_truncate,
4058 .fo_ioctl = badfo_ioctl,
4059 .fo_poll = badfo_poll,
4060 .fo_kqfilter = badfo_kqfilter,
4061 .fo_stat = badfo_stat,
4062 .fo_close = badfo_close,
4063 .fo_chmod = badfo_chmod,
4064 .fo_chown = badfo_chown,
4065 .fo_sendfile = badfo_sendfile,
4066 .fo_fill_kinfo = badfo_fill_kinfo,
4070 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4071 int flags, struct thread *td)
4074 return (EOPNOTSUPP);
4078 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4086 invfo_ioctl(struct file *fp, u_long com, void *data,
4087 struct ucred *active_cred, struct thread *td)
4094 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4098 return (poll_no_poll(events));
4102 invfo_kqfilter(struct file *fp, struct knote *kn)
4109 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4117 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4125 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4126 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4133 /*-------------------------------------------------------------------*/
4136 * File Descriptor pseudo-device driver (/dev/fd/).
4138 * Opening minor device N dup()s the file (if any) connected to file
4139 * descriptor N belonging to the calling process. Note that this driver
4140 * consists of only the ``open()'' routine, because all subsequent
4141 * references to this file will be direct to the other driver.
4143 * XXX: we could give this one a cloning event handler if necessary.
4148 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4152 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4153 * the file descriptor being sought for duplication. The error
4154 * return ensures that the vnode for this device will be released
4155 * by vn_open. Open will detect this special error and take the
4156 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4157 * will simply report the error.
4159 td->td_dupfd = dev2unit(dev);
4163 static struct cdevsw fildesc_cdevsw = {
4164 .d_version = D_VERSION,
4170 fildesc_drvinit(void *unused)
4174 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4175 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4176 make_dev_alias(dev, "stdin");
4177 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4178 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4179 make_dev_alias(dev, "stdout");
4180 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4181 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4182 make_dev_alias(dev, "stderr");
4185 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);