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