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