kern_descrip.c revision 263958
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 263958 2014-03-31 02:17:58Z 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.  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	/* copy the old data over and point at the new tables */
1534	memcpy(ntable, otable, onfiles * sizeof(*otable));
1535	fdp->fd_ofiles = ntable;
1536
1537	/*
1538	 * Allocate a new map only if the old is not large enough.  It will
1539	 * grow at a slower rate than the table as it can map more
1540	 * entries than the table can hold.
1541	 */
1542	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1543		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1544		    M_ZERO | M_WAITOK);
1545		/* copy over the old data and update the pointer */
1546		memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1547		fdp->fd_map = nmap;
1548	}
1549
1550	/*
1551	 * In order to have a valid pattern for fget_unlocked()
1552	 * fdp->fd_nfiles must be the last member to be updated, otherwise
1553	 * fget_unlocked() consumers may reference a new, higher value for
1554	 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1555	 * resulting in OOB accesses.
1556	 */
1557	atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1558
1559	/*
1560	 * Do not free the old file table, as some threads may still
1561	 * reference entries within it.  Instead, place it on a freelist
1562	 * which will be processed when the struct filedesc is released.
1563	 *
1564	 * Note that if onfiles == NDFILE, we're dealing with the original
1565	 * static allocation contained within (struct filedesc0 *)fdp,
1566	 * which must not be freed.
1567	 */
1568	if (onfiles > NDFILE) {
1569		ft = (struct freetable *)&otable[onfiles];
1570		fdp0 = (struct filedesc0 *)fdp;
1571		ft->ft_table = otable;
1572		SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1573	}
1574	/*
1575	 * The map does not have the same possibility of threads still
1576	 * holding references to it.  So always free it as long as it
1577	 * does not reference the original static allocation.
1578	 */
1579	if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1580		free(omap, M_FILEDESC);
1581}
1582
1583/*
1584 * Allocate a file descriptor for the process.
1585 */
1586int
1587fdalloc(struct thread *td, int minfd, int *result)
1588{
1589	struct proc *p = td->td_proc;
1590	struct filedesc *fdp = p->p_fd;
1591	int fd = -1, maxfd, allocfd;
1592#ifdef RACCT
1593	int error;
1594#endif
1595
1596	FILEDESC_XLOCK_ASSERT(fdp);
1597
1598	if (fdp->fd_freefile > minfd)
1599		minfd = fdp->fd_freefile;
1600
1601	maxfd = getmaxfd(p);
1602
1603	/*
1604	 * Search the bitmap for a free descriptor starting at minfd.
1605	 * If none is found, grow the file table.
1606	 */
1607	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1608	if (fd >= maxfd)
1609		return (EMFILE);
1610	if (fd >= fdp->fd_nfiles) {
1611		allocfd = min(fd * 2, maxfd);
1612#ifdef RACCT
1613		PROC_LOCK(p);
1614		error = racct_set(p, RACCT_NOFILE, allocfd);
1615		PROC_UNLOCK(p);
1616		if (error != 0)
1617			return (EMFILE);
1618#endif
1619		/*
1620		 * fd is already equal to first free descriptor >= minfd, so
1621		 * we only need to grow the table and we are done.
1622		 */
1623		fdgrowtable_exp(fdp, allocfd);
1624	}
1625
1626	/*
1627	 * Perform some sanity checks, then mark the file descriptor as
1628	 * used and return it to the caller.
1629	 */
1630	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1631	    ("invalid descriptor %d", fd));
1632	KASSERT(!fdisused(fdp, fd),
1633	    ("fd_first_free() returned non-free descriptor"));
1634	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1635	    ("file descriptor isn't free"));
1636	KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1637	fdused(fdp, fd);
1638	*result = fd;
1639	return (0);
1640}
1641
1642/*
1643 * Allocate n file descriptors for the process.
1644 */
1645int
1646fdallocn(struct thread *td, int minfd, int *fds, int n)
1647{
1648	struct proc *p = td->td_proc;
1649	struct filedesc *fdp = p->p_fd;
1650	int i;
1651
1652	FILEDESC_XLOCK_ASSERT(fdp);
1653
1654	if (!fdavail(td, n))
1655		return (EMFILE);
1656
1657	for (i = 0; i < n; i++)
1658		if (fdalloc(td, 0, &fds[i]) != 0)
1659			break;
1660
1661	if (i < n) {
1662		for (i--; i >= 0; i--)
1663			fdunused(fdp, fds[i]);
1664		return (EMFILE);
1665	}
1666
1667	return (0);
1668}
1669
1670/*
1671 * Check to see whether n user file descriptors are available to the process
1672 * p.
1673 */
1674int
1675fdavail(struct thread *td, int n)
1676{
1677	struct proc *p = td->td_proc;
1678	struct filedesc *fdp = td->td_proc->p_fd;
1679	int i, lim, last;
1680
1681	FILEDESC_LOCK_ASSERT(fdp);
1682
1683	/*
1684	 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1685	 *      call racct_add() from there instead of dealing with containers
1686	 *      here.
1687	 */
1688	lim = getmaxfd(p);
1689	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1690		return (1);
1691	last = min(fdp->fd_nfiles, lim);
1692	for (i = fdp->fd_freefile; i < last; i++) {
1693		if (fdp->fd_ofiles[i].fde_file == NULL && --n <= 0)
1694			return (1);
1695	}
1696	return (0);
1697}
1698
1699/*
1700 * Create a new open file structure and allocate a file decriptor for the
1701 * process that refers to it.  We add one reference to the file for the
1702 * descriptor table and one reference for resultfp. This is to prevent us
1703 * being preempted and the entry in the descriptor table closed after we
1704 * release the FILEDESC lock.
1705 */
1706int
1707falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1708{
1709	struct file *fp;
1710	int error, fd;
1711
1712	error = falloc_noinstall(td, &fp);
1713	if (error)
1714		return (error);		/* no reference held on error */
1715
1716	error = finstall(td, fp, &fd, flags, NULL);
1717	if (error) {
1718		fdrop(fp, td);		/* one reference (fp only) */
1719		return (error);
1720	}
1721
1722	if (resultfp != NULL)
1723		*resultfp = fp;		/* copy out result */
1724	else
1725		fdrop(fp, td);		/* release local reference */
1726
1727	if (resultfd != NULL)
1728		*resultfd = fd;
1729
1730	return (0);
1731}
1732
1733/*
1734 * Create a new open file structure without allocating a file descriptor.
1735 */
1736int
1737falloc_noinstall(struct thread *td, struct file **resultfp)
1738{
1739	struct file *fp;
1740	int maxuserfiles = maxfiles - (maxfiles / 20);
1741	static struct timeval lastfail;
1742	static int curfail;
1743
1744	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1745
1746	if ((openfiles >= maxuserfiles &&
1747	    priv_check(td, PRIV_MAXFILES) != 0) ||
1748	    openfiles >= maxfiles) {
1749		if (ppsratecheck(&lastfail, &curfail, 1)) {
1750			printf("kern.maxfiles limit exceeded by uid %i, "
1751			    "please see tuning(7).\n", td->td_ucred->cr_ruid);
1752		}
1753		return (ENFILE);
1754	}
1755	atomic_add_int(&openfiles, 1);
1756	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1757	refcount_init(&fp->f_count, 1);
1758	fp->f_cred = crhold(td->td_ucred);
1759	fp->f_ops = &badfileops;
1760	fp->f_data = NULL;
1761	fp->f_vnode = NULL;
1762	*resultfp = fp;
1763	return (0);
1764}
1765
1766/*
1767 * Install a file in a file descriptor table.
1768 */
1769int
1770finstall(struct thread *td, struct file *fp, int *fd, int flags,
1771    struct filecaps *fcaps)
1772{
1773	struct filedesc *fdp = td->td_proc->p_fd;
1774	struct filedescent *fde;
1775	int error;
1776
1777	KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1778	KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1779	if (fcaps != NULL)
1780		filecaps_validate(fcaps, __func__);
1781
1782	FILEDESC_XLOCK(fdp);
1783	if ((error = fdalloc(td, 0, fd))) {
1784		FILEDESC_XUNLOCK(fdp);
1785		return (error);
1786	}
1787	fhold(fp);
1788	fde = &fdp->fd_ofiles[*fd];
1789	fde->fde_file = fp;
1790	if ((flags & O_CLOEXEC) != 0)
1791		fde->fde_flags |= UF_EXCLOSE;
1792	if (fcaps != NULL)
1793		filecaps_move(fcaps, &fde->fde_caps);
1794	else
1795		filecaps_fill(&fde->fde_caps);
1796	FILEDESC_XUNLOCK(fdp);
1797	return (0);
1798}
1799
1800/*
1801 * Build a new filedesc structure from another.
1802 * Copy the current, root, and jail root vnode references.
1803 */
1804struct filedesc *
1805fdinit(struct filedesc *fdp)
1806{
1807	struct filedesc0 *newfdp;
1808
1809	newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1810	FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1811	if (fdp != NULL) {
1812		FILEDESC_SLOCK(fdp);
1813		newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1814		if (newfdp->fd_fd.fd_cdir)
1815			VREF(newfdp->fd_fd.fd_cdir);
1816		newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1817		if (newfdp->fd_fd.fd_rdir)
1818			VREF(newfdp->fd_fd.fd_rdir);
1819		newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1820		if (newfdp->fd_fd.fd_jdir)
1821			VREF(newfdp->fd_fd.fd_jdir);
1822		FILEDESC_SUNLOCK(fdp);
1823	}
1824
1825	/* Create the file descriptor table. */
1826	newfdp->fd_fd.fd_refcnt = 1;
1827	newfdp->fd_fd.fd_holdcnt = 1;
1828	newfdp->fd_fd.fd_cmask = CMASK;
1829	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1830	newfdp->fd_fd.fd_nfiles = NDFILE;
1831	newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1832	newfdp->fd_fd.fd_lastfile = -1;
1833	return (&newfdp->fd_fd);
1834}
1835
1836static struct filedesc *
1837fdhold(struct proc *p)
1838{
1839	struct filedesc *fdp;
1840
1841	mtx_lock(&fdesc_mtx);
1842	fdp = p->p_fd;
1843	if (fdp != NULL)
1844		fdp->fd_holdcnt++;
1845	mtx_unlock(&fdesc_mtx);
1846	return (fdp);
1847}
1848
1849static void
1850fddrop(struct filedesc *fdp)
1851{
1852	struct filedesc0 *fdp0;
1853	struct freetable *ft;
1854	int i;
1855
1856	mtx_lock(&fdesc_mtx);
1857	i = --fdp->fd_holdcnt;
1858	mtx_unlock(&fdesc_mtx);
1859	if (i > 0)
1860		return;
1861
1862	FILEDESC_LOCK_DESTROY(fdp);
1863	fdp0 = (struct filedesc0 *)fdp;
1864	while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1865		SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1866		free(ft->ft_table, M_FILEDESC);
1867	}
1868	free(fdp, M_FILEDESC);
1869}
1870
1871/*
1872 * Share a filedesc structure.
1873 */
1874struct filedesc *
1875fdshare(struct filedesc *fdp)
1876{
1877
1878	FILEDESC_XLOCK(fdp);
1879	fdp->fd_refcnt++;
1880	FILEDESC_XUNLOCK(fdp);
1881	return (fdp);
1882}
1883
1884/*
1885 * Unshare a filedesc structure, if necessary by making a copy
1886 */
1887void
1888fdunshare(struct proc *p, struct thread *td)
1889{
1890
1891	FILEDESC_XLOCK(p->p_fd);
1892	if (p->p_fd->fd_refcnt > 1) {
1893		struct filedesc *tmp;
1894
1895		FILEDESC_XUNLOCK(p->p_fd);
1896		tmp = fdcopy(p->p_fd);
1897		fdescfree(td);
1898		p->p_fd = tmp;
1899	} else
1900		FILEDESC_XUNLOCK(p->p_fd);
1901}
1902
1903/*
1904 * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
1905 * this is to ease callers, not catch errors.
1906 */
1907struct filedesc *
1908fdcopy(struct filedesc *fdp)
1909{
1910	struct filedesc *newfdp;
1911	struct filedescent *nfde, *ofde;
1912	int i;
1913
1914	/* Certain daemons might not have file descriptors. */
1915	if (fdp == NULL)
1916		return (NULL);
1917
1918	newfdp = fdinit(fdp);
1919	FILEDESC_SLOCK(fdp);
1920	while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1921		FILEDESC_SUNLOCK(fdp);
1922		FILEDESC_XLOCK(newfdp);
1923		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1924		FILEDESC_XUNLOCK(newfdp);
1925		FILEDESC_SLOCK(fdp);
1926	}
1927	/* copy all passable descriptors (i.e. not kqueue) */
1928	newfdp->fd_freefile = -1;
1929	for (i = 0; i <= fdp->fd_lastfile; ++i) {
1930		ofde = &fdp->fd_ofiles[i];
1931		if (fdisused(fdp, i) &&
1932		    (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1933		    ofde->fde_file->f_ops != &badfileops) {
1934			nfde = &newfdp->fd_ofiles[i];
1935			*nfde = *ofde;
1936			filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1937			fhold(nfde->fde_file);
1938			newfdp->fd_lastfile = i;
1939		} else {
1940			if (newfdp->fd_freefile == -1)
1941				newfdp->fd_freefile = i;
1942		}
1943	}
1944	newfdp->fd_cmask = fdp->fd_cmask;
1945	FILEDESC_SUNLOCK(fdp);
1946	FILEDESC_XLOCK(newfdp);
1947	for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1948		if (newfdp->fd_ofiles[i].fde_file != NULL)
1949			fdused(newfdp, i);
1950	}
1951	if (newfdp->fd_freefile == -1)
1952		newfdp->fd_freefile = i;
1953	FILEDESC_XUNLOCK(newfdp);
1954	return (newfdp);
1955}
1956
1957/*
1958 * Release a filedesc structure.
1959 */
1960void
1961fdescfree(struct thread *td)
1962{
1963	struct filedesc *fdp;
1964	int i;
1965	struct filedesc_to_leader *fdtol;
1966	struct file *fp;
1967	struct vnode *cdir, *jdir, *rdir, *vp;
1968	struct flock lf;
1969
1970	/* Certain daemons might not have file descriptors. */
1971	fdp = td->td_proc->p_fd;
1972	if (fdp == NULL)
1973		return;
1974
1975#ifdef RACCT
1976	PROC_LOCK(td->td_proc);
1977	racct_set(td->td_proc, RACCT_NOFILE, 0);
1978	PROC_UNLOCK(td->td_proc);
1979#endif
1980
1981	/* Check for special need to clear POSIX style locks */
1982	fdtol = td->td_proc->p_fdtol;
1983	if (fdtol != NULL) {
1984		FILEDESC_XLOCK(fdp);
1985		KASSERT(fdtol->fdl_refcount > 0,
1986		    ("filedesc_to_refcount botch: fdl_refcount=%d",
1987		    fdtol->fdl_refcount));
1988		if (fdtol->fdl_refcount == 1 &&
1989		    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1990			for (i = 0; i <= fdp->fd_lastfile; i++) {
1991				fp = fdp->fd_ofiles[i].fde_file;
1992				if (fp == NULL || fp->f_type != DTYPE_VNODE)
1993					continue;
1994				fhold(fp);
1995				FILEDESC_XUNLOCK(fdp);
1996				lf.l_whence = SEEK_SET;
1997				lf.l_start = 0;
1998				lf.l_len = 0;
1999				lf.l_type = F_UNLCK;
2000				vp = fp->f_vnode;
2001				(void) VOP_ADVLOCK(vp,
2002				    (caddr_t)td->td_proc->p_leader, F_UNLCK,
2003				    &lf, F_POSIX);
2004				FILEDESC_XLOCK(fdp);
2005				fdrop(fp, td);
2006			}
2007		}
2008	retry:
2009		if (fdtol->fdl_refcount == 1) {
2010			if (fdp->fd_holdleaderscount > 0 &&
2011			    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2012				/*
2013				 * close() or do_dup() has cleared a reference
2014				 * in a shared file descriptor table.
2015				 */
2016				fdp->fd_holdleaderswakeup = 1;
2017				sx_sleep(&fdp->fd_holdleaderscount,
2018				    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2019				goto retry;
2020			}
2021			if (fdtol->fdl_holdcount > 0) {
2022				/*
2023				 * Ensure that fdtol->fdl_leader remains
2024				 * valid in closef().
2025				 */
2026				fdtol->fdl_wakeup = 1;
2027				sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2028				    "fdlhold", 0);
2029				goto retry;
2030			}
2031		}
2032		fdtol->fdl_refcount--;
2033		if (fdtol->fdl_refcount == 0 &&
2034		    fdtol->fdl_holdcount == 0) {
2035			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2036			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2037		} else
2038			fdtol = NULL;
2039		td->td_proc->p_fdtol = NULL;
2040		FILEDESC_XUNLOCK(fdp);
2041		if (fdtol != NULL)
2042			free(fdtol, M_FILEDESC_TO_LEADER);
2043	}
2044	FILEDESC_XLOCK(fdp);
2045	i = --fdp->fd_refcnt;
2046	FILEDESC_XUNLOCK(fdp);
2047	if (i > 0)
2048		return;
2049
2050	for (i = 0; i <= fdp->fd_lastfile; i++) {
2051		fp = fdp->fd_ofiles[i].fde_file;
2052		if (fp != NULL) {
2053			FILEDESC_XLOCK(fdp);
2054			fdfree(fdp, i);
2055			FILEDESC_XUNLOCK(fdp);
2056			(void) closef(fp, td);
2057		}
2058	}
2059	FILEDESC_XLOCK(fdp);
2060
2061	/* XXX This should happen earlier. */
2062	mtx_lock(&fdesc_mtx);
2063	td->td_proc->p_fd = NULL;
2064	mtx_unlock(&fdesc_mtx);
2065
2066	if (fdp->fd_nfiles > NDFILE)
2067		free(fdp->fd_ofiles, M_FILEDESC);
2068	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2069		free(fdp->fd_map, M_FILEDESC);
2070
2071	fdp->fd_nfiles = 0;
2072
2073	cdir = fdp->fd_cdir;
2074	fdp->fd_cdir = NULL;
2075	rdir = fdp->fd_rdir;
2076	fdp->fd_rdir = NULL;
2077	jdir = fdp->fd_jdir;
2078	fdp->fd_jdir = NULL;
2079	FILEDESC_XUNLOCK(fdp);
2080
2081	if (cdir != NULL)
2082		vrele(cdir);
2083	if (rdir != NULL)
2084		vrele(rdir);
2085	if (jdir != NULL)
2086		vrele(jdir);
2087
2088	fddrop(fdp);
2089}
2090
2091/*
2092 * For setugid programs, we don't want to people to use that setugidness
2093 * to generate error messages which write to a file which otherwise would
2094 * otherwise be off-limits to the process.  We check for filesystems where
2095 * the vnode can change out from under us after execve (like [lin]procfs).
2096 *
2097 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2098 * sufficient.  We also don't check for setugidness since we know we are.
2099 */
2100static int
2101is_unsafe(struct file *fp)
2102{
2103	if (fp->f_type == DTYPE_VNODE) {
2104		struct vnode *vp = fp->f_vnode;
2105
2106		if ((vp->v_vflag & VV_PROCDEP) != 0)
2107			return (1);
2108	}
2109	return (0);
2110}
2111
2112/*
2113 * Make this setguid thing safe, if at all possible.
2114 */
2115void
2116setugidsafety(struct thread *td)
2117{
2118	struct filedesc *fdp;
2119	struct file *fp;
2120	int i;
2121
2122	/* Certain daemons might not have file descriptors. */
2123	fdp = td->td_proc->p_fd;
2124	if (fdp == NULL)
2125		return;
2126
2127	/*
2128	 * Note: fdp->fd_ofiles may be reallocated out from under us while
2129	 * we are blocked in a close.  Be careful!
2130	 */
2131	FILEDESC_XLOCK(fdp);
2132	for (i = 0; i <= fdp->fd_lastfile; i++) {
2133		if (i > 2)
2134			break;
2135		fp = fdp->fd_ofiles[i].fde_file;
2136		if (fp != NULL && is_unsafe(fp)) {
2137			knote_fdclose(td, i);
2138			/*
2139			 * NULL-out descriptor prior to close to avoid
2140			 * a race while close blocks.
2141			 */
2142			fdfree(fdp, i);
2143			FILEDESC_XUNLOCK(fdp);
2144			(void) closef(fp, td);
2145			FILEDESC_XLOCK(fdp);
2146		}
2147	}
2148	FILEDESC_XUNLOCK(fdp);
2149}
2150
2151/*
2152 * If a specific file object occupies a specific file descriptor, close the
2153 * file descriptor entry and drop a reference on the file object.  This is a
2154 * convenience function to handle a subsequent error in a function that calls
2155 * falloc() that handles the race that another thread might have closed the
2156 * file descriptor out from under the thread creating the file object.
2157 */
2158void
2159fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2160{
2161
2162	FILEDESC_XLOCK(fdp);
2163	if (fdp->fd_ofiles[idx].fde_file == fp) {
2164		fdfree(fdp, idx);
2165		FILEDESC_XUNLOCK(fdp);
2166		fdrop(fp, td);
2167	} else
2168		FILEDESC_XUNLOCK(fdp);
2169}
2170
2171/*
2172 * Close any files on exec?
2173 */
2174void
2175fdcloseexec(struct thread *td)
2176{
2177	struct filedesc *fdp;
2178	struct filedescent *fde;
2179	struct file *fp;
2180	int i;
2181
2182	/* Certain daemons might not have file descriptors. */
2183	fdp = td->td_proc->p_fd;
2184	if (fdp == NULL)
2185		return;
2186
2187	/*
2188	 * We cannot cache fd_ofiles since operations
2189	 * may block and rip them out from under us.
2190	 */
2191	FILEDESC_XLOCK(fdp);
2192	for (i = 0; i <= fdp->fd_lastfile; i++) {
2193		fde = &fdp->fd_ofiles[i];
2194		fp = fde->fde_file;
2195		if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2196		    (fde->fde_flags & UF_EXCLOSE))) {
2197			fdfree(fdp, i);
2198			(void) closefp(fdp, i, fp, td, 0);
2199			/* closefp() drops the FILEDESC lock. */
2200			FILEDESC_XLOCK(fdp);
2201		}
2202	}
2203	FILEDESC_XUNLOCK(fdp);
2204}
2205
2206/*
2207 * It is unsafe for set[ug]id processes to be started with file
2208 * descriptors 0..2 closed, as these descriptors are given implicit
2209 * significance in the Standard C library.  fdcheckstd() will create a
2210 * descriptor referencing /dev/null for each of stdin, stdout, and
2211 * stderr that is not already open.
2212 */
2213int
2214fdcheckstd(struct thread *td)
2215{
2216	struct filedesc *fdp;
2217	register_t retval, save;
2218	int i, error, devnull;
2219
2220	fdp = td->td_proc->p_fd;
2221	if (fdp == NULL)
2222		return (0);
2223	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2224	devnull = -1;
2225	error = 0;
2226	for (i = 0; i < 3; i++) {
2227		if (fdp->fd_ofiles[i].fde_file != NULL)
2228			continue;
2229		if (devnull < 0) {
2230			save = td->td_retval[0];
2231			error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2232			    O_RDWR, 0);
2233			devnull = td->td_retval[0];
2234			td->td_retval[0] = save;
2235			if (error)
2236				break;
2237			KASSERT(devnull == i, ("oof, we didn't get our fd"));
2238		} else {
2239			error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2240			if (error != 0)
2241				break;
2242		}
2243	}
2244	return (error);
2245}
2246
2247/*
2248 * Internal form of close.  Decrement reference count on file structure.
2249 * Note: td may be NULL when closing a file that was being passed in a
2250 * message.
2251 *
2252 * XXXRW: Giant is not required for the caller, but often will be held; this
2253 * makes it moderately likely the Giant will be recursed in the VFS case.
2254 */
2255int
2256closef(struct file *fp, struct thread *td)
2257{
2258	struct vnode *vp;
2259	struct flock lf;
2260	struct filedesc_to_leader *fdtol;
2261	struct filedesc *fdp;
2262
2263	/*
2264	 * POSIX record locking dictates that any close releases ALL
2265	 * locks owned by this process.  This is handled by setting
2266	 * a flag in the unlock to free ONLY locks obeying POSIX
2267	 * semantics, and not to free BSD-style file locks.
2268	 * If the descriptor was in a message, POSIX-style locks
2269	 * aren't passed with the descriptor, and the thread pointer
2270	 * will be NULL.  Callers should be careful only to pass a
2271	 * NULL thread pointer when there really is no owning
2272	 * context that might have locks, or the locks will be
2273	 * leaked.
2274	 */
2275	if (fp->f_type == DTYPE_VNODE && td != NULL) {
2276		vp = fp->f_vnode;
2277		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2278			lf.l_whence = SEEK_SET;
2279			lf.l_start = 0;
2280			lf.l_len = 0;
2281			lf.l_type = F_UNLCK;
2282			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2283			    F_UNLCK, &lf, F_POSIX);
2284		}
2285		fdtol = td->td_proc->p_fdtol;
2286		if (fdtol != NULL) {
2287			/*
2288			 * Handle special case where file descriptor table is
2289			 * shared between multiple process leaders.
2290			 */
2291			fdp = td->td_proc->p_fd;
2292			FILEDESC_XLOCK(fdp);
2293			for (fdtol = fdtol->fdl_next;
2294			     fdtol != td->td_proc->p_fdtol;
2295			     fdtol = fdtol->fdl_next) {
2296				if ((fdtol->fdl_leader->p_flag &
2297				     P_ADVLOCK) == 0)
2298					continue;
2299				fdtol->fdl_holdcount++;
2300				FILEDESC_XUNLOCK(fdp);
2301				lf.l_whence = SEEK_SET;
2302				lf.l_start = 0;
2303				lf.l_len = 0;
2304				lf.l_type = F_UNLCK;
2305				vp = fp->f_vnode;
2306				(void) VOP_ADVLOCK(vp,
2307				    (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2308				    F_POSIX);
2309				FILEDESC_XLOCK(fdp);
2310				fdtol->fdl_holdcount--;
2311				if (fdtol->fdl_holdcount == 0 &&
2312				    fdtol->fdl_wakeup != 0) {
2313					fdtol->fdl_wakeup = 0;
2314					wakeup(fdtol);
2315				}
2316			}
2317			FILEDESC_XUNLOCK(fdp);
2318		}
2319	}
2320	return (fdrop(fp, td));
2321}
2322
2323/*
2324 * Initialize the file pointer with the specified properties.
2325 *
2326 * The ops are set with release semantics to be certain that the flags, type,
2327 * and data are visible when ops is.  This is to prevent ops methods from being
2328 * called with bad data.
2329 */
2330void
2331finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2332{
2333	fp->f_data = data;
2334	fp->f_flag = flag;
2335	fp->f_type = type;
2336	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2337}
2338
2339int
2340fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2341    int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2342{
2343	struct file *fp;
2344	u_int count;
2345#ifdef CAPABILITIES
2346	cap_rights_t haverights;
2347	int error;
2348#endif
2349
2350	/*
2351	 * Avoid reads reordering and then a first access to the
2352	 * fdp->fd_ofiles table which could result in OOB operation.
2353	 */
2354	if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2355		return (EBADF);
2356	/*
2357	 * Fetch the descriptor locklessly.  We avoid fdrop() races by
2358	 * never raising a refcount above 0.  To accomplish this we have
2359	 * to use a cmpset loop rather than an atomic_add.  The descriptor
2360	 * must be re-verified once we acquire a reference to be certain
2361	 * that the identity is still correct and we did not lose a race
2362	 * due to preemption.
2363	 */
2364	for (;;) {
2365		fp = fdp->fd_ofiles[fd].fde_file;
2366		if (fp == NULL)
2367			return (EBADF);
2368#ifdef CAPABILITIES
2369		haverights = *cap_rights(fdp, fd);
2370		if (needrightsp != NULL) {
2371			error = cap_check(&haverights, needrightsp);
2372			if (error != 0)
2373				return (error);
2374			if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2375				error = cap_fcntl_check(fdp, fd, needfcntl);
2376				if (error != 0)
2377					return (error);
2378			}
2379		}
2380#endif
2381		count = fp->f_count;
2382		if (count == 0)
2383			continue;
2384		/*
2385		 * Use an acquire barrier to prevent caching of fd_ofiles
2386		 * so it is refreshed for verification.
2387		 */
2388		if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2389			continue;
2390		if (fp == fdp->fd_ofiles[fd].fde_file)
2391			break;
2392		fdrop(fp, curthread);
2393	}
2394	*fpp = fp;
2395	if (haverightsp != NULL) {
2396#ifdef CAPABILITIES
2397		*haverightsp = haverights;
2398#else
2399		CAP_ALL(haverightsp);
2400#endif
2401	}
2402	return (0);
2403}
2404
2405/*
2406 * Extract the file pointer associated with the specified descriptor for the
2407 * current user process.
2408 *
2409 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2410 * returned.
2411 *
2412 * File's rights will be checked against the capability rights mask.
2413 *
2414 * If an error occured the non-zero error is returned and *fpp is set to
2415 * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
2416 * responsible for fdrop().
2417 */
2418static __inline int
2419_fget(struct thread *td, int fd, struct file **fpp, int flags,
2420    cap_rights_t *needrightsp, u_char *maxprotp)
2421{
2422	struct filedesc *fdp;
2423	struct file *fp;
2424	cap_rights_t haverights, needrights;
2425	int error;
2426
2427	*fpp = NULL;
2428	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2429		return (EBADF);
2430	if (needrightsp != NULL)
2431		needrights = *needrightsp;
2432	else
2433		cap_rights_init(&needrights);
2434	if (maxprotp != NULL)
2435		cap_rights_set(&needrights, CAP_MMAP);
2436	error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2437	if (error != 0)
2438		return (error);
2439	if (fp->f_ops == &badfileops) {
2440		fdrop(fp, td);
2441		return (EBADF);
2442	}
2443
2444#ifdef CAPABILITIES
2445	/*
2446	 * If requested, convert capability rights to access flags.
2447	 */
2448	if (maxprotp != NULL)
2449		*maxprotp = cap_rights_to_vmprot(&haverights);
2450#else /* !CAPABILITIES */
2451	if (maxprotp != NULL)
2452		*maxprotp = VM_PROT_ALL;
2453#endif /* CAPABILITIES */
2454
2455	/*
2456	 * FREAD and FWRITE failure return EBADF as per POSIX.
2457	 */
2458	error = 0;
2459	switch (flags) {
2460	case FREAD:
2461	case FWRITE:
2462		if ((fp->f_flag & flags) == 0)
2463			error = EBADF;
2464		break;
2465	case FEXEC:
2466	    	if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2467		    ((fp->f_flag & FWRITE) != 0))
2468			error = EBADF;
2469		break;
2470	case 0:
2471		break;
2472	default:
2473		KASSERT(0, ("wrong flags"));
2474	}
2475
2476	if (error != 0) {
2477		fdrop(fp, td);
2478		return (error);
2479	}
2480
2481	*fpp = fp;
2482	return (0);
2483}
2484
2485int
2486fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2487{
2488
2489	return(_fget(td, fd, fpp, 0, rightsp, NULL));
2490}
2491
2492int
2493fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2494    struct file **fpp)
2495{
2496
2497	return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2498}
2499
2500int
2501fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2502{
2503
2504	return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2505}
2506
2507int
2508fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2509{
2510
2511	return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2512}
2513
2514/*
2515 * Like fget() but loads the underlying vnode, or returns an error if the
2516 * descriptor does not represent a vnode.  Note that pipes use vnodes but
2517 * never have VM objects.  The returned vnode will be vref()'d.
2518 *
2519 * XXX: what about the unused flags ?
2520 */
2521static __inline int
2522_fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2523    struct vnode **vpp)
2524{
2525	struct file *fp;
2526	int error;
2527
2528	*vpp = NULL;
2529	error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2530	if (error != 0)
2531		return (error);
2532	if (fp->f_vnode == NULL) {
2533		error = EINVAL;
2534	} else {
2535		*vpp = fp->f_vnode;
2536		vref(*vpp);
2537	}
2538	fdrop(fp, td);
2539
2540	return (error);
2541}
2542
2543int
2544fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2545{
2546
2547	return (_fgetvp(td, fd, 0, rightsp, vpp));
2548}
2549
2550int
2551fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2552    struct filecaps *havecaps, struct vnode **vpp)
2553{
2554	struct filedesc *fdp;
2555	struct file *fp;
2556#ifdef CAPABILITIES
2557	int error;
2558#endif
2559
2560	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2561		return (EBADF);
2562
2563	fp = fget_locked(fdp, fd);
2564	if (fp == NULL || fp->f_ops == &badfileops)
2565		return (EBADF);
2566
2567#ifdef CAPABILITIES
2568	if (needrightsp != NULL) {
2569		error = cap_check(cap_rights(fdp, fd), needrightsp);
2570		if (error != 0)
2571			return (error);
2572	}
2573#endif
2574
2575	if (fp->f_vnode == NULL)
2576		return (EINVAL);
2577
2578	*vpp = fp->f_vnode;
2579	vref(*vpp);
2580	filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2581
2582	return (0);
2583}
2584
2585int
2586fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2587{
2588
2589	return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2590}
2591
2592int
2593fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2594{
2595
2596	return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2597}
2598
2599#ifdef notyet
2600int
2601fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2602    struct vnode **vpp)
2603{
2604
2605	return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2606}
2607#endif
2608
2609/*
2610 * Like fget() but loads the underlying socket, or returns an error if the
2611 * descriptor does not represent a socket.
2612 *
2613 * We bump the ref count on the returned socket.  XXX Also obtain the SX lock
2614 * in the future.
2615 *
2616 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2617 * on their file descriptor reference to prevent the socket from being free'd
2618 * during use.
2619 */
2620int
2621fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2622    u_int *fflagp)
2623{
2624	struct file *fp;
2625	int error;
2626
2627	*spp = NULL;
2628	if (fflagp != NULL)
2629		*fflagp = 0;
2630	if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2631		return (error);
2632	if (fp->f_type != DTYPE_SOCKET) {
2633		error = ENOTSOCK;
2634	} else {
2635		*spp = fp->f_data;
2636		if (fflagp)
2637			*fflagp = fp->f_flag;
2638		SOCK_LOCK(*spp);
2639		soref(*spp);
2640		SOCK_UNLOCK(*spp);
2641	}
2642	fdrop(fp, td);
2643
2644	return (error);
2645}
2646
2647/*
2648 * Drop the reference count on the socket and XXX release the SX lock in the
2649 * future.  The last reference closes the socket.
2650 *
2651 * Note: fputsock() is deprecated, see comment for fgetsock().
2652 */
2653void
2654fputsock(struct socket *so)
2655{
2656
2657	ACCEPT_LOCK();
2658	SOCK_LOCK(so);
2659	CURVNET_SET(so->so_vnet);
2660	sorele(so);
2661	CURVNET_RESTORE();
2662}
2663
2664/*
2665 * Handle the last reference to a file being closed.
2666 */
2667int
2668_fdrop(struct file *fp, struct thread *td)
2669{
2670	int error;
2671
2672	error = 0;
2673	if (fp->f_count != 0)
2674		panic("fdrop: count %d", fp->f_count);
2675	if (fp->f_ops != &badfileops)
2676		error = fo_close(fp, td);
2677	atomic_subtract_int(&openfiles, 1);
2678	crfree(fp->f_cred);
2679	free(fp->f_advice, M_FADVISE);
2680	uma_zfree(file_zone, fp);
2681
2682	return (error);
2683}
2684
2685/*
2686 * Apply an advisory lock on a file descriptor.
2687 *
2688 * Just attempt to get a record lock of the requested type on the entire file
2689 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2690 */
2691#ifndef _SYS_SYSPROTO_H_
2692struct flock_args {
2693	int	fd;
2694	int	how;
2695};
2696#endif
2697/* ARGSUSED */
2698int
2699sys_flock(struct thread *td, struct flock_args *uap)
2700{
2701	struct file *fp;
2702	struct vnode *vp;
2703	struct flock lf;
2704	cap_rights_t rights;
2705	int error;
2706
2707	error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2708	if (error != 0)
2709		return (error);
2710	if (fp->f_type != DTYPE_VNODE) {
2711		fdrop(fp, td);
2712		return (EOPNOTSUPP);
2713	}
2714
2715	vp = fp->f_vnode;
2716	lf.l_whence = SEEK_SET;
2717	lf.l_start = 0;
2718	lf.l_len = 0;
2719	if (uap->how & LOCK_UN) {
2720		lf.l_type = F_UNLCK;
2721		atomic_clear_int(&fp->f_flag, FHASLOCK);
2722		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2723		goto done2;
2724	}
2725	if (uap->how & LOCK_EX)
2726		lf.l_type = F_WRLCK;
2727	else if (uap->how & LOCK_SH)
2728		lf.l_type = F_RDLCK;
2729	else {
2730		error = EBADF;
2731		goto done2;
2732	}
2733	atomic_set_int(&fp->f_flag, FHASLOCK);
2734	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2735	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2736done2:
2737	fdrop(fp, td);
2738	return (error);
2739}
2740/*
2741 * Duplicate the specified descriptor to a free descriptor.
2742 */
2743int
2744dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2745    int openerror, int *indxp)
2746{
2747	struct file *fp;
2748	int error, indx;
2749
2750	KASSERT(openerror == ENODEV || openerror == ENXIO,
2751	    ("unexpected error %d in %s", openerror, __func__));
2752
2753	/*
2754	 * If the to-be-dup'd fd number is greater than the allowed number
2755	 * of file descriptors, or the fd to be dup'd has already been
2756	 * closed, then reject.
2757	 */
2758	FILEDESC_XLOCK(fdp);
2759	if ((fp = fget_locked(fdp, dfd)) == NULL) {
2760		FILEDESC_XUNLOCK(fdp);
2761		return (EBADF);
2762	}
2763
2764	error = fdalloc(td, 0, &indx);
2765	if (error != 0) {
2766		FILEDESC_XUNLOCK(fdp);
2767		return (error);
2768	}
2769
2770	/*
2771	 * There are two cases of interest here.
2772	 *
2773	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2774	 *
2775	 * For ENXIO steal away the file structure from (dfd) and store it in
2776	 * (indx).  (dfd) is effectively closed by this operation.
2777	 */
2778	switch (openerror) {
2779	case ENODEV:
2780		/*
2781		 * Check that the mode the file is being opened for is a
2782		 * subset of the mode of the existing descriptor.
2783		 */
2784		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2785			fdunused(fdp, indx);
2786			FILEDESC_XUNLOCK(fdp);
2787			return (EACCES);
2788		}
2789		fhold(fp);
2790		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2791		filecaps_copy(&fdp->fd_ofiles[dfd].fde_caps,
2792		    &fdp->fd_ofiles[indx].fde_caps);
2793		break;
2794	case ENXIO:
2795		/*
2796		 * Steal away the file pointer from dfd and stuff it into indx.
2797		 */
2798		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2799		bzero(&fdp->fd_ofiles[dfd], sizeof(fdp->fd_ofiles[dfd]));
2800		fdunused(fdp, dfd);
2801		break;
2802	}
2803	FILEDESC_XUNLOCK(fdp);
2804	*indxp = indx;
2805	return (0);
2806}
2807
2808/*
2809 * Scan all active processes and prisons to see if any of them have a current
2810 * or root directory of `olddp'. If so, replace them with the new mount point.
2811 */
2812void
2813mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2814{
2815	struct filedesc *fdp;
2816	struct prison *pr;
2817	struct proc *p;
2818	int nrele;
2819
2820	if (vrefcnt(olddp) == 1)
2821		return;
2822	nrele = 0;
2823	sx_slock(&allproc_lock);
2824	FOREACH_PROC_IN_SYSTEM(p) {
2825		fdp = fdhold(p);
2826		if (fdp == NULL)
2827			continue;
2828		FILEDESC_XLOCK(fdp);
2829		if (fdp->fd_cdir == olddp) {
2830			vref(newdp);
2831			fdp->fd_cdir = newdp;
2832			nrele++;
2833		}
2834		if (fdp->fd_rdir == olddp) {
2835			vref(newdp);
2836			fdp->fd_rdir = newdp;
2837			nrele++;
2838		}
2839		if (fdp->fd_jdir == olddp) {
2840			vref(newdp);
2841			fdp->fd_jdir = newdp;
2842			nrele++;
2843		}
2844		FILEDESC_XUNLOCK(fdp);
2845		fddrop(fdp);
2846	}
2847	sx_sunlock(&allproc_lock);
2848	if (rootvnode == olddp) {
2849		vref(newdp);
2850		rootvnode = newdp;
2851		nrele++;
2852	}
2853	mtx_lock(&prison0.pr_mtx);
2854	if (prison0.pr_root == olddp) {
2855		vref(newdp);
2856		prison0.pr_root = newdp;
2857		nrele++;
2858	}
2859	mtx_unlock(&prison0.pr_mtx);
2860	sx_slock(&allprison_lock);
2861	TAILQ_FOREACH(pr, &allprison, pr_list) {
2862		mtx_lock(&pr->pr_mtx);
2863		if (pr->pr_root == olddp) {
2864			vref(newdp);
2865			pr->pr_root = newdp;
2866			nrele++;
2867		}
2868		mtx_unlock(&pr->pr_mtx);
2869	}
2870	sx_sunlock(&allprison_lock);
2871	while (nrele--)
2872		vrele(olddp);
2873}
2874
2875struct filedesc_to_leader *
2876filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2877{
2878	struct filedesc_to_leader *fdtol;
2879
2880	fdtol = malloc(sizeof(struct filedesc_to_leader),
2881	       M_FILEDESC_TO_LEADER,
2882	       M_WAITOK);
2883	fdtol->fdl_refcount = 1;
2884	fdtol->fdl_holdcount = 0;
2885	fdtol->fdl_wakeup = 0;
2886	fdtol->fdl_leader = leader;
2887	if (old != NULL) {
2888		FILEDESC_XLOCK(fdp);
2889		fdtol->fdl_next = old->fdl_next;
2890		fdtol->fdl_prev = old;
2891		old->fdl_next = fdtol;
2892		fdtol->fdl_next->fdl_prev = fdtol;
2893		FILEDESC_XUNLOCK(fdp);
2894	} else {
2895		fdtol->fdl_next = fdtol;
2896		fdtol->fdl_prev = fdtol;
2897	}
2898	return (fdtol);
2899}
2900
2901/*
2902 * Get file structures globally.
2903 */
2904static int
2905sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2906{
2907	struct xfile xf;
2908	struct filedesc *fdp;
2909	struct file *fp;
2910	struct proc *p;
2911	int error, n;
2912
2913	error = sysctl_wire_old_buffer(req, 0);
2914	if (error != 0)
2915		return (error);
2916	if (req->oldptr == NULL) {
2917		n = 0;
2918		sx_slock(&allproc_lock);
2919		FOREACH_PROC_IN_SYSTEM(p) {
2920			if (p->p_state == PRS_NEW)
2921				continue;
2922			fdp = fdhold(p);
2923			if (fdp == NULL)
2924				continue;
2925			/* overestimates sparse tables. */
2926			if (fdp->fd_lastfile > 0)
2927				n += fdp->fd_lastfile;
2928			fddrop(fdp);
2929		}
2930		sx_sunlock(&allproc_lock);
2931		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2932	}
2933	error = 0;
2934	bzero(&xf, sizeof(xf));
2935	xf.xf_size = sizeof(xf);
2936	sx_slock(&allproc_lock);
2937	FOREACH_PROC_IN_SYSTEM(p) {
2938		PROC_LOCK(p);
2939		if (p->p_state == PRS_NEW) {
2940			PROC_UNLOCK(p);
2941			continue;
2942		}
2943		if (p_cansee(req->td, p) != 0) {
2944			PROC_UNLOCK(p);
2945			continue;
2946		}
2947		xf.xf_pid = p->p_pid;
2948		xf.xf_uid = p->p_ucred->cr_uid;
2949		PROC_UNLOCK(p);
2950		fdp = fdhold(p);
2951		if (fdp == NULL)
2952			continue;
2953		FILEDESC_SLOCK(fdp);
2954		for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2955			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
2956				continue;
2957			xf.xf_fd = n;
2958			xf.xf_file = fp;
2959			xf.xf_data = fp->f_data;
2960			xf.xf_vnode = fp->f_vnode;
2961			xf.xf_type = fp->f_type;
2962			xf.xf_count = fp->f_count;
2963			xf.xf_msgcount = 0;
2964			xf.xf_offset = foffset_get(fp);
2965			xf.xf_flag = fp->f_flag;
2966			error = SYSCTL_OUT(req, &xf, sizeof(xf));
2967			if (error)
2968				break;
2969		}
2970		FILEDESC_SUNLOCK(fdp);
2971		fddrop(fdp);
2972		if (error)
2973			break;
2974	}
2975	sx_sunlock(&allproc_lock);
2976	return (error);
2977}
2978
2979SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2980    0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2981
2982#ifdef KINFO_OFILE_SIZE
2983CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2984#endif
2985
2986#ifdef COMPAT_FREEBSD7
2987static int
2988export_vnode_for_osysctl(struct vnode *vp, int type,
2989    struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2990{
2991	int error;
2992	char *fullpath, *freepath;
2993
2994	bzero(kif, sizeof(*kif));
2995	kif->kf_structsize = sizeof(*kif);
2996
2997	vref(vp);
2998	kif->kf_fd = type;
2999	kif->kf_type = KF_TYPE_VNODE;
3000	/* This function only handles directories. */
3001	if (vp->v_type != VDIR) {
3002		vrele(vp);
3003		return (ENOTDIR);
3004	}
3005	kif->kf_vnode_type = KF_VTYPE_VDIR;
3006
3007	/*
3008	 * This is not a true file descriptor, so we set a bogus refcount
3009	 * and offset to indicate these fields should be ignored.
3010	 */
3011	kif->kf_ref_count = -1;
3012	kif->kf_offset = -1;
3013
3014	freepath = NULL;
3015	fullpath = "-";
3016	FILEDESC_SUNLOCK(fdp);
3017	vn_fullpath(curthread, vp, &fullpath, &freepath);
3018	vrele(vp);
3019	strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3020	if (freepath != NULL)
3021		free(freepath, M_TEMP);
3022	error = SYSCTL_OUT(req, kif, sizeof(*kif));
3023	FILEDESC_SLOCK(fdp);
3024	return (error);
3025}
3026
3027/*
3028 * Get per-process file descriptors for use by procstat(1), et al.
3029 */
3030static int
3031sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3032{
3033	char *fullpath, *freepath;
3034	struct kinfo_ofile *kif;
3035	struct filedesc *fdp;
3036	int error, i, *name;
3037	struct shmfd *shmfd;
3038	struct socket *so;
3039	struct vnode *vp;
3040	struct ksem *ks;
3041	struct file *fp;
3042	struct proc *p;
3043	struct tty *tp;
3044
3045	name = (int *)arg1;
3046	error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3047	if (error != 0)
3048		return (error);
3049	fdp = fdhold(p);
3050	PROC_UNLOCK(p);
3051	if (fdp == NULL)
3052		return (ENOENT);
3053	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3054	FILEDESC_SLOCK(fdp);
3055	if (fdp->fd_cdir != NULL)
3056		export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3057				fdp, req);
3058	if (fdp->fd_rdir != NULL)
3059		export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3060				fdp, req);
3061	if (fdp->fd_jdir != NULL)
3062		export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3063				fdp, req);
3064	for (i = 0; fdp->fd_refcnt > 0 && i < fdp->fd_nfiles; i++) {
3065		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3066			continue;
3067		bzero(kif, sizeof(*kif));
3068		kif->kf_structsize = sizeof(*kif);
3069		ks = NULL;
3070		vp = NULL;
3071		so = NULL;
3072		tp = NULL;
3073		shmfd = NULL;
3074		kif->kf_fd = i;
3075
3076		switch (fp->f_type) {
3077		case DTYPE_VNODE:
3078			kif->kf_type = KF_TYPE_VNODE;
3079			vp = fp->f_vnode;
3080			break;
3081
3082		case DTYPE_SOCKET:
3083			kif->kf_type = KF_TYPE_SOCKET;
3084			so = fp->f_data;
3085			break;
3086
3087		case DTYPE_PIPE:
3088			kif->kf_type = KF_TYPE_PIPE;
3089			break;
3090
3091		case DTYPE_FIFO:
3092			kif->kf_type = KF_TYPE_FIFO;
3093			vp = fp->f_vnode;
3094			break;
3095
3096		case DTYPE_KQUEUE:
3097			kif->kf_type = KF_TYPE_KQUEUE;
3098			break;
3099
3100		case DTYPE_CRYPTO:
3101			kif->kf_type = KF_TYPE_CRYPTO;
3102			break;
3103
3104		case DTYPE_MQUEUE:
3105			kif->kf_type = KF_TYPE_MQUEUE;
3106			break;
3107
3108		case DTYPE_SHM:
3109			kif->kf_type = KF_TYPE_SHM;
3110			shmfd = fp->f_data;
3111			break;
3112
3113		case DTYPE_SEM:
3114			kif->kf_type = KF_TYPE_SEM;
3115			ks = fp->f_data;
3116			break;
3117
3118		case DTYPE_PTS:
3119			kif->kf_type = KF_TYPE_PTS;
3120			tp = fp->f_data;
3121			break;
3122
3123#ifdef PROCDESC
3124		case DTYPE_PROCDESC:
3125			kif->kf_type = KF_TYPE_PROCDESC;
3126			break;
3127#endif
3128
3129		default:
3130			kif->kf_type = KF_TYPE_UNKNOWN;
3131			break;
3132		}
3133		kif->kf_ref_count = fp->f_count;
3134		if (fp->f_flag & FREAD)
3135			kif->kf_flags |= KF_FLAG_READ;
3136		if (fp->f_flag & FWRITE)
3137			kif->kf_flags |= KF_FLAG_WRITE;
3138		if (fp->f_flag & FAPPEND)
3139			kif->kf_flags |= KF_FLAG_APPEND;
3140		if (fp->f_flag & FASYNC)
3141			kif->kf_flags |= KF_FLAG_ASYNC;
3142		if (fp->f_flag & FFSYNC)
3143			kif->kf_flags |= KF_FLAG_FSYNC;
3144		if (fp->f_flag & FNONBLOCK)
3145			kif->kf_flags |= KF_FLAG_NONBLOCK;
3146		if (fp->f_flag & O_DIRECT)
3147			kif->kf_flags |= KF_FLAG_DIRECT;
3148		if (fp->f_flag & FHASLOCK)
3149			kif->kf_flags |= KF_FLAG_HASLOCK;
3150		kif->kf_offset = foffset_get(fp);
3151		if (vp != NULL) {
3152			vref(vp);
3153			switch (vp->v_type) {
3154			case VNON:
3155				kif->kf_vnode_type = KF_VTYPE_VNON;
3156				break;
3157			case VREG:
3158				kif->kf_vnode_type = KF_VTYPE_VREG;
3159				break;
3160			case VDIR:
3161				kif->kf_vnode_type = KF_VTYPE_VDIR;
3162				break;
3163			case VBLK:
3164				kif->kf_vnode_type = KF_VTYPE_VBLK;
3165				break;
3166			case VCHR:
3167				kif->kf_vnode_type = KF_VTYPE_VCHR;
3168				break;
3169			case VLNK:
3170				kif->kf_vnode_type = KF_VTYPE_VLNK;
3171				break;
3172			case VSOCK:
3173				kif->kf_vnode_type = KF_VTYPE_VSOCK;
3174				break;
3175			case VFIFO:
3176				kif->kf_vnode_type = KF_VTYPE_VFIFO;
3177				break;
3178			case VBAD:
3179				kif->kf_vnode_type = KF_VTYPE_VBAD;
3180				break;
3181			default:
3182				kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3183				break;
3184			}
3185			/*
3186			 * It is OK to drop the filedesc lock here as we will
3187			 * re-validate and re-evaluate its properties when
3188			 * the loop continues.
3189			 */
3190			freepath = NULL;
3191			fullpath = "-";
3192			FILEDESC_SUNLOCK(fdp);
3193			vn_fullpath(curthread, vp, &fullpath, &freepath);
3194			vrele(vp);
3195			strlcpy(kif->kf_path, fullpath,
3196			    sizeof(kif->kf_path));
3197			if (freepath != NULL)
3198				free(freepath, M_TEMP);
3199			FILEDESC_SLOCK(fdp);
3200		}
3201		if (so != NULL) {
3202			struct sockaddr *sa;
3203
3204			if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3205			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3206				bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3207				free(sa, M_SONAME);
3208			}
3209			if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3210			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3211				bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3212				free(sa, M_SONAME);
3213			}
3214			kif->kf_sock_domain =
3215			    so->so_proto->pr_domain->dom_family;
3216			kif->kf_sock_type = so->so_type;
3217			kif->kf_sock_protocol = so->so_proto->pr_protocol;
3218		}
3219		if (tp != NULL) {
3220			strlcpy(kif->kf_path, tty_devname(tp),
3221			    sizeof(kif->kf_path));
3222		}
3223		if (shmfd != NULL)
3224			shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3225		if (ks != NULL && ksem_info != NULL)
3226			ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3227		error = SYSCTL_OUT(req, kif, sizeof(*kif));
3228		if (error)
3229			break;
3230	}
3231	FILEDESC_SUNLOCK(fdp);
3232	fddrop(fdp);
3233	free(kif, M_TEMP);
3234	return (0);
3235}
3236
3237static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
3238    sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3239#endif	/* COMPAT_FREEBSD7 */
3240
3241#ifdef KINFO_FILE_SIZE
3242CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3243#endif
3244
3245struct export_fd_buf {
3246	struct filedesc		*fdp;
3247	struct sbuf 		*sb;
3248	ssize_t			remainder;
3249	struct kinfo_file	kif;
3250};
3251
3252static int
3253export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3254    int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3255{
3256	struct {
3257		int	fflag;
3258		int	kf_fflag;
3259	} fflags_table[] = {
3260		{ FAPPEND, KF_FLAG_APPEND },
3261		{ FASYNC, KF_FLAG_ASYNC },
3262		{ FFSYNC, KF_FLAG_FSYNC },
3263		{ FHASLOCK, KF_FLAG_HASLOCK },
3264		{ FNONBLOCK, KF_FLAG_NONBLOCK },
3265		{ FREAD, KF_FLAG_READ },
3266		{ FWRITE, KF_FLAG_WRITE },
3267		{ O_CREAT, KF_FLAG_CREAT },
3268		{ O_DIRECT, KF_FLAG_DIRECT },
3269		{ O_EXCL, KF_FLAG_EXCL },
3270		{ O_EXEC, KF_FLAG_EXEC },
3271		{ O_EXLOCK, KF_FLAG_EXLOCK },
3272		{ O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3273		{ O_SHLOCK, KF_FLAG_SHLOCK },
3274		{ O_TRUNC, KF_FLAG_TRUNC }
3275	};
3276#define	NFFLAGS	(sizeof(fflags_table) / sizeof(*fflags_table))
3277	struct kinfo_file *kif;
3278	struct vnode *vp;
3279	int error, locked;
3280	unsigned int i;
3281
3282	if (efbuf->remainder == 0)
3283		return (0);
3284	kif = &efbuf->kif;
3285	bzero(kif, sizeof(*kif));
3286	locked = efbuf->fdp != NULL;
3287	switch (type) {
3288	case KF_TYPE_FIFO:
3289	case KF_TYPE_VNODE:
3290		if (locked) {
3291			FILEDESC_SUNLOCK(efbuf->fdp);
3292			locked = 0;
3293		}
3294		vp = (struct vnode *)data;
3295		error = fill_vnode_info(vp, kif);
3296		vrele(vp);
3297		break;
3298	case KF_TYPE_SOCKET:
3299		error = fill_socket_info((struct socket *)data, kif);
3300		break;
3301	case KF_TYPE_PIPE:
3302		error = fill_pipe_info((struct pipe *)data, kif);
3303		break;
3304	case KF_TYPE_PTS:
3305		error = fill_pts_info((struct tty *)data, kif);
3306		break;
3307	case KF_TYPE_PROCDESC:
3308		error = fill_procdesc_info((struct procdesc *)data, kif);
3309		break;
3310	case KF_TYPE_SEM:
3311		error = fill_sem_info((struct file *)data, kif);
3312		break;
3313	case KF_TYPE_SHM:
3314		error = fill_shm_info((struct file *)data, kif);
3315		break;
3316	default:
3317		error = 0;
3318	}
3319	if (error == 0)
3320		kif->kf_status |= KF_ATTR_VALID;
3321
3322	/*
3323	 * Translate file access flags.
3324	 */
3325	for (i = 0; i < NFFLAGS; i++)
3326		if (fflags & fflags_table[i].fflag)
3327			kif->kf_flags |=  fflags_table[i].kf_fflag;
3328	if (rightsp != NULL)
3329		kif->kf_cap_rights = *rightsp;
3330	else
3331		cap_rights_init(&kif->kf_cap_rights);
3332	kif->kf_fd = fd;
3333	kif->kf_type = type;
3334	kif->kf_ref_count = refcnt;
3335	kif->kf_offset = offset;
3336	/* Pack record size down */
3337	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3338	    strlen(kif->kf_path) + 1;
3339	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3340	if (efbuf->remainder != -1) {
3341		if (efbuf->remainder < kif->kf_structsize) {
3342			/* Terminate export. */
3343			efbuf->remainder = 0;
3344			if (efbuf->fdp != NULL && !locked)
3345				FILEDESC_SLOCK(efbuf->fdp);
3346			return (0);
3347		}
3348		efbuf->remainder -= kif->kf_structsize;
3349	}
3350	if (locked)
3351		FILEDESC_SUNLOCK(efbuf->fdp);
3352	error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3353	if (efbuf->fdp != NULL)
3354		FILEDESC_SLOCK(efbuf->fdp);
3355	return (error);
3356}
3357
3358/*
3359 * Store a process file descriptor information to sbuf.
3360 *
3361 * Takes a locked proc as argument, and returns with the proc unlocked.
3362 */
3363int
3364kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
3365{
3366	struct file *fp;
3367	struct filedesc *fdp;
3368	struct export_fd_buf *efbuf;
3369	struct vnode *cttyvp, *textvp, *tracevp;
3370	int64_t offset;
3371	void *data;
3372	int error, i;
3373	int type, refcnt, fflags;
3374	cap_rights_t rights;
3375
3376	PROC_LOCK_ASSERT(p, MA_OWNED);
3377
3378	/* ktrace vnode */
3379	tracevp = p->p_tracevp;
3380	if (tracevp != NULL)
3381		vref(tracevp);
3382	/* text vnode */
3383	textvp = p->p_textvp;
3384	if (textvp != NULL)
3385		vref(textvp);
3386	/* Controlling tty. */
3387	cttyvp = NULL;
3388	if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3389		cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3390		if (cttyvp != NULL)
3391			vref(cttyvp);
3392	}
3393	fdp = fdhold(p);
3394	PROC_UNLOCK(p);
3395	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3396	efbuf->fdp = NULL;
3397	efbuf->sb = sb;
3398	efbuf->remainder = maxlen;
3399	if (tracevp != NULL)
3400		export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3401		    FREAD | FWRITE, -1, -1, NULL, efbuf);
3402	if (textvp != NULL)
3403		export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3404		    FREAD, -1, -1, NULL, efbuf);
3405	if (cttyvp != NULL)
3406		export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3407		    FREAD | FWRITE, -1, -1, NULL, efbuf);
3408	error = 0;
3409	if (fdp == NULL)
3410		goto fail;
3411	efbuf->fdp = fdp;
3412	FILEDESC_SLOCK(fdp);
3413	/* working directory */
3414	if (fdp->fd_cdir != NULL) {
3415		vref(fdp->fd_cdir);
3416		data = fdp->fd_cdir;
3417		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3418		    FREAD, -1, -1, NULL, efbuf);
3419	}
3420	/* root directory */
3421	if (fdp->fd_rdir != NULL) {
3422		vref(fdp->fd_rdir);
3423		data = fdp->fd_rdir;
3424		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3425		    FREAD, -1, -1, NULL, efbuf);
3426	}
3427	/* jail directory */
3428	if (fdp->fd_jdir != NULL) {
3429		vref(fdp->fd_jdir);
3430		data = fdp->fd_jdir;
3431		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3432		    FREAD, -1, -1, NULL, efbuf);
3433	}
3434	for (i = 0; fdp->fd_refcnt > 0 && i < fdp->fd_nfiles; i++) {
3435		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3436			continue;
3437		data = NULL;
3438#ifdef CAPABILITIES
3439		rights = *cap_rights(fdp, i);
3440#else /* !CAPABILITIES */
3441		cap_rights_init(&rights);
3442#endif
3443		switch (fp->f_type) {
3444		case DTYPE_VNODE:
3445			type = KF_TYPE_VNODE;
3446			vref(fp->f_vnode);
3447			data = fp->f_vnode;
3448			break;
3449
3450		case DTYPE_SOCKET:
3451			type = KF_TYPE_SOCKET;
3452			data = fp->f_data;
3453			break;
3454
3455		case DTYPE_PIPE:
3456			type = KF_TYPE_PIPE;
3457			data = fp->f_data;
3458			break;
3459
3460		case DTYPE_FIFO:
3461			type = KF_TYPE_FIFO;
3462			vref(fp->f_vnode);
3463			data = fp->f_vnode;
3464			break;
3465
3466		case DTYPE_KQUEUE:
3467			type = KF_TYPE_KQUEUE;
3468			break;
3469
3470		case DTYPE_CRYPTO:
3471			type = KF_TYPE_CRYPTO;
3472			break;
3473
3474		case DTYPE_MQUEUE:
3475			type = KF_TYPE_MQUEUE;
3476			break;
3477
3478		case DTYPE_SHM:
3479			type = KF_TYPE_SHM;
3480			data = fp;
3481			break;
3482
3483		case DTYPE_SEM:
3484			type = KF_TYPE_SEM;
3485			data = fp;
3486			break;
3487
3488		case DTYPE_PTS:
3489			type = KF_TYPE_PTS;
3490			data = fp->f_data;
3491			break;
3492
3493#ifdef PROCDESC
3494		case DTYPE_PROCDESC:
3495			type = KF_TYPE_PROCDESC;
3496			data = fp->f_data;
3497			break;
3498#endif
3499
3500		default:
3501			type = KF_TYPE_UNKNOWN;
3502			break;
3503		}
3504		refcnt = fp->f_count;
3505		fflags = fp->f_flag;
3506		offset = foffset_get(fp);
3507
3508		/*
3509		 * Create sysctl entry.
3510		 * It is OK to drop the filedesc lock here as we will
3511		 * re-validate and re-evaluate its properties when
3512		 * the loop continues.
3513		 */
3514		error = export_fd_to_sb(data, type, i, fflags, refcnt,
3515		    offset, &rights, efbuf);
3516		if (error != 0)
3517			break;
3518	}
3519	FILEDESC_SUNLOCK(fdp);
3520	fddrop(fdp);
3521fail:
3522	free(efbuf, M_TEMP);
3523	return (error);
3524}
3525
3526#define FILEDESC_SBUF_SIZE	(sizeof(struct kinfo_file) * 5)
3527
3528/*
3529 * Get per-process file descriptors for use by procstat(1), et al.
3530 */
3531static int
3532sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3533{
3534	struct sbuf sb;
3535	struct proc *p;
3536	ssize_t maxlen;
3537	int error, error2, *name;
3538
3539	name = (int *)arg1;
3540
3541	sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3542	error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3543	if (error != 0) {
3544		sbuf_delete(&sb);
3545		return (error);
3546	}
3547	maxlen = req->oldptr != NULL ? req->oldlen : -1;
3548	error = kern_proc_filedesc_out(p, &sb, maxlen);
3549	error2 = sbuf_finish(&sb);
3550	sbuf_delete(&sb);
3551	return (error != 0 ? error : error2);
3552}
3553
3554int
3555vntype_to_kinfo(int vtype)
3556{
3557	struct {
3558		int	vtype;
3559		int	kf_vtype;
3560	} vtypes_table[] = {
3561		{ VBAD, KF_VTYPE_VBAD },
3562		{ VBLK, KF_VTYPE_VBLK },
3563		{ VCHR, KF_VTYPE_VCHR },
3564		{ VDIR, KF_VTYPE_VDIR },
3565		{ VFIFO, KF_VTYPE_VFIFO },
3566		{ VLNK, KF_VTYPE_VLNK },
3567		{ VNON, KF_VTYPE_VNON },
3568		{ VREG, KF_VTYPE_VREG },
3569		{ VSOCK, KF_VTYPE_VSOCK }
3570	};
3571#define	NVTYPES	(sizeof(vtypes_table) / sizeof(*vtypes_table))
3572	unsigned int i;
3573
3574	/*
3575	 * Perform vtype translation.
3576	 */
3577	for (i = 0; i < NVTYPES; i++)
3578		if (vtypes_table[i].vtype == vtype)
3579			break;
3580	if (i < NVTYPES)
3581		return (vtypes_table[i].kf_vtype);
3582
3583	return (KF_VTYPE_UNKNOWN);
3584}
3585
3586static int
3587fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3588{
3589	struct vattr va;
3590	char *fullpath, *freepath;
3591	int error;
3592
3593	if (vp == NULL)
3594		return (1);
3595	kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3596	freepath = NULL;
3597	fullpath = "-";
3598	error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3599	if (error == 0) {
3600		strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3601	}
3602	if (freepath != NULL)
3603		free(freepath, M_TEMP);
3604
3605	/*
3606	 * Retrieve vnode attributes.
3607	 */
3608	va.va_fsid = VNOVAL;
3609	va.va_rdev = NODEV;
3610	vn_lock(vp, LK_SHARED | LK_RETRY);
3611	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3612	VOP_UNLOCK(vp, 0);
3613	if (error != 0)
3614		return (error);
3615	if (va.va_fsid != VNOVAL)
3616		kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3617	else
3618		kif->kf_un.kf_file.kf_file_fsid =
3619		    vp->v_mount->mnt_stat.f_fsid.val[0];
3620	kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3621	kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3622	kif->kf_un.kf_file.kf_file_size = va.va_size;
3623	kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3624	return (0);
3625}
3626
3627static int
3628fill_socket_info(struct socket *so, struct kinfo_file *kif)
3629{
3630	struct sockaddr *sa;
3631	struct inpcb *inpcb;
3632	struct unpcb *unpcb;
3633	int error;
3634
3635	if (so == NULL)
3636		return (1);
3637	kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3638	kif->kf_sock_type = so->so_type;
3639	kif->kf_sock_protocol = so->so_proto->pr_protocol;
3640	kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3641	switch(kif->kf_sock_domain) {
3642	case AF_INET:
3643	case AF_INET6:
3644		if (kif->kf_sock_protocol == IPPROTO_TCP) {
3645			if (so->so_pcb != NULL) {
3646				inpcb = (struct inpcb *)(so->so_pcb);
3647				kif->kf_un.kf_sock.kf_sock_inpcb =
3648				    (uintptr_t)inpcb->inp_ppcb;
3649			}
3650		}
3651		break;
3652	case AF_UNIX:
3653		if (so->so_pcb != NULL) {
3654			unpcb = (struct unpcb *)(so->so_pcb);
3655			if (unpcb->unp_conn) {
3656				kif->kf_un.kf_sock.kf_sock_unpconn =
3657				    (uintptr_t)unpcb->unp_conn;
3658				kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3659				    so->so_rcv.sb_state;
3660				kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3661				    so->so_snd.sb_state;
3662			}
3663		}
3664		break;
3665	}
3666	error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3667	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3668		bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3669		free(sa, M_SONAME);
3670	}
3671	error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3672	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3673		bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3674		free(sa, M_SONAME);
3675	}
3676	strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3677	    sizeof(kif->kf_path));
3678	return (0);
3679}
3680
3681static int
3682fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3683{
3684
3685	if (tp == NULL)
3686		return (1);
3687	kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3688	strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3689	return (0);
3690}
3691
3692static int
3693fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3694{
3695
3696	if (pi == NULL)
3697		return (1);
3698	kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3699	kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3700	kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3701	return (0);
3702}
3703
3704static int
3705fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3706{
3707
3708	if (pdp == NULL)
3709		return (1);
3710	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3711	return (0);
3712}
3713
3714static int
3715fill_sem_info(struct file *fp, struct kinfo_file *kif)
3716{
3717	struct thread *td;
3718	struct stat sb;
3719
3720	td = curthread;
3721	if (fp->f_data == NULL)
3722		return (1);
3723	if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3724		return (1);
3725	if (ksem_info == NULL)
3726		return (1);
3727	ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3728	    &kif->kf_un.kf_sem.kf_sem_value);
3729	kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3730	return (0);
3731}
3732
3733static int
3734fill_shm_info(struct file *fp, struct kinfo_file *kif)
3735{
3736	struct thread *td;
3737	struct stat sb;
3738
3739	td = curthread;
3740	if (fp->f_data == NULL)
3741		return (1);
3742	if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3743		return (1);
3744	shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3745	kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3746	kif->kf_un.kf_file.kf_file_size = sb.st_size;
3747	return (0);
3748}
3749
3750static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3751    sysctl_kern_proc_filedesc, "Process filedesc entries");
3752
3753#ifdef DDB
3754/*
3755 * For the purposes of debugging, generate a human-readable string for the
3756 * file type.
3757 */
3758static const char *
3759file_type_to_name(short type)
3760{
3761
3762	switch (type) {
3763	case 0:
3764		return ("zero");
3765	case DTYPE_VNODE:
3766		return ("vnod");
3767	case DTYPE_SOCKET:
3768		return ("sock");
3769	case DTYPE_PIPE:
3770		return ("pipe");
3771	case DTYPE_FIFO:
3772		return ("fifo");
3773	case DTYPE_KQUEUE:
3774		return ("kque");
3775	case DTYPE_CRYPTO:
3776		return ("crpt");
3777	case DTYPE_MQUEUE:
3778		return ("mque");
3779	case DTYPE_SHM:
3780		return ("shm");
3781	case DTYPE_SEM:
3782		return ("ksem");
3783	default:
3784		return ("unkn");
3785	}
3786}
3787
3788/*
3789 * For the purposes of debugging, identify a process (if any, perhaps one of
3790 * many) that references the passed file in its file descriptor array. Return
3791 * NULL if none.
3792 */
3793static struct proc *
3794file_to_first_proc(struct file *fp)
3795{
3796	struct filedesc *fdp;
3797	struct proc *p;
3798	int n;
3799
3800	FOREACH_PROC_IN_SYSTEM(p) {
3801		if (p->p_state == PRS_NEW)
3802			continue;
3803		fdp = p->p_fd;
3804		if (fdp == NULL)
3805			continue;
3806		for (n = 0; n < fdp->fd_nfiles; n++) {
3807			if (fp == fdp->fd_ofiles[n].fde_file)
3808				return (p);
3809		}
3810	}
3811	return (NULL);
3812}
3813
3814static void
3815db_print_file(struct file *fp, int header)
3816{
3817	struct proc *p;
3818
3819	if (header)
3820		db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3821		    "File", "Type", "Data", "Flag", "GCFl", "Count",
3822		    "MCount", "Vnode", "FPID", "FCmd");
3823	p = file_to_first_proc(fp);
3824	db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3825	    file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3826	    0, fp->f_count, 0, fp->f_vnode,
3827	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3828}
3829
3830DB_SHOW_COMMAND(file, db_show_file)
3831{
3832	struct file *fp;
3833
3834	if (!have_addr) {
3835		db_printf("usage: show file <addr>\n");
3836		return;
3837	}
3838	fp = (struct file *)addr;
3839	db_print_file(fp, 1);
3840}
3841
3842DB_SHOW_COMMAND(files, db_show_files)
3843{
3844	struct filedesc *fdp;
3845	struct file *fp;
3846	struct proc *p;
3847	int header;
3848	int n;
3849
3850	header = 1;
3851	FOREACH_PROC_IN_SYSTEM(p) {
3852		if (p->p_state == PRS_NEW)
3853			continue;
3854		if ((fdp = p->p_fd) == NULL)
3855			continue;
3856		for (n = 0; n < fdp->fd_nfiles; ++n) {
3857			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3858				continue;
3859			db_print_file(fp, header);
3860			header = 0;
3861		}
3862	}
3863}
3864#endif
3865
3866SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3867    &maxfilesperproc, 0, "Maximum files allowed open per process");
3868
3869SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3870    &maxfiles, 0, "Maximum number of files");
3871
3872SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3873    __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3874
3875/* ARGSUSED*/
3876static void
3877filelistinit(void *dummy)
3878{
3879
3880	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3881	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3882	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3883	mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3884}
3885SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3886
3887/*-------------------------------------------------------------------*/
3888
3889static int
3890badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3891    int flags, struct thread *td)
3892{
3893
3894	return (EBADF);
3895}
3896
3897static int
3898badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3899    struct thread *td)
3900{
3901
3902	return (EINVAL);
3903}
3904
3905static int
3906badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3907    struct thread *td)
3908{
3909
3910	return (EBADF);
3911}
3912
3913static int
3914badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3915    struct thread *td)
3916{
3917
3918	return (0);
3919}
3920
3921static int
3922badfo_kqfilter(struct file *fp, struct knote *kn)
3923{
3924
3925	return (EBADF);
3926}
3927
3928static int
3929badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3930    struct thread *td)
3931{
3932
3933	return (EBADF);
3934}
3935
3936static int
3937badfo_close(struct file *fp, struct thread *td)
3938{
3939
3940	return (EBADF);
3941}
3942
3943static int
3944badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3945    struct thread *td)
3946{
3947
3948	return (EBADF);
3949}
3950
3951static int
3952badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3953    struct thread *td)
3954{
3955
3956	return (EBADF);
3957}
3958
3959static int
3960badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3961    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3962    int kflags, struct thread *td)
3963{
3964
3965	return (EBADF);
3966}
3967
3968struct fileops badfileops = {
3969	.fo_read = badfo_readwrite,
3970	.fo_write = badfo_readwrite,
3971	.fo_truncate = badfo_truncate,
3972	.fo_ioctl = badfo_ioctl,
3973	.fo_poll = badfo_poll,
3974	.fo_kqfilter = badfo_kqfilter,
3975	.fo_stat = badfo_stat,
3976	.fo_close = badfo_close,
3977	.fo_chmod = badfo_chmod,
3978	.fo_chown = badfo_chown,
3979	.fo_sendfile = badfo_sendfile,
3980};
3981
3982int
3983invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3984    struct thread *td)
3985{
3986
3987	return (EINVAL);
3988}
3989
3990int
3991invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3992    struct thread *td)
3993{
3994
3995	return (EINVAL);
3996}
3997
3998int
3999invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4000    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4001    int kflags, struct thread *td)
4002{
4003
4004	return (EINVAL);
4005}
4006
4007/*-------------------------------------------------------------------*/
4008
4009/*
4010 * File Descriptor pseudo-device driver (/dev/fd/).
4011 *
4012 * Opening minor device N dup()s the file (if any) connected to file
4013 * descriptor N belonging to the calling process.  Note that this driver
4014 * consists of only the ``open()'' routine, because all subsequent
4015 * references to this file will be direct to the other driver.
4016 *
4017 * XXX: we could give this one a cloning event handler if necessary.
4018 */
4019
4020/* ARGSUSED */
4021static int
4022fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4023{
4024
4025	/*
4026	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4027	 * the file descriptor being sought for duplication. The error
4028	 * return ensures that the vnode for this device will be released
4029	 * by vn_open. Open will detect this special error and take the
4030	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4031	 * will simply report the error.
4032	 */
4033	td->td_dupfd = dev2unit(dev);
4034	return (ENODEV);
4035}
4036
4037static struct cdevsw fildesc_cdevsw = {
4038	.d_version =	D_VERSION,
4039	.d_open =	fdopen,
4040	.d_name =	"FD",
4041};
4042
4043static void
4044fildesc_drvinit(void *unused)
4045{
4046	struct cdev *dev;
4047
4048	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4049	    UID_ROOT, GID_WHEEL, 0666, "fd/0");
4050	make_dev_alias(dev, "stdin");
4051	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4052	    UID_ROOT, GID_WHEEL, 0666, "fd/1");
4053	make_dev_alias(dev, "stdout");
4054	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4055	    UID_ROOT, GID_WHEEL, 0666, "fd/2");
4056	make_dev_alias(dev, "stderr");
4057}
4058
4059SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
4060