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