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