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