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>
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;
501 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
504 case F_DUPFD_CLOEXEC:
506 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
511 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
514 case F_DUP2FD_CLOEXEC:
516 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
521 if (fget_locked(fdp, fd) == NULL) {
522 FILEDESC_SUNLOCK(fdp);
526 fde = &fdp->fd_ofiles[fd];
528 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
529 FILEDESC_SUNLOCK(fdp);
534 if (fget_locked(fdp, fd) == NULL) {
535 FILEDESC_XUNLOCK(fdp);
539 fde = &fdp->fd_ofiles[fd];
540 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
541 (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 * Verify we have a valid descriptor to dup from and possibly to
825 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
826 * return EINVAL when the new descriptor is out of bounds.
831 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
832 maxfd = getmaxfd(td);
834 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
837 if (fget_locked(fdp, old) == NULL) {
838 FILEDESC_XUNLOCK(fdp);
841 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
842 td->td_retval[0] = new;
843 if (flags & FDDUP_FLAG_CLOEXEC)
844 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
845 FILEDESC_XUNLOCK(fdp);
850 * If the caller specified a file descriptor, make sure the file
851 * table is large enough to hold it, and grab it. Otherwise, just
852 * allocate a new descriptor the usual way.
857 if ((error = fdalloc(td, new, &new)) != 0) {
858 FILEDESC_XUNLOCK(fdp);
862 case FDDUP_MUSTREPLACE:
863 /* Target file descriptor must exist. */
864 if (fget_locked(fdp, new) == NULL) {
865 FILEDESC_XUNLOCK(fdp);
870 if (new >= fdp->fd_nfiles) {
872 * The resource limits are here instead of e.g.
873 * fdalloc(), because the file descriptor table may be
874 * shared between processes, so we can't really use
875 * racct_add()/racct_sub(). Instead of counting the
876 * number of actually allocated descriptors, just put
877 * the limit on the size of the file descriptor table.
882 error = racct_set(p, RACCT_NOFILE, new + 1);
885 FILEDESC_XUNLOCK(fdp);
890 fdgrowtable_exp(fdp, new + 1);
892 if (!fdisused(fdp, new))
896 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
899 KASSERT(old != new, ("new fd is same as old"));
901 oldfde = &fdp->fd_ofiles[old];
902 fhold(oldfde->fde_file);
903 newfde = &fdp->fd_ofiles[new];
904 delfp = newfde->fde_file;
907 * Duplicate the source descriptor.
910 seq_write_begin(&newfde->fde_seq);
912 filecaps_free(&newfde->fde_caps);
913 memcpy(newfde, oldfde, fde_change_size);
914 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps, true);
915 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
916 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
918 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
920 seq_write_end(&newfde->fde_seq);
922 td->td_retval[0] = new;
925 (void) closefp(fdp, new, delfp, td, 1);
926 /* closefp() drops the FILEDESC lock for us. */
928 FILEDESC_XUNLOCK(fdp);
935 * If sigio is on the list associated with a process or process group,
936 * disable signalling from the device, remove sigio from the list and
940 funsetown(struct sigio **sigiop)
950 *(sigio->sio_myref) = NULL;
951 if ((sigio)->sio_pgid < 0) {
952 struct pgrp *pg = (sigio)->sio_pgrp;
954 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
958 struct proc *p = (sigio)->sio_proc;
960 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
965 crfree(sigio->sio_ucred);
966 free(sigio, M_SIGIO);
970 * Free a list of sigio structures.
971 * We only need to lock the SIGIO_LOCK because we have made ourselves
972 * inaccessible to callers of fsetown and therefore do not need to lock
973 * the proc or pgrp struct for the list manipulation.
976 funsetownlst(struct sigiolst *sigiolst)
982 sigio = SLIST_FIRST(sigiolst);
989 * Every entry of the list should belong
990 * to a single proc or pgrp.
992 if (sigio->sio_pgid < 0) {
993 pg = sigio->sio_pgrp;
994 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
995 } else /* if (sigio->sio_pgid > 0) */ {
997 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1001 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1002 *(sigio->sio_myref) = NULL;
1004 KASSERT(sigio->sio_pgid < 0,
1005 ("Proc sigio in pgrp sigio list"));
1006 KASSERT(sigio->sio_pgrp == pg,
1007 ("Bogus pgrp in sigio list"));
1009 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1012 } else /* if (p != NULL) */ {
1013 KASSERT(sigio->sio_pgid > 0,
1014 ("Pgrp sigio in proc sigio list"));
1015 KASSERT(sigio->sio_proc == p,
1016 ("Bogus proc in sigio list"));
1018 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1023 crfree(sigio->sio_ucred);
1024 free(sigio, M_SIGIO);
1031 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1033 * After permission checking, add a sigio structure to the sigio list for
1034 * the process or process group.
1037 fsetown(pid_t pgid, struct sigio **sigiop)
1041 struct sigio *sigio;
1051 /* Allocate and fill in the new sigio out of locks. */
1052 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1053 sigio->sio_pgid = pgid;
1054 sigio->sio_ucred = crhold(curthread->td_ucred);
1055 sigio->sio_myref = sigiop;
1057 sx_slock(&proctree_lock);
1066 * Policy - Don't allow a process to FSETOWN a process
1067 * in another session.
1069 * Remove this test to allow maximum flexibility or
1070 * restrict FSETOWN to the current process or process
1071 * group for maximum safety.
1074 if (proc->p_session != curthread->td_proc->p_session) {
1080 } else /* if (pgid < 0) */ {
1081 pgrp = pgfind(-pgid);
1089 * Policy - Don't allow a process to FSETOWN a process
1090 * in another session.
1092 * Remove this test to allow maximum flexibility or
1093 * restrict FSETOWN to the current process or process
1094 * group for maximum safety.
1096 if (pgrp->pg_session != curthread->td_proc->p_session) {
1107 * Since funsetownlst() is called without the proctree
1108 * locked, we need to check for P_WEXIT.
1109 * XXX: is ESRCH correct?
1111 if ((proc->p_flag & P_WEXIT) != 0) {
1116 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1117 sigio->sio_proc = proc;
1121 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1122 sigio->sio_pgrp = pgrp;
1125 sx_sunlock(&proctree_lock);
1132 sx_sunlock(&proctree_lock);
1133 crfree(sigio->sio_ucred);
1134 free(sigio, M_SIGIO);
1139 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1143 struct sigio **sigiop;
1148 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1154 * Function drops the filedesc lock on return.
1157 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1162 FILEDESC_XLOCK_ASSERT(fdp);
1165 if (td->td_proc->p_fdtol != NULL) {
1167 * Ask fdfree() to sleep to ensure that all relevant
1168 * process leaders can be traversed in closef().
1170 fdp->fd_holdleaderscount++;
1177 * We now hold the fp reference that used to be owned by the
1178 * descriptor array. We have to unlock the FILEDESC *AFTER*
1179 * knote_fdclose to prevent a race of the fd getting opened, a knote
1180 * added, and deleteing a knote for the new fd.
1182 knote_fdclose(td, fd);
1185 * We need to notify mqueue if the object is of type mqueue.
1187 if (fp->f_type == DTYPE_MQUEUE)
1188 mq_fdclose(td, fd, fp);
1189 FILEDESC_XUNLOCK(fdp);
1191 error = closef(fp, td);
1193 FILEDESC_XLOCK(fdp);
1194 fdp->fd_holdleaderscount--;
1195 if (fdp->fd_holdleaderscount == 0 &&
1196 fdp->fd_holdleaderswakeup != 0) {
1197 fdp->fd_holdleaderswakeup = 0;
1198 wakeup(&fdp->fd_holdleaderscount);
1200 FILEDESC_XUNLOCK(fdp);
1206 * Close a file descriptor.
1208 #ifndef _SYS_SYSPROTO_H_
1215 sys_close(struct thread *td, struct close_args *uap)
1218 return (kern_close(td, uap->fd));
1222 kern_close(struct thread *td, int fd)
1224 struct filedesc *fdp;
1227 fdp = td->td_proc->p_fd;
1229 AUDIT_SYSCLOSE(td, fd);
1231 FILEDESC_XLOCK(fdp);
1232 if ((fp = fget_locked(fdp, fd)) == NULL) {
1233 FILEDESC_XUNLOCK(fdp);
1238 /* closefp() drops the FILEDESC lock for us. */
1239 return (closefp(fdp, fd, fp, td, 1));
1243 * Close open file descriptors.
1245 #ifndef _SYS_SYSPROTO_H_
1246 struct closefrom_args {
1252 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1254 struct filedesc *fdp;
1257 fdp = td->td_proc->p_fd;
1258 AUDIT_ARG_FD(uap->lowfd);
1261 * Treat negative starting file descriptor values identical to
1262 * closefrom(0) which closes all files.
1266 FILEDESC_SLOCK(fdp);
1267 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1268 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1269 FILEDESC_SUNLOCK(fdp);
1270 (void)kern_close(td, fd);
1271 FILEDESC_SLOCK(fdp);
1274 FILEDESC_SUNLOCK(fdp);
1278 #if defined(COMPAT_43)
1280 * Return status information about a file descriptor.
1282 #ifndef _SYS_SYSPROTO_H_
1283 struct ofstat_args {
1290 ofstat(struct thread *td, struct ofstat_args *uap)
1296 error = kern_fstat(td, uap->fd, &ub);
1299 error = copyout(&oub, uap->sb, sizeof(oub));
1303 #endif /* COMPAT_43 */
1306 * Return status information about a file descriptor.
1308 #ifndef _SYS_SYSPROTO_H_
1316 sys_fstat(struct thread *td, struct fstat_args *uap)
1321 error = kern_fstat(td, uap->fd, &ub);
1323 error = copyout(&ub, uap->sb, sizeof(ub));
1328 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1331 cap_rights_t rights;
1336 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1340 AUDIT_ARG_FILE(td->td_proc, fp);
1342 error = fo_stat(fp, sbp, td->td_ucred, td);
1345 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1352 * Return status information about a file descriptor.
1354 #ifndef _SYS_SYSPROTO_H_
1355 struct nfstat_args {
1362 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1368 error = kern_fstat(td, uap->fd, &ub);
1370 cvtnstat(&ub, &nub);
1371 error = copyout(&nub, uap->sb, sizeof(nub));
1377 * Return pathconf information about a file descriptor.
1379 #ifndef _SYS_SYSPROTO_H_
1380 struct fpathconf_args {
1387 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1391 cap_rights_t rights;
1394 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1398 if (uap->name == _PC_ASYNC_IO) {
1399 td->td_retval[0] = _POSIX_ASYNCHRONOUS_IO;
1404 vn_lock(vp, LK_SHARED | LK_RETRY);
1405 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1407 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1408 if (uap->name != _PC_PIPE_BUF) {
1411 td->td_retval[0] = PIPE_BUF;
1423 * Initialize filecaps structure.
1426 filecaps_init(struct filecaps *fcaps)
1429 bzero(fcaps, sizeof(*fcaps));
1430 fcaps->fc_nioctls = -1;
1434 * Copy filecaps structure allocating memory for ioctls array if needed.
1436 * The last parameter indicates whether the fdtable is locked. If it is not and
1437 * ioctls are encountered, copying fails and the caller must lock the table.
1439 * Note that if the table was not locked, the caller has to check the relevant
1440 * sequence counter to determine whether the operation was successful.
1443 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1448 if (src->fc_ioctls == NULL)
1453 KASSERT(src->fc_nioctls > 0,
1454 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1456 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1457 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1458 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1463 * Move filecaps structure to the new place and clear the old place.
1466 filecaps_move(struct filecaps *src, struct filecaps *dst)
1470 bzero(src, sizeof(*src));
1474 * Fill the given filecaps structure with full rights.
1477 filecaps_fill(struct filecaps *fcaps)
1480 CAP_ALL(&fcaps->fc_rights);
1481 fcaps->fc_ioctls = NULL;
1482 fcaps->fc_nioctls = -1;
1483 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1487 * Free memory allocated within filecaps structure.
1490 filecaps_free(struct filecaps *fcaps)
1493 free(fcaps->fc_ioctls, M_FILECAPS);
1494 bzero(fcaps, sizeof(*fcaps));
1498 * Validate the given filecaps structure.
1501 filecaps_validate(const struct filecaps *fcaps, const char *func)
1504 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1505 ("%s: invalid rights", func));
1506 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1507 ("%s: invalid fcntls", func));
1508 KASSERT(fcaps->fc_fcntls == 0 ||
1509 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1510 ("%s: fcntls without CAP_FCNTL", func));
1511 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1512 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1513 ("%s: invalid ioctls", func));
1514 KASSERT(fcaps->fc_nioctls == 0 ||
1515 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1516 ("%s: ioctls without CAP_IOCTL", func));
1520 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1524 FILEDESC_XLOCK_ASSERT(fdp);
1526 nfd1 = fdp->fd_nfiles * 2;
1529 fdgrowtable(fdp, nfd1);
1533 * Grow the file table to accommodate (at least) nfd descriptors.
1536 fdgrowtable(struct filedesc *fdp, int nfd)
1538 struct filedesc0 *fdp0;
1539 struct freetable *ft;
1540 struct fdescenttbl *ntable;
1541 struct fdescenttbl *otable;
1542 int nnfiles, onfiles;
1543 NDSLOTTYPE *nmap, *omap;
1546 * If lastfile is -1 this struct filedesc was just allocated and we are
1547 * growing it to accommodate for the one we are going to copy from. There
1548 * is no need to have a lock on this one as it's not visible to anyone.
1550 if (fdp->fd_lastfile != -1)
1551 FILEDESC_XLOCK_ASSERT(fdp);
1553 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1555 /* save old values */
1556 onfiles = fdp->fd_nfiles;
1557 otable = fdp->fd_files;
1560 /* compute the size of the new table */
1561 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1562 if (nnfiles <= onfiles)
1563 /* the table is already large enough */
1567 * Allocate a new table. We need enough space for the number of
1568 * entries, file entries themselves and the struct freetable we will use
1569 * when we decommission the table and place it on the freelist.
1570 * We place the struct freetable in the middle so we don't have
1571 * to worry about padding.
1573 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1574 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1575 sizeof(struct freetable),
1576 M_FILEDESC, M_ZERO | M_WAITOK);
1577 /* copy the old data */
1578 ntable->fdt_nfiles = nnfiles;
1579 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1580 onfiles * sizeof(ntable->fdt_ofiles[0]));
1583 * Allocate a new map only if the old is not large enough. It will
1584 * grow at a slower rate than the table as it can map more
1585 * entries than the table can hold.
1587 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1588 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1590 /* copy over the old data and update the pointer */
1591 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1596 * Make sure that ntable is correctly initialized before we replace
1597 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1600 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1603 * Do not free the old file table, as some threads may still
1604 * reference entries within it. Instead, place it on a freelist
1605 * which will be processed when the struct filedesc is released.
1607 * Note that if onfiles == NDFILE, we're dealing with the original
1608 * static allocation contained within (struct filedesc0 *)fdp,
1609 * which must not be freed.
1611 if (onfiles > NDFILE) {
1612 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1613 fdp0 = (struct filedesc0 *)fdp;
1614 ft->ft_table = otable;
1615 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1618 * The map does not have the same possibility of threads still
1619 * holding references to it. So always free it as long as it
1620 * does not reference the original static allocation.
1622 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1623 free(omap, M_FILEDESC);
1627 * Allocate a file descriptor for the process.
1630 fdalloc(struct thread *td, int minfd, int *result)
1632 struct proc *p = td->td_proc;
1633 struct filedesc *fdp = p->p_fd;
1634 int fd, maxfd, allocfd;
1639 FILEDESC_XLOCK_ASSERT(fdp);
1641 if (fdp->fd_freefile > minfd)
1642 minfd = fdp->fd_freefile;
1644 maxfd = getmaxfd(td);
1647 * Search the bitmap for a free descriptor starting at minfd.
1648 * If none is found, grow the file table.
1650 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1653 if (fd >= fdp->fd_nfiles) {
1654 allocfd = min(fd * 2, maxfd);
1658 error = racct_set(p, RACCT_NOFILE, allocfd);
1665 * fd is already equal to first free descriptor >= minfd, so
1666 * we only need to grow the table and we are done.
1668 fdgrowtable_exp(fdp, allocfd);
1672 * Perform some sanity checks, then mark the file descriptor as
1673 * used and return it to the caller.
1675 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1676 ("invalid descriptor %d", fd));
1677 KASSERT(!fdisused(fdp, fd),
1678 ("fd_first_free() returned non-free descriptor"));
1679 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1680 ("file descriptor isn't free"));
1687 * Allocate n file descriptors for the process.
1690 fdallocn(struct thread *td, int minfd, int *fds, int n)
1692 struct proc *p = td->td_proc;
1693 struct filedesc *fdp = p->p_fd;
1696 FILEDESC_XLOCK_ASSERT(fdp);
1698 for (i = 0; i < n; i++)
1699 if (fdalloc(td, 0, &fds[i]) != 0)
1703 for (i--; i >= 0; i--)
1704 fdunused(fdp, fds[i]);
1712 * Create a new open file structure and allocate a file descriptor for the
1713 * process that refers to it. We add one reference to the file for the
1714 * descriptor table and one reference for resultfp. This is to prevent us
1715 * being preempted and the entry in the descriptor table closed after we
1716 * release the FILEDESC lock.
1719 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1720 struct filecaps *fcaps)
1725 error = falloc_noinstall(td, &fp);
1727 return (error); /* no reference held on error */
1729 error = finstall(td, fp, &fd, flags, fcaps);
1731 fdrop(fp, td); /* one reference (fp only) */
1735 if (resultfp != NULL)
1736 *resultfp = fp; /* copy out result */
1738 fdrop(fp, td); /* release local reference */
1740 if (resultfd != NULL)
1747 * Create a new open file structure without allocating a file descriptor.
1750 falloc_noinstall(struct thread *td, struct file **resultfp)
1753 int maxuserfiles = maxfiles - (maxfiles / 20);
1754 static struct timeval lastfail;
1757 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1759 if ((openfiles >= maxuserfiles &&
1760 priv_check(td, PRIV_MAXFILES) != 0) ||
1761 openfiles >= maxfiles) {
1762 if (ppsratecheck(&lastfail, &curfail, 1)) {
1763 printf("kern.maxfiles limit exceeded by uid %i, "
1764 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1768 atomic_add_int(&openfiles, 1);
1769 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1770 refcount_init(&fp->f_count, 1);
1771 fp->f_cred = crhold(td->td_ucred);
1772 fp->f_ops = &badfileops;
1778 * Install a file in a file descriptor table.
1781 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1782 struct filecaps *fcaps)
1784 struct filedescent *fde;
1788 filecaps_validate(fcaps, __func__);
1789 FILEDESC_XLOCK_ASSERT(fdp);
1791 fde = &fdp->fd_ofiles[fd];
1793 seq_write_begin(&fde->fde_seq);
1796 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1798 filecaps_move(fcaps, &fde->fde_caps);
1800 filecaps_fill(&fde->fde_caps);
1802 seq_write_end(&fde->fde_seq);
1807 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1808 struct filecaps *fcaps)
1810 struct filedesc *fdp = td->td_proc->p_fd;
1815 FILEDESC_XLOCK(fdp);
1816 if ((error = fdalloc(td, 0, fd))) {
1817 FILEDESC_XUNLOCK(fdp);
1821 _finstall(fdp, fp, *fd, flags, fcaps);
1822 FILEDESC_XUNLOCK(fdp);
1827 * Build a new filedesc structure from another.
1828 * Copy the current, root, and jail root vnode references.
1830 * If fdp is not NULL, return with it shared locked.
1833 fdinit(struct filedesc *fdp, bool prepfiles)
1835 struct filedesc0 *newfdp0;
1836 struct filedesc *newfdp;
1838 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1839 newfdp = &newfdp0->fd_fd;
1841 /* Create the file descriptor table. */
1842 FILEDESC_LOCK_INIT(newfdp);
1843 refcount_init(&newfdp->fd_refcnt, 1);
1844 refcount_init(&newfdp->fd_holdcnt, 1);
1845 newfdp->fd_cmask = CMASK;
1846 newfdp->fd_map = newfdp0->fd_dmap;
1847 newfdp->fd_lastfile = -1;
1848 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
1849 newfdp->fd_files->fdt_nfiles = NDFILE;
1854 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
1855 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1857 FILEDESC_SLOCK(fdp);
1858 newfdp->fd_cdir = fdp->fd_cdir;
1859 if (newfdp->fd_cdir)
1860 VREF(newfdp->fd_cdir);
1861 newfdp->fd_rdir = fdp->fd_rdir;
1862 if (newfdp->fd_rdir)
1863 VREF(newfdp->fd_rdir);
1864 newfdp->fd_jdir = fdp->fd_jdir;
1865 if (newfdp->fd_jdir)
1866 VREF(newfdp->fd_jdir);
1869 FILEDESC_SUNLOCK(fdp);
1871 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1872 FILEDESC_SUNLOCK(fdp);
1873 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1874 FILEDESC_SLOCK(fdp);
1881 static struct filedesc *
1882 fdhold(struct proc *p)
1884 struct filedesc *fdp;
1886 PROC_LOCK_ASSERT(p, MA_OWNED);
1889 refcount_acquire(&fdp->fd_holdcnt);
1894 fddrop(struct filedesc *fdp)
1897 if (fdp->fd_holdcnt > 1) {
1898 if (refcount_release(&fdp->fd_holdcnt) == 0)
1902 FILEDESC_LOCK_DESTROY(fdp);
1903 uma_zfree(filedesc0_zone, fdp);
1907 * Share a filedesc structure.
1910 fdshare(struct filedesc *fdp)
1913 refcount_acquire(&fdp->fd_refcnt);
1918 * Unshare a filedesc structure, if necessary by making a copy
1921 fdunshare(struct thread *td)
1923 struct filedesc *tmp;
1924 struct proc *p = td->td_proc;
1926 if (p->p_fd->fd_refcnt == 1)
1929 tmp = fdcopy(p->p_fd);
1935 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
1939 td->td_proc->p_fd = fdp;
1943 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1944 * this is to ease callers, not catch errors.
1947 fdcopy(struct filedesc *fdp)
1949 struct filedesc *newfdp;
1950 struct filedescent *nfde, *ofde;
1955 newfdp = fdinit(fdp, true);
1956 /* copy all passable descriptors (i.e. not kqueue) */
1957 newfdp->fd_freefile = -1;
1958 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1959 ofde = &fdp->fd_ofiles[i];
1960 if (ofde->fde_file == NULL ||
1961 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
1962 if (newfdp->fd_freefile == -1)
1963 newfdp->fd_freefile = i;
1966 nfde = &newfdp->fd_ofiles[i];
1968 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
1969 fhold(nfde->fde_file);
1970 fdused_init(newfdp, i);
1971 newfdp->fd_lastfile = i;
1973 if (newfdp->fd_freefile == -1)
1974 newfdp->fd_freefile = i;
1975 newfdp->fd_cmask = fdp->fd_cmask;
1976 FILEDESC_SUNLOCK(fdp);
1981 * Copies a filedesc structure, while remapping all file descriptors
1982 * stored inside using a translation table.
1984 * File descriptors are copied over to the new file descriptor table,
1985 * regardless of whether the close-on-exec flag is set.
1988 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
1989 struct filedesc **ret)
1991 struct filedesc *newfdp;
1992 struct filedescent *nfde, *ofde;
1997 newfdp = fdinit(fdp, true);
1998 if (nfds > fdp->fd_lastfile + 1) {
1999 /* New table cannot be larger than the old one. */
2003 /* Copy all passable descriptors (i.e. not kqueue). */
2004 newfdp->fd_freefile = nfds;
2005 for (i = 0; i < nfds; ++i) {
2006 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2007 /* File descriptor out of bounds. */
2011 ofde = &fdp->fd_ofiles[fds[i]];
2012 if (ofde->fde_file == NULL) {
2013 /* Unused file descriptor. */
2017 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2018 /* File descriptor cannot be passed. */
2022 nfde = &newfdp->fd_ofiles[i];
2024 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2025 fhold(nfde->fde_file);
2026 fdused_init(newfdp, i);
2027 newfdp->fd_lastfile = i;
2029 newfdp->fd_cmask = fdp->fd_cmask;
2030 FILEDESC_SUNLOCK(fdp);
2034 FILEDESC_SUNLOCK(fdp);
2035 fdescfree_remapped(newfdp);
2040 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2041 * one of processes using it exits) and the table used to be shared.
2044 fdclearlocks(struct thread *td)
2046 struct filedesc *fdp;
2047 struct filedesc_to_leader *fdtol;
2057 MPASS(fdtol != NULL);
2059 FILEDESC_XLOCK(fdp);
2060 KASSERT(fdtol->fdl_refcount > 0,
2061 ("filedesc_to_refcount botch: fdl_refcount=%d",
2062 fdtol->fdl_refcount));
2063 if (fdtol->fdl_refcount == 1 &&
2064 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2065 for (i = 0; i <= fdp->fd_lastfile; i++) {
2066 fp = fdp->fd_ofiles[i].fde_file;
2067 if (fp == NULL || fp->f_type != DTYPE_VNODE)
2070 FILEDESC_XUNLOCK(fdp);
2071 lf.l_whence = SEEK_SET;
2074 lf.l_type = F_UNLCK;
2076 (void) VOP_ADVLOCK(vp,
2077 (caddr_t)p->p_leader, F_UNLCK,
2079 FILEDESC_XLOCK(fdp);
2084 if (fdtol->fdl_refcount == 1) {
2085 if (fdp->fd_holdleaderscount > 0 &&
2086 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2088 * close() or kern_dup() has cleared a reference
2089 * in a shared file descriptor table.
2091 fdp->fd_holdleaderswakeup = 1;
2092 sx_sleep(&fdp->fd_holdleaderscount,
2093 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2096 if (fdtol->fdl_holdcount > 0) {
2098 * Ensure that fdtol->fdl_leader remains
2099 * valid in closef().
2101 fdtol->fdl_wakeup = 1;
2102 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2107 fdtol->fdl_refcount--;
2108 if (fdtol->fdl_refcount == 0 &&
2109 fdtol->fdl_holdcount == 0) {
2110 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2111 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2115 FILEDESC_XUNLOCK(fdp);
2117 free(fdtol, M_FILEDESC_TO_LEADER);
2121 * Release a filedesc structure.
2124 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2126 struct filedesc0 *fdp0;
2127 struct freetable *ft, *tft;
2128 struct filedescent *fde;
2132 for (i = 0; i <= fdp->fd_lastfile; i++) {
2133 fde = &fdp->fd_ofiles[i];
2138 (void) closef(fp, td);
2144 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2145 free(fdp->fd_map, M_FILEDESC);
2146 if (fdp->fd_nfiles > NDFILE)
2147 free(fdp->fd_files, M_FILEDESC);
2149 fdp0 = (struct filedesc0 *)fdp;
2150 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2151 free(ft->ft_table, M_FILEDESC);
2157 fdescfree(struct thread *td)
2160 struct filedesc *fdp;
2161 struct vnode *cdir, *jdir, *rdir;
2170 racct_set(p, RACCT_NOFILE, 0);
2175 if (p->p_fdtol != NULL)
2182 if (refcount_release(&fdp->fd_refcnt) == 0)
2185 FILEDESC_XLOCK(fdp);
2186 cdir = fdp->fd_cdir;
2187 fdp->fd_cdir = NULL;
2188 rdir = fdp->fd_rdir;
2189 fdp->fd_rdir = NULL;
2190 jdir = fdp->fd_jdir;
2191 fdp->fd_jdir = NULL;
2192 FILEDESC_XUNLOCK(fdp);
2201 fdescfree_fds(td, fdp, 1);
2205 fdescfree_remapped(struct filedesc *fdp)
2208 if (fdp->fd_cdir != NULL)
2209 vrele(fdp->fd_cdir);
2210 if (fdp->fd_rdir != NULL)
2211 vrele(fdp->fd_rdir);
2212 if (fdp->fd_jdir != NULL)
2213 vrele(fdp->fd_jdir);
2215 fdescfree_fds(curthread, fdp, 0);
2219 * For setugid programs, we don't want to people to use that setugidness
2220 * to generate error messages which write to a file which otherwise would
2221 * otherwise be off-limits to the process. We check for filesystems where
2222 * the vnode can change out from under us after execve (like [lin]procfs).
2224 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2225 * sufficient. We also don't check for setugidness since we know we are.
2228 is_unsafe(struct file *fp)
2232 if (fp->f_type != DTYPE_VNODE)
2236 return ((vp->v_vflag & VV_PROCDEP) != 0);
2240 * Make this setguid thing safe, if at all possible.
2243 fdsetugidsafety(struct thread *td)
2245 struct filedesc *fdp;
2249 fdp = td->td_proc->p_fd;
2250 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2251 MPASS(fdp->fd_nfiles >= 3);
2252 for (i = 0; i <= 2; i++) {
2253 fp = fdp->fd_ofiles[i].fde_file;
2254 if (fp != NULL && is_unsafe(fp)) {
2255 FILEDESC_XLOCK(fdp);
2256 knote_fdclose(td, i);
2258 * NULL-out descriptor prior to close to avoid
2259 * a race while close blocks.
2262 FILEDESC_XUNLOCK(fdp);
2263 (void) closef(fp, td);
2269 * If a specific file object occupies a specific file descriptor, close the
2270 * file descriptor entry and drop a reference on the file object. This is a
2271 * convenience function to handle a subsequent error in a function that calls
2272 * falloc() that handles the race that another thread might have closed the
2273 * file descriptor out from under the thread creating the file object.
2276 fdclose(struct thread *td, struct file *fp, int idx)
2278 struct filedesc *fdp = td->td_proc->p_fd;
2280 FILEDESC_XLOCK(fdp);
2281 if (fdp->fd_ofiles[idx].fde_file == fp) {
2283 FILEDESC_XUNLOCK(fdp);
2286 FILEDESC_XUNLOCK(fdp);
2290 * Close any files on exec?
2293 fdcloseexec(struct thread *td)
2295 struct filedesc *fdp;
2296 struct filedescent *fde;
2300 fdp = td->td_proc->p_fd;
2301 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2302 for (i = 0; i <= fdp->fd_lastfile; i++) {
2303 fde = &fdp->fd_ofiles[i];
2305 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2306 (fde->fde_flags & UF_EXCLOSE))) {
2307 FILEDESC_XLOCK(fdp);
2309 (void) closefp(fdp, i, fp, td, 0);
2310 FILEDESC_UNLOCK_ASSERT(fdp);
2316 * It is unsafe for set[ug]id processes to be started with file
2317 * descriptors 0..2 closed, as these descriptors are given implicit
2318 * significance in the Standard C library. fdcheckstd() will create a
2319 * descriptor referencing /dev/null for each of stdin, stdout, and
2320 * stderr that is not already open.
2323 fdcheckstd(struct thread *td)
2325 struct filedesc *fdp;
2327 int i, error, devnull;
2329 fdp = td->td_proc->p_fd;
2330 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2331 MPASS(fdp->fd_nfiles >= 3);
2333 for (i = 0; i <= 2; i++) {
2334 if (fdp->fd_ofiles[i].fde_file != NULL)
2337 save = td->td_retval[0];
2338 if (devnull != -1) {
2339 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2341 error = kern_openat(td, AT_FDCWD, "/dev/null",
2342 UIO_SYSSPACE, O_RDWR, 0);
2344 devnull = td->td_retval[0];
2345 KASSERT(devnull == i, ("we didn't get our fd"));
2348 td->td_retval[0] = save;
2356 * Internal form of close. Decrement reference count on file structure.
2357 * Note: td may be NULL when closing a file that was being passed in a
2360 * XXXRW: Giant is not required for the caller, but often will be held; this
2361 * makes it moderately likely the Giant will be recursed in the VFS case.
2364 closef(struct file *fp, struct thread *td)
2368 struct filedesc_to_leader *fdtol;
2369 struct filedesc *fdp;
2372 * POSIX record locking dictates that any close releases ALL
2373 * locks owned by this process. This is handled by setting
2374 * a flag in the unlock to free ONLY locks obeying POSIX
2375 * semantics, and not to free BSD-style file locks.
2376 * If the descriptor was in a message, POSIX-style locks
2377 * aren't passed with the descriptor, and the thread pointer
2378 * will be NULL. Callers should be careful only to pass a
2379 * NULL thread pointer when there really is no owning
2380 * context that might have locks, or the locks will be
2383 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2385 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2386 lf.l_whence = SEEK_SET;
2389 lf.l_type = F_UNLCK;
2390 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2391 F_UNLCK, &lf, F_POSIX);
2393 fdtol = td->td_proc->p_fdtol;
2394 if (fdtol != NULL) {
2396 * Handle special case where file descriptor table is
2397 * shared between multiple process leaders.
2399 fdp = td->td_proc->p_fd;
2400 FILEDESC_XLOCK(fdp);
2401 for (fdtol = fdtol->fdl_next;
2402 fdtol != td->td_proc->p_fdtol;
2403 fdtol = fdtol->fdl_next) {
2404 if ((fdtol->fdl_leader->p_flag &
2407 fdtol->fdl_holdcount++;
2408 FILEDESC_XUNLOCK(fdp);
2409 lf.l_whence = SEEK_SET;
2412 lf.l_type = F_UNLCK;
2414 (void) VOP_ADVLOCK(vp,
2415 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2417 FILEDESC_XLOCK(fdp);
2418 fdtol->fdl_holdcount--;
2419 if (fdtol->fdl_holdcount == 0 &&
2420 fdtol->fdl_wakeup != 0) {
2421 fdtol->fdl_wakeup = 0;
2425 FILEDESC_XUNLOCK(fdp);
2428 return (fdrop(fp, td));
2432 * Initialize the file pointer with the specified properties.
2434 * The ops are set with release semantics to be certain that the flags, type,
2435 * and data are visible when ops is. This is to prevent ops methods from being
2436 * called with bad data.
2439 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2444 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2448 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2449 struct file **fpp, seq_t *seqp)
2452 struct filedescent *fde;
2454 struct fdescenttbl *fdt;
2459 cap_rights_t haverights;
2463 fdt = fdp->fd_files;
2464 if ((u_int)fd >= fdt->fdt_nfiles)
2467 * Fetch the descriptor locklessly. We avoid fdrop() races by
2468 * never raising a refcount above 0. To accomplish this we have
2469 * to use a cmpset loop rather than an atomic_add. The descriptor
2470 * must be re-verified once we acquire a reference to be certain
2471 * that the identity is still correct and we did not lose a race
2472 * due to preemption.
2476 seq = seq_read(fd_seq(fdt, fd));
2477 fde = &fdt->fdt_ofiles[fd];
2478 haverights = *cap_rights_fde(fde);
2480 if (!seq_consistent(fd_seq(fdt, fd), seq)) {
2485 fp = fdt->fdt_ofiles[fd].fde_file;
2490 error = cap_check(&haverights, needrightsp);
2495 count = fp->f_count;
2498 * Force a reload. Other thread could reallocate the
2499 * table before this fd was closed, so it possible that
2500 * there is a stale fp pointer in cached version.
2502 fdt = *(struct fdescenttbl * volatile *)&(fdp->fd_files);
2506 * Use an acquire barrier to force re-reading of fdt so it is
2507 * refreshed for verification.
2509 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) == 0)
2511 fdt = fdp->fd_files;
2513 if (seq_consistent_nomb(fd_seq(fdt, fd), seq))
2515 if (fp == fdt->fdt_ofiles[fd].fde_file)
2518 fdrop(fp, curthread);
2530 * Extract the file pointer associated with the specified descriptor for the
2531 * current user process.
2533 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2536 * File's rights will be checked against the capability rights mask.
2538 * If an error occurred the non-zero error is returned and *fpp is set to
2539 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2540 * responsible for fdrop().
2543 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2544 cap_rights_t *needrightsp, seq_t *seqp)
2546 struct filedesc *fdp;
2551 fdp = td->td_proc->p_fd;
2552 error = fget_unlocked(fdp, fd, needrightsp, &fp, seqp);
2555 if (fp->f_ops == &badfileops) {
2561 * FREAD and FWRITE failure return EBADF as per POSIX.
2567 if ((fp->f_flag & flags) == 0)
2571 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2572 ((fp->f_flag & FWRITE) != 0))
2578 KASSERT(0, ("wrong flags"));
2591 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2594 return (_fget(td, fd, fpp, 0, rightsp, NULL));
2598 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2602 #ifndef CAPABILITIES
2603 error = _fget(td, fd, fpp, 0, rightsp, NULL);
2604 if (maxprotp != NULL)
2605 *maxprotp = VM_PROT_ALL;
2607 struct filedesc *fdp = td->td_proc->p_fd;
2610 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2612 error = _fget(td, fd, fpp, 0, rightsp, &seq);
2616 * If requested, convert capability rights to access flags.
2618 if (maxprotp != NULL)
2619 *maxprotp = cap_rights_to_vmprot(cap_rights(fdp, fd));
2620 if (!fd_modified(fdp, fd, seq))
2629 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2632 return (_fget(td, fd, fpp, FREAD, rightsp, NULL));
2636 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2639 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2643 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2646 struct filedesc *fdp = td->td_proc->p_fd;
2647 #ifndef CAPABILITIES
2648 return (fget_unlocked(fdp, fd, rightsp, fpp, NULL));
2653 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2655 error = fget_unlocked(fdp, fd, rightsp, fpp, &seq);
2658 error = cap_fcntl_check(fdp, fd, needfcntl);
2659 if (!fd_modified(fdp, fd, seq))
2672 * Like fget() but loads the underlying vnode, or returns an error if the
2673 * descriptor does not represent a vnode. Note that pipes use vnodes but
2674 * never have VM objects. The returned vnode will be vref()'d.
2676 * XXX: what about the unused flags ?
2679 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2686 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2689 if (fp->f_vnode == NULL) {
2701 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2704 return (_fgetvp(td, fd, 0, rightsp, vpp));
2708 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2709 struct filecaps *havecaps, struct vnode **vpp)
2711 struct filedesc *fdp;
2717 fdp = td->td_proc->p_fd;
2718 fp = fget_locked(fdp, fd);
2719 if (fp == NULL || fp->f_ops == &badfileops)
2723 error = cap_check(cap_rights(fdp, fd), needrightsp);
2728 if (fp->f_vnode == NULL)
2733 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps, true);
2739 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2742 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2746 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2749 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2754 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2758 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2763 * Like fget() but loads the underlying socket, or returns an error if the
2764 * descriptor does not represent a socket.
2766 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2769 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2770 * on their file descriptor reference to prevent the socket from being free'd
2774 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2783 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2785 if (fp->f_type != DTYPE_SOCKET) {
2790 *fflagp = fp->f_flag;
2801 * Drop the reference count on the socket and XXX release the SX lock in the
2802 * future. The last reference closes the socket.
2804 * Note: fputsock() is deprecated, see comment for fgetsock().
2807 fputsock(struct socket *so)
2812 CURVNET_SET(so->so_vnet);
2818 * Handle the last reference to a file being closed.
2821 _fdrop(struct file *fp, struct thread *td)
2825 if (fp->f_count != 0)
2826 panic("fdrop: count %d", fp->f_count);
2827 error = fo_close(fp, td);
2828 atomic_subtract_int(&openfiles, 1);
2830 free(fp->f_advice, M_FADVISE);
2831 uma_zfree(file_zone, fp);
2837 * Apply an advisory lock on a file descriptor.
2839 * Just attempt to get a record lock of the requested type on the entire file
2840 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2842 #ifndef _SYS_SYSPROTO_H_
2850 sys_flock(struct thread *td, struct flock_args *uap)
2855 cap_rights_t rights;
2858 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2861 if (fp->f_type != DTYPE_VNODE) {
2863 return (EOPNOTSUPP);
2867 lf.l_whence = SEEK_SET;
2870 if (uap->how & LOCK_UN) {
2871 lf.l_type = F_UNLCK;
2872 atomic_clear_int(&fp->f_flag, FHASLOCK);
2873 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2876 if (uap->how & LOCK_EX)
2877 lf.l_type = F_WRLCK;
2878 else if (uap->how & LOCK_SH)
2879 lf.l_type = F_RDLCK;
2884 atomic_set_int(&fp->f_flag, FHASLOCK);
2885 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2886 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2892 * Duplicate the specified descriptor to a free descriptor.
2895 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2896 int openerror, int *indxp)
2898 struct filedescent *newfde, *oldfde;
2902 KASSERT(openerror == ENODEV || openerror == ENXIO,
2903 ("unexpected error %d in %s", openerror, __func__));
2906 * If the to-be-dup'd fd number is greater than the allowed number
2907 * of file descriptors, or the fd to be dup'd has already been
2908 * closed, then reject.
2910 FILEDESC_XLOCK(fdp);
2911 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2912 FILEDESC_XUNLOCK(fdp);
2916 error = fdalloc(td, 0, &indx);
2918 FILEDESC_XUNLOCK(fdp);
2923 * There are two cases of interest here.
2925 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2927 * For ENXIO steal away the file structure from (dfd) and store it in
2928 * (indx). (dfd) is effectively closed by this operation.
2930 switch (openerror) {
2933 * Check that the mode the file is being opened for is a
2934 * subset of the mode of the existing descriptor.
2936 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2937 fdunused(fdp, indx);
2938 FILEDESC_XUNLOCK(fdp);
2942 newfde = &fdp->fd_ofiles[indx];
2943 oldfde = &fdp->fd_ofiles[dfd];
2945 seq_write_begin(&newfde->fde_seq);
2947 memcpy(newfde, oldfde, fde_change_size);
2948 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps, true);
2950 seq_write_end(&newfde->fde_seq);
2955 * Steal away the file pointer from dfd and stuff it into indx.
2957 newfde = &fdp->fd_ofiles[indx];
2958 oldfde = &fdp->fd_ofiles[dfd];
2960 seq_write_begin(&newfde->fde_seq);
2962 memcpy(newfde, oldfde, fde_change_size);
2963 oldfde->fde_file = NULL;
2966 seq_write_end(&newfde->fde_seq);
2970 FILEDESC_XUNLOCK(fdp);
2976 * This sysctl determines if we will allow a process to chroot(2) if it
2977 * has a directory open:
2978 * 0: disallowed for all processes.
2979 * 1: allowed for processes that were not already chroot(2)'ed.
2980 * 2: allowed for all processes.
2983 static int chroot_allow_open_directories = 1;
2985 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
2986 &chroot_allow_open_directories, 0,
2987 "Allow a process to chroot(2) if it has a directory open");
2990 * Helper function for raised chroot(2) security function: Refuse if
2991 * any filedescriptors are open directories.
2994 chroot_refuse_vdir_fds(struct filedesc *fdp)
3000 FILEDESC_LOCK_ASSERT(fdp);
3002 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3003 fp = fget_locked(fdp, fd);
3006 if (fp->f_type == DTYPE_VNODE) {
3008 if (vp->v_type == VDIR)
3016 * Common routine for kern_chroot() and jail_attach(). The caller is
3017 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3018 * authorize this operation.
3021 pwd_chroot(struct thread *td, struct vnode *vp)
3023 struct filedesc *fdp;
3024 struct vnode *oldvp;
3027 fdp = td->td_proc->p_fd;
3028 FILEDESC_XLOCK(fdp);
3029 if (chroot_allow_open_directories == 0 ||
3030 (chroot_allow_open_directories == 1 && fdp->fd_rdir != rootvnode)) {
3031 error = chroot_refuse_vdir_fds(fdp);
3033 FILEDESC_XUNLOCK(fdp);
3037 oldvp = fdp->fd_rdir;
3040 if (fdp->fd_jdir == NULL) {
3044 FILEDESC_XUNLOCK(fdp);
3050 pwd_chdir(struct thread *td, struct vnode *vp)
3052 struct filedesc *fdp;
3053 struct vnode *oldvp;
3055 fdp = td->td_proc->p_fd;
3056 FILEDESC_XLOCK(fdp);
3057 VNASSERT(vp->v_usecount > 0, vp,
3058 ("chdir to a vnode with zero usecount"));
3059 oldvp = fdp->fd_cdir;
3061 FILEDESC_XUNLOCK(fdp);
3066 * Scan all active processes and prisons to see if any of them have a current
3067 * or root directory of `olddp'. If so, replace them with the new mount point.
3070 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3072 struct filedesc *fdp;
3077 if (vrefcnt(olddp) == 1)
3080 sx_slock(&allproc_lock);
3081 FOREACH_PROC_IN_SYSTEM(p) {
3087 FILEDESC_XLOCK(fdp);
3088 if (fdp->fd_cdir == olddp) {
3090 fdp->fd_cdir = newdp;
3093 if (fdp->fd_rdir == olddp) {
3095 fdp->fd_rdir = newdp;
3098 if (fdp->fd_jdir == olddp) {
3100 fdp->fd_jdir = newdp;
3103 FILEDESC_XUNLOCK(fdp);
3106 sx_sunlock(&allproc_lock);
3107 if (rootvnode == olddp) {
3112 mtx_lock(&prison0.pr_mtx);
3113 if (prison0.pr_root == olddp) {
3115 prison0.pr_root = newdp;
3118 mtx_unlock(&prison0.pr_mtx);
3119 sx_slock(&allprison_lock);
3120 TAILQ_FOREACH(pr, &allprison, pr_list) {
3121 mtx_lock(&pr->pr_mtx);
3122 if (pr->pr_root == olddp) {
3124 pr->pr_root = newdp;
3127 mtx_unlock(&pr->pr_mtx);
3129 sx_sunlock(&allprison_lock);
3134 struct filedesc_to_leader *
3135 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3137 struct filedesc_to_leader *fdtol;
3139 fdtol = malloc(sizeof(struct filedesc_to_leader),
3140 M_FILEDESC_TO_LEADER, M_WAITOK);
3141 fdtol->fdl_refcount = 1;
3142 fdtol->fdl_holdcount = 0;
3143 fdtol->fdl_wakeup = 0;
3144 fdtol->fdl_leader = leader;
3146 FILEDESC_XLOCK(fdp);
3147 fdtol->fdl_next = old->fdl_next;
3148 fdtol->fdl_prev = old;
3149 old->fdl_next = fdtol;
3150 fdtol->fdl_next->fdl_prev = fdtol;
3151 FILEDESC_XUNLOCK(fdp);
3153 fdtol->fdl_next = fdtol;
3154 fdtol->fdl_prev = fdtol;
3160 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3162 struct filedesc *fdp;
3163 int i, count, slots;
3165 if (*(int *)arg1 != 0)
3168 fdp = curproc->p_fd;
3170 FILEDESC_SLOCK(fdp);
3171 slots = NDSLOTS(fdp->fd_lastfile + 1);
3172 for (i = 0; i < slots; i++)
3173 count += bitcountl(fdp->fd_map[i]);
3174 FILEDESC_SUNLOCK(fdp);
3176 return (SYSCTL_OUT(req, &count, sizeof(count)));
3179 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3180 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3181 "Number of open file descriptors");
3184 * Get file structures globally.
3187 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3190 struct filedesc *fdp;
3195 error = sysctl_wire_old_buffer(req, 0);
3198 if (req->oldptr == NULL) {
3200 sx_slock(&allproc_lock);
3201 FOREACH_PROC_IN_SYSTEM(p) {
3203 if (p->p_state == PRS_NEW) {
3211 /* overestimates sparse tables. */
3212 if (fdp->fd_lastfile > 0)
3213 n += fdp->fd_lastfile;
3216 sx_sunlock(&allproc_lock);
3217 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3220 bzero(&xf, sizeof(xf));
3221 xf.xf_size = sizeof(xf);
3222 sx_slock(&allproc_lock);
3223 FOREACH_PROC_IN_SYSTEM(p) {
3225 if (p->p_state == PRS_NEW) {
3229 if (p_cansee(req->td, p) != 0) {
3233 xf.xf_pid = p->p_pid;
3234 xf.xf_uid = p->p_ucred->cr_uid;
3239 FILEDESC_SLOCK(fdp);
3240 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3241 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3245 xf.xf_data = fp->f_data;
3246 xf.xf_vnode = fp->f_vnode;
3247 xf.xf_type = fp->f_type;
3248 xf.xf_count = fp->f_count;
3250 xf.xf_offset = foffset_get(fp);
3251 xf.xf_flag = fp->f_flag;
3252 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3256 FILEDESC_SUNLOCK(fdp);
3261 sx_sunlock(&allproc_lock);
3265 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3266 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3268 #ifdef KINFO_FILE_SIZE
3269 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3273 xlate_fflags(int fflags)
3275 static const struct {
3278 } fflags_table[] = {
3279 { FAPPEND, KF_FLAG_APPEND },
3280 { FASYNC, KF_FLAG_ASYNC },
3281 { FFSYNC, KF_FLAG_FSYNC },
3282 { FHASLOCK, KF_FLAG_HASLOCK },
3283 { FNONBLOCK, KF_FLAG_NONBLOCK },
3284 { FREAD, KF_FLAG_READ },
3285 { FWRITE, KF_FLAG_WRITE },
3286 { O_CREAT, KF_FLAG_CREAT },
3287 { O_DIRECT, KF_FLAG_DIRECT },
3288 { O_EXCL, KF_FLAG_EXCL },
3289 { O_EXEC, KF_FLAG_EXEC },
3290 { O_EXLOCK, KF_FLAG_EXLOCK },
3291 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3292 { O_SHLOCK, KF_FLAG_SHLOCK },
3293 { O_TRUNC, KF_FLAG_TRUNC }
3299 for (i = 0; i < nitems(fflags_table); i++)
3300 if (fflags & fflags_table[i].fflag)
3301 kflags |= fflags_table[i].kf_fflag;
3305 /* Trim unused data from kf_path by truncating the structure size. */
3307 pack_kinfo(struct kinfo_file *kif)
3310 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3311 strlen(kif->kf_path) + 1;
3312 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3316 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3317 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3321 bzero(kif, sizeof(*kif));
3323 /* Set a default type to allow for empty fill_kinfo() methods. */
3324 kif->kf_type = KF_TYPE_UNKNOWN;
3325 kif->kf_flags = xlate_fflags(fp->f_flag);
3326 if (rightsp != NULL)
3327 kif->kf_cap_rights = *rightsp;
3329 cap_rights_init(&kif->kf_cap_rights);
3331 kif->kf_ref_count = fp->f_count;
3332 kif->kf_offset = foffset_get(fp);
3335 * This may drop the filedesc lock, so the 'fp' cannot be
3336 * accessed after this call.
3338 error = fo_fill_kinfo(fp, kif, fdp);
3340 kif->kf_status |= KF_ATTR_VALID;
3341 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3344 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3348 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3349 struct kinfo_file *kif, int flags)
3353 bzero(kif, sizeof(*kif));
3355 kif->kf_type = KF_TYPE_VNODE;
3356 error = vn_fill_kinfo_vnode(vp, kif);
3358 kif->kf_status |= KF_ATTR_VALID;
3359 kif->kf_flags = xlate_fflags(fflags);
3360 cap_rights_init(&kif->kf_cap_rights);
3362 kif->kf_ref_count = -1;
3363 kif->kf_offset = -1;
3364 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3367 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3371 struct export_fd_buf {
3372 struct filedesc *fdp;
3375 struct kinfo_file kif;
3380 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3382 struct kinfo_file *kif;
3385 if (efbuf->remainder != -1) {
3386 if (efbuf->remainder < kif->kf_structsize) {
3387 /* Terminate export. */
3388 efbuf->remainder = 0;
3391 efbuf->remainder -= kif->kf_structsize;
3393 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3397 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3398 struct export_fd_buf *efbuf)
3402 if (efbuf->remainder == 0)
3404 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3406 FILEDESC_SUNLOCK(efbuf->fdp);
3407 error = export_kinfo_to_sb(efbuf);
3408 FILEDESC_SLOCK(efbuf->fdp);
3413 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3414 struct export_fd_buf *efbuf)
3418 if (efbuf->remainder == 0)
3420 if (efbuf->fdp != NULL)
3421 FILEDESC_SUNLOCK(efbuf->fdp);
3422 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3423 error = export_kinfo_to_sb(efbuf);
3424 if (efbuf->fdp != NULL)
3425 FILEDESC_SLOCK(efbuf->fdp);
3430 * Store a process file descriptor information to sbuf.
3432 * Takes a locked proc as argument, and returns with the proc unlocked.
3435 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3439 struct filedesc *fdp;
3440 struct export_fd_buf *efbuf;
3441 struct vnode *cttyvp, *textvp, *tracevp;
3443 cap_rights_t rights;
3445 PROC_LOCK_ASSERT(p, MA_OWNED);
3448 tracevp = p->p_tracevp;
3449 if (tracevp != NULL)
3452 textvp = p->p_textvp;
3455 /* Controlling tty. */
3457 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3458 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3464 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3467 efbuf->remainder = maxlen;
3468 efbuf->flags = flags;
3469 if (tracevp != NULL)
3470 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3473 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3475 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3481 FILEDESC_SLOCK(fdp);
3482 /* working directory */
3483 if (fdp->fd_cdir != NULL) {
3485 export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3487 /* root directory */
3488 if (fdp->fd_rdir != NULL) {
3490 export_vnode_to_sb(fdp->fd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3492 /* jail directory */
3493 if (fdp->fd_jdir != NULL) {
3495 export_vnode_to_sb(fdp->fd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3497 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3498 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3501 rights = *cap_rights(fdp, i);
3502 #else /* !CAPABILITIES */
3503 cap_rights_init(&rights);
3506 * Create sysctl entry. It is OK to drop the filedesc
3507 * lock inside of export_file_to_sb() as we will
3508 * re-validate and re-evaluate its properties when the
3511 error = export_file_to_sb(fp, i, &rights, efbuf);
3512 if (error != 0 || efbuf->remainder == 0)
3515 FILEDESC_SUNLOCK(fdp);
3518 free(efbuf, M_TEMP);
3522 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3525 * Get per-process file descriptors for use by procstat(1), et al.
3528 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3533 int error, error2, *name;
3537 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3538 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3539 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3544 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3545 error = kern_proc_filedesc_out(p, &sb, maxlen,
3546 KERN_FILEDESC_PACK_KINFO);
3547 error2 = sbuf_finish(&sb);
3549 return (error != 0 ? error : error2);
3552 #ifdef KINFO_OFILE_SIZE
3553 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3556 #ifdef COMPAT_FREEBSD7
3558 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3561 okif->kf_structsize = sizeof(*okif);
3562 okif->kf_type = kif->kf_type;
3563 okif->kf_fd = kif->kf_fd;
3564 okif->kf_ref_count = kif->kf_ref_count;
3565 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3566 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3567 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3568 okif->kf_offset = kif->kf_offset;
3569 okif->kf_vnode_type = kif->kf_vnode_type;
3570 okif->kf_sock_domain = kif->kf_sock_domain;
3571 okif->kf_sock_type = kif->kf_sock_type;
3572 okif->kf_sock_protocol = kif->kf_sock_protocol;
3573 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3574 okif->kf_sa_local = kif->kf_sa_local;
3575 okif->kf_sa_peer = kif->kf_sa_peer;
3579 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3580 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3585 FILEDESC_SUNLOCK(fdp);
3586 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
3587 kinfo_to_okinfo(kif, okif);
3588 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3589 FILEDESC_SLOCK(fdp);
3594 * Get per-process file descriptors for use by procstat(1), et al.
3597 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3599 struct kinfo_ofile *okif;
3600 struct kinfo_file *kif;
3601 struct filedesc *fdp;
3602 int error, i, *name;
3607 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3614 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3615 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
3616 FILEDESC_SLOCK(fdp);
3617 if (fdp->fd_cdir != NULL)
3618 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3620 if (fdp->fd_rdir != NULL)
3621 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3623 if (fdp->fd_jdir != NULL)
3624 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3626 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3627 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3629 export_file_to_kinfo(fp, i, NULL, kif, fdp,
3630 KERN_FILEDESC_PACK_KINFO);
3631 FILEDESC_SUNLOCK(fdp);
3632 kinfo_to_okinfo(kif, okif);
3633 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3634 FILEDESC_SLOCK(fdp);
3638 FILEDESC_SUNLOCK(fdp);
3645 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3646 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3647 "Process ofiledesc entries");
3648 #endif /* COMPAT_FREEBSD7 */
3651 vntype_to_kinfo(int vtype)
3656 } vtypes_table[] = {
3657 { VBAD, KF_VTYPE_VBAD },
3658 { VBLK, KF_VTYPE_VBLK },
3659 { VCHR, KF_VTYPE_VCHR },
3660 { VDIR, KF_VTYPE_VDIR },
3661 { VFIFO, KF_VTYPE_VFIFO },
3662 { VLNK, KF_VTYPE_VLNK },
3663 { VNON, KF_VTYPE_VNON },
3664 { VREG, KF_VTYPE_VREG },
3665 { VSOCK, KF_VTYPE_VSOCK }
3670 * Perform vtype translation.
3672 for (i = 0; i < nitems(vtypes_table); i++)
3673 if (vtypes_table[i].vtype == vtype)
3674 return (vtypes_table[i].kf_vtype);
3676 return (KF_VTYPE_UNKNOWN);
3679 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3680 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3681 "Process filedesc entries");
3684 * Store a process current working directory information to sbuf.
3686 * Takes a locked proc as argument, and returns with the proc unlocked.
3689 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3691 struct filedesc *fdp;
3692 struct export_fd_buf *efbuf;
3695 PROC_LOCK_ASSERT(p, MA_OWNED);
3702 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3705 efbuf->remainder = maxlen;
3707 FILEDESC_SLOCK(fdp);
3708 if (fdp->fd_cdir == NULL)
3712 error = export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD,
3715 FILEDESC_SUNLOCK(fdp);
3717 free(efbuf, M_TEMP);
3722 * Get per-process current working directory.
3725 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
3730 int error, error2, *name;
3734 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
3735 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3736 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3741 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3742 error = kern_proc_cwd_out(p, &sb, maxlen);
3743 error2 = sbuf_finish(&sb);
3745 return (error != 0 ? error : error2);
3748 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
3749 sysctl_kern_proc_cwd, "Process current working directory");
3753 * For the purposes of debugging, generate a human-readable string for the
3757 file_type_to_name(short type)
3787 * For the purposes of debugging, identify a process (if any, perhaps one of
3788 * many) that references the passed file in its file descriptor array. Return
3791 static struct proc *
3792 file_to_first_proc(struct file *fp)
3794 struct filedesc *fdp;
3798 FOREACH_PROC_IN_SYSTEM(p) {
3799 if (p->p_state == PRS_NEW)
3804 for (n = 0; n <= fdp->fd_lastfile; n++) {
3805 if (fp == fdp->fd_ofiles[n].fde_file)
3813 db_print_file(struct file *fp, int header)
3818 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3819 "File", "Type", "Data", "Flag", "GCFl", "Count",
3820 "MCount", "Vnode", "FPID", "FCmd");
3821 p = file_to_first_proc(fp);
3822 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3823 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3824 0, fp->f_count, 0, fp->f_vnode,
3825 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3828 DB_SHOW_COMMAND(file, db_show_file)
3833 db_printf("usage: show file <addr>\n");
3836 fp = (struct file *)addr;
3837 db_print_file(fp, 1);
3840 DB_SHOW_COMMAND(files, db_show_files)
3842 struct filedesc *fdp;
3849 FOREACH_PROC_IN_SYSTEM(p) {
3850 if (p->p_state == PRS_NEW)
3852 if ((fdp = p->p_fd) == NULL)
3854 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3855 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3857 db_print_file(fp, header);
3864 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3865 &maxfilesperproc, 0, "Maximum files allowed open per process");
3867 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3868 &maxfiles, 0, "Maximum number of files");
3870 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3871 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3875 filelistinit(void *dummy)
3878 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3879 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3880 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
3881 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
3882 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3884 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3886 /*-------------------------------------------------------------------*/
3889 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3890 int flags, struct thread *td)
3897 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3905 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3913 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3921 badfo_kqfilter(struct file *fp, struct knote *kn)
3928 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3936 badfo_close(struct file *fp, struct thread *td)
3943 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3951 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3959 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3960 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3968 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
3974 struct fileops badfileops = {
3975 .fo_read = badfo_readwrite,
3976 .fo_write = badfo_readwrite,
3977 .fo_truncate = badfo_truncate,
3978 .fo_ioctl = badfo_ioctl,
3979 .fo_poll = badfo_poll,
3980 .fo_kqfilter = badfo_kqfilter,
3981 .fo_stat = badfo_stat,
3982 .fo_close = badfo_close,
3983 .fo_chmod = badfo_chmod,
3984 .fo_chown = badfo_chown,
3985 .fo_sendfile = badfo_sendfile,
3986 .fo_fill_kinfo = badfo_fill_kinfo,
3990 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
3991 int flags, struct thread *td)
3994 return (EOPNOTSUPP);
3998 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4006 invfo_ioctl(struct file *fp, u_long com, void *data,
4007 struct ucred *active_cred, struct thread *td)
4014 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4018 return (poll_no_poll(events));
4022 invfo_kqfilter(struct file *fp, struct knote *kn)
4029 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4037 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4045 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4046 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4053 /*-------------------------------------------------------------------*/
4056 * File Descriptor pseudo-device driver (/dev/fd/).
4058 * Opening minor device N dup()s the file (if any) connected to file
4059 * descriptor N belonging to the calling process. Note that this driver
4060 * consists of only the ``open()'' routine, because all subsequent
4061 * references to this file will be direct to the other driver.
4063 * XXX: we could give this one a cloning event handler if necessary.
4068 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4072 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4073 * the file descriptor being sought for duplication. The error
4074 * return ensures that the vnode for this device will be released
4075 * by vn_open. Open will detect this special error and take the
4076 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4077 * will simply report the error.
4079 td->td_dupfd = dev2unit(dev);
4083 static struct cdevsw fildesc_cdevsw = {
4084 .d_version = D_VERSION,
4090 fildesc_drvinit(void *unused)
4094 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4095 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4096 make_dev_alias(dev, "stdin");
4097 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4098 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4099 make_dev_alias(dev, "stdout");
4100 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4101 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4102 make_dev_alias(dev, "stderr");
4105 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);