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 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
827 * Verify we have a valid descriptor to dup from and possibly to
828 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
829 * return EINVAL when the new descriptor is out of bounds.
834 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
835 maxfd = getmaxfd(td);
837 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
841 if (fget_locked(fdp, old) == NULL)
843 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
844 td->td_retval[0] = new;
845 if (flags & FDDUP_FLAG_CLOEXEC)
846 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
852 * If the caller specified a file descriptor, make sure the file
853 * table is large enough to hold it, and grab it. Otherwise, just
854 * allocate a new descriptor the usual way.
859 if ((error = fdalloc(td, new, &new)) != 0)
862 case FDDUP_MUSTREPLACE:
863 /* Target file descriptor must exist. */
864 if (fget_locked(fdp, new) == NULL)
868 if (new >= fdp->fd_nfiles) {
870 * The resource limits are here instead of e.g.
871 * fdalloc(), because the file descriptor table may be
872 * shared between processes, so we can't really use
873 * racct_add()/racct_sub(). Instead of counting the
874 * number of actually allocated descriptors, just put
875 * the limit on the size of the file descriptor table.
880 error = racct_set(p, RACCT_NOFILE, new + 1);
888 fdgrowtable_exp(fdp, new + 1);
890 if (!fdisused(fdp, new))
894 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
897 KASSERT(old != new, ("new fd is same as old"));
899 oldfde = &fdp->fd_ofiles[old];
900 fhold(oldfde->fde_file);
901 newfde = &fdp->fd_ofiles[new];
902 delfp = newfde->fde_file;
905 * Duplicate the source descriptor.
908 seq_write_begin(&newfde->fde_seq);
910 filecaps_free(&newfde->fde_caps);
911 memcpy(newfde, oldfde, fde_change_size);
912 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps, true);
913 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
914 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
916 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
918 seq_write_end(&newfde->fde_seq);
920 td->td_retval[0] = new;
925 (void) closefp(fdp, new, delfp, td, 1);
926 FILEDESC_UNLOCK_ASSERT(fdp);
929 FILEDESC_XUNLOCK(fdp);
936 * If sigio is on the list associated with a process or process group,
937 * disable signalling from the device, remove sigio from the list and
941 funsetown(struct sigio **sigiop)
951 *(sigio->sio_myref) = NULL;
952 if ((sigio)->sio_pgid < 0) {
953 struct pgrp *pg = (sigio)->sio_pgrp;
955 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
959 struct proc *p = (sigio)->sio_proc;
961 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
966 crfree(sigio->sio_ucred);
967 free(sigio, M_SIGIO);
971 * Free a list of sigio structures.
972 * We only need to lock the SIGIO_LOCK because we have made ourselves
973 * inaccessible to callers of fsetown and therefore do not need to lock
974 * the proc or pgrp struct for the list manipulation.
977 funsetownlst(struct sigiolst *sigiolst)
983 sigio = SLIST_FIRST(sigiolst);
990 * Every entry of the list should belong
991 * to a single proc or pgrp.
993 if (sigio->sio_pgid < 0) {
994 pg = sigio->sio_pgrp;
995 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
996 } else /* if (sigio->sio_pgid > 0) */ {
998 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1002 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1003 *(sigio->sio_myref) = NULL;
1005 KASSERT(sigio->sio_pgid < 0,
1006 ("Proc sigio in pgrp sigio list"));
1007 KASSERT(sigio->sio_pgrp == pg,
1008 ("Bogus pgrp in sigio list"));
1010 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1013 } else /* if (p != NULL) */ {
1014 KASSERT(sigio->sio_pgid > 0,
1015 ("Pgrp sigio in proc sigio list"));
1016 KASSERT(sigio->sio_proc == p,
1017 ("Bogus proc in sigio list"));
1019 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1024 crfree(sigio->sio_ucred);
1025 free(sigio, M_SIGIO);
1032 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1034 * After permission checking, add a sigio structure to the sigio list for
1035 * the process or process group.
1038 fsetown(pid_t pgid, struct sigio **sigiop)
1042 struct sigio *sigio;
1052 /* Allocate and fill in the new sigio out of locks. */
1053 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1054 sigio->sio_pgid = pgid;
1055 sigio->sio_ucred = crhold(curthread->td_ucred);
1056 sigio->sio_myref = sigiop;
1058 sx_slock(&proctree_lock);
1067 * Policy - Don't allow a process to FSETOWN a process
1068 * in another session.
1070 * Remove this test to allow maximum flexibility or
1071 * restrict FSETOWN to the current process or process
1072 * group for maximum safety.
1075 if (proc->p_session != curthread->td_proc->p_session) {
1081 } else /* if (pgid < 0) */ {
1082 pgrp = pgfind(-pgid);
1090 * Policy - Don't allow a process to FSETOWN a process
1091 * in another session.
1093 * Remove this test to allow maximum flexibility or
1094 * restrict FSETOWN to the current process or process
1095 * group for maximum safety.
1097 if (pgrp->pg_session != curthread->td_proc->p_session) {
1108 * Since funsetownlst() is called without the proctree
1109 * locked, we need to check for P_WEXIT.
1110 * XXX: is ESRCH correct?
1112 if ((proc->p_flag & P_WEXIT) != 0) {
1117 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1118 sigio->sio_proc = proc;
1122 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1123 sigio->sio_pgrp = pgrp;
1126 sx_sunlock(&proctree_lock);
1133 sx_sunlock(&proctree_lock);
1134 crfree(sigio->sio_ucred);
1135 free(sigio, M_SIGIO);
1140 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1144 struct sigio **sigiop;
1149 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1155 * Function drops the filedesc lock on return.
1158 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1163 FILEDESC_XLOCK_ASSERT(fdp);
1166 if (td->td_proc->p_fdtol != NULL) {
1168 * Ask fdfree() to sleep to ensure that all relevant
1169 * process leaders can be traversed in closef().
1171 fdp->fd_holdleaderscount++;
1178 * We now hold the fp reference that used to be owned by the
1179 * descriptor array. We have to unlock the FILEDESC *AFTER*
1180 * knote_fdclose to prevent a race of the fd getting opened, a knote
1181 * added, and deleteing a knote for the new fd.
1183 knote_fdclose(td, fd);
1186 * We need to notify mqueue if the object is of type mqueue.
1188 if (fp->f_type == DTYPE_MQUEUE)
1189 mq_fdclose(td, fd, fp);
1190 FILEDESC_XUNLOCK(fdp);
1192 error = closef(fp, td);
1194 FILEDESC_XLOCK(fdp);
1195 fdp->fd_holdleaderscount--;
1196 if (fdp->fd_holdleaderscount == 0 &&
1197 fdp->fd_holdleaderswakeup != 0) {
1198 fdp->fd_holdleaderswakeup = 0;
1199 wakeup(&fdp->fd_holdleaderscount);
1201 FILEDESC_XUNLOCK(fdp);
1207 * Close a file descriptor.
1209 #ifndef _SYS_SYSPROTO_H_
1216 sys_close(struct thread *td, struct close_args *uap)
1219 return (kern_close(td, uap->fd));
1223 kern_close(struct thread *td, int fd)
1225 struct filedesc *fdp;
1228 fdp = td->td_proc->p_fd;
1230 AUDIT_SYSCLOSE(td, fd);
1232 FILEDESC_XLOCK(fdp);
1233 if ((fp = fget_locked(fdp, fd)) == NULL) {
1234 FILEDESC_XUNLOCK(fdp);
1239 /* closefp() drops the FILEDESC lock for us. */
1240 return (closefp(fdp, fd, fp, td, 1));
1244 * Close open file descriptors.
1246 #ifndef _SYS_SYSPROTO_H_
1247 struct closefrom_args {
1253 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1255 struct filedesc *fdp;
1258 fdp = td->td_proc->p_fd;
1259 AUDIT_ARG_FD(uap->lowfd);
1262 * Treat negative starting file descriptor values identical to
1263 * closefrom(0) which closes all files.
1267 FILEDESC_SLOCK(fdp);
1268 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1269 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1270 FILEDESC_SUNLOCK(fdp);
1271 (void)kern_close(td, fd);
1272 FILEDESC_SLOCK(fdp);
1275 FILEDESC_SUNLOCK(fdp);
1279 #if defined(COMPAT_43)
1281 * Return status information about a file descriptor.
1283 #ifndef _SYS_SYSPROTO_H_
1284 struct ofstat_args {
1291 ofstat(struct thread *td, struct ofstat_args *uap)
1297 error = kern_fstat(td, uap->fd, &ub);
1300 error = copyout(&oub, uap->sb, sizeof(oub));
1304 #endif /* COMPAT_43 */
1307 * Return status information about a file descriptor.
1309 #ifndef _SYS_SYSPROTO_H_
1317 sys_fstat(struct thread *td, struct fstat_args *uap)
1322 error = kern_fstat(td, uap->fd, &ub);
1324 error = copyout(&ub, uap->sb, sizeof(ub));
1329 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1332 cap_rights_t rights;
1337 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1341 AUDIT_ARG_FILE(td->td_proc, fp);
1343 error = fo_stat(fp, sbp, td->td_ucred, td);
1346 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1353 * Return status information about a file descriptor.
1355 #ifndef _SYS_SYSPROTO_H_
1356 struct nfstat_args {
1363 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1369 error = kern_fstat(td, uap->fd, &ub);
1371 cvtnstat(&ub, &nub);
1372 error = copyout(&nub, uap->sb, sizeof(nub));
1378 * Return pathconf information about a file descriptor.
1380 #ifndef _SYS_SYSPROTO_H_
1381 struct fpathconf_args {
1388 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1392 cap_rights_t rights;
1395 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1399 if (uap->name == _PC_ASYNC_IO) {
1400 td->td_retval[0] = _POSIX_ASYNCHRONOUS_IO;
1405 vn_lock(vp, LK_SHARED | LK_RETRY);
1406 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1408 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1409 if (uap->name != _PC_PIPE_BUF) {
1412 td->td_retval[0] = PIPE_BUF;
1424 * Initialize filecaps structure.
1427 filecaps_init(struct filecaps *fcaps)
1430 bzero(fcaps, sizeof(*fcaps));
1431 fcaps->fc_nioctls = -1;
1435 * Copy filecaps structure allocating memory for ioctls array if needed.
1437 * The last parameter indicates whether the fdtable is locked. If it is not and
1438 * ioctls are encountered, copying fails and the caller must lock the table.
1440 * Note that if the table was not locked, the caller has to check the relevant
1441 * sequence counter to determine whether the operation was successful.
1444 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1449 if (src->fc_ioctls == NULL)
1454 KASSERT(src->fc_nioctls > 0,
1455 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1457 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1458 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1459 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1464 * Move filecaps structure to the new place and clear the old place.
1467 filecaps_move(struct filecaps *src, struct filecaps *dst)
1471 bzero(src, sizeof(*src));
1475 * Fill the given filecaps structure with full rights.
1478 filecaps_fill(struct filecaps *fcaps)
1481 CAP_ALL(&fcaps->fc_rights);
1482 fcaps->fc_ioctls = NULL;
1483 fcaps->fc_nioctls = -1;
1484 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1488 * Free memory allocated within filecaps structure.
1491 filecaps_free(struct filecaps *fcaps)
1494 free(fcaps->fc_ioctls, M_FILECAPS);
1495 bzero(fcaps, sizeof(*fcaps));
1499 * Validate the given filecaps structure.
1502 filecaps_validate(const struct filecaps *fcaps, const char *func)
1505 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1506 ("%s: invalid rights", func));
1507 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1508 ("%s: invalid fcntls", func));
1509 KASSERT(fcaps->fc_fcntls == 0 ||
1510 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1511 ("%s: fcntls without CAP_FCNTL", func));
1512 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1513 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1514 ("%s: invalid ioctls", func));
1515 KASSERT(fcaps->fc_nioctls == 0 ||
1516 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1517 ("%s: ioctls without CAP_IOCTL", func));
1521 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1525 FILEDESC_XLOCK_ASSERT(fdp);
1527 nfd1 = fdp->fd_nfiles * 2;
1530 fdgrowtable(fdp, nfd1);
1534 * Grow the file table to accommodate (at least) nfd descriptors.
1537 fdgrowtable(struct filedesc *fdp, int nfd)
1539 struct filedesc0 *fdp0;
1540 struct freetable *ft;
1541 struct fdescenttbl *ntable;
1542 struct fdescenttbl *otable;
1543 int nnfiles, onfiles;
1544 NDSLOTTYPE *nmap, *omap;
1547 * If lastfile is -1 this struct filedesc was just allocated and we are
1548 * growing it to accommodate for the one we are going to copy from. There
1549 * is no need to have a lock on this one as it's not visible to anyone.
1551 if (fdp->fd_lastfile != -1)
1552 FILEDESC_XLOCK_ASSERT(fdp);
1554 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1556 /* save old values */
1557 onfiles = fdp->fd_nfiles;
1558 otable = fdp->fd_files;
1561 /* compute the size of the new table */
1562 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1563 if (nnfiles <= onfiles)
1564 /* the table is already large enough */
1568 * Allocate a new table. We need enough space for the number of
1569 * entries, file entries themselves and the struct freetable we will use
1570 * when we decommission the table and place it on the freelist.
1571 * We place the struct freetable in the middle so we don't have
1572 * to worry about padding.
1574 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1575 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1576 sizeof(struct freetable),
1577 M_FILEDESC, M_ZERO | M_WAITOK);
1578 /* copy the old data */
1579 ntable->fdt_nfiles = nnfiles;
1580 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1581 onfiles * sizeof(ntable->fdt_ofiles[0]));
1584 * Allocate a new map only if the old is not large enough. It will
1585 * grow at a slower rate than the table as it can map more
1586 * entries than the table can hold.
1588 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1589 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1591 /* copy over the old data and update the pointer */
1592 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1597 * Make sure that ntable is correctly initialized before we replace
1598 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1601 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1604 * Do not free the old file table, as some threads may still
1605 * reference entries within it. Instead, place it on a freelist
1606 * which will be processed when the struct filedesc is released.
1608 * Note that if onfiles == NDFILE, we're dealing with the original
1609 * static allocation contained within (struct filedesc0 *)fdp,
1610 * which must not be freed.
1612 if (onfiles > NDFILE) {
1613 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1614 fdp0 = (struct filedesc0 *)fdp;
1615 ft->ft_table = otable;
1616 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1619 * The map does not have the same possibility of threads still
1620 * holding references to it. So always free it as long as it
1621 * does not reference the original static allocation.
1623 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1624 free(omap, M_FILEDESC);
1628 * Allocate a file descriptor for the process.
1631 fdalloc(struct thread *td, int minfd, int *result)
1633 struct proc *p = td->td_proc;
1634 struct filedesc *fdp = p->p_fd;
1635 int fd, maxfd, allocfd;
1640 FILEDESC_XLOCK_ASSERT(fdp);
1642 if (fdp->fd_freefile > minfd)
1643 minfd = fdp->fd_freefile;
1645 maxfd = getmaxfd(td);
1648 * Search the bitmap for a free descriptor starting at minfd.
1649 * If none is found, grow the file table.
1651 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1654 if (fd >= fdp->fd_nfiles) {
1655 allocfd = min(fd * 2, maxfd);
1659 error = racct_set(p, RACCT_NOFILE, allocfd);
1666 * fd is already equal to first free descriptor >= minfd, so
1667 * we only need to grow the table and we are done.
1669 fdgrowtable_exp(fdp, allocfd);
1673 * Perform some sanity checks, then mark the file descriptor as
1674 * used and return it to the caller.
1676 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1677 ("invalid descriptor %d", fd));
1678 KASSERT(!fdisused(fdp, fd),
1679 ("fd_first_free() returned non-free descriptor"));
1680 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1681 ("file descriptor isn't free"));
1688 * Allocate n file descriptors for the process.
1691 fdallocn(struct thread *td, int minfd, int *fds, int n)
1693 struct proc *p = td->td_proc;
1694 struct filedesc *fdp = p->p_fd;
1697 FILEDESC_XLOCK_ASSERT(fdp);
1699 for (i = 0; i < n; i++)
1700 if (fdalloc(td, 0, &fds[i]) != 0)
1704 for (i--; i >= 0; i--)
1705 fdunused(fdp, fds[i]);
1713 * Create a new open file structure and allocate a file descriptor for the
1714 * process that refers to it. We add one reference to the file for the
1715 * descriptor table and one reference for resultfp. This is to prevent us
1716 * being preempted and the entry in the descriptor table closed after we
1717 * release the FILEDESC lock.
1720 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1721 struct filecaps *fcaps)
1726 error = falloc_noinstall(td, &fp);
1728 return (error); /* no reference held on error */
1730 error = finstall(td, fp, &fd, flags, fcaps);
1732 fdrop(fp, td); /* one reference (fp only) */
1736 if (resultfp != NULL)
1737 *resultfp = fp; /* copy out result */
1739 fdrop(fp, td); /* release local reference */
1741 if (resultfd != NULL)
1748 * Create a new open file structure without allocating a file descriptor.
1751 falloc_noinstall(struct thread *td, struct file **resultfp)
1754 int maxuserfiles = maxfiles - (maxfiles / 20);
1755 static struct timeval lastfail;
1758 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1760 if ((openfiles >= maxuserfiles &&
1761 priv_check(td, PRIV_MAXFILES) != 0) ||
1762 openfiles >= maxfiles) {
1763 if (ppsratecheck(&lastfail, &curfail, 1)) {
1764 printf("kern.maxfiles limit exceeded by uid %i, "
1765 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1769 atomic_add_int(&openfiles, 1);
1770 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1771 refcount_init(&fp->f_count, 1);
1772 fp->f_cred = crhold(td->td_ucred);
1773 fp->f_ops = &badfileops;
1779 * Install a file in a file descriptor table.
1782 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1783 struct filecaps *fcaps)
1785 struct filedescent *fde;
1789 filecaps_validate(fcaps, __func__);
1790 FILEDESC_XLOCK_ASSERT(fdp);
1792 fde = &fdp->fd_ofiles[fd];
1794 seq_write_begin(&fde->fde_seq);
1797 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1799 filecaps_move(fcaps, &fde->fde_caps);
1801 filecaps_fill(&fde->fde_caps);
1803 seq_write_end(&fde->fde_seq);
1808 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1809 struct filecaps *fcaps)
1811 struct filedesc *fdp = td->td_proc->p_fd;
1816 FILEDESC_XLOCK(fdp);
1817 if ((error = fdalloc(td, 0, fd))) {
1818 FILEDESC_XUNLOCK(fdp);
1822 _finstall(fdp, fp, *fd, flags, fcaps);
1823 FILEDESC_XUNLOCK(fdp);
1828 * Build a new filedesc structure from another.
1829 * Copy the current, root, and jail root vnode references.
1831 * If fdp is not NULL, return with it shared locked.
1834 fdinit(struct filedesc *fdp, bool prepfiles)
1836 struct filedesc0 *newfdp0;
1837 struct filedesc *newfdp;
1839 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1840 newfdp = &newfdp0->fd_fd;
1842 /* Create the file descriptor table. */
1843 FILEDESC_LOCK_INIT(newfdp);
1844 refcount_init(&newfdp->fd_refcnt, 1);
1845 refcount_init(&newfdp->fd_holdcnt, 1);
1846 newfdp->fd_cmask = CMASK;
1847 newfdp->fd_map = newfdp0->fd_dmap;
1848 newfdp->fd_lastfile = -1;
1849 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
1850 newfdp->fd_files->fdt_nfiles = NDFILE;
1855 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
1856 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1858 FILEDESC_SLOCK(fdp);
1859 newfdp->fd_cdir = fdp->fd_cdir;
1860 if (newfdp->fd_cdir)
1861 VREF(newfdp->fd_cdir);
1862 newfdp->fd_rdir = fdp->fd_rdir;
1863 if (newfdp->fd_rdir)
1864 VREF(newfdp->fd_rdir);
1865 newfdp->fd_jdir = fdp->fd_jdir;
1866 if (newfdp->fd_jdir)
1867 VREF(newfdp->fd_jdir);
1870 FILEDESC_SUNLOCK(fdp);
1872 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1873 FILEDESC_SUNLOCK(fdp);
1874 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1875 FILEDESC_SLOCK(fdp);
1882 static struct filedesc *
1883 fdhold(struct proc *p)
1885 struct filedesc *fdp;
1887 PROC_LOCK_ASSERT(p, MA_OWNED);
1890 refcount_acquire(&fdp->fd_holdcnt);
1895 fddrop(struct filedesc *fdp)
1898 if (fdp->fd_holdcnt > 1) {
1899 if (refcount_release(&fdp->fd_holdcnt) == 0)
1903 FILEDESC_LOCK_DESTROY(fdp);
1904 uma_zfree(filedesc0_zone, fdp);
1908 * Share a filedesc structure.
1911 fdshare(struct filedesc *fdp)
1914 refcount_acquire(&fdp->fd_refcnt);
1919 * Unshare a filedesc structure, if necessary by making a copy
1922 fdunshare(struct thread *td)
1924 struct filedesc *tmp;
1925 struct proc *p = td->td_proc;
1927 if (p->p_fd->fd_refcnt == 1)
1930 tmp = fdcopy(p->p_fd);
1936 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
1940 td->td_proc->p_fd = fdp;
1944 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1945 * this is to ease callers, not catch errors.
1948 fdcopy(struct filedesc *fdp)
1950 struct filedesc *newfdp;
1951 struct filedescent *nfde, *ofde;
1956 newfdp = fdinit(fdp, true);
1957 /* copy all passable descriptors (i.e. not kqueue) */
1958 newfdp->fd_freefile = -1;
1959 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1960 ofde = &fdp->fd_ofiles[i];
1961 if (ofde->fde_file == NULL ||
1962 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
1963 if (newfdp->fd_freefile == -1)
1964 newfdp->fd_freefile = i;
1967 nfde = &newfdp->fd_ofiles[i];
1969 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
1970 fhold(nfde->fde_file);
1971 fdused_init(newfdp, i);
1972 newfdp->fd_lastfile = i;
1974 if (newfdp->fd_freefile == -1)
1975 newfdp->fd_freefile = i;
1976 newfdp->fd_cmask = fdp->fd_cmask;
1977 FILEDESC_SUNLOCK(fdp);
1982 * Copies a filedesc structure, while remapping all file descriptors
1983 * stored inside using a translation table.
1985 * File descriptors are copied over to the new file descriptor table,
1986 * regardless of whether the close-on-exec flag is set.
1989 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
1990 struct filedesc **ret)
1992 struct filedesc *newfdp;
1993 struct filedescent *nfde, *ofde;
1998 newfdp = fdinit(fdp, true);
1999 if (nfds > fdp->fd_lastfile + 1) {
2000 /* New table cannot be larger than the old one. */
2004 /* Copy all passable descriptors (i.e. not kqueue). */
2005 newfdp->fd_freefile = nfds;
2006 for (i = 0; i < nfds; ++i) {
2007 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2008 /* File descriptor out of bounds. */
2012 ofde = &fdp->fd_ofiles[fds[i]];
2013 if (ofde->fde_file == NULL) {
2014 /* Unused file descriptor. */
2018 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2019 /* File descriptor cannot be passed. */
2023 nfde = &newfdp->fd_ofiles[i];
2025 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2026 fhold(nfde->fde_file);
2027 fdused_init(newfdp, i);
2028 newfdp->fd_lastfile = i;
2030 newfdp->fd_cmask = fdp->fd_cmask;
2031 FILEDESC_SUNLOCK(fdp);
2035 FILEDESC_SUNLOCK(fdp);
2036 fdescfree_remapped(newfdp);
2041 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2042 * one of processes using it exits) and the table used to be shared.
2045 fdclearlocks(struct thread *td)
2047 struct filedesc *fdp;
2048 struct filedesc_to_leader *fdtol;
2058 MPASS(fdtol != NULL);
2060 FILEDESC_XLOCK(fdp);
2061 KASSERT(fdtol->fdl_refcount > 0,
2062 ("filedesc_to_refcount botch: fdl_refcount=%d",
2063 fdtol->fdl_refcount));
2064 if (fdtol->fdl_refcount == 1 &&
2065 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2066 for (i = 0; i <= fdp->fd_lastfile; i++) {
2067 fp = fdp->fd_ofiles[i].fde_file;
2068 if (fp == NULL || fp->f_type != DTYPE_VNODE)
2071 FILEDESC_XUNLOCK(fdp);
2072 lf.l_whence = SEEK_SET;
2075 lf.l_type = F_UNLCK;
2077 (void) VOP_ADVLOCK(vp,
2078 (caddr_t)p->p_leader, F_UNLCK,
2080 FILEDESC_XLOCK(fdp);
2085 if (fdtol->fdl_refcount == 1) {
2086 if (fdp->fd_holdleaderscount > 0 &&
2087 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2089 * close() or kern_dup() has cleared a reference
2090 * in a shared file descriptor table.
2092 fdp->fd_holdleaderswakeup = 1;
2093 sx_sleep(&fdp->fd_holdleaderscount,
2094 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2097 if (fdtol->fdl_holdcount > 0) {
2099 * Ensure that fdtol->fdl_leader remains
2100 * valid in closef().
2102 fdtol->fdl_wakeup = 1;
2103 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2108 fdtol->fdl_refcount--;
2109 if (fdtol->fdl_refcount == 0 &&
2110 fdtol->fdl_holdcount == 0) {
2111 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2112 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2116 FILEDESC_XUNLOCK(fdp);
2118 free(fdtol, M_FILEDESC_TO_LEADER);
2122 * Release a filedesc structure.
2125 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2127 struct filedesc0 *fdp0;
2128 struct freetable *ft, *tft;
2129 struct filedescent *fde;
2133 for (i = 0; i <= fdp->fd_lastfile; i++) {
2134 fde = &fdp->fd_ofiles[i];
2139 (void) closef(fp, td);
2145 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2146 free(fdp->fd_map, M_FILEDESC);
2147 if (fdp->fd_nfiles > NDFILE)
2148 free(fdp->fd_files, M_FILEDESC);
2150 fdp0 = (struct filedesc0 *)fdp;
2151 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2152 free(ft->ft_table, M_FILEDESC);
2158 fdescfree(struct thread *td)
2161 struct filedesc *fdp;
2162 struct vnode *cdir, *jdir, *rdir;
2171 racct_set(p, RACCT_NOFILE, 0);
2176 if (p->p_fdtol != NULL)
2183 if (refcount_release(&fdp->fd_refcnt) == 0)
2186 FILEDESC_XLOCK(fdp);
2187 cdir = fdp->fd_cdir;
2188 fdp->fd_cdir = NULL;
2189 rdir = fdp->fd_rdir;
2190 fdp->fd_rdir = NULL;
2191 jdir = fdp->fd_jdir;
2192 fdp->fd_jdir = NULL;
2193 FILEDESC_XUNLOCK(fdp);
2202 fdescfree_fds(td, fdp, 1);
2206 fdescfree_remapped(struct filedesc *fdp)
2209 if (fdp->fd_cdir != NULL)
2210 vrele(fdp->fd_cdir);
2211 if (fdp->fd_rdir != NULL)
2212 vrele(fdp->fd_rdir);
2213 if (fdp->fd_jdir != NULL)
2214 vrele(fdp->fd_jdir);
2216 fdescfree_fds(curthread, fdp, 0);
2220 * For setugid programs, we don't want to people to use that setugidness
2221 * to generate error messages which write to a file which otherwise would
2222 * otherwise be off-limits to the process. We check for filesystems where
2223 * the vnode can change out from under us after execve (like [lin]procfs).
2225 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2226 * sufficient. We also don't check for setugidness since we know we are.
2229 is_unsafe(struct file *fp)
2233 if (fp->f_type != DTYPE_VNODE)
2237 return ((vp->v_vflag & VV_PROCDEP) != 0);
2241 * Make this setguid thing safe, if at all possible.
2244 fdsetugidsafety(struct thread *td)
2246 struct filedesc *fdp;
2250 fdp = td->td_proc->p_fd;
2251 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2252 MPASS(fdp->fd_nfiles >= 3);
2253 for (i = 0; i <= 2; i++) {
2254 fp = fdp->fd_ofiles[i].fde_file;
2255 if (fp != NULL && is_unsafe(fp)) {
2256 FILEDESC_XLOCK(fdp);
2257 knote_fdclose(td, i);
2259 * NULL-out descriptor prior to close to avoid
2260 * a race while close blocks.
2263 FILEDESC_XUNLOCK(fdp);
2264 (void) closef(fp, td);
2270 * If a specific file object occupies a specific file descriptor, close the
2271 * file descriptor entry and drop a reference on the file object. This is a
2272 * convenience function to handle a subsequent error in a function that calls
2273 * falloc() that handles the race that another thread might have closed the
2274 * file descriptor out from under the thread creating the file object.
2277 fdclose(struct thread *td, struct file *fp, int idx)
2279 struct filedesc *fdp = td->td_proc->p_fd;
2281 FILEDESC_XLOCK(fdp);
2282 if (fdp->fd_ofiles[idx].fde_file == fp) {
2284 FILEDESC_XUNLOCK(fdp);
2287 FILEDESC_XUNLOCK(fdp);
2291 * Close any files on exec?
2294 fdcloseexec(struct thread *td)
2296 struct filedesc *fdp;
2297 struct filedescent *fde;
2301 fdp = td->td_proc->p_fd;
2302 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2303 for (i = 0; i <= fdp->fd_lastfile; i++) {
2304 fde = &fdp->fd_ofiles[i];
2306 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2307 (fde->fde_flags & UF_EXCLOSE))) {
2308 FILEDESC_XLOCK(fdp);
2310 (void) closefp(fdp, i, fp, td, 0);
2311 FILEDESC_UNLOCK_ASSERT(fdp);
2317 * It is unsafe for set[ug]id processes to be started with file
2318 * descriptors 0..2 closed, as these descriptors are given implicit
2319 * significance in the Standard C library. fdcheckstd() will create a
2320 * descriptor referencing /dev/null for each of stdin, stdout, and
2321 * stderr that is not already open.
2324 fdcheckstd(struct thread *td)
2326 struct filedesc *fdp;
2328 int i, error, devnull;
2330 fdp = td->td_proc->p_fd;
2331 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2332 MPASS(fdp->fd_nfiles >= 3);
2334 for (i = 0; i <= 2; i++) {
2335 if (fdp->fd_ofiles[i].fde_file != NULL)
2338 save = td->td_retval[0];
2339 if (devnull != -1) {
2340 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2342 error = kern_openat(td, AT_FDCWD, "/dev/null",
2343 UIO_SYSSPACE, O_RDWR, 0);
2345 devnull = td->td_retval[0];
2346 KASSERT(devnull == i, ("we didn't get our fd"));
2349 td->td_retval[0] = save;
2357 * Internal form of close. Decrement reference count on file structure.
2358 * Note: td may be NULL when closing a file that was being passed in a
2361 * XXXRW: Giant is not required for the caller, but often will be held; this
2362 * makes it moderately likely the Giant will be recursed in the VFS case.
2365 closef(struct file *fp, struct thread *td)
2369 struct filedesc_to_leader *fdtol;
2370 struct filedesc *fdp;
2373 * POSIX record locking dictates that any close releases ALL
2374 * locks owned by this process. This is handled by setting
2375 * a flag in the unlock to free ONLY locks obeying POSIX
2376 * semantics, and not to free BSD-style file locks.
2377 * If the descriptor was in a message, POSIX-style locks
2378 * aren't passed with the descriptor, and the thread pointer
2379 * will be NULL. Callers should be careful only to pass a
2380 * NULL thread pointer when there really is no owning
2381 * context that might have locks, or the locks will be
2384 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2386 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2387 lf.l_whence = SEEK_SET;
2390 lf.l_type = F_UNLCK;
2391 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2392 F_UNLCK, &lf, F_POSIX);
2394 fdtol = td->td_proc->p_fdtol;
2395 if (fdtol != NULL) {
2397 * Handle special case where file descriptor table is
2398 * shared between multiple process leaders.
2400 fdp = td->td_proc->p_fd;
2401 FILEDESC_XLOCK(fdp);
2402 for (fdtol = fdtol->fdl_next;
2403 fdtol != td->td_proc->p_fdtol;
2404 fdtol = fdtol->fdl_next) {
2405 if ((fdtol->fdl_leader->p_flag &
2408 fdtol->fdl_holdcount++;
2409 FILEDESC_XUNLOCK(fdp);
2410 lf.l_whence = SEEK_SET;
2413 lf.l_type = F_UNLCK;
2415 (void) VOP_ADVLOCK(vp,
2416 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2418 FILEDESC_XLOCK(fdp);
2419 fdtol->fdl_holdcount--;
2420 if (fdtol->fdl_holdcount == 0 &&
2421 fdtol->fdl_wakeup != 0) {
2422 fdtol->fdl_wakeup = 0;
2426 FILEDESC_XUNLOCK(fdp);
2429 return (fdrop(fp, td));
2433 * Initialize the file pointer with the specified properties.
2435 * The ops are set with release semantics to be certain that the flags, type,
2436 * and data are visible when ops is. This is to prevent ops methods from being
2437 * called with bad data.
2440 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2445 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2449 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2450 struct file **fpp, seq_t *seqp)
2453 struct filedescent *fde;
2455 struct fdescenttbl *fdt;
2460 cap_rights_t haverights;
2464 fdt = fdp->fd_files;
2465 if ((u_int)fd >= fdt->fdt_nfiles)
2468 * Fetch the descriptor locklessly. We avoid fdrop() races by
2469 * never raising a refcount above 0. To accomplish this we have
2470 * to use a cmpset loop rather than an atomic_add. The descriptor
2471 * must be re-verified once we acquire a reference to be certain
2472 * that the identity is still correct and we did not lose a race
2473 * due to preemption.
2477 seq = seq_read(fd_seq(fdt, fd));
2478 fde = &fdt->fdt_ofiles[fd];
2479 haverights = *cap_rights_fde(fde);
2481 if (!seq_consistent(fd_seq(fdt, fd), seq)) {
2486 fp = fdt->fdt_ofiles[fd].fde_file;
2491 error = cap_check(&haverights, needrightsp);
2496 count = fp->f_count;
2499 * Force a reload. Other thread could reallocate the
2500 * table before this fd was closed, so it possible that
2501 * there is a stale fp pointer in cached version.
2503 fdt = *(struct fdescenttbl * volatile *)&(fdp->fd_files);
2507 * Use an acquire barrier to force re-reading of fdt so it is
2508 * refreshed for verification.
2510 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) == 0)
2512 fdt = fdp->fd_files;
2514 if (seq_consistent_nomb(fd_seq(fdt, fd), seq))
2516 if (fp == fdt->fdt_ofiles[fd].fde_file)
2519 fdrop(fp, curthread);
2531 * Extract the file pointer associated with the specified descriptor for the
2532 * current user process.
2534 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2537 * File's rights will be checked against the capability rights mask.
2539 * If an error occurred the non-zero error is returned and *fpp is set to
2540 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2541 * responsible for fdrop().
2544 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2545 cap_rights_t *needrightsp, seq_t *seqp)
2547 struct filedesc *fdp;
2552 fdp = td->td_proc->p_fd;
2553 error = fget_unlocked(fdp, fd, needrightsp, &fp, seqp);
2556 if (fp->f_ops == &badfileops) {
2562 * FREAD and FWRITE failure return EBADF as per POSIX.
2568 if ((fp->f_flag & flags) == 0)
2572 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2573 ((fp->f_flag & FWRITE) != 0))
2579 KASSERT(0, ("wrong flags"));
2592 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2595 return (_fget(td, fd, fpp, 0, rightsp, NULL));
2599 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2603 #ifndef CAPABILITIES
2604 error = _fget(td, fd, fpp, 0, rightsp, NULL);
2605 if (maxprotp != NULL)
2606 *maxprotp = VM_PROT_ALL;
2608 struct filedesc *fdp = td->td_proc->p_fd;
2611 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2613 error = _fget(td, fd, fpp, 0, rightsp, &seq);
2617 * If requested, convert capability rights to access flags.
2619 if (maxprotp != NULL)
2620 *maxprotp = cap_rights_to_vmprot(cap_rights(fdp, fd));
2621 if (!fd_modified(fdp, fd, seq))
2630 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2633 return (_fget(td, fd, fpp, FREAD, rightsp, NULL));
2637 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2640 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2644 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2647 struct filedesc *fdp = td->td_proc->p_fd;
2648 #ifndef CAPABILITIES
2649 return (fget_unlocked(fdp, fd, rightsp, fpp, NULL));
2654 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2656 error = fget_unlocked(fdp, fd, rightsp, fpp, &seq);
2659 error = cap_fcntl_check(fdp, fd, needfcntl);
2660 if (!fd_modified(fdp, fd, seq))
2673 * Like fget() but loads the underlying vnode, or returns an error if the
2674 * descriptor does not represent a vnode. Note that pipes use vnodes but
2675 * never have VM objects. The returned vnode will be vref()'d.
2677 * XXX: what about the unused flags ?
2680 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2687 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2690 if (fp->f_vnode == NULL) {
2702 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2705 return (_fgetvp(td, fd, 0, rightsp, vpp));
2709 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2710 struct filecaps *havecaps, struct vnode **vpp)
2712 struct filedesc *fdp;
2718 fdp = td->td_proc->p_fd;
2719 fp = fget_locked(fdp, fd);
2720 if (fp == NULL || fp->f_ops == &badfileops)
2724 error = cap_check(cap_rights(fdp, fd), needrightsp);
2729 if (fp->f_vnode == NULL)
2734 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps, true);
2740 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2743 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2747 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2750 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2755 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2759 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2764 * Like fget() but loads the underlying socket, or returns an error if the
2765 * descriptor does not represent a socket.
2767 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2770 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2771 * on their file descriptor reference to prevent the socket from being free'd
2775 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2784 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2786 if (fp->f_type != DTYPE_SOCKET) {
2791 *fflagp = fp->f_flag;
2802 * Drop the reference count on the socket and XXX release the SX lock in the
2803 * future. The last reference closes the socket.
2805 * Note: fputsock() is deprecated, see comment for fgetsock().
2808 fputsock(struct socket *so)
2813 CURVNET_SET(so->so_vnet);
2819 * Handle the last reference to a file being closed.
2822 _fdrop(struct file *fp, struct thread *td)
2826 if (fp->f_count != 0)
2827 panic("fdrop: count %d", fp->f_count);
2828 error = fo_close(fp, td);
2829 atomic_subtract_int(&openfiles, 1);
2831 free(fp->f_advice, M_FADVISE);
2832 uma_zfree(file_zone, fp);
2838 * Apply an advisory lock on a file descriptor.
2840 * Just attempt to get a record lock of the requested type on the entire file
2841 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2843 #ifndef _SYS_SYSPROTO_H_
2851 sys_flock(struct thread *td, struct flock_args *uap)
2856 cap_rights_t rights;
2859 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2862 if (fp->f_type != DTYPE_VNODE) {
2864 return (EOPNOTSUPP);
2868 lf.l_whence = SEEK_SET;
2871 if (uap->how & LOCK_UN) {
2872 lf.l_type = F_UNLCK;
2873 atomic_clear_int(&fp->f_flag, FHASLOCK);
2874 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2877 if (uap->how & LOCK_EX)
2878 lf.l_type = F_WRLCK;
2879 else if (uap->how & LOCK_SH)
2880 lf.l_type = F_RDLCK;
2885 atomic_set_int(&fp->f_flag, FHASLOCK);
2886 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2887 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2893 * Duplicate the specified descriptor to a free descriptor.
2896 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2897 int openerror, int *indxp)
2899 struct filedescent *newfde, *oldfde;
2903 KASSERT(openerror == ENODEV || openerror == ENXIO,
2904 ("unexpected error %d in %s", openerror, __func__));
2907 * If the to-be-dup'd fd number is greater than the allowed number
2908 * of file descriptors, or the fd to be dup'd has already been
2909 * closed, then reject.
2911 FILEDESC_XLOCK(fdp);
2912 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2913 FILEDESC_XUNLOCK(fdp);
2917 error = fdalloc(td, 0, &indx);
2919 FILEDESC_XUNLOCK(fdp);
2924 * There are two cases of interest here.
2926 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2928 * For ENXIO steal away the file structure from (dfd) and store it in
2929 * (indx). (dfd) is effectively closed by this operation.
2931 switch (openerror) {
2934 * Check that the mode the file is being opened for is a
2935 * subset of the mode of the existing descriptor.
2937 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2938 fdunused(fdp, indx);
2939 FILEDESC_XUNLOCK(fdp);
2943 newfde = &fdp->fd_ofiles[indx];
2944 oldfde = &fdp->fd_ofiles[dfd];
2946 seq_write_begin(&newfde->fde_seq);
2948 memcpy(newfde, oldfde, fde_change_size);
2949 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps, true);
2951 seq_write_end(&newfde->fde_seq);
2956 * Steal away the file pointer from dfd and stuff it into indx.
2958 newfde = &fdp->fd_ofiles[indx];
2959 oldfde = &fdp->fd_ofiles[dfd];
2961 seq_write_begin(&newfde->fde_seq);
2963 memcpy(newfde, oldfde, fde_change_size);
2964 oldfde->fde_file = NULL;
2967 seq_write_end(&newfde->fde_seq);
2971 FILEDESC_XUNLOCK(fdp);
2977 * This sysctl determines if we will allow a process to chroot(2) if it
2978 * has a directory open:
2979 * 0: disallowed for all processes.
2980 * 1: allowed for processes that were not already chroot(2)'ed.
2981 * 2: allowed for all processes.
2984 static int chroot_allow_open_directories = 1;
2986 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
2987 &chroot_allow_open_directories, 0,
2988 "Allow a process to chroot(2) if it has a directory open");
2991 * Helper function for raised chroot(2) security function: Refuse if
2992 * any filedescriptors are open directories.
2995 chroot_refuse_vdir_fds(struct filedesc *fdp)
3001 FILEDESC_LOCK_ASSERT(fdp);
3003 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3004 fp = fget_locked(fdp, fd);
3007 if (fp->f_type == DTYPE_VNODE) {
3009 if (vp->v_type == VDIR)
3017 * Common routine for kern_chroot() and jail_attach(). The caller is
3018 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3019 * authorize this operation.
3022 pwd_chroot(struct thread *td, struct vnode *vp)
3024 struct filedesc *fdp;
3025 struct vnode *oldvp;
3028 fdp = td->td_proc->p_fd;
3029 FILEDESC_XLOCK(fdp);
3030 if (chroot_allow_open_directories == 0 ||
3031 (chroot_allow_open_directories == 1 && fdp->fd_rdir != rootvnode)) {
3032 error = chroot_refuse_vdir_fds(fdp);
3034 FILEDESC_XUNLOCK(fdp);
3038 oldvp = fdp->fd_rdir;
3041 if (fdp->fd_jdir == NULL) {
3045 FILEDESC_XUNLOCK(fdp);
3051 pwd_chdir(struct thread *td, struct vnode *vp)
3053 struct filedesc *fdp;
3054 struct vnode *oldvp;
3056 fdp = td->td_proc->p_fd;
3057 FILEDESC_XLOCK(fdp);
3058 VNASSERT(vp->v_usecount > 0, vp,
3059 ("chdir to a vnode with zero usecount"));
3060 oldvp = fdp->fd_cdir;
3062 FILEDESC_XUNLOCK(fdp);
3067 * Scan all active processes and prisons to see if any of them have a current
3068 * or root directory of `olddp'. If so, replace them with the new mount point.
3071 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3073 struct filedesc *fdp;
3078 if (vrefcnt(olddp) == 1)
3081 sx_slock(&allproc_lock);
3082 FOREACH_PROC_IN_SYSTEM(p) {
3088 FILEDESC_XLOCK(fdp);
3089 if (fdp->fd_cdir == olddp) {
3091 fdp->fd_cdir = newdp;
3094 if (fdp->fd_rdir == olddp) {
3096 fdp->fd_rdir = newdp;
3099 if (fdp->fd_jdir == olddp) {
3101 fdp->fd_jdir = newdp;
3104 FILEDESC_XUNLOCK(fdp);
3107 sx_sunlock(&allproc_lock);
3108 if (rootvnode == olddp) {
3113 mtx_lock(&prison0.pr_mtx);
3114 if (prison0.pr_root == olddp) {
3116 prison0.pr_root = newdp;
3119 mtx_unlock(&prison0.pr_mtx);
3120 sx_slock(&allprison_lock);
3121 TAILQ_FOREACH(pr, &allprison, pr_list) {
3122 mtx_lock(&pr->pr_mtx);
3123 if (pr->pr_root == olddp) {
3125 pr->pr_root = newdp;
3128 mtx_unlock(&pr->pr_mtx);
3130 sx_sunlock(&allprison_lock);
3135 struct filedesc_to_leader *
3136 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3138 struct filedesc_to_leader *fdtol;
3140 fdtol = malloc(sizeof(struct filedesc_to_leader),
3141 M_FILEDESC_TO_LEADER, M_WAITOK);
3142 fdtol->fdl_refcount = 1;
3143 fdtol->fdl_holdcount = 0;
3144 fdtol->fdl_wakeup = 0;
3145 fdtol->fdl_leader = leader;
3147 FILEDESC_XLOCK(fdp);
3148 fdtol->fdl_next = old->fdl_next;
3149 fdtol->fdl_prev = old;
3150 old->fdl_next = fdtol;
3151 fdtol->fdl_next->fdl_prev = fdtol;
3152 FILEDESC_XUNLOCK(fdp);
3154 fdtol->fdl_next = fdtol;
3155 fdtol->fdl_prev = fdtol;
3161 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3163 struct filedesc *fdp;
3164 int i, count, slots;
3166 if (*(int *)arg1 != 0)
3169 fdp = curproc->p_fd;
3171 FILEDESC_SLOCK(fdp);
3172 slots = NDSLOTS(fdp->fd_lastfile + 1);
3173 for (i = 0; i < slots; i++)
3174 count += bitcountl(fdp->fd_map[i]);
3175 FILEDESC_SUNLOCK(fdp);
3177 return (SYSCTL_OUT(req, &count, sizeof(count)));
3180 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3181 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3182 "Number of open file descriptors");
3185 * Get file structures globally.
3188 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3191 struct filedesc *fdp;
3196 error = sysctl_wire_old_buffer(req, 0);
3199 if (req->oldptr == NULL) {
3201 sx_slock(&allproc_lock);
3202 FOREACH_PROC_IN_SYSTEM(p) {
3204 if (p->p_state == PRS_NEW) {
3212 /* overestimates sparse tables. */
3213 if (fdp->fd_lastfile > 0)
3214 n += fdp->fd_lastfile;
3217 sx_sunlock(&allproc_lock);
3218 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3221 bzero(&xf, sizeof(xf));
3222 xf.xf_size = sizeof(xf);
3223 sx_slock(&allproc_lock);
3224 FOREACH_PROC_IN_SYSTEM(p) {
3226 if (p->p_state == PRS_NEW) {
3230 if (p_cansee(req->td, p) != 0) {
3234 xf.xf_pid = p->p_pid;
3235 xf.xf_uid = p->p_ucred->cr_uid;
3240 FILEDESC_SLOCK(fdp);
3241 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3242 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3246 xf.xf_data = fp->f_data;
3247 xf.xf_vnode = fp->f_vnode;
3248 xf.xf_type = fp->f_type;
3249 xf.xf_count = fp->f_count;
3251 xf.xf_offset = foffset_get(fp);
3252 xf.xf_flag = fp->f_flag;
3253 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3257 FILEDESC_SUNLOCK(fdp);
3262 sx_sunlock(&allproc_lock);
3266 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3267 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3269 #ifdef KINFO_FILE_SIZE
3270 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3274 xlate_fflags(int fflags)
3276 static const struct {
3279 } fflags_table[] = {
3280 { FAPPEND, KF_FLAG_APPEND },
3281 { FASYNC, KF_FLAG_ASYNC },
3282 { FFSYNC, KF_FLAG_FSYNC },
3283 { FHASLOCK, KF_FLAG_HASLOCK },
3284 { FNONBLOCK, KF_FLAG_NONBLOCK },
3285 { FREAD, KF_FLAG_READ },
3286 { FWRITE, KF_FLAG_WRITE },
3287 { O_CREAT, KF_FLAG_CREAT },
3288 { O_DIRECT, KF_FLAG_DIRECT },
3289 { O_EXCL, KF_FLAG_EXCL },
3290 { O_EXEC, KF_FLAG_EXEC },
3291 { O_EXLOCK, KF_FLAG_EXLOCK },
3292 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3293 { O_SHLOCK, KF_FLAG_SHLOCK },
3294 { O_TRUNC, KF_FLAG_TRUNC }
3300 for (i = 0; i < nitems(fflags_table); i++)
3301 if (fflags & fflags_table[i].fflag)
3302 kflags |= fflags_table[i].kf_fflag;
3306 /* Trim unused data from kf_path by truncating the structure size. */
3308 pack_kinfo(struct kinfo_file *kif)
3311 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3312 strlen(kif->kf_path) + 1;
3313 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3317 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3318 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3322 bzero(kif, sizeof(*kif));
3324 /* Set a default type to allow for empty fill_kinfo() methods. */
3325 kif->kf_type = KF_TYPE_UNKNOWN;
3326 kif->kf_flags = xlate_fflags(fp->f_flag);
3327 if (rightsp != NULL)
3328 kif->kf_cap_rights = *rightsp;
3330 cap_rights_init(&kif->kf_cap_rights);
3332 kif->kf_ref_count = fp->f_count;
3333 kif->kf_offset = foffset_get(fp);
3336 * This may drop the filedesc lock, so the 'fp' cannot be
3337 * accessed after this call.
3339 error = fo_fill_kinfo(fp, kif, fdp);
3341 kif->kf_status |= KF_ATTR_VALID;
3342 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3345 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3349 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3350 struct kinfo_file *kif, int flags)
3354 bzero(kif, sizeof(*kif));
3356 kif->kf_type = KF_TYPE_VNODE;
3357 error = vn_fill_kinfo_vnode(vp, kif);
3359 kif->kf_status |= KF_ATTR_VALID;
3360 kif->kf_flags = xlate_fflags(fflags);
3361 cap_rights_init(&kif->kf_cap_rights);
3363 kif->kf_ref_count = -1;
3364 kif->kf_offset = -1;
3365 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3368 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3372 struct export_fd_buf {
3373 struct filedesc *fdp;
3376 struct kinfo_file kif;
3381 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3383 struct kinfo_file *kif;
3386 if (efbuf->remainder != -1) {
3387 if (efbuf->remainder < kif->kf_structsize) {
3388 /* Terminate export. */
3389 efbuf->remainder = 0;
3392 efbuf->remainder -= kif->kf_structsize;
3394 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3398 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3399 struct export_fd_buf *efbuf)
3403 if (efbuf->remainder == 0)
3405 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3407 FILEDESC_SUNLOCK(efbuf->fdp);
3408 error = export_kinfo_to_sb(efbuf);
3409 FILEDESC_SLOCK(efbuf->fdp);
3414 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3415 struct export_fd_buf *efbuf)
3419 if (efbuf->remainder == 0)
3421 if (efbuf->fdp != NULL)
3422 FILEDESC_SUNLOCK(efbuf->fdp);
3423 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3424 error = export_kinfo_to_sb(efbuf);
3425 if (efbuf->fdp != NULL)
3426 FILEDESC_SLOCK(efbuf->fdp);
3431 * Store a process file descriptor information to sbuf.
3433 * Takes a locked proc as argument, and returns with the proc unlocked.
3436 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3440 struct filedesc *fdp;
3441 struct export_fd_buf *efbuf;
3442 struct vnode *cttyvp, *textvp, *tracevp;
3444 cap_rights_t rights;
3446 PROC_LOCK_ASSERT(p, MA_OWNED);
3449 tracevp = p->p_tracevp;
3450 if (tracevp != NULL)
3453 textvp = p->p_textvp;
3456 /* Controlling tty. */
3458 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3459 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3465 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3468 efbuf->remainder = maxlen;
3469 efbuf->flags = flags;
3470 if (tracevp != NULL)
3471 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3474 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3476 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3482 FILEDESC_SLOCK(fdp);
3483 /* working directory */
3484 if (fdp->fd_cdir != NULL) {
3486 export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3488 /* root directory */
3489 if (fdp->fd_rdir != NULL) {
3491 export_vnode_to_sb(fdp->fd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3493 /* jail directory */
3494 if (fdp->fd_jdir != NULL) {
3496 export_vnode_to_sb(fdp->fd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3498 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3499 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3502 rights = *cap_rights(fdp, i);
3503 #else /* !CAPABILITIES */
3504 cap_rights_init(&rights);
3507 * Create sysctl entry. It is OK to drop the filedesc
3508 * lock inside of export_file_to_sb() as we will
3509 * re-validate and re-evaluate its properties when the
3512 error = export_file_to_sb(fp, i, &rights, efbuf);
3513 if (error != 0 || efbuf->remainder == 0)
3516 FILEDESC_SUNLOCK(fdp);
3519 free(efbuf, M_TEMP);
3523 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3526 * Get per-process file descriptors for use by procstat(1), et al.
3529 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3534 int error, error2, *name;
3538 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3539 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3540 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3545 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3546 error = kern_proc_filedesc_out(p, &sb, maxlen,
3547 KERN_FILEDESC_PACK_KINFO);
3548 error2 = sbuf_finish(&sb);
3550 return (error != 0 ? error : error2);
3553 #ifdef KINFO_OFILE_SIZE
3554 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3557 #ifdef COMPAT_FREEBSD7
3559 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3562 okif->kf_structsize = sizeof(*okif);
3563 okif->kf_type = kif->kf_type;
3564 okif->kf_fd = kif->kf_fd;
3565 okif->kf_ref_count = kif->kf_ref_count;
3566 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3567 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3568 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3569 okif->kf_offset = kif->kf_offset;
3570 okif->kf_vnode_type = kif->kf_vnode_type;
3571 okif->kf_sock_domain = kif->kf_sock_domain;
3572 okif->kf_sock_type = kif->kf_sock_type;
3573 okif->kf_sock_protocol = kif->kf_sock_protocol;
3574 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3575 okif->kf_sa_local = kif->kf_sa_local;
3576 okif->kf_sa_peer = kif->kf_sa_peer;
3580 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3581 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3586 FILEDESC_SUNLOCK(fdp);
3587 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
3588 kinfo_to_okinfo(kif, okif);
3589 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3590 FILEDESC_SLOCK(fdp);
3595 * Get per-process file descriptors for use by procstat(1), et al.
3598 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3600 struct kinfo_ofile *okif;
3601 struct kinfo_file *kif;
3602 struct filedesc *fdp;
3603 int error, i, *name;
3608 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3615 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3616 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
3617 FILEDESC_SLOCK(fdp);
3618 if (fdp->fd_cdir != NULL)
3619 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3621 if (fdp->fd_rdir != NULL)
3622 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3624 if (fdp->fd_jdir != NULL)
3625 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3627 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3628 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3630 export_file_to_kinfo(fp, i, NULL, kif, fdp,
3631 KERN_FILEDESC_PACK_KINFO);
3632 FILEDESC_SUNLOCK(fdp);
3633 kinfo_to_okinfo(kif, okif);
3634 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3635 FILEDESC_SLOCK(fdp);
3639 FILEDESC_SUNLOCK(fdp);
3646 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3647 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3648 "Process ofiledesc entries");
3649 #endif /* COMPAT_FREEBSD7 */
3652 vntype_to_kinfo(int vtype)
3657 } vtypes_table[] = {
3658 { VBAD, KF_VTYPE_VBAD },
3659 { VBLK, KF_VTYPE_VBLK },
3660 { VCHR, KF_VTYPE_VCHR },
3661 { VDIR, KF_VTYPE_VDIR },
3662 { VFIFO, KF_VTYPE_VFIFO },
3663 { VLNK, KF_VTYPE_VLNK },
3664 { VNON, KF_VTYPE_VNON },
3665 { VREG, KF_VTYPE_VREG },
3666 { VSOCK, KF_VTYPE_VSOCK }
3671 * Perform vtype translation.
3673 for (i = 0; i < nitems(vtypes_table); i++)
3674 if (vtypes_table[i].vtype == vtype)
3675 return (vtypes_table[i].kf_vtype);
3677 return (KF_VTYPE_UNKNOWN);
3680 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3681 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3682 "Process filedesc entries");
3685 * Store a process current working directory information to sbuf.
3687 * Takes a locked proc as argument, and returns with the proc unlocked.
3690 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3692 struct filedesc *fdp;
3693 struct export_fd_buf *efbuf;
3696 PROC_LOCK_ASSERT(p, MA_OWNED);
3703 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3706 efbuf->remainder = maxlen;
3708 FILEDESC_SLOCK(fdp);
3709 if (fdp->fd_cdir == NULL)
3713 error = export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD,
3716 FILEDESC_SUNLOCK(fdp);
3718 free(efbuf, M_TEMP);
3723 * Get per-process current working directory.
3726 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
3731 int error, error2, *name;
3735 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
3736 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3737 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3742 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3743 error = kern_proc_cwd_out(p, &sb, maxlen);
3744 error2 = sbuf_finish(&sb);
3746 return (error != 0 ? error : error2);
3749 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
3750 sysctl_kern_proc_cwd, "Process current working directory");
3754 * For the purposes of debugging, generate a human-readable string for the
3758 file_type_to_name(short type)
3788 * For the purposes of debugging, identify a process (if any, perhaps one of
3789 * many) that references the passed file in its file descriptor array. Return
3792 static struct proc *
3793 file_to_first_proc(struct file *fp)
3795 struct filedesc *fdp;
3799 FOREACH_PROC_IN_SYSTEM(p) {
3800 if (p->p_state == PRS_NEW)
3805 for (n = 0; n <= fdp->fd_lastfile; n++) {
3806 if (fp == fdp->fd_ofiles[n].fde_file)
3814 db_print_file(struct file *fp, int header)
3819 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3820 "File", "Type", "Data", "Flag", "GCFl", "Count",
3821 "MCount", "Vnode", "FPID", "FCmd");
3822 p = file_to_first_proc(fp);
3823 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3824 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3825 0, fp->f_count, 0, fp->f_vnode,
3826 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3829 DB_SHOW_COMMAND(file, db_show_file)
3834 db_printf("usage: show file <addr>\n");
3837 fp = (struct file *)addr;
3838 db_print_file(fp, 1);
3841 DB_SHOW_COMMAND(files, db_show_files)
3843 struct filedesc *fdp;
3850 FOREACH_PROC_IN_SYSTEM(p) {
3851 if (p->p_state == PRS_NEW)
3853 if ((fdp = p->p_fd) == NULL)
3855 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3856 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3858 db_print_file(fp, header);
3865 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3866 &maxfilesperproc, 0, "Maximum files allowed open per process");
3868 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3869 &maxfiles, 0, "Maximum number of files");
3871 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3872 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3876 filelistinit(void *dummy)
3879 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3880 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3881 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
3882 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
3883 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3885 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3887 /*-------------------------------------------------------------------*/
3890 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3891 int flags, struct thread *td)
3898 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3906 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3914 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3922 badfo_kqfilter(struct file *fp, struct knote *kn)
3929 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3937 badfo_close(struct file *fp, struct thread *td)
3944 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3952 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3960 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3961 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3969 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
3975 struct fileops badfileops = {
3976 .fo_read = badfo_readwrite,
3977 .fo_write = badfo_readwrite,
3978 .fo_truncate = badfo_truncate,
3979 .fo_ioctl = badfo_ioctl,
3980 .fo_poll = badfo_poll,
3981 .fo_kqfilter = badfo_kqfilter,
3982 .fo_stat = badfo_stat,
3983 .fo_close = badfo_close,
3984 .fo_chmod = badfo_chmod,
3985 .fo_chown = badfo_chown,
3986 .fo_sendfile = badfo_sendfile,
3987 .fo_fill_kinfo = badfo_fill_kinfo,
3991 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
3992 int flags, struct thread *td)
3995 return (EOPNOTSUPP);
3999 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4007 invfo_ioctl(struct file *fp, u_long com, void *data,
4008 struct ucred *active_cred, struct thread *td)
4015 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4019 return (poll_no_poll(events));
4023 invfo_kqfilter(struct file *fp, struct knote *kn)
4030 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4038 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4046 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4047 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4054 /*-------------------------------------------------------------------*/
4057 * File Descriptor pseudo-device driver (/dev/fd/).
4059 * Opening minor device N dup()s the file (if any) connected to file
4060 * descriptor N belonging to the calling process. Note that this driver
4061 * consists of only the ``open()'' routine, because all subsequent
4062 * references to this file will be direct to the other driver.
4064 * XXX: we could give this one a cloning event handler if necessary.
4069 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4073 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4074 * the file descriptor being sought for duplication. The error
4075 * return ensures that the vnode for this device will be released
4076 * by vn_open. Open will detect this special error and take the
4077 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4078 * will simply report the error.
4080 td->td_dupfd = dev2unit(dev);
4084 static struct cdevsw fildesc_cdevsw = {
4085 .d_version = D_VERSION,
4091 fildesc_drvinit(void *unused)
4095 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4096 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4097 make_dev_alias(dev, "stdin");
4098 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4099 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4100 make_dev_alias(dev, "stdout");
4101 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4102 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4103 make_dev_alias(dev, "stderr");
4106 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);