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