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