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