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);
838 if (fget_locked(fdp, old) == NULL)
840 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
841 td->td_retval[0] = new;
842 if (flags & FDDUP_FLAG_CLOEXEC)
843 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
849 * If the caller specified a file descriptor, make sure the file
850 * table is large enough to hold it, and grab it. Otherwise, just
851 * allocate a new descriptor the usual way.
856 if ((error = fdalloc(td, new, &new)) != 0)
859 case FDDUP_MUSTREPLACE:
860 /* Target file descriptor must exist. */
861 if (fget_locked(fdp, new) == NULL)
865 if (new >= fdp->fd_nfiles) {
867 * The resource limits are here instead of e.g.
868 * fdalloc(), because the file descriptor table may be
869 * shared between processes, so we can't really use
870 * racct_add()/racct_sub(). Instead of counting the
871 * number of actually allocated descriptors, just put
872 * the limit on the size of the file descriptor table.
877 error = racct_set(p, RACCT_NOFILE, new + 1);
885 fdgrowtable_exp(fdp, new + 1);
887 if (!fdisused(fdp, new))
891 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
894 KASSERT(old != new, ("new fd is same as old"));
896 oldfde = &fdp->fd_ofiles[old];
897 fhold(oldfde->fde_file);
898 newfde = &fdp->fd_ofiles[new];
899 delfp = newfde->fde_file;
902 * Duplicate the source descriptor.
905 seq_write_begin(&newfde->fde_seq);
907 filecaps_free(&newfde->fde_caps);
908 memcpy(newfde, oldfde, fde_change_size);
909 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps, true);
910 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
911 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
913 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
915 seq_write_end(&newfde->fde_seq);
917 td->td_retval[0] = new;
922 (void) closefp(fdp, new, delfp, td, 1);
923 FILEDESC_UNLOCK_ASSERT(fdp);
926 FILEDESC_XUNLOCK(fdp);
933 * If sigio is on the list associated with a process or process group,
934 * disable signalling from the device, remove sigio from the list and
938 funsetown(struct sigio **sigiop)
948 *(sigio->sio_myref) = NULL;
949 if ((sigio)->sio_pgid < 0) {
950 struct pgrp *pg = (sigio)->sio_pgrp;
952 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
956 struct proc *p = (sigio)->sio_proc;
958 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
963 crfree(sigio->sio_ucred);
964 free(sigio, M_SIGIO);
968 * Free a list of sigio structures.
969 * We only need to lock the SIGIO_LOCK because we have made ourselves
970 * inaccessible to callers of fsetown and therefore do not need to lock
971 * the proc or pgrp struct for the list manipulation.
974 funsetownlst(struct sigiolst *sigiolst)
980 sigio = SLIST_FIRST(sigiolst);
987 * Every entry of the list should belong
988 * to a single proc or pgrp.
990 if (sigio->sio_pgid < 0) {
991 pg = sigio->sio_pgrp;
992 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
993 } else /* if (sigio->sio_pgid > 0) */ {
995 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
999 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1000 *(sigio->sio_myref) = NULL;
1002 KASSERT(sigio->sio_pgid < 0,
1003 ("Proc sigio in pgrp sigio list"));
1004 KASSERT(sigio->sio_pgrp == pg,
1005 ("Bogus pgrp in sigio list"));
1007 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1010 } else /* if (p != NULL) */ {
1011 KASSERT(sigio->sio_pgid > 0,
1012 ("Pgrp sigio in proc sigio list"));
1013 KASSERT(sigio->sio_proc == p,
1014 ("Bogus proc in sigio list"));
1016 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1021 crfree(sigio->sio_ucred);
1022 free(sigio, M_SIGIO);
1029 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1031 * After permission checking, add a sigio structure to the sigio list for
1032 * the process or process group.
1035 fsetown(pid_t pgid, struct sigio **sigiop)
1039 struct sigio *sigio;
1049 /* Allocate and fill in the new sigio out of locks. */
1050 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1051 sigio->sio_pgid = pgid;
1052 sigio->sio_ucred = crhold(curthread->td_ucred);
1053 sigio->sio_myref = sigiop;
1055 sx_slock(&proctree_lock);
1064 * Policy - Don't allow a process to FSETOWN a process
1065 * in another session.
1067 * Remove this test to allow maximum flexibility or
1068 * restrict FSETOWN to the current process or process
1069 * group for maximum safety.
1072 if (proc->p_session != curthread->td_proc->p_session) {
1078 } else /* if (pgid < 0) */ {
1079 pgrp = pgfind(-pgid);
1087 * Policy - Don't allow a process to FSETOWN a process
1088 * in another session.
1090 * Remove this test to allow maximum flexibility or
1091 * restrict FSETOWN to the current process or process
1092 * group for maximum safety.
1094 if (pgrp->pg_session != curthread->td_proc->p_session) {
1105 * Since funsetownlst() is called without the proctree
1106 * locked, we need to check for P_WEXIT.
1107 * XXX: is ESRCH correct?
1109 if ((proc->p_flag & P_WEXIT) != 0) {
1114 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1115 sigio->sio_proc = proc;
1119 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1120 sigio->sio_pgrp = pgrp;
1123 sx_sunlock(&proctree_lock);
1130 sx_sunlock(&proctree_lock);
1131 crfree(sigio->sio_ucred);
1132 free(sigio, M_SIGIO);
1137 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1141 struct sigio **sigiop;
1146 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1152 * Function drops the filedesc lock on return.
1155 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1160 FILEDESC_XLOCK_ASSERT(fdp);
1163 if (td->td_proc->p_fdtol != NULL) {
1165 * Ask fdfree() to sleep to ensure that all relevant
1166 * process leaders can be traversed in closef().
1168 fdp->fd_holdleaderscount++;
1175 * We now hold the fp reference that used to be owned by the
1176 * descriptor array. We have to unlock the FILEDESC *AFTER*
1177 * knote_fdclose to prevent a race of the fd getting opened, a knote
1178 * added, and deleteing a knote for the new fd.
1180 knote_fdclose(td, fd);
1183 * We need to notify mqueue if the object is of type mqueue.
1185 if (fp->f_type == DTYPE_MQUEUE)
1186 mq_fdclose(td, fd, fp);
1187 FILEDESC_XUNLOCK(fdp);
1189 error = closef(fp, td);
1191 FILEDESC_XLOCK(fdp);
1192 fdp->fd_holdleaderscount--;
1193 if (fdp->fd_holdleaderscount == 0 &&
1194 fdp->fd_holdleaderswakeup != 0) {
1195 fdp->fd_holdleaderswakeup = 0;
1196 wakeup(&fdp->fd_holdleaderscount);
1198 FILEDESC_XUNLOCK(fdp);
1204 * Close a file descriptor.
1206 #ifndef _SYS_SYSPROTO_H_
1213 sys_close(struct thread *td, struct close_args *uap)
1216 return (kern_close(td, uap->fd));
1220 kern_close(struct thread *td, int fd)
1222 struct filedesc *fdp;
1225 fdp = td->td_proc->p_fd;
1227 AUDIT_SYSCLOSE(td, fd);
1229 FILEDESC_XLOCK(fdp);
1230 if ((fp = fget_locked(fdp, fd)) == NULL) {
1231 FILEDESC_XUNLOCK(fdp);
1236 /* closefp() drops the FILEDESC lock for us. */
1237 return (closefp(fdp, fd, fp, td, 1));
1241 * Close open file descriptors.
1243 #ifndef _SYS_SYSPROTO_H_
1244 struct closefrom_args {
1250 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1252 struct filedesc *fdp;
1255 fdp = td->td_proc->p_fd;
1256 AUDIT_ARG_FD(uap->lowfd);
1259 * Treat negative starting file descriptor values identical to
1260 * closefrom(0) which closes all files.
1264 FILEDESC_SLOCK(fdp);
1265 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1266 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1267 FILEDESC_SUNLOCK(fdp);
1268 (void)kern_close(td, fd);
1269 FILEDESC_SLOCK(fdp);
1272 FILEDESC_SUNLOCK(fdp);
1276 #if defined(COMPAT_43)
1278 * Return status information about a file descriptor.
1280 #ifndef _SYS_SYSPROTO_H_
1281 struct ofstat_args {
1288 ofstat(struct thread *td, struct ofstat_args *uap)
1294 error = kern_fstat(td, uap->fd, &ub);
1297 error = copyout(&oub, uap->sb, sizeof(oub));
1301 #endif /* COMPAT_43 */
1304 * Return status information about a file descriptor.
1306 #ifndef _SYS_SYSPROTO_H_
1314 sys_fstat(struct thread *td, struct fstat_args *uap)
1319 error = kern_fstat(td, uap->fd, &ub);
1321 error = copyout(&ub, uap->sb, sizeof(ub));
1326 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1329 cap_rights_t rights;
1334 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1338 AUDIT_ARG_FILE(td->td_proc, fp);
1340 error = fo_stat(fp, sbp, td->td_ucred, td);
1343 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1350 * Return status information about a file descriptor.
1352 #ifndef _SYS_SYSPROTO_H_
1353 struct nfstat_args {
1360 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1366 error = kern_fstat(td, uap->fd, &ub);
1368 cvtnstat(&ub, &nub);
1369 error = copyout(&nub, uap->sb, sizeof(nub));
1375 * Return pathconf information about a file descriptor.
1377 #ifndef _SYS_SYSPROTO_H_
1378 struct fpathconf_args {
1385 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1389 cap_rights_t rights;
1392 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1396 if (uap->name == _PC_ASYNC_IO) {
1397 td->td_retval[0] = _POSIX_ASYNCHRONOUS_IO;
1402 vn_lock(vp, LK_SHARED | LK_RETRY);
1403 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1405 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1406 if (uap->name != _PC_PIPE_BUF) {
1409 td->td_retval[0] = PIPE_BUF;
1421 * Initialize filecaps structure.
1424 filecaps_init(struct filecaps *fcaps)
1427 bzero(fcaps, sizeof(*fcaps));
1428 fcaps->fc_nioctls = -1;
1432 * Copy filecaps structure allocating memory for ioctls array if needed.
1434 * The last parameter indicates whether the fdtable is locked. If it is not and
1435 * ioctls are encountered, copying fails and the caller must lock the table.
1437 * Note that if the table was not locked, the caller has to check the relevant
1438 * sequence counter to determine whether the operation was successful.
1441 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1446 if (src->fc_ioctls == NULL)
1451 KASSERT(src->fc_nioctls > 0,
1452 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1454 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1455 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1456 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1461 * Move filecaps structure to the new place and clear the old place.
1464 filecaps_move(struct filecaps *src, struct filecaps *dst)
1468 bzero(src, sizeof(*src));
1472 * Fill the given filecaps structure with full rights.
1475 filecaps_fill(struct filecaps *fcaps)
1478 CAP_ALL(&fcaps->fc_rights);
1479 fcaps->fc_ioctls = NULL;
1480 fcaps->fc_nioctls = -1;
1481 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1485 * Free memory allocated within filecaps structure.
1488 filecaps_free(struct filecaps *fcaps)
1491 free(fcaps->fc_ioctls, M_FILECAPS);
1492 bzero(fcaps, sizeof(*fcaps));
1496 * Validate the given filecaps structure.
1499 filecaps_validate(const struct filecaps *fcaps, const char *func)
1502 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1503 ("%s: invalid rights", func));
1504 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1505 ("%s: invalid fcntls", func));
1506 KASSERT(fcaps->fc_fcntls == 0 ||
1507 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1508 ("%s: fcntls without CAP_FCNTL", func));
1509 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1510 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1511 ("%s: invalid ioctls", func));
1512 KASSERT(fcaps->fc_nioctls == 0 ||
1513 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1514 ("%s: ioctls without CAP_IOCTL", func));
1518 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1522 FILEDESC_XLOCK_ASSERT(fdp);
1524 nfd1 = fdp->fd_nfiles * 2;
1527 fdgrowtable(fdp, nfd1);
1531 * Grow the file table to accommodate (at least) nfd descriptors.
1534 fdgrowtable(struct filedesc *fdp, int nfd)
1536 struct filedesc0 *fdp0;
1537 struct freetable *ft;
1538 struct fdescenttbl *ntable;
1539 struct fdescenttbl *otable;
1540 int nnfiles, onfiles;
1541 NDSLOTTYPE *nmap, *omap;
1544 * If lastfile is -1 this struct filedesc was just allocated and we are
1545 * growing it to accommodate for the one we are going to copy from. There
1546 * is no need to have a lock on this one as it's not visible to anyone.
1548 if (fdp->fd_lastfile != -1)
1549 FILEDESC_XLOCK_ASSERT(fdp);
1551 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1553 /* save old values */
1554 onfiles = fdp->fd_nfiles;
1555 otable = fdp->fd_files;
1558 /* compute the size of the new table */
1559 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1560 if (nnfiles <= onfiles)
1561 /* the table is already large enough */
1565 * Allocate a new table. We need enough space for the number of
1566 * entries, file entries themselves and the struct freetable we will use
1567 * when we decommission the table and place it on the freelist.
1568 * We place the struct freetable in the middle so we don't have
1569 * to worry about padding.
1571 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1572 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1573 sizeof(struct freetable),
1574 M_FILEDESC, M_ZERO | M_WAITOK);
1575 /* copy the old data */
1576 ntable->fdt_nfiles = nnfiles;
1577 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1578 onfiles * sizeof(ntable->fdt_ofiles[0]));
1581 * Allocate a new map only if the old is not large enough. It will
1582 * grow at a slower rate than the table as it can map more
1583 * entries than the table can hold.
1585 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1586 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1588 /* copy over the old data and update the pointer */
1589 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1594 * Make sure that ntable is correctly initialized before we replace
1595 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1598 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1601 * Do not free the old file table, as some threads may still
1602 * reference entries within it. Instead, place it on a freelist
1603 * which will be processed when the struct filedesc is released.
1605 * Note that if onfiles == NDFILE, we're dealing with the original
1606 * static allocation contained within (struct filedesc0 *)fdp,
1607 * which must not be freed.
1609 if (onfiles > NDFILE) {
1610 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1611 fdp0 = (struct filedesc0 *)fdp;
1612 ft->ft_table = otable;
1613 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1616 * The map does not have the same possibility of threads still
1617 * holding references to it. So always free it as long as it
1618 * does not reference the original static allocation.
1620 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1621 free(omap, M_FILEDESC);
1625 * Allocate a file descriptor for the process.
1628 fdalloc(struct thread *td, int minfd, int *result)
1630 struct proc *p = td->td_proc;
1631 struct filedesc *fdp = p->p_fd;
1632 int fd, maxfd, allocfd;
1637 FILEDESC_XLOCK_ASSERT(fdp);
1639 if (fdp->fd_freefile > minfd)
1640 minfd = fdp->fd_freefile;
1642 maxfd = getmaxfd(td);
1645 * Search the bitmap for a free descriptor starting at minfd.
1646 * If none is found, grow the file table.
1648 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1651 if (fd >= fdp->fd_nfiles) {
1652 allocfd = min(fd * 2, maxfd);
1656 error = racct_set(p, RACCT_NOFILE, allocfd);
1663 * fd is already equal to first free descriptor >= minfd, so
1664 * we only need to grow the table and we are done.
1666 fdgrowtable_exp(fdp, allocfd);
1670 * Perform some sanity checks, then mark the file descriptor as
1671 * used and return it to the caller.
1673 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1674 ("invalid descriptor %d", fd));
1675 KASSERT(!fdisused(fdp, fd),
1676 ("fd_first_free() returned non-free descriptor"));
1677 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1678 ("file descriptor isn't free"));
1685 * Allocate n file descriptors for the process.
1688 fdallocn(struct thread *td, int minfd, int *fds, int n)
1690 struct proc *p = td->td_proc;
1691 struct filedesc *fdp = p->p_fd;
1694 FILEDESC_XLOCK_ASSERT(fdp);
1696 for (i = 0; i < n; i++)
1697 if (fdalloc(td, 0, &fds[i]) != 0)
1701 for (i--; i >= 0; i--)
1702 fdunused(fdp, fds[i]);
1710 * Create a new open file structure and allocate a file descriptor for the
1711 * process that refers to it. We add one reference to the file for the
1712 * descriptor table and one reference for resultfp. This is to prevent us
1713 * being preempted and the entry in the descriptor table closed after we
1714 * release the FILEDESC lock.
1717 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1718 struct filecaps *fcaps)
1723 error = falloc_noinstall(td, &fp);
1725 return (error); /* no reference held on error */
1727 error = finstall(td, fp, &fd, flags, fcaps);
1729 fdrop(fp, td); /* one reference (fp only) */
1733 if (resultfp != NULL)
1734 *resultfp = fp; /* copy out result */
1736 fdrop(fp, td); /* release local reference */
1738 if (resultfd != NULL)
1745 * Create a new open file structure without allocating a file descriptor.
1748 falloc_noinstall(struct thread *td, struct file **resultfp)
1751 int maxuserfiles = maxfiles - (maxfiles / 20);
1752 static struct timeval lastfail;
1755 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1757 if ((openfiles >= maxuserfiles &&
1758 priv_check(td, PRIV_MAXFILES) != 0) ||
1759 openfiles >= maxfiles) {
1760 if (ppsratecheck(&lastfail, &curfail, 1)) {
1761 printf("kern.maxfiles limit exceeded by uid %i, "
1762 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1766 atomic_add_int(&openfiles, 1);
1767 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1768 refcount_init(&fp->f_count, 1);
1769 fp->f_cred = crhold(td->td_ucred);
1770 fp->f_ops = &badfileops;
1776 * Install a file in a file descriptor table.
1779 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1780 struct filecaps *fcaps)
1782 struct filedescent *fde;
1786 filecaps_validate(fcaps, __func__);
1787 FILEDESC_XLOCK_ASSERT(fdp);
1789 fde = &fdp->fd_ofiles[fd];
1791 seq_write_begin(&fde->fde_seq);
1794 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1796 filecaps_move(fcaps, &fde->fde_caps);
1798 filecaps_fill(&fde->fde_caps);
1800 seq_write_end(&fde->fde_seq);
1805 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1806 struct filecaps *fcaps)
1808 struct filedesc *fdp = td->td_proc->p_fd;
1813 FILEDESC_XLOCK(fdp);
1814 if ((error = fdalloc(td, 0, fd))) {
1815 FILEDESC_XUNLOCK(fdp);
1819 _finstall(fdp, fp, *fd, flags, fcaps);
1820 FILEDESC_XUNLOCK(fdp);
1825 * Build a new filedesc structure from another.
1826 * Copy the current, root, and jail root vnode references.
1828 * If fdp is not NULL, return with it shared locked.
1831 fdinit(struct filedesc *fdp, bool prepfiles)
1833 struct filedesc0 *newfdp0;
1834 struct filedesc *newfdp;
1836 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1837 newfdp = &newfdp0->fd_fd;
1839 /* Create the file descriptor table. */
1840 FILEDESC_LOCK_INIT(newfdp);
1841 refcount_init(&newfdp->fd_refcnt, 1);
1842 refcount_init(&newfdp->fd_holdcnt, 1);
1843 newfdp->fd_cmask = CMASK;
1844 newfdp->fd_map = newfdp0->fd_dmap;
1845 newfdp->fd_lastfile = -1;
1846 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
1847 newfdp->fd_files->fdt_nfiles = NDFILE;
1852 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
1853 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1855 FILEDESC_SLOCK(fdp);
1856 newfdp->fd_cdir = fdp->fd_cdir;
1857 if (newfdp->fd_cdir)
1858 VREF(newfdp->fd_cdir);
1859 newfdp->fd_rdir = fdp->fd_rdir;
1860 if (newfdp->fd_rdir)
1861 VREF(newfdp->fd_rdir);
1862 newfdp->fd_jdir = fdp->fd_jdir;
1863 if (newfdp->fd_jdir)
1864 VREF(newfdp->fd_jdir);
1867 FILEDESC_SUNLOCK(fdp);
1869 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1870 FILEDESC_SUNLOCK(fdp);
1871 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1872 FILEDESC_SLOCK(fdp);
1879 static struct filedesc *
1880 fdhold(struct proc *p)
1882 struct filedesc *fdp;
1884 PROC_LOCK_ASSERT(p, MA_OWNED);
1887 refcount_acquire(&fdp->fd_holdcnt);
1892 fddrop(struct filedesc *fdp)
1895 if (fdp->fd_holdcnt > 1) {
1896 if (refcount_release(&fdp->fd_holdcnt) == 0)
1900 FILEDESC_LOCK_DESTROY(fdp);
1901 uma_zfree(filedesc0_zone, fdp);
1905 * Share a filedesc structure.
1908 fdshare(struct filedesc *fdp)
1911 refcount_acquire(&fdp->fd_refcnt);
1916 * Unshare a filedesc structure, if necessary by making a copy
1919 fdunshare(struct thread *td)
1921 struct filedesc *tmp;
1922 struct proc *p = td->td_proc;
1924 if (p->p_fd->fd_refcnt == 1)
1927 tmp = fdcopy(p->p_fd);
1933 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
1937 td->td_proc->p_fd = fdp;
1941 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1942 * this is to ease callers, not catch errors.
1945 fdcopy(struct filedesc *fdp)
1947 struct filedesc *newfdp;
1948 struct filedescent *nfde, *ofde;
1953 newfdp = fdinit(fdp, true);
1954 /* copy all passable descriptors (i.e. not kqueue) */
1955 newfdp->fd_freefile = -1;
1956 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1957 ofde = &fdp->fd_ofiles[i];
1958 if (ofde->fde_file == NULL ||
1959 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
1960 if (newfdp->fd_freefile == -1)
1961 newfdp->fd_freefile = i;
1964 nfde = &newfdp->fd_ofiles[i];
1966 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
1967 fhold(nfde->fde_file);
1968 fdused_init(newfdp, i);
1969 newfdp->fd_lastfile = i;
1971 if (newfdp->fd_freefile == -1)
1972 newfdp->fd_freefile = i;
1973 newfdp->fd_cmask = fdp->fd_cmask;
1974 FILEDESC_SUNLOCK(fdp);
1979 * Copies a filedesc structure, while remapping all file descriptors
1980 * stored inside using a translation table.
1982 * File descriptors are copied over to the new file descriptor table,
1983 * regardless of whether the close-on-exec flag is set.
1986 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
1987 struct filedesc **ret)
1989 struct filedesc *newfdp;
1990 struct filedescent *nfde, *ofde;
1995 newfdp = fdinit(fdp, true);
1996 if (nfds > fdp->fd_lastfile + 1) {
1997 /* New table cannot be larger than the old one. */
2001 /* Copy all passable descriptors (i.e. not kqueue). */
2002 newfdp->fd_freefile = nfds;
2003 for (i = 0; i < nfds; ++i) {
2004 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2005 /* File descriptor out of bounds. */
2009 ofde = &fdp->fd_ofiles[fds[i]];
2010 if (ofde->fde_file == NULL) {
2011 /* Unused file descriptor. */
2015 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2016 /* File descriptor cannot be passed. */
2020 nfde = &newfdp->fd_ofiles[i];
2022 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2023 fhold(nfde->fde_file);
2024 fdused_init(newfdp, i);
2025 newfdp->fd_lastfile = i;
2027 newfdp->fd_cmask = fdp->fd_cmask;
2028 FILEDESC_SUNLOCK(fdp);
2032 FILEDESC_SUNLOCK(fdp);
2033 fdescfree_remapped(newfdp);
2038 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2039 * one of processes using it exits) and the table used to be shared.
2042 fdclearlocks(struct thread *td)
2044 struct filedesc *fdp;
2045 struct filedesc_to_leader *fdtol;
2055 MPASS(fdtol != NULL);
2057 FILEDESC_XLOCK(fdp);
2058 KASSERT(fdtol->fdl_refcount > 0,
2059 ("filedesc_to_refcount botch: fdl_refcount=%d",
2060 fdtol->fdl_refcount));
2061 if (fdtol->fdl_refcount == 1 &&
2062 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2063 for (i = 0; i <= fdp->fd_lastfile; i++) {
2064 fp = fdp->fd_ofiles[i].fde_file;
2065 if (fp == NULL || fp->f_type != DTYPE_VNODE)
2068 FILEDESC_XUNLOCK(fdp);
2069 lf.l_whence = SEEK_SET;
2072 lf.l_type = F_UNLCK;
2074 (void) VOP_ADVLOCK(vp,
2075 (caddr_t)p->p_leader, F_UNLCK,
2077 FILEDESC_XLOCK(fdp);
2082 if (fdtol->fdl_refcount == 1) {
2083 if (fdp->fd_holdleaderscount > 0 &&
2084 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2086 * close() or kern_dup() has cleared a reference
2087 * in a shared file descriptor table.
2089 fdp->fd_holdleaderswakeup = 1;
2090 sx_sleep(&fdp->fd_holdleaderscount,
2091 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2094 if (fdtol->fdl_holdcount > 0) {
2096 * Ensure that fdtol->fdl_leader remains
2097 * valid in closef().
2099 fdtol->fdl_wakeup = 1;
2100 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2105 fdtol->fdl_refcount--;
2106 if (fdtol->fdl_refcount == 0 &&
2107 fdtol->fdl_holdcount == 0) {
2108 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2109 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2113 FILEDESC_XUNLOCK(fdp);
2115 free(fdtol, M_FILEDESC_TO_LEADER);
2119 * Release a filedesc structure.
2122 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2124 struct filedesc0 *fdp0;
2125 struct freetable *ft, *tft;
2126 struct filedescent *fde;
2130 for (i = 0; i <= fdp->fd_lastfile; i++) {
2131 fde = &fdp->fd_ofiles[i];
2136 (void) closef(fp, td);
2142 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2143 free(fdp->fd_map, M_FILEDESC);
2144 if (fdp->fd_nfiles > NDFILE)
2145 free(fdp->fd_files, M_FILEDESC);
2147 fdp0 = (struct filedesc0 *)fdp;
2148 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2149 free(ft->ft_table, M_FILEDESC);
2155 fdescfree(struct thread *td)
2158 struct filedesc *fdp;
2159 struct vnode *cdir, *jdir, *rdir;
2168 racct_set(p, RACCT_NOFILE, 0);
2173 if (p->p_fdtol != NULL)
2180 if (refcount_release(&fdp->fd_refcnt) == 0)
2183 FILEDESC_XLOCK(fdp);
2184 cdir = fdp->fd_cdir;
2185 fdp->fd_cdir = NULL;
2186 rdir = fdp->fd_rdir;
2187 fdp->fd_rdir = NULL;
2188 jdir = fdp->fd_jdir;
2189 fdp->fd_jdir = NULL;
2190 FILEDESC_XUNLOCK(fdp);
2199 fdescfree_fds(td, fdp, 1);
2203 fdescfree_remapped(struct filedesc *fdp)
2206 if (fdp->fd_cdir != NULL)
2207 vrele(fdp->fd_cdir);
2208 if (fdp->fd_rdir != NULL)
2209 vrele(fdp->fd_rdir);
2210 if (fdp->fd_jdir != NULL)
2211 vrele(fdp->fd_jdir);
2213 fdescfree_fds(curthread, fdp, 0);
2217 * For setugid programs, we don't want to people to use that setugidness
2218 * to generate error messages which write to a file which otherwise would
2219 * otherwise be off-limits to the process. We check for filesystems where
2220 * the vnode can change out from under us after execve (like [lin]procfs).
2222 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2223 * sufficient. We also don't check for setugidness since we know we are.
2226 is_unsafe(struct file *fp)
2230 if (fp->f_type != DTYPE_VNODE)
2234 return ((vp->v_vflag & VV_PROCDEP) != 0);
2238 * Make this setguid thing safe, if at all possible.
2241 fdsetugidsafety(struct thread *td)
2243 struct filedesc *fdp;
2247 fdp = td->td_proc->p_fd;
2248 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2249 MPASS(fdp->fd_nfiles >= 3);
2250 for (i = 0; i <= 2; i++) {
2251 fp = fdp->fd_ofiles[i].fde_file;
2252 if (fp != NULL && is_unsafe(fp)) {
2253 FILEDESC_XLOCK(fdp);
2254 knote_fdclose(td, i);
2256 * NULL-out descriptor prior to close to avoid
2257 * a race while close blocks.
2260 FILEDESC_XUNLOCK(fdp);
2261 (void) closef(fp, td);
2267 * If a specific file object occupies a specific file descriptor, close the
2268 * file descriptor entry and drop a reference on the file object. This is a
2269 * convenience function to handle a subsequent error in a function that calls
2270 * falloc() that handles the race that another thread might have closed the
2271 * file descriptor out from under the thread creating the file object.
2274 fdclose(struct thread *td, struct file *fp, int idx)
2276 struct filedesc *fdp = td->td_proc->p_fd;
2278 FILEDESC_XLOCK(fdp);
2279 if (fdp->fd_ofiles[idx].fde_file == fp) {
2281 FILEDESC_XUNLOCK(fdp);
2284 FILEDESC_XUNLOCK(fdp);
2288 * Close any files on exec?
2291 fdcloseexec(struct thread *td)
2293 struct filedesc *fdp;
2294 struct filedescent *fde;
2298 fdp = td->td_proc->p_fd;
2299 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2300 for (i = 0; i <= fdp->fd_lastfile; i++) {
2301 fde = &fdp->fd_ofiles[i];
2303 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2304 (fde->fde_flags & UF_EXCLOSE))) {
2305 FILEDESC_XLOCK(fdp);
2307 (void) closefp(fdp, i, fp, td, 0);
2308 FILEDESC_UNLOCK_ASSERT(fdp);
2314 * It is unsafe for set[ug]id processes to be started with file
2315 * descriptors 0..2 closed, as these descriptors are given implicit
2316 * significance in the Standard C library. fdcheckstd() will create a
2317 * descriptor referencing /dev/null for each of stdin, stdout, and
2318 * stderr that is not already open.
2321 fdcheckstd(struct thread *td)
2323 struct filedesc *fdp;
2325 int i, error, devnull;
2327 fdp = td->td_proc->p_fd;
2328 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2329 MPASS(fdp->fd_nfiles >= 3);
2331 for (i = 0; i <= 2; i++) {
2332 if (fdp->fd_ofiles[i].fde_file != NULL)
2335 save = td->td_retval[0];
2336 if (devnull != -1) {
2337 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2339 error = kern_openat(td, AT_FDCWD, "/dev/null",
2340 UIO_SYSSPACE, O_RDWR, 0);
2342 devnull = td->td_retval[0];
2343 KASSERT(devnull == i, ("we didn't get our fd"));
2346 td->td_retval[0] = save;
2354 * Internal form of close. Decrement reference count on file structure.
2355 * Note: td may be NULL when closing a file that was being passed in a
2358 * XXXRW: Giant is not required for the caller, but often will be held; this
2359 * makes it moderately likely the Giant will be recursed in the VFS case.
2362 closef(struct file *fp, struct thread *td)
2366 struct filedesc_to_leader *fdtol;
2367 struct filedesc *fdp;
2370 * POSIX record locking dictates that any close releases ALL
2371 * locks owned by this process. This is handled by setting
2372 * a flag in the unlock to free ONLY locks obeying POSIX
2373 * semantics, and not to free BSD-style file locks.
2374 * If the descriptor was in a message, POSIX-style locks
2375 * aren't passed with the descriptor, and the thread pointer
2376 * will be NULL. Callers should be careful only to pass a
2377 * NULL thread pointer when there really is no owning
2378 * context that might have locks, or the locks will be
2381 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2383 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2384 lf.l_whence = SEEK_SET;
2387 lf.l_type = F_UNLCK;
2388 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2389 F_UNLCK, &lf, F_POSIX);
2391 fdtol = td->td_proc->p_fdtol;
2392 if (fdtol != NULL) {
2394 * Handle special case where file descriptor table is
2395 * shared between multiple process leaders.
2397 fdp = td->td_proc->p_fd;
2398 FILEDESC_XLOCK(fdp);
2399 for (fdtol = fdtol->fdl_next;
2400 fdtol != td->td_proc->p_fdtol;
2401 fdtol = fdtol->fdl_next) {
2402 if ((fdtol->fdl_leader->p_flag &
2405 fdtol->fdl_holdcount++;
2406 FILEDESC_XUNLOCK(fdp);
2407 lf.l_whence = SEEK_SET;
2410 lf.l_type = F_UNLCK;
2412 (void) VOP_ADVLOCK(vp,
2413 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2415 FILEDESC_XLOCK(fdp);
2416 fdtol->fdl_holdcount--;
2417 if (fdtol->fdl_holdcount == 0 &&
2418 fdtol->fdl_wakeup != 0) {
2419 fdtol->fdl_wakeup = 0;
2423 FILEDESC_XUNLOCK(fdp);
2426 return (fdrop(fp, td));
2430 * Initialize the file pointer with the specified properties.
2432 * The ops are set with release semantics to be certain that the flags, type,
2433 * and data are visible when ops is. This is to prevent ops methods from being
2434 * called with bad data.
2437 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2442 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2446 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2447 struct file **fpp, seq_t *seqp)
2450 struct filedescent *fde;
2452 struct fdescenttbl *fdt;
2457 cap_rights_t haverights;
2461 fdt = fdp->fd_files;
2462 if ((u_int)fd >= fdt->fdt_nfiles)
2465 * Fetch the descriptor locklessly. We avoid fdrop() races by
2466 * never raising a refcount above 0. To accomplish this we have
2467 * to use a cmpset loop rather than an atomic_add. The descriptor
2468 * must be re-verified once we acquire a reference to be certain
2469 * that the identity is still correct and we did not lose a race
2470 * due to preemption.
2474 seq = seq_read(fd_seq(fdt, fd));
2475 fde = &fdt->fdt_ofiles[fd];
2476 haverights = *cap_rights_fde(fde);
2478 if (!seq_consistent(fd_seq(fdt, fd), seq)) {
2483 fp = fdt->fdt_ofiles[fd].fde_file;
2488 error = cap_check(&haverights, needrightsp);
2493 count = fp->f_count;
2496 * Force a reload. Other thread could reallocate the
2497 * table before this fd was closed, so it possible that
2498 * there is a stale fp pointer in cached version.
2500 fdt = *(struct fdescenttbl * volatile *)&(fdp->fd_files);
2504 * Use an acquire barrier to force re-reading of fdt so it is
2505 * refreshed for verification.
2507 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) == 0)
2509 fdt = fdp->fd_files;
2511 if (seq_consistent_nomb(fd_seq(fdt, fd), seq))
2513 if (fp == fdt->fdt_ofiles[fd].fde_file)
2516 fdrop(fp, curthread);
2528 * Extract the file pointer associated with the specified descriptor for the
2529 * current user process.
2531 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2534 * File's rights will be checked against the capability rights mask.
2536 * If an error occurred the non-zero error is returned and *fpp is set to
2537 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2538 * responsible for fdrop().
2541 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2542 cap_rights_t *needrightsp, seq_t *seqp)
2544 struct filedesc *fdp;
2549 fdp = td->td_proc->p_fd;
2550 error = fget_unlocked(fdp, fd, needrightsp, &fp, seqp);
2553 if (fp->f_ops == &badfileops) {
2559 * FREAD and FWRITE failure return EBADF as per POSIX.
2565 if ((fp->f_flag & flags) == 0)
2569 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2570 ((fp->f_flag & FWRITE) != 0))
2576 KASSERT(0, ("wrong flags"));
2589 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2592 return (_fget(td, fd, fpp, 0, rightsp, NULL));
2596 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2600 #ifndef CAPABILITIES
2601 error = _fget(td, fd, fpp, 0, rightsp, NULL);
2602 if (maxprotp != NULL)
2603 *maxprotp = VM_PROT_ALL;
2605 struct filedesc *fdp = td->td_proc->p_fd;
2608 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2610 error = _fget(td, fd, fpp, 0, rightsp, &seq);
2614 * If requested, convert capability rights to access flags.
2616 if (maxprotp != NULL)
2617 *maxprotp = cap_rights_to_vmprot(cap_rights(fdp, fd));
2618 if (!fd_modified(fdp, fd, seq))
2627 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2630 return (_fget(td, fd, fpp, FREAD, rightsp, NULL));
2634 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2637 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2641 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2644 struct filedesc *fdp = td->td_proc->p_fd;
2645 #ifndef CAPABILITIES
2646 return (fget_unlocked(fdp, fd, rightsp, fpp, NULL));
2651 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2653 error = fget_unlocked(fdp, fd, rightsp, fpp, &seq);
2656 error = cap_fcntl_check(fdp, fd, needfcntl);
2657 if (!fd_modified(fdp, fd, seq))
2670 * Like fget() but loads the underlying vnode, or returns an error if the
2671 * descriptor does not represent a vnode. Note that pipes use vnodes but
2672 * never have VM objects. The returned vnode will be vref()'d.
2674 * XXX: what about the unused flags ?
2677 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2684 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2687 if (fp->f_vnode == NULL) {
2699 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2702 return (_fgetvp(td, fd, 0, rightsp, vpp));
2706 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2707 struct filecaps *havecaps, struct vnode **vpp)
2709 struct filedesc *fdp;
2715 fdp = td->td_proc->p_fd;
2716 fp = fget_locked(fdp, fd);
2717 if (fp == NULL || fp->f_ops == &badfileops)
2721 error = cap_check(cap_rights(fdp, fd), needrightsp);
2726 if (fp->f_vnode == NULL)
2731 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps, true);
2737 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2740 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2744 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2747 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2752 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2756 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2761 * Like fget() but loads the underlying socket, or returns an error if the
2762 * descriptor does not represent a socket.
2764 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2767 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2768 * on their file descriptor reference to prevent the socket from being free'd
2772 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2781 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2783 if (fp->f_type != DTYPE_SOCKET) {
2788 *fflagp = fp->f_flag;
2799 * Drop the reference count on the socket and XXX release the SX lock in the
2800 * future. The last reference closes the socket.
2802 * Note: fputsock() is deprecated, see comment for fgetsock().
2805 fputsock(struct socket *so)
2810 CURVNET_SET(so->so_vnet);
2816 * Handle the last reference to a file being closed.
2819 _fdrop(struct file *fp, struct thread *td)
2823 if (fp->f_count != 0)
2824 panic("fdrop: count %d", fp->f_count);
2825 error = fo_close(fp, td);
2826 atomic_subtract_int(&openfiles, 1);
2828 free(fp->f_advice, M_FADVISE);
2829 uma_zfree(file_zone, fp);
2835 * Apply an advisory lock on a file descriptor.
2837 * Just attempt to get a record lock of the requested type on the entire file
2838 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2840 #ifndef _SYS_SYSPROTO_H_
2848 sys_flock(struct thread *td, struct flock_args *uap)
2853 cap_rights_t rights;
2856 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2859 if (fp->f_type != DTYPE_VNODE) {
2861 return (EOPNOTSUPP);
2865 lf.l_whence = SEEK_SET;
2868 if (uap->how & LOCK_UN) {
2869 lf.l_type = F_UNLCK;
2870 atomic_clear_int(&fp->f_flag, FHASLOCK);
2871 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2874 if (uap->how & LOCK_EX)
2875 lf.l_type = F_WRLCK;
2876 else if (uap->how & LOCK_SH)
2877 lf.l_type = F_RDLCK;
2882 atomic_set_int(&fp->f_flag, FHASLOCK);
2883 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2884 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2890 * Duplicate the specified descriptor to a free descriptor.
2893 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2894 int openerror, int *indxp)
2896 struct filedescent *newfde, *oldfde;
2900 KASSERT(openerror == ENODEV || openerror == ENXIO,
2901 ("unexpected error %d in %s", openerror, __func__));
2904 * If the to-be-dup'd fd number is greater than the allowed number
2905 * of file descriptors, or the fd to be dup'd has already been
2906 * closed, then reject.
2908 FILEDESC_XLOCK(fdp);
2909 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2910 FILEDESC_XUNLOCK(fdp);
2914 error = fdalloc(td, 0, &indx);
2916 FILEDESC_XUNLOCK(fdp);
2921 * There are two cases of interest here.
2923 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2925 * For ENXIO steal away the file structure from (dfd) and store it in
2926 * (indx). (dfd) is effectively closed by this operation.
2928 switch (openerror) {
2931 * Check that the mode the file is being opened for is a
2932 * subset of the mode of the existing descriptor.
2934 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2935 fdunused(fdp, indx);
2936 FILEDESC_XUNLOCK(fdp);
2940 newfde = &fdp->fd_ofiles[indx];
2941 oldfde = &fdp->fd_ofiles[dfd];
2943 seq_write_begin(&newfde->fde_seq);
2945 memcpy(newfde, oldfde, fde_change_size);
2946 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps, true);
2948 seq_write_end(&newfde->fde_seq);
2953 * Steal away the file pointer from dfd and stuff it into indx.
2955 newfde = &fdp->fd_ofiles[indx];
2956 oldfde = &fdp->fd_ofiles[dfd];
2958 seq_write_begin(&newfde->fde_seq);
2960 memcpy(newfde, oldfde, fde_change_size);
2961 oldfde->fde_file = NULL;
2964 seq_write_end(&newfde->fde_seq);
2968 FILEDESC_XUNLOCK(fdp);
2974 * This sysctl determines if we will allow a process to chroot(2) if it
2975 * has a directory open:
2976 * 0: disallowed for all processes.
2977 * 1: allowed for processes that were not already chroot(2)'ed.
2978 * 2: allowed for all processes.
2981 static int chroot_allow_open_directories = 1;
2983 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
2984 &chroot_allow_open_directories, 0,
2985 "Allow a process to chroot(2) if it has a directory open");
2988 * Helper function for raised chroot(2) security function: Refuse if
2989 * any filedescriptors are open directories.
2992 chroot_refuse_vdir_fds(struct filedesc *fdp)
2998 FILEDESC_LOCK_ASSERT(fdp);
3000 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3001 fp = fget_locked(fdp, fd);
3004 if (fp->f_type == DTYPE_VNODE) {
3006 if (vp->v_type == VDIR)
3014 * Common routine for kern_chroot() and jail_attach(). The caller is
3015 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3016 * authorize this operation.
3019 pwd_chroot(struct thread *td, struct vnode *vp)
3021 struct filedesc *fdp;
3022 struct vnode *oldvp;
3025 fdp = td->td_proc->p_fd;
3026 FILEDESC_XLOCK(fdp);
3027 if (chroot_allow_open_directories == 0 ||
3028 (chroot_allow_open_directories == 1 && fdp->fd_rdir != rootvnode)) {
3029 error = chroot_refuse_vdir_fds(fdp);
3031 FILEDESC_XUNLOCK(fdp);
3035 oldvp = fdp->fd_rdir;
3038 if (fdp->fd_jdir == NULL) {
3042 FILEDESC_XUNLOCK(fdp);
3048 pwd_chdir(struct thread *td, struct vnode *vp)
3050 struct filedesc *fdp;
3051 struct vnode *oldvp;
3053 fdp = td->td_proc->p_fd;
3054 FILEDESC_XLOCK(fdp);
3055 VNASSERT(vp->v_usecount > 0, vp,
3056 ("chdir to a vnode with zero usecount"));
3057 oldvp = fdp->fd_cdir;
3059 FILEDESC_XUNLOCK(fdp);
3064 * Scan all active processes and prisons to see if any of them have a current
3065 * or root directory of `olddp'. If so, replace them with the new mount point.
3068 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3070 struct filedesc *fdp;
3075 if (vrefcnt(olddp) == 1)
3078 sx_slock(&allproc_lock);
3079 FOREACH_PROC_IN_SYSTEM(p) {
3085 FILEDESC_XLOCK(fdp);
3086 if (fdp->fd_cdir == olddp) {
3088 fdp->fd_cdir = newdp;
3091 if (fdp->fd_rdir == olddp) {
3093 fdp->fd_rdir = newdp;
3096 if (fdp->fd_jdir == olddp) {
3098 fdp->fd_jdir = newdp;
3101 FILEDESC_XUNLOCK(fdp);
3104 sx_sunlock(&allproc_lock);
3105 if (rootvnode == olddp) {
3110 mtx_lock(&prison0.pr_mtx);
3111 if (prison0.pr_root == olddp) {
3113 prison0.pr_root = newdp;
3116 mtx_unlock(&prison0.pr_mtx);
3117 sx_slock(&allprison_lock);
3118 TAILQ_FOREACH(pr, &allprison, pr_list) {
3119 mtx_lock(&pr->pr_mtx);
3120 if (pr->pr_root == olddp) {
3122 pr->pr_root = newdp;
3125 mtx_unlock(&pr->pr_mtx);
3127 sx_sunlock(&allprison_lock);
3132 struct filedesc_to_leader *
3133 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3135 struct filedesc_to_leader *fdtol;
3137 fdtol = malloc(sizeof(struct filedesc_to_leader),
3138 M_FILEDESC_TO_LEADER, M_WAITOK);
3139 fdtol->fdl_refcount = 1;
3140 fdtol->fdl_holdcount = 0;
3141 fdtol->fdl_wakeup = 0;
3142 fdtol->fdl_leader = leader;
3144 FILEDESC_XLOCK(fdp);
3145 fdtol->fdl_next = old->fdl_next;
3146 fdtol->fdl_prev = old;
3147 old->fdl_next = fdtol;
3148 fdtol->fdl_next->fdl_prev = fdtol;
3149 FILEDESC_XUNLOCK(fdp);
3151 fdtol->fdl_next = fdtol;
3152 fdtol->fdl_prev = fdtol;
3158 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3160 struct filedesc *fdp;
3161 int i, count, slots;
3163 if (*(int *)arg1 != 0)
3166 fdp = curproc->p_fd;
3168 FILEDESC_SLOCK(fdp);
3169 slots = NDSLOTS(fdp->fd_lastfile + 1);
3170 for (i = 0; i < slots; i++)
3171 count += bitcountl(fdp->fd_map[i]);
3172 FILEDESC_SUNLOCK(fdp);
3174 return (SYSCTL_OUT(req, &count, sizeof(count)));
3177 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3178 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3179 "Number of open file descriptors");
3182 * Get file structures globally.
3185 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3188 struct filedesc *fdp;
3193 error = sysctl_wire_old_buffer(req, 0);
3196 if (req->oldptr == NULL) {
3198 sx_slock(&allproc_lock);
3199 FOREACH_PROC_IN_SYSTEM(p) {
3201 if (p->p_state == PRS_NEW) {
3209 /* overestimates sparse tables. */
3210 if (fdp->fd_lastfile > 0)
3211 n += fdp->fd_lastfile;
3214 sx_sunlock(&allproc_lock);
3215 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3218 bzero(&xf, sizeof(xf));
3219 xf.xf_size = sizeof(xf);
3220 sx_slock(&allproc_lock);
3221 FOREACH_PROC_IN_SYSTEM(p) {
3223 if (p->p_state == PRS_NEW) {
3227 if (p_cansee(req->td, p) != 0) {
3231 xf.xf_pid = p->p_pid;
3232 xf.xf_uid = p->p_ucred->cr_uid;
3237 FILEDESC_SLOCK(fdp);
3238 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3239 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3243 xf.xf_data = fp->f_data;
3244 xf.xf_vnode = fp->f_vnode;
3245 xf.xf_type = fp->f_type;
3246 xf.xf_count = fp->f_count;
3248 xf.xf_offset = foffset_get(fp);
3249 xf.xf_flag = fp->f_flag;
3250 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3254 FILEDESC_SUNLOCK(fdp);
3259 sx_sunlock(&allproc_lock);
3263 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3264 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3266 #ifdef KINFO_FILE_SIZE
3267 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3271 xlate_fflags(int fflags)
3273 static const struct {
3276 } fflags_table[] = {
3277 { FAPPEND, KF_FLAG_APPEND },
3278 { FASYNC, KF_FLAG_ASYNC },
3279 { FFSYNC, KF_FLAG_FSYNC },
3280 { FHASLOCK, KF_FLAG_HASLOCK },
3281 { FNONBLOCK, KF_FLAG_NONBLOCK },
3282 { FREAD, KF_FLAG_READ },
3283 { FWRITE, KF_FLAG_WRITE },
3284 { O_CREAT, KF_FLAG_CREAT },
3285 { O_DIRECT, KF_FLAG_DIRECT },
3286 { O_EXCL, KF_FLAG_EXCL },
3287 { O_EXEC, KF_FLAG_EXEC },
3288 { O_EXLOCK, KF_FLAG_EXLOCK },
3289 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3290 { O_SHLOCK, KF_FLAG_SHLOCK },
3291 { O_TRUNC, KF_FLAG_TRUNC }
3297 for (i = 0; i < nitems(fflags_table); i++)
3298 if (fflags & fflags_table[i].fflag)
3299 kflags |= fflags_table[i].kf_fflag;
3303 /* Trim unused data from kf_path by truncating the structure size. */
3305 pack_kinfo(struct kinfo_file *kif)
3308 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3309 strlen(kif->kf_path) + 1;
3310 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3314 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3315 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3319 bzero(kif, sizeof(*kif));
3321 /* Set a default type to allow for empty fill_kinfo() methods. */
3322 kif->kf_type = KF_TYPE_UNKNOWN;
3323 kif->kf_flags = xlate_fflags(fp->f_flag);
3324 if (rightsp != NULL)
3325 kif->kf_cap_rights = *rightsp;
3327 cap_rights_init(&kif->kf_cap_rights);
3329 kif->kf_ref_count = fp->f_count;
3330 kif->kf_offset = foffset_get(fp);
3333 * This may drop the filedesc lock, so the 'fp' cannot be
3334 * accessed after this call.
3336 error = fo_fill_kinfo(fp, kif, fdp);
3338 kif->kf_status |= KF_ATTR_VALID;
3339 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3342 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3346 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3347 struct kinfo_file *kif, int flags)
3351 bzero(kif, sizeof(*kif));
3353 kif->kf_type = KF_TYPE_VNODE;
3354 error = vn_fill_kinfo_vnode(vp, kif);
3356 kif->kf_status |= KF_ATTR_VALID;
3357 kif->kf_flags = xlate_fflags(fflags);
3358 cap_rights_init(&kif->kf_cap_rights);
3360 kif->kf_ref_count = -1;
3361 kif->kf_offset = -1;
3362 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3365 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3369 struct export_fd_buf {
3370 struct filedesc *fdp;
3373 struct kinfo_file kif;
3378 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3380 struct kinfo_file *kif;
3383 if (efbuf->remainder != -1) {
3384 if (efbuf->remainder < kif->kf_structsize) {
3385 /* Terminate export. */
3386 efbuf->remainder = 0;
3389 efbuf->remainder -= kif->kf_structsize;
3391 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3395 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3396 struct export_fd_buf *efbuf)
3400 if (efbuf->remainder == 0)
3402 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3404 FILEDESC_SUNLOCK(efbuf->fdp);
3405 error = export_kinfo_to_sb(efbuf);
3406 FILEDESC_SLOCK(efbuf->fdp);
3411 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3412 struct export_fd_buf *efbuf)
3416 if (efbuf->remainder == 0)
3418 if (efbuf->fdp != NULL)
3419 FILEDESC_SUNLOCK(efbuf->fdp);
3420 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3421 error = export_kinfo_to_sb(efbuf);
3422 if (efbuf->fdp != NULL)
3423 FILEDESC_SLOCK(efbuf->fdp);
3428 * Store a process file descriptor information to sbuf.
3430 * Takes a locked proc as argument, and returns with the proc unlocked.
3433 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3437 struct filedesc *fdp;
3438 struct export_fd_buf *efbuf;
3439 struct vnode *cttyvp, *textvp, *tracevp;
3441 cap_rights_t rights;
3443 PROC_LOCK_ASSERT(p, MA_OWNED);
3446 tracevp = p->p_tracevp;
3447 if (tracevp != NULL)
3450 textvp = p->p_textvp;
3453 /* Controlling tty. */
3455 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3456 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3462 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3465 efbuf->remainder = maxlen;
3466 efbuf->flags = flags;
3467 if (tracevp != NULL)
3468 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3471 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3473 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3479 FILEDESC_SLOCK(fdp);
3480 /* working directory */
3481 if (fdp->fd_cdir != NULL) {
3483 export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3485 /* root directory */
3486 if (fdp->fd_rdir != NULL) {
3488 export_vnode_to_sb(fdp->fd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3490 /* jail directory */
3491 if (fdp->fd_jdir != NULL) {
3493 export_vnode_to_sb(fdp->fd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3495 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3496 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3499 rights = *cap_rights(fdp, i);
3500 #else /* !CAPABILITIES */
3501 cap_rights_init(&rights);
3504 * Create sysctl entry. It is OK to drop the filedesc
3505 * lock inside of export_file_to_sb() as we will
3506 * re-validate and re-evaluate its properties when the
3509 error = export_file_to_sb(fp, i, &rights, efbuf);
3510 if (error != 0 || efbuf->remainder == 0)
3513 FILEDESC_SUNLOCK(fdp);
3516 free(efbuf, M_TEMP);
3520 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3523 * Get per-process file descriptors for use by procstat(1), et al.
3526 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3531 int error, error2, *name;
3535 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3536 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3537 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3542 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3543 error = kern_proc_filedesc_out(p, &sb, maxlen,
3544 KERN_FILEDESC_PACK_KINFO);
3545 error2 = sbuf_finish(&sb);
3547 return (error != 0 ? error : error2);
3550 #ifdef KINFO_OFILE_SIZE
3551 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3554 #ifdef COMPAT_FREEBSD7
3556 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3559 okif->kf_structsize = sizeof(*okif);
3560 okif->kf_type = kif->kf_type;
3561 okif->kf_fd = kif->kf_fd;
3562 okif->kf_ref_count = kif->kf_ref_count;
3563 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3564 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3565 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3566 okif->kf_offset = kif->kf_offset;
3567 okif->kf_vnode_type = kif->kf_vnode_type;
3568 okif->kf_sock_domain = kif->kf_sock_domain;
3569 okif->kf_sock_type = kif->kf_sock_type;
3570 okif->kf_sock_protocol = kif->kf_sock_protocol;
3571 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3572 okif->kf_sa_local = kif->kf_sa_local;
3573 okif->kf_sa_peer = kif->kf_sa_peer;
3577 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3578 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3583 FILEDESC_SUNLOCK(fdp);
3584 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
3585 kinfo_to_okinfo(kif, okif);
3586 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3587 FILEDESC_SLOCK(fdp);
3592 * Get per-process file descriptors for use by procstat(1), et al.
3595 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3597 struct kinfo_ofile *okif;
3598 struct kinfo_file *kif;
3599 struct filedesc *fdp;
3600 int error, i, *name;
3605 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3612 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3613 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
3614 FILEDESC_SLOCK(fdp);
3615 if (fdp->fd_cdir != NULL)
3616 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3618 if (fdp->fd_rdir != NULL)
3619 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3621 if (fdp->fd_jdir != NULL)
3622 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3624 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3625 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3627 export_file_to_kinfo(fp, i, NULL, kif, fdp,
3628 KERN_FILEDESC_PACK_KINFO);
3629 FILEDESC_SUNLOCK(fdp);
3630 kinfo_to_okinfo(kif, okif);
3631 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3632 FILEDESC_SLOCK(fdp);
3636 FILEDESC_SUNLOCK(fdp);
3643 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3644 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3645 "Process ofiledesc entries");
3646 #endif /* COMPAT_FREEBSD7 */
3649 vntype_to_kinfo(int vtype)
3654 } vtypes_table[] = {
3655 { VBAD, KF_VTYPE_VBAD },
3656 { VBLK, KF_VTYPE_VBLK },
3657 { VCHR, KF_VTYPE_VCHR },
3658 { VDIR, KF_VTYPE_VDIR },
3659 { VFIFO, KF_VTYPE_VFIFO },
3660 { VLNK, KF_VTYPE_VLNK },
3661 { VNON, KF_VTYPE_VNON },
3662 { VREG, KF_VTYPE_VREG },
3663 { VSOCK, KF_VTYPE_VSOCK }
3668 * Perform vtype translation.
3670 for (i = 0; i < nitems(vtypes_table); i++)
3671 if (vtypes_table[i].vtype == vtype)
3672 return (vtypes_table[i].kf_vtype);
3674 return (KF_VTYPE_UNKNOWN);
3677 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3678 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3679 "Process filedesc entries");
3682 * Store a process current working directory information to sbuf.
3684 * Takes a locked proc as argument, and returns with the proc unlocked.
3687 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3689 struct filedesc *fdp;
3690 struct export_fd_buf *efbuf;
3693 PROC_LOCK_ASSERT(p, MA_OWNED);
3700 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3703 efbuf->remainder = maxlen;
3705 FILEDESC_SLOCK(fdp);
3706 if (fdp->fd_cdir == NULL)
3710 error = export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD,
3713 FILEDESC_SUNLOCK(fdp);
3715 free(efbuf, M_TEMP);
3720 * Get per-process current working directory.
3723 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
3728 int error, error2, *name;
3732 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
3733 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3734 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3739 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3740 error = kern_proc_cwd_out(p, &sb, maxlen);
3741 error2 = sbuf_finish(&sb);
3743 return (error != 0 ? error : error2);
3746 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
3747 sysctl_kern_proc_cwd, "Process current working directory");
3751 * For the purposes of debugging, generate a human-readable string for the
3755 file_type_to_name(short type)
3785 * For the purposes of debugging, identify a process (if any, perhaps one of
3786 * many) that references the passed file in its file descriptor array. Return
3789 static struct proc *
3790 file_to_first_proc(struct file *fp)
3792 struct filedesc *fdp;
3796 FOREACH_PROC_IN_SYSTEM(p) {
3797 if (p->p_state == PRS_NEW)
3802 for (n = 0; n <= fdp->fd_lastfile; n++) {
3803 if (fp == fdp->fd_ofiles[n].fde_file)
3811 db_print_file(struct file *fp, int header)
3816 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3817 "File", "Type", "Data", "Flag", "GCFl", "Count",
3818 "MCount", "Vnode", "FPID", "FCmd");
3819 p = file_to_first_proc(fp);
3820 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3821 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3822 0, fp->f_count, 0, fp->f_vnode,
3823 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3826 DB_SHOW_COMMAND(file, db_show_file)
3831 db_printf("usage: show file <addr>\n");
3834 fp = (struct file *)addr;
3835 db_print_file(fp, 1);
3838 DB_SHOW_COMMAND(files, db_show_files)
3840 struct filedesc *fdp;
3847 FOREACH_PROC_IN_SYSTEM(p) {
3848 if (p->p_state == PRS_NEW)
3850 if ((fdp = p->p_fd) == NULL)
3852 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3853 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3855 db_print_file(fp, header);
3862 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3863 &maxfilesperproc, 0, "Maximum files allowed open per process");
3865 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3866 &maxfiles, 0, "Maximum number of files");
3868 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3869 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3873 filelistinit(void *dummy)
3876 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3877 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3878 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
3879 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
3880 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3882 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3884 /*-------------------------------------------------------------------*/
3887 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3888 int flags, struct thread *td)
3895 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3903 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3911 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3919 badfo_kqfilter(struct file *fp, struct knote *kn)
3926 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3934 badfo_close(struct file *fp, struct thread *td)
3941 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3949 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3957 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3958 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3966 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
3972 struct fileops badfileops = {
3973 .fo_read = badfo_readwrite,
3974 .fo_write = badfo_readwrite,
3975 .fo_truncate = badfo_truncate,
3976 .fo_ioctl = badfo_ioctl,
3977 .fo_poll = badfo_poll,
3978 .fo_kqfilter = badfo_kqfilter,
3979 .fo_stat = badfo_stat,
3980 .fo_close = badfo_close,
3981 .fo_chmod = badfo_chmod,
3982 .fo_chown = badfo_chown,
3983 .fo_sendfile = badfo_sendfile,
3984 .fo_fill_kinfo = badfo_fill_kinfo,
3988 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
3989 int flags, struct thread *td)
3992 return (EOPNOTSUPP);
3996 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4004 invfo_ioctl(struct file *fp, u_long com, void *data,
4005 struct ucred *active_cred, struct thread *td)
4012 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4016 return (poll_no_poll(events));
4020 invfo_kqfilter(struct file *fp, struct knote *kn)
4027 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4035 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4043 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4044 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4051 /*-------------------------------------------------------------------*/
4054 * File Descriptor pseudo-device driver (/dev/fd/).
4056 * Opening minor device N dup()s the file (if any) connected to file
4057 * descriptor N belonging to the calling process. Note that this driver
4058 * consists of only the ``open()'' routine, because all subsequent
4059 * references to this file will be direct to the other driver.
4061 * XXX: we could give this one a cloning event handler if necessary.
4066 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4070 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4071 * the file descriptor being sought for duplication. The error
4072 * return ensures that the vnode for this device will be released
4073 * by vn_open. Open will detect this special error and take the
4074 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4075 * will simply report the error.
4077 td->td_dupfd = dev2unit(dev);
4081 static struct cdevsw fildesc_cdevsw = {
4082 .d_version = D_VERSION,
4088 fildesc_drvinit(void *unused)
4092 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4093 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4094 make_dev_alias(dev, "stdin");
4095 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4096 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4097 make_dev_alias(dev, "stdout");
4098 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4099 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4100 make_dev_alias(dev, "stderr");
4103 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);