kern_descrip.c revision 262458
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 262458 2014-02-24 21:03:38Z 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 */
299static inline void
300fdfree(struct filedesc *fdp, int fd)
301{
302	struct filedescent *fde;
303
304	fde = &fdp->fd_ofiles[fd];
305	filecaps_free(&fde->fde_caps);
306	bzero(fde, sizeof(*fde));
307	fdunused(fdp, fd);
308}
309
310/*
311 * System calls on descriptors.
312 */
313#ifndef _SYS_SYSPROTO_H_
314struct getdtablesize_args {
315	int	dummy;
316};
317#endif
318/* ARGSUSED */
319int
320sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
321{
322	struct proc *p = td->td_proc;
323	uint64_t lim;
324
325	PROC_LOCK(p);
326	td->td_retval[0] =
327	    min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
328	lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
329	PROC_UNLOCK(p);
330	if (lim < td->td_retval[0])
331		td->td_retval[0] = lim;
332	return (0);
333}
334
335/*
336 * Duplicate a file descriptor to a particular value.
337 *
338 * Note: keep in mind that a potential race condition exists when closing
339 * descriptors from a shared descriptor table (via rfork).
340 */
341#ifndef _SYS_SYSPROTO_H_
342struct dup2_args {
343	u_int	from;
344	u_int	to;
345};
346#endif
347/* ARGSUSED */
348int
349sys_dup2(struct thread *td, struct dup2_args *uap)
350{
351
352	return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
353		    td->td_retval));
354}
355
356/*
357 * Duplicate a file descriptor.
358 */
359#ifndef _SYS_SYSPROTO_H_
360struct dup_args {
361	u_int	fd;
362};
363#endif
364/* ARGSUSED */
365int
366sys_dup(struct thread *td, struct dup_args *uap)
367{
368
369	return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
370}
371
372/*
373 * The file control system call.
374 */
375#ifndef _SYS_SYSPROTO_H_
376struct fcntl_args {
377	int	fd;
378	int	cmd;
379	long	arg;
380};
381#endif
382/* ARGSUSED */
383int
384sys_fcntl(struct thread *td, struct fcntl_args *uap)
385{
386	struct flock fl;
387	struct __oflock ofl;
388	intptr_t arg;
389	int error;
390	int cmd;
391
392	error = 0;
393	cmd = uap->cmd;
394	switch (uap->cmd) {
395	case F_OGETLK:
396	case F_OSETLK:
397	case F_OSETLKW:
398		/*
399		 * Convert old flock structure to new.
400		 */
401		error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
402		fl.l_start = ofl.l_start;
403		fl.l_len = ofl.l_len;
404		fl.l_pid = ofl.l_pid;
405		fl.l_type = ofl.l_type;
406		fl.l_whence = ofl.l_whence;
407		fl.l_sysid = 0;
408
409		switch (uap->cmd) {
410		case F_OGETLK:
411		    cmd = F_GETLK;
412		    break;
413		case F_OSETLK:
414		    cmd = F_SETLK;
415		    break;
416		case F_OSETLKW:
417		    cmd = F_SETLKW;
418		    break;
419		}
420		arg = (intptr_t)&fl;
421		break;
422        case F_GETLK:
423        case F_SETLK:
424        case F_SETLKW:
425	case F_SETLK_REMOTE:
426                error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
427                arg = (intptr_t)&fl;
428                break;
429	default:
430		arg = uap->arg;
431		break;
432	}
433	if (error)
434		return (error);
435	error = kern_fcntl(td, uap->fd, cmd, arg);
436	if (error)
437		return (error);
438	if (uap->cmd == F_OGETLK) {
439		ofl.l_start = fl.l_start;
440		ofl.l_len = fl.l_len;
441		ofl.l_pid = fl.l_pid;
442		ofl.l_type = fl.l_type;
443		ofl.l_whence = fl.l_whence;
444		error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
445	} else if (uap->cmd == F_GETLK) {
446		error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
447	}
448	return (error);
449}
450
451int
452kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
453{
454	struct filedesc *fdp;
455	struct flock *flp;
456	struct file *fp, *fp2;
457	struct filedescent *fde;
458	struct proc *p;
459	struct vnode *vp;
460	cap_rights_t rights;
461	int error, flg, tmp;
462	u_int old, new;
463	uint64_t bsize;
464	off_t foffset;
465
466	error = 0;
467	flg = F_POSIX;
468	p = td->td_proc;
469	fdp = p->p_fd;
470
471	switch (cmd) {
472	case F_DUPFD:
473		tmp = arg;
474		error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
475		break;
476
477	case F_DUPFD_CLOEXEC:
478		tmp = arg;
479		error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
480		    td->td_retval);
481		break;
482
483	case F_DUP2FD:
484		tmp = arg;
485		error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
486		break;
487
488	case F_DUP2FD_CLOEXEC:
489		tmp = arg;
490		error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
491		    td->td_retval);
492		break;
493
494	case F_GETFD:
495		FILEDESC_SLOCK(fdp);
496		if ((fp = fget_locked(fdp, fd)) == NULL) {
497			FILEDESC_SUNLOCK(fdp);
498			error = EBADF;
499			break;
500		}
501		fde = &fdp->fd_ofiles[fd];
502		td->td_retval[0] =
503		    (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
504		FILEDESC_SUNLOCK(fdp);
505		break;
506
507	case F_SETFD:
508		FILEDESC_XLOCK(fdp);
509		if ((fp = fget_locked(fdp, fd)) == NULL) {
510			FILEDESC_XUNLOCK(fdp);
511			error = EBADF;
512			break;
513		}
514		fde = &fdp->fd_ofiles[fd];
515		fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
516		    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
517		FILEDESC_XUNLOCK(fdp);
518		break;
519
520	case F_GETFL:
521		error = fget_unlocked(fdp, fd,
522		    cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
523		if (error != 0)
524			break;
525		td->td_retval[0] = OFLAGS(fp->f_flag);
526		fdrop(fp, td);
527		break;
528
529	case F_SETFL:
530		error = fget_unlocked(fdp, fd,
531		    cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
532		if (error != 0)
533			break;
534		do {
535			tmp = flg = fp->f_flag;
536			tmp &= ~FCNTLFLAGS;
537			tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
538		} while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
539		tmp = fp->f_flag & FNONBLOCK;
540		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
541		if (error != 0) {
542			fdrop(fp, td);
543			break;
544		}
545		tmp = fp->f_flag & FASYNC;
546		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
547		if (error == 0) {
548			fdrop(fp, td);
549			break;
550		}
551		atomic_clear_int(&fp->f_flag, FNONBLOCK);
552		tmp = 0;
553		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
554		fdrop(fp, td);
555		break;
556
557	case F_GETOWN:
558		error = fget_unlocked(fdp, fd,
559		    cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
560		if (error != 0)
561			break;
562		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
563		if (error == 0)
564			td->td_retval[0] = tmp;
565		fdrop(fp, td);
566		break;
567
568	case F_SETOWN:
569		error = fget_unlocked(fdp, fd,
570		    cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
571		if (error != 0)
572			break;
573		tmp = arg;
574		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
575		fdrop(fp, td);
576		break;
577
578	case F_SETLK_REMOTE:
579		error = priv_check(td, PRIV_NFS_LOCKD);
580		if (error)
581			return (error);
582		flg = F_REMOTE;
583		goto do_setlk;
584
585	case F_SETLKW:
586		flg |= F_WAIT;
587		/* FALLTHROUGH F_SETLK */
588
589	case F_SETLK:
590	do_setlk:
591		cap_rights_init(&rights, CAP_FLOCK);
592		error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
593		if (error != 0)
594			break;
595		if (fp->f_type != DTYPE_VNODE) {
596			error = EBADF;
597			fdrop(fp, td);
598			break;
599		}
600
601		flp = (struct flock *)arg;
602		if (flp->l_whence == SEEK_CUR) {
603			foffset = foffset_get(fp);
604			if (foffset < 0 ||
605			    (flp->l_start > 0 &&
606			     foffset > OFF_MAX - flp->l_start)) {
607				FILEDESC_SUNLOCK(fdp);
608				error = EOVERFLOW;
609				fdrop(fp, td);
610				break;
611			}
612			flp->l_start += foffset;
613		}
614
615		vp = fp->f_vnode;
616		switch (flp->l_type) {
617		case F_RDLCK:
618			if ((fp->f_flag & FREAD) == 0) {
619				error = EBADF;
620				break;
621			}
622			PROC_LOCK(p->p_leader);
623			p->p_leader->p_flag |= P_ADVLOCK;
624			PROC_UNLOCK(p->p_leader);
625			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
626			    flp, flg);
627			break;
628		case F_WRLCK:
629			if ((fp->f_flag & FWRITE) == 0) {
630				error = EBADF;
631				break;
632			}
633			PROC_LOCK(p->p_leader);
634			p->p_leader->p_flag |= P_ADVLOCK;
635			PROC_UNLOCK(p->p_leader);
636			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
637			    flp, flg);
638			break;
639		case F_UNLCK:
640			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
641			    flp, flg);
642			break;
643		case F_UNLCKSYS:
644			/*
645			 * Temporary api for testing remote lock
646			 * infrastructure.
647			 */
648			if (flg != F_REMOTE) {
649				error = EINVAL;
650				break;
651			}
652			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
653			    F_UNLCKSYS, flp, flg);
654			break;
655		default:
656			error = EINVAL;
657			break;
658		}
659		if (error != 0 || flp->l_type == F_UNLCK ||
660		    flp->l_type == F_UNLCKSYS) {
661			fdrop(fp, td);
662			break;
663		}
664
665		/*
666		 * Check for a race with close.
667		 *
668		 * The vnode is now advisory locked (or unlocked, but this case
669		 * is not really important) as the caller requested.
670		 * We had to drop the filedesc lock, so we need to recheck if
671		 * the descriptor is still valid, because if it was closed
672		 * in the meantime we need to remove advisory lock from the
673		 * vnode - close on any descriptor leading to an advisory
674		 * locked vnode, removes that lock.
675		 * We will return 0 on purpose in that case, as the result of
676		 * successful advisory lock might have been externally visible
677		 * already. This is fine - effectively we pretend to the caller
678		 * that the closing thread was a bit slower and that the
679		 * advisory lock succeeded before the close.
680		 */
681		error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
682		if (error != 0) {
683			fdrop(fp, td);
684			break;
685		}
686		if (fp != fp2) {
687			flp->l_whence = SEEK_SET;
688			flp->l_start = 0;
689			flp->l_len = 0;
690			flp->l_type = F_UNLCK;
691			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
692			    F_UNLCK, flp, F_POSIX);
693		}
694		fdrop(fp, td);
695		fdrop(fp2, td);
696		break;
697
698	case F_GETLK:
699		error = fget_unlocked(fdp, fd,
700		    cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
701		if (error != 0)
702			break;
703		if (fp->f_type != DTYPE_VNODE) {
704			error = EBADF;
705			fdrop(fp, td);
706			break;
707		}
708		flp = (struct flock *)arg;
709		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
710		    flp->l_type != F_UNLCK) {
711			error = EINVAL;
712			fdrop(fp, td);
713			break;
714		}
715		if (flp->l_whence == SEEK_CUR) {
716			foffset = foffset_get(fp);
717			if ((flp->l_start > 0 &&
718			    foffset > OFF_MAX - flp->l_start) ||
719			    (flp->l_start < 0 &&
720			     foffset < OFF_MIN - flp->l_start)) {
721				FILEDESC_SUNLOCK(fdp);
722				error = EOVERFLOW;
723				fdrop(fp, td);
724				break;
725			}
726			flp->l_start += foffset;
727		}
728		vp = fp->f_vnode;
729		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
730		    F_POSIX);
731		fdrop(fp, td);
732		break;
733
734	case F_RDAHEAD:
735		arg = arg ? 128 * 1024: 0;
736		/* FALLTHROUGH */
737	case F_READAHEAD:
738		error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
739		if (error != 0)
740			break;
741		if (fp->f_type != DTYPE_VNODE) {
742			fdrop(fp, td);
743			error = EBADF;
744			break;
745		}
746		if (arg >= 0) {
747			vp = fp->f_vnode;
748			error = vn_lock(vp, LK_SHARED);
749			if (error != 0) {
750				fdrop(fp, td);
751				break;
752			}
753			bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
754			VOP_UNLOCK(vp, 0);
755			fp->f_seqcount = (arg + bsize - 1) / bsize;
756			do {
757				new = old = fp->f_flag;
758				new |= FRDAHEAD;
759			} while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
760		} else {
761			do {
762				new = old = fp->f_flag;
763				new &= ~FRDAHEAD;
764			} while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
765		}
766		fdrop(fp, td);
767		break;
768
769	default:
770		error = EINVAL;
771		break;
772	}
773	return (error);
774}
775
776static int
777getmaxfd(struct proc *p)
778{
779	int maxfd;
780
781	PROC_LOCK(p);
782	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
783	PROC_UNLOCK(p);
784
785	return (maxfd);
786}
787
788/*
789 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
790 */
791int
792do_dup(struct thread *td, int flags, int old, int new,
793    register_t *retval)
794{
795	struct filedesc *fdp;
796	struct filedescent *oldfde, *newfde;
797	struct proc *p;
798	struct file *fp;
799	struct file *delfp;
800	int error, maxfd;
801
802	p = td->td_proc;
803	fdp = p->p_fd;
804
805	/*
806	 * Verify we have a valid descriptor to dup from and possibly to
807	 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
808	 * return EINVAL when the new descriptor is out of bounds.
809	 */
810	if (old < 0)
811		return (EBADF);
812	if (new < 0)
813		return (flags & DUP_FCNTL ? EINVAL : EBADF);
814	maxfd = getmaxfd(p);
815	if (new >= maxfd)
816		return (flags & DUP_FCNTL ? EINVAL : EBADF);
817
818	FILEDESC_XLOCK(fdp);
819	if (fget_locked(fdp, old) == NULL) {
820		FILEDESC_XUNLOCK(fdp);
821		return (EBADF);
822	}
823	oldfde = &fdp->fd_ofiles[old];
824	if (flags & DUP_FIXED && old == new) {
825		*retval = new;
826		if (flags & DUP_CLOEXEC)
827			fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
828		FILEDESC_XUNLOCK(fdp);
829		return (0);
830	}
831	fp = oldfde->fde_file;
832	fhold(fp);
833
834	/*
835	 * If the caller specified a file descriptor, make sure the file
836	 * table is large enough to hold it, and grab it.  Otherwise, just
837	 * allocate a new descriptor the usual way.
838	 */
839	if (flags & DUP_FIXED) {
840		if (new >= fdp->fd_nfiles) {
841			/*
842			 * The resource limits are here instead of e.g.
843			 * fdalloc(), because the file descriptor table may be
844			 * shared between processes, so we can't really use
845			 * racct_add()/racct_sub().  Instead of counting the
846			 * number of actually allocated descriptors, just put
847			 * the limit on the size of the file descriptor table.
848			 */
849#ifdef RACCT
850			PROC_LOCK(p);
851			error = racct_set(p, RACCT_NOFILE, new + 1);
852			PROC_UNLOCK(p);
853			if (error != 0) {
854				FILEDESC_XUNLOCK(fdp);
855				fdrop(fp, td);
856				return (EMFILE);
857			}
858#endif
859			fdgrowtable_exp(fdp, new + 1);
860			oldfde = &fdp->fd_ofiles[old];
861		}
862		newfde = &fdp->fd_ofiles[new];
863		if (newfde->fde_file == NULL)
864			fdused(fdp, new);
865	} else {
866		if ((error = fdalloc(td, new, &new)) != 0) {
867			FILEDESC_XUNLOCK(fdp);
868			fdrop(fp, td);
869			return (error);
870		}
871		newfde = &fdp->fd_ofiles[new];
872	}
873
874	KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
875	KASSERT(old != new, ("new fd is same as old"));
876
877	delfp = newfde->fde_file;
878
879	/*
880	 * Duplicate the source descriptor.
881	 */
882	filecaps_free(&newfde->fde_caps);
883	*newfde = *oldfde;
884	filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
885	if ((flags & DUP_CLOEXEC) != 0)
886		newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
887	else
888		newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
889	if (new > fdp->fd_lastfile)
890		fdp->fd_lastfile = new;
891	*retval = new;
892
893	if (delfp != NULL) {
894		(void) closefp(fdp, new, delfp, td, 1);
895		/* closefp() drops the FILEDESC lock for us. */
896	} else {
897		FILEDESC_XUNLOCK(fdp);
898	}
899
900	return (0);
901}
902
903/*
904 * If sigio is on the list associated with a process or process group,
905 * disable signalling from the device, remove sigio from the list and
906 * free sigio.
907 */
908void
909funsetown(struct sigio **sigiop)
910{
911	struct sigio *sigio;
912
913	SIGIO_LOCK();
914	sigio = *sigiop;
915	if (sigio == NULL) {
916		SIGIO_UNLOCK();
917		return;
918	}
919	*(sigio->sio_myref) = NULL;
920	if ((sigio)->sio_pgid < 0) {
921		struct pgrp *pg = (sigio)->sio_pgrp;
922		PGRP_LOCK(pg);
923		SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
924			     sigio, sio_pgsigio);
925		PGRP_UNLOCK(pg);
926	} else {
927		struct proc *p = (sigio)->sio_proc;
928		PROC_LOCK(p);
929		SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
930			     sigio, sio_pgsigio);
931		PROC_UNLOCK(p);
932	}
933	SIGIO_UNLOCK();
934	crfree(sigio->sio_ucred);
935	free(sigio, M_SIGIO);
936}
937
938/*
939 * Free a list of sigio structures.
940 * We only need to lock the SIGIO_LOCK because we have made ourselves
941 * inaccessible to callers of fsetown and therefore do not need to lock
942 * the proc or pgrp struct for the list manipulation.
943 */
944void
945funsetownlst(struct sigiolst *sigiolst)
946{
947	struct proc *p;
948	struct pgrp *pg;
949	struct sigio *sigio;
950
951	sigio = SLIST_FIRST(sigiolst);
952	if (sigio == NULL)
953		return;
954	p = NULL;
955	pg = NULL;
956
957	/*
958	 * Every entry of the list should belong
959	 * to a single proc or pgrp.
960	 */
961	if (sigio->sio_pgid < 0) {
962		pg = sigio->sio_pgrp;
963		PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
964	} else /* if (sigio->sio_pgid > 0) */ {
965		p = sigio->sio_proc;
966		PROC_LOCK_ASSERT(p, MA_NOTOWNED);
967	}
968
969	SIGIO_LOCK();
970	while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
971		*(sigio->sio_myref) = NULL;
972		if (pg != NULL) {
973			KASSERT(sigio->sio_pgid < 0,
974			    ("Proc sigio in pgrp sigio list"));
975			KASSERT(sigio->sio_pgrp == pg,
976			    ("Bogus pgrp in sigio list"));
977			PGRP_LOCK(pg);
978			SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
979			    sio_pgsigio);
980			PGRP_UNLOCK(pg);
981		} else /* if (p != NULL) */ {
982			KASSERT(sigio->sio_pgid > 0,
983			    ("Pgrp sigio in proc sigio list"));
984			KASSERT(sigio->sio_proc == p,
985			    ("Bogus proc in sigio list"));
986			PROC_LOCK(p);
987			SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
988			    sio_pgsigio);
989			PROC_UNLOCK(p);
990		}
991		SIGIO_UNLOCK();
992		crfree(sigio->sio_ucred);
993		free(sigio, M_SIGIO);
994		SIGIO_LOCK();
995	}
996	SIGIO_UNLOCK();
997}
998
999/*
1000 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1001 *
1002 * After permission checking, add a sigio structure to the sigio list for
1003 * the process or process group.
1004 */
1005int
1006fsetown(pid_t pgid, struct sigio **sigiop)
1007{
1008	struct proc *proc;
1009	struct pgrp *pgrp;
1010	struct sigio *sigio;
1011	int ret;
1012
1013	if (pgid == 0) {
1014		funsetown(sigiop);
1015		return (0);
1016	}
1017
1018	ret = 0;
1019
1020	/* Allocate and fill in the new sigio out of locks. */
1021	sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1022	sigio->sio_pgid = pgid;
1023	sigio->sio_ucred = crhold(curthread->td_ucred);
1024	sigio->sio_myref = sigiop;
1025
1026	sx_slock(&proctree_lock);
1027	if (pgid > 0) {
1028		proc = pfind(pgid);
1029		if (proc == NULL) {
1030			ret = ESRCH;
1031			goto fail;
1032		}
1033
1034		/*
1035		 * Policy - Don't allow a process to FSETOWN a process
1036		 * in another session.
1037		 *
1038		 * Remove this test to allow maximum flexibility or
1039		 * restrict FSETOWN to the current process or process
1040		 * group for maximum safety.
1041		 */
1042		PROC_UNLOCK(proc);
1043		if (proc->p_session != curthread->td_proc->p_session) {
1044			ret = EPERM;
1045			goto fail;
1046		}
1047
1048		pgrp = NULL;
1049	} else /* if (pgid < 0) */ {
1050		pgrp = pgfind(-pgid);
1051		if (pgrp == NULL) {
1052			ret = ESRCH;
1053			goto fail;
1054		}
1055		PGRP_UNLOCK(pgrp);
1056
1057		/*
1058		 * Policy - Don't allow a process to FSETOWN a process
1059		 * in another session.
1060		 *
1061		 * Remove this test to allow maximum flexibility or
1062		 * restrict FSETOWN to the current process or process
1063		 * group for maximum safety.
1064		 */
1065		if (pgrp->pg_session != curthread->td_proc->p_session) {
1066			ret = EPERM;
1067			goto fail;
1068		}
1069
1070		proc = NULL;
1071	}
1072	funsetown(sigiop);
1073	if (pgid > 0) {
1074		PROC_LOCK(proc);
1075		/*
1076		 * Since funsetownlst() is called without the proctree
1077		 * locked, we need to check for P_WEXIT.
1078		 * XXX: is ESRCH correct?
1079		 */
1080		if ((proc->p_flag & P_WEXIT) != 0) {
1081			PROC_UNLOCK(proc);
1082			ret = ESRCH;
1083			goto fail;
1084		}
1085		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1086		sigio->sio_proc = proc;
1087		PROC_UNLOCK(proc);
1088	} else {
1089		PGRP_LOCK(pgrp);
1090		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1091		sigio->sio_pgrp = pgrp;
1092		PGRP_UNLOCK(pgrp);
1093	}
1094	sx_sunlock(&proctree_lock);
1095	SIGIO_LOCK();
1096	*sigiop = sigio;
1097	SIGIO_UNLOCK();
1098	return (0);
1099
1100fail:
1101	sx_sunlock(&proctree_lock);
1102	crfree(sigio->sio_ucred);
1103	free(sigio, M_SIGIO);
1104	return (ret);
1105}
1106
1107/*
1108 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1109 */
1110pid_t
1111fgetown(sigiop)
1112	struct sigio **sigiop;
1113{
1114	pid_t pgid;
1115
1116	SIGIO_LOCK();
1117	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1118	SIGIO_UNLOCK();
1119	return (pgid);
1120}
1121
1122/*
1123 * Function drops the filedesc lock on return.
1124 */
1125static int
1126closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1127    int holdleaders)
1128{
1129	int error;
1130
1131	FILEDESC_XLOCK_ASSERT(fdp);
1132
1133	if (holdleaders) {
1134		if (td->td_proc->p_fdtol != NULL) {
1135			/*
1136			 * Ask fdfree() to sleep to ensure that all relevant
1137			 * process leaders can be traversed in closef().
1138			 */
1139			fdp->fd_holdleaderscount++;
1140		} else {
1141			holdleaders = 0;
1142		}
1143	}
1144
1145	/*
1146	 * We now hold the fp reference that used to be owned by the
1147	 * descriptor array.  We have to unlock the FILEDESC *AFTER*
1148	 * knote_fdclose to prevent a race of the fd getting opened, a knote
1149	 * added, and deleteing a knote for the new fd.
1150	 */
1151	knote_fdclose(td, fd);
1152
1153	/*
1154	 * We need to notify mqueue if the object is of type mqueue.
1155	 */
1156	if (fp->f_type == DTYPE_MQUEUE)
1157		mq_fdclose(td, fd, fp);
1158	FILEDESC_XUNLOCK(fdp);
1159
1160	error = closef(fp, td);
1161	if (holdleaders) {
1162		FILEDESC_XLOCK(fdp);
1163		fdp->fd_holdleaderscount--;
1164		if (fdp->fd_holdleaderscount == 0 &&
1165		    fdp->fd_holdleaderswakeup != 0) {
1166			fdp->fd_holdleaderswakeup = 0;
1167			wakeup(&fdp->fd_holdleaderscount);
1168		}
1169		FILEDESC_XUNLOCK(fdp);
1170	}
1171	return (error);
1172}
1173
1174/*
1175 * Close a file descriptor.
1176 */
1177#ifndef _SYS_SYSPROTO_H_
1178struct close_args {
1179	int     fd;
1180};
1181#endif
1182/* ARGSUSED */
1183int
1184sys_close(td, uap)
1185	struct thread *td;
1186	struct close_args *uap;
1187{
1188
1189	return (kern_close(td, uap->fd));
1190}
1191
1192int
1193kern_close(td, fd)
1194	struct thread *td;
1195	int fd;
1196{
1197	struct filedesc *fdp;
1198	struct file *fp;
1199
1200	fdp = td->td_proc->p_fd;
1201
1202	AUDIT_SYSCLOSE(td, fd);
1203
1204	FILEDESC_XLOCK(fdp);
1205	if ((fp = fget_locked(fdp, fd)) == NULL) {
1206		FILEDESC_XUNLOCK(fdp);
1207		return (EBADF);
1208	}
1209	fdfree(fdp, fd);
1210
1211	/* closefp() drops the FILEDESC lock for us. */
1212	return (closefp(fdp, fd, fp, td, 1));
1213}
1214
1215/*
1216 * Close open file descriptors.
1217 */
1218#ifndef _SYS_SYSPROTO_H_
1219struct closefrom_args {
1220	int	lowfd;
1221};
1222#endif
1223/* ARGSUSED */
1224int
1225sys_closefrom(struct thread *td, struct closefrom_args *uap)
1226{
1227	struct filedesc *fdp;
1228	int fd;
1229
1230	fdp = td->td_proc->p_fd;
1231	AUDIT_ARG_FD(uap->lowfd);
1232
1233	/*
1234	 * Treat negative starting file descriptor values identical to
1235	 * closefrom(0) which closes all files.
1236	 */
1237	if (uap->lowfd < 0)
1238		uap->lowfd = 0;
1239	FILEDESC_SLOCK(fdp);
1240	for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1241		if (fdp->fd_ofiles[fd].fde_file != NULL) {
1242			FILEDESC_SUNLOCK(fdp);
1243			(void)kern_close(td, fd);
1244			FILEDESC_SLOCK(fdp);
1245		}
1246	}
1247	FILEDESC_SUNLOCK(fdp);
1248	return (0);
1249}
1250
1251#if defined(COMPAT_43)
1252/*
1253 * Return status information about a file descriptor.
1254 */
1255#ifndef _SYS_SYSPROTO_H_
1256struct ofstat_args {
1257	int	fd;
1258	struct	ostat *sb;
1259};
1260#endif
1261/* ARGSUSED */
1262int
1263ofstat(struct thread *td, struct ofstat_args *uap)
1264{
1265	struct ostat oub;
1266	struct stat ub;
1267	int error;
1268
1269	error = kern_fstat(td, uap->fd, &ub);
1270	if (error == 0) {
1271		cvtstat(&ub, &oub);
1272		error = copyout(&oub, uap->sb, sizeof(oub));
1273	}
1274	return (error);
1275}
1276#endif /* COMPAT_43 */
1277
1278/*
1279 * Return status information about a file descriptor.
1280 */
1281#ifndef _SYS_SYSPROTO_H_
1282struct fstat_args {
1283	int	fd;
1284	struct	stat *sb;
1285};
1286#endif
1287/* ARGSUSED */
1288int
1289sys_fstat(struct thread *td, struct fstat_args *uap)
1290{
1291	struct stat ub;
1292	int error;
1293
1294	error = kern_fstat(td, uap->fd, &ub);
1295	if (error == 0)
1296		error = copyout(&ub, uap->sb, sizeof(ub));
1297	return (error);
1298}
1299
1300int
1301kern_fstat(struct thread *td, int fd, struct stat *sbp)
1302{
1303	struct file *fp;
1304	cap_rights_t rights;
1305	int error;
1306
1307	AUDIT_ARG_FD(fd);
1308
1309	error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1310	if (error != 0)
1311		return (error);
1312
1313	AUDIT_ARG_FILE(td->td_proc, fp);
1314
1315	error = fo_stat(fp, sbp, td->td_ucred, td);
1316	fdrop(fp, td);
1317#ifdef KTRACE
1318	if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1319		ktrstat(sbp);
1320#endif
1321	return (error);
1322}
1323
1324/*
1325 * Return status information about a file descriptor.
1326 */
1327#ifndef _SYS_SYSPROTO_H_
1328struct nfstat_args {
1329	int	fd;
1330	struct	nstat *sb;
1331};
1332#endif
1333/* ARGSUSED */
1334int
1335sys_nfstat(struct thread *td, struct nfstat_args *uap)
1336{
1337	struct nstat nub;
1338	struct stat ub;
1339	int error;
1340
1341	error = kern_fstat(td, uap->fd, &ub);
1342	if (error == 0) {
1343		cvtnstat(&ub, &nub);
1344		error = copyout(&nub, uap->sb, sizeof(nub));
1345	}
1346	return (error);
1347}
1348
1349/*
1350 * Return pathconf information about a file descriptor.
1351 */
1352#ifndef _SYS_SYSPROTO_H_
1353struct fpathconf_args {
1354	int	fd;
1355	int	name;
1356};
1357#endif
1358/* ARGSUSED */
1359int
1360sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1361{
1362	struct file *fp;
1363	struct vnode *vp;
1364	cap_rights_t rights;
1365	int error;
1366
1367	error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1368	if (error != 0)
1369		return (error);
1370
1371	/* If asynchronous I/O is available, it works for all descriptors. */
1372	if (uap->name == _PC_ASYNC_IO) {
1373		td->td_retval[0] = async_io_version;
1374		goto out;
1375	}
1376	vp = fp->f_vnode;
1377	if (vp != NULL) {
1378		vn_lock(vp, LK_SHARED | LK_RETRY);
1379		error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1380		VOP_UNLOCK(vp, 0);
1381	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1382		if (uap->name != _PC_PIPE_BUF) {
1383			error = EINVAL;
1384		} else {
1385			td->td_retval[0] = PIPE_BUF;
1386			error = 0;
1387		}
1388	} else {
1389		error = EOPNOTSUPP;
1390	}
1391out:
1392	fdrop(fp, td);
1393	return (error);
1394}
1395
1396/*
1397 * Initialize filecaps structure.
1398 */
1399void
1400filecaps_init(struct filecaps *fcaps)
1401{
1402
1403	bzero(fcaps, sizeof(*fcaps));
1404	fcaps->fc_nioctls = -1;
1405}
1406
1407/*
1408 * Copy filecaps structure allocating memory for ioctls array if needed.
1409 */
1410void
1411filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1412{
1413	size_t size;
1414
1415	*dst = *src;
1416	if (src->fc_ioctls != NULL) {
1417		KASSERT(src->fc_nioctls > 0,
1418		    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1419
1420		size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1421		dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1422		bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1423	}
1424}
1425
1426/*
1427 * Move filecaps structure to the new place and clear the old place.
1428 */
1429void
1430filecaps_move(struct filecaps *src, struct filecaps *dst)
1431{
1432
1433	*dst = *src;
1434	bzero(src, sizeof(*src));
1435}
1436
1437/*
1438 * Fill the given filecaps structure with full rights.
1439 */
1440static void
1441filecaps_fill(struct filecaps *fcaps)
1442{
1443
1444	CAP_ALL(&fcaps->fc_rights);
1445	fcaps->fc_ioctls = NULL;
1446	fcaps->fc_nioctls = -1;
1447	fcaps->fc_fcntls = CAP_FCNTL_ALL;
1448}
1449
1450/*
1451 * Free memory allocated within filecaps structure.
1452 */
1453void
1454filecaps_free(struct filecaps *fcaps)
1455{
1456
1457	free(fcaps->fc_ioctls, M_FILECAPS);
1458	bzero(fcaps, sizeof(*fcaps));
1459}
1460
1461/*
1462 * Validate the given filecaps structure.
1463 */
1464static void
1465filecaps_validate(const struct filecaps *fcaps, const char *func)
1466{
1467
1468	KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1469	    ("%s: invalid rights", func));
1470	KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1471	    ("%s: invalid fcntls", func));
1472	KASSERT(fcaps->fc_fcntls == 0 ||
1473	    cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1474	    ("%s: fcntls without CAP_FCNTL", func));
1475	KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1476	    (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1477	    ("%s: invalid ioctls", func));
1478	KASSERT(fcaps->fc_nioctls == 0 ||
1479	    cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1480	    ("%s: ioctls without CAP_IOCTL", func));
1481}
1482
1483static void
1484fdgrowtable_exp(struct filedesc *fdp, int nfd)
1485{
1486	int nfd1;
1487
1488	FILEDESC_XLOCK_ASSERT(fdp);
1489
1490	nfd1 = fdp->fd_nfiles * 2;
1491	if (nfd1 < nfd)
1492		nfd1 = nfd;
1493	fdgrowtable(fdp, nfd1);
1494}
1495
1496/*
1497 * Grow the file table to accomodate (at least) nfd descriptors.
1498 */
1499static void
1500fdgrowtable(struct filedesc *fdp, int nfd)
1501{
1502	struct filedesc0 *fdp0;
1503	struct freetable *ft;
1504	struct filedescent *ntable;
1505	struct filedescent *otable;
1506	int nnfiles, onfiles;
1507	NDSLOTTYPE *nmap, *omap;
1508
1509	FILEDESC_XLOCK_ASSERT(fdp);
1510
1511	KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1512
1513	/* save old values */
1514	onfiles = fdp->fd_nfiles;
1515	otable = fdp->fd_ofiles;
1516	omap = fdp->fd_map;
1517
1518	/* compute the size of the new table */
1519	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1520	if (nnfiles <= onfiles)
1521		/* the table is already large enough */
1522		return;
1523
1524	/*
1525	 * Allocate a new table and map.  We need enough space for the
1526	 * file entries themselves and the struct freetable we will use
1527	 * when we decommission the table and place it on the freelist.
1528	 * We place the struct freetable in the middle so we don't have
1529	 * to worry about padding.
1530	 */
1531	ntable = malloc(nnfiles * sizeof(ntable[0]) + sizeof(struct freetable),
1532	    M_FILEDESC, M_ZERO | M_WAITOK);
1533	nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1534	    M_ZERO | M_WAITOK);
1535
1536	/* copy the old data over and point at the new tables */
1537	memcpy(ntable, otable, onfiles * sizeof(*otable));
1538	memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1539
1540	/* update the pointers and counters */
1541	memcpy(ntable, otable, onfiles * sizeof(ntable[0]));
1542	fdp->fd_ofiles = ntable;
1543	fdp->fd_map = nmap;
1544
1545	/*
1546	 * In order to have a valid pattern for fget_unlocked()
1547	 * fdp->fd_nfiles must be the last member to be updated, otherwise
1548	 * fget_unlocked() consumers may reference a new, higher value for
1549	 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1550	 * resulting in OOB accesses.
1551	 */
1552	atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1553
1554	/*
1555	 * Do not free the old file table, as some threads may still
1556	 * reference entries within it.  Instead, place it on a freelist
1557	 * which will be processed when the struct filedesc is released.
1558	 *
1559	 * Do, however, free the old map.
1560	 *
1561	 * Note that if onfiles == NDFILE, we're dealing with the original
1562	 * static allocation contained within (struct filedesc0 *)fdp,
1563	 * which must not be freed.
1564	 */
1565	if (onfiles > NDFILE) {
1566		ft = (struct freetable *)&otable[onfiles];
1567		fdp0 = (struct filedesc0 *)fdp;
1568		ft->ft_table = otable;
1569		SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1570		free(omap, M_FILEDESC);
1571	}
1572}
1573
1574/*
1575 * Allocate a file descriptor for the process.
1576 */
1577int
1578fdalloc(struct thread *td, int minfd, int *result)
1579{
1580	struct proc *p = td->td_proc;
1581	struct filedesc *fdp = p->p_fd;
1582	int fd = -1, maxfd, allocfd;
1583#ifdef RACCT
1584	int error;
1585#endif
1586
1587	FILEDESC_XLOCK_ASSERT(fdp);
1588
1589	if (fdp->fd_freefile > minfd)
1590		minfd = fdp->fd_freefile;
1591
1592	maxfd = getmaxfd(p);
1593
1594	/*
1595	 * Search the bitmap for a free descriptor starting at minfd.
1596	 * If none is found, grow the file table.
1597	 */
1598	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1599	if (fd >= maxfd)
1600		return (EMFILE);
1601	if (fd >= fdp->fd_nfiles) {
1602		allocfd = min(fd * 2, maxfd);
1603#ifdef RACCT
1604		PROC_LOCK(p);
1605		error = racct_set(p, RACCT_NOFILE, allocfd);
1606		PROC_UNLOCK(p);
1607		if (error != 0)
1608			return (EMFILE);
1609#endif
1610		/*
1611		 * fd is already equal to first free descriptor >= minfd, so
1612		 * we only need to grow the table and we are done.
1613		 */
1614		fdgrowtable_exp(fdp, allocfd);
1615	}
1616
1617	/*
1618	 * Perform some sanity checks, then mark the file descriptor as
1619	 * used and return it to the caller.
1620	 */
1621	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1622	    ("invalid descriptor %d", fd));
1623	KASSERT(!fdisused(fdp, fd),
1624	    ("fd_first_free() returned non-free descriptor"));
1625	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1626	    ("file descriptor isn't free"));
1627	KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1628	fdused(fdp, fd);
1629	*result = fd;
1630	return (0);
1631}
1632
1633/*
1634 * Allocate n file descriptors for the process.
1635 */
1636int
1637fdallocn(struct thread *td, int minfd, int *fds, int n)
1638{
1639	struct proc *p = td->td_proc;
1640	struct filedesc *fdp = p->p_fd;
1641	int i;
1642
1643	FILEDESC_XLOCK_ASSERT(fdp);
1644
1645	if (!fdavail(td, n))
1646		return (EMFILE);
1647
1648	for (i = 0; i < n; i++)
1649		if (fdalloc(td, 0, &fds[i]) != 0)
1650			break;
1651
1652	if (i < n) {
1653		for (i--; i >= 0; i--)
1654			fdunused(fdp, fds[i]);
1655		return (EMFILE);
1656	}
1657
1658	return (0);
1659}
1660
1661/*
1662 * Check to see whether n user file descriptors are available to the process
1663 * p.
1664 */
1665int
1666fdavail(struct thread *td, int n)
1667{
1668	struct proc *p = td->td_proc;
1669	struct filedesc *fdp = td->td_proc->p_fd;
1670	int i, lim, last;
1671
1672	FILEDESC_LOCK_ASSERT(fdp);
1673
1674	/*
1675	 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1676	 *      call racct_add() from there instead of dealing with containers
1677	 *      here.
1678	 */
1679	lim = getmaxfd(p);
1680	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1681		return (1);
1682	last = min(fdp->fd_nfiles, lim);
1683	for (i = fdp->fd_freefile; i < last; i++) {
1684		if (fdp->fd_ofiles[i].fde_file == NULL && --n <= 0)
1685			return (1);
1686	}
1687	return (0);
1688}
1689
1690/*
1691 * Create a new open file structure and allocate a file decriptor for the
1692 * process that refers to it.  We add one reference to the file for the
1693 * descriptor table and one reference for resultfp. This is to prevent us
1694 * being preempted and the entry in the descriptor table closed after we
1695 * release the FILEDESC lock.
1696 */
1697int
1698falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1699{
1700	struct file *fp;
1701	int error, fd;
1702
1703	error = falloc_noinstall(td, &fp);
1704	if (error)
1705		return (error);		/* no reference held on error */
1706
1707	error = finstall(td, fp, &fd, flags, NULL);
1708	if (error) {
1709		fdrop(fp, td);		/* one reference (fp only) */
1710		return (error);
1711	}
1712
1713	if (resultfp != NULL)
1714		*resultfp = fp;		/* copy out result */
1715	else
1716		fdrop(fp, td);		/* release local reference */
1717
1718	if (resultfd != NULL)
1719		*resultfd = fd;
1720
1721	return (0);
1722}
1723
1724/*
1725 * Create a new open file structure without allocating a file descriptor.
1726 */
1727int
1728falloc_noinstall(struct thread *td, struct file **resultfp)
1729{
1730	struct file *fp;
1731	int maxuserfiles = maxfiles - (maxfiles / 20);
1732	static struct timeval lastfail;
1733	static int curfail;
1734
1735	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1736
1737	if ((openfiles >= maxuserfiles &&
1738	    priv_check(td, PRIV_MAXFILES) != 0) ||
1739	    openfiles >= maxfiles) {
1740		if (ppsratecheck(&lastfail, &curfail, 1)) {
1741			printf("kern.maxfiles limit exceeded by uid %i, "
1742			    "please see tuning(7).\n", td->td_ucred->cr_ruid);
1743		}
1744		return (ENFILE);
1745	}
1746	atomic_add_int(&openfiles, 1);
1747	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1748	refcount_init(&fp->f_count, 1);
1749	fp->f_cred = crhold(td->td_ucred);
1750	fp->f_ops = &badfileops;
1751	fp->f_data = NULL;
1752	fp->f_vnode = NULL;
1753	*resultfp = fp;
1754	return (0);
1755}
1756
1757/*
1758 * Install a file in a file descriptor table.
1759 */
1760int
1761finstall(struct thread *td, struct file *fp, int *fd, int flags,
1762    struct filecaps *fcaps)
1763{
1764	struct filedesc *fdp = td->td_proc->p_fd;
1765	struct filedescent *fde;
1766	int error;
1767
1768	KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1769	KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1770	if (fcaps != NULL)
1771		filecaps_validate(fcaps, __func__);
1772
1773	FILEDESC_XLOCK(fdp);
1774	if ((error = fdalloc(td, 0, fd))) {
1775		FILEDESC_XUNLOCK(fdp);
1776		return (error);
1777	}
1778	fhold(fp);
1779	fde = &fdp->fd_ofiles[*fd];
1780	fde->fde_file = fp;
1781	if ((flags & O_CLOEXEC) != 0)
1782		fde->fde_flags |= UF_EXCLOSE;
1783	if (fcaps != NULL)
1784		filecaps_move(fcaps, &fde->fde_caps);
1785	else
1786		filecaps_fill(&fde->fde_caps);
1787	FILEDESC_XUNLOCK(fdp);
1788	return (0);
1789}
1790
1791/*
1792 * Build a new filedesc structure from another.
1793 * Copy the current, root, and jail root vnode references.
1794 */
1795struct filedesc *
1796fdinit(struct filedesc *fdp)
1797{
1798	struct filedesc0 *newfdp;
1799
1800	newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1801	FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1802	if (fdp != NULL) {
1803		FILEDESC_XLOCK(fdp);
1804		newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1805		if (newfdp->fd_fd.fd_cdir)
1806			VREF(newfdp->fd_fd.fd_cdir);
1807		newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1808		if (newfdp->fd_fd.fd_rdir)
1809			VREF(newfdp->fd_fd.fd_rdir);
1810		newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1811		if (newfdp->fd_fd.fd_jdir)
1812			VREF(newfdp->fd_fd.fd_jdir);
1813		FILEDESC_XUNLOCK(fdp);
1814	}
1815
1816	/* Create the file descriptor table. */
1817	newfdp->fd_fd.fd_refcnt = 1;
1818	newfdp->fd_fd.fd_holdcnt = 1;
1819	newfdp->fd_fd.fd_cmask = CMASK;
1820	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1821	newfdp->fd_fd.fd_nfiles = NDFILE;
1822	newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1823	newfdp->fd_fd.fd_lastfile = -1;
1824	return (&newfdp->fd_fd);
1825}
1826
1827static struct filedesc *
1828fdhold(struct proc *p)
1829{
1830	struct filedesc *fdp;
1831
1832	mtx_lock(&fdesc_mtx);
1833	fdp = p->p_fd;
1834	if (fdp != NULL)
1835		fdp->fd_holdcnt++;
1836	mtx_unlock(&fdesc_mtx);
1837	return (fdp);
1838}
1839
1840static void
1841fddrop(struct filedesc *fdp)
1842{
1843	struct filedesc0 *fdp0;
1844	struct freetable *ft;
1845	int i;
1846
1847	mtx_lock(&fdesc_mtx);
1848	i = --fdp->fd_holdcnt;
1849	mtx_unlock(&fdesc_mtx);
1850	if (i > 0)
1851		return;
1852
1853	FILEDESC_LOCK_DESTROY(fdp);
1854	fdp0 = (struct filedesc0 *)fdp;
1855	while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1856		SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1857		free(ft->ft_table, M_FILEDESC);
1858	}
1859	free(fdp, M_FILEDESC);
1860}
1861
1862/*
1863 * Share a filedesc structure.
1864 */
1865struct filedesc *
1866fdshare(struct filedesc *fdp)
1867{
1868
1869	FILEDESC_XLOCK(fdp);
1870	fdp->fd_refcnt++;
1871	FILEDESC_XUNLOCK(fdp);
1872	return (fdp);
1873}
1874
1875/*
1876 * Unshare a filedesc structure, if necessary by making a copy
1877 */
1878void
1879fdunshare(struct proc *p, struct thread *td)
1880{
1881
1882	FILEDESC_XLOCK(p->p_fd);
1883	if (p->p_fd->fd_refcnt > 1) {
1884		struct filedesc *tmp;
1885
1886		FILEDESC_XUNLOCK(p->p_fd);
1887		tmp = fdcopy(p->p_fd);
1888		fdescfree(td);
1889		p->p_fd = tmp;
1890	} else
1891		FILEDESC_XUNLOCK(p->p_fd);
1892}
1893
1894/*
1895 * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
1896 * this is to ease callers, not catch errors.
1897 */
1898struct filedesc *
1899fdcopy(struct filedesc *fdp)
1900{
1901	struct filedesc *newfdp;
1902	struct filedescent *nfde, *ofde;
1903	int i;
1904
1905	/* Certain daemons might not have file descriptors. */
1906	if (fdp == NULL)
1907		return (NULL);
1908
1909	newfdp = fdinit(fdp);
1910	FILEDESC_SLOCK(fdp);
1911	while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1912		FILEDESC_SUNLOCK(fdp);
1913		FILEDESC_XLOCK(newfdp);
1914		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1915		FILEDESC_XUNLOCK(newfdp);
1916		FILEDESC_SLOCK(fdp);
1917	}
1918	/* copy all passable descriptors (i.e. not kqueue) */
1919	newfdp->fd_freefile = -1;
1920	for (i = 0; i <= fdp->fd_lastfile; ++i) {
1921		ofde = &fdp->fd_ofiles[i];
1922		if (fdisused(fdp, i) &&
1923		    (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1924		    ofde->fde_file->f_ops != &badfileops) {
1925			nfde = &newfdp->fd_ofiles[i];
1926			*nfde = *ofde;
1927			filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1928			fhold(nfde->fde_file);
1929			newfdp->fd_lastfile = i;
1930		} else {
1931			if (newfdp->fd_freefile == -1)
1932				newfdp->fd_freefile = i;
1933		}
1934	}
1935	newfdp->fd_cmask = fdp->fd_cmask;
1936	FILEDESC_SUNLOCK(fdp);
1937	FILEDESC_XLOCK(newfdp);
1938	for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1939		if (newfdp->fd_ofiles[i].fde_file != NULL)
1940			fdused(newfdp, i);
1941	}
1942	if (newfdp->fd_freefile == -1)
1943		newfdp->fd_freefile = i;
1944	FILEDESC_XUNLOCK(newfdp);
1945	return (newfdp);
1946}
1947
1948/*
1949 * Release a filedesc structure.
1950 */
1951void
1952fdescfree(struct thread *td)
1953{
1954	struct filedesc *fdp;
1955	int i;
1956	struct filedesc_to_leader *fdtol;
1957	struct file *fp;
1958	struct vnode *cdir, *jdir, *rdir, *vp;
1959	struct flock lf;
1960
1961	/* Certain daemons might not have file descriptors. */
1962	fdp = td->td_proc->p_fd;
1963	if (fdp == NULL)
1964		return;
1965
1966#ifdef RACCT
1967	PROC_LOCK(td->td_proc);
1968	racct_set(td->td_proc, RACCT_NOFILE, 0);
1969	PROC_UNLOCK(td->td_proc);
1970#endif
1971
1972	/* Check for special need to clear POSIX style locks */
1973	fdtol = td->td_proc->p_fdtol;
1974	if (fdtol != NULL) {
1975		FILEDESC_XLOCK(fdp);
1976		KASSERT(fdtol->fdl_refcount > 0,
1977		    ("filedesc_to_refcount botch: fdl_refcount=%d",
1978		    fdtol->fdl_refcount));
1979		if (fdtol->fdl_refcount == 1 &&
1980		    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1981			for (i = 0; i <= fdp->fd_lastfile; i++) {
1982				fp = fdp->fd_ofiles[i].fde_file;
1983				if (fp == NULL || fp->f_type != DTYPE_VNODE)
1984					continue;
1985				fhold(fp);
1986				FILEDESC_XUNLOCK(fdp);
1987				lf.l_whence = SEEK_SET;
1988				lf.l_start = 0;
1989				lf.l_len = 0;
1990				lf.l_type = F_UNLCK;
1991				vp = fp->f_vnode;
1992				(void) VOP_ADVLOCK(vp,
1993				    (caddr_t)td->td_proc->p_leader, F_UNLCK,
1994				    &lf, F_POSIX);
1995				FILEDESC_XLOCK(fdp);
1996				fdrop(fp, td);
1997			}
1998		}
1999	retry:
2000		if (fdtol->fdl_refcount == 1) {
2001			if (fdp->fd_holdleaderscount > 0 &&
2002			    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2003				/*
2004				 * close() or do_dup() has cleared a reference
2005				 * in a shared file descriptor table.
2006				 */
2007				fdp->fd_holdleaderswakeup = 1;
2008				sx_sleep(&fdp->fd_holdleaderscount,
2009				    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2010				goto retry;
2011			}
2012			if (fdtol->fdl_holdcount > 0) {
2013				/*
2014				 * Ensure that fdtol->fdl_leader remains
2015				 * valid in closef().
2016				 */
2017				fdtol->fdl_wakeup = 1;
2018				sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2019				    "fdlhold", 0);
2020				goto retry;
2021			}
2022		}
2023		fdtol->fdl_refcount--;
2024		if (fdtol->fdl_refcount == 0 &&
2025		    fdtol->fdl_holdcount == 0) {
2026			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2027			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2028		} else
2029			fdtol = NULL;
2030		td->td_proc->p_fdtol = NULL;
2031		FILEDESC_XUNLOCK(fdp);
2032		if (fdtol != NULL)
2033			free(fdtol, M_FILEDESC_TO_LEADER);
2034	}
2035	FILEDESC_XLOCK(fdp);
2036	i = --fdp->fd_refcnt;
2037	FILEDESC_XUNLOCK(fdp);
2038	if (i > 0)
2039		return;
2040
2041	for (i = 0; i <= fdp->fd_lastfile; i++) {
2042		fp = fdp->fd_ofiles[i].fde_file;
2043		if (fp != NULL) {
2044			FILEDESC_XLOCK(fdp);
2045			fdfree(fdp, i);
2046			FILEDESC_XUNLOCK(fdp);
2047			(void) closef(fp, td);
2048		}
2049	}
2050	FILEDESC_XLOCK(fdp);
2051
2052	/* XXX This should happen earlier. */
2053	mtx_lock(&fdesc_mtx);
2054	td->td_proc->p_fd = NULL;
2055	mtx_unlock(&fdesc_mtx);
2056
2057	if (fdp->fd_nfiles > NDFILE)
2058		free(fdp->fd_ofiles, M_FILEDESC);
2059	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2060		free(fdp->fd_map, M_FILEDESC);
2061
2062	fdp->fd_nfiles = 0;
2063
2064	cdir = fdp->fd_cdir;
2065	fdp->fd_cdir = NULL;
2066	rdir = fdp->fd_rdir;
2067	fdp->fd_rdir = NULL;
2068	jdir = fdp->fd_jdir;
2069	fdp->fd_jdir = NULL;
2070	FILEDESC_XUNLOCK(fdp);
2071
2072	if (cdir != NULL)
2073		vrele(cdir);
2074	if (rdir != NULL)
2075		vrele(rdir);
2076	if (jdir != NULL)
2077		vrele(jdir);
2078
2079	fddrop(fdp);
2080}
2081
2082/*
2083 * For setugid programs, we don't want to people to use that setugidness
2084 * to generate error messages which write to a file which otherwise would
2085 * otherwise be off-limits to the process.  We check for filesystems where
2086 * the vnode can change out from under us after execve (like [lin]procfs).
2087 *
2088 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2089 * sufficient.  We also don't check for setugidness since we know we are.
2090 */
2091static int
2092is_unsafe(struct file *fp)
2093{
2094	if (fp->f_type == DTYPE_VNODE) {
2095		struct vnode *vp = fp->f_vnode;
2096
2097		if ((vp->v_vflag & VV_PROCDEP) != 0)
2098			return (1);
2099	}
2100	return (0);
2101}
2102
2103/*
2104 * Make this setguid thing safe, if at all possible.
2105 */
2106void
2107setugidsafety(struct thread *td)
2108{
2109	struct filedesc *fdp;
2110	struct file *fp;
2111	int i;
2112
2113	/* Certain daemons might not have file descriptors. */
2114	fdp = td->td_proc->p_fd;
2115	if (fdp == NULL)
2116		return;
2117
2118	/*
2119	 * Note: fdp->fd_ofiles may be reallocated out from under us while
2120	 * we are blocked in a close.  Be careful!
2121	 */
2122	FILEDESC_XLOCK(fdp);
2123	for (i = 0; i <= fdp->fd_lastfile; i++) {
2124		if (i > 2)
2125			break;
2126		fp = fdp->fd_ofiles[i].fde_file;
2127		if (fp != NULL && is_unsafe(fp)) {
2128			knote_fdclose(td, i);
2129			/*
2130			 * NULL-out descriptor prior to close to avoid
2131			 * a race while close blocks.
2132			 */
2133			fdfree(fdp, i);
2134			FILEDESC_XUNLOCK(fdp);
2135			(void) closef(fp, td);
2136			FILEDESC_XLOCK(fdp);
2137		}
2138	}
2139	FILEDESC_XUNLOCK(fdp);
2140}
2141
2142/*
2143 * If a specific file object occupies a specific file descriptor, close the
2144 * file descriptor entry and drop a reference on the file object.  This is a
2145 * convenience function to handle a subsequent error in a function that calls
2146 * falloc() that handles the race that another thread might have closed the
2147 * file descriptor out from under the thread creating the file object.
2148 */
2149void
2150fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2151{
2152
2153	FILEDESC_XLOCK(fdp);
2154	if (fdp->fd_ofiles[idx].fde_file == fp) {
2155		fdfree(fdp, idx);
2156		FILEDESC_XUNLOCK(fdp);
2157		fdrop(fp, td);
2158	} else
2159		FILEDESC_XUNLOCK(fdp);
2160}
2161
2162/*
2163 * Close any files on exec?
2164 */
2165void
2166fdcloseexec(struct thread *td)
2167{
2168	struct filedesc *fdp;
2169	struct filedescent *fde;
2170	struct file *fp;
2171	int i;
2172
2173	/* Certain daemons might not have file descriptors. */
2174	fdp = td->td_proc->p_fd;
2175	if (fdp == NULL)
2176		return;
2177
2178	/*
2179	 * We cannot cache fd_ofiles since operations
2180	 * may block and rip them out from under us.
2181	 */
2182	FILEDESC_XLOCK(fdp);
2183	for (i = 0; i <= fdp->fd_lastfile; i++) {
2184		fde = &fdp->fd_ofiles[i];
2185		fp = fde->fde_file;
2186		if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2187		    (fde->fde_flags & UF_EXCLOSE))) {
2188			fdfree(fdp, i);
2189			(void) closefp(fdp, i, fp, td, 0);
2190			/* closefp() drops the FILEDESC lock. */
2191			FILEDESC_XLOCK(fdp);
2192		}
2193	}
2194	FILEDESC_XUNLOCK(fdp);
2195}
2196
2197/*
2198 * It is unsafe for set[ug]id processes to be started with file
2199 * descriptors 0..2 closed, as these descriptors are given implicit
2200 * significance in the Standard C library.  fdcheckstd() will create a
2201 * descriptor referencing /dev/null for each of stdin, stdout, and
2202 * stderr that is not already open.
2203 */
2204int
2205fdcheckstd(struct thread *td)
2206{
2207	struct filedesc *fdp;
2208	register_t retval, save;
2209	int i, error, devnull;
2210
2211	fdp = td->td_proc->p_fd;
2212	if (fdp == NULL)
2213		return (0);
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_nfiles; ++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,
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, &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_nfiles; 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, CTLFLAG_RD,
3229    sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3230#endif	/* COMPAT_FREEBSD7 */
3231
3232#ifdef KINFO_FILE_SIZE
3233CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3234#endif
3235
3236struct export_fd_buf {
3237	struct filedesc		*fdp;
3238	struct sbuf 		*sb;
3239	ssize_t			remainder;
3240	struct kinfo_file	kif;
3241};
3242
3243static int
3244export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3245    int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3246{
3247	struct {
3248		int	fflag;
3249		int	kf_fflag;
3250	} fflags_table[] = {
3251		{ FAPPEND, KF_FLAG_APPEND },
3252		{ FASYNC, KF_FLAG_ASYNC },
3253		{ FFSYNC, KF_FLAG_FSYNC },
3254		{ FHASLOCK, KF_FLAG_HASLOCK },
3255		{ FNONBLOCK, KF_FLAG_NONBLOCK },
3256		{ FREAD, KF_FLAG_READ },
3257		{ FWRITE, KF_FLAG_WRITE },
3258		{ O_CREAT, KF_FLAG_CREAT },
3259		{ O_DIRECT, KF_FLAG_DIRECT },
3260		{ O_EXCL, KF_FLAG_EXCL },
3261		{ O_EXEC, KF_FLAG_EXEC },
3262		{ O_EXLOCK, KF_FLAG_EXLOCK },
3263		{ O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3264		{ O_SHLOCK, KF_FLAG_SHLOCK },
3265		{ O_TRUNC, KF_FLAG_TRUNC }
3266	};
3267#define	NFFLAGS	(sizeof(fflags_table) / sizeof(*fflags_table))
3268	struct kinfo_file *kif;
3269	struct vnode *vp;
3270	int error, locked;
3271	unsigned int i;
3272
3273	if (efbuf->remainder == 0)
3274		return (0);
3275	kif = &efbuf->kif;
3276	bzero(kif, sizeof(*kif));
3277	locked = efbuf->fdp != NULL;
3278	switch (type) {
3279	case KF_TYPE_FIFO:
3280	case KF_TYPE_VNODE:
3281		if (locked) {
3282			FILEDESC_SUNLOCK(efbuf->fdp);
3283			locked = 0;
3284		}
3285		vp = (struct vnode *)data;
3286		error = fill_vnode_info(vp, kif);
3287		vrele(vp);
3288		break;
3289	case KF_TYPE_SOCKET:
3290		error = fill_socket_info((struct socket *)data, kif);
3291		break;
3292	case KF_TYPE_PIPE:
3293		error = fill_pipe_info((struct pipe *)data, kif);
3294		break;
3295	case KF_TYPE_PTS:
3296		error = fill_pts_info((struct tty *)data, kif);
3297		break;
3298	case KF_TYPE_PROCDESC:
3299		error = fill_procdesc_info((struct procdesc *)data, kif);
3300		break;
3301	case KF_TYPE_SEM:
3302		error = fill_sem_info((struct file *)data, kif);
3303		break;
3304	case KF_TYPE_SHM:
3305		error = fill_shm_info((struct file *)data, kif);
3306		break;
3307	default:
3308		error = 0;
3309	}
3310	if (error == 0)
3311		kif->kf_status |= KF_ATTR_VALID;
3312
3313	/*
3314	 * Translate file access flags.
3315	 */
3316	for (i = 0; i < NFFLAGS; i++)
3317		if (fflags & fflags_table[i].fflag)
3318			kif->kf_flags |=  fflags_table[i].kf_fflag;
3319	if (rightsp != NULL)
3320		kif->kf_cap_rights = *rightsp;
3321	else
3322		cap_rights_init(&kif->kf_cap_rights);
3323	kif->kf_fd = fd;
3324	kif->kf_type = type;
3325	kif->kf_ref_count = refcnt;
3326	kif->kf_offset = offset;
3327	/* Pack record size down */
3328	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3329	    strlen(kif->kf_path) + 1;
3330	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3331	if (efbuf->remainder != -1) {
3332		if (efbuf->remainder < kif->kf_structsize) {
3333			/* Terminate export. */
3334			efbuf->remainder = 0;
3335			if (efbuf->fdp != NULL && !locked)
3336				FILEDESC_SLOCK(efbuf->fdp);
3337			return (0);
3338		}
3339		efbuf->remainder -= kif->kf_structsize;
3340	}
3341	if (locked)
3342		FILEDESC_SUNLOCK(efbuf->fdp);
3343	error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3344	if (efbuf->fdp != NULL)
3345		FILEDESC_SLOCK(efbuf->fdp);
3346	return (error);
3347}
3348
3349/*
3350 * Store a process file descriptor information to sbuf.
3351 *
3352 * Takes a locked proc as argument, and returns with the proc unlocked.
3353 */
3354int
3355kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
3356{
3357	struct file *fp;
3358	struct filedesc *fdp;
3359	struct export_fd_buf *efbuf;
3360	struct vnode *cttyvp, *textvp, *tracevp;
3361	int64_t offset;
3362	void *data;
3363	int error, i;
3364	int type, refcnt, fflags;
3365	cap_rights_t rights;
3366
3367	PROC_LOCK_ASSERT(p, MA_OWNED);
3368
3369	/* ktrace vnode */
3370	tracevp = p->p_tracevp;
3371	if (tracevp != NULL)
3372		vref(tracevp);
3373	/* text vnode */
3374	textvp = p->p_textvp;
3375	if (textvp != NULL)
3376		vref(textvp);
3377	/* Controlling tty. */
3378	cttyvp = NULL;
3379	if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3380		cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3381		if (cttyvp != NULL)
3382			vref(cttyvp);
3383	}
3384	fdp = fdhold(p);
3385	PROC_UNLOCK(p);
3386	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3387	efbuf->fdp = NULL;
3388	efbuf->sb = sb;
3389	efbuf->remainder = maxlen;
3390	if (tracevp != NULL)
3391		export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3392		    FREAD | FWRITE, -1, -1, NULL, efbuf);
3393	if (textvp != NULL)
3394		export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3395		    FREAD, -1, -1, NULL, efbuf);
3396	if (cttyvp != NULL)
3397		export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3398		    FREAD | FWRITE, -1, -1, NULL, efbuf);
3399	error = 0;
3400	if (fdp == NULL)
3401		goto fail;
3402	efbuf->fdp = fdp;
3403	FILEDESC_SLOCK(fdp);
3404	/* working directory */
3405	if (fdp->fd_cdir != NULL) {
3406		vref(fdp->fd_cdir);
3407		data = fdp->fd_cdir;
3408		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3409		    FREAD, -1, -1, NULL, efbuf);
3410	}
3411	/* root directory */
3412	if (fdp->fd_rdir != NULL) {
3413		vref(fdp->fd_rdir);
3414		data = fdp->fd_rdir;
3415		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3416		    FREAD, -1, -1, NULL, efbuf);
3417	}
3418	/* jail directory */
3419	if (fdp->fd_jdir != NULL) {
3420		vref(fdp->fd_jdir);
3421		data = fdp->fd_jdir;
3422		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3423		    FREAD, -1, -1, NULL, efbuf);
3424	}
3425	for (i = 0; fdp->fd_refcnt > 0 && i < fdp->fd_nfiles; i++) {
3426		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3427			continue;
3428		data = NULL;
3429#ifdef CAPABILITIES
3430		rights = *cap_rights(fdp, i);
3431#else /* !CAPABILITIES */
3432		cap_rights_init(&rights);
3433#endif
3434		switch (fp->f_type) {
3435		case DTYPE_VNODE:
3436			type = KF_TYPE_VNODE;
3437			vref(fp->f_vnode);
3438			data = fp->f_vnode;
3439			break;
3440
3441		case DTYPE_SOCKET:
3442			type = KF_TYPE_SOCKET;
3443			data = fp->f_data;
3444			break;
3445
3446		case DTYPE_PIPE:
3447			type = KF_TYPE_PIPE;
3448			data = fp->f_data;
3449			break;
3450
3451		case DTYPE_FIFO:
3452			type = KF_TYPE_FIFO;
3453			vref(fp->f_vnode);
3454			data = fp->f_vnode;
3455			break;
3456
3457		case DTYPE_KQUEUE:
3458			type = KF_TYPE_KQUEUE;
3459			break;
3460
3461		case DTYPE_CRYPTO:
3462			type = KF_TYPE_CRYPTO;
3463			break;
3464
3465		case DTYPE_MQUEUE:
3466			type = KF_TYPE_MQUEUE;
3467			break;
3468
3469		case DTYPE_SHM:
3470			type = KF_TYPE_SHM;
3471			data = fp;
3472			break;
3473
3474		case DTYPE_SEM:
3475			type = KF_TYPE_SEM;
3476			data = fp;
3477			break;
3478
3479		case DTYPE_PTS:
3480			type = KF_TYPE_PTS;
3481			data = fp->f_data;
3482			break;
3483
3484#ifdef PROCDESC
3485		case DTYPE_PROCDESC:
3486			type = KF_TYPE_PROCDESC;
3487			data = fp->f_data;
3488			break;
3489#endif
3490
3491		default:
3492			type = KF_TYPE_UNKNOWN;
3493			break;
3494		}
3495		refcnt = fp->f_count;
3496		fflags = fp->f_flag;
3497		offset = foffset_get(fp);
3498
3499		/*
3500		 * Create sysctl entry.
3501		 * It is OK to drop the filedesc lock here as we will
3502		 * re-validate and re-evaluate its properties when
3503		 * the loop continues.
3504		 */
3505		error = export_fd_to_sb(data, type, i, fflags, refcnt,
3506		    offset, &rights, efbuf);
3507		if (error != 0)
3508			break;
3509	}
3510	FILEDESC_SUNLOCK(fdp);
3511	fddrop(fdp);
3512fail:
3513	free(efbuf, M_TEMP);
3514	return (error);
3515}
3516
3517#define FILEDESC_SBUF_SIZE	(sizeof(struct kinfo_file) * 5)
3518
3519/*
3520 * Get per-process file descriptors for use by procstat(1), et al.
3521 */
3522static int
3523sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3524{
3525	struct sbuf sb;
3526	struct proc *p;
3527	ssize_t maxlen;
3528	int error, error2, *name;
3529
3530	name = (int *)arg1;
3531
3532	sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3533	error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3534	if (error != 0) {
3535		sbuf_delete(&sb);
3536		return (error);
3537	}
3538	maxlen = req->oldptr != NULL ? req->oldlen : -1;
3539	error = kern_proc_filedesc_out(p, &sb, maxlen);
3540	error2 = sbuf_finish(&sb);
3541	sbuf_delete(&sb);
3542	return (error != 0 ? error : error2);
3543}
3544
3545int
3546vntype_to_kinfo(int vtype)
3547{
3548	struct {
3549		int	vtype;
3550		int	kf_vtype;
3551	} vtypes_table[] = {
3552		{ VBAD, KF_VTYPE_VBAD },
3553		{ VBLK, KF_VTYPE_VBLK },
3554		{ VCHR, KF_VTYPE_VCHR },
3555		{ VDIR, KF_VTYPE_VDIR },
3556		{ VFIFO, KF_VTYPE_VFIFO },
3557		{ VLNK, KF_VTYPE_VLNK },
3558		{ VNON, KF_VTYPE_VNON },
3559		{ VREG, KF_VTYPE_VREG },
3560		{ VSOCK, KF_VTYPE_VSOCK }
3561	};
3562#define	NVTYPES	(sizeof(vtypes_table) / sizeof(*vtypes_table))
3563	unsigned int i;
3564
3565	/*
3566	 * Perform vtype translation.
3567	 */
3568	for (i = 0; i < NVTYPES; i++)
3569		if (vtypes_table[i].vtype == vtype)
3570			break;
3571	if (i < NVTYPES)
3572		return (vtypes_table[i].kf_vtype);
3573
3574	return (KF_VTYPE_UNKNOWN);
3575}
3576
3577static int
3578fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3579{
3580	struct vattr va;
3581	char *fullpath, *freepath;
3582	int error;
3583
3584	if (vp == NULL)
3585		return (1);
3586	kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3587	freepath = NULL;
3588	fullpath = "-";
3589	error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3590	if (error == 0) {
3591		strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3592	}
3593	if (freepath != NULL)
3594		free(freepath, M_TEMP);
3595
3596	/*
3597	 * Retrieve vnode attributes.
3598	 */
3599	va.va_fsid = VNOVAL;
3600	va.va_rdev = NODEV;
3601	vn_lock(vp, LK_SHARED | LK_RETRY);
3602	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3603	VOP_UNLOCK(vp, 0);
3604	if (error != 0)
3605		return (error);
3606	if (va.va_fsid != VNOVAL)
3607		kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3608	else
3609		kif->kf_un.kf_file.kf_file_fsid =
3610		    vp->v_mount->mnt_stat.f_fsid.val[0];
3611	kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3612	kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3613	kif->kf_un.kf_file.kf_file_size = va.va_size;
3614	kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3615	return (0);
3616}
3617
3618static int
3619fill_socket_info(struct socket *so, struct kinfo_file *kif)
3620{
3621	struct sockaddr *sa;
3622	struct inpcb *inpcb;
3623	struct unpcb *unpcb;
3624	int error;
3625
3626	if (so == NULL)
3627		return (1);
3628	kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3629	kif->kf_sock_type = so->so_type;
3630	kif->kf_sock_protocol = so->so_proto->pr_protocol;
3631	kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3632	switch(kif->kf_sock_domain) {
3633	case AF_INET:
3634	case AF_INET6:
3635		if (kif->kf_sock_protocol == IPPROTO_TCP) {
3636			if (so->so_pcb != NULL) {
3637				inpcb = (struct inpcb *)(so->so_pcb);
3638				kif->kf_un.kf_sock.kf_sock_inpcb =
3639				    (uintptr_t)inpcb->inp_ppcb;
3640			}
3641		}
3642		break;
3643	case AF_UNIX:
3644		if (so->so_pcb != NULL) {
3645			unpcb = (struct unpcb *)(so->so_pcb);
3646			if (unpcb->unp_conn) {
3647				kif->kf_un.kf_sock.kf_sock_unpconn =
3648				    (uintptr_t)unpcb->unp_conn;
3649				kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3650				    so->so_rcv.sb_state;
3651				kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3652				    so->so_snd.sb_state;
3653			}
3654		}
3655		break;
3656	}
3657	error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3658	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3659		bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3660		free(sa, M_SONAME);
3661	}
3662	error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3663	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3664		bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3665		free(sa, M_SONAME);
3666	}
3667	strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3668	    sizeof(kif->kf_path));
3669	return (0);
3670}
3671
3672static int
3673fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3674{
3675
3676	if (tp == NULL)
3677		return (1);
3678	kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3679	strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3680	return (0);
3681}
3682
3683static int
3684fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3685{
3686
3687	if (pi == NULL)
3688		return (1);
3689	kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3690	kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3691	kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3692	return (0);
3693}
3694
3695static int
3696fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3697{
3698
3699	if (pdp == NULL)
3700		return (1);
3701	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3702	return (0);
3703}
3704
3705static int
3706fill_sem_info(struct file *fp, struct kinfo_file *kif)
3707{
3708	struct thread *td;
3709	struct stat sb;
3710
3711	td = curthread;
3712	if (fp->f_data == NULL)
3713		return (1);
3714	if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3715		return (1);
3716	if (ksem_info == NULL)
3717		return (1);
3718	ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3719	    &kif->kf_un.kf_sem.kf_sem_value);
3720	kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3721	return (0);
3722}
3723
3724static int
3725fill_shm_info(struct file *fp, struct kinfo_file *kif)
3726{
3727	struct thread *td;
3728	struct stat sb;
3729
3730	td = curthread;
3731	if (fp->f_data == NULL)
3732		return (1);
3733	if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3734		return (1);
3735	shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3736	kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3737	kif->kf_un.kf_file.kf_file_size = sb.st_size;
3738	return (0);
3739}
3740
3741static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3742    sysctl_kern_proc_filedesc, "Process filedesc entries");
3743
3744#ifdef DDB
3745/*
3746 * For the purposes of debugging, generate a human-readable string for the
3747 * file type.
3748 */
3749static const char *
3750file_type_to_name(short type)
3751{
3752
3753	switch (type) {
3754	case 0:
3755		return ("zero");
3756	case DTYPE_VNODE:
3757		return ("vnod");
3758	case DTYPE_SOCKET:
3759		return ("sock");
3760	case DTYPE_PIPE:
3761		return ("pipe");
3762	case DTYPE_FIFO:
3763		return ("fifo");
3764	case DTYPE_KQUEUE:
3765		return ("kque");
3766	case DTYPE_CRYPTO:
3767		return ("crpt");
3768	case DTYPE_MQUEUE:
3769		return ("mque");
3770	case DTYPE_SHM:
3771		return ("shm");
3772	case DTYPE_SEM:
3773		return ("ksem");
3774	default:
3775		return ("unkn");
3776	}
3777}
3778
3779/*
3780 * For the purposes of debugging, identify a process (if any, perhaps one of
3781 * many) that references the passed file in its file descriptor array. Return
3782 * NULL if none.
3783 */
3784static struct proc *
3785file_to_first_proc(struct file *fp)
3786{
3787	struct filedesc *fdp;
3788	struct proc *p;
3789	int n;
3790
3791	FOREACH_PROC_IN_SYSTEM(p) {
3792		if (p->p_state == PRS_NEW)
3793			continue;
3794		fdp = p->p_fd;
3795		if (fdp == NULL)
3796			continue;
3797		for (n = 0; n < fdp->fd_nfiles; n++) {
3798			if (fp == fdp->fd_ofiles[n].fde_file)
3799				return (p);
3800		}
3801	}
3802	return (NULL);
3803}
3804
3805static void
3806db_print_file(struct file *fp, int header)
3807{
3808	struct proc *p;
3809
3810	if (header)
3811		db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3812		    "File", "Type", "Data", "Flag", "GCFl", "Count",
3813		    "MCount", "Vnode", "FPID", "FCmd");
3814	p = file_to_first_proc(fp);
3815	db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3816	    file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3817	    0, fp->f_count, 0, fp->f_vnode,
3818	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3819}
3820
3821DB_SHOW_COMMAND(file, db_show_file)
3822{
3823	struct file *fp;
3824
3825	if (!have_addr) {
3826		db_printf("usage: show file <addr>\n");
3827		return;
3828	}
3829	fp = (struct file *)addr;
3830	db_print_file(fp, 1);
3831}
3832
3833DB_SHOW_COMMAND(files, db_show_files)
3834{
3835	struct filedesc *fdp;
3836	struct file *fp;
3837	struct proc *p;
3838	int header;
3839	int n;
3840
3841	header = 1;
3842	FOREACH_PROC_IN_SYSTEM(p) {
3843		if (p->p_state == PRS_NEW)
3844			continue;
3845		if ((fdp = p->p_fd) == NULL)
3846			continue;
3847		for (n = 0; n < fdp->fd_nfiles; ++n) {
3848			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3849				continue;
3850			db_print_file(fp, header);
3851			header = 0;
3852		}
3853	}
3854}
3855#endif
3856
3857SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3858    &maxfilesperproc, 0, "Maximum files allowed open per process");
3859
3860SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3861    &maxfiles, 0, "Maximum number of files");
3862
3863SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3864    __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3865
3866/* ARGSUSED*/
3867static void
3868filelistinit(void *dummy)
3869{
3870
3871	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3872	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3873	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3874	mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3875}
3876SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3877
3878/*-------------------------------------------------------------------*/
3879
3880static int
3881badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3882    int flags, struct thread *td)
3883{
3884
3885	return (EBADF);
3886}
3887
3888static int
3889badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3890    struct thread *td)
3891{
3892
3893	return (EINVAL);
3894}
3895
3896static int
3897badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3898    struct thread *td)
3899{
3900
3901	return (EBADF);
3902}
3903
3904static int
3905badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3906    struct thread *td)
3907{
3908
3909	return (0);
3910}
3911
3912static int
3913badfo_kqfilter(struct file *fp, struct knote *kn)
3914{
3915
3916	return (EBADF);
3917}
3918
3919static int
3920badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3921    struct thread *td)
3922{
3923
3924	return (EBADF);
3925}
3926
3927static int
3928badfo_close(struct file *fp, struct thread *td)
3929{
3930
3931	return (EBADF);
3932}
3933
3934static int
3935badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3936    struct thread *td)
3937{
3938
3939	return (EBADF);
3940}
3941
3942static int
3943badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3944    struct thread *td)
3945{
3946
3947	return (EBADF);
3948}
3949
3950static int
3951badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3952    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3953    int kflags, struct thread *td)
3954{
3955
3956	return (EBADF);
3957}
3958
3959struct fileops badfileops = {
3960	.fo_read = badfo_readwrite,
3961	.fo_write = badfo_readwrite,
3962	.fo_truncate = badfo_truncate,
3963	.fo_ioctl = badfo_ioctl,
3964	.fo_poll = badfo_poll,
3965	.fo_kqfilter = badfo_kqfilter,
3966	.fo_stat = badfo_stat,
3967	.fo_close = badfo_close,
3968	.fo_chmod = badfo_chmod,
3969	.fo_chown = badfo_chown,
3970	.fo_sendfile = badfo_sendfile,
3971};
3972
3973int
3974invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3975    struct thread *td)
3976{
3977
3978	return (EINVAL);
3979}
3980
3981int
3982invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3983    struct thread *td)
3984{
3985
3986	return (EINVAL);
3987}
3988
3989int
3990invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3991    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3992    int kflags, struct thread *td)
3993{
3994
3995	return (EINVAL);
3996}
3997
3998/*-------------------------------------------------------------------*/
3999
4000/*
4001 * File Descriptor pseudo-device driver (/dev/fd/).
4002 *
4003 * Opening minor device N dup()s the file (if any) connected to file
4004 * descriptor N belonging to the calling process.  Note that this driver
4005 * consists of only the ``open()'' routine, because all subsequent
4006 * references to this file will be direct to the other driver.
4007 *
4008 * XXX: we could give this one a cloning event handler if necessary.
4009 */
4010
4011/* ARGSUSED */
4012static int
4013fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4014{
4015
4016	/*
4017	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4018	 * the file descriptor being sought for duplication. The error
4019	 * return ensures that the vnode for this device will be released
4020	 * by vn_open. Open will detect this special error and take the
4021	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4022	 * will simply report the error.
4023	 */
4024	td->td_dupfd = dev2unit(dev);
4025	return (ENODEV);
4026}
4027
4028static struct cdevsw fildesc_cdevsw = {
4029	.d_version =	D_VERSION,
4030	.d_open =	fdopen,
4031	.d_name =	"FD",
4032};
4033
4034static void
4035fildesc_drvinit(void *unused)
4036{
4037	struct cdev *dev;
4038
4039	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4040	    UID_ROOT, GID_WHEEL, 0666, "fd/0");
4041	make_dev_alias(dev, "stdin");
4042	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4043	    UID_ROOT, GID_WHEEL, 0666, "fd/1");
4044	make_dev_alias(dev, "stdout");
4045	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4046	    UID_ROOT, GID_WHEEL, 0666, "fd/2");
4047	make_dev_alias(dev, "stderr");
4048}
4049
4050SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
4051