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