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