kern_descrip.c revision 273894
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 273894 2014-10-31 09:19:46Z 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	KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
242	    ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
243
244	return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
245}
246#endif
247
248/*
249 * Mark a file descriptor as used.
250 */
251static void
252fdused_init(struct filedesc *fdp, int fd)
253{
254
255	KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
256
257	fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
258}
259
260static void
261fdused(struct filedesc *fdp, int fd)
262{
263
264	FILEDESC_XLOCK_ASSERT(fdp);
265
266	fdused_init(fdp, fd);
267	if (fd > fdp->fd_lastfile)
268		fdp->fd_lastfile = fd;
269	if (fd == fdp->fd_freefile)
270		fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
271}
272
273/*
274 * Mark a file descriptor as unused.
275 */
276static void
277fdunused(struct filedesc *fdp, int fd)
278{
279
280	FILEDESC_XLOCK_ASSERT(fdp);
281
282	KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
283	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
284	    ("fd=%d is still in use", fd));
285
286	fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
287	if (fd < fdp->fd_freefile)
288		fdp->fd_freefile = fd;
289	if (fd == fdp->fd_lastfile)
290		fdp->fd_lastfile = fd_last_used(fdp, fd);
291}
292
293/*
294 * Free a file descriptor.
295 *
296 * Avoid some work if fdp is about to be destroyed.
297 */
298static inline void
299fdefree_last(struct filedescent *fde)
300{
301
302	filecaps_free(&fde->fde_caps);
303}
304
305static inline void
306fdfree(struct filedesc *fdp, int fd)
307{
308	struct filedescent *fde;
309
310	fde = &fdp->fd_ofiles[fd];
311#ifdef CAPABILITIES
312	seq_write_begin(&fde->fde_seq);
313#endif
314	fdefree_last(fde);
315	bzero(fde, fde_change_size);
316	fdunused(fdp, fd);
317#ifdef CAPABILITIES
318	seq_write_end(&fde->fde_seq);
319#endif
320}
321
322/*
323 * System calls on descriptors.
324 */
325#ifndef _SYS_SYSPROTO_H_
326struct getdtablesize_args {
327	int	dummy;
328};
329#endif
330/* ARGSUSED */
331int
332sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
333{
334	struct proc *p = td->td_proc;
335	uint64_t lim;
336
337	PROC_LOCK(p);
338	td->td_retval[0] =
339	    min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
340	lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
341	PROC_UNLOCK(p);
342	if (lim < td->td_retval[0])
343		td->td_retval[0] = lim;
344	return (0);
345}
346
347/*
348 * Duplicate a file descriptor to a particular value.
349 *
350 * Note: keep in mind that a potential race condition exists when closing
351 * descriptors from a shared descriptor table (via rfork).
352 */
353#ifndef _SYS_SYSPROTO_H_
354struct dup2_args {
355	u_int	from;
356	u_int	to;
357};
358#endif
359/* ARGSUSED */
360int
361sys_dup2(struct thread *td, struct dup2_args *uap)
362{
363
364	return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
365		    td->td_retval));
366}
367
368/*
369 * Duplicate a file descriptor.
370 */
371#ifndef _SYS_SYSPROTO_H_
372struct dup_args {
373	u_int	fd;
374};
375#endif
376/* ARGSUSED */
377int
378sys_dup(struct thread *td, struct dup_args *uap)
379{
380
381	return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
382}
383
384/*
385 * The file control system call.
386 */
387#ifndef _SYS_SYSPROTO_H_
388struct fcntl_args {
389	int	fd;
390	int	cmd;
391	long	arg;
392};
393#endif
394/* ARGSUSED */
395int
396sys_fcntl(struct thread *td, struct fcntl_args *uap)
397{
398
399	return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
400}
401
402int
403kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
404{
405	struct flock fl;
406	struct __oflock ofl;
407	intptr_t arg1;
408	int error;
409
410	error = 0;
411	switch (cmd) {
412	case F_OGETLK:
413	case F_OSETLK:
414	case F_OSETLKW:
415		/*
416		 * Convert old flock structure to new.
417		 */
418		error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
419		fl.l_start = ofl.l_start;
420		fl.l_len = ofl.l_len;
421		fl.l_pid = ofl.l_pid;
422		fl.l_type = ofl.l_type;
423		fl.l_whence = ofl.l_whence;
424		fl.l_sysid = 0;
425
426		switch (cmd) {
427		case F_OGETLK:
428		    cmd = F_GETLK;
429		    break;
430		case F_OSETLK:
431		    cmd = F_SETLK;
432		    break;
433		case F_OSETLKW:
434		    cmd = F_SETLKW;
435		    break;
436		}
437		arg1 = (intptr_t)&fl;
438		break;
439        case F_GETLK:
440        case F_SETLK:
441        case F_SETLKW:
442	case F_SETLK_REMOTE:
443                error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
444                arg1 = (intptr_t)&fl;
445                break;
446	default:
447		arg1 = arg;
448		break;
449	}
450	if (error)
451		return (error);
452	error = kern_fcntl(td, fd, cmd, arg1);
453	if (error)
454		return (error);
455	if (cmd == F_OGETLK) {
456		ofl.l_start = fl.l_start;
457		ofl.l_len = fl.l_len;
458		ofl.l_pid = fl.l_pid;
459		ofl.l_type = fl.l_type;
460		ofl.l_whence = fl.l_whence;
461		error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
462	} else if (cmd == F_GETLK) {
463		error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
464	}
465	return (error);
466}
467
468int
469kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
470{
471	struct filedesc *fdp;
472	struct flock *flp;
473	struct file *fp, *fp2;
474	struct filedescent *fde;
475	struct proc *p;
476	struct vnode *vp;
477	cap_rights_t rights;
478	int error, flg, tmp;
479	uint64_t bsize;
480	off_t foffset;
481
482	error = 0;
483	flg = F_POSIX;
484	p = td->td_proc;
485	fdp = p->p_fd;
486
487	switch (cmd) {
488	case F_DUPFD:
489		tmp = arg;
490		error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
491		break;
492
493	case F_DUPFD_CLOEXEC:
494		tmp = arg;
495		error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
496		    td->td_retval);
497		break;
498
499	case F_DUP2FD:
500		tmp = arg;
501		error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
502		break;
503
504	case F_DUP2FD_CLOEXEC:
505		tmp = arg;
506		error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
507		    td->td_retval);
508		break;
509
510	case F_GETFD:
511		FILEDESC_SLOCK(fdp);
512		if (fget_locked(fdp, fd) == NULL) {
513			FILEDESC_SUNLOCK(fdp);
514			error = EBADF;
515			break;
516		}
517		fde = &fdp->fd_ofiles[fd];
518		td->td_retval[0] =
519		    (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
520		FILEDESC_SUNLOCK(fdp);
521		break;
522
523	case F_SETFD:
524		FILEDESC_XLOCK(fdp);
525		if (fget_locked(fdp, fd) == NULL) {
526			FILEDESC_XUNLOCK(fdp);
527			error = EBADF;
528			break;
529		}
530		fde = &fdp->fd_ofiles[fd];
531		fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
532		    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
533		FILEDESC_XUNLOCK(fdp);
534		break;
535
536	case F_GETFL:
537		error = fget_unlocked(fdp, fd,
538		    cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
539		if (error != 0)
540			break;
541		td->td_retval[0] = OFLAGS(fp->f_flag);
542		fdrop(fp, td);
543		break;
544
545	case F_SETFL:
546		error = fget_unlocked(fdp, fd,
547		    cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
548		if (error != 0)
549			break;
550		do {
551			tmp = flg = fp->f_flag;
552			tmp &= ~FCNTLFLAGS;
553			tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
554		} while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
555		tmp = fp->f_flag & FNONBLOCK;
556		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
557		if (error != 0) {
558			fdrop(fp, td);
559			break;
560		}
561		tmp = fp->f_flag & FASYNC;
562		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
563		if (error == 0) {
564			fdrop(fp, td);
565			break;
566		}
567		atomic_clear_int(&fp->f_flag, FNONBLOCK);
568		tmp = 0;
569		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
570		fdrop(fp, td);
571		break;
572
573	case F_GETOWN:
574		error = fget_unlocked(fdp, fd,
575		    cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
576		if (error != 0)
577			break;
578		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
579		if (error == 0)
580			td->td_retval[0] = tmp;
581		fdrop(fp, td);
582		break;
583
584	case F_SETOWN:
585		error = fget_unlocked(fdp, fd,
586		    cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
587		if (error != 0)
588			break;
589		tmp = arg;
590		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
591		fdrop(fp, td);
592		break;
593
594	case F_SETLK_REMOTE:
595		error = priv_check(td, PRIV_NFS_LOCKD);
596		if (error)
597			return (error);
598		flg = F_REMOTE;
599		goto do_setlk;
600
601	case F_SETLKW:
602		flg |= F_WAIT;
603		/* FALLTHROUGH F_SETLK */
604
605	case F_SETLK:
606	do_setlk:
607		cap_rights_init(&rights, CAP_FLOCK);
608		error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
609		if (error != 0)
610			break;
611		if (fp->f_type != DTYPE_VNODE) {
612			error = EBADF;
613			fdrop(fp, td);
614			break;
615		}
616
617		flp = (struct flock *)arg;
618		if (flp->l_whence == SEEK_CUR) {
619			foffset = foffset_get(fp);
620			if (foffset < 0 ||
621			    (flp->l_start > 0 &&
622			     foffset > OFF_MAX - flp->l_start)) {
623				FILEDESC_SUNLOCK(fdp);
624				error = EOVERFLOW;
625				fdrop(fp, td);
626				break;
627			}
628			flp->l_start += foffset;
629		}
630
631		vp = fp->f_vnode;
632		switch (flp->l_type) {
633		case F_RDLCK:
634			if ((fp->f_flag & FREAD) == 0) {
635				error = EBADF;
636				break;
637			}
638			PROC_LOCK(p->p_leader);
639			p->p_leader->p_flag |= P_ADVLOCK;
640			PROC_UNLOCK(p->p_leader);
641			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
642			    flp, flg);
643			break;
644		case F_WRLCK:
645			if ((fp->f_flag & FWRITE) == 0) {
646				error = EBADF;
647				break;
648			}
649			PROC_LOCK(p->p_leader);
650			p->p_leader->p_flag |= P_ADVLOCK;
651			PROC_UNLOCK(p->p_leader);
652			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
653			    flp, flg);
654			break;
655		case F_UNLCK:
656			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
657			    flp, flg);
658			break;
659		case F_UNLCKSYS:
660			/*
661			 * Temporary api for testing remote lock
662			 * infrastructure.
663			 */
664			if (flg != F_REMOTE) {
665				error = EINVAL;
666				break;
667			}
668			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
669			    F_UNLCKSYS, flp, flg);
670			break;
671		default:
672			error = EINVAL;
673			break;
674		}
675		if (error != 0 || flp->l_type == F_UNLCK ||
676		    flp->l_type == F_UNLCKSYS) {
677			fdrop(fp, td);
678			break;
679		}
680
681		/*
682		 * Check for a race with close.
683		 *
684		 * The vnode is now advisory locked (or unlocked, but this case
685		 * is not really important) as the caller requested.
686		 * We had to drop the filedesc lock, so we need to recheck if
687		 * the descriptor is still valid, because if it was closed
688		 * in the meantime we need to remove advisory lock from the
689		 * vnode - close on any descriptor leading to an advisory
690		 * locked vnode, removes that lock.
691		 * We will return 0 on purpose in that case, as the result of
692		 * successful advisory lock might have been externally visible
693		 * already. This is fine - effectively we pretend to the caller
694		 * that the closing thread was a bit slower and that the
695		 * advisory lock succeeded before the close.
696		 */
697		error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
698		if (error != 0) {
699			fdrop(fp, td);
700			break;
701		}
702		if (fp != fp2) {
703			flp->l_whence = SEEK_SET;
704			flp->l_start = 0;
705			flp->l_len = 0;
706			flp->l_type = F_UNLCK;
707			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
708			    F_UNLCK, flp, F_POSIX);
709		}
710		fdrop(fp, td);
711		fdrop(fp2, td);
712		break;
713
714	case F_GETLK:
715		error = fget_unlocked(fdp, fd,
716		    cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
717		if (error != 0)
718			break;
719		if (fp->f_type != DTYPE_VNODE) {
720			error = EBADF;
721			fdrop(fp, td);
722			break;
723		}
724		flp = (struct flock *)arg;
725		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
726		    flp->l_type != F_UNLCK) {
727			error = EINVAL;
728			fdrop(fp, td);
729			break;
730		}
731		if (flp->l_whence == SEEK_CUR) {
732			foffset = foffset_get(fp);
733			if ((flp->l_start > 0 &&
734			    foffset > OFF_MAX - flp->l_start) ||
735			    (flp->l_start < 0 &&
736			     foffset < OFF_MIN - flp->l_start)) {
737				FILEDESC_SUNLOCK(fdp);
738				error = EOVERFLOW;
739				fdrop(fp, td);
740				break;
741			}
742			flp->l_start += foffset;
743		}
744		vp = fp->f_vnode;
745		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
746		    F_POSIX);
747		fdrop(fp, td);
748		break;
749
750	case F_RDAHEAD:
751		arg = arg ? 128 * 1024: 0;
752		/* FALLTHROUGH */
753	case F_READAHEAD:
754		error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
755		if (error != 0)
756			break;
757		if (fp->f_type != DTYPE_VNODE) {
758			fdrop(fp, td);
759			error = EBADF;
760			break;
761		}
762		vp = fp->f_vnode;
763		/*
764		 * Exclusive lock synchronizes against f_seqcount reads and
765		 * writes in sequential_heuristic().
766		 */
767		error = vn_lock(vp, LK_EXCLUSIVE);
768		if (error != 0) {
769			fdrop(fp, td);
770			break;
771		}
772		if (arg >= 0) {
773			bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
774			fp->f_seqcount = (arg + bsize - 1) / bsize;
775			atomic_set_int(&fp->f_flag, FRDAHEAD);
776		} else {
777			atomic_clear_int(&fp->f_flag, FRDAHEAD);
778		}
779		VOP_UNLOCK(vp, 0);
780		fdrop(fp, td);
781		break;
782
783	default:
784		error = EINVAL;
785		break;
786	}
787	return (error);
788}
789
790static int
791getmaxfd(struct proc *p)
792{
793	int maxfd;
794
795	PROC_LOCK(p);
796	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
797	PROC_UNLOCK(p);
798
799	return (maxfd);
800}
801
802/*
803 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
804 */
805static int
806do_dup(struct thread *td, int flags, int old, int new,
807    register_t *retval)
808{
809	struct filedesc *fdp;
810	struct filedescent *oldfde, *newfde;
811	struct proc *p;
812	struct file *fp;
813	struct file *delfp;
814	int error, maxfd;
815
816	p = td->td_proc;
817	fdp = p->p_fd;
818
819	/*
820	 * Verify we have a valid descriptor to dup from and possibly to
821	 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
822	 * return EINVAL when the new descriptor is out of bounds.
823	 */
824	if (old < 0)
825		return (EBADF);
826	if (new < 0)
827		return (flags & DUP_FCNTL ? EINVAL : EBADF);
828	maxfd = getmaxfd(p);
829	if (new >= maxfd)
830		return (flags & DUP_FCNTL ? EINVAL : EBADF);
831
832	FILEDESC_XLOCK(fdp);
833	if (fget_locked(fdp, old) == NULL) {
834		FILEDESC_XUNLOCK(fdp);
835		return (EBADF);
836	}
837	oldfde = &fdp->fd_ofiles[old];
838	if (flags & DUP_FIXED && old == new) {
839		*retval = new;
840		if (flags & DUP_CLOEXEC)
841			fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
842		FILEDESC_XUNLOCK(fdp);
843		return (0);
844	}
845	fp = oldfde->fde_file;
846	fhold(fp);
847
848	/*
849	 * If the caller specified a file descriptor, make sure the file
850	 * table is large enough to hold it, and grab it.  Otherwise, just
851	 * allocate a new descriptor the usual way.
852	 */
853	if (flags & DUP_FIXED) {
854		if (new >= fdp->fd_nfiles) {
855			/*
856			 * The resource limits are here instead of e.g.
857			 * fdalloc(), because the file descriptor table may be
858			 * shared between processes, so we can't really use
859			 * racct_add()/racct_sub().  Instead of counting the
860			 * number of actually allocated descriptors, just put
861			 * the limit on the size of the file descriptor table.
862			 */
863#ifdef RACCT
864			PROC_LOCK(p);
865			error = racct_set(p, RACCT_NOFILE, new + 1);
866			PROC_UNLOCK(p);
867			if (error != 0) {
868				FILEDESC_XUNLOCK(fdp);
869				fdrop(fp, td);
870				return (EMFILE);
871			}
872#endif
873			fdgrowtable_exp(fdp, new + 1);
874			oldfde = &fdp->fd_ofiles[old];
875		}
876		newfde = &fdp->fd_ofiles[new];
877		if (newfde->fde_file == NULL)
878			fdused(fdp, new);
879	} else {
880		if ((error = fdalloc(td, new, &new)) != 0) {
881			FILEDESC_XUNLOCK(fdp);
882			fdrop(fp, td);
883			return (error);
884		}
885		newfde = &fdp->fd_ofiles[new];
886	}
887
888	KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
889	KASSERT(old != new, ("new fd is same as old"));
890
891	delfp = newfde->fde_file;
892
893	/*
894	 * Duplicate the source descriptor.
895	 */
896#ifdef CAPABILITIES
897	seq_write_begin(&newfde->fde_seq);
898#endif
899	filecaps_free(&newfde->fde_caps);
900	memcpy(newfde, oldfde, fde_change_size);
901	filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
902	if ((flags & DUP_CLOEXEC) != 0)
903		newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
904	else
905		newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
906#ifdef CAPABILITIES
907	seq_write_end(&newfde->fde_seq);
908#endif
909	*retval = new;
910
911	if (delfp != NULL) {
912		(void) closefp(fdp, new, delfp, td, 1);
913		/* closefp() drops the FILEDESC lock for us. */
914	} else {
915		FILEDESC_XUNLOCK(fdp);
916	}
917
918	return (0);
919}
920
921/*
922 * If sigio is on the list associated with a process or process group,
923 * disable signalling from the device, remove sigio from the list and
924 * free sigio.
925 */
926void
927funsetown(struct sigio **sigiop)
928{
929	struct sigio *sigio;
930
931	SIGIO_LOCK();
932	sigio = *sigiop;
933	if (sigio == NULL) {
934		SIGIO_UNLOCK();
935		return;
936	}
937	*(sigio->sio_myref) = NULL;
938	if ((sigio)->sio_pgid < 0) {
939		struct pgrp *pg = (sigio)->sio_pgrp;
940		PGRP_LOCK(pg);
941		SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
942			     sigio, sio_pgsigio);
943		PGRP_UNLOCK(pg);
944	} else {
945		struct proc *p = (sigio)->sio_proc;
946		PROC_LOCK(p);
947		SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
948			     sigio, sio_pgsigio);
949		PROC_UNLOCK(p);
950	}
951	SIGIO_UNLOCK();
952	crfree(sigio->sio_ucred);
953	free(sigio, M_SIGIO);
954}
955
956/*
957 * Free a list of sigio structures.
958 * We only need to lock the SIGIO_LOCK because we have made ourselves
959 * inaccessible to callers of fsetown and therefore do not need to lock
960 * the proc or pgrp struct for the list manipulation.
961 */
962void
963funsetownlst(struct sigiolst *sigiolst)
964{
965	struct proc *p;
966	struct pgrp *pg;
967	struct sigio *sigio;
968
969	sigio = SLIST_FIRST(sigiolst);
970	if (sigio == NULL)
971		return;
972	p = NULL;
973	pg = NULL;
974
975	/*
976	 * Every entry of the list should belong
977	 * to a single proc or pgrp.
978	 */
979	if (sigio->sio_pgid < 0) {
980		pg = sigio->sio_pgrp;
981		PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
982	} else /* if (sigio->sio_pgid > 0) */ {
983		p = sigio->sio_proc;
984		PROC_LOCK_ASSERT(p, MA_NOTOWNED);
985	}
986
987	SIGIO_LOCK();
988	while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
989		*(sigio->sio_myref) = NULL;
990		if (pg != NULL) {
991			KASSERT(sigio->sio_pgid < 0,
992			    ("Proc sigio in pgrp sigio list"));
993			KASSERT(sigio->sio_pgrp == pg,
994			    ("Bogus pgrp in sigio list"));
995			PGRP_LOCK(pg);
996			SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
997			    sio_pgsigio);
998			PGRP_UNLOCK(pg);
999		} else /* if (p != NULL) */ {
1000			KASSERT(sigio->sio_pgid > 0,
1001			    ("Pgrp sigio in proc sigio list"));
1002			KASSERT(sigio->sio_proc == p,
1003			    ("Bogus proc in sigio list"));
1004			PROC_LOCK(p);
1005			SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1006			    sio_pgsigio);
1007			PROC_UNLOCK(p);
1008		}
1009		SIGIO_UNLOCK();
1010		crfree(sigio->sio_ucred);
1011		free(sigio, M_SIGIO);
1012		SIGIO_LOCK();
1013	}
1014	SIGIO_UNLOCK();
1015}
1016
1017/*
1018 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1019 *
1020 * After permission checking, add a sigio structure to the sigio list for
1021 * the process or process group.
1022 */
1023int
1024fsetown(pid_t pgid, struct sigio **sigiop)
1025{
1026	struct proc *proc;
1027	struct pgrp *pgrp;
1028	struct sigio *sigio;
1029	int ret;
1030
1031	if (pgid == 0) {
1032		funsetown(sigiop);
1033		return (0);
1034	}
1035
1036	ret = 0;
1037
1038	/* Allocate and fill in the new sigio out of locks. */
1039	sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1040	sigio->sio_pgid = pgid;
1041	sigio->sio_ucred = crhold(curthread->td_ucred);
1042	sigio->sio_myref = sigiop;
1043
1044	sx_slock(&proctree_lock);
1045	if (pgid > 0) {
1046		proc = pfind(pgid);
1047		if (proc == NULL) {
1048			ret = ESRCH;
1049			goto fail;
1050		}
1051
1052		/*
1053		 * Policy - Don't allow a process to FSETOWN a process
1054		 * in another session.
1055		 *
1056		 * Remove this test to allow maximum flexibility or
1057		 * restrict FSETOWN to the current process or process
1058		 * group for maximum safety.
1059		 */
1060		PROC_UNLOCK(proc);
1061		if (proc->p_session != curthread->td_proc->p_session) {
1062			ret = EPERM;
1063			goto fail;
1064		}
1065
1066		pgrp = NULL;
1067	} else /* if (pgid < 0) */ {
1068		pgrp = pgfind(-pgid);
1069		if (pgrp == NULL) {
1070			ret = ESRCH;
1071			goto fail;
1072		}
1073		PGRP_UNLOCK(pgrp);
1074
1075		/*
1076		 * Policy - Don't allow a process to FSETOWN a process
1077		 * in another session.
1078		 *
1079		 * Remove this test to allow maximum flexibility or
1080		 * restrict FSETOWN to the current process or process
1081		 * group for maximum safety.
1082		 */
1083		if (pgrp->pg_session != curthread->td_proc->p_session) {
1084			ret = EPERM;
1085			goto fail;
1086		}
1087
1088		proc = NULL;
1089	}
1090	funsetown(sigiop);
1091	if (pgid > 0) {
1092		PROC_LOCK(proc);
1093		/*
1094		 * Since funsetownlst() is called without the proctree
1095		 * locked, we need to check for P_WEXIT.
1096		 * XXX: is ESRCH correct?
1097		 */
1098		if ((proc->p_flag & P_WEXIT) != 0) {
1099			PROC_UNLOCK(proc);
1100			ret = ESRCH;
1101			goto fail;
1102		}
1103		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1104		sigio->sio_proc = proc;
1105		PROC_UNLOCK(proc);
1106	} else {
1107		PGRP_LOCK(pgrp);
1108		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1109		sigio->sio_pgrp = pgrp;
1110		PGRP_UNLOCK(pgrp);
1111	}
1112	sx_sunlock(&proctree_lock);
1113	SIGIO_LOCK();
1114	*sigiop = sigio;
1115	SIGIO_UNLOCK();
1116	return (0);
1117
1118fail:
1119	sx_sunlock(&proctree_lock);
1120	crfree(sigio->sio_ucred);
1121	free(sigio, M_SIGIO);
1122	return (ret);
1123}
1124
1125/*
1126 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1127 */
1128pid_t
1129fgetown(sigiop)
1130	struct sigio **sigiop;
1131{
1132	pid_t pgid;
1133
1134	SIGIO_LOCK();
1135	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1136	SIGIO_UNLOCK();
1137	return (pgid);
1138}
1139
1140/*
1141 * Function drops the filedesc lock on return.
1142 */
1143static int
1144closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1145    int holdleaders)
1146{
1147	int error;
1148
1149	FILEDESC_XLOCK_ASSERT(fdp);
1150
1151	if (holdleaders) {
1152		if (td->td_proc->p_fdtol != NULL) {
1153			/*
1154			 * Ask fdfree() to sleep to ensure that all relevant
1155			 * process leaders can be traversed in closef().
1156			 */
1157			fdp->fd_holdleaderscount++;
1158		} else {
1159			holdleaders = 0;
1160		}
1161	}
1162
1163	/*
1164	 * We now hold the fp reference that used to be owned by the
1165	 * descriptor array.  We have to unlock the FILEDESC *AFTER*
1166	 * knote_fdclose to prevent a race of the fd getting opened, a knote
1167	 * added, and deleteing a knote for the new fd.
1168	 */
1169	knote_fdclose(td, fd);
1170
1171	/*
1172	 * We need to notify mqueue if the object is of type mqueue.
1173	 */
1174	if (fp->f_type == DTYPE_MQUEUE)
1175		mq_fdclose(td, fd, fp);
1176	FILEDESC_XUNLOCK(fdp);
1177
1178	error = closef(fp, td);
1179	if (holdleaders) {
1180		FILEDESC_XLOCK(fdp);
1181		fdp->fd_holdleaderscount--;
1182		if (fdp->fd_holdleaderscount == 0 &&
1183		    fdp->fd_holdleaderswakeup != 0) {
1184			fdp->fd_holdleaderswakeup = 0;
1185			wakeup(&fdp->fd_holdleaderscount);
1186		}
1187		FILEDESC_XUNLOCK(fdp);
1188	}
1189	return (error);
1190}
1191
1192/*
1193 * Close a file descriptor.
1194 */
1195#ifndef _SYS_SYSPROTO_H_
1196struct close_args {
1197	int     fd;
1198};
1199#endif
1200/* ARGSUSED */
1201int
1202sys_close(td, uap)
1203	struct thread *td;
1204	struct close_args *uap;
1205{
1206
1207	return (kern_close(td, uap->fd));
1208}
1209
1210int
1211kern_close(td, fd)
1212	struct thread *td;
1213	int fd;
1214{
1215	struct filedesc *fdp;
1216	struct file *fp;
1217
1218	fdp = td->td_proc->p_fd;
1219
1220	AUDIT_SYSCLOSE(td, fd);
1221
1222	FILEDESC_XLOCK(fdp);
1223	if ((fp = fget_locked(fdp, fd)) == NULL) {
1224		FILEDESC_XUNLOCK(fdp);
1225		return (EBADF);
1226	}
1227	fdfree(fdp, fd);
1228
1229	/* closefp() drops the FILEDESC lock for us. */
1230	return (closefp(fdp, fd, fp, td, 1));
1231}
1232
1233/*
1234 * Close open file descriptors.
1235 */
1236#ifndef _SYS_SYSPROTO_H_
1237struct closefrom_args {
1238	int	lowfd;
1239};
1240#endif
1241/* ARGSUSED */
1242int
1243sys_closefrom(struct thread *td, struct closefrom_args *uap)
1244{
1245	struct filedesc *fdp;
1246	int fd;
1247
1248	fdp = td->td_proc->p_fd;
1249	AUDIT_ARG_FD(uap->lowfd);
1250
1251	/*
1252	 * Treat negative starting file descriptor values identical to
1253	 * closefrom(0) which closes all files.
1254	 */
1255	if (uap->lowfd < 0)
1256		uap->lowfd = 0;
1257	FILEDESC_SLOCK(fdp);
1258	for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1259		if (fdp->fd_ofiles[fd].fde_file != NULL) {
1260			FILEDESC_SUNLOCK(fdp);
1261			(void)kern_close(td, fd);
1262			FILEDESC_SLOCK(fdp);
1263		}
1264	}
1265	FILEDESC_SUNLOCK(fdp);
1266	return (0);
1267}
1268
1269#if defined(COMPAT_43)
1270/*
1271 * Return status information about a file descriptor.
1272 */
1273#ifndef _SYS_SYSPROTO_H_
1274struct ofstat_args {
1275	int	fd;
1276	struct	ostat *sb;
1277};
1278#endif
1279/* ARGSUSED */
1280int
1281ofstat(struct thread *td, struct ofstat_args *uap)
1282{
1283	struct ostat oub;
1284	struct stat ub;
1285	int error;
1286
1287	error = kern_fstat(td, uap->fd, &ub);
1288	if (error == 0) {
1289		cvtstat(&ub, &oub);
1290		error = copyout(&oub, uap->sb, sizeof(oub));
1291	}
1292	return (error);
1293}
1294#endif /* COMPAT_43 */
1295
1296/*
1297 * Return status information about a file descriptor.
1298 */
1299#ifndef _SYS_SYSPROTO_H_
1300struct fstat_args {
1301	int	fd;
1302	struct	stat *sb;
1303};
1304#endif
1305/* ARGSUSED */
1306int
1307sys_fstat(struct thread *td, struct fstat_args *uap)
1308{
1309	struct stat ub;
1310	int error;
1311
1312	error = kern_fstat(td, uap->fd, &ub);
1313	if (error == 0)
1314		error = copyout(&ub, uap->sb, sizeof(ub));
1315	return (error);
1316}
1317
1318int
1319kern_fstat(struct thread *td, int fd, struct stat *sbp)
1320{
1321	struct file *fp;
1322	cap_rights_t rights;
1323	int error;
1324
1325	AUDIT_ARG_FD(fd);
1326
1327	error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1328	if (error != 0)
1329		return (error);
1330
1331	AUDIT_ARG_FILE(td->td_proc, fp);
1332
1333	error = fo_stat(fp, sbp, td->td_ucred, td);
1334	fdrop(fp, td);
1335#ifdef KTRACE
1336	if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1337		ktrstat(sbp);
1338#endif
1339	return (error);
1340}
1341
1342/*
1343 * Return status information about a file descriptor.
1344 */
1345#ifndef _SYS_SYSPROTO_H_
1346struct nfstat_args {
1347	int	fd;
1348	struct	nstat *sb;
1349};
1350#endif
1351/* ARGSUSED */
1352int
1353sys_nfstat(struct thread *td, struct nfstat_args *uap)
1354{
1355	struct nstat nub;
1356	struct stat ub;
1357	int error;
1358
1359	error = kern_fstat(td, uap->fd, &ub);
1360	if (error == 0) {
1361		cvtnstat(&ub, &nub);
1362		error = copyout(&nub, uap->sb, sizeof(nub));
1363	}
1364	return (error);
1365}
1366
1367/*
1368 * Return pathconf information about a file descriptor.
1369 */
1370#ifndef _SYS_SYSPROTO_H_
1371struct fpathconf_args {
1372	int	fd;
1373	int	name;
1374};
1375#endif
1376/* ARGSUSED */
1377int
1378sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1379{
1380	struct file *fp;
1381	struct vnode *vp;
1382	cap_rights_t rights;
1383	int error;
1384
1385	error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1386	if (error != 0)
1387		return (error);
1388
1389	/* If asynchronous I/O is available, it works for all descriptors. */
1390	if (uap->name == _PC_ASYNC_IO) {
1391		td->td_retval[0] = async_io_version;
1392		goto out;
1393	}
1394	vp = fp->f_vnode;
1395	if (vp != NULL) {
1396		vn_lock(vp, LK_SHARED | LK_RETRY);
1397		error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1398		VOP_UNLOCK(vp, 0);
1399	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1400		if (uap->name != _PC_PIPE_BUF) {
1401			error = EINVAL;
1402		} else {
1403			td->td_retval[0] = PIPE_BUF;
1404			error = 0;
1405		}
1406	} else {
1407		error = EOPNOTSUPP;
1408	}
1409out:
1410	fdrop(fp, td);
1411	return (error);
1412}
1413
1414/*
1415 * Initialize filecaps structure.
1416 */
1417void
1418filecaps_init(struct filecaps *fcaps)
1419{
1420
1421	bzero(fcaps, sizeof(*fcaps));
1422	fcaps->fc_nioctls = -1;
1423}
1424
1425/*
1426 * Copy filecaps structure allocating memory for ioctls array if needed.
1427 */
1428void
1429filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1430{
1431	size_t size;
1432
1433	*dst = *src;
1434	if (src->fc_ioctls != NULL) {
1435		KASSERT(src->fc_nioctls > 0,
1436		    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1437
1438		size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1439		dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1440		bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1441	}
1442}
1443
1444/*
1445 * Move filecaps structure to the new place and clear the old place.
1446 */
1447void
1448filecaps_move(struct filecaps *src, struct filecaps *dst)
1449{
1450
1451	*dst = *src;
1452	bzero(src, sizeof(*src));
1453}
1454
1455/*
1456 * Fill the given filecaps structure with full rights.
1457 */
1458static void
1459filecaps_fill(struct filecaps *fcaps)
1460{
1461
1462	CAP_ALL(&fcaps->fc_rights);
1463	fcaps->fc_ioctls = NULL;
1464	fcaps->fc_nioctls = -1;
1465	fcaps->fc_fcntls = CAP_FCNTL_ALL;
1466}
1467
1468/*
1469 * Free memory allocated within filecaps structure.
1470 */
1471void
1472filecaps_free(struct filecaps *fcaps)
1473{
1474
1475	free(fcaps->fc_ioctls, M_FILECAPS);
1476	bzero(fcaps, sizeof(*fcaps));
1477}
1478
1479/*
1480 * Validate the given filecaps structure.
1481 */
1482static void
1483filecaps_validate(const struct filecaps *fcaps, const char *func)
1484{
1485
1486	KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1487	    ("%s: invalid rights", func));
1488	KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1489	    ("%s: invalid fcntls", func));
1490	KASSERT(fcaps->fc_fcntls == 0 ||
1491	    cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1492	    ("%s: fcntls without CAP_FCNTL", func));
1493	KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1494	    (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1495	    ("%s: invalid ioctls", func));
1496	KASSERT(fcaps->fc_nioctls == 0 ||
1497	    cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1498	    ("%s: ioctls without CAP_IOCTL", func));
1499}
1500
1501static void
1502fdgrowtable_exp(struct filedesc *fdp, int nfd)
1503{
1504	int nfd1;
1505
1506	FILEDESC_XLOCK_ASSERT(fdp);
1507
1508	nfd1 = fdp->fd_nfiles * 2;
1509	if (nfd1 < nfd)
1510		nfd1 = nfd;
1511	fdgrowtable(fdp, nfd1);
1512}
1513
1514/*
1515 * Grow the file table to accomodate (at least) nfd descriptors.
1516 */
1517static void
1518fdgrowtable(struct filedesc *fdp, int nfd)
1519{
1520	struct filedesc0 *fdp0;
1521	struct freetable *ft;
1522	struct fdescenttbl *ntable;
1523	struct fdescenttbl *otable;
1524	int nnfiles, onfiles;
1525	NDSLOTTYPE *nmap, *omap;
1526
1527	FILEDESC_XLOCK_ASSERT(fdp);
1528
1529	KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1530
1531	/* save old values */
1532	onfiles = fdp->fd_nfiles;
1533	otable = fdp->fd_files;
1534	omap = fdp->fd_map;
1535
1536	/* compute the size of the new table */
1537	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1538	if (nnfiles <= onfiles)
1539		/* the table is already large enough */
1540		return;
1541
1542	/*
1543	 * Allocate a new table.  We need enough space for the number of
1544	 * entries, file entries themselves and the struct freetable we will use
1545	 * when we decommission the table and place it on the freelist.
1546	 * We place the struct freetable in the middle so we don't have
1547	 * to worry about padding.
1548	 */
1549	ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1550	    nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1551	    sizeof(struct freetable),
1552	    M_FILEDESC, M_ZERO | M_WAITOK);
1553	/* copy the old data */
1554	ntable->fdt_nfiles = nnfiles;
1555	memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1556	    onfiles * sizeof(ntable->fdt_ofiles[0]));
1557
1558	/*
1559	 * Allocate a new map only if the old is not large enough.  It will
1560	 * grow at a slower rate than the table as it can map more
1561	 * entries than the table can hold.
1562	 */
1563	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1564		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1565		    M_ZERO | M_WAITOK);
1566		/* copy over the old data and update the pointer */
1567		memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1568		fdp->fd_map = nmap;
1569	}
1570
1571	/*
1572	 * Make sure that ntable is correctly initialized before we replace
1573	 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1574	 * data.
1575	 */
1576	atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1577
1578	/*
1579	 * Do not free the old file table, as some threads may still
1580	 * reference entries within it.  Instead, place it on a freelist
1581	 * which will be processed when the struct filedesc is released.
1582	 *
1583	 * Note that if onfiles == NDFILE, we're dealing with the original
1584	 * static allocation contained within (struct filedesc0 *)fdp,
1585	 * which must not be freed.
1586	 */
1587	if (onfiles > NDFILE) {
1588		ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1589		fdp0 = (struct filedesc0 *)fdp;
1590		ft->ft_table = otable;
1591		SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1592	}
1593	/*
1594	 * The map does not have the same possibility of threads still
1595	 * holding references to it.  So always free it as long as it
1596	 * does not reference the original static allocation.
1597	 */
1598	if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1599		free(omap, M_FILEDESC);
1600}
1601
1602/*
1603 * Allocate a file descriptor for the process.
1604 */
1605int
1606fdalloc(struct thread *td, int minfd, int *result)
1607{
1608	struct proc *p = td->td_proc;
1609	struct filedesc *fdp = p->p_fd;
1610	int fd = -1, maxfd, allocfd;
1611#ifdef RACCT
1612	int error;
1613#endif
1614
1615	FILEDESC_XLOCK_ASSERT(fdp);
1616
1617	if (fdp->fd_freefile > minfd)
1618		minfd = fdp->fd_freefile;
1619
1620	maxfd = getmaxfd(p);
1621
1622	/*
1623	 * Search the bitmap for a free descriptor starting at minfd.
1624	 * If none is found, grow the file table.
1625	 */
1626	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1627	if (fd >= maxfd)
1628		return (EMFILE);
1629	if (fd >= fdp->fd_nfiles) {
1630		allocfd = min(fd * 2, maxfd);
1631#ifdef RACCT
1632		PROC_LOCK(p);
1633		error = racct_set(p, RACCT_NOFILE, allocfd);
1634		PROC_UNLOCK(p);
1635		if (error != 0)
1636			return (EMFILE);
1637#endif
1638		/*
1639		 * fd is already equal to first free descriptor >= minfd, so
1640		 * we only need to grow the table and we are done.
1641		 */
1642		fdgrowtable_exp(fdp, allocfd);
1643	}
1644
1645	/*
1646	 * Perform some sanity checks, then mark the file descriptor as
1647	 * used and return it to the caller.
1648	 */
1649	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1650	    ("invalid descriptor %d", fd));
1651	KASSERT(!fdisused(fdp, fd),
1652	    ("fd_first_free() returned non-free descriptor"));
1653	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1654	    ("file descriptor isn't free"));
1655	KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1656	fdused(fdp, fd);
1657	*result = fd;
1658	return (0);
1659}
1660
1661/*
1662 * Allocate n file descriptors for the process.
1663 */
1664int
1665fdallocn(struct thread *td, int minfd, int *fds, int n)
1666{
1667	struct proc *p = td->td_proc;
1668	struct filedesc *fdp = p->p_fd;
1669	int i;
1670
1671	FILEDESC_XLOCK_ASSERT(fdp);
1672
1673	for (i = 0; i < n; i++)
1674		if (fdalloc(td, 0, &fds[i]) != 0)
1675			break;
1676
1677	if (i < n) {
1678		for (i--; i >= 0; i--)
1679			fdunused(fdp, fds[i]);
1680		return (EMFILE);
1681	}
1682
1683	return (0);
1684}
1685
1686/*
1687 * Create a new open file structure and allocate a file decriptor for the
1688 * process that refers to it.  We add one reference to the file for the
1689 * descriptor table and one reference for resultfp. This is to prevent us
1690 * being preempted and the entry in the descriptor table closed after we
1691 * release the FILEDESC lock.
1692 */
1693int
1694falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1695{
1696	struct file *fp;
1697	int error, fd;
1698
1699	error = falloc_noinstall(td, &fp);
1700	if (error)
1701		return (error);		/* no reference held on error */
1702
1703	error = finstall(td, fp, &fd, flags, NULL);
1704	if (error) {
1705		fdrop(fp, td);		/* one reference (fp only) */
1706		return (error);
1707	}
1708
1709	if (resultfp != NULL)
1710		*resultfp = fp;		/* copy out result */
1711	else
1712		fdrop(fp, td);		/* release local reference */
1713
1714	if (resultfd != NULL)
1715		*resultfd = fd;
1716
1717	return (0);
1718}
1719
1720/*
1721 * Create a new open file structure without allocating a file descriptor.
1722 */
1723int
1724falloc_noinstall(struct thread *td, struct file **resultfp)
1725{
1726	struct file *fp;
1727	int maxuserfiles = maxfiles - (maxfiles / 20);
1728	static struct timeval lastfail;
1729	static int curfail;
1730
1731	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1732
1733	if ((openfiles >= maxuserfiles &&
1734	    priv_check(td, PRIV_MAXFILES) != 0) ||
1735	    openfiles >= maxfiles) {
1736		if (ppsratecheck(&lastfail, &curfail, 1)) {
1737			printf("kern.maxfiles limit exceeded by uid %i, "
1738			    "please see tuning(7).\n", td->td_ucred->cr_ruid);
1739		}
1740		return (ENFILE);
1741	}
1742	atomic_add_int(&openfiles, 1);
1743	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1744	refcount_init(&fp->f_count, 1);
1745	fp->f_cred = crhold(td->td_ucred);
1746	fp->f_ops = &badfileops;
1747	*resultfp = fp;
1748	return (0);
1749}
1750
1751/*
1752 * Install a file in a file descriptor table.
1753 */
1754int
1755finstall(struct thread *td, struct file *fp, int *fd, int flags,
1756    struct filecaps *fcaps)
1757{
1758	struct filedesc *fdp = td->td_proc->p_fd;
1759	struct filedescent *fde;
1760	int error;
1761
1762	KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1763	KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1764	if (fcaps != NULL)
1765		filecaps_validate(fcaps, __func__);
1766
1767	FILEDESC_XLOCK(fdp);
1768	if ((error = fdalloc(td, 0, fd))) {
1769		FILEDESC_XUNLOCK(fdp);
1770		return (error);
1771	}
1772	fhold(fp);
1773	fde = &fdp->fd_ofiles[*fd];
1774#ifdef CAPABILITIES
1775	seq_write_begin(&fde->fde_seq);
1776#endif
1777	fde->fde_file = fp;
1778	if ((flags & O_CLOEXEC) != 0)
1779		fde->fde_flags |= UF_EXCLOSE;
1780	if (fcaps != NULL)
1781		filecaps_move(fcaps, &fde->fde_caps);
1782	else
1783		filecaps_fill(&fde->fde_caps);
1784#ifdef CAPABILITIES
1785	seq_write_end(&fde->fde_seq);
1786#endif
1787	FILEDESC_XUNLOCK(fdp);
1788	return (0);
1789}
1790
1791/*
1792 * Build a new filedesc structure from another.
1793 * Copy the current, root, and jail root vnode references.
1794 */
1795struct filedesc *
1796fdinit(struct filedesc *fdp)
1797{
1798	struct filedesc0 *newfdp;
1799
1800	newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1801	FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1802	if (fdp != NULL) {
1803		FILEDESC_SLOCK(fdp);
1804		newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1805		if (newfdp->fd_fd.fd_cdir)
1806			VREF(newfdp->fd_fd.fd_cdir);
1807		newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1808		if (newfdp->fd_fd.fd_rdir)
1809			VREF(newfdp->fd_fd.fd_rdir);
1810		newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1811		if (newfdp->fd_fd.fd_jdir)
1812			VREF(newfdp->fd_fd.fd_jdir);
1813		FILEDESC_SUNLOCK(fdp);
1814	}
1815
1816	/* Create the file descriptor table. */
1817	newfdp->fd_fd.fd_refcnt = 1;
1818	newfdp->fd_fd.fd_holdcnt = 1;
1819	newfdp->fd_fd.fd_cmask = CMASK;
1820	newfdp->fd_dfiles.fdt_nfiles = NDFILE;
1821	newfdp->fd_fd.fd_files = (struct fdescenttbl *)&newfdp->fd_dfiles;
1822	newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1823	newfdp->fd_fd.fd_lastfile = -1;
1824	return (&newfdp->fd_fd);
1825}
1826
1827static struct filedesc *
1828fdhold(struct proc *p)
1829{
1830	struct filedesc *fdp;
1831
1832	mtx_lock(&fdesc_mtx);
1833	fdp = p->p_fd;
1834	if (fdp != NULL)
1835		fdp->fd_holdcnt++;
1836	mtx_unlock(&fdesc_mtx);
1837	return (fdp);
1838}
1839
1840static void
1841fddrop(struct filedesc *fdp)
1842{
1843	struct filedesc0 *fdp0;
1844	struct freetable *ft;
1845	int i;
1846
1847	mtx_lock(&fdesc_mtx);
1848	i = --fdp->fd_holdcnt;
1849	mtx_unlock(&fdesc_mtx);
1850	if (i > 0)
1851		return;
1852
1853	FILEDESC_LOCK_DESTROY(fdp);
1854	fdp0 = (struct filedesc0 *)fdp;
1855	while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1856		SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1857		free(ft->ft_table, M_FILEDESC);
1858	}
1859	free(fdp, M_FILEDESC);
1860}
1861
1862/*
1863 * Share a filedesc structure.
1864 */
1865struct filedesc *
1866fdshare(struct filedesc *fdp)
1867{
1868
1869	FILEDESC_XLOCK(fdp);
1870	fdp->fd_refcnt++;
1871	FILEDESC_XUNLOCK(fdp);
1872	return (fdp);
1873}
1874
1875/*
1876 * Unshare a filedesc structure, if necessary by making a copy
1877 */
1878void
1879fdunshare(struct thread *td)
1880{
1881	struct filedesc *tmp;
1882	struct proc *p = td->td_proc;
1883
1884	if (p->p_fd->fd_refcnt == 1)
1885		return;
1886
1887	tmp = fdcopy(p->p_fd);
1888	fdescfree(td);
1889	p->p_fd = tmp;
1890}
1891
1892/*
1893 * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
1894 * this is to ease callers, not catch errors.
1895 */
1896struct filedesc *
1897fdcopy(struct filedesc *fdp)
1898{
1899	struct filedesc *newfdp;
1900	struct filedescent *nfde, *ofde;
1901	int i;
1902
1903	/* Certain daemons might not have file descriptors. */
1904	if (fdp == NULL)
1905		return (NULL);
1906
1907	newfdp = fdinit(fdp);
1908	FILEDESC_SLOCK(fdp);
1909	while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1910		FILEDESC_SUNLOCK(fdp);
1911		FILEDESC_XLOCK(newfdp);
1912		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1913		FILEDESC_XUNLOCK(newfdp);
1914		FILEDESC_SLOCK(fdp);
1915	}
1916	/* copy all passable descriptors (i.e. not kqueue) */
1917	newfdp->fd_freefile = -1;
1918	for (i = 0; i <= fdp->fd_lastfile; ++i) {
1919		ofde = &fdp->fd_ofiles[i];
1920		if (ofde->fde_file == NULL ||
1921		    (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
1922			if (newfdp->fd_freefile == -1)
1923				newfdp->fd_freefile = i;
1924			continue;
1925		}
1926		nfde = &newfdp->fd_ofiles[i];
1927		*nfde = *ofde;
1928		filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1929		fhold(nfde->fde_file);
1930		fdused_init(newfdp, i);
1931		newfdp->fd_lastfile = i;
1932	}
1933	if (newfdp->fd_freefile == -1)
1934		newfdp->fd_freefile = i;
1935	newfdp->fd_cmask = fdp->fd_cmask;
1936	FILEDESC_SUNLOCK(fdp);
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