kern_descrip.c revision 268001
1/*-
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.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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.
21 *
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
32 * SUCH DAMAGE.
33 *
34 *	@(#)kern_descrip.c	8.6 (Berkeley) 4/19/94
35 */
36
37#include <sys/cdefs.h>
38__FBSDID("$FreeBSD: head/sys/kern/kern_descrip.c 268001 2014-06-28 05:41:53Z mjg $");
39
40#include "opt_capsicum.h"
41#include "opt_compat.h"
42#include "opt_ddb.h"
43#include "opt_ktrace.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47
48#include <sys/capsicum.h>
49#include <sys/conf.h>
50#include <sys/domain.h>
51#include <sys/fcntl.h>
52#include <sys/file.h>
53#include <sys/filedesc.h>
54#include <sys/filio.h>
55#include <sys/jail.h>
56#include <sys/kernel.h>
57#include <sys/ksem.h>
58#include <sys/limits.h>
59#include <sys/lock.h>
60#include <sys/malloc.h>
61#include <sys/mman.h>
62#include <sys/mount.h>
63#include <sys/mqueue.h>
64#include <sys/mutex.h>
65#include <sys/namei.h>
66#include <sys/selinfo.h>
67#include <sys/pipe.h>
68#include <sys/priv.h>
69#include <sys/proc.h>
70#include <sys/procdesc.h>
71#include <sys/protosw.h>
72#include <sys/racct.h>
73#include <sys/resourcevar.h>
74#include <sys/sbuf.h>
75#include <sys/signalvar.h>
76#include <sys/socketvar.h>
77#include <sys/stat.h>
78#include <sys/sx.h>
79#include <sys/syscallsubr.h>
80#include <sys/sysctl.h>
81#include <sys/sysproto.h>
82#include <sys/tty.h>
83#include <sys/unistd.h>
84#include <sys/un.h>
85#include <sys/unpcb.h>
86#include <sys/user.h>
87#include <sys/vnode.h>
88#ifdef KTRACE
89#include <sys/ktrace.h>
90#endif
91
92#include <net/vnet.h>
93
94#include <netinet/in.h>
95#include <netinet/in_pcb.h>
96
97#include <security/audit/audit.h>
98
99#include <vm/uma.h>
100#include <vm/vm.h>
101
102#include <ddb/ddb.h>
103
104static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
105static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
106    "file desc to leader structures");
107static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
108MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
109
110MALLOC_DECLARE(M_FADVISE);
111
112static uma_zone_t file_zone;
113
114void	(*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
115
116static int	closefp(struct filedesc *fdp, int fd, struct file *fp,
117		    struct thread *td, int holdleaders);
118static int	fd_first_free(struct filedesc *fdp, int low, int size);
119static int	fd_last_used(struct filedesc *fdp, int size);
120static void	fdgrowtable(struct filedesc *fdp, int nfd);
121static void	fdgrowtable_exp(struct filedesc *fdp, int nfd);
122static void	fdunused(struct filedesc *fdp, int fd);
123static void	fdused(struct filedesc *fdp, int fd);
124static int	fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
125static int	fill_procdesc_info(struct procdesc *pdp,
126		    struct kinfo_file *kif);
127static int	fill_pts_info(struct tty *tp, struct kinfo_file *kif);
128static int	fill_sem_info(struct file *fp, struct kinfo_file *kif);
129static int	fill_shm_info(struct file *fp, struct kinfo_file *kif);
130static int	fill_socket_info(struct socket *so, struct kinfo_file *kif);
131static int	fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
132static int	getmaxfd(struct proc *p);
133
134/*
135 * Each process has:
136 *
137 * - An array of open file descriptors (fd_ofiles)
138 * - An array of file flags (fd_ofileflags)
139 * - A bitmap recording which descriptors are in use (fd_map)
140 *
141 * A process starts out with NDFILE descriptors.  The value of NDFILE has
142 * been selected based the historical limit of 20 open files, and an
143 * assumption that the majority of processes, especially short-lived
144 * processes like shells, will never need more.
145 *
146 * If this initial allocation is exhausted, a larger descriptor table and
147 * map are allocated dynamically, and the pointers in the process's struct
148 * filedesc are updated to point to those.  This is repeated every time
149 * the process runs out of file descriptors (provided it hasn't hit its
150 * resource limit).
151 *
152 * Since threads may hold references to individual descriptor table
153 * entries, the tables are never freed.  Instead, they are placed on a
154 * linked list and freed only when the struct filedesc is released.
155 */
156#define NDFILE		20
157#define NDSLOTSIZE	sizeof(NDSLOTTYPE)
158#define	NDENTRIES	(NDSLOTSIZE * __CHAR_BIT)
159#define NDSLOT(x)	((x) / NDENTRIES)
160#define NDBIT(x)	((NDSLOTTYPE)1 << ((x) % NDENTRIES))
161#define	NDSLOTS(x)	(((x) + NDENTRIES - 1) / NDENTRIES)
162
163/*
164 * SLIST entry used to keep track of ofiles which must be reclaimed when
165 * the process exits.
166 */
167struct freetable {
168	struct filedescent *ft_table;
169	SLIST_ENTRY(freetable) ft_next;
170};
171
172/*
173 * Initial allocation: a filedesc structure + the head of SLIST used to
174 * keep track of old ofiles + enough space for NDFILE descriptors.
175 */
176struct filedesc0 {
177	struct filedesc fd_fd;
178	SLIST_HEAD(, freetable) fd_free;
179	struct	filedescent fd_dfiles[NDFILE];
180	NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
181};
182
183/*
184 * Descriptor management.
185 */
186volatile int openfiles;			/* actual number of open files */
187struct mtx sigio_lock;		/* mtx to protect pointers to sigio */
188void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
189
190/* A mutex to protect the association between a proc and filedesc. */
191static struct mtx fdesc_mtx;
192
193/*
194 * If low >= size, just return low. Otherwise find the first zero bit in the
195 * given bitmap, starting at low and not exceeding size - 1. Return size if
196 * not found.
197 */
198static int
199fd_first_free(struct filedesc *fdp, int low, int size)
200{
201	NDSLOTTYPE *map = fdp->fd_map;
202	NDSLOTTYPE mask;
203	int off, maxoff;
204
205	if (low >= size)
206		return (low);
207
208	off = NDSLOT(low);
209	if (low % NDENTRIES) {
210		mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
211		if ((mask &= ~map[off]) != 0UL)
212			return (off * NDENTRIES + ffsl(mask) - 1);
213		++off;
214	}
215	for (maxoff = NDSLOTS(size); off < maxoff; ++off)
216		if (map[off] != ~0UL)
217			return (off * NDENTRIES + ffsl(~map[off]) - 1);
218	return (size);
219}
220
221/*
222 * Find the highest non-zero bit in the given bitmap, starting at 0 and
223 * not exceeding size - 1. Return -1 if not found.
224 */
225static int
226fd_last_used(struct filedesc *fdp, int size)
227{
228	NDSLOTTYPE *map = fdp->fd_map;
229	NDSLOTTYPE mask;
230	int off, minoff;
231
232	off = NDSLOT(size);
233	if (size % NDENTRIES) {
234		mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
235		if ((mask &= map[off]) != 0)
236			return (off * NDENTRIES + flsl(mask) - 1);
237		--off;
238	}
239	for (minoff = NDSLOT(0); off >= minoff; --off)
240		if (map[off] != 0)
241			return (off * NDENTRIES + flsl(map[off]) - 1);
242	return (-1);
243}
244
245static int
246fdisused(struct filedesc *fdp, int fd)
247{
248
249	FILEDESC_LOCK_ASSERT(fdp);
250
251	KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
252	    ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
253
254	return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
255}
256
257/*
258 * Mark a file descriptor as used.
259 */
260static void
261fdused(struct filedesc *fdp, int fd)
262{
263
264	FILEDESC_XLOCK_ASSERT(fdp);
265
266	KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
267
268	fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
269	if (fd > fdp->fd_lastfile)
270		fdp->fd_lastfile = fd;
271	if (fd == fdp->fd_freefile)
272		fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
273}
274
275/*
276 * Mark a file descriptor as unused.
277 */
278static void
279fdunused(struct filedesc *fdp, int fd)
280{
281
282	FILEDESC_XLOCK_ASSERT(fdp);
283
284	KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
285	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
286	    ("fd=%d is still in use", fd));
287
288	fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
289	if (fd < fdp->fd_freefile)
290		fdp->fd_freefile = fd;
291	if (fd == fdp->fd_lastfile)
292		fdp->fd_lastfile = fd_last_used(fdp, fd);
293}
294
295/*
296 * Free a file descriptor.
297 */
298static inline void
299fdfree(struct filedesc *fdp, int fd)
300{
301	struct filedescent *fde;
302
303	fde = &fdp->fd_ofiles[fd];
304	filecaps_free(&fde->fde_caps);
305	bzero(fde, sizeof(*fde));
306	fdunused(fdp, fd);
307}
308
309/*
310 * System calls on descriptors.
311 */
312#ifndef _SYS_SYSPROTO_H_
313struct getdtablesize_args {
314	int	dummy;
315};
316#endif
317/* ARGSUSED */
318int
319sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
320{
321	struct proc *p = td->td_proc;
322	uint64_t lim;
323
324	PROC_LOCK(p);
325	td->td_retval[0] =
326	    min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
327	lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
328	PROC_UNLOCK(p);
329	if (lim < td->td_retval[0])
330		td->td_retval[0] = lim;
331	return (0);
332}
333
334/*
335 * Duplicate a file descriptor to a particular value.
336 *
337 * Note: keep in mind that a potential race condition exists when closing
338 * descriptors from a shared descriptor table (via rfork).
339 */
340#ifndef _SYS_SYSPROTO_H_
341struct dup2_args {
342	u_int	from;
343	u_int	to;
344};
345#endif
346/* ARGSUSED */
347int
348sys_dup2(struct thread *td, struct dup2_args *uap)
349{
350
351	return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
352		    td->td_retval));
353}
354
355/*
356 * Duplicate a file descriptor.
357 */
358#ifndef _SYS_SYSPROTO_H_
359struct dup_args {
360	u_int	fd;
361};
362#endif
363/* ARGSUSED */
364int
365sys_dup(struct thread *td, struct dup_args *uap)
366{
367
368	return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
369}
370
371/*
372 * The file control system call.
373 */
374#ifndef _SYS_SYSPROTO_H_
375struct fcntl_args {
376	int	fd;
377	int	cmd;
378	long	arg;
379};
380#endif
381/* ARGSUSED */
382int
383sys_fcntl(struct thread *td, struct fcntl_args *uap)
384{
385	struct flock fl;
386	struct __oflock ofl;
387	intptr_t arg;
388	int error;
389	int cmd;
390
391	error = 0;
392	cmd = uap->cmd;
393	switch (uap->cmd) {
394	case F_OGETLK:
395	case F_OSETLK:
396	case F_OSETLKW:
397		/*
398		 * Convert old flock structure to new.
399		 */
400		error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
401		fl.l_start = ofl.l_start;
402		fl.l_len = ofl.l_len;
403		fl.l_pid = ofl.l_pid;
404		fl.l_type = ofl.l_type;
405		fl.l_whence = ofl.l_whence;
406		fl.l_sysid = 0;
407
408		switch (uap->cmd) {
409		case F_OGETLK:
410		    cmd = F_GETLK;
411		    break;
412		case F_OSETLK:
413		    cmd = F_SETLK;
414		    break;
415		case F_OSETLKW:
416		    cmd = F_SETLKW;
417		    break;
418		}
419		arg = (intptr_t)&fl;
420		break;
421        case F_GETLK:
422        case F_SETLK:
423        case F_SETLKW:
424	case F_SETLK_REMOTE:
425                error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
426                arg = (intptr_t)&fl;
427                break;
428	default:
429		arg = uap->arg;
430		break;
431	}
432	if (error)
433		return (error);
434	error = kern_fcntl(td, uap->fd, cmd, arg);
435	if (error)
436		return (error);
437	if (uap->cmd == F_OGETLK) {
438		ofl.l_start = fl.l_start;
439		ofl.l_len = fl.l_len;
440		ofl.l_pid = fl.l_pid;
441		ofl.l_type = fl.l_type;
442		ofl.l_whence = fl.l_whence;
443		error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
444	} else if (uap->cmd == F_GETLK) {
445		error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
446	}
447	return (error);
448}
449
450int
451kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
452{
453	struct filedesc *fdp;
454	struct flock *flp;
455	struct file *fp, *fp2;
456	struct filedescent *fde;
457	struct proc *p;
458	struct vnode *vp;
459	cap_rights_t rights;
460	int error, flg, tmp;
461	u_int old, new;
462	uint64_t bsize;
463	off_t foffset;
464
465	error = 0;
466	flg = F_POSIX;
467	p = td->td_proc;
468	fdp = p->p_fd;
469
470	switch (cmd) {
471	case F_DUPFD:
472		tmp = arg;
473		error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
474		break;
475
476	case F_DUPFD_CLOEXEC:
477		tmp = arg;
478		error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
479		    td->td_retval);
480		break;
481
482	case F_DUP2FD:
483		tmp = arg;
484		error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
485		break;
486
487	case F_DUP2FD_CLOEXEC:
488		tmp = arg;
489		error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
490		    td->td_retval);
491		break;
492
493	case F_GETFD:
494		FILEDESC_SLOCK(fdp);
495		if ((fp = fget_locked(fdp, fd)) == NULL) {
496			FILEDESC_SUNLOCK(fdp);
497			error = EBADF;
498			break;
499		}
500		fde = &fdp->fd_ofiles[fd];
501		td->td_retval[0] =
502		    (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
503		FILEDESC_SUNLOCK(fdp);
504		break;
505
506	case F_SETFD:
507		FILEDESC_XLOCK(fdp);
508		if ((fp = fget_locked(fdp, fd)) == NULL) {
509			FILEDESC_XUNLOCK(fdp);
510			error = EBADF;
511			break;
512		}
513		fde = &fdp->fd_ofiles[fd];
514		fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
515		    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
516		FILEDESC_XUNLOCK(fdp);
517		break;
518
519	case F_GETFL:
520		error = fget_unlocked(fdp, fd,
521		    cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
522		if (error != 0)
523			break;
524		td->td_retval[0] = OFLAGS(fp->f_flag);
525		fdrop(fp, td);
526		break;
527
528	case F_SETFL:
529		error = fget_unlocked(fdp, fd,
530		    cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
531		if (error != 0)
532			break;
533		do {
534			tmp = flg = fp->f_flag;
535			tmp &= ~FCNTLFLAGS;
536			tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
537		} while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
538		tmp = fp->f_flag & FNONBLOCK;
539		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
540		if (error != 0) {
541			fdrop(fp, td);
542			break;
543		}
544		tmp = fp->f_flag & FASYNC;
545		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
546		if (error == 0) {
547			fdrop(fp, td);
548			break;
549		}
550		atomic_clear_int(&fp->f_flag, FNONBLOCK);
551		tmp = 0;
552		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
553		fdrop(fp, td);
554		break;
555
556	case F_GETOWN:
557		error = fget_unlocked(fdp, fd,
558		    cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
559		if (error != 0)
560			break;
561		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
562		if (error == 0)
563			td->td_retval[0] = tmp;
564		fdrop(fp, td);
565		break;
566
567	case F_SETOWN:
568		error = fget_unlocked(fdp, fd,
569		    cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
570		if (error != 0)
571			break;
572		tmp = arg;
573		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
574		fdrop(fp, td);
575		break;
576
577	case F_SETLK_REMOTE:
578		error = priv_check(td, PRIV_NFS_LOCKD);
579		if (error)
580			return (error);
581		flg = F_REMOTE;
582		goto do_setlk;
583
584	case F_SETLKW:
585		flg |= F_WAIT;
586		/* FALLTHROUGH F_SETLK */
587
588	case F_SETLK:
589	do_setlk:
590		cap_rights_init(&rights, CAP_FLOCK);
591		error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
592		if (error != 0)
593			break;
594		if (fp->f_type != DTYPE_VNODE) {
595			error = EBADF;
596			fdrop(fp, td);
597			break;
598		}
599
600		flp = (struct flock *)arg;
601		if (flp->l_whence == SEEK_CUR) {
602			foffset = foffset_get(fp);
603			if (foffset < 0 ||
604			    (flp->l_start > 0 &&
605			     foffset > OFF_MAX - flp->l_start)) {
606				FILEDESC_SUNLOCK(fdp);
607				error = EOVERFLOW;
608				fdrop(fp, td);
609				break;
610			}
611			flp->l_start += foffset;
612		}
613
614		vp = fp->f_vnode;
615		switch (flp->l_type) {
616		case F_RDLCK:
617			if ((fp->f_flag & FREAD) == 0) {
618				error = EBADF;
619				break;
620			}
621			PROC_LOCK(p->p_leader);
622			p->p_leader->p_flag |= P_ADVLOCK;
623			PROC_UNLOCK(p->p_leader);
624			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
625			    flp, flg);
626			break;
627		case F_WRLCK:
628			if ((fp->f_flag & FWRITE) == 0) {
629				error = EBADF;
630				break;
631			}
632			PROC_LOCK(p->p_leader);
633			p->p_leader->p_flag |= P_ADVLOCK;
634			PROC_UNLOCK(p->p_leader);
635			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
636			    flp, flg);
637			break;
638		case F_UNLCK:
639			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
640			    flp, flg);
641			break;
642		case F_UNLCKSYS:
643			/*
644			 * Temporary api for testing remote lock
645			 * infrastructure.
646			 */
647			if (flg != F_REMOTE) {
648				error = EINVAL;
649				break;
650			}
651			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
652			    F_UNLCKSYS, flp, flg);
653			break;
654		default:
655			error = EINVAL;
656			break;
657		}
658		if (error != 0 || flp->l_type == F_UNLCK ||
659		    flp->l_type == F_UNLCKSYS) {
660			fdrop(fp, td);
661			break;
662		}
663
664		/*
665		 * Check for a race with close.
666		 *
667		 * The vnode is now advisory locked (or unlocked, but this case
668		 * is not really important) as the caller requested.
669		 * We had to drop the filedesc lock, so we need to recheck if
670		 * the descriptor is still valid, because if it was closed
671		 * in the meantime we need to remove advisory lock from the
672		 * vnode - close on any descriptor leading to an advisory
673		 * locked vnode, removes that lock.
674		 * We will return 0 on purpose in that case, as the result of
675		 * successful advisory lock might have been externally visible
676		 * already. This is fine - effectively we pretend to the caller
677		 * that the closing thread was a bit slower and that the
678		 * advisory lock succeeded before the close.
679		 */
680		error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
681		if (error != 0) {
682			fdrop(fp, td);
683			break;
684		}
685		if (fp != fp2) {
686			flp->l_whence = SEEK_SET;
687			flp->l_start = 0;
688			flp->l_len = 0;
689			flp->l_type = F_UNLCK;
690			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
691			    F_UNLCK, flp, F_POSIX);
692		}
693		fdrop(fp, td);
694		fdrop(fp2, td);
695		break;
696
697	case F_GETLK:
698		error = fget_unlocked(fdp, fd,
699		    cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
700		if (error != 0)
701			break;
702		if (fp->f_type != DTYPE_VNODE) {
703			error = EBADF;
704			fdrop(fp, td);
705			break;
706		}
707		flp = (struct flock *)arg;
708		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
709		    flp->l_type != F_UNLCK) {
710			error = EINVAL;
711			fdrop(fp, td);
712			break;
713		}
714		if (flp->l_whence == SEEK_CUR) {
715			foffset = foffset_get(fp);
716			if ((flp->l_start > 0 &&
717			    foffset > OFF_MAX - flp->l_start) ||
718			    (flp->l_start < 0 &&
719			     foffset < OFF_MIN - flp->l_start)) {
720				FILEDESC_SUNLOCK(fdp);
721				error = EOVERFLOW;
722				fdrop(fp, td);
723				break;
724			}
725			flp->l_start += foffset;
726		}
727		vp = fp->f_vnode;
728		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
729		    F_POSIX);
730		fdrop(fp, td);
731		break;
732
733	case F_RDAHEAD:
734		arg = arg ? 128 * 1024: 0;
735		/* FALLTHROUGH */
736	case F_READAHEAD:
737		error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
738		if (error != 0)
739			break;
740		if (fp->f_type != DTYPE_VNODE) {
741			fdrop(fp, td);
742			error = EBADF;
743			break;
744		}
745		if (arg >= 0) {
746			vp = fp->f_vnode;
747			error = vn_lock(vp, LK_SHARED);
748			if (error != 0) {
749				fdrop(fp, td);
750				break;
751			}
752			bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
753			VOP_UNLOCK(vp, 0);
754			fp->f_seqcount = (arg + bsize - 1) / bsize;
755			do {
756				new = old = fp->f_flag;
757				new |= FRDAHEAD;
758			} while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
759		} else {
760			do {
761				new = old = fp->f_flag;
762				new &= ~FRDAHEAD;
763			} while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
764		}
765		fdrop(fp, td);
766		break;
767
768	default:
769		error = EINVAL;
770		break;
771	}
772	return (error);
773}
774
775static int
776getmaxfd(struct proc *p)
777{
778	int maxfd;
779
780	PROC_LOCK(p);
781	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
782	PROC_UNLOCK(p);
783
784	return (maxfd);
785}
786
787/*
788 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
789 */
790int
791do_dup(struct thread *td, int flags, int old, int new,
792    register_t *retval)
793{
794	struct filedesc *fdp;
795	struct filedescent *oldfde, *newfde;
796	struct proc *p;
797	struct file *fp;
798	struct file *delfp;
799	int error, maxfd;
800
801	p = td->td_proc;
802	fdp = p->p_fd;
803
804	/*
805	 * Verify we have a valid descriptor to dup from and possibly to
806	 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
807	 * return EINVAL when the new descriptor is out of bounds.
808	 */
809	if (old < 0)
810		return (EBADF);
811	if (new < 0)
812		return (flags & DUP_FCNTL ? EINVAL : EBADF);
813	maxfd = getmaxfd(p);
814	if (new >= maxfd)
815		return (flags & DUP_FCNTL ? EINVAL : EBADF);
816
817	FILEDESC_XLOCK(fdp);
818	if (fget_locked(fdp, old) == NULL) {
819		FILEDESC_XUNLOCK(fdp);
820		return (EBADF);
821	}
822	oldfde = &fdp->fd_ofiles[old];
823	if (flags & DUP_FIXED && old == new) {
824		*retval = new;
825		if (flags & DUP_CLOEXEC)
826			fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
827		FILEDESC_XUNLOCK(fdp);
828		return (0);
829	}
830	fp = oldfde->fde_file;
831	fhold(fp);
832
833	/*
834	 * If the caller specified a file descriptor, make sure the file
835	 * table is large enough to hold it, and grab it.  Otherwise, just
836	 * allocate a new descriptor the usual way.
837	 */
838	if (flags & DUP_FIXED) {
839		if (new >= fdp->fd_nfiles) {
840			/*
841			 * The resource limits are here instead of e.g.
842			 * fdalloc(), because the file descriptor table may be
843			 * shared between processes, so we can't really use
844			 * racct_add()/racct_sub().  Instead of counting the
845			 * number of actually allocated descriptors, just put
846			 * the limit on the size of the file descriptor table.
847			 */
848#ifdef RACCT
849			PROC_LOCK(p);
850			error = racct_set(p, RACCT_NOFILE, new + 1);
851			PROC_UNLOCK(p);
852			if (error != 0) {
853				FILEDESC_XUNLOCK(fdp);
854				fdrop(fp, td);
855				return (EMFILE);
856			}
857#endif
858			fdgrowtable_exp(fdp, new + 1);
859			oldfde = &fdp->fd_ofiles[old];
860		}
861		newfde = &fdp->fd_ofiles[new];
862		if (newfde->fde_file == NULL)
863			fdused(fdp, new);
864	} else {
865		if ((error = fdalloc(td, new, &new)) != 0) {
866			FILEDESC_XUNLOCK(fdp);
867			fdrop(fp, td);
868			return (error);
869		}
870		newfde = &fdp->fd_ofiles[new];
871	}
872
873	KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
874	KASSERT(old != new, ("new fd is same as old"));
875
876	delfp = newfde->fde_file;
877
878	/*
879	 * Duplicate the source descriptor.
880	 */
881	filecaps_free(&newfde->fde_caps);
882	*newfde = *oldfde;
883	filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
884	if ((flags & DUP_CLOEXEC) != 0)
885		newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
886	else
887		newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
888	*retval = new;
889
890	if (delfp != NULL) {
891		(void) closefp(fdp, new, delfp, td, 1);
892		/* closefp() drops the FILEDESC lock for us. */
893	} else {
894		FILEDESC_XUNLOCK(fdp);
895	}
896
897	return (0);
898}
899
900/*
901 * If sigio is on the list associated with a process or process group,
902 * disable signalling from the device, remove sigio from the list and
903 * free sigio.
904 */
905void
906funsetown(struct sigio **sigiop)
907{
908	struct sigio *sigio;
909
910	SIGIO_LOCK();
911	sigio = *sigiop;
912	if (sigio == NULL) {
913		SIGIO_UNLOCK();
914		return;
915	}
916	*(sigio->sio_myref) = NULL;
917	if ((sigio)->sio_pgid < 0) {
918		struct pgrp *pg = (sigio)->sio_pgrp;
919		PGRP_LOCK(pg);
920		SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
921			     sigio, sio_pgsigio);
922		PGRP_UNLOCK(pg);
923	} else {
924		struct proc *p = (sigio)->sio_proc;
925		PROC_LOCK(p);
926		SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
927			     sigio, sio_pgsigio);
928		PROC_UNLOCK(p);
929	}
930	SIGIO_UNLOCK();
931	crfree(sigio->sio_ucred);
932	free(sigio, M_SIGIO);
933}
934
935/*
936 * Free a list of sigio structures.
937 * We only need to lock the SIGIO_LOCK because we have made ourselves
938 * inaccessible to callers of fsetown and therefore do not need to lock
939 * the proc or pgrp struct for the list manipulation.
940 */
941void
942funsetownlst(struct sigiolst *sigiolst)
943{
944	struct proc *p;
945	struct pgrp *pg;
946	struct sigio *sigio;
947
948	sigio = SLIST_FIRST(sigiolst);
949	if (sigio == NULL)
950		return;
951	p = NULL;
952	pg = NULL;
953
954	/*
955	 * Every entry of the list should belong
956	 * to a single proc or pgrp.
957	 */
958	if (sigio->sio_pgid < 0) {
959		pg = sigio->sio_pgrp;
960		PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
961	} else /* if (sigio->sio_pgid > 0) */ {
962		p = sigio->sio_proc;
963		PROC_LOCK_ASSERT(p, MA_NOTOWNED);
964	}
965
966	SIGIO_LOCK();
967	while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
968		*(sigio->sio_myref) = NULL;
969		if (pg != NULL) {
970			KASSERT(sigio->sio_pgid < 0,
971			    ("Proc sigio in pgrp sigio list"));
972			KASSERT(sigio->sio_pgrp == pg,
973			    ("Bogus pgrp in sigio list"));
974			PGRP_LOCK(pg);
975			SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
976			    sio_pgsigio);
977			PGRP_UNLOCK(pg);
978		} else /* if (p != NULL) */ {
979			KASSERT(sigio->sio_pgid > 0,
980			    ("Pgrp sigio in proc sigio list"));
981			KASSERT(sigio->sio_proc == p,
982			    ("Bogus proc in sigio list"));
983			PROC_LOCK(p);
984			SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
985			    sio_pgsigio);
986			PROC_UNLOCK(p);
987		}
988		SIGIO_UNLOCK();
989		crfree(sigio->sio_ucred);
990		free(sigio, M_SIGIO);
991		SIGIO_LOCK();
992	}
993	SIGIO_UNLOCK();
994}
995
996/*
997 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
998 *
999 * After permission checking, add a sigio structure to the sigio list for
1000 * the process or process group.
1001 */
1002int
1003fsetown(pid_t pgid, struct sigio **sigiop)
1004{
1005	struct proc *proc;
1006	struct pgrp *pgrp;
1007	struct sigio *sigio;
1008	int ret;
1009
1010	if (pgid == 0) {
1011		funsetown(sigiop);
1012		return (0);
1013	}
1014
1015	ret = 0;
1016
1017	/* Allocate and fill in the new sigio out of locks. */
1018	sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1019	sigio->sio_pgid = pgid;
1020	sigio->sio_ucred = crhold(curthread->td_ucred);
1021	sigio->sio_myref = sigiop;
1022
1023	sx_slock(&proctree_lock);
1024	if (pgid > 0) {
1025		proc = pfind(pgid);
1026		if (proc == NULL) {
1027			ret = ESRCH;
1028			goto fail;
1029		}
1030
1031		/*
1032		 * Policy - Don't allow a process to FSETOWN a process
1033		 * in another session.
1034		 *
1035		 * Remove this test to allow maximum flexibility or
1036		 * restrict FSETOWN to the current process or process
1037		 * group for maximum safety.
1038		 */
1039		PROC_UNLOCK(proc);
1040		if (proc->p_session != curthread->td_proc->p_session) {
1041			ret = EPERM;
1042			goto fail;
1043		}
1044
1045		pgrp = NULL;
1046	} else /* if (pgid < 0) */ {
1047		pgrp = pgfind(-pgid);
1048		if (pgrp == NULL) {
1049			ret = ESRCH;
1050			goto fail;
1051		}
1052		PGRP_UNLOCK(pgrp);
1053
1054		/*
1055		 * Policy - Don't allow a process to FSETOWN a process
1056		 * in another session.
1057		 *
1058		 * Remove this test to allow maximum flexibility or
1059		 * restrict FSETOWN to the current process or process
1060		 * group for maximum safety.
1061		 */
1062		if (pgrp->pg_session != curthread->td_proc->p_session) {
1063			ret = EPERM;
1064			goto fail;
1065		}
1066
1067		proc = NULL;
1068	}
1069	funsetown(sigiop);
1070	if (pgid > 0) {
1071		PROC_LOCK(proc);
1072		/*
1073		 * Since funsetownlst() is called without the proctree
1074		 * locked, we need to check for P_WEXIT.
1075		 * XXX: is ESRCH correct?
1076		 */
1077		if ((proc->p_flag & P_WEXIT) != 0) {
1078			PROC_UNLOCK(proc);
1079			ret = ESRCH;
1080			goto fail;
1081		}
1082		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1083		sigio->sio_proc = proc;
1084		PROC_UNLOCK(proc);
1085	} else {
1086		PGRP_LOCK(pgrp);
1087		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1088		sigio->sio_pgrp = pgrp;
1089		PGRP_UNLOCK(pgrp);
1090	}
1091	sx_sunlock(&proctree_lock);
1092	SIGIO_LOCK();
1093	*sigiop = sigio;
1094	SIGIO_UNLOCK();
1095	return (0);
1096
1097fail:
1098	sx_sunlock(&proctree_lock);
1099	crfree(sigio->sio_ucred);
1100	free(sigio, M_SIGIO);
1101	return (ret);
1102}
1103
1104/*
1105 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1106 */
1107pid_t
1108fgetown(sigiop)
1109	struct sigio **sigiop;
1110{
1111	pid_t pgid;
1112
1113	SIGIO_LOCK();
1114	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1115	SIGIO_UNLOCK();
1116	return (pgid);
1117}
1118
1119/*
1120 * Function drops the filedesc lock on return.
1121 */
1122static int
1123closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1124    int holdleaders)
1125{
1126	int error;
1127
1128	FILEDESC_XLOCK_ASSERT(fdp);
1129
1130	if (holdleaders) {
1131		if (td->td_proc->p_fdtol != NULL) {
1132			/*
1133			 * Ask fdfree() to sleep to ensure that all relevant
1134			 * process leaders can be traversed in closef().
1135			 */
1136			fdp->fd_holdleaderscount++;
1137		} else {
1138			holdleaders = 0;
1139		}
1140	}
1141
1142	/*
1143	 * We now hold the fp reference that used to be owned by the
1144	 * descriptor array.  We have to unlock the FILEDESC *AFTER*
1145	 * knote_fdclose to prevent a race of the fd getting opened, a knote
1146	 * added, and deleteing a knote for the new fd.
1147	 */
1148	knote_fdclose(td, fd);
1149
1150	/*
1151	 * We need to notify mqueue if the object is of type mqueue.
1152	 */
1153	if (fp->f_type == DTYPE_MQUEUE)
1154		mq_fdclose(td, fd, fp);
1155	FILEDESC_XUNLOCK(fdp);
1156
1157	error = closef(fp, td);
1158	if (holdleaders) {
1159		FILEDESC_XLOCK(fdp);
1160		fdp->fd_holdleaderscount--;
1161		if (fdp->fd_holdleaderscount == 0 &&
1162		    fdp->fd_holdleaderswakeup != 0) {
1163			fdp->fd_holdleaderswakeup = 0;
1164			wakeup(&fdp->fd_holdleaderscount);
1165		}
1166		FILEDESC_XUNLOCK(fdp);
1167	}
1168	return (error);
1169}
1170
1171/*
1172 * Close a file descriptor.
1173 */
1174#ifndef _SYS_SYSPROTO_H_
1175struct close_args {
1176	int     fd;
1177};
1178#endif
1179/* ARGSUSED */
1180int
1181sys_close(td, uap)
1182	struct thread *td;
1183	struct close_args *uap;
1184{
1185
1186	return (kern_close(td, uap->fd));
1187}
1188
1189int
1190kern_close(td, fd)
1191	struct thread *td;
1192	int fd;
1193{
1194	struct filedesc *fdp;
1195	struct file *fp;
1196
1197	fdp = td->td_proc->p_fd;
1198
1199	AUDIT_SYSCLOSE(td, fd);
1200
1201	FILEDESC_XLOCK(fdp);
1202	if ((fp = fget_locked(fdp, fd)) == NULL) {
1203		FILEDESC_XUNLOCK(fdp);
1204		return (EBADF);
1205	}
1206	fdfree(fdp, fd);
1207
1208	/* closefp() drops the FILEDESC lock for us. */
1209	return (closefp(fdp, fd, fp, td, 1));
1210}
1211
1212/*
1213 * Close open file descriptors.
1214 */
1215#ifndef _SYS_SYSPROTO_H_
1216struct closefrom_args {
1217	int	lowfd;
1218};
1219#endif
1220/* ARGSUSED */
1221int
1222sys_closefrom(struct thread *td, struct closefrom_args *uap)
1223{
1224	struct filedesc *fdp;
1225	int fd;
1226
1227	fdp = td->td_proc->p_fd;
1228	AUDIT_ARG_FD(uap->lowfd);
1229
1230	/*
1231	 * Treat negative starting file descriptor values identical to
1232	 * closefrom(0) which closes all files.
1233	 */
1234	if (uap->lowfd < 0)
1235		uap->lowfd = 0;
1236	FILEDESC_SLOCK(fdp);
1237	for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1238		if (fdp->fd_ofiles[fd].fde_file != NULL) {
1239			FILEDESC_SUNLOCK(fdp);
1240			(void)kern_close(td, fd);
1241			FILEDESC_SLOCK(fdp);
1242		}
1243	}
1244	FILEDESC_SUNLOCK(fdp);
1245	return (0);
1246}
1247
1248#if defined(COMPAT_43)
1249/*
1250 * Return status information about a file descriptor.
1251 */
1252#ifndef _SYS_SYSPROTO_H_
1253struct ofstat_args {
1254	int	fd;
1255	struct	ostat *sb;
1256};
1257#endif
1258/* ARGSUSED */
1259int
1260ofstat(struct thread *td, struct ofstat_args *uap)
1261{
1262	struct ostat oub;
1263	struct stat ub;
1264	int error;
1265
1266	error = kern_fstat(td, uap->fd, &ub);
1267	if (error == 0) {
1268		cvtstat(&ub, &oub);
1269		error = copyout(&oub, uap->sb, sizeof(oub));
1270	}
1271	return (error);
1272}
1273#endif /* COMPAT_43 */
1274
1275/*
1276 * Return status information about a file descriptor.
1277 */
1278#ifndef _SYS_SYSPROTO_H_
1279struct fstat_args {
1280	int	fd;
1281	struct	stat *sb;
1282};
1283#endif
1284/* ARGSUSED */
1285int
1286sys_fstat(struct thread *td, struct fstat_args *uap)
1287{
1288	struct stat ub;
1289	int error;
1290
1291	error = kern_fstat(td, uap->fd, &ub);
1292	if (error == 0)
1293		error = copyout(&ub, uap->sb, sizeof(ub));
1294	return (error);
1295}
1296
1297int
1298kern_fstat(struct thread *td, int fd, struct stat *sbp)
1299{
1300	struct file *fp;
1301	cap_rights_t rights;
1302	int error;
1303
1304	AUDIT_ARG_FD(fd);
1305
1306	error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1307	if (error != 0)
1308		return (error);
1309
1310	AUDIT_ARG_FILE(td->td_proc, fp);
1311
1312	error = fo_stat(fp, sbp, td->td_ucred, td);
1313	fdrop(fp, td);
1314#ifdef KTRACE
1315	if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1316		ktrstat(sbp);
1317#endif
1318	return (error);
1319}
1320
1321/*
1322 * Return status information about a file descriptor.
1323 */
1324#ifndef _SYS_SYSPROTO_H_
1325struct nfstat_args {
1326	int	fd;
1327	struct	nstat *sb;
1328};
1329#endif
1330/* ARGSUSED */
1331int
1332sys_nfstat(struct thread *td, struct nfstat_args *uap)
1333{
1334	struct nstat nub;
1335	struct stat ub;
1336	int error;
1337
1338	error = kern_fstat(td, uap->fd, &ub);
1339	if (error == 0) {
1340		cvtnstat(&ub, &nub);
1341		error = copyout(&nub, uap->sb, sizeof(nub));
1342	}
1343	return (error);
1344}
1345
1346/*
1347 * Return pathconf information about a file descriptor.
1348 */
1349#ifndef _SYS_SYSPROTO_H_
1350struct fpathconf_args {
1351	int	fd;
1352	int	name;
1353};
1354#endif
1355/* ARGSUSED */
1356int
1357sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1358{
1359	struct file *fp;
1360	struct vnode *vp;
1361	cap_rights_t rights;
1362	int error;
1363
1364	error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1365	if (error != 0)
1366		return (error);
1367
1368	/* If asynchronous I/O is available, it works for all descriptors. */
1369	if (uap->name == _PC_ASYNC_IO) {
1370		td->td_retval[0] = async_io_version;
1371		goto out;
1372	}
1373	vp = fp->f_vnode;
1374	if (vp != NULL) {
1375		vn_lock(vp, LK_SHARED | LK_RETRY);
1376		error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1377		VOP_UNLOCK(vp, 0);
1378	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1379		if (uap->name != _PC_PIPE_BUF) {
1380			error = EINVAL;
1381		} else {
1382			td->td_retval[0] = PIPE_BUF;
1383			error = 0;
1384		}
1385	} else {
1386		error = EOPNOTSUPP;
1387	}
1388out:
1389	fdrop(fp, td);
1390	return (error);
1391}
1392
1393/*
1394 * Initialize filecaps structure.
1395 */
1396void
1397filecaps_init(struct filecaps *fcaps)
1398{
1399
1400	bzero(fcaps, sizeof(*fcaps));
1401	fcaps->fc_nioctls = -1;
1402}
1403
1404/*
1405 * Copy filecaps structure allocating memory for ioctls array if needed.
1406 */
1407void
1408filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1409{
1410	size_t size;
1411
1412	*dst = *src;
1413	if (src->fc_ioctls != NULL) {
1414		KASSERT(src->fc_nioctls > 0,
1415		    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1416
1417		size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1418		dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1419		bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1420	}
1421}
1422
1423/*
1424 * Move filecaps structure to the new place and clear the old place.
1425 */
1426void
1427filecaps_move(struct filecaps *src, struct filecaps *dst)
1428{
1429
1430	*dst = *src;
1431	bzero(src, sizeof(*src));
1432}
1433
1434/*
1435 * Fill the given filecaps structure with full rights.
1436 */
1437static void
1438filecaps_fill(struct filecaps *fcaps)
1439{
1440
1441	CAP_ALL(&fcaps->fc_rights);
1442	fcaps->fc_ioctls = NULL;
1443	fcaps->fc_nioctls = -1;
1444	fcaps->fc_fcntls = CAP_FCNTL_ALL;
1445}
1446
1447/*
1448 * Free memory allocated within filecaps structure.
1449 */
1450void
1451filecaps_free(struct filecaps *fcaps)
1452{
1453
1454	free(fcaps->fc_ioctls, M_FILECAPS);
1455	bzero(fcaps, sizeof(*fcaps));
1456}
1457
1458/*
1459 * Validate the given filecaps structure.
1460 */
1461static void
1462filecaps_validate(const struct filecaps *fcaps, const char *func)
1463{
1464
1465	KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1466	    ("%s: invalid rights", func));
1467	KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1468	    ("%s: invalid fcntls", func));
1469	KASSERT(fcaps->fc_fcntls == 0 ||
1470	    cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1471	    ("%s: fcntls without CAP_FCNTL", func));
1472	KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1473	    (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1474	    ("%s: invalid ioctls", func));
1475	KASSERT(fcaps->fc_nioctls == 0 ||
1476	    cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1477	    ("%s: ioctls without CAP_IOCTL", func));
1478}
1479
1480static void
1481fdgrowtable_exp(struct filedesc *fdp, int nfd)
1482{
1483	int nfd1;
1484
1485	FILEDESC_XLOCK_ASSERT(fdp);
1486
1487	nfd1 = fdp->fd_nfiles * 2;
1488	if (nfd1 < nfd)
1489		nfd1 = nfd;
1490	fdgrowtable(fdp, nfd1);
1491}
1492
1493/*
1494 * Grow the file table to accomodate (at least) nfd descriptors.
1495 */
1496static void
1497fdgrowtable(struct filedesc *fdp, int nfd)
1498{
1499	struct filedesc0 *fdp0;
1500	struct freetable *ft;
1501	struct filedescent *ntable;
1502	struct filedescent *otable;
1503	int nnfiles, onfiles;
1504	NDSLOTTYPE *nmap, *omap;
1505
1506	FILEDESC_XLOCK_ASSERT(fdp);
1507
1508	KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1509
1510	/* save old values */
1511	onfiles = fdp->fd_nfiles;
1512	otable = fdp->fd_ofiles;
1513	omap = fdp->fd_map;
1514
1515	/* compute the size of the new table */
1516	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1517	if (nnfiles <= onfiles)
1518		/* the table is already large enough */
1519		return;
1520
1521	/*
1522	 * Allocate a new table.  We need enough space for the
1523	 * file entries themselves and the struct freetable we will use
1524	 * when we decommission the table and place it on the freelist.
1525	 * We place the struct freetable in the middle so we don't have
1526	 * to worry about padding.
1527	 */
1528	ntable = malloc(nnfiles * sizeof(ntable[0]) + sizeof(struct freetable),
1529	    M_FILEDESC, M_ZERO | M_WAITOK);
1530	/* copy the old data over and point at the new tables */
1531	memcpy(ntable, otable, onfiles * sizeof(*otable));
1532	fdp->fd_ofiles = ntable;
1533
1534	/*
1535	 * Allocate a new map only if the old is not large enough.  It will
1536	 * grow at a slower rate than the table as it can map more
1537	 * entries than the table can hold.
1538	 */
1539	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1540		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1541		    M_ZERO | M_WAITOK);
1542		/* copy over the old data and update the pointer */
1543		memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1544		fdp->fd_map = nmap;
1545	}
1546
1547	/*
1548	 * In order to have a valid pattern for fget_unlocked()
1549	 * fdp->fd_nfiles must be the last member to be updated, otherwise
1550	 * fget_unlocked() consumers may reference a new, higher value for
1551	 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1552	 * resulting in OOB accesses.
1553	 */
1554	atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1555
1556	/*
1557	 * Do not free the old file table, as some threads may still
1558	 * reference entries within it.  Instead, place it on a freelist
1559	 * which will be processed when the struct filedesc is released.
1560	 *
1561	 * Note that if onfiles == NDFILE, we're dealing with the original
1562	 * static allocation contained within (struct filedesc0 *)fdp,
1563	 * which must not be freed.
1564	 */
1565	if (onfiles > NDFILE) {
1566		ft = (struct freetable *)&otable[onfiles];
1567		fdp0 = (struct filedesc0 *)fdp;
1568		ft->ft_table = otable;
1569		SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1570	}
1571	/*
1572	 * The map does not have the same possibility of threads still
1573	 * holding references to it.  So always free it as long as it
1574	 * does not reference the original static allocation.
1575	 */
1576	if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1577		free(omap, M_FILEDESC);
1578}
1579
1580/*
1581 * Allocate a file descriptor for the process.
1582 */
1583int
1584fdalloc(struct thread *td, int minfd, int *result)
1585{
1586	struct proc *p = td->td_proc;
1587	struct filedesc *fdp = p->p_fd;
1588	int fd = -1, maxfd, allocfd;
1589#ifdef RACCT
1590	int error;
1591#endif
1592
1593	FILEDESC_XLOCK_ASSERT(fdp);
1594
1595	if (fdp->fd_freefile > minfd)
1596		minfd = fdp->fd_freefile;
1597
1598	maxfd = getmaxfd(p);
1599
1600	/*
1601	 * Search the bitmap for a free descriptor starting at minfd.
1602	 * If none is found, grow the file table.
1603	 */
1604	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1605	if (fd >= maxfd)
1606		return (EMFILE);
1607	if (fd >= fdp->fd_nfiles) {
1608		allocfd = min(fd * 2, maxfd);
1609#ifdef RACCT
1610		PROC_LOCK(p);
1611		error = racct_set(p, RACCT_NOFILE, allocfd);
1612		PROC_UNLOCK(p);
1613		if (error != 0)
1614			return (EMFILE);
1615#endif
1616		/*
1617		 * fd is already equal to first free descriptor >= minfd, so
1618		 * we only need to grow the table and we are done.
1619		 */
1620		fdgrowtable_exp(fdp, allocfd);
1621	}
1622
1623	/*
1624	 * Perform some sanity checks, then mark the file descriptor as
1625	 * used and return it to the caller.
1626	 */
1627	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1628	    ("invalid descriptor %d", fd));
1629	KASSERT(!fdisused(fdp, fd),
1630	    ("fd_first_free() returned non-free descriptor"));
1631	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1632	    ("file descriptor isn't free"));
1633	KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1634	fdused(fdp, fd);
1635	*result = fd;
1636	return (0);
1637}
1638
1639/*
1640 * Allocate n file descriptors for the process.
1641 */
1642int
1643fdallocn(struct thread *td, int minfd, int *fds, int n)
1644{
1645	struct proc *p = td->td_proc;
1646	struct filedesc *fdp = p->p_fd;
1647	int i;
1648
1649	FILEDESC_XLOCK_ASSERT(fdp);
1650
1651	for (i = 0; i < n; i++)
1652		if (fdalloc(td, 0, &fds[i]) != 0)
1653			break;
1654
1655	if (i < n) {
1656		for (i--; i >= 0; i--)
1657			fdunused(fdp, fds[i]);
1658		return (EMFILE);
1659	}
1660
1661	return (0);
1662}
1663
1664/*
1665 * Create a new open file structure and allocate a file decriptor for the
1666 * process that refers to it.  We add one reference to the file for the
1667 * descriptor table and one reference for resultfp. This is to prevent us
1668 * being preempted and the entry in the descriptor table closed after we
1669 * release the FILEDESC lock.
1670 */
1671int
1672falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1673{
1674	struct file *fp;
1675	int error, fd;
1676
1677	error = falloc_noinstall(td, &fp);
1678	if (error)
1679		return (error);		/* no reference held on error */
1680
1681	error = finstall(td, fp, &fd, flags, NULL);
1682	if (error) {
1683		fdrop(fp, td);		/* one reference (fp only) */
1684		return (error);
1685	}
1686
1687	if (resultfp != NULL)
1688		*resultfp = fp;		/* copy out result */
1689	else
1690		fdrop(fp, td);		/* release local reference */
1691
1692	if (resultfd != NULL)
1693		*resultfd = fd;
1694
1695	return (0);
1696}
1697
1698/*
1699 * Create a new open file structure without allocating a file descriptor.
1700 */
1701int
1702falloc_noinstall(struct thread *td, struct file **resultfp)
1703{
1704	struct file *fp;
1705	int maxuserfiles = maxfiles - (maxfiles / 20);
1706	static struct timeval lastfail;
1707	static int curfail;
1708
1709	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1710
1711	if ((openfiles >= maxuserfiles &&
1712	    priv_check(td, PRIV_MAXFILES) != 0) ||
1713	    openfiles >= maxfiles) {
1714		if (ppsratecheck(&lastfail, &curfail, 1)) {
1715			printf("kern.maxfiles limit exceeded by uid %i, "
1716			    "please see tuning(7).\n", td->td_ucred->cr_ruid);
1717		}
1718		return (ENFILE);
1719	}
1720	atomic_add_int(&openfiles, 1);
1721	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1722	refcount_init(&fp->f_count, 1);
1723	fp->f_cred = crhold(td->td_ucred);
1724	fp->f_ops = &badfileops;
1725	fp->f_data = NULL;
1726	fp->f_vnode = NULL;
1727	*resultfp = fp;
1728	return (0);
1729}
1730
1731/*
1732 * Install a file in a file descriptor table.
1733 */
1734int
1735finstall(struct thread *td, struct file *fp, int *fd, int flags,
1736    struct filecaps *fcaps)
1737{
1738	struct filedesc *fdp = td->td_proc->p_fd;
1739	struct filedescent *fde;
1740	int error;
1741
1742	KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1743	KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1744	if (fcaps != NULL)
1745		filecaps_validate(fcaps, __func__);
1746
1747	FILEDESC_XLOCK(fdp);
1748	if ((error = fdalloc(td, 0, fd))) {
1749		FILEDESC_XUNLOCK(fdp);
1750		return (error);
1751	}
1752	fhold(fp);
1753	fde = &fdp->fd_ofiles[*fd];
1754	fde->fde_file = fp;
1755	if ((flags & O_CLOEXEC) != 0)
1756		fde->fde_flags |= UF_EXCLOSE;
1757	if (fcaps != NULL)
1758		filecaps_move(fcaps, &fde->fde_caps);
1759	else
1760		filecaps_fill(&fde->fde_caps);
1761	FILEDESC_XUNLOCK(fdp);
1762	return (0);
1763}
1764
1765/*
1766 * Build a new filedesc structure from another.
1767 * Copy the current, root, and jail root vnode references.
1768 */
1769struct filedesc *
1770fdinit(struct filedesc *fdp)
1771{
1772	struct filedesc0 *newfdp;
1773
1774	newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1775	FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1776	if (fdp != NULL) {
1777		FILEDESC_SLOCK(fdp);
1778		newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1779		if (newfdp->fd_fd.fd_cdir)
1780			VREF(newfdp->fd_fd.fd_cdir);
1781		newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1782		if (newfdp->fd_fd.fd_rdir)
1783			VREF(newfdp->fd_fd.fd_rdir);
1784		newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1785		if (newfdp->fd_fd.fd_jdir)
1786			VREF(newfdp->fd_fd.fd_jdir);
1787		FILEDESC_SUNLOCK(fdp);
1788	}
1789
1790	/* Create the file descriptor table. */
1791	newfdp->fd_fd.fd_refcnt = 1;
1792	newfdp->fd_fd.fd_holdcnt = 1;
1793	newfdp->fd_fd.fd_cmask = CMASK;
1794	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1795	newfdp->fd_fd.fd_nfiles = NDFILE;
1796	newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1797	newfdp->fd_fd.fd_lastfile = -1;
1798	return (&newfdp->fd_fd);
1799}
1800
1801static struct filedesc *
1802fdhold(struct proc *p)
1803{
1804	struct filedesc *fdp;
1805
1806	mtx_lock(&fdesc_mtx);
1807	fdp = p->p_fd;
1808	if (fdp != NULL)
1809		fdp->fd_holdcnt++;
1810	mtx_unlock(&fdesc_mtx);
1811	return (fdp);
1812}
1813
1814static void
1815fddrop(struct filedesc *fdp)
1816{
1817	struct filedesc0 *fdp0;
1818	struct freetable *ft;
1819	int i;
1820
1821	mtx_lock(&fdesc_mtx);
1822	i = --fdp->fd_holdcnt;
1823	mtx_unlock(&fdesc_mtx);
1824	if (i > 0)
1825		return;
1826
1827	FILEDESC_LOCK_DESTROY(fdp);
1828	fdp0 = (struct filedesc0 *)fdp;
1829	while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1830		SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1831		free(ft->ft_table, M_FILEDESC);
1832	}
1833	free(fdp, M_FILEDESC);
1834}
1835
1836/*
1837 * Share a filedesc structure.
1838 */
1839struct filedesc *
1840fdshare(struct filedesc *fdp)
1841{
1842
1843	FILEDESC_XLOCK(fdp);
1844	fdp->fd_refcnt++;
1845	FILEDESC_XUNLOCK(fdp);
1846	return (fdp);
1847}
1848
1849/*
1850 * Unshare a filedesc structure, if necessary by making a copy
1851 */
1852void
1853fdunshare(struct thread *td)
1854{
1855	struct filedesc *tmp;
1856	struct proc *p = td->td_proc;
1857
1858	if (p->p_fd->fd_refcnt == 1)
1859		return;
1860
1861	tmp = fdcopy(p->p_fd);
1862	fdescfree(td);
1863	p->p_fd = tmp;
1864}
1865
1866/*
1867 * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
1868 * this is to ease callers, not catch errors.
1869 */
1870struct filedesc *
1871fdcopy(struct filedesc *fdp)
1872{
1873	struct filedesc *newfdp;
1874	struct filedescent *nfde, *ofde;
1875	int i;
1876
1877	/* Certain daemons might not have file descriptors. */
1878	if (fdp == NULL)
1879		return (NULL);
1880
1881	newfdp = fdinit(fdp);
1882	FILEDESC_SLOCK(fdp);
1883	while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1884		FILEDESC_SUNLOCK(fdp);
1885		FILEDESC_XLOCK(newfdp);
1886		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1887		FILEDESC_XUNLOCK(newfdp);
1888		FILEDESC_SLOCK(fdp);
1889	}
1890	/* copy all passable descriptors (i.e. not kqueue) */
1891	newfdp->fd_freefile = -1;
1892	for (i = 0; i <= fdp->fd_lastfile; ++i) {
1893		ofde = &fdp->fd_ofiles[i];
1894		if (fdisused(fdp, i) &&
1895		    (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1896		    ofde->fde_file->f_ops != &badfileops) {
1897			nfde = &newfdp->fd_ofiles[i];
1898			*nfde = *ofde;
1899			filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1900			fhold(nfde->fde_file);
1901			newfdp->fd_lastfile = i;
1902		} else {
1903			if (newfdp->fd_freefile == -1)
1904				newfdp->fd_freefile = i;
1905		}
1906	}
1907	newfdp->fd_cmask = fdp->fd_cmask;
1908	FILEDESC_SUNLOCK(fdp);
1909	FILEDESC_XLOCK(newfdp);
1910	for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1911		if (newfdp->fd_ofiles[i].fde_file != NULL)
1912			fdused(newfdp, i);
1913	}
1914	if (newfdp->fd_freefile == -1)
1915		newfdp->fd_freefile = i;
1916	FILEDESC_XUNLOCK(newfdp);
1917	return (newfdp);
1918}
1919
1920/*
1921 * Release a filedesc structure.
1922 */
1923void
1924fdescfree(struct thread *td)
1925{
1926	struct filedesc *fdp;
1927	int i;
1928	struct filedesc_to_leader *fdtol;
1929	struct file *fp;
1930	struct vnode *cdir, *jdir, *rdir, *vp;
1931	struct flock lf;
1932
1933	/* Certain daemons might not have file descriptors. */
1934	fdp = td->td_proc->p_fd;
1935	if (fdp == NULL)
1936		return;
1937
1938#ifdef RACCT
1939	PROC_LOCK(td->td_proc);
1940	racct_set(td->td_proc, RACCT_NOFILE, 0);
1941	PROC_UNLOCK(td->td_proc);
1942#endif
1943
1944	/* Check for special need to clear POSIX style locks */
1945	fdtol = td->td_proc->p_fdtol;
1946	if (fdtol != NULL) {
1947		FILEDESC_XLOCK(fdp);
1948		KASSERT(fdtol->fdl_refcount > 0,
1949		    ("filedesc_to_refcount botch: fdl_refcount=%d",
1950		    fdtol->fdl_refcount));
1951		if (fdtol->fdl_refcount == 1 &&
1952		    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1953			for (i = 0; i <= fdp->fd_lastfile; i++) {
1954				fp = fdp->fd_ofiles[i].fde_file;
1955				if (fp == NULL || fp->f_type != DTYPE_VNODE)
1956					continue;
1957				fhold(fp);
1958				FILEDESC_XUNLOCK(fdp);
1959				lf.l_whence = SEEK_SET;
1960				lf.l_start = 0;
1961				lf.l_len = 0;
1962				lf.l_type = F_UNLCK;
1963				vp = fp->f_vnode;
1964				(void) VOP_ADVLOCK(vp,
1965				    (caddr_t)td->td_proc->p_leader, F_UNLCK,
1966				    &lf, F_POSIX);
1967				FILEDESC_XLOCK(fdp);
1968				fdrop(fp, td);
1969			}
1970		}
1971	retry:
1972		if (fdtol->fdl_refcount == 1) {
1973			if (fdp->fd_holdleaderscount > 0 &&
1974			    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1975				/*
1976				 * close() or do_dup() has cleared a reference
1977				 * in a shared file descriptor table.
1978				 */
1979				fdp->fd_holdleaderswakeup = 1;
1980				sx_sleep(&fdp->fd_holdleaderscount,
1981				    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1982				goto retry;
1983			}
1984			if (fdtol->fdl_holdcount > 0) {
1985				/*
1986				 * Ensure that fdtol->fdl_leader remains
1987				 * valid in closef().
1988				 */
1989				fdtol->fdl_wakeup = 1;
1990				sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1991				    "fdlhold", 0);
1992				goto retry;
1993			}
1994		}
1995		fdtol->fdl_refcount--;
1996		if (fdtol->fdl_refcount == 0 &&
1997		    fdtol->fdl_holdcount == 0) {
1998			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1999			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2000		} else
2001			fdtol = NULL;
2002		td->td_proc->p_fdtol = NULL;
2003		FILEDESC_XUNLOCK(fdp);
2004		if (fdtol != NULL)
2005			free(fdtol, M_FILEDESC_TO_LEADER);
2006	}
2007
2008	mtx_lock(&fdesc_mtx);
2009	td->td_proc->p_fd = NULL;
2010	mtx_unlock(&fdesc_mtx);
2011
2012	FILEDESC_XLOCK(fdp);
2013	i = --fdp->fd_refcnt;
2014	FILEDESC_XUNLOCK(fdp);
2015	if (i > 0)
2016		return;
2017
2018	for (i = 0; i <= fdp->fd_lastfile; i++) {
2019		fp = fdp->fd_ofiles[i].fde_file;
2020		if (fp != NULL) {
2021			FILEDESC_XLOCK(fdp);
2022			fdfree(fdp, i);
2023			FILEDESC_XUNLOCK(fdp);
2024			(void) closef(fp, td);
2025		}
2026	}
2027	FILEDESC_XLOCK(fdp);
2028
2029	if (fdp->fd_nfiles > NDFILE)
2030		free(fdp->fd_ofiles, M_FILEDESC);
2031	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2032		free(fdp->fd_map, M_FILEDESC);
2033
2034	fdp->fd_nfiles = 0;
2035
2036	cdir = fdp->fd_cdir;
2037	fdp->fd_cdir = NULL;
2038	rdir = fdp->fd_rdir;
2039	fdp->fd_rdir = NULL;
2040	jdir = fdp->fd_jdir;
2041	fdp->fd_jdir = NULL;
2042	FILEDESC_XUNLOCK(fdp);
2043
2044	if (cdir != NULL)
2045		vrele(cdir);
2046	if (rdir != NULL)
2047		vrele(rdir);
2048	if (jdir != NULL)
2049		vrele(jdir);
2050
2051	fddrop(fdp);
2052}
2053
2054/*
2055 * For setugid programs, we don't want to people to use that setugidness
2056 * to generate error messages which write to a file which otherwise would
2057 * otherwise be off-limits to the process.  We check for filesystems where
2058 * the vnode can change out from under us after execve (like [lin]procfs).
2059 *
2060 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2061 * sufficient.  We also don't check for setugidness since we know we are.
2062 */
2063static int
2064is_unsafe(struct file *fp)
2065{
2066	if (fp->f_type == DTYPE_VNODE) {
2067		struct vnode *vp = fp->f_vnode;
2068
2069		if ((vp->v_vflag & VV_PROCDEP) != 0)
2070			return (1);
2071	}
2072	return (0);
2073}
2074
2075/*
2076 * Make this setguid thing safe, if at all possible.
2077 */
2078void
2079setugidsafety(struct thread *td)
2080{
2081	struct filedesc *fdp;
2082	struct file *fp;
2083	int i;
2084
2085	fdp = td->td_proc->p_fd;
2086	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2087	FILEDESC_XLOCK(fdp);
2088	for (i = 0; i <= fdp->fd_lastfile; i++) {
2089		if (i > 2)
2090			break;
2091		fp = fdp->fd_ofiles[i].fde_file;
2092		if (fp != NULL && is_unsafe(fp)) {
2093			knote_fdclose(td, i);
2094			/*
2095			 * NULL-out descriptor prior to close to avoid
2096			 * a race while close blocks.
2097			 */
2098			fdfree(fdp, i);
2099			FILEDESC_XUNLOCK(fdp);
2100			(void) closef(fp, td);
2101			FILEDESC_XLOCK(fdp);
2102		}
2103	}
2104	FILEDESC_XUNLOCK(fdp);
2105}
2106
2107/*
2108 * If a specific file object occupies a specific file descriptor, close the
2109 * file descriptor entry and drop a reference on the file object.  This is a
2110 * convenience function to handle a subsequent error in a function that calls
2111 * falloc() that handles the race that another thread might have closed the
2112 * file descriptor out from under the thread creating the file object.
2113 */
2114void
2115fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2116{
2117
2118	FILEDESC_XLOCK(fdp);
2119	if (fdp->fd_ofiles[idx].fde_file == fp) {
2120		fdfree(fdp, idx);
2121		FILEDESC_XUNLOCK(fdp);
2122		fdrop(fp, td);
2123	} else
2124		FILEDESC_XUNLOCK(fdp);
2125}
2126
2127/*
2128 * Close any files on exec?
2129 */
2130void
2131fdcloseexec(struct thread *td)
2132{
2133	struct filedesc *fdp;
2134	struct filedescent *fde;
2135	struct file *fp;
2136	int i;
2137
2138	fdp = td->td_proc->p_fd;
2139	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2140	FILEDESC_XLOCK(fdp);
2141	for (i = 0; i <= fdp->fd_lastfile; i++) {
2142		fde = &fdp->fd_ofiles[i];
2143		fp = fde->fde_file;
2144		if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2145		    (fde->fde_flags & UF_EXCLOSE))) {
2146			fdfree(fdp, i);
2147			(void) closefp(fdp, i, fp, td, 0);
2148			/* closefp() drops the FILEDESC lock. */
2149			FILEDESC_XLOCK(fdp);
2150		}
2151	}
2152	FILEDESC_XUNLOCK(fdp);
2153}
2154
2155/*
2156 * It is unsafe for set[ug]id processes to be started with file
2157 * descriptors 0..2 closed, as these descriptors are given implicit
2158 * significance in the Standard C library.  fdcheckstd() will create a
2159 * descriptor referencing /dev/null for each of stdin, stdout, and
2160 * stderr that is not already open.
2161 */
2162int
2163fdcheckstd(struct thread *td)
2164{
2165	struct filedesc *fdp;
2166	register_t retval, save;
2167	int i, error, devnull;
2168
2169	fdp = td->td_proc->p_fd;
2170	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2171	devnull = -1;
2172	error = 0;
2173	for (i = 0; i < 3; i++) {
2174		if (fdp->fd_ofiles[i].fde_file != NULL)
2175			continue;
2176		if (devnull < 0) {
2177			save = td->td_retval[0];
2178			error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2179			    O_RDWR, 0);
2180			devnull = td->td_retval[0];
2181			td->td_retval[0] = save;
2182			if (error)
2183				break;
2184			KASSERT(devnull == i, ("oof, we didn't get our fd"));
2185		} else {
2186			error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2187			if (error != 0)
2188				break;
2189		}
2190	}
2191	return (error);
2192}
2193
2194/*
2195 * Internal form of close.  Decrement reference count on file structure.
2196 * Note: td may be NULL when closing a file that was being passed in a
2197 * message.
2198 *
2199 * XXXRW: Giant is not required for the caller, but often will be held; this
2200 * makes it moderately likely the Giant will be recursed in the VFS case.
2201 */
2202int
2203closef(struct file *fp, struct thread *td)
2204{
2205	struct vnode *vp;
2206	struct flock lf;
2207	struct filedesc_to_leader *fdtol;
2208	struct filedesc *fdp;
2209
2210	/*
2211	 * POSIX record locking dictates that any close releases ALL
2212	 * locks owned by this process.  This is handled by setting
2213	 * a flag in the unlock to free ONLY locks obeying POSIX
2214	 * semantics, and not to free BSD-style file locks.
2215	 * If the descriptor was in a message, POSIX-style locks
2216	 * aren't passed with the descriptor, and the thread pointer
2217	 * will be NULL.  Callers should be careful only to pass a
2218	 * NULL thread pointer when there really is no owning
2219	 * context that might have locks, or the locks will be
2220	 * leaked.
2221	 */
2222	if (fp->f_type == DTYPE_VNODE && td != NULL) {
2223		vp = fp->f_vnode;
2224		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2225			lf.l_whence = SEEK_SET;
2226			lf.l_start = 0;
2227			lf.l_len = 0;
2228			lf.l_type = F_UNLCK;
2229			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2230			    F_UNLCK, &lf, F_POSIX);
2231		}
2232		fdtol = td->td_proc->p_fdtol;
2233		if (fdtol != NULL) {
2234			/*
2235			 * Handle special case where file descriptor table is
2236			 * shared between multiple process leaders.
2237			 */
2238			fdp = td->td_proc->p_fd;
2239			FILEDESC_XLOCK(fdp);
2240			for (fdtol = fdtol->fdl_next;
2241			     fdtol != td->td_proc->p_fdtol;
2242			     fdtol = fdtol->fdl_next) {
2243				if ((fdtol->fdl_leader->p_flag &
2244				     P_ADVLOCK) == 0)
2245					continue;
2246				fdtol->fdl_holdcount++;
2247				FILEDESC_XUNLOCK(fdp);
2248				lf.l_whence = SEEK_SET;
2249				lf.l_start = 0;
2250				lf.l_len = 0;
2251				lf.l_type = F_UNLCK;
2252				vp = fp->f_vnode;
2253				(void) VOP_ADVLOCK(vp,
2254				    (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2255				    F_POSIX);
2256				FILEDESC_XLOCK(fdp);
2257				fdtol->fdl_holdcount--;
2258				if (fdtol->fdl_holdcount == 0 &&
2259				    fdtol->fdl_wakeup != 0) {
2260					fdtol->fdl_wakeup = 0;
2261					wakeup(fdtol);
2262				}
2263			}
2264			FILEDESC_XUNLOCK(fdp);
2265		}
2266	}
2267	return (fdrop(fp, td));
2268}
2269
2270/*
2271 * Initialize the file pointer with the specified properties.
2272 *
2273 * The ops are set with release semantics to be certain that the flags, type,
2274 * and data are visible when ops is.  This is to prevent ops methods from being
2275 * called with bad data.
2276 */
2277void
2278finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2279{
2280	fp->f_data = data;
2281	fp->f_flag = flag;
2282	fp->f_type = type;
2283	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2284}
2285
2286int
2287fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2288    int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2289{
2290	struct file *fp;
2291	u_int count;
2292#ifdef CAPABILITIES
2293	cap_rights_t haverights;
2294	int error;
2295#endif
2296
2297	/*
2298	 * Avoid reads reordering and then a first access to the
2299	 * fdp->fd_ofiles table which could result in OOB operation.
2300	 */
2301	if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2302		return (EBADF);
2303	/*
2304	 * Fetch the descriptor locklessly.  We avoid fdrop() races by
2305	 * never raising a refcount above 0.  To accomplish this we have
2306	 * to use a cmpset loop rather than an atomic_add.  The descriptor
2307	 * must be re-verified once we acquire a reference to be certain
2308	 * that the identity is still correct and we did not lose a race
2309	 * due to preemption.
2310	 */
2311	for (;;) {
2312		fp = fdp->fd_ofiles[fd].fde_file;
2313		if (fp == NULL)
2314			return (EBADF);
2315#ifdef CAPABILITIES
2316		haverights = *cap_rights(fdp, fd);
2317		if (needrightsp != NULL) {
2318			error = cap_check(&haverights, needrightsp);
2319			if (error != 0)
2320				return (error);
2321			if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2322				error = cap_fcntl_check(fdp, fd, needfcntl);
2323				if (error != 0)
2324					return (error);
2325			}
2326		}
2327#endif
2328		count = fp->f_count;
2329		if (count == 0)
2330			continue;
2331		/*
2332		 * Use an acquire barrier to prevent caching of fd_ofiles
2333		 * so it is refreshed for verification.
2334		 */
2335		if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2336			continue;
2337		if (fp == fdp->fd_ofiles[fd].fde_file)
2338			break;
2339		fdrop(fp, curthread);
2340	}
2341	*fpp = fp;
2342	if (haverightsp != NULL) {
2343#ifdef CAPABILITIES
2344		*haverightsp = haverights;
2345#else
2346		CAP_ALL(haverightsp);
2347#endif
2348	}
2349	return (0);
2350}
2351
2352/*
2353 * Extract the file pointer associated with the specified descriptor for the
2354 * current user process.
2355 *
2356 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2357 * returned.
2358 *
2359 * File's rights will be checked against the capability rights mask.
2360 *
2361 * If an error occured the non-zero error is returned and *fpp is set to
2362 * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
2363 * responsible for fdrop().
2364 */
2365static __inline int
2366_fget(struct thread *td, int fd, struct file **fpp, int flags,
2367    cap_rights_t *needrightsp, u_char *maxprotp)
2368{
2369	struct filedesc *fdp;
2370	struct file *fp;
2371	cap_rights_t haverights, needrights;
2372	int error;
2373
2374	*fpp = NULL;
2375	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2376		return (EBADF);
2377	if (needrightsp != NULL)
2378		needrights = *needrightsp;
2379	else
2380		cap_rights_init(&needrights);
2381	if (maxprotp != NULL)
2382		cap_rights_set(&needrights, CAP_MMAP);
2383	error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2384	if (error != 0)
2385		return (error);
2386	if (fp->f_ops == &badfileops) {
2387		fdrop(fp, td);
2388		return (EBADF);
2389	}
2390
2391#ifdef CAPABILITIES
2392	/*
2393	 * If requested, convert capability rights to access flags.
2394	 */
2395	if (maxprotp != NULL)
2396		*maxprotp = cap_rights_to_vmprot(&haverights);
2397#else /* !CAPABILITIES */
2398	if (maxprotp != NULL)
2399		*maxprotp = VM_PROT_ALL;
2400#endif /* CAPABILITIES */
2401
2402	/*
2403	 * FREAD and FWRITE failure return EBADF as per POSIX.
2404	 */
2405	error = 0;
2406	switch (flags) {
2407	case FREAD:
2408	case FWRITE:
2409		if ((fp->f_flag & flags) == 0)
2410			error = EBADF;
2411		break;
2412	case FEXEC:
2413	    	if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2414		    ((fp->f_flag & FWRITE) != 0))
2415			error = EBADF;
2416		break;
2417	case 0:
2418		break;
2419	default:
2420		KASSERT(0, ("wrong flags"));
2421	}
2422
2423	if (error != 0) {
2424		fdrop(fp, td);
2425		return (error);
2426	}
2427
2428	*fpp = fp;
2429	return (0);
2430}
2431
2432int
2433fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2434{
2435
2436	return(_fget(td, fd, fpp, 0, rightsp, NULL));
2437}
2438
2439int
2440fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2441    struct file **fpp)
2442{
2443
2444	return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2445}
2446
2447int
2448fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2449{
2450
2451	return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2452}
2453
2454int
2455fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2456{
2457
2458	return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2459}
2460
2461/*
2462 * Like fget() but loads the underlying vnode, or returns an error if the
2463 * descriptor does not represent a vnode.  Note that pipes use vnodes but
2464 * never have VM objects.  The returned vnode will be vref()'d.
2465 *
2466 * XXX: what about the unused flags ?
2467 */
2468static __inline int
2469_fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2470    struct vnode **vpp)
2471{
2472	struct file *fp;
2473	int error;
2474
2475	*vpp = NULL;
2476	error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2477	if (error != 0)
2478		return (error);
2479	if (fp->f_vnode == NULL) {
2480		error = EINVAL;
2481	} else {
2482		*vpp = fp->f_vnode;
2483		vref(*vpp);
2484	}
2485	fdrop(fp, td);
2486
2487	return (error);
2488}
2489
2490int
2491fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2492{
2493
2494	return (_fgetvp(td, fd, 0, rightsp, vpp));
2495}
2496
2497int
2498fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2499    struct filecaps *havecaps, struct vnode **vpp)
2500{
2501	struct filedesc *fdp;
2502	struct file *fp;
2503#ifdef CAPABILITIES
2504	int error;
2505#endif
2506
2507	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2508		return (EBADF);
2509
2510	fp = fget_locked(fdp, fd);
2511	if (fp == NULL || fp->f_ops == &badfileops)
2512		return (EBADF);
2513
2514#ifdef CAPABILITIES
2515	if (needrightsp != NULL) {
2516		error = cap_check(cap_rights(fdp, fd), needrightsp);
2517		if (error != 0)
2518			return (error);
2519	}
2520#endif
2521
2522	if (fp->f_vnode == NULL)
2523		return (EINVAL);
2524
2525	*vpp = fp->f_vnode;
2526	vref(*vpp);
2527	filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2528
2529	return (0);
2530}
2531
2532int
2533fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2534{
2535
2536	return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2537}
2538
2539int
2540fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2541{
2542
2543	return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2544}
2545
2546#ifdef notyet
2547int
2548fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2549    struct vnode **vpp)
2550{
2551
2552	return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2553}
2554#endif
2555
2556/*
2557 * Like fget() but loads the underlying socket, or returns an error if the
2558 * descriptor does not represent a socket.
2559 *
2560 * We bump the ref count on the returned socket.  XXX Also obtain the SX lock
2561 * in the future.
2562 *
2563 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2564 * on their file descriptor reference to prevent the socket from being free'd
2565 * during use.
2566 */
2567int
2568fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2569    u_int *fflagp)
2570{
2571	struct file *fp;
2572	int error;
2573
2574	*spp = NULL;
2575	if (fflagp != NULL)
2576		*fflagp = 0;
2577	if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2578		return (error);
2579	if (fp->f_type != DTYPE_SOCKET) {
2580		error = ENOTSOCK;
2581	} else {
2582		*spp = fp->f_data;
2583		if (fflagp)
2584			*fflagp = fp->f_flag;
2585		SOCK_LOCK(*spp);
2586		soref(*spp);
2587		SOCK_UNLOCK(*spp);
2588	}
2589	fdrop(fp, td);
2590
2591	return (error);
2592}
2593
2594/*
2595 * Drop the reference count on the socket and XXX release the SX lock in the
2596 * future.  The last reference closes the socket.
2597 *
2598 * Note: fputsock() is deprecated, see comment for fgetsock().
2599 */
2600void
2601fputsock(struct socket *so)
2602{
2603
2604	ACCEPT_LOCK();
2605	SOCK_LOCK(so);
2606	CURVNET_SET(so->so_vnet);
2607	sorele(so);
2608	CURVNET_RESTORE();
2609}
2610
2611/*
2612 * Handle the last reference to a file being closed.
2613 */
2614int
2615_fdrop(struct file *fp, struct thread *td)
2616{
2617	int error;
2618
2619	error = 0;
2620	if (fp->f_count != 0)
2621		panic("fdrop: count %d", fp->f_count);
2622	if (fp->f_ops != &badfileops)
2623		error = fo_close(fp, td);
2624	atomic_subtract_int(&openfiles, 1);
2625	crfree(fp->f_cred);
2626	free(fp->f_advice, M_FADVISE);
2627	uma_zfree(file_zone, fp);
2628
2629	return (error);
2630}
2631
2632/*
2633 * Apply an advisory lock on a file descriptor.
2634 *
2635 * Just attempt to get a record lock of the requested type on the entire file
2636 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2637 */
2638#ifndef _SYS_SYSPROTO_H_
2639struct flock_args {
2640	int	fd;
2641	int	how;
2642};
2643#endif
2644/* ARGSUSED */
2645int
2646sys_flock(struct thread *td, struct flock_args *uap)
2647{
2648	struct file *fp;
2649	struct vnode *vp;
2650	struct flock lf;
2651	cap_rights_t rights;
2652	int error;
2653
2654	error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2655	if (error != 0)
2656		return (error);
2657	if (fp->f_type != DTYPE_VNODE) {
2658		fdrop(fp, td);
2659		return (EOPNOTSUPP);
2660	}
2661
2662	vp = fp->f_vnode;
2663	lf.l_whence = SEEK_SET;
2664	lf.l_start = 0;
2665	lf.l_len = 0;
2666	if (uap->how & LOCK_UN) {
2667		lf.l_type = F_UNLCK;
2668		atomic_clear_int(&fp->f_flag, FHASLOCK);
2669		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2670		goto done2;
2671	}
2672	if (uap->how & LOCK_EX)
2673		lf.l_type = F_WRLCK;
2674	else if (uap->how & LOCK_SH)
2675		lf.l_type = F_RDLCK;
2676	else {
2677		error = EBADF;
2678		goto done2;
2679	}
2680	atomic_set_int(&fp->f_flag, FHASLOCK);
2681	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2682	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2683done2:
2684	fdrop(fp, td);
2685	return (error);
2686}
2687/*
2688 * Duplicate the specified descriptor to a free descriptor.
2689 */
2690int
2691dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2692    int openerror, int *indxp)
2693{
2694	struct file *fp;
2695	int error, indx;
2696
2697	KASSERT(openerror == ENODEV || openerror == ENXIO,
2698	    ("unexpected error %d in %s", openerror, __func__));
2699
2700	/*
2701	 * If the to-be-dup'd fd number is greater than the allowed number
2702	 * of file descriptors, or the fd to be dup'd has already been
2703	 * closed, then reject.
2704	 */
2705	FILEDESC_XLOCK(fdp);
2706	if ((fp = fget_locked(fdp, dfd)) == NULL) {
2707		FILEDESC_XUNLOCK(fdp);
2708		return (EBADF);
2709	}
2710
2711	error = fdalloc(td, 0, &indx);
2712	if (error != 0) {
2713		FILEDESC_XUNLOCK(fdp);
2714		return (error);
2715	}
2716
2717	/*
2718	 * There are two cases of interest here.
2719	 *
2720	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2721	 *
2722	 * For ENXIO steal away the file structure from (dfd) and store it in
2723	 * (indx).  (dfd) is effectively closed by this operation.
2724	 */
2725	switch (openerror) {
2726	case ENODEV:
2727		/*
2728		 * Check that the mode the file is being opened for is a
2729		 * subset of the mode of the existing descriptor.
2730		 */
2731		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2732			fdunused(fdp, indx);
2733			FILEDESC_XUNLOCK(fdp);
2734			return (EACCES);
2735		}
2736		fhold(fp);
2737		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2738		filecaps_copy(&fdp->fd_ofiles[dfd].fde_caps,
2739		    &fdp->fd_ofiles[indx].fde_caps);
2740		break;
2741	case ENXIO:
2742		/*
2743		 * Steal away the file pointer from dfd and stuff it into indx.
2744		 */
2745		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2746		bzero(&fdp->fd_ofiles[dfd], sizeof(fdp->fd_ofiles[dfd]));
2747		fdunused(fdp, dfd);
2748		break;
2749	}
2750	FILEDESC_XUNLOCK(fdp);
2751	*indxp = indx;
2752	return (0);
2753}
2754
2755/*
2756 * Scan all active processes and prisons to see if any of them have a current
2757 * or root directory of `olddp'. If so, replace them with the new mount point.
2758 */
2759void
2760mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2761{
2762	struct filedesc *fdp;
2763	struct prison *pr;
2764	struct proc *p;
2765	int nrele;
2766
2767	if (vrefcnt(olddp) == 1)
2768		return;
2769	nrele = 0;
2770	sx_slock(&allproc_lock);
2771	FOREACH_PROC_IN_SYSTEM(p) {
2772		fdp = fdhold(p);
2773		if (fdp == NULL)
2774			continue;
2775		FILEDESC_XLOCK(fdp);
2776		if (fdp->fd_cdir == olddp) {
2777			vref(newdp);
2778			fdp->fd_cdir = newdp;
2779			nrele++;
2780		}
2781		if (fdp->fd_rdir == olddp) {
2782			vref(newdp);
2783			fdp->fd_rdir = newdp;
2784			nrele++;
2785		}
2786		if (fdp->fd_jdir == olddp) {
2787			vref(newdp);
2788			fdp->fd_jdir = newdp;
2789			nrele++;
2790		}
2791		FILEDESC_XUNLOCK(fdp);
2792		fddrop(fdp);
2793	}
2794	sx_sunlock(&allproc_lock);
2795	if (rootvnode == olddp) {
2796		vref(newdp);
2797		rootvnode = newdp;
2798		nrele++;
2799	}
2800	mtx_lock(&prison0.pr_mtx);
2801	if (prison0.pr_root == olddp) {
2802		vref(newdp);
2803		prison0.pr_root = newdp;
2804		nrele++;
2805	}
2806	mtx_unlock(&prison0.pr_mtx);
2807	sx_slock(&allprison_lock);
2808	TAILQ_FOREACH(pr, &allprison, pr_list) {
2809		mtx_lock(&pr->pr_mtx);
2810		if (pr->pr_root == olddp) {
2811			vref(newdp);
2812			pr->pr_root = newdp;
2813			nrele++;
2814		}
2815		mtx_unlock(&pr->pr_mtx);
2816	}
2817	sx_sunlock(&allprison_lock);
2818	while (nrele--)
2819		vrele(olddp);
2820}
2821
2822struct filedesc_to_leader *
2823filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2824{
2825	struct filedesc_to_leader *fdtol;
2826
2827	fdtol = malloc(sizeof(struct filedesc_to_leader),
2828	       M_FILEDESC_TO_LEADER,
2829	       M_WAITOK);
2830	fdtol->fdl_refcount = 1;
2831	fdtol->fdl_holdcount = 0;
2832	fdtol->fdl_wakeup = 0;
2833	fdtol->fdl_leader = leader;
2834	if (old != NULL) {
2835		FILEDESC_XLOCK(fdp);
2836		fdtol->fdl_next = old->fdl_next;
2837		fdtol->fdl_prev = old;
2838		old->fdl_next = fdtol;
2839		fdtol->fdl_next->fdl_prev = fdtol;
2840		FILEDESC_XUNLOCK(fdp);
2841	} else {
2842		fdtol->fdl_next = fdtol;
2843		fdtol->fdl_prev = fdtol;
2844	}
2845	return (fdtol);
2846}
2847
2848/*
2849 * Get file structures globally.
2850 */
2851static int
2852sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2853{
2854	struct xfile xf;
2855	struct filedesc *fdp;
2856	struct file *fp;
2857	struct proc *p;
2858	int error, n;
2859
2860	error = sysctl_wire_old_buffer(req, 0);
2861	if (error != 0)
2862		return (error);
2863	if (req->oldptr == NULL) {
2864		n = 0;
2865		sx_slock(&allproc_lock);
2866		FOREACH_PROC_IN_SYSTEM(p) {
2867			if (p->p_state == PRS_NEW)
2868				continue;
2869			fdp = fdhold(p);
2870			if (fdp == NULL)
2871				continue;
2872			/* overestimates sparse tables. */
2873			if (fdp->fd_lastfile > 0)
2874				n += fdp->fd_lastfile;
2875			fddrop(fdp);
2876		}
2877		sx_sunlock(&allproc_lock);
2878		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2879	}
2880	error = 0;
2881	bzero(&xf, sizeof(xf));
2882	xf.xf_size = sizeof(xf);
2883	sx_slock(&allproc_lock);
2884	FOREACH_PROC_IN_SYSTEM(p) {
2885		PROC_LOCK(p);
2886		if (p->p_state == PRS_NEW) {
2887			PROC_UNLOCK(p);
2888			continue;
2889		}
2890		if (p_cansee(req->td, p) != 0) {
2891			PROC_UNLOCK(p);
2892			continue;
2893		}
2894		xf.xf_pid = p->p_pid;
2895		xf.xf_uid = p->p_ucred->cr_uid;
2896		PROC_UNLOCK(p);
2897		fdp = fdhold(p);
2898		if (fdp == NULL)
2899			continue;
2900		FILEDESC_SLOCK(fdp);
2901		for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
2902			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
2903				continue;
2904			xf.xf_fd = n;
2905			xf.xf_file = fp;
2906			xf.xf_data = fp->f_data;
2907			xf.xf_vnode = fp->f_vnode;
2908			xf.xf_type = fp->f_type;
2909			xf.xf_count = fp->f_count;
2910			xf.xf_msgcount = 0;
2911			xf.xf_offset = foffset_get(fp);
2912			xf.xf_flag = fp->f_flag;
2913			error = SYSCTL_OUT(req, &xf, sizeof(xf));
2914			if (error)
2915				break;
2916		}
2917		FILEDESC_SUNLOCK(fdp);
2918		fddrop(fdp);
2919		if (error)
2920			break;
2921	}
2922	sx_sunlock(&allproc_lock);
2923	return (error);
2924}
2925
2926SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
2927    0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2928
2929#ifdef KINFO_OFILE_SIZE
2930CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2931#endif
2932
2933#ifdef COMPAT_FREEBSD7
2934static int
2935export_vnode_for_osysctl(struct vnode *vp, int type,
2936    struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2937{
2938	int error;
2939	char *fullpath, *freepath;
2940
2941	bzero(kif, sizeof(*kif));
2942	kif->kf_structsize = sizeof(*kif);
2943
2944	vref(vp);
2945	kif->kf_fd = type;
2946	kif->kf_type = KF_TYPE_VNODE;
2947	/* This function only handles directories. */
2948	if (vp->v_type != VDIR) {
2949		vrele(vp);
2950		return (ENOTDIR);
2951	}
2952	kif->kf_vnode_type = KF_VTYPE_VDIR;
2953
2954	/*
2955	 * This is not a true file descriptor, so we set a bogus refcount
2956	 * and offset to indicate these fields should be ignored.
2957	 */
2958	kif->kf_ref_count = -1;
2959	kif->kf_offset = -1;
2960
2961	freepath = NULL;
2962	fullpath = "-";
2963	FILEDESC_SUNLOCK(fdp);
2964	vn_fullpath(curthread, vp, &fullpath, &freepath);
2965	vrele(vp);
2966	strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2967	if (freepath != NULL)
2968		free(freepath, M_TEMP);
2969	error = SYSCTL_OUT(req, kif, sizeof(*kif));
2970	FILEDESC_SLOCK(fdp);
2971	return (error);
2972}
2973
2974/*
2975 * Get per-process file descriptors for use by procstat(1), et al.
2976 */
2977static int
2978sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2979{
2980	char *fullpath, *freepath;
2981	struct kinfo_ofile *kif;
2982	struct filedesc *fdp;
2983	int error, i, *name;
2984	struct shmfd *shmfd;
2985	struct socket *so;
2986	struct vnode *vp;
2987	struct ksem *ks;
2988	struct file *fp;
2989	struct proc *p;
2990	struct tty *tp;
2991
2992	name = (int *)arg1;
2993	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
2994	if (error != 0)
2995		return (error);
2996	fdp = fdhold(p);
2997	PROC_UNLOCK(p);
2998	if (fdp == NULL)
2999		return (ENOENT);
3000	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3001	FILEDESC_SLOCK(fdp);
3002	if (fdp->fd_cdir != NULL)
3003		export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3004				fdp, req);
3005	if (fdp->fd_rdir != NULL)
3006		export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3007				fdp, req);
3008	if (fdp->fd_jdir != NULL)
3009		export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3010				fdp, req);
3011	for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3012		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3013			continue;
3014		bzero(kif, sizeof(*kif));
3015		kif->kf_structsize = sizeof(*kif);
3016		ks = NULL;
3017		vp = NULL;
3018		so = NULL;
3019		tp = NULL;
3020		shmfd = NULL;
3021		kif->kf_fd = i;
3022
3023		switch (fp->f_type) {
3024		case DTYPE_VNODE:
3025			kif->kf_type = KF_TYPE_VNODE;
3026			vp = fp->f_vnode;
3027			break;
3028
3029		case DTYPE_SOCKET:
3030			kif->kf_type = KF_TYPE_SOCKET;
3031			so = fp->f_data;
3032			break;
3033
3034		case DTYPE_PIPE:
3035			kif->kf_type = KF_TYPE_PIPE;
3036			break;
3037
3038		case DTYPE_FIFO:
3039			kif->kf_type = KF_TYPE_FIFO;
3040			vp = fp->f_vnode;
3041			break;
3042
3043		case DTYPE_KQUEUE:
3044			kif->kf_type = KF_TYPE_KQUEUE;
3045			break;
3046
3047		case DTYPE_CRYPTO:
3048			kif->kf_type = KF_TYPE_CRYPTO;
3049			break;
3050
3051		case DTYPE_MQUEUE:
3052			kif->kf_type = KF_TYPE_MQUEUE;
3053			break;
3054
3055		case DTYPE_SHM:
3056			kif->kf_type = KF_TYPE_SHM;
3057			shmfd = fp->f_data;
3058			break;
3059
3060		case DTYPE_SEM:
3061			kif->kf_type = KF_TYPE_SEM;
3062			ks = fp->f_data;
3063			break;
3064
3065		case DTYPE_PTS:
3066			kif->kf_type = KF_TYPE_PTS;
3067			tp = fp->f_data;
3068			break;
3069
3070		case DTYPE_PROCDESC:
3071			kif->kf_type = KF_TYPE_PROCDESC;
3072			break;
3073
3074		default:
3075			kif->kf_type = KF_TYPE_UNKNOWN;
3076			break;
3077		}
3078		kif->kf_ref_count = fp->f_count;
3079		if (fp->f_flag & FREAD)
3080			kif->kf_flags |= KF_FLAG_READ;
3081		if (fp->f_flag & FWRITE)
3082			kif->kf_flags |= KF_FLAG_WRITE;
3083		if (fp->f_flag & FAPPEND)
3084			kif->kf_flags |= KF_FLAG_APPEND;
3085		if (fp->f_flag & FASYNC)
3086			kif->kf_flags |= KF_FLAG_ASYNC;
3087		if (fp->f_flag & FFSYNC)
3088			kif->kf_flags |= KF_FLAG_FSYNC;
3089		if (fp->f_flag & FNONBLOCK)
3090			kif->kf_flags |= KF_FLAG_NONBLOCK;
3091		if (fp->f_flag & O_DIRECT)
3092			kif->kf_flags |= KF_FLAG_DIRECT;
3093		if (fp->f_flag & FHASLOCK)
3094			kif->kf_flags |= KF_FLAG_HASLOCK;
3095		kif->kf_offset = foffset_get(fp);
3096		if (vp != NULL) {
3097			vref(vp);
3098			switch (vp->v_type) {
3099			case VNON:
3100				kif->kf_vnode_type = KF_VTYPE_VNON;
3101				break;
3102			case VREG:
3103				kif->kf_vnode_type = KF_VTYPE_VREG;
3104				break;
3105			case VDIR:
3106				kif->kf_vnode_type = KF_VTYPE_VDIR;
3107				break;
3108			case VBLK:
3109				kif->kf_vnode_type = KF_VTYPE_VBLK;
3110				break;
3111			case VCHR:
3112				kif->kf_vnode_type = KF_VTYPE_VCHR;
3113				break;
3114			case VLNK:
3115				kif->kf_vnode_type = KF_VTYPE_VLNK;
3116				break;
3117			case VSOCK:
3118				kif->kf_vnode_type = KF_VTYPE_VSOCK;
3119				break;
3120			case VFIFO:
3121				kif->kf_vnode_type = KF_VTYPE_VFIFO;
3122				break;
3123			case VBAD:
3124				kif->kf_vnode_type = KF_VTYPE_VBAD;
3125				break;
3126			default:
3127				kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3128				break;
3129			}
3130			/*
3131			 * It is OK to drop the filedesc lock here as we will
3132			 * re-validate and re-evaluate its properties when
3133			 * the loop continues.
3134			 */
3135			freepath = NULL;
3136			fullpath = "-";
3137			FILEDESC_SUNLOCK(fdp);
3138			vn_fullpath(curthread, vp, &fullpath, &freepath);
3139			vrele(vp);
3140			strlcpy(kif->kf_path, fullpath,
3141			    sizeof(kif->kf_path));
3142			if (freepath != NULL)
3143				free(freepath, M_TEMP);
3144			FILEDESC_SLOCK(fdp);
3145		}
3146		if (so != NULL) {
3147			struct sockaddr *sa;
3148
3149			if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3150			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3151				bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3152				free(sa, M_SONAME);
3153			}
3154			if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3155			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3156				bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3157				free(sa, M_SONAME);
3158			}
3159			kif->kf_sock_domain =
3160			    so->so_proto->pr_domain->dom_family;
3161			kif->kf_sock_type = so->so_type;
3162			kif->kf_sock_protocol = so->so_proto->pr_protocol;
3163		}
3164		if (tp != NULL) {
3165			strlcpy(kif->kf_path, tty_devname(tp),
3166			    sizeof(kif->kf_path));
3167		}
3168		if (shmfd != NULL)
3169			shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3170		if (ks != NULL && ksem_info != NULL)
3171			ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3172		error = SYSCTL_OUT(req, kif, sizeof(*kif));
3173		if (error)
3174			break;
3175	}
3176	FILEDESC_SUNLOCK(fdp);
3177	fddrop(fdp);
3178	free(kif, M_TEMP);
3179	return (0);
3180}
3181
3182static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3183    CTLFLAG_RD||CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3184    "Process ofiledesc entries");
3185#endif	/* COMPAT_FREEBSD7 */
3186
3187#ifdef KINFO_FILE_SIZE
3188CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3189#endif
3190
3191struct export_fd_buf {
3192	struct filedesc		*fdp;
3193	struct sbuf 		*sb;
3194	ssize_t			remainder;
3195	struct kinfo_file	kif;
3196};
3197
3198static int
3199export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3200    int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3201{
3202	struct {
3203		int	fflag;
3204		int	kf_fflag;
3205	} fflags_table[] = {
3206		{ FAPPEND, KF_FLAG_APPEND },
3207		{ FASYNC, KF_FLAG_ASYNC },
3208		{ FFSYNC, KF_FLAG_FSYNC },
3209		{ FHASLOCK, KF_FLAG_HASLOCK },
3210		{ FNONBLOCK, KF_FLAG_NONBLOCK },
3211		{ FREAD, KF_FLAG_READ },
3212		{ FWRITE, KF_FLAG_WRITE },
3213		{ O_CREAT, KF_FLAG_CREAT },
3214		{ O_DIRECT, KF_FLAG_DIRECT },
3215		{ O_EXCL, KF_FLAG_EXCL },
3216		{ O_EXEC, KF_FLAG_EXEC },
3217		{ O_EXLOCK, KF_FLAG_EXLOCK },
3218		{ O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3219		{ O_SHLOCK, KF_FLAG_SHLOCK },
3220		{ O_TRUNC, KF_FLAG_TRUNC }
3221	};
3222#define	NFFLAGS	(sizeof(fflags_table) / sizeof(*fflags_table))
3223	struct kinfo_file *kif;
3224	struct vnode *vp;
3225	int error, locked;
3226	unsigned int i;
3227
3228	if (efbuf->remainder == 0)
3229		return (0);
3230	kif = &efbuf->kif;
3231	bzero(kif, sizeof(*kif));
3232	locked = efbuf->fdp != NULL;
3233	switch (type) {
3234	case KF_TYPE_FIFO:
3235	case KF_TYPE_VNODE:
3236		if (locked) {
3237			FILEDESC_SUNLOCK(efbuf->fdp);
3238			locked = 0;
3239		}
3240		vp = (struct vnode *)data;
3241		error = fill_vnode_info(vp, kif);
3242		vrele(vp);
3243		break;
3244	case KF_TYPE_SOCKET:
3245		error = fill_socket_info((struct socket *)data, kif);
3246		break;
3247	case KF_TYPE_PIPE:
3248		error = fill_pipe_info((struct pipe *)data, kif);
3249		break;
3250	case KF_TYPE_PTS:
3251		error = fill_pts_info((struct tty *)data, kif);
3252		break;
3253	case KF_TYPE_PROCDESC:
3254		error = fill_procdesc_info((struct procdesc *)data, kif);
3255		break;
3256	case KF_TYPE_SEM:
3257		error = fill_sem_info((struct file *)data, kif);
3258		break;
3259	case KF_TYPE_SHM:
3260		error = fill_shm_info((struct file *)data, kif);
3261		break;
3262	default:
3263		error = 0;
3264	}
3265	if (error == 0)
3266		kif->kf_status |= KF_ATTR_VALID;
3267
3268	/*
3269	 * Translate file access flags.
3270	 */
3271	for (i = 0; i < NFFLAGS; i++)
3272		if (fflags & fflags_table[i].fflag)
3273			kif->kf_flags |=  fflags_table[i].kf_fflag;
3274	if (rightsp != NULL)
3275		kif->kf_cap_rights = *rightsp;
3276	else
3277		cap_rights_init(&kif->kf_cap_rights);
3278	kif->kf_fd = fd;
3279	kif->kf_type = type;
3280	kif->kf_ref_count = refcnt;
3281	kif->kf_offset = offset;
3282	/* Pack record size down */
3283	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3284	    strlen(kif->kf_path) + 1;
3285	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3286	if (efbuf->remainder != -1) {
3287		if (efbuf->remainder < kif->kf_structsize) {
3288			/* Terminate export. */
3289			efbuf->remainder = 0;
3290			if (efbuf->fdp != NULL && !locked)
3291				FILEDESC_SLOCK(efbuf->fdp);
3292			return (0);
3293		}
3294		efbuf->remainder -= kif->kf_structsize;
3295	}
3296	if (locked)
3297		FILEDESC_SUNLOCK(efbuf->fdp);
3298	error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3299	if (efbuf->fdp != NULL)
3300		FILEDESC_SLOCK(efbuf->fdp);
3301	return (error);
3302}
3303
3304/*
3305 * Store a process file descriptor information to sbuf.
3306 *
3307 * Takes a locked proc as argument, and returns with the proc unlocked.
3308 */
3309int
3310kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
3311{
3312	struct file *fp;
3313	struct filedesc *fdp;
3314	struct export_fd_buf *efbuf;
3315	struct vnode *cttyvp, *textvp, *tracevp;
3316	int64_t offset;
3317	void *data;
3318	int error, i;
3319	int type, refcnt, fflags;
3320	cap_rights_t rights;
3321
3322	PROC_LOCK_ASSERT(p, MA_OWNED);
3323
3324	/* ktrace vnode */
3325	tracevp = p->p_tracevp;
3326	if (tracevp != NULL)
3327		vref(tracevp);
3328	/* text vnode */
3329	textvp = p->p_textvp;
3330	if (textvp != NULL)
3331		vref(textvp);
3332	/* Controlling tty. */
3333	cttyvp = NULL;
3334	if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3335		cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3336		if (cttyvp != NULL)
3337			vref(cttyvp);
3338	}
3339	fdp = fdhold(p);
3340	PROC_UNLOCK(p);
3341	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3342	efbuf->fdp = NULL;
3343	efbuf->sb = sb;
3344	efbuf->remainder = maxlen;
3345	if (tracevp != NULL)
3346		export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3347		    FREAD | FWRITE, -1, -1, NULL, efbuf);
3348	if (textvp != NULL)
3349		export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3350		    FREAD, -1, -1, NULL, efbuf);
3351	if (cttyvp != NULL)
3352		export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3353		    FREAD | FWRITE, -1, -1, NULL, efbuf);
3354	error = 0;
3355	if (fdp == NULL)
3356		goto fail;
3357	efbuf->fdp = fdp;
3358	FILEDESC_SLOCK(fdp);
3359	/* working directory */
3360	if (fdp->fd_cdir != NULL) {
3361		vref(fdp->fd_cdir);
3362		data = fdp->fd_cdir;
3363		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3364		    FREAD, -1, -1, NULL, efbuf);
3365	}
3366	/* root directory */
3367	if (fdp->fd_rdir != NULL) {
3368		vref(fdp->fd_rdir);
3369		data = fdp->fd_rdir;
3370		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3371		    FREAD, -1, -1, NULL, efbuf);
3372	}
3373	/* jail directory */
3374	if (fdp->fd_jdir != NULL) {
3375		vref(fdp->fd_jdir);
3376		data = fdp->fd_jdir;
3377		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3378		    FREAD, -1, -1, NULL, efbuf);
3379	}
3380	for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3381		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3382			continue;
3383		data = NULL;
3384#ifdef CAPABILITIES
3385		rights = *cap_rights(fdp, i);
3386#else /* !CAPABILITIES */
3387		cap_rights_init(&rights);
3388#endif
3389		switch (fp->f_type) {
3390		case DTYPE_VNODE:
3391			type = KF_TYPE_VNODE;
3392			vref(fp->f_vnode);
3393			data = fp->f_vnode;
3394			break;
3395
3396		case DTYPE_SOCKET:
3397			type = KF_TYPE_SOCKET;
3398			data = fp->f_data;
3399			break;
3400
3401		case DTYPE_PIPE:
3402			type = KF_TYPE_PIPE;
3403			data = fp->f_data;
3404			break;
3405
3406		case DTYPE_FIFO:
3407			type = KF_TYPE_FIFO;
3408			vref(fp->f_vnode);
3409			data = fp->f_vnode;
3410			break;
3411
3412		case DTYPE_KQUEUE:
3413			type = KF_TYPE_KQUEUE;
3414			break;
3415
3416		case DTYPE_CRYPTO:
3417			type = KF_TYPE_CRYPTO;
3418			break;
3419
3420		case DTYPE_MQUEUE:
3421			type = KF_TYPE_MQUEUE;
3422			break;
3423
3424		case DTYPE_SHM:
3425			type = KF_TYPE_SHM;
3426			data = fp;
3427			break;
3428
3429		case DTYPE_SEM:
3430			type = KF_TYPE_SEM;
3431			data = fp;
3432			break;
3433
3434		case DTYPE_PTS:
3435			type = KF_TYPE_PTS;
3436			data = fp->f_data;
3437			break;
3438
3439		case DTYPE_PROCDESC:
3440			type = KF_TYPE_PROCDESC;
3441			data = fp->f_data;
3442			break;
3443
3444		default:
3445			type = KF_TYPE_UNKNOWN;
3446			break;
3447		}
3448		refcnt = fp->f_count;
3449		fflags = fp->f_flag;
3450		offset = foffset_get(fp);
3451
3452		/*
3453		 * Create sysctl entry.
3454		 * It is OK to drop the filedesc lock here as we will
3455		 * re-validate and re-evaluate its properties when
3456		 * the loop continues.
3457		 */
3458		error = export_fd_to_sb(data, type, i, fflags, refcnt,
3459		    offset, &rights, efbuf);
3460		if (error != 0)
3461			break;
3462	}
3463	FILEDESC_SUNLOCK(fdp);
3464	fddrop(fdp);
3465fail:
3466	free(efbuf, M_TEMP);
3467	return (error);
3468}
3469
3470#define FILEDESC_SBUF_SIZE	(sizeof(struct kinfo_file) * 5)
3471
3472/*
3473 * Get per-process file descriptors for use by procstat(1), et al.
3474 */
3475static int
3476sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3477{
3478	struct sbuf sb;
3479	struct proc *p;
3480	ssize_t maxlen;
3481	int error, error2, *name;
3482
3483	name = (int *)arg1;
3484
3485	sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3486	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3487	if (error != 0) {
3488		sbuf_delete(&sb);
3489		return (error);
3490	}
3491	maxlen = req->oldptr != NULL ? req->oldlen : -1;
3492	error = kern_proc_filedesc_out(p, &sb, maxlen);
3493	error2 = sbuf_finish(&sb);
3494	sbuf_delete(&sb);
3495	return (error != 0 ? error : error2);
3496}
3497
3498int
3499vntype_to_kinfo(int vtype)
3500{
3501	struct {
3502		int	vtype;
3503		int	kf_vtype;
3504	} vtypes_table[] = {
3505		{ VBAD, KF_VTYPE_VBAD },
3506		{ VBLK, KF_VTYPE_VBLK },
3507		{ VCHR, KF_VTYPE_VCHR },
3508		{ VDIR, KF_VTYPE_VDIR },
3509		{ VFIFO, KF_VTYPE_VFIFO },
3510		{ VLNK, KF_VTYPE_VLNK },
3511		{ VNON, KF_VTYPE_VNON },
3512		{ VREG, KF_VTYPE_VREG },
3513		{ VSOCK, KF_VTYPE_VSOCK }
3514	};
3515#define	NVTYPES	(sizeof(vtypes_table) / sizeof(*vtypes_table))
3516	unsigned int i;
3517
3518	/*
3519	 * Perform vtype translation.
3520	 */
3521	for (i = 0; i < NVTYPES; i++)
3522		if (vtypes_table[i].vtype == vtype)
3523			break;
3524	if (i < NVTYPES)
3525		return (vtypes_table[i].kf_vtype);
3526
3527	return (KF_VTYPE_UNKNOWN);
3528}
3529
3530static int
3531fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3532{
3533	struct vattr va;
3534	char *fullpath, *freepath;
3535	int error;
3536
3537	if (vp == NULL)
3538		return (1);
3539	kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3540	freepath = NULL;
3541	fullpath = "-";
3542	error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3543	if (error == 0) {
3544		strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3545	}
3546	if (freepath != NULL)
3547		free(freepath, M_TEMP);
3548
3549	/*
3550	 * Retrieve vnode attributes.
3551	 */
3552	va.va_fsid = VNOVAL;
3553	va.va_rdev = NODEV;
3554	vn_lock(vp, LK_SHARED | LK_RETRY);
3555	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3556	VOP_UNLOCK(vp, 0);
3557	if (error != 0)
3558		return (error);
3559	if (va.va_fsid != VNOVAL)
3560		kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3561	else
3562		kif->kf_un.kf_file.kf_file_fsid =
3563		    vp->v_mount->mnt_stat.f_fsid.val[0];
3564	kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3565	kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3566	kif->kf_un.kf_file.kf_file_size = va.va_size;
3567	kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3568	return (0);
3569}
3570
3571static int
3572fill_socket_info(struct socket *so, struct kinfo_file *kif)
3573{
3574	struct sockaddr *sa;
3575	struct inpcb *inpcb;
3576	struct unpcb *unpcb;
3577	int error;
3578
3579	if (so == NULL)
3580		return (1);
3581	kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3582	kif->kf_sock_type = so->so_type;
3583	kif->kf_sock_protocol = so->so_proto->pr_protocol;
3584	kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3585	switch(kif->kf_sock_domain) {
3586	case AF_INET:
3587	case AF_INET6:
3588		if (kif->kf_sock_protocol == IPPROTO_TCP) {
3589			if (so->so_pcb != NULL) {
3590				inpcb = (struct inpcb *)(so->so_pcb);
3591				kif->kf_un.kf_sock.kf_sock_inpcb =
3592				    (uintptr_t)inpcb->inp_ppcb;
3593			}
3594		}
3595		break;
3596	case AF_UNIX:
3597		if (so->so_pcb != NULL) {
3598			unpcb = (struct unpcb *)(so->so_pcb);
3599			if (unpcb->unp_conn) {
3600				kif->kf_un.kf_sock.kf_sock_unpconn =
3601				    (uintptr_t)unpcb->unp_conn;
3602				kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3603				    so->so_rcv.sb_state;
3604				kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3605				    so->so_snd.sb_state;
3606			}
3607		}
3608		break;
3609	}
3610	error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3611	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3612		bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3613		free(sa, M_SONAME);
3614	}
3615	error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3616	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3617		bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3618		free(sa, M_SONAME);
3619	}
3620	strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3621	    sizeof(kif->kf_path));
3622	return (0);
3623}
3624
3625static int
3626fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3627{
3628
3629	if (tp == NULL)
3630		return (1);
3631	kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3632	strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3633	return (0);
3634}
3635
3636static int
3637fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3638{
3639
3640	if (pi == NULL)
3641		return (1);
3642	kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3643	kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3644	kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3645	return (0);
3646}
3647
3648static int
3649fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3650{
3651
3652	if (pdp == NULL)
3653		return (1);
3654	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3655	return (0);
3656}
3657
3658static int
3659fill_sem_info(struct file *fp, struct kinfo_file *kif)
3660{
3661	struct thread *td;
3662	struct stat sb;
3663
3664	td = curthread;
3665	if (fp->f_data == NULL)
3666		return (1);
3667	if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3668		return (1);
3669	if (ksem_info == NULL)
3670		return (1);
3671	ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3672	    &kif->kf_un.kf_sem.kf_sem_value);
3673	kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3674	return (0);
3675}
3676
3677static int
3678fill_shm_info(struct file *fp, struct kinfo_file *kif)
3679{
3680	struct thread *td;
3681	struct stat sb;
3682
3683	td = curthread;
3684	if (fp->f_data == NULL)
3685		return (1);
3686	if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3687		return (1);
3688	shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3689	kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3690	kif->kf_un.kf_file.kf_file_size = sb.st_size;
3691	return (0);
3692}
3693
3694static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3695    CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3696    "Process filedesc entries");
3697
3698#ifdef DDB
3699/*
3700 * For the purposes of debugging, generate a human-readable string for the
3701 * file type.
3702 */
3703static const char *
3704file_type_to_name(short type)
3705{
3706
3707	switch (type) {
3708	case 0:
3709		return ("zero");
3710	case DTYPE_VNODE:
3711		return ("vnod");
3712	case DTYPE_SOCKET:
3713		return ("sock");
3714	case DTYPE_PIPE:
3715		return ("pipe");
3716	case DTYPE_FIFO:
3717		return ("fifo");
3718	case DTYPE_KQUEUE:
3719		return ("kque");
3720	case DTYPE_CRYPTO:
3721		return ("crpt");
3722	case DTYPE_MQUEUE:
3723		return ("mque");
3724	case DTYPE_SHM:
3725		return ("shm");
3726	case DTYPE_SEM:
3727		return ("ksem");
3728	default:
3729		return ("unkn");
3730	}
3731}
3732
3733/*
3734 * For the purposes of debugging, identify a process (if any, perhaps one of
3735 * many) that references the passed file in its file descriptor array. Return
3736 * NULL if none.
3737 */
3738static struct proc *
3739file_to_first_proc(struct file *fp)
3740{
3741	struct filedesc *fdp;
3742	struct proc *p;
3743	int n;
3744
3745	FOREACH_PROC_IN_SYSTEM(p) {
3746		if (p->p_state == PRS_NEW)
3747			continue;
3748		fdp = p->p_fd;
3749		if (fdp == NULL)
3750			continue;
3751		for (n = 0; n <= fdp->fd_lastfile; n++) {
3752			if (fp == fdp->fd_ofiles[n].fde_file)
3753				return (p);
3754		}
3755	}
3756	return (NULL);
3757}
3758
3759static void
3760db_print_file(struct file *fp, int header)
3761{
3762	struct proc *p;
3763
3764	if (header)
3765		db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3766		    "File", "Type", "Data", "Flag", "GCFl", "Count",
3767		    "MCount", "Vnode", "FPID", "FCmd");
3768	p = file_to_first_proc(fp);
3769	db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3770	    file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3771	    0, fp->f_count, 0, fp->f_vnode,
3772	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3773}
3774
3775DB_SHOW_COMMAND(file, db_show_file)
3776{
3777	struct file *fp;
3778
3779	if (!have_addr) {
3780		db_printf("usage: show file <addr>\n");
3781		return;
3782	}
3783	fp = (struct file *)addr;
3784	db_print_file(fp, 1);
3785}
3786
3787DB_SHOW_COMMAND(files, db_show_files)
3788{
3789	struct filedesc *fdp;
3790	struct file *fp;
3791	struct proc *p;
3792	int header;
3793	int n;
3794
3795	header = 1;
3796	FOREACH_PROC_IN_SYSTEM(p) {
3797		if (p->p_state == PRS_NEW)
3798			continue;
3799		if ((fdp = p->p_fd) == NULL)
3800			continue;
3801		for (n = 0; n <= fdp->fd_lastfile; ++n) {
3802			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3803				continue;
3804			db_print_file(fp, header);
3805			header = 0;
3806		}
3807	}
3808}
3809#endif
3810
3811SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3812    &maxfilesperproc, 0, "Maximum files allowed open per process");
3813
3814SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3815    &maxfiles, 0, "Maximum number of files");
3816
3817SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3818    __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3819
3820/* ARGSUSED*/
3821static void
3822filelistinit(void *dummy)
3823{
3824
3825	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3826	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3827	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3828	mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3829}
3830SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3831
3832/*-------------------------------------------------------------------*/
3833
3834static int
3835badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3836    int flags, struct thread *td)
3837{
3838
3839	return (EBADF);
3840}
3841
3842static int
3843badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3844    struct thread *td)
3845{
3846
3847	return (EINVAL);
3848}
3849
3850static int
3851badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3852    struct thread *td)
3853{
3854
3855	return (EBADF);
3856}
3857
3858static int
3859badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3860    struct thread *td)
3861{
3862
3863	return (0);
3864}
3865
3866static int
3867badfo_kqfilter(struct file *fp, struct knote *kn)
3868{
3869
3870	return (EBADF);
3871}
3872
3873static int
3874badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3875    struct thread *td)
3876{
3877
3878	return (EBADF);
3879}
3880
3881static int
3882badfo_close(struct file *fp, struct thread *td)
3883{
3884
3885	return (EBADF);
3886}
3887
3888static int
3889badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3890    struct thread *td)
3891{
3892
3893	return (EBADF);
3894}
3895
3896static int
3897badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3898    struct thread *td)
3899{
3900
3901	return (EBADF);
3902}
3903
3904static int
3905badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3906    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3907    int kflags, struct sendfile_sync *sfs, struct thread *td)
3908{
3909
3910	return (EBADF);
3911}
3912
3913struct fileops badfileops = {
3914	.fo_read = badfo_readwrite,
3915	.fo_write = badfo_readwrite,
3916	.fo_truncate = badfo_truncate,
3917	.fo_ioctl = badfo_ioctl,
3918	.fo_poll = badfo_poll,
3919	.fo_kqfilter = badfo_kqfilter,
3920	.fo_stat = badfo_stat,
3921	.fo_close = badfo_close,
3922	.fo_chmod = badfo_chmod,
3923	.fo_chown = badfo_chown,
3924	.fo_sendfile = badfo_sendfile,
3925};
3926
3927int
3928invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3929    struct thread *td)
3930{
3931
3932	return (EINVAL);
3933}
3934
3935int
3936invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3937    struct thread *td)
3938{
3939
3940	return (EINVAL);
3941}
3942
3943int
3944invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3945    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3946    int kflags, struct sendfile_sync *sfs, struct thread *td)
3947{
3948
3949	return (EINVAL);
3950}
3951
3952/*-------------------------------------------------------------------*/
3953
3954/*
3955 * File Descriptor pseudo-device driver (/dev/fd/).
3956 *
3957 * Opening minor device N dup()s the file (if any) connected to file
3958 * descriptor N belonging to the calling process.  Note that this driver
3959 * consists of only the ``open()'' routine, because all subsequent
3960 * references to this file will be direct to the other driver.
3961 *
3962 * XXX: we could give this one a cloning event handler if necessary.
3963 */
3964
3965/* ARGSUSED */
3966static int
3967fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3968{
3969
3970	/*
3971	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3972	 * the file descriptor being sought for duplication. The error
3973	 * return ensures that the vnode for this device will be released
3974	 * by vn_open. Open will detect this special error and take the
3975	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3976	 * will simply report the error.
3977	 */
3978	td->td_dupfd = dev2unit(dev);
3979	return (ENODEV);
3980}
3981
3982static struct cdevsw fildesc_cdevsw = {
3983	.d_version =	D_VERSION,
3984	.d_open =	fdopen,
3985	.d_name =	"FD",
3986};
3987
3988static void
3989fildesc_drvinit(void *unused)
3990{
3991	struct cdev *dev;
3992
3993	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3994	    UID_ROOT, GID_WHEEL, 0666, "fd/0");
3995	make_dev_alias(dev, "stdin");
3996	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3997	    UID_ROOT, GID_WHEEL, 0666, "fd/1");
3998	make_dev_alias(dev, "stdout");
3999	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4000	    UID_ROOT, GID_WHEEL, 0666, "fd/2");
4001	make_dev_alias(dev, "stderr");
4002}
4003
4004SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
4005