xref: /freebsd/sys/kern/kern_descrip.c (revision 0440b3d2cbf83afb55209a9938b31a48912f222c)
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 
37 #include "opt_capsicum.h"
38 #include "opt_ddb.h"
39 #include "opt_ktrace.h"
40 
41 #include <sys/systm.h>
42 #include <sys/capsicum.h>
43 #include <sys/conf.h>
44 #include <sys/fcntl.h>
45 #include <sys/file.h>
46 #include <sys/filedesc.h>
47 #include <sys/filio.h>
48 #include <sys/jail.h>
49 #include <sys/kernel.h>
50 #include <sys/limits.h>
51 #include <sys/lock.h>
52 #include <sys/malloc.h>
53 #include <sys/mount.h>
54 #include <sys/mutex.h>
55 #include <sys/namei.h>
56 #include <sys/selinfo.h>
57 #include <sys/poll.h>
58 #include <sys/priv.h>
59 #include <sys/proc.h>
60 #include <sys/protosw.h>
61 #include <sys/racct.h>
62 #include <sys/resourcevar.h>
63 #include <sys/sbuf.h>
64 #include <sys/signalvar.h>
65 #include <sys/kdb.h>
66 #include <sys/smr.h>
67 #include <sys/stat.h>
68 #include <sys/sx.h>
69 #include <sys/syscallsubr.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysproto.h>
72 #include <sys/unistd.h>
73 #include <sys/user.h>
74 #include <sys/vnode.h>
75 #include <sys/ktrace.h>
76 
77 #include <net/vnet.h>
78 
79 #include <security/audit/audit.h>
80 
81 #include <vm/uma.h>
82 #include <vm/vm.h>
83 
84 #include <ddb/ddb.h>
85 
86 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
87 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
88 static MALLOC_DEFINE(M_PWDDESC, "pwddesc", "Pwd descriptors");
89 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
90     "file desc to leader structures");
91 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
92 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
93 
94 MALLOC_DECLARE(M_FADVISE);
95 
96 static __read_mostly uma_zone_t file_zone;
97 static __read_mostly uma_zone_t filedesc0_zone;
98 __read_mostly uma_zone_t pwd_zone;
99 VFS_SMR_DECLARE;
100 
101 static int	closefp(struct filedesc *fdp, int fd, struct file *fp,
102 		    struct thread *td, bool holdleaders, bool audit);
103 static void	export_file_to_kinfo(struct file *fp, int fd,
104 		    cap_rights_t *rightsp, struct kinfo_file *kif,
105 		    struct filedesc *fdp, int flags);
106 static int	fd_first_free(struct filedesc *fdp, int low, int size);
107 static void	fdgrowtable(struct filedesc *fdp, int nfd);
108 static void	fdgrowtable_exp(struct filedesc *fdp, int nfd);
109 static void	fdunused(struct filedesc *fdp, int fd);
110 static void	fdused(struct filedesc *fdp, int fd);
111 static int	fget_unlocked_seq(struct thread *td, int fd,
112 		    const cap_rights_t *needrightsp, struct file **fpp,
113 		    seqc_t *seqp);
114 static int	getmaxfd(struct thread *td);
115 static u_long	*filecaps_copy_prep(const struct filecaps *src);
116 static void	filecaps_copy_finish(const struct filecaps *src,
117 		    struct filecaps *dst, u_long *ioctls);
118 static u_long 	*filecaps_free_prep(struct filecaps *fcaps);
119 static void	filecaps_free_finish(u_long *ioctls);
120 
121 static struct pwd *pwd_alloc(void);
122 
123 /*
124  * Each process has:
125  *
126  * - An array of open file descriptors (fd_ofiles)
127  * - An array of file flags (fd_ofileflags)
128  * - A bitmap recording which descriptors are in use (fd_map)
129  *
130  * A process starts out with NDFILE descriptors.  The value of NDFILE has
131  * been selected based the historical limit of 20 open files, and an
132  * assumption that the majority of processes, especially short-lived
133  * processes like shells, will never need more.
134  *
135  * If this initial allocation is exhausted, a larger descriptor table and
136  * map are allocated dynamically, and the pointers in the process's struct
137  * filedesc are updated to point to those.  This is repeated every time
138  * the process runs out of file descriptors (provided it hasn't hit its
139  * resource limit).
140  *
141  * Since threads may hold references to individual descriptor table
142  * entries, the tables are never freed.  Instead, they are placed on a
143  * linked list and freed only when the struct filedesc is released.
144  */
145 #define NDFILE		20
146 #define NDSLOTSIZE	sizeof(NDSLOTTYPE)
147 #define	NDENTRIES	(NDSLOTSIZE * __CHAR_BIT)
148 #define NDSLOT(x)	((x) / NDENTRIES)
149 #define NDBIT(x)	((NDSLOTTYPE)1 << ((x) % NDENTRIES))
150 #define	NDSLOTS(x)	(((x) + NDENTRIES - 1) / NDENTRIES)
151 
152 #define	FILEDESC_FOREACH_FDE(fdp, _iterator, _fde)				\
153 	struct filedesc *_fdp = (fdp);						\
154 	int _lastfile = fdlastfile_single(_fdp);				\
155 	for (_iterator = 0; _iterator <= _lastfile; _iterator++)		\
156 		if ((_fde = &_fdp->fd_ofiles[_iterator])->fde_file != NULL)
157 
158 #define	FILEDESC_FOREACH_FP(fdp, _iterator, _fp)				\
159 	struct filedesc *_fdp = (fdp);						\
160 	int _lastfile = fdlastfile_single(_fdp);				\
161 	for (_iterator = 0; _iterator <= _lastfile; _iterator++)		\
162 		if ((_fp = _fdp->fd_ofiles[_iterator].fde_file) != NULL)
163 
164 /*
165  * SLIST entry used to keep track of ofiles which must be reclaimed when
166  * the process exits.
167  */
168 struct freetable {
169 	struct fdescenttbl *ft_table;
170 	SLIST_ENTRY(freetable) ft_next;
171 };
172 
173 /*
174  * Initial allocation: a filedesc structure + the head of SLIST used to
175  * keep track of old ofiles + enough space for NDFILE descriptors.
176  */
177 
178 struct fdescenttbl0 {
179 	int	fdt_nfiles;
180 	struct	filedescent fdt_ofiles[NDFILE];
181 };
182 
183 struct filedesc0 {
184 	struct filedesc fd_fd;
185 	SLIST_HEAD(, freetable) fd_free;
186 	struct	fdescenttbl0 fd_dfiles;
187 	NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
188 };
189 
190 /*
191  * Descriptor management.
192  */
193 static int __exclusive_cache_line openfiles; /* actual number of open files */
194 struct mtx sigio_lock;		/* mtx to protect pointers to sigio */
195 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
196 
197 /*
198  * If low >= size, just return low. Otherwise find the first zero bit in the
199  * given bitmap, starting at low and not exceeding size - 1. Return size if
200  * not found.
201  */
202 static int
203 fd_first_free(struct filedesc *fdp, int low, int size)
204 {
205 	NDSLOTTYPE *map = fdp->fd_map;
206 	NDSLOTTYPE mask;
207 	int off, maxoff;
208 
209 	if (low >= size)
210 		return (low);
211 
212 	off = NDSLOT(low);
213 	if (low % NDENTRIES) {
214 		mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
215 		if ((mask &= ~map[off]) != 0UL)
216 			return (off * NDENTRIES + ffsl(mask) - 1);
217 		++off;
218 	}
219 	for (maxoff = NDSLOTS(size); off < maxoff; ++off)
220 		if (map[off] != ~0UL)
221 			return (off * NDENTRIES + ffsl(~map[off]) - 1);
222 	return (size);
223 }
224 
225 /*
226  * Find the last used fd.
227  *
228  * Call this variant if fdp can't be modified by anyone else (e.g, during exec).
229  * Otherwise use fdlastfile.
230  */
231 int
232 fdlastfile_single(struct filedesc *fdp)
233 {
234 	NDSLOTTYPE *map = fdp->fd_map;
235 	int off, minoff;
236 
237 	off = NDSLOT(fdp->fd_nfiles - 1);
238 	for (minoff = NDSLOT(0); off >= minoff; --off)
239 		if (map[off] != 0)
240 			return (off * NDENTRIES + flsl(map[off]) - 1);
241 	return (-1);
242 }
243 
244 int
245 fdlastfile(struct filedesc *fdp)
246 {
247 
248 	FILEDESC_LOCK_ASSERT(fdp);
249 	return (fdlastfile_single(fdp));
250 }
251 
252 static int
253 fdisused(struct filedesc *fdp, int fd)
254 {
255 
256 	KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
257 	    ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
258 
259 	return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
260 }
261 
262 /*
263  * Mark a file descriptor as used.
264  */
265 static void
266 fdused_init(struct filedesc *fdp, int fd)
267 {
268 
269 	KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
270 
271 	fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
272 }
273 
274 static void
275 fdused(struct filedesc *fdp, int fd)
276 {
277 
278 	FILEDESC_XLOCK_ASSERT(fdp);
279 
280 	fdused_init(fdp, fd);
281 	if (fd == fdp->fd_freefile)
282 		fdp->fd_freefile++;
283 }
284 
285 /*
286  * Mark a file descriptor as unused.
287  */
288 static void
289 fdunused(struct filedesc *fdp, int fd)
290 {
291 
292 	FILEDESC_XLOCK_ASSERT(fdp);
293 
294 	KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
295 	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
296 	    ("fd=%d is still in use", fd));
297 
298 	fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
299 	if (fd < fdp->fd_freefile)
300 		fdp->fd_freefile = fd;
301 }
302 
303 /*
304  * Free a file descriptor.
305  *
306  * Avoid some work if fdp is about to be destroyed.
307  */
308 static inline void
309 fdefree_last(struct filedescent *fde)
310 {
311 
312 	filecaps_free(&fde->fde_caps);
313 }
314 
315 static inline void
316 fdfree(struct filedesc *fdp, int fd)
317 {
318 	struct filedescent *fde;
319 
320 	FILEDESC_XLOCK_ASSERT(fdp);
321 	fde = &fdp->fd_ofiles[fd];
322 #ifdef CAPABILITIES
323 	seqc_write_begin(&fde->fde_seqc);
324 #endif
325 	fde->fde_file = NULL;
326 #ifdef CAPABILITIES
327 	seqc_write_end(&fde->fde_seqc);
328 #endif
329 	fdefree_last(fde);
330 	fdunused(fdp, fd);
331 }
332 
333 /*
334  * System calls on descriptors.
335  */
336 #ifndef _SYS_SYSPROTO_H_
337 struct getdtablesize_args {
338 	int	dummy;
339 };
340 #endif
341 /* ARGSUSED */
342 int
343 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
344 {
345 #ifdef	RACCT
346 	uint64_t lim;
347 #endif
348 
349 	td->td_retval[0] = getmaxfd(td);
350 #ifdef	RACCT
351 	PROC_LOCK(td->td_proc);
352 	lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
353 	PROC_UNLOCK(td->td_proc);
354 	if (lim < td->td_retval[0])
355 		td->td_retval[0] = lim;
356 #endif
357 	return (0);
358 }
359 
360 /*
361  * Duplicate a file descriptor to a particular value.
362  *
363  * Note: keep in mind that a potential race condition exists when closing
364  * descriptors from a shared descriptor table (via rfork).
365  */
366 #ifndef _SYS_SYSPROTO_H_
367 struct dup2_args {
368 	u_int	from;
369 	u_int	to;
370 };
371 #endif
372 /* ARGSUSED */
373 int
374 sys_dup2(struct thread *td, struct dup2_args *uap)
375 {
376 
377 	return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
378 }
379 
380 /*
381  * Duplicate a file descriptor.
382  */
383 #ifndef _SYS_SYSPROTO_H_
384 struct dup_args {
385 	u_int	fd;
386 };
387 #endif
388 /* ARGSUSED */
389 int
390 sys_dup(struct thread *td, struct dup_args *uap)
391 {
392 
393 	return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
394 }
395 
396 /*
397  * The file control system call.
398  */
399 #ifndef _SYS_SYSPROTO_H_
400 struct fcntl_args {
401 	int	fd;
402 	int	cmd;
403 	long	arg;
404 };
405 #endif
406 /* ARGSUSED */
407 int
408 sys_fcntl(struct thread *td, struct fcntl_args *uap)
409 {
410 
411 	return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
412 }
413 
414 int
415 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, intptr_t arg)
416 {
417 	struct flock fl;
418 	struct __oflock ofl;
419 	intptr_t arg1;
420 	int error, newcmd;
421 
422 	error = 0;
423 	newcmd = cmd;
424 	switch (cmd) {
425 	case F_OGETLK:
426 	case F_OSETLK:
427 	case F_OSETLKW:
428 		/*
429 		 * Convert old flock structure to new.
430 		 */
431 		error = copyin((void *)arg, &ofl, sizeof(ofl));
432 		fl.l_start = ofl.l_start;
433 		fl.l_len = ofl.l_len;
434 		fl.l_pid = ofl.l_pid;
435 		fl.l_type = ofl.l_type;
436 		fl.l_whence = ofl.l_whence;
437 		fl.l_sysid = 0;
438 
439 		switch (cmd) {
440 		case F_OGETLK:
441 			newcmd = F_GETLK;
442 			break;
443 		case F_OSETLK:
444 			newcmd = F_SETLK;
445 			break;
446 		case F_OSETLKW:
447 			newcmd = F_SETLKW;
448 			break;
449 		}
450 		arg1 = (intptr_t)&fl;
451 		break;
452 	case F_GETLK:
453 	case F_SETLK:
454 	case F_SETLKW:
455 	case F_SETLK_REMOTE:
456 		error = copyin((void *)arg, &fl, sizeof(fl));
457 		arg1 = (intptr_t)&fl;
458 		break;
459 	default:
460 		arg1 = arg;
461 		break;
462 	}
463 	if (error)
464 		return (error);
465 	error = kern_fcntl(td, fd, newcmd, arg1);
466 	if (error)
467 		return (error);
468 	if (cmd == F_OGETLK) {
469 		ofl.l_start = fl.l_start;
470 		ofl.l_len = fl.l_len;
471 		ofl.l_pid = fl.l_pid;
472 		ofl.l_type = fl.l_type;
473 		ofl.l_whence = fl.l_whence;
474 		error = copyout(&ofl, (void *)arg, sizeof(ofl));
475 	} else if (cmd == F_GETLK) {
476 		error = copyout(&fl, (void *)arg, sizeof(fl));
477 	}
478 	return (error);
479 }
480 
481 int
482 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
483 {
484 	struct filedesc *fdp;
485 	struct flock *flp;
486 	struct file *fp, *fp2;
487 	struct filedescent *fde;
488 	struct proc *p;
489 	struct vnode *vp;
490 	struct mount *mp;
491 	struct kinfo_file *kif;
492 	int error, flg, kif_sz, seals, tmp, got_set, got_cleared;
493 	uint64_t bsize;
494 	off_t foffset;
495 
496 	error = 0;
497 	flg = F_POSIX;
498 	p = td->td_proc;
499 	fdp = p->p_fd;
500 
501 	AUDIT_ARG_FD(cmd);
502 	AUDIT_ARG_CMD(cmd);
503 	switch (cmd) {
504 	case F_DUPFD:
505 		tmp = arg;
506 		error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
507 		break;
508 
509 	case F_DUPFD_CLOEXEC:
510 		tmp = arg;
511 		error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
512 		break;
513 
514 	case F_DUP2FD:
515 		tmp = arg;
516 		error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
517 		break;
518 
519 	case F_DUP2FD_CLOEXEC:
520 		tmp = arg;
521 		error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
522 		break;
523 
524 	case F_GETFD:
525 		error = EBADF;
526 		FILEDESC_SLOCK(fdp);
527 		fde = fdeget_noref(fdp, fd);
528 		if (fde != NULL) {
529 			td->td_retval[0] =
530 			    (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
531 			error = 0;
532 		}
533 		FILEDESC_SUNLOCK(fdp);
534 		break;
535 
536 	case F_SETFD:
537 		error = EBADF;
538 		FILEDESC_XLOCK(fdp);
539 		fde = fdeget_noref(fdp, fd);
540 		if (fde != NULL) {
541 			fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
542 			    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
543 			error = 0;
544 		}
545 		FILEDESC_XUNLOCK(fdp);
546 		break;
547 
548 	case F_GETFL:
549 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
550 		if (error != 0)
551 			break;
552 		td->td_retval[0] = OFLAGS(fp->f_flag);
553 		fdrop(fp, td);
554 		break;
555 
556 	case F_SETFL:
557 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
558 		if (error != 0)
559 			break;
560 		if (fp->f_ops == &path_fileops) {
561 			fdrop(fp, td);
562 			error = EBADF;
563 			break;
564 		}
565 		do {
566 			tmp = flg = fp->f_flag;
567 			tmp &= ~FCNTLFLAGS;
568 			tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
569 		} while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
570 		got_set = tmp & ~flg;
571 		got_cleared = flg & ~tmp;
572 		tmp = fp->f_flag & FNONBLOCK;
573 		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
574 		if (error != 0)
575 			goto revert_f_setfl;
576 		tmp = fp->f_flag & FASYNC;
577 		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
578 		if (error == 0) {
579 			fdrop(fp, td);
580 			break;
581 		}
582 		atomic_clear_int(&fp->f_flag, FNONBLOCK);
583 		tmp = 0;
584 		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
585 revert_f_setfl:
586 		do {
587 			tmp = flg = fp->f_flag;
588 			tmp &= ~FCNTLFLAGS;
589 			tmp |= got_cleared;
590 			tmp &= ~got_set;
591 		} while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
592 		fdrop(fp, td);
593 		break;
594 
595 	case F_GETOWN:
596 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
597 		if (error != 0)
598 			break;
599 		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
600 		if (error == 0)
601 			td->td_retval[0] = tmp;
602 		fdrop(fp, td);
603 		break;
604 
605 	case F_SETOWN:
606 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
607 		if (error != 0)
608 			break;
609 		tmp = arg;
610 		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
611 		fdrop(fp, td);
612 		break;
613 
614 	case F_SETLK_REMOTE:
615 		error = priv_check(td, PRIV_NFS_LOCKD);
616 		if (error != 0)
617 			return (error);
618 		flg = F_REMOTE;
619 		goto do_setlk;
620 
621 	case F_SETLKW:
622 		flg |= F_WAIT;
623 		/* FALLTHROUGH F_SETLK */
624 
625 	case F_SETLK:
626 	do_setlk:
627 		flp = (struct flock *)arg;
628 		if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
629 			error = EINVAL;
630 			break;
631 		}
632 
633 		error = fget_unlocked(td, fd, &cap_flock_rights, &fp);
634 		if (error != 0)
635 			break;
636 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
637 			error = EBADF;
638 			fdrop(fp, td);
639 			break;
640 		}
641 
642 		if (flp->l_whence == SEEK_CUR) {
643 			foffset = foffset_get(fp);
644 			if (foffset < 0 ||
645 			    (flp->l_start > 0 &&
646 			     foffset > OFF_MAX - flp->l_start)) {
647 				error = EOVERFLOW;
648 				fdrop(fp, td);
649 				break;
650 			}
651 			flp->l_start += foffset;
652 		}
653 
654 		vp = fp->f_vnode;
655 		switch (flp->l_type) {
656 		case F_RDLCK:
657 			if ((fp->f_flag & FREAD) == 0) {
658 				error = EBADF;
659 				break;
660 			}
661 			if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
662 				PROC_LOCK(p->p_leader);
663 				p->p_leader->p_flag |= P_ADVLOCK;
664 				PROC_UNLOCK(p->p_leader);
665 			}
666 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
667 			    flp, flg);
668 			break;
669 		case F_WRLCK:
670 			if ((fp->f_flag & FWRITE) == 0) {
671 				error = EBADF;
672 				break;
673 			}
674 			if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
675 				PROC_LOCK(p->p_leader);
676 				p->p_leader->p_flag |= P_ADVLOCK;
677 				PROC_UNLOCK(p->p_leader);
678 			}
679 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
680 			    flp, flg);
681 			break;
682 		case F_UNLCK:
683 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
684 			    flp, flg);
685 			break;
686 		case F_UNLCKSYS:
687 			if (flg != F_REMOTE) {
688 				error = EINVAL;
689 				break;
690 			}
691 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
692 			    F_UNLCKSYS, flp, flg);
693 			break;
694 		default:
695 			error = EINVAL;
696 			break;
697 		}
698 		if (error != 0 || flp->l_type == F_UNLCK ||
699 		    flp->l_type == F_UNLCKSYS) {
700 			fdrop(fp, td);
701 			break;
702 		}
703 
704 		/*
705 		 * Check for a race with close.
706 		 *
707 		 * The vnode is now advisory locked (or unlocked, but this case
708 		 * is not really important) as the caller requested.
709 		 * We had to drop the filedesc lock, so we need to recheck if
710 		 * the descriptor is still valid, because if it was closed
711 		 * in the meantime we need to remove advisory lock from the
712 		 * vnode - close on any descriptor leading to an advisory
713 		 * locked vnode, removes that lock.
714 		 * We will return 0 on purpose in that case, as the result of
715 		 * successful advisory lock might have been externally visible
716 		 * already. This is fine - effectively we pretend to the caller
717 		 * that the closing thread was a bit slower and that the
718 		 * advisory lock succeeded before the close.
719 		 */
720 		error = fget_unlocked(td, fd, &cap_no_rights, &fp2);
721 		if (error != 0) {
722 			fdrop(fp, td);
723 			break;
724 		}
725 		if (fp != fp2) {
726 			flp->l_whence = SEEK_SET;
727 			flp->l_start = 0;
728 			flp->l_len = 0;
729 			flp->l_type = F_UNLCK;
730 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
731 			    F_UNLCK, flp, F_POSIX);
732 		}
733 		fdrop(fp, td);
734 		fdrop(fp2, td);
735 		break;
736 
737 	case F_GETLK:
738 		error = fget_unlocked(td, fd, &cap_flock_rights, &fp);
739 		if (error != 0)
740 			break;
741 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
742 			error = EBADF;
743 			fdrop(fp, td);
744 			break;
745 		}
746 		flp = (struct flock *)arg;
747 		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
748 		    flp->l_type != F_UNLCK) {
749 			error = EINVAL;
750 			fdrop(fp, td);
751 			break;
752 		}
753 		if (flp->l_whence == SEEK_CUR) {
754 			foffset = foffset_get(fp);
755 			if ((flp->l_start > 0 &&
756 			    foffset > OFF_MAX - flp->l_start) ||
757 			    (flp->l_start < 0 &&
758 			    foffset < OFF_MIN - flp->l_start)) {
759 				error = EOVERFLOW;
760 				fdrop(fp, td);
761 				break;
762 			}
763 			flp->l_start += foffset;
764 		}
765 		vp = fp->f_vnode;
766 		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
767 		    F_POSIX);
768 		fdrop(fp, td);
769 		break;
770 
771 	case F_ADD_SEALS:
772 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
773 		if (error != 0)
774 			break;
775 		error = fo_add_seals(fp, arg);
776 		fdrop(fp, td);
777 		break;
778 
779 	case F_GET_SEALS:
780 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
781 		if (error != 0)
782 			break;
783 		if (fo_get_seals(fp, &seals) == 0)
784 			td->td_retval[0] = seals;
785 		else
786 			error = EINVAL;
787 		fdrop(fp, td);
788 		break;
789 
790 	case F_RDAHEAD:
791 		arg = arg ? 128 * 1024: 0;
792 		/* FALLTHROUGH */
793 	case F_READAHEAD:
794 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
795 		if (error != 0)
796 			break;
797 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
798 			fdrop(fp, td);
799 			error = EBADF;
800 			break;
801 		}
802 		vp = fp->f_vnode;
803 		if (vp->v_type != VREG) {
804 			fdrop(fp, td);
805 			error = ENOTTY;
806 			break;
807 		}
808 
809 		/*
810 		 * Exclusive lock synchronizes against f_seqcount reads and
811 		 * writes in sequential_heuristic().
812 		 */
813 		error = vn_lock(vp, LK_EXCLUSIVE);
814 		if (error != 0) {
815 			fdrop(fp, td);
816 			break;
817 		}
818 		if (arg >= 0) {
819 			bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
820 			arg = MIN(arg, INT_MAX - bsize + 1);
821 			fp->f_seqcount[UIO_READ] = MIN(IO_SEQMAX,
822 			    (arg + bsize - 1) / bsize);
823 			atomic_set_int(&fp->f_flag, FRDAHEAD);
824 		} else {
825 			atomic_clear_int(&fp->f_flag, FRDAHEAD);
826 		}
827 		VOP_UNLOCK(vp);
828 		fdrop(fp, td);
829 		break;
830 
831 	case F_ISUNIONSTACK:
832 		/*
833 		 * Check if the vnode is part of a union stack (either the
834 		 * "union" flag from mount(2) or unionfs).
835 		 *
836 		 * Prior to introduction of this op libc's readdir would call
837 		 * fstatfs(2), in effect unnecessarily copying kilobytes of
838 		 * data just to check fs name and a mount flag.
839 		 *
840 		 * Fixing the code to handle everything in the kernel instead
841 		 * is a non-trivial endeavor and has low priority, thus this
842 		 * horrible kludge facilitates the current behavior in a much
843 		 * cheaper manner until someone(tm) sorts this out.
844 		 */
845 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
846 		if (error != 0)
847 			break;
848 		if (fp->f_type != DTYPE_VNODE) {
849 			fdrop(fp, td);
850 			error = EBADF;
851 			break;
852 		}
853 		vp = fp->f_vnode;
854 		/*
855 		 * Since we don't prevent dooming the vnode even non-null mp
856 		 * found can become immediately stale. This is tolerable since
857 		 * mount points are type-stable (providing safe memory access)
858 		 * and any vfs op on this vnode going forward will return an
859 		 * error (meaning return value in this case is meaningless).
860 		 */
861 		mp = atomic_load_ptr(&vp->v_mount);
862 		if (__predict_false(mp == NULL)) {
863 			fdrop(fp, td);
864 			error = EBADF;
865 			break;
866 		}
867 		td->td_retval[0] = 0;
868 		if (mp->mnt_kern_flag & MNTK_UNIONFS ||
869 		    mp->mnt_flag & MNT_UNION)
870 			td->td_retval[0] = 1;
871 		fdrop(fp, td);
872 		break;
873 
874 	case F_KINFO:
875 #ifdef CAPABILITY_MODE
876 		if (CAP_TRACING(td))
877 			ktrcapfail(CAPFAIL_SYSCALL, &cmd);
878 		if (IN_CAPABILITY_MODE(td)) {
879 			error = ECAPMODE;
880 			break;
881 		}
882 #endif
883 		error = copyin((void *)arg, &kif_sz, sizeof(kif_sz));
884 		if (error != 0)
885 			break;
886 		if (kif_sz != sizeof(*kif)) {
887 			error = EINVAL;
888 			break;
889 		}
890 		kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK | M_ZERO);
891 		FILEDESC_SLOCK(fdp);
892 		error = fget_cap_noref(fdp, fd, &cap_fcntl_rights, &fp, NULL);
893 		if (error == 0 && fhold(fp)) {
894 			export_file_to_kinfo(fp, fd, NULL, kif, fdp, 0);
895 			FILEDESC_SUNLOCK(fdp);
896 			fdrop(fp, td);
897 			if ((kif->kf_status & KF_ATTR_VALID) != 0) {
898 				kif->kf_structsize = sizeof(*kif);
899 				error = copyout(kif, (void *)arg, sizeof(*kif));
900 			} else {
901 				error = EBADF;
902 			}
903 		} else {
904 			FILEDESC_SUNLOCK(fdp);
905 			if (error == 0)
906 				error = EBADF;
907 		}
908 		free(kif, M_TEMP);
909 		break;
910 
911 	default:
912 		error = EINVAL;
913 		break;
914 	}
915 	return (error);
916 }
917 
918 static int
919 getmaxfd(struct thread *td)
920 {
921 
922 	return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
923 }
924 
925 /*
926  * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
927  */
928 int
929 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
930 {
931 	struct filedesc *fdp;
932 	struct filedescent *oldfde, *newfde;
933 	struct proc *p;
934 	struct file *delfp, *oldfp;
935 	u_long *oioctls, *nioctls;
936 	int error, maxfd;
937 
938 	p = td->td_proc;
939 	fdp = p->p_fd;
940 	oioctls = NULL;
941 
942 	MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
943 	MPASS(mode < FDDUP_LASTMODE);
944 
945 	AUDIT_ARG_FD(old);
946 	/* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
947 
948 	/*
949 	 * Verify we have a valid descriptor to dup from and possibly to
950 	 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
951 	 * return EINVAL when the new descriptor is out of bounds.
952 	 */
953 	if (old < 0)
954 		return (EBADF);
955 	if (new < 0)
956 		return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
957 	maxfd = getmaxfd(td);
958 	if (new >= maxfd)
959 		return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
960 
961 	error = EBADF;
962 	FILEDESC_XLOCK(fdp);
963 	if (fget_noref(fdp, old) == NULL)
964 		goto unlock;
965 	if (mode == FDDUP_FIXED && old == new) {
966 		td->td_retval[0] = new;
967 		if (flags & FDDUP_FLAG_CLOEXEC)
968 			fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
969 		error = 0;
970 		goto unlock;
971 	}
972 
973 	oldfde = &fdp->fd_ofiles[old];
974 	oldfp = oldfde->fde_file;
975 	if (!fhold(oldfp))
976 		goto unlock;
977 
978 	/*
979 	 * If the caller specified a file descriptor, make sure the file
980 	 * table is large enough to hold it, and grab it.  Otherwise, just
981 	 * allocate a new descriptor the usual way.
982 	 */
983 	switch (mode) {
984 	case FDDUP_NORMAL:
985 	case FDDUP_FCNTL:
986 		if ((error = fdalloc(td, new, &new)) != 0) {
987 			fdrop(oldfp, td);
988 			goto unlock;
989 		}
990 		break;
991 	case FDDUP_FIXED:
992 		if (new >= fdp->fd_nfiles) {
993 			/*
994 			 * The resource limits are here instead of e.g.
995 			 * fdalloc(), because the file descriptor table may be
996 			 * shared between processes, so we can't really use
997 			 * racct_add()/racct_sub().  Instead of counting the
998 			 * number of actually allocated descriptors, just put
999 			 * the limit on the size of the file descriptor table.
1000 			 */
1001 #ifdef RACCT
1002 			if (RACCT_ENABLED()) {
1003 				error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
1004 				if (error != 0) {
1005 					error = EMFILE;
1006 					fdrop(oldfp, td);
1007 					goto unlock;
1008 				}
1009 			}
1010 #endif
1011 			fdgrowtable_exp(fdp, new + 1);
1012 		}
1013 		if (!fdisused(fdp, new))
1014 			fdused(fdp, new);
1015 		break;
1016 	default:
1017 		KASSERT(0, ("%s unsupported mode %d", __func__, mode));
1018 	}
1019 
1020 	KASSERT(old != new, ("new fd is same as old"));
1021 
1022 	/* Refetch oldfde because the table may have grown and old one freed. */
1023 	oldfde = &fdp->fd_ofiles[old];
1024 	KASSERT(oldfp == oldfde->fde_file,
1025 	    ("fdt_ofiles shift from growth observed at fd %d",
1026 	    old));
1027 
1028 	newfde = &fdp->fd_ofiles[new];
1029 	delfp = newfde->fde_file;
1030 
1031 	nioctls = filecaps_copy_prep(&oldfde->fde_caps);
1032 
1033 	/*
1034 	 * Duplicate the source descriptor.
1035 	 */
1036 #ifdef CAPABILITIES
1037 	seqc_write_begin(&newfde->fde_seqc);
1038 #endif
1039 	oioctls = filecaps_free_prep(&newfde->fde_caps);
1040 	fde_copy(oldfde, newfde);
1041 	filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
1042 	    nioctls);
1043 	if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
1044 		newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
1045 	else
1046 		newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
1047 #ifdef CAPABILITIES
1048 	seqc_write_end(&newfde->fde_seqc);
1049 #endif
1050 	td->td_retval[0] = new;
1051 
1052 	error = 0;
1053 
1054 	if (delfp != NULL) {
1055 		(void) closefp(fdp, new, delfp, td, true, false);
1056 		FILEDESC_UNLOCK_ASSERT(fdp);
1057 	} else {
1058 unlock:
1059 		FILEDESC_XUNLOCK(fdp);
1060 	}
1061 
1062 	filecaps_free_finish(oioctls);
1063 	return (error);
1064 }
1065 
1066 static void
1067 sigiofree(struct sigio *sigio)
1068 {
1069 	crfree(sigio->sio_ucred);
1070 	free(sigio, M_SIGIO);
1071 }
1072 
1073 static struct sigio *
1074 funsetown_locked(struct sigio *sigio)
1075 {
1076 	struct proc *p;
1077 	struct pgrp *pg;
1078 
1079 	SIGIO_ASSERT_LOCKED();
1080 
1081 	if (sigio == NULL)
1082 		return (NULL);
1083 	*sigio->sio_myref = NULL;
1084 	if (sigio->sio_pgid < 0) {
1085 		pg = sigio->sio_pgrp;
1086 		PGRP_LOCK(pg);
1087 		SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio, sio_pgsigio);
1088 		PGRP_UNLOCK(pg);
1089 	} else {
1090 		p = sigio->sio_proc;
1091 		PROC_LOCK(p);
1092 		SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, sio_pgsigio);
1093 		PROC_UNLOCK(p);
1094 	}
1095 	return (sigio);
1096 }
1097 
1098 /*
1099  * If sigio is on the list associated with a process or process group,
1100  * disable signalling from the device, remove sigio from the list and
1101  * free sigio.
1102  */
1103 void
1104 funsetown(struct sigio **sigiop)
1105 {
1106 	struct sigio *sigio;
1107 
1108 	/* Racy check, consumers must provide synchronization. */
1109 	if (*sigiop == NULL)
1110 		return;
1111 
1112 	SIGIO_LOCK();
1113 	sigio = funsetown_locked(*sigiop);
1114 	SIGIO_UNLOCK();
1115 	if (sigio != NULL)
1116 		sigiofree(sigio);
1117 }
1118 
1119 /*
1120  * Free a list of sigio structures.  The caller must ensure that new sigio
1121  * structures cannot be added after this point.  For process groups this is
1122  * guaranteed using the proctree lock; for processes, the P_WEXIT flag serves
1123  * as an interlock.
1124  */
1125 void
1126 funsetownlst(struct sigiolst *sigiolst)
1127 {
1128 	struct proc *p;
1129 	struct pgrp *pg;
1130 	struct sigio *sigio, *tmp;
1131 
1132 	/* Racy check. */
1133 	sigio = SLIST_FIRST(sigiolst);
1134 	if (sigio == NULL)
1135 		return;
1136 
1137 	p = NULL;
1138 	pg = NULL;
1139 
1140 	SIGIO_LOCK();
1141 	sigio = SLIST_FIRST(sigiolst);
1142 	if (sigio == NULL) {
1143 		SIGIO_UNLOCK();
1144 		return;
1145 	}
1146 
1147 	/*
1148 	 * Every entry of the list should belong to a single proc or pgrp.
1149 	 */
1150 	if (sigio->sio_pgid < 0) {
1151 		pg = sigio->sio_pgrp;
1152 		sx_assert(&proctree_lock, SX_XLOCKED);
1153 		PGRP_LOCK(pg);
1154 	} else /* if (sigio->sio_pgid > 0) */ {
1155 		p = sigio->sio_proc;
1156 		PROC_LOCK(p);
1157 		KASSERT((p->p_flag & P_WEXIT) != 0,
1158 		    ("%s: process %p is not exiting", __func__, p));
1159 	}
1160 
1161 	SLIST_FOREACH(sigio, sigiolst, sio_pgsigio) {
1162 		*sigio->sio_myref = NULL;
1163 		if (pg != NULL) {
1164 			KASSERT(sigio->sio_pgid < 0,
1165 			    ("Proc sigio in pgrp sigio list"));
1166 			KASSERT(sigio->sio_pgrp == pg,
1167 			    ("Bogus pgrp in sigio list"));
1168 		} else /* if (p != NULL) */ {
1169 			KASSERT(sigio->sio_pgid > 0,
1170 			    ("Pgrp sigio in proc sigio list"));
1171 			KASSERT(sigio->sio_proc == p,
1172 			    ("Bogus proc in sigio list"));
1173 		}
1174 	}
1175 
1176 	if (pg != NULL)
1177 		PGRP_UNLOCK(pg);
1178 	else
1179 		PROC_UNLOCK(p);
1180 	SIGIO_UNLOCK();
1181 
1182 	SLIST_FOREACH_SAFE(sigio, sigiolst, sio_pgsigio, tmp)
1183 		sigiofree(sigio);
1184 }
1185 
1186 /*
1187  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1188  *
1189  * After permission checking, add a sigio structure to the sigio list for
1190  * the process or process group.
1191  */
1192 int
1193 fsetown(pid_t pgid, struct sigio **sigiop)
1194 {
1195 	struct proc *proc;
1196 	struct pgrp *pgrp;
1197 	struct sigio *osigio, *sigio;
1198 	int ret;
1199 
1200 	if (pgid == 0) {
1201 		funsetown(sigiop);
1202 		return (0);
1203 	}
1204 
1205 	sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1206 	sigio->sio_pgid = pgid;
1207 	sigio->sio_ucred = crhold(curthread->td_ucred);
1208 	sigio->sio_myref = sigiop;
1209 
1210 	ret = 0;
1211 	if (pgid > 0) {
1212 		ret = pget(pgid, PGET_NOTWEXIT | PGET_NOTID | PGET_HOLD, &proc);
1213 		SIGIO_LOCK();
1214 		osigio = funsetown_locked(*sigiop);
1215 		if (ret == 0) {
1216 			PROC_LOCK(proc);
1217 			_PRELE(proc);
1218 			if ((proc->p_flag & P_WEXIT) != 0) {
1219 				ret = ESRCH;
1220 			} else if (proc->p_session !=
1221 			    curthread->td_proc->p_session) {
1222 				/*
1223 				 * Policy - Don't allow a process to FSETOWN a
1224 				 * process in another session.
1225 				 *
1226 				 * Remove this test to allow maximum flexibility
1227 				 * or restrict FSETOWN to the current process or
1228 				 * process group for maximum safety.
1229 				 */
1230 				ret = EPERM;
1231 			} else {
1232 				sigio->sio_proc = proc;
1233 				SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio,
1234 				    sio_pgsigio);
1235 			}
1236 			PROC_UNLOCK(proc);
1237 		}
1238 	} else /* if (pgid < 0) */ {
1239 		sx_slock(&proctree_lock);
1240 		SIGIO_LOCK();
1241 		osigio = funsetown_locked(*sigiop);
1242 		pgrp = pgfind(-pgid);
1243 		if (pgrp == NULL) {
1244 			ret = ESRCH;
1245 		} else {
1246 			if (pgrp->pg_session != curthread->td_proc->p_session) {
1247 				/*
1248 				 * Policy - Don't allow a process to FSETOWN a
1249 				 * process in another session.
1250 				 *
1251 				 * Remove this test to allow maximum flexibility
1252 				 * or restrict FSETOWN to the current process or
1253 				 * process group for maximum safety.
1254 				 */
1255 				ret = EPERM;
1256 			} else {
1257 				sigio->sio_pgrp = pgrp;
1258 				SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio,
1259 				    sio_pgsigio);
1260 			}
1261 			PGRP_UNLOCK(pgrp);
1262 		}
1263 		sx_sunlock(&proctree_lock);
1264 	}
1265 	if (ret == 0)
1266 		*sigiop = sigio;
1267 	SIGIO_UNLOCK();
1268 	if (osigio != NULL)
1269 		sigiofree(osigio);
1270 	return (ret);
1271 }
1272 
1273 /*
1274  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1275  */
1276 pid_t
1277 fgetown(struct sigio **sigiop)
1278 {
1279 	pid_t pgid;
1280 
1281 	SIGIO_LOCK();
1282 	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1283 	SIGIO_UNLOCK();
1284 	return (pgid);
1285 }
1286 
1287 static int
1288 closefp_impl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1289     bool audit)
1290 {
1291 	int error;
1292 
1293 	FILEDESC_XLOCK_ASSERT(fdp);
1294 
1295 	/*
1296 	 * We now hold the fp reference that used to be owned by the
1297 	 * descriptor array.  We have to unlock the FILEDESC *AFTER*
1298 	 * knote_fdclose to prevent a race of the fd getting opened, a knote
1299 	 * added, and deleteing a knote for the new fd.
1300 	 */
1301 	if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1302 		knote_fdclose(td, fd);
1303 
1304 	/*
1305 	 * We need to notify mqueue if the object is of type mqueue.
1306 	 */
1307 	if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1308 		mq_fdclose(td, fd, fp);
1309 	FILEDESC_XUNLOCK(fdp);
1310 
1311 #ifdef AUDIT
1312 	if (AUDITING_TD(td) && audit)
1313 		audit_sysclose(td, fd, fp);
1314 #endif
1315 	error = closef(fp, td);
1316 
1317 	/*
1318 	 * All paths leading up to closefp() will have already removed or
1319 	 * replaced the fd in the filedesc table, so a restart would not
1320 	 * operate on the same file.
1321 	 */
1322 	if (error == ERESTART)
1323 		error = EINTR;
1324 
1325 	return (error);
1326 }
1327 
1328 static int
1329 closefp_hl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1330     bool holdleaders, bool audit)
1331 {
1332 	int error;
1333 
1334 	FILEDESC_XLOCK_ASSERT(fdp);
1335 
1336 	if (holdleaders) {
1337 		if (td->td_proc->p_fdtol != NULL) {
1338 			/*
1339 			 * Ask fdfree() to sleep to ensure that all relevant
1340 			 * process leaders can be traversed in closef().
1341 			 */
1342 			fdp->fd_holdleaderscount++;
1343 		} else {
1344 			holdleaders = false;
1345 		}
1346 	}
1347 
1348 	error = closefp_impl(fdp, fd, fp, td, audit);
1349 	if (holdleaders) {
1350 		FILEDESC_XLOCK(fdp);
1351 		fdp->fd_holdleaderscount--;
1352 		if (fdp->fd_holdleaderscount == 0 &&
1353 		    fdp->fd_holdleaderswakeup != 0) {
1354 			fdp->fd_holdleaderswakeup = 0;
1355 			wakeup(&fdp->fd_holdleaderscount);
1356 		}
1357 		FILEDESC_XUNLOCK(fdp);
1358 	}
1359 	return (error);
1360 }
1361 
1362 static int
1363 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1364     bool holdleaders, bool audit)
1365 {
1366 
1367 	FILEDESC_XLOCK_ASSERT(fdp);
1368 
1369 	if (__predict_false(td->td_proc->p_fdtol != NULL)) {
1370 		return (closefp_hl(fdp, fd, fp, td, holdleaders, audit));
1371 	} else {
1372 		return (closefp_impl(fdp, fd, fp, td, audit));
1373 	}
1374 }
1375 
1376 /*
1377  * Close a file descriptor.
1378  */
1379 #ifndef _SYS_SYSPROTO_H_
1380 struct close_args {
1381 	int     fd;
1382 };
1383 #endif
1384 /* ARGSUSED */
1385 int
1386 sys_close(struct thread *td, struct close_args *uap)
1387 {
1388 
1389 	return (kern_close(td, uap->fd));
1390 }
1391 
1392 int
1393 kern_close(struct thread *td, int fd)
1394 {
1395 	struct filedesc *fdp;
1396 	struct file *fp;
1397 
1398 	fdp = td->td_proc->p_fd;
1399 
1400 	FILEDESC_XLOCK(fdp);
1401 	if ((fp = fget_noref(fdp, fd)) == NULL) {
1402 		FILEDESC_XUNLOCK(fdp);
1403 		return (EBADF);
1404 	}
1405 	fdfree(fdp, fd);
1406 
1407 	/* closefp() drops the FILEDESC lock for us. */
1408 	return (closefp(fdp, fd, fp, td, true, true));
1409 }
1410 
1411 static int
1412 close_range_cloexec(struct thread *td, u_int lowfd, u_int highfd)
1413 {
1414 	struct filedesc *fdp;
1415 	struct fdescenttbl *fdt;
1416 	struct filedescent *fde;
1417 	int fd;
1418 
1419 	fdp = td->td_proc->p_fd;
1420 	FILEDESC_XLOCK(fdp);
1421 	fdt = atomic_load_ptr(&fdp->fd_files);
1422 	highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1423 	fd = lowfd;
1424 	if (__predict_false(fd > highfd)) {
1425 		goto out_locked;
1426 	}
1427 	for (; fd <= highfd; fd++) {
1428 		fde = &fdt->fdt_ofiles[fd];
1429 		if (fde->fde_file != NULL)
1430 			fde->fde_flags |= UF_EXCLOSE;
1431 	}
1432 out_locked:
1433 	FILEDESC_XUNLOCK(fdp);
1434 	return (0);
1435 }
1436 
1437 static int
1438 close_range_impl(struct thread *td, u_int lowfd, u_int highfd)
1439 {
1440 	struct filedesc *fdp;
1441 	const struct fdescenttbl *fdt;
1442 	struct file *fp;
1443 	int fd;
1444 
1445 	fdp = td->td_proc->p_fd;
1446 	FILEDESC_XLOCK(fdp);
1447 	fdt = atomic_load_ptr(&fdp->fd_files);
1448 	highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1449 	fd = lowfd;
1450 	if (__predict_false(fd > highfd)) {
1451 		goto out_locked;
1452 	}
1453 	for (;;) {
1454 		fp = fdt->fdt_ofiles[fd].fde_file;
1455 		if (fp == NULL) {
1456 			if (fd == highfd)
1457 				goto out_locked;
1458 		} else {
1459 			fdfree(fdp, fd);
1460 			(void) closefp(fdp, fd, fp, td, true, true);
1461 			if (fd == highfd)
1462 				goto out_unlocked;
1463 			FILEDESC_XLOCK(fdp);
1464 			fdt = atomic_load_ptr(&fdp->fd_files);
1465 		}
1466 		fd++;
1467 	}
1468 out_locked:
1469 	FILEDESC_XUNLOCK(fdp);
1470 out_unlocked:
1471 	return (0);
1472 }
1473 
1474 int
1475 kern_close_range(struct thread *td, int flags, u_int lowfd, u_int highfd)
1476 {
1477 
1478 	/*
1479 	 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1480 	 * open should not be a usage error.  From a close_range() perspective,
1481 	 * close_range(3, ~0U, 0) in the same scenario should also likely not
1482 	 * be a usage error as all fd above 3 are in-fact already closed.
1483 	 */
1484 	if (highfd < lowfd) {
1485 		return (EINVAL);
1486 	}
1487 
1488 	if ((flags & CLOSE_RANGE_CLOEXEC) != 0)
1489 		return (close_range_cloexec(td, lowfd, highfd));
1490 
1491 	return (close_range_impl(td, lowfd, highfd));
1492 }
1493 
1494 #ifndef _SYS_SYSPROTO_H_
1495 struct close_range_args {
1496 	u_int	lowfd;
1497 	u_int	highfd;
1498 	int	flags;
1499 };
1500 #endif
1501 int
1502 sys_close_range(struct thread *td, struct close_range_args *uap)
1503 {
1504 
1505 	AUDIT_ARG_FD(uap->lowfd);
1506 	AUDIT_ARG_CMD(uap->highfd);
1507 	AUDIT_ARG_FFLAGS(uap->flags);
1508 
1509 	if ((uap->flags & ~(CLOSE_RANGE_CLOEXEC)) != 0)
1510 		return (EINVAL);
1511 	return (kern_close_range(td, uap->flags, uap->lowfd, uap->highfd));
1512 }
1513 
1514 #ifdef COMPAT_FREEBSD12
1515 /*
1516  * Close open file descriptors.
1517  */
1518 #ifndef _SYS_SYSPROTO_H_
1519 struct freebsd12_closefrom_args {
1520 	int	lowfd;
1521 };
1522 #endif
1523 /* ARGSUSED */
1524 int
1525 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1526 {
1527 	u_int lowfd;
1528 
1529 	AUDIT_ARG_FD(uap->lowfd);
1530 
1531 	/*
1532 	 * Treat negative starting file descriptor values identical to
1533 	 * closefrom(0) which closes all files.
1534 	 */
1535 	lowfd = MAX(0, uap->lowfd);
1536 	return (kern_close_range(td, 0, lowfd, ~0U));
1537 }
1538 #endif	/* COMPAT_FREEBSD12 */
1539 
1540 #if defined(COMPAT_43)
1541 /*
1542  * Return status information about a file descriptor.
1543  */
1544 #ifndef _SYS_SYSPROTO_H_
1545 struct ofstat_args {
1546 	int	fd;
1547 	struct	ostat *sb;
1548 };
1549 #endif
1550 /* ARGSUSED */
1551 int
1552 ofstat(struct thread *td, struct ofstat_args *uap)
1553 {
1554 	struct ostat oub;
1555 	struct stat ub;
1556 	int error;
1557 
1558 	error = kern_fstat(td, uap->fd, &ub);
1559 	if (error == 0) {
1560 		cvtstat(&ub, &oub);
1561 		error = copyout(&oub, uap->sb, sizeof(oub));
1562 	}
1563 	return (error);
1564 }
1565 #endif /* COMPAT_43 */
1566 
1567 #if defined(COMPAT_FREEBSD11)
1568 int
1569 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1570 {
1571 	struct stat sb;
1572 	struct freebsd11_stat osb;
1573 	int error;
1574 
1575 	error = kern_fstat(td, uap->fd, &sb);
1576 	if (error != 0)
1577 		return (error);
1578 	error = freebsd11_cvtstat(&sb, &osb);
1579 	if (error == 0)
1580 		error = copyout(&osb, uap->sb, sizeof(osb));
1581 	return (error);
1582 }
1583 #endif	/* COMPAT_FREEBSD11 */
1584 
1585 /*
1586  * Return status information about a file descriptor.
1587  */
1588 #ifndef _SYS_SYSPROTO_H_
1589 struct fstat_args {
1590 	int	fd;
1591 	struct	stat *sb;
1592 };
1593 #endif
1594 /* ARGSUSED */
1595 int
1596 sys_fstat(struct thread *td, struct fstat_args *uap)
1597 {
1598 	struct stat ub;
1599 	int error;
1600 
1601 	error = kern_fstat(td, uap->fd, &ub);
1602 	if (error == 0)
1603 		error = copyout(&ub, uap->sb, sizeof(ub));
1604 	return (error);
1605 }
1606 
1607 int
1608 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1609 {
1610 	struct file *fp;
1611 	int error;
1612 
1613 	AUDIT_ARG_FD(fd);
1614 
1615 	error = fget(td, fd, &cap_fstat_rights, &fp);
1616 	if (__predict_false(error != 0))
1617 		return (error);
1618 
1619 	AUDIT_ARG_FILE(td->td_proc, fp);
1620 
1621 	sbp->st_filerev = 0;
1622 	sbp->st_bsdflags = 0;
1623 	error = fo_stat(fp, sbp, td->td_ucred);
1624 	fdrop(fp, td);
1625 #ifdef __STAT_TIME_T_EXT
1626 	sbp->st_atim_ext = 0;
1627 	sbp->st_mtim_ext = 0;
1628 	sbp->st_ctim_ext = 0;
1629 	sbp->st_btim_ext = 0;
1630 #endif
1631 #ifdef KTRACE
1632 	if (KTRPOINT(td, KTR_STRUCT))
1633 		ktrstat_error(sbp, error);
1634 #endif
1635 	return (error);
1636 }
1637 
1638 #if defined(COMPAT_FREEBSD11)
1639 /*
1640  * Return status information about a file descriptor.
1641  */
1642 #ifndef _SYS_SYSPROTO_H_
1643 struct freebsd11_nfstat_args {
1644 	int	fd;
1645 	struct	nstat *sb;
1646 };
1647 #endif
1648 /* ARGSUSED */
1649 int
1650 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1651 {
1652 	struct nstat nub;
1653 	struct stat ub;
1654 	int error;
1655 
1656 	error = kern_fstat(td, uap->fd, &ub);
1657 	if (error != 0)
1658 		return (error);
1659 	error = freebsd11_cvtnstat(&ub, &nub);
1660 	if (error != 0)
1661 		error = copyout(&nub, uap->sb, sizeof(nub));
1662 	return (error);
1663 }
1664 #endif /* COMPAT_FREEBSD11 */
1665 
1666 /*
1667  * Return pathconf information about a file descriptor.
1668  */
1669 #ifndef _SYS_SYSPROTO_H_
1670 struct fpathconf_args {
1671 	int	fd;
1672 	int	name;
1673 };
1674 #endif
1675 /* ARGSUSED */
1676 int
1677 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1678 {
1679 	long value;
1680 	int error;
1681 
1682 	error = kern_fpathconf(td, uap->fd, uap->name, &value);
1683 	if (error == 0)
1684 		td->td_retval[0] = value;
1685 	return (error);
1686 }
1687 
1688 int
1689 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1690 {
1691 	struct file *fp;
1692 	struct vnode *vp;
1693 	int error;
1694 
1695 	error = fget(td, fd, &cap_fpathconf_rights, &fp);
1696 	if (error != 0)
1697 		return (error);
1698 
1699 	if (name == _PC_ASYNC_IO) {
1700 		*valuep = _POSIX_ASYNCHRONOUS_IO;
1701 		goto out;
1702 	}
1703 	vp = fp->f_vnode;
1704 	if (vp != NULL) {
1705 		vn_lock(vp, LK_SHARED | LK_RETRY);
1706 		error = VOP_PATHCONF(vp, name, valuep);
1707 		VOP_UNLOCK(vp);
1708 	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1709 		if (name != _PC_PIPE_BUF) {
1710 			error = EINVAL;
1711 		} else {
1712 			*valuep = PIPE_BUF;
1713 			error = 0;
1714 		}
1715 	} else {
1716 		error = EOPNOTSUPP;
1717 	}
1718 out:
1719 	fdrop(fp, td);
1720 	return (error);
1721 }
1722 
1723 /*
1724  * Copy filecaps structure allocating memory for ioctls array if needed.
1725  *
1726  * The last parameter indicates whether the fdtable is locked. If it is not and
1727  * ioctls are encountered, copying fails and the caller must lock the table.
1728  *
1729  * Note that if the table was not locked, the caller has to check the relevant
1730  * sequence counter to determine whether the operation was successful.
1731  */
1732 bool
1733 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1734 {
1735 	size_t size;
1736 
1737 	if (src->fc_ioctls != NULL && !locked)
1738 		return (false);
1739 	memcpy(dst, src, sizeof(*src));
1740 	if (src->fc_ioctls == NULL)
1741 		return (true);
1742 
1743 	KASSERT(src->fc_nioctls > 0,
1744 	    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1745 
1746 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1747 	dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1748 	memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1749 	return (true);
1750 }
1751 
1752 static u_long *
1753 filecaps_copy_prep(const struct filecaps *src)
1754 {
1755 	u_long *ioctls;
1756 	size_t size;
1757 
1758 	if (__predict_true(src->fc_ioctls == NULL))
1759 		return (NULL);
1760 
1761 	KASSERT(src->fc_nioctls > 0,
1762 	    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1763 
1764 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1765 	ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1766 	return (ioctls);
1767 }
1768 
1769 static void
1770 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1771     u_long *ioctls)
1772 {
1773 	size_t size;
1774 
1775 	*dst = *src;
1776 	if (__predict_true(src->fc_ioctls == NULL)) {
1777 		MPASS(ioctls == NULL);
1778 		return;
1779 	}
1780 
1781 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1782 	dst->fc_ioctls = ioctls;
1783 	bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1784 }
1785 
1786 /*
1787  * Move filecaps structure to the new place and clear the old place.
1788  */
1789 void
1790 filecaps_move(struct filecaps *src, struct filecaps *dst)
1791 {
1792 
1793 	*dst = *src;
1794 	bzero(src, sizeof(*src));
1795 }
1796 
1797 /*
1798  * Fill the given filecaps structure with full rights.
1799  */
1800 static void
1801 filecaps_fill(struct filecaps *fcaps)
1802 {
1803 
1804 	CAP_ALL(&fcaps->fc_rights);
1805 	fcaps->fc_ioctls = NULL;
1806 	fcaps->fc_nioctls = -1;
1807 	fcaps->fc_fcntls = CAP_FCNTL_ALL;
1808 }
1809 
1810 /*
1811  * Free memory allocated within filecaps structure.
1812  */
1813 static void
1814 filecaps_free_ioctl(struct filecaps *fcaps)
1815 {
1816 
1817 	free(fcaps->fc_ioctls, M_FILECAPS);
1818 	fcaps->fc_ioctls = NULL;
1819 }
1820 
1821 void
1822 filecaps_free(struct filecaps *fcaps)
1823 {
1824 
1825 	filecaps_free_ioctl(fcaps);
1826 	bzero(fcaps, sizeof(*fcaps));
1827 }
1828 
1829 static u_long *
1830 filecaps_free_prep(struct filecaps *fcaps)
1831 {
1832 	u_long *ioctls;
1833 
1834 	ioctls = fcaps->fc_ioctls;
1835 	bzero(fcaps, sizeof(*fcaps));
1836 	return (ioctls);
1837 }
1838 
1839 static void
1840 filecaps_free_finish(u_long *ioctls)
1841 {
1842 
1843 	free(ioctls, M_FILECAPS);
1844 }
1845 
1846 /*
1847  * Validate the given filecaps structure.
1848  */
1849 static void
1850 filecaps_validate(const struct filecaps *fcaps, const char *func)
1851 {
1852 
1853 	KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1854 	    ("%s: invalid rights", func));
1855 	KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1856 	    ("%s: invalid fcntls", func));
1857 	KASSERT(fcaps->fc_fcntls == 0 ||
1858 	    cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1859 	    ("%s: fcntls without CAP_FCNTL", func));
1860 	/*
1861 	 * open calls without WANTIOCTLCAPS free caps but leave the counter
1862 	 */
1863 #if 0
1864 	KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1865 	    (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1866 	    ("%s: invalid ioctls", func));
1867 #endif
1868 	KASSERT(fcaps->fc_nioctls == 0 ||
1869 	    cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1870 	    ("%s: ioctls without CAP_IOCTL", func));
1871 }
1872 
1873 static void
1874 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1875 {
1876 	int nfd1;
1877 
1878 	FILEDESC_XLOCK_ASSERT(fdp);
1879 
1880 	nfd1 = fdp->fd_nfiles * 2;
1881 	if (nfd1 < nfd)
1882 		nfd1 = nfd;
1883 	fdgrowtable(fdp, nfd1);
1884 }
1885 
1886 /*
1887  * Grow the file table to accommodate (at least) nfd descriptors.
1888  */
1889 static void
1890 fdgrowtable(struct filedesc *fdp, int nfd)
1891 {
1892 	struct filedesc0 *fdp0;
1893 	struct freetable *ft;
1894 	struct fdescenttbl *ntable;
1895 	struct fdescenttbl *otable;
1896 	int nnfiles, onfiles;
1897 	NDSLOTTYPE *nmap, *omap;
1898 
1899 	KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1900 
1901 	/* save old values */
1902 	onfiles = fdp->fd_nfiles;
1903 	otable = fdp->fd_files;
1904 	omap = fdp->fd_map;
1905 
1906 	/* compute the size of the new table */
1907 	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1908 	if (nnfiles <= onfiles)
1909 		/* the table is already large enough */
1910 		return;
1911 
1912 	/*
1913 	 * Allocate a new table.  We need enough space for the number of
1914 	 * entries, file entries themselves and the struct freetable we will use
1915 	 * when we decommission the table and place it on the freelist.
1916 	 * We place the struct freetable in the middle so we don't have
1917 	 * to worry about padding.
1918 	 */
1919 	ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1920 	    nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1921 	    sizeof(struct freetable),
1922 	    M_FILEDESC, M_ZERO | M_WAITOK);
1923 	/* copy the old data */
1924 	ntable->fdt_nfiles = nnfiles;
1925 	memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1926 	    onfiles * sizeof(ntable->fdt_ofiles[0]));
1927 
1928 	/*
1929 	 * Allocate a new map only if the old is not large enough.  It will
1930 	 * grow at a slower rate than the table as it can map more
1931 	 * entries than the table can hold.
1932 	 */
1933 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1934 		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1935 		    M_ZERO | M_WAITOK);
1936 		/* copy over the old data and update the pointer */
1937 		memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1938 		fdp->fd_map = nmap;
1939 	}
1940 
1941 	/*
1942 	 * Make sure that ntable is correctly initialized before we replace
1943 	 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1944 	 * data.
1945 	 */
1946 	atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1947 
1948 	/*
1949 	 * Free the old file table when not shared by other threads or processes.
1950 	 * The old file table is considered to be shared when either are true:
1951 	 * - The process has more than one thread.
1952 	 * - The file descriptor table has been shared via fdshare().
1953 	 *
1954 	 * When shared, the old file table will be placed on a freelist
1955 	 * which will be processed when the struct filedesc is released.
1956 	 *
1957 	 * Note that if onfiles == NDFILE, we're dealing with the original
1958 	 * static allocation contained within (struct filedesc0 *)fdp,
1959 	 * which must not be freed.
1960 	 */
1961 	if (onfiles > NDFILE) {
1962 		/*
1963 		 * Note we may be called here from fdinit while allocating a
1964 		 * table for a new process in which case ->p_fd points
1965 		 * elsewhere.
1966 		 */
1967 		if (curproc->p_fd != fdp || FILEDESC_IS_ONLY_USER(fdp)) {
1968 			free(otable, M_FILEDESC);
1969 		} else {
1970 			ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1971 			fdp0 = (struct filedesc0 *)fdp;
1972 			ft->ft_table = otable;
1973 			SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1974 		}
1975 	}
1976 	/*
1977 	 * The map does not have the same possibility of threads still
1978 	 * holding references to it.  So always free it as long as it
1979 	 * does not reference the original static allocation.
1980 	 */
1981 	if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1982 		free(omap, M_FILEDESC);
1983 }
1984 
1985 /*
1986  * Allocate a file descriptor for the process.
1987  */
1988 int
1989 fdalloc(struct thread *td, int minfd, int *result)
1990 {
1991 	struct proc *p = td->td_proc;
1992 	struct filedesc *fdp = p->p_fd;
1993 	int fd, maxfd, allocfd;
1994 #ifdef RACCT
1995 	int error;
1996 #endif
1997 
1998 	FILEDESC_XLOCK_ASSERT(fdp);
1999 
2000 	if (fdp->fd_freefile > minfd)
2001 		minfd = fdp->fd_freefile;
2002 
2003 	maxfd = getmaxfd(td);
2004 
2005 	/*
2006 	 * Search the bitmap for a free descriptor starting at minfd.
2007 	 * If none is found, grow the file table.
2008 	 */
2009 	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
2010 	if (__predict_false(fd >= maxfd))
2011 		return (EMFILE);
2012 	if (__predict_false(fd >= fdp->fd_nfiles)) {
2013 		allocfd = min(fd * 2, maxfd);
2014 #ifdef RACCT
2015 		if (RACCT_ENABLED()) {
2016 			error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
2017 			if (error != 0)
2018 				return (EMFILE);
2019 		}
2020 #endif
2021 		/*
2022 		 * fd is already equal to first free descriptor >= minfd, so
2023 		 * we only need to grow the table and we are done.
2024 		 */
2025 		fdgrowtable_exp(fdp, allocfd);
2026 	}
2027 
2028 	/*
2029 	 * Perform some sanity checks, then mark the file descriptor as
2030 	 * used and return it to the caller.
2031 	 */
2032 	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
2033 	    ("invalid descriptor %d", fd));
2034 	KASSERT(!fdisused(fdp, fd),
2035 	    ("fd_first_free() returned non-free descriptor"));
2036 	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
2037 	    ("file descriptor isn't free"));
2038 	fdused(fdp, fd);
2039 	*result = fd;
2040 	return (0);
2041 }
2042 
2043 /*
2044  * Allocate n file descriptors for the process.
2045  */
2046 int
2047 fdallocn(struct thread *td, int minfd, int *fds, int n)
2048 {
2049 	struct proc *p = td->td_proc;
2050 	struct filedesc *fdp = p->p_fd;
2051 	int i;
2052 
2053 	FILEDESC_XLOCK_ASSERT(fdp);
2054 
2055 	for (i = 0; i < n; i++)
2056 		if (fdalloc(td, 0, &fds[i]) != 0)
2057 			break;
2058 
2059 	if (i < n) {
2060 		for (i--; i >= 0; i--)
2061 			fdunused(fdp, fds[i]);
2062 		return (EMFILE);
2063 	}
2064 
2065 	return (0);
2066 }
2067 
2068 /*
2069  * Create a new open file structure and allocate a file descriptor for the
2070  * process that refers to it.  We add one reference to the file for the
2071  * descriptor table and one reference for resultfp. This is to prevent us
2072  * being preempted and the entry in the descriptor table closed after we
2073  * release the FILEDESC lock.
2074  */
2075 int
2076 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
2077     struct filecaps *fcaps)
2078 {
2079 	struct file *fp;
2080 	int error, fd;
2081 
2082 	MPASS(resultfp != NULL);
2083 	MPASS(resultfd != NULL);
2084 
2085 	error = _falloc_noinstall(td, &fp, 2);
2086 	if (__predict_false(error != 0)) {
2087 		return (error);
2088 	}
2089 
2090 	error = finstall_refed(td, fp, &fd, flags, fcaps);
2091 	if (__predict_false(error != 0)) {
2092 		falloc_abort(td, fp);
2093 		return (error);
2094 	}
2095 
2096 	*resultfp = fp;
2097 	*resultfd = fd;
2098 
2099 	return (0);
2100 }
2101 
2102 /*
2103  * Create a new open file structure without allocating a file descriptor.
2104  */
2105 int
2106 _falloc_noinstall(struct thread *td, struct file **resultfp, u_int n)
2107 {
2108 	struct file *fp;
2109 	int maxuserfiles = maxfiles - (maxfiles / 20);
2110 	int openfiles_new;
2111 	static struct timeval lastfail;
2112 	static int curfail;
2113 
2114 	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
2115 	MPASS(n > 0);
2116 
2117 	openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
2118 	if ((openfiles_new >= maxuserfiles &&
2119 	    priv_check(td, PRIV_MAXFILES) != 0) ||
2120 	    openfiles_new >= maxfiles) {
2121 		atomic_subtract_int(&openfiles, 1);
2122 		if (ppsratecheck(&lastfail, &curfail, 1)) {
2123 			printf("kern.maxfiles limit exceeded by uid %i, (%s) "
2124 			    "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
2125 		}
2126 		return (ENFILE);
2127 	}
2128 	fp = uma_zalloc(file_zone, M_WAITOK);
2129 	bzero(fp, sizeof(*fp));
2130 	refcount_init(&fp->f_count, n);
2131 	fp->f_cred = crhold(td->td_ucred);
2132 	fp->f_ops = &badfileops;
2133 	*resultfp = fp;
2134 	return (0);
2135 }
2136 
2137 void
2138 falloc_abort(struct thread *td, struct file *fp)
2139 {
2140 
2141 	/*
2142 	 * For assertion purposes.
2143 	 */
2144 	refcount_init(&fp->f_count, 0);
2145 	_fdrop(fp, td);
2146 }
2147 
2148 /*
2149  * Install a file in a file descriptor table.
2150  */
2151 void
2152 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
2153     struct filecaps *fcaps)
2154 {
2155 	struct filedescent *fde;
2156 
2157 	MPASS(fp != NULL);
2158 	if (fcaps != NULL)
2159 		filecaps_validate(fcaps, __func__);
2160 	FILEDESC_XLOCK_ASSERT(fdp);
2161 
2162 	fde = &fdp->fd_ofiles[fd];
2163 #ifdef CAPABILITIES
2164 	seqc_write_begin(&fde->fde_seqc);
2165 #endif
2166 	fde->fde_file = fp;
2167 	fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
2168 	if (fcaps != NULL)
2169 		filecaps_move(fcaps, &fde->fde_caps);
2170 	else
2171 		filecaps_fill(&fde->fde_caps);
2172 #ifdef CAPABILITIES
2173 	seqc_write_end(&fde->fde_seqc);
2174 #endif
2175 }
2176 
2177 int
2178 finstall_refed(struct thread *td, struct file *fp, int *fd, int flags,
2179     struct filecaps *fcaps)
2180 {
2181 	struct filedesc *fdp = td->td_proc->p_fd;
2182 	int error;
2183 
2184 	MPASS(fd != NULL);
2185 
2186 	FILEDESC_XLOCK(fdp);
2187 	error = fdalloc(td, 0, fd);
2188 	if (__predict_true(error == 0)) {
2189 		_finstall(fdp, fp, *fd, flags, fcaps);
2190 	}
2191 	FILEDESC_XUNLOCK(fdp);
2192 	return (error);
2193 }
2194 
2195 int
2196 finstall(struct thread *td, struct file *fp, int *fd, int flags,
2197     struct filecaps *fcaps)
2198 {
2199 	int error;
2200 
2201 	MPASS(fd != NULL);
2202 
2203 	if (!fhold(fp))
2204 		return (EBADF);
2205 	error = finstall_refed(td, fp, fd, flags, fcaps);
2206 	if (__predict_false(error != 0)) {
2207 		fdrop(fp, td);
2208 	}
2209 	return (error);
2210 }
2211 
2212 /*
2213  * Build a new filedesc structure from another.
2214  *
2215  * If fdp is not NULL, return with it shared locked.
2216  */
2217 struct filedesc *
2218 fdinit(void)
2219 {
2220 	struct filedesc0 *newfdp0;
2221 	struct filedesc *newfdp;
2222 
2223 	newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2224 	newfdp = &newfdp0->fd_fd;
2225 
2226 	/* Create the file descriptor table. */
2227 	FILEDESC_LOCK_INIT(newfdp);
2228 	refcount_init(&newfdp->fd_refcnt, 1);
2229 	refcount_init(&newfdp->fd_holdcnt, 1);
2230 	newfdp->fd_map = newfdp0->fd_dmap;
2231 	newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2232 	newfdp->fd_files->fdt_nfiles = NDFILE;
2233 
2234 	return (newfdp);
2235 }
2236 
2237 /*
2238  * Build a pwddesc structure from another.
2239  * Copy the current, root, and jail root vnode references.
2240  *
2241  * If pdp is not NULL and keeplock is true, return with it (exclusively) locked.
2242  */
2243 struct pwddesc *
2244 pdinit(struct pwddesc *pdp, bool keeplock)
2245 {
2246 	struct pwddesc *newpdp;
2247 	struct pwd *newpwd;
2248 
2249 	newpdp = malloc(sizeof(*newpdp), M_PWDDESC, M_WAITOK | M_ZERO);
2250 
2251 	PWDDESC_LOCK_INIT(newpdp);
2252 	refcount_init(&newpdp->pd_refcount, 1);
2253 	newpdp->pd_cmask = CMASK;
2254 
2255 	if (pdp == NULL) {
2256 		newpwd = pwd_alloc();
2257 		smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2258 		return (newpdp);
2259 	}
2260 
2261 	PWDDESC_XLOCK(pdp);
2262 	newpwd = pwd_hold_pwddesc(pdp);
2263 	smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2264 	if (!keeplock)
2265 		PWDDESC_XUNLOCK(pdp);
2266 	return (newpdp);
2267 }
2268 
2269 /*
2270  * Hold either filedesc or pwddesc of the passed process.
2271  *
2272  * The process lock is used to synchronize against the target exiting and
2273  * freeing the data.
2274  *
2275  * Clearing can be ilustrated in 3 steps:
2276  * 1. set the pointer to NULL. Either routine can race against it, hence
2277  *   atomic_load_ptr.
2278  * 2. observe the process lock as not taken. Until then fdhold/pdhold can
2279  *   race to either still see the pointer or find NULL. It is still safe to
2280  *   grab a reference as clearing is stalled.
2281  * 3. after the lock is observed as not taken, any fdhold/pdhold calls are
2282  *   guaranteed to see NULL, making it safe to finish clearing
2283  */
2284 static struct filedesc *
2285 fdhold(struct proc *p)
2286 {
2287 	struct filedesc *fdp;
2288 
2289 	PROC_LOCK_ASSERT(p, MA_OWNED);
2290 	fdp = atomic_load_ptr(&p->p_fd);
2291 	if (fdp != NULL)
2292 		refcount_acquire(&fdp->fd_holdcnt);
2293 	return (fdp);
2294 }
2295 
2296 static struct pwddesc *
2297 pdhold(struct proc *p)
2298 {
2299 	struct pwddesc *pdp;
2300 
2301 	PROC_LOCK_ASSERT(p, MA_OWNED);
2302 	pdp = atomic_load_ptr(&p->p_pd);
2303 	if (pdp != NULL)
2304 		refcount_acquire(&pdp->pd_refcount);
2305 	return (pdp);
2306 }
2307 
2308 static void
2309 fddrop(struct filedesc *fdp)
2310 {
2311 
2312 	if (refcount_load(&fdp->fd_holdcnt) > 1) {
2313 		if (refcount_release(&fdp->fd_holdcnt) == 0)
2314 			return;
2315 	}
2316 
2317 	FILEDESC_LOCK_DESTROY(fdp);
2318 	uma_zfree(filedesc0_zone, fdp);
2319 }
2320 
2321 static void
2322 pddrop(struct pwddesc *pdp)
2323 {
2324 	struct pwd *pwd;
2325 
2326 	if (refcount_release_if_not_last(&pdp->pd_refcount))
2327 		return;
2328 
2329 	PWDDESC_XLOCK(pdp);
2330 	if (refcount_release(&pdp->pd_refcount) == 0) {
2331 		PWDDESC_XUNLOCK(pdp);
2332 		return;
2333 	}
2334 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
2335 	pwd_set(pdp, NULL);
2336 	PWDDESC_XUNLOCK(pdp);
2337 	pwd_drop(pwd);
2338 
2339 	PWDDESC_LOCK_DESTROY(pdp);
2340 	free(pdp, M_PWDDESC);
2341 }
2342 
2343 /*
2344  * Share a filedesc structure.
2345  */
2346 struct filedesc *
2347 fdshare(struct filedesc *fdp)
2348 {
2349 
2350 	refcount_acquire(&fdp->fd_refcnt);
2351 	return (fdp);
2352 }
2353 
2354 /*
2355  * Share a pwddesc structure.
2356  */
2357 struct pwddesc *
2358 pdshare(struct pwddesc *pdp)
2359 {
2360 	refcount_acquire(&pdp->pd_refcount);
2361 	return (pdp);
2362 }
2363 
2364 /*
2365  * Unshare a filedesc structure, if necessary by making a copy
2366  */
2367 void
2368 fdunshare(struct thread *td)
2369 {
2370 	struct filedesc *tmp;
2371 	struct proc *p = td->td_proc;
2372 
2373 	if (refcount_load(&p->p_fd->fd_refcnt) == 1)
2374 		return;
2375 
2376 	tmp = fdcopy(p->p_fd);
2377 	fdescfree(td);
2378 	p->p_fd = tmp;
2379 }
2380 
2381 /*
2382  * Unshare a pwddesc structure.
2383  */
2384 void
2385 pdunshare(struct thread *td)
2386 {
2387 	struct pwddesc *pdp;
2388 	struct proc *p;
2389 
2390 	p = td->td_proc;
2391 	/* Not shared. */
2392 	if (refcount_load(&p->p_pd->pd_refcount) == 1)
2393 		return;
2394 
2395 	pdp = pdcopy(p->p_pd);
2396 	pdescfree(td);
2397 	p->p_pd = pdp;
2398 }
2399 
2400 /*
2401  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
2402  * this is to ease callers, not catch errors.
2403  */
2404 struct filedesc *
2405 fdcopy(struct filedesc *fdp)
2406 {
2407 	struct filedesc *newfdp;
2408 	struct filedescent *nfde, *ofde;
2409 	int i, lastfile;
2410 
2411 	MPASS(fdp != NULL);
2412 
2413 	newfdp = fdinit();
2414 	FILEDESC_SLOCK(fdp);
2415 	for (;;) {
2416 		lastfile = fdlastfile(fdp);
2417 		if (lastfile < newfdp->fd_nfiles)
2418 			break;
2419 		FILEDESC_SUNLOCK(fdp);
2420 		fdgrowtable(newfdp, lastfile + 1);
2421 		FILEDESC_SLOCK(fdp);
2422 	}
2423 	/* copy all passable descriptors (i.e. not kqueue) */
2424 	newfdp->fd_freefile = fdp->fd_freefile;
2425 	FILEDESC_FOREACH_FDE(fdp, i, ofde) {
2426 		if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2427 		    !fhold(ofde->fde_file)) {
2428 			if (newfdp->fd_freefile == fdp->fd_freefile)
2429 				newfdp->fd_freefile = i;
2430 			continue;
2431 		}
2432 		nfde = &newfdp->fd_ofiles[i];
2433 		*nfde = *ofde;
2434 		filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2435 		fdused_init(newfdp, i);
2436 	}
2437 	MPASS(newfdp->fd_freefile != -1);
2438 	FILEDESC_SUNLOCK(fdp);
2439 	return (newfdp);
2440 }
2441 
2442 /*
2443  * Copy a pwddesc structure.
2444  */
2445 struct pwddesc *
2446 pdcopy(struct pwddesc *pdp)
2447 {
2448 	struct pwddesc *newpdp;
2449 
2450 	MPASS(pdp != NULL);
2451 
2452 	newpdp = pdinit(pdp, true);
2453 	newpdp->pd_cmask = pdp->pd_cmask;
2454 	PWDDESC_XUNLOCK(pdp);
2455 	return (newpdp);
2456 }
2457 
2458 /*
2459  * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2460  * one of processes using it exits) and the table used to be shared.
2461  */
2462 static void
2463 fdclearlocks(struct thread *td)
2464 {
2465 	struct filedesc *fdp;
2466 	struct filedesc_to_leader *fdtol;
2467 	struct flock lf;
2468 	struct file *fp;
2469 	struct proc *p;
2470 	struct vnode *vp;
2471 	int i;
2472 
2473 	p = td->td_proc;
2474 	fdp = p->p_fd;
2475 	fdtol = p->p_fdtol;
2476 	MPASS(fdtol != NULL);
2477 
2478 	FILEDESC_XLOCK(fdp);
2479 	KASSERT(fdtol->fdl_refcount > 0,
2480 	    ("filedesc_to_refcount botch: fdl_refcount=%d",
2481 	    fdtol->fdl_refcount));
2482 	if (fdtol->fdl_refcount == 1 &&
2483 	    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2484 		FILEDESC_FOREACH_FP(fdp, i, fp) {
2485 			if (fp->f_type != DTYPE_VNODE ||
2486 			    !fhold(fp))
2487 				continue;
2488 			FILEDESC_XUNLOCK(fdp);
2489 			lf.l_whence = SEEK_SET;
2490 			lf.l_start = 0;
2491 			lf.l_len = 0;
2492 			lf.l_type = F_UNLCK;
2493 			vp = fp->f_vnode;
2494 			(void) VOP_ADVLOCK(vp,
2495 			    (caddr_t)p->p_leader, F_UNLCK,
2496 			    &lf, F_POSIX);
2497 			FILEDESC_XLOCK(fdp);
2498 			fdrop(fp, td);
2499 		}
2500 	}
2501 retry:
2502 	if (fdtol->fdl_refcount == 1) {
2503 		if (fdp->fd_holdleaderscount > 0 &&
2504 		    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2505 			/*
2506 			 * close() or kern_dup() has cleared a reference
2507 			 * in a shared file descriptor table.
2508 			 */
2509 			fdp->fd_holdleaderswakeup = 1;
2510 			sx_sleep(&fdp->fd_holdleaderscount,
2511 			    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2512 			goto retry;
2513 		}
2514 		if (fdtol->fdl_holdcount > 0) {
2515 			/*
2516 			 * Ensure that fdtol->fdl_leader remains
2517 			 * valid in closef().
2518 			 */
2519 			fdtol->fdl_wakeup = 1;
2520 			sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2521 			    "fdlhold", 0);
2522 			goto retry;
2523 		}
2524 	}
2525 	fdtol->fdl_refcount--;
2526 	if (fdtol->fdl_refcount == 0 &&
2527 	    fdtol->fdl_holdcount == 0) {
2528 		fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2529 		fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2530 	} else
2531 		fdtol = NULL;
2532 	p->p_fdtol = NULL;
2533 	FILEDESC_XUNLOCK(fdp);
2534 	if (fdtol != NULL)
2535 		free(fdtol, M_FILEDESC_TO_LEADER);
2536 }
2537 
2538 /*
2539  * Release a filedesc structure.
2540  */
2541 static void
2542 fdescfree_fds(struct thread *td, struct filedesc *fdp)
2543 {
2544 	struct filedesc0 *fdp0;
2545 	struct freetable *ft, *tft;
2546 	struct filedescent *fde;
2547 	struct file *fp;
2548 	int i;
2549 
2550 	KASSERT(refcount_load(&fdp->fd_refcnt) == 0,
2551 	    ("%s: fd table %p carries references", __func__, fdp));
2552 
2553 	/*
2554 	 * Serialize with threads iterating over the table, if any.
2555 	 */
2556 	if (refcount_load(&fdp->fd_holdcnt) > 1) {
2557 		FILEDESC_XLOCK(fdp);
2558 		FILEDESC_XUNLOCK(fdp);
2559 	}
2560 
2561 	FILEDESC_FOREACH_FDE(fdp, i, fde) {
2562 		fp = fde->fde_file;
2563 		fdefree_last(fde);
2564 		(void) closef(fp, td);
2565 	}
2566 
2567 	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2568 		free(fdp->fd_map, M_FILEDESC);
2569 	if (fdp->fd_nfiles > NDFILE)
2570 		free(fdp->fd_files, M_FILEDESC);
2571 
2572 	fdp0 = (struct filedesc0 *)fdp;
2573 	SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2574 		free(ft->ft_table, M_FILEDESC);
2575 
2576 	fddrop(fdp);
2577 }
2578 
2579 void
2580 fdescfree(struct thread *td)
2581 {
2582 	struct proc *p;
2583 	struct filedesc *fdp;
2584 
2585 	p = td->td_proc;
2586 	fdp = p->p_fd;
2587 	MPASS(fdp != NULL);
2588 
2589 #ifdef RACCT
2590 	if (RACCT_ENABLED())
2591 		racct_set_unlocked(p, RACCT_NOFILE, 0);
2592 #endif
2593 
2594 	if (p->p_fdtol != NULL)
2595 		fdclearlocks(td);
2596 
2597 	/*
2598 	 * Check fdhold for an explanation.
2599 	 */
2600 	atomic_store_ptr(&p->p_fd, NULL);
2601 	atomic_thread_fence_seq_cst();
2602 	PROC_WAIT_UNLOCKED(p);
2603 
2604 	if (refcount_release(&fdp->fd_refcnt) == 0)
2605 		return;
2606 
2607 	fdescfree_fds(td, fdp);
2608 }
2609 
2610 void
2611 pdescfree(struct thread *td)
2612 {
2613 	struct proc *p;
2614 	struct pwddesc *pdp;
2615 
2616 	p = td->td_proc;
2617 	pdp = p->p_pd;
2618 	MPASS(pdp != NULL);
2619 
2620 	/*
2621 	 * Check pdhold for an explanation.
2622 	 */
2623 	atomic_store_ptr(&p->p_pd, NULL);
2624 	atomic_thread_fence_seq_cst();
2625 	PROC_WAIT_UNLOCKED(p);
2626 
2627 	pddrop(pdp);
2628 }
2629 
2630 /*
2631  * For setugid programs, we don't want to people to use that setugidness
2632  * to generate error messages which write to a file which otherwise would
2633  * otherwise be off-limits to the process.  We check for filesystems where
2634  * the vnode can change out from under us after execve (like [lin]procfs).
2635  *
2636  * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2637  * sufficient.  We also don't check for setugidness since we know we are.
2638  */
2639 static bool
2640 is_unsafe(struct file *fp)
2641 {
2642 	struct vnode *vp;
2643 
2644 	if (fp->f_type != DTYPE_VNODE)
2645 		return (false);
2646 
2647 	vp = fp->f_vnode;
2648 	return ((vp->v_vflag & VV_PROCDEP) != 0);
2649 }
2650 
2651 /*
2652  * Make this setguid thing safe, if at all possible.
2653  */
2654 void
2655 fdsetugidsafety(struct thread *td)
2656 {
2657 	struct filedesc *fdp;
2658 	struct file *fp;
2659 	int i;
2660 
2661 	fdp = td->td_proc->p_fd;
2662 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2663 	    ("the fdtable should not be shared"));
2664 	MPASS(fdp->fd_nfiles >= 3);
2665 	for (i = 0; i <= 2; i++) {
2666 		fp = fdp->fd_ofiles[i].fde_file;
2667 		if (fp != NULL && is_unsafe(fp)) {
2668 			FILEDESC_XLOCK(fdp);
2669 			knote_fdclose(td, i);
2670 			/*
2671 			 * NULL-out descriptor prior to close to avoid
2672 			 * a race while close blocks.
2673 			 */
2674 			fdfree(fdp, i);
2675 			FILEDESC_XUNLOCK(fdp);
2676 			(void) closef(fp, td);
2677 		}
2678 	}
2679 }
2680 
2681 /*
2682  * If a specific file object occupies a specific file descriptor, close the
2683  * file descriptor entry and drop a reference on the file object.  This is a
2684  * convenience function to handle a subsequent error in a function that calls
2685  * falloc() that handles the race that another thread might have closed the
2686  * file descriptor out from under the thread creating the file object.
2687  */
2688 void
2689 fdclose(struct thread *td, struct file *fp, int idx)
2690 {
2691 	struct filedesc *fdp = td->td_proc->p_fd;
2692 
2693 	FILEDESC_XLOCK(fdp);
2694 	if (fdp->fd_ofiles[idx].fde_file == fp) {
2695 		fdfree(fdp, idx);
2696 		FILEDESC_XUNLOCK(fdp);
2697 		fdrop(fp, td);
2698 	} else
2699 		FILEDESC_XUNLOCK(fdp);
2700 }
2701 
2702 /*
2703  * Close any files on exec?
2704  */
2705 void
2706 fdcloseexec(struct thread *td)
2707 {
2708 	struct filedesc *fdp;
2709 	struct filedescent *fde;
2710 	struct file *fp;
2711 	int i;
2712 
2713 	fdp = td->td_proc->p_fd;
2714 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2715 	    ("the fdtable should not be shared"));
2716 	FILEDESC_FOREACH_FDE(fdp, i, fde) {
2717 		fp = fde->fde_file;
2718 		if (fp->f_type == DTYPE_MQUEUE ||
2719 		    (fde->fde_flags & UF_EXCLOSE)) {
2720 			FILEDESC_XLOCK(fdp);
2721 			fdfree(fdp, i);
2722 			(void) closefp(fdp, i, fp, td, false, false);
2723 			FILEDESC_UNLOCK_ASSERT(fdp);
2724 		}
2725 	}
2726 }
2727 
2728 /*
2729  * It is unsafe for set[ug]id processes to be started with file
2730  * descriptors 0..2 closed, as these descriptors are given implicit
2731  * significance in the Standard C library.  fdcheckstd() will create a
2732  * descriptor referencing /dev/null for each of stdin, stdout, and
2733  * stderr that is not already open.
2734  */
2735 int
2736 fdcheckstd(struct thread *td)
2737 {
2738 	struct filedesc *fdp;
2739 	register_t save;
2740 	int i, error, devnull;
2741 
2742 	fdp = td->td_proc->p_fd;
2743 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2744 	    ("the fdtable should not be shared"));
2745 	MPASS(fdp->fd_nfiles >= 3);
2746 	devnull = -1;
2747 	for (i = 0; i <= 2; i++) {
2748 		if (fdp->fd_ofiles[i].fde_file != NULL)
2749 			continue;
2750 
2751 		save = td->td_retval[0];
2752 		if (devnull != -1) {
2753 			error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2754 		} else {
2755 			error = kern_openat(td, AT_FDCWD, "/dev/null",
2756 			    UIO_SYSSPACE, O_RDWR, 0);
2757 			if (error == 0) {
2758 				devnull = td->td_retval[0];
2759 				KASSERT(devnull == i, ("we didn't get our fd"));
2760 			}
2761 		}
2762 		td->td_retval[0] = save;
2763 		if (error != 0)
2764 			return (error);
2765 	}
2766 	return (0);
2767 }
2768 
2769 /*
2770  * Internal form of close.  Decrement reference count on file structure.
2771  * Note: td may be NULL when closing a file that was being passed in a
2772  * message.
2773  */
2774 int
2775 closef(struct file *fp, struct thread *td)
2776 {
2777 	struct vnode *vp;
2778 	struct flock lf;
2779 	struct filedesc_to_leader *fdtol;
2780 	struct filedesc *fdp;
2781 
2782 	MPASS(td != NULL);
2783 
2784 	/*
2785 	 * POSIX record locking dictates that any close releases ALL
2786 	 * locks owned by this process.  This is handled by setting
2787 	 * a flag in the unlock to free ONLY locks obeying POSIX
2788 	 * semantics, and not to free BSD-style file locks.
2789 	 * If the descriptor was in a message, POSIX-style locks
2790 	 * aren't passed with the descriptor, and the thread pointer
2791 	 * will be NULL.  Callers should be careful only to pass a
2792 	 * NULL thread pointer when there really is no owning
2793 	 * context that might have locks, or the locks will be
2794 	 * leaked.
2795 	 */
2796 	if (fp->f_type == DTYPE_VNODE) {
2797 		vp = fp->f_vnode;
2798 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2799 			lf.l_whence = SEEK_SET;
2800 			lf.l_start = 0;
2801 			lf.l_len = 0;
2802 			lf.l_type = F_UNLCK;
2803 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2804 			    F_UNLCK, &lf, F_POSIX);
2805 		}
2806 		fdtol = td->td_proc->p_fdtol;
2807 		if (fdtol != NULL) {
2808 			/*
2809 			 * Handle special case where file descriptor table is
2810 			 * shared between multiple process leaders.
2811 			 */
2812 			fdp = td->td_proc->p_fd;
2813 			FILEDESC_XLOCK(fdp);
2814 			for (fdtol = fdtol->fdl_next;
2815 			    fdtol != td->td_proc->p_fdtol;
2816 			    fdtol = fdtol->fdl_next) {
2817 				if ((fdtol->fdl_leader->p_flag &
2818 				    P_ADVLOCK) == 0)
2819 					continue;
2820 				fdtol->fdl_holdcount++;
2821 				FILEDESC_XUNLOCK(fdp);
2822 				lf.l_whence = SEEK_SET;
2823 				lf.l_start = 0;
2824 				lf.l_len = 0;
2825 				lf.l_type = F_UNLCK;
2826 				vp = fp->f_vnode;
2827 				(void) VOP_ADVLOCK(vp,
2828 				    (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2829 				    F_POSIX);
2830 				FILEDESC_XLOCK(fdp);
2831 				fdtol->fdl_holdcount--;
2832 				if (fdtol->fdl_holdcount == 0 &&
2833 				    fdtol->fdl_wakeup != 0) {
2834 					fdtol->fdl_wakeup = 0;
2835 					wakeup(fdtol);
2836 				}
2837 			}
2838 			FILEDESC_XUNLOCK(fdp);
2839 		}
2840 	}
2841 	return (fdrop_close(fp, td));
2842 }
2843 
2844 /*
2845  * Hack for file descriptor passing code.
2846  */
2847 void
2848 closef_nothread(struct file *fp)
2849 {
2850 
2851 	fdrop(fp, NULL);
2852 }
2853 
2854 /*
2855  * Initialize the file pointer with the specified properties.
2856  *
2857  * The ops are set with release semantics to be certain that the flags, type,
2858  * and data are visible when ops is.  This is to prevent ops methods from being
2859  * called with bad data.
2860  */
2861 void
2862 finit(struct file *fp, u_int flag, short type, void *data,
2863     const struct fileops *ops)
2864 {
2865 	fp->f_data = data;
2866 	fp->f_flag = flag;
2867 	fp->f_type = type;
2868 	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2869 }
2870 
2871 void
2872 finit_vnode(struct file *fp, u_int flag, void *data, const struct fileops *ops)
2873 {
2874 	fp->f_seqcount[UIO_READ] = 1;
2875 	fp->f_seqcount[UIO_WRITE] = 1;
2876 	finit(fp, (flag & FMASK) | (fp->f_flag & FHASLOCK), DTYPE_VNODE,
2877 	    data, ops);
2878 }
2879 
2880 int
2881 fget_cap_noref(struct filedesc *fdp, int fd, const cap_rights_t *needrightsp,
2882     struct file **fpp, struct filecaps *havecapsp)
2883 {
2884 	struct filedescent *fde;
2885 	int error;
2886 
2887 	FILEDESC_LOCK_ASSERT(fdp);
2888 
2889 	*fpp = NULL;
2890 	fde = fdeget_noref(fdp, fd);
2891 	if (fde == NULL) {
2892 		error = EBADF;
2893 		goto out;
2894 	}
2895 
2896 #ifdef CAPABILITIES
2897 	error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2898 	if (error != 0)
2899 		goto out;
2900 #endif
2901 
2902 	if (havecapsp != NULL)
2903 		filecaps_copy(&fde->fde_caps, havecapsp, true);
2904 
2905 	*fpp = fde->fde_file;
2906 
2907 	error = 0;
2908 out:
2909 	return (error);
2910 }
2911 
2912 #ifdef CAPABILITIES
2913 int
2914 fget_cap(struct thread *td, int fd, const cap_rights_t *needrightsp,
2915     struct file **fpp, struct filecaps *havecapsp)
2916 {
2917 	struct filedesc *fdp = td->td_proc->p_fd;
2918 	int error;
2919 	struct file *fp;
2920 	seqc_t seq;
2921 
2922 	*fpp = NULL;
2923 	for (;;) {
2924 		error = fget_unlocked_seq(td, fd, needrightsp, &fp, &seq);
2925 		if (error != 0)
2926 			return (error);
2927 
2928 		if (havecapsp != NULL) {
2929 			if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2930 			    havecapsp, false)) {
2931 				fdrop(fp, td);
2932 				goto get_locked;
2933 			}
2934 		}
2935 
2936 		if (!fd_modified(fdp, fd, seq))
2937 			break;
2938 		fdrop(fp, td);
2939 	}
2940 
2941 	*fpp = fp;
2942 	return (0);
2943 
2944 get_locked:
2945 	FILEDESC_SLOCK(fdp);
2946 	error = fget_cap_noref(fdp, fd, needrightsp, fpp, havecapsp);
2947 	if (error == 0 && !fhold(*fpp))
2948 		error = EBADF;
2949 	FILEDESC_SUNLOCK(fdp);
2950 	return (error);
2951 }
2952 #else
2953 int
2954 fget_cap(struct thread *td, int fd, const cap_rights_t *needrightsp,
2955     struct file **fpp, struct filecaps *havecapsp)
2956 {
2957 	int error;
2958 	error = fget_unlocked(td, fd, needrightsp, fpp);
2959 	if (havecapsp != NULL && error == 0)
2960 		filecaps_fill(havecapsp);
2961 
2962 	return (error);
2963 }
2964 #endif
2965 
2966 int
2967 fget_remote(struct thread *td, struct proc *p, int fd, struct file **fpp)
2968 {
2969 	struct filedesc *fdp;
2970 	struct file *fp;
2971 	int error;
2972 
2973 	if (p == td->td_proc)	/* curproc */
2974 		return (fget_unlocked(td, fd, &cap_no_rights, fpp));
2975 
2976 	PROC_LOCK(p);
2977 	fdp = fdhold(p);
2978 	PROC_UNLOCK(p);
2979 	if (fdp == NULL)
2980 		return (ENOENT);
2981 	FILEDESC_SLOCK(fdp);
2982 	if (refcount_load(&fdp->fd_refcnt) != 0) {
2983 		fp = fget_noref(fdp, fd);
2984 		if (fp != NULL && fhold(fp)) {
2985 			*fpp = fp;
2986 			error = 0;
2987 		} else {
2988 			error = EBADF;
2989 		}
2990 	} else {
2991 		error = ENOENT;
2992 	}
2993 	FILEDESC_SUNLOCK(fdp);
2994 	fddrop(fdp);
2995 	return (error);
2996 }
2997 
2998 int
2999 fget_remote_foreach(struct thread *td, struct proc *p,
3000     int (*fn)(struct proc *, int, struct file *, void *), void *arg)
3001 {
3002 	struct filedesc *fdp;
3003 	struct fdescenttbl *fdt;
3004 	struct file *fp;
3005 	int error, error1, fd, highfd;
3006 
3007 	error = 0;
3008 	PROC_LOCK(p);
3009 	fdp = fdhold(p);
3010 	PROC_UNLOCK(p);
3011 	if (fdp == NULL)
3012 		return (ENOENT);
3013 
3014 	FILEDESC_SLOCK(fdp);
3015 	if (refcount_load(&fdp->fd_refcnt) != 0) {
3016 		fdt = atomic_load_ptr(&fdp->fd_files);
3017 		highfd = fdt->fdt_nfiles - 1;
3018 		FILEDESC_SUNLOCK(fdp);
3019 	} else {
3020 		error = ENOENT;
3021 		FILEDESC_SUNLOCK(fdp);
3022 		goto out;
3023 	}
3024 
3025 	for (fd = 0; fd <= highfd; fd++) {
3026 		error1 = fget_remote(td, p, fd, &fp);
3027 		if (error1 != 0)
3028 			continue;
3029 		error = fn(p, fd, fp, arg);
3030 		fdrop(fp, td);
3031 		if (error != 0)
3032 			break;
3033 	}
3034 out:
3035 	fddrop(fdp);
3036 	return (error);
3037 }
3038 
3039 #ifdef CAPABILITIES
3040 int
3041 fgetvp_lookup_smr(struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3042 {
3043 	const struct filedescent *fde;
3044 	const struct fdescenttbl *fdt;
3045 	struct filedesc *fdp;
3046 	struct file *fp;
3047 	struct vnode *vp;
3048 	const cap_rights_t *haverights;
3049 	cap_rights_t rights;
3050 	seqc_t seq;
3051 	int fd;
3052 
3053 	VFS_SMR_ASSERT_ENTERED();
3054 
3055 	fd = ndp->ni_dirfd;
3056 	rights = *ndp->ni_rightsneeded;
3057 	cap_rights_set_one(&rights, CAP_LOOKUP);
3058 
3059 	fdp = curproc->p_fd;
3060 	fdt = fdp->fd_files;
3061 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3062 		return (EBADF);
3063 	seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3064 	fde = &fdt->fdt_ofiles[fd];
3065 	haverights = cap_rights_fde_inline(fde);
3066 	fp = fde->fde_file;
3067 	if (__predict_false(fp == NULL))
3068 		return (EAGAIN);
3069 	if (__predict_false(cap_check_inline_transient(haverights, &rights)))
3070 		return (EAGAIN);
3071 	*fsearch = ((fp->f_flag & FSEARCH) != 0);
3072 	vp = fp->f_vnode;
3073 	if (__predict_false(vp == NULL)) {
3074 		return (EAGAIN);
3075 	}
3076 	if (!filecaps_copy(&fde->fde_caps, &ndp->ni_filecaps, false)) {
3077 		return (EAGAIN);
3078 	}
3079 	/*
3080 	 * Use an acquire barrier to force re-reading of fdt so it is
3081 	 * refreshed for verification.
3082 	 */
3083 	atomic_thread_fence_acq();
3084 	fdt = fdp->fd_files;
3085 	if (__predict_false(!seqc_consistent_no_fence(fd_seqc(fdt, fd), seq)))
3086 		return (EAGAIN);
3087 	/*
3088 	 * If file descriptor doesn't have all rights,
3089 	 * all lookups relative to it must also be
3090 	 * strictly relative.
3091 	 *
3092 	 * Not yet supported by fast path.
3093 	 */
3094 	CAP_ALL(&rights);
3095 	if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3096 	    ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3097 	    ndp->ni_filecaps.fc_nioctls != -1) {
3098 #ifdef notyet
3099 		ndp->ni_lcf |= NI_LCF_STRICTREL;
3100 #else
3101 		return (EAGAIN);
3102 #endif
3103 	}
3104 	*vpp = vp;
3105 	return (0);
3106 }
3107 #else
3108 int
3109 fgetvp_lookup_smr(struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3110 {
3111 	const struct fdescenttbl *fdt;
3112 	struct filedesc *fdp;
3113 	struct file *fp;
3114 	struct vnode *vp;
3115 	int fd;
3116 
3117 	VFS_SMR_ASSERT_ENTERED();
3118 
3119 	fd = ndp->ni_dirfd;
3120 	fdp = curproc->p_fd;
3121 	fdt = fdp->fd_files;
3122 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3123 		return (EBADF);
3124 	fp = fdt->fdt_ofiles[fd].fde_file;
3125 	if (__predict_false(fp == NULL))
3126 		return (EAGAIN);
3127 	*fsearch = ((fp->f_flag & FSEARCH) != 0);
3128 	vp = fp->f_vnode;
3129 	if (__predict_false(vp == NULL || vp->v_type != VDIR)) {
3130 		return (EAGAIN);
3131 	}
3132 	/*
3133 	 * Use an acquire barrier to force re-reading of fdt so it is
3134 	 * refreshed for verification.
3135 	 */
3136 	atomic_thread_fence_acq();
3137 	fdt = fdp->fd_files;
3138 	if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3139 		return (EAGAIN);
3140 	filecaps_fill(&ndp->ni_filecaps);
3141 	*vpp = vp;
3142 	return (0);
3143 }
3144 #endif
3145 
3146 int
3147 fgetvp_lookup(struct nameidata *ndp, struct vnode **vpp)
3148 {
3149 	struct thread *td;
3150 	struct file *fp;
3151 	struct vnode *vp;
3152 	struct componentname *cnp;
3153 	cap_rights_t rights;
3154 	int error;
3155 
3156 	td = curthread;
3157 	rights = *ndp->ni_rightsneeded;
3158 	cap_rights_set_one(&rights, CAP_LOOKUP);
3159 	cnp = &ndp->ni_cnd;
3160 
3161 	error = fget_cap(td, ndp->ni_dirfd, &rights, &fp, &ndp->ni_filecaps);
3162 	if (__predict_false(error != 0))
3163 		return (error);
3164 	if (__predict_false(fp->f_ops == &badfileops)) {
3165 		error = EBADF;
3166 		goto out_free;
3167 	}
3168 	vp = fp->f_vnode;
3169 	if (__predict_false(vp == NULL)) {
3170 		error = ENOTDIR;
3171 		goto out_free;
3172 	}
3173 	vrefact(vp);
3174 	/*
3175 	 * XXX does not check for VDIR, handled by namei_setup
3176 	 */
3177 	if ((fp->f_flag & FSEARCH) != 0)
3178 		cnp->cn_flags |= NOEXECCHECK;
3179 	fdrop(fp, td);
3180 
3181 #ifdef CAPABILITIES
3182 	/*
3183 	 * If file descriptor doesn't have all rights,
3184 	 * all lookups relative to it must also be
3185 	 * strictly relative.
3186 	 */
3187 	CAP_ALL(&rights);
3188 	if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3189 	    ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3190 	    ndp->ni_filecaps.fc_nioctls != -1) {
3191 		ndp->ni_lcf |= NI_LCF_STRICTREL;
3192 		ndp->ni_resflags |= NIRES_STRICTREL;
3193 	}
3194 #endif
3195 
3196 	/*
3197 	 * TODO: avoid copying ioctl caps if it can be helped to begin with
3198 	 */
3199 	if ((cnp->cn_flags & WANTIOCTLCAPS) == 0)
3200 		filecaps_free_ioctl(&ndp->ni_filecaps);
3201 
3202 	*vpp = vp;
3203 	return (0);
3204 
3205 out_free:
3206 	filecaps_free(&ndp->ni_filecaps);
3207 	fdrop(fp, td);
3208 	return (error);
3209 }
3210 
3211 /*
3212  * Fetch the descriptor locklessly.
3213  *
3214  * We avoid fdrop() races by never raising a refcount above 0.  To accomplish
3215  * this we have to use a cmpset loop rather than an atomic_add.  The descriptor
3216  * must be re-verified once we acquire a reference to be certain that the
3217  * identity is still correct and we did not lose a race due to preemption.
3218  *
3219  * Force a reload of fdt when looping. Another thread could reallocate
3220  * the table before this fd was closed, so it is possible that there is
3221  * a stale fp pointer in cached version.
3222  */
3223 #ifdef CAPABILITIES
3224 static int
3225 fget_unlocked_seq(struct thread *td, int fd, const cap_rights_t *needrightsp,
3226     struct file **fpp, seqc_t *seqp)
3227 {
3228 	struct filedesc *fdp;
3229 	const struct filedescent *fde;
3230 	const struct fdescenttbl *fdt;
3231 	struct file *fp;
3232 	seqc_t seq;
3233 	cap_rights_t haverights;
3234 	int error;
3235 
3236 	fdp = td->td_proc->p_fd;
3237 	fdt = fdp->fd_files;
3238 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3239 		return (EBADF);
3240 
3241 	for (;;) {
3242 		seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3243 		fde = &fdt->fdt_ofiles[fd];
3244 		haverights = *cap_rights_fde_inline(fde);
3245 		fp = fde->fde_file;
3246 		if (__predict_false(fp == NULL)) {
3247 			if (seqc_consistent(fd_seqc(fdt, fd), seq))
3248 				return (EBADF);
3249 			fdt = atomic_load_ptr(&fdp->fd_files);
3250 			continue;
3251 		}
3252 		error = cap_check_inline(&haverights, needrightsp);
3253 		if (__predict_false(error != 0)) {
3254 			if (seqc_consistent(fd_seqc(fdt, fd), seq))
3255 				return (error);
3256 			fdt = atomic_load_ptr(&fdp->fd_files);
3257 			continue;
3258 		}
3259 		if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3260 			fdt = atomic_load_ptr(&fdp->fd_files);
3261 			continue;
3262 		}
3263 		/*
3264 		 * Use an acquire barrier to force re-reading of fdt so it is
3265 		 * refreshed for verification.
3266 		 */
3267 		atomic_thread_fence_acq();
3268 		fdt = fdp->fd_files;
3269 		if (seqc_consistent_no_fence(fd_seqc(fdt, fd), seq))
3270 			break;
3271 		fdrop(fp, td);
3272 	}
3273 	*fpp = fp;
3274 	if (seqp != NULL) {
3275 		*seqp = seq;
3276 	}
3277 	return (0);
3278 }
3279 #else
3280 static int
3281 fget_unlocked_seq(struct thread *td, int fd, const cap_rights_t *needrightsp,
3282     struct file **fpp, seqc_t *seqp __unused)
3283 {
3284 	struct filedesc *fdp;
3285 	const struct fdescenttbl *fdt;
3286 	struct file *fp;
3287 
3288 	fdp = td->td_proc->p_fd;
3289 	fdt = fdp->fd_files;
3290 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3291 		return (EBADF);
3292 
3293 	for (;;) {
3294 		fp = fdt->fdt_ofiles[fd].fde_file;
3295 		if (__predict_false(fp == NULL))
3296 			return (EBADF);
3297 		if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3298 			fdt = atomic_load_ptr(&fdp->fd_files);
3299 			continue;
3300 		}
3301 		/*
3302 		 * Use an acquire barrier to force re-reading of fdt so it is
3303 		 * refreshed for verification.
3304 		 */
3305 		atomic_thread_fence_acq();
3306 		fdt = fdp->fd_files;
3307 		if (__predict_true(fp == fdt->fdt_ofiles[fd].fde_file))
3308 			break;
3309 		fdrop(fp, td);
3310 	}
3311 	*fpp = fp;
3312 	return (0);
3313 }
3314 #endif
3315 
3316 /*
3317  * See the comments in fget_unlocked_seq for an explanation of how this works.
3318  *
3319  * This is a simplified variant which bails out to the aforementioned routine
3320  * if anything goes wrong. In practice this only happens when userspace is
3321  * racing with itself.
3322  */
3323 int
3324 fget_unlocked(struct thread *td, int fd, const cap_rights_t *needrightsp,
3325     struct file **fpp)
3326 {
3327 	struct filedesc *fdp;
3328 #ifdef CAPABILITIES
3329 	const struct filedescent *fde;
3330 #endif
3331 	const struct fdescenttbl *fdt;
3332 	struct file *fp;
3333 #ifdef CAPABILITIES
3334 	seqc_t seq;
3335 	const cap_rights_t *haverights;
3336 #endif
3337 
3338 	fdp = td->td_proc->p_fd;
3339 	fdt = fdp->fd_files;
3340 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles)) {
3341 		*fpp = NULL;
3342 		return (EBADF);
3343 	}
3344 #ifdef CAPABILITIES
3345 	seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3346 	fde = &fdt->fdt_ofiles[fd];
3347 	haverights = cap_rights_fde_inline(fde);
3348 	fp = fde->fde_file;
3349 #else
3350 	fp = fdt->fdt_ofiles[fd].fde_file;
3351 #endif
3352 	if (__predict_false(fp == NULL))
3353 		goto out_fallback;
3354 #ifdef CAPABILITIES
3355 	if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
3356 		goto out_fallback;
3357 #endif
3358 	if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
3359 		goto out_fallback;
3360 
3361 	/*
3362 	 * Use an acquire barrier to force re-reading of fdt so it is
3363 	 * refreshed for verification.
3364 	 */
3365 	atomic_thread_fence_acq();
3366 	fdt = fdp->fd_files;
3367 #ifdef	CAPABILITIES
3368 	if (__predict_false(!seqc_consistent_no_fence(fd_seqc(fdt, fd), seq)))
3369 #else
3370 	if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3371 #endif
3372 		goto out_fdrop;
3373 	*fpp = fp;
3374 	return (0);
3375 out_fdrop:
3376 	fdrop(fp, td);
3377 out_fallback:
3378 	*fpp = NULL;
3379 	return (fget_unlocked_seq(td, fd, needrightsp, fpp, NULL));
3380 }
3381 
3382 /*
3383  * Translate fd -> file when the caller guarantees the file descriptor table
3384  * can't be changed by others.
3385  *
3386  * Note this does not mean the file object itself is only visible to the caller,
3387  * merely that it wont disappear without having to be referenced.
3388  *
3389  * Must be paired with fput_only_user.
3390  */
3391 #ifdef	CAPABILITIES
3392 int
3393 fget_only_user(struct filedesc *fdp, int fd, const cap_rights_t *needrightsp,
3394     struct file **fpp)
3395 {
3396 	const struct filedescent *fde;
3397 	const struct fdescenttbl *fdt;
3398 	const cap_rights_t *haverights;
3399 	struct file *fp;
3400 	int error;
3401 
3402 	MPASS(FILEDESC_IS_ONLY_USER(fdp));
3403 
3404 	*fpp = NULL;
3405 	if (__predict_false(fd >= fdp->fd_nfiles))
3406 		return (EBADF);
3407 
3408 	fdt = fdp->fd_files;
3409 	fde = &fdt->fdt_ofiles[fd];
3410 	fp = fde->fde_file;
3411 	if (__predict_false(fp == NULL))
3412 		return (EBADF);
3413 	MPASS(refcount_load(&fp->f_count) > 0);
3414 	haverights = cap_rights_fde_inline(fde);
3415 	error = cap_check_inline(haverights, needrightsp);
3416 	if (__predict_false(error != 0))
3417 		return (error);
3418 	*fpp = fp;
3419 	return (0);
3420 }
3421 #else
3422 int
3423 fget_only_user(struct filedesc *fdp, int fd, const cap_rights_t *needrightsp,
3424     struct file **fpp)
3425 {
3426 	struct file *fp;
3427 
3428 	MPASS(FILEDESC_IS_ONLY_USER(fdp));
3429 
3430 	*fpp = NULL;
3431 	if (__predict_false(fd >= fdp->fd_nfiles))
3432 		return (EBADF);
3433 
3434 	fp = fdp->fd_ofiles[fd].fde_file;
3435 	if (__predict_false(fp == NULL))
3436 		return (EBADF);
3437 
3438 	MPASS(refcount_load(&fp->f_count) > 0);
3439 	*fpp = fp;
3440 	return (0);
3441 }
3442 #endif
3443 
3444 /*
3445  * Extract the file pointer associated with the specified descriptor for the
3446  * current user process.
3447  *
3448  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
3449  * returned.
3450  *
3451  * File's rights will be checked against the capability rights mask.
3452  *
3453  * If an error occurred the non-zero error is returned and *fpp is set to
3454  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
3455  * responsible for fdrop().
3456  */
3457 static __inline int
3458 _fget(struct thread *td, int fd, struct file **fpp, int flags,
3459     const cap_rights_t *needrightsp)
3460 {
3461 	struct file *fp;
3462 	int error;
3463 
3464 	*fpp = NULL;
3465 	error = fget_unlocked(td, fd, needrightsp, &fp);
3466 	if (__predict_false(error != 0))
3467 		return (error);
3468 	if (__predict_false(fp->f_ops == &badfileops)) {
3469 		fdrop(fp, td);
3470 		return (EBADF);
3471 	}
3472 
3473 	/*
3474 	 * FREAD and FWRITE failure return EBADF as per POSIX.
3475 	 */
3476 	error = 0;
3477 	switch (flags) {
3478 	case FREAD:
3479 	case FWRITE:
3480 		if ((fp->f_flag & flags) == 0)
3481 			error = EBADF;
3482 		break;
3483 	case FEXEC:
3484 		if (fp->f_ops != &path_fileops &&
3485 		    ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
3486 		    (fp->f_flag & FWRITE) != 0))
3487 			error = EBADF;
3488 		break;
3489 	case 0:
3490 		break;
3491 	default:
3492 		KASSERT(0, ("wrong flags"));
3493 	}
3494 
3495 	if (error != 0) {
3496 		fdrop(fp, td);
3497 		return (error);
3498 	}
3499 
3500 	*fpp = fp;
3501 	return (0);
3502 }
3503 
3504 int
3505 fget(struct thread *td, int fd, const cap_rights_t *rightsp, struct file **fpp)
3506 {
3507 
3508 	return (_fget(td, fd, fpp, 0, rightsp));
3509 }
3510 
3511 int
3512 fget_mmap(struct thread *td, int fd, const cap_rights_t *rightsp,
3513     vm_prot_t *maxprotp, struct file **fpp)
3514 {
3515 	int error;
3516 #ifndef CAPABILITIES
3517 	error = _fget(td, fd, fpp, 0, rightsp);
3518 	if (maxprotp != NULL)
3519 		*maxprotp = VM_PROT_ALL;
3520 	return (error);
3521 #else
3522 	cap_rights_t fdrights;
3523 	struct filedesc *fdp;
3524 	struct file *fp;
3525 	seqc_t seq;
3526 
3527 	*fpp = NULL;
3528 	fdp = td->td_proc->p_fd;
3529 	MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
3530 	for (;;) {
3531 		error = fget_unlocked_seq(td, fd, rightsp, &fp, &seq);
3532 		if (__predict_false(error != 0))
3533 			return (error);
3534 		if (__predict_false(fp->f_ops == &badfileops)) {
3535 			fdrop(fp, td);
3536 			return (EBADF);
3537 		}
3538 		if (maxprotp != NULL)
3539 			fdrights = *cap_rights(fdp, fd);
3540 		if (!fd_modified(fdp, fd, seq))
3541 			break;
3542 		fdrop(fp, td);
3543 	}
3544 
3545 	/*
3546 	 * If requested, convert capability rights to access flags.
3547 	 */
3548 	if (maxprotp != NULL)
3549 		*maxprotp = cap_rights_to_vmprot(&fdrights);
3550 	*fpp = fp;
3551 	return (0);
3552 #endif
3553 }
3554 
3555 int
3556 fget_read(struct thread *td, int fd, const cap_rights_t *rightsp,
3557     struct file **fpp)
3558 {
3559 
3560 	return (_fget(td, fd, fpp, FREAD, rightsp));
3561 }
3562 
3563 int
3564 fget_write(struct thread *td, int fd, const cap_rights_t *rightsp,
3565     struct file **fpp)
3566 {
3567 
3568 	return (_fget(td, fd, fpp, FWRITE, rightsp));
3569 }
3570 
3571 int
3572 fget_fcntl(struct thread *td, int fd, const cap_rights_t *rightsp,
3573     int needfcntl, struct file **fpp)
3574 {
3575 #ifndef CAPABILITIES
3576 	return (fget_unlocked(td, fd, rightsp, fpp));
3577 #else
3578 	struct filedesc *fdp = td->td_proc->p_fd;
3579 	struct file *fp;
3580 	int error;
3581 	seqc_t seq;
3582 
3583 	*fpp = NULL;
3584 	MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
3585 	for (;;) {
3586 		error = fget_unlocked_seq(td, fd, rightsp, &fp, &seq);
3587 		if (error != 0)
3588 			return (error);
3589 		error = cap_fcntl_check(fdp, fd, needfcntl);
3590 		if (!fd_modified(fdp, fd, seq))
3591 			break;
3592 		fdrop(fp, td);
3593 	}
3594 	if (error != 0) {
3595 		fdrop(fp, td);
3596 		return (error);
3597 	}
3598 	*fpp = fp;
3599 	return (0);
3600 #endif
3601 }
3602 
3603 /*
3604  * Like fget() but loads the underlying vnode, or returns an error if the
3605  * descriptor does not represent a vnode.  Note that pipes use vnodes but
3606  * never have VM objects.  The returned vnode will be vref()'d.
3607  *
3608  * XXX: what about the unused flags ?
3609  */
3610 static __inline int
3611 _fgetvp(struct thread *td, int fd, int flags, const cap_rights_t *needrightsp,
3612     struct vnode **vpp)
3613 {
3614 	struct file *fp;
3615 	int error;
3616 
3617 	*vpp = NULL;
3618 	error = _fget(td, fd, &fp, flags, needrightsp);
3619 	if (error != 0)
3620 		return (error);
3621 	if (fp->f_vnode == NULL) {
3622 		error = EINVAL;
3623 	} else {
3624 		*vpp = fp->f_vnode;
3625 		vrefact(*vpp);
3626 	}
3627 	fdrop(fp, td);
3628 
3629 	return (error);
3630 }
3631 
3632 int
3633 fgetvp(struct thread *td, int fd, const cap_rights_t *rightsp,
3634     struct vnode **vpp)
3635 {
3636 
3637 	return (_fgetvp(td, fd, 0, rightsp, vpp));
3638 }
3639 
3640 int
3641 fgetvp_rights(struct thread *td, int fd, const cap_rights_t *needrightsp,
3642     struct filecaps *havecaps, struct vnode **vpp)
3643 {
3644 	struct filecaps caps;
3645 	struct file *fp;
3646 	int error;
3647 
3648 	error = fget_cap(td, fd, needrightsp, &fp, &caps);
3649 	if (error != 0)
3650 		return (error);
3651 	if (fp->f_ops == &badfileops) {
3652 		error = EBADF;
3653 		goto out;
3654 	}
3655 	if (fp->f_vnode == NULL) {
3656 		error = EINVAL;
3657 		goto out;
3658 	}
3659 
3660 	*havecaps = caps;
3661 	*vpp = fp->f_vnode;
3662 	vrefact(*vpp);
3663 	fdrop(fp, td);
3664 
3665 	return (0);
3666 out:
3667 	filecaps_free(&caps);
3668 	fdrop(fp, td);
3669 	return (error);
3670 }
3671 
3672 int
3673 fgetvp_read(struct thread *td, int fd, const cap_rights_t *rightsp,
3674     struct vnode **vpp)
3675 {
3676 
3677 	return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3678 }
3679 
3680 int
3681 fgetvp_exec(struct thread *td, int fd, const cap_rights_t *rightsp,
3682     struct vnode **vpp)
3683 {
3684 
3685 	return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3686 }
3687 
3688 #ifdef notyet
3689 int
3690 fgetvp_write(struct thread *td, int fd, const cap_rights_t *rightsp,
3691     struct vnode **vpp)
3692 {
3693 
3694 	return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3695 }
3696 #endif
3697 
3698 /*
3699  * Handle the last reference to a file being closed.
3700  *
3701  * Without the noinline attribute clang keeps inlining the func thorough this
3702  * file when fdrop is used.
3703  */
3704 int __noinline
3705 _fdrop(struct file *fp, struct thread *td)
3706 {
3707 	int error;
3708 
3709 	KASSERT(refcount_load(&fp->f_count) == 0,
3710 	    ("fdrop: fp %p count %d", fp, refcount_load(&fp->f_count)));
3711 
3712 	error = fo_close(fp, td);
3713 	atomic_subtract_int(&openfiles, 1);
3714 	crfree(fp->f_cred);
3715 	free(fp->f_advice, M_FADVISE);
3716 	uma_zfree(file_zone, fp);
3717 
3718 	return (error);
3719 }
3720 
3721 /*
3722  * Apply an advisory lock on a file descriptor.
3723  *
3724  * Just attempt to get a record lock of the requested type on the entire file
3725  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3726  */
3727 #ifndef _SYS_SYSPROTO_H_
3728 struct flock_args {
3729 	int	fd;
3730 	int	how;
3731 };
3732 #endif
3733 /* ARGSUSED */
3734 int
3735 sys_flock(struct thread *td, struct flock_args *uap)
3736 {
3737 	struct file *fp;
3738 	struct vnode *vp;
3739 	struct flock lf;
3740 	int error;
3741 
3742 	error = fget(td, uap->fd, &cap_flock_rights, &fp);
3743 	if (error != 0)
3744 		return (error);
3745 	error = EOPNOTSUPP;
3746 	if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
3747 		goto done;
3748 	}
3749 	if (fp->f_ops == &path_fileops) {
3750 		goto done;
3751 	}
3752 
3753 	error = 0;
3754 	vp = fp->f_vnode;
3755 	lf.l_whence = SEEK_SET;
3756 	lf.l_start = 0;
3757 	lf.l_len = 0;
3758 	if (uap->how & LOCK_UN) {
3759 		lf.l_type = F_UNLCK;
3760 		atomic_clear_int(&fp->f_flag, FHASLOCK);
3761 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3762 		goto done;
3763 	}
3764 	if (uap->how & LOCK_EX)
3765 		lf.l_type = F_WRLCK;
3766 	else if (uap->how & LOCK_SH)
3767 		lf.l_type = F_RDLCK;
3768 	else {
3769 		error = EBADF;
3770 		goto done;
3771 	}
3772 	atomic_set_int(&fp->f_flag, FHASLOCK);
3773 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3774 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3775 done:
3776 	fdrop(fp, td);
3777 	return (error);
3778 }
3779 /*
3780  * Duplicate the specified descriptor to a free descriptor.
3781  */
3782 int
3783 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3784     int openerror, int *indxp)
3785 {
3786 	struct filedescent *newfde, *oldfde;
3787 	struct file *fp;
3788 	u_long *ioctls;
3789 	int error, indx;
3790 
3791 	KASSERT(openerror == ENODEV || openerror == ENXIO,
3792 	    ("unexpected error %d in %s", openerror, __func__));
3793 
3794 	/*
3795 	 * If the to-be-dup'd fd number is greater than the allowed number
3796 	 * of file descriptors, or the fd to be dup'd has already been
3797 	 * closed, then reject.
3798 	 */
3799 	FILEDESC_XLOCK(fdp);
3800 	if ((fp = fget_noref(fdp, dfd)) == NULL) {
3801 		FILEDESC_XUNLOCK(fdp);
3802 		return (EBADF);
3803 	}
3804 
3805 	error = fdalloc(td, 0, &indx);
3806 	if (error != 0) {
3807 		FILEDESC_XUNLOCK(fdp);
3808 		return (error);
3809 	}
3810 
3811 	/*
3812 	 * There are two cases of interest here.
3813 	 *
3814 	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3815 	 *
3816 	 * For ENXIO steal away the file structure from (dfd) and store it in
3817 	 * (indx).  (dfd) is effectively closed by this operation.
3818 	 */
3819 	switch (openerror) {
3820 	case ENODEV:
3821 		/*
3822 		 * Check that the mode the file is being opened for is a
3823 		 * subset of the mode of the existing descriptor.
3824 		 */
3825 		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3826 			fdunused(fdp, indx);
3827 			FILEDESC_XUNLOCK(fdp);
3828 			return (EACCES);
3829 		}
3830 		if (!fhold(fp)) {
3831 			fdunused(fdp, indx);
3832 			FILEDESC_XUNLOCK(fdp);
3833 			return (EBADF);
3834 		}
3835 		newfde = &fdp->fd_ofiles[indx];
3836 		oldfde = &fdp->fd_ofiles[dfd];
3837 		ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3838 #ifdef CAPABILITIES
3839 		seqc_write_begin(&newfde->fde_seqc);
3840 #endif
3841 		fde_copy(oldfde, newfde);
3842 		filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3843 		    ioctls);
3844 #ifdef CAPABILITIES
3845 		seqc_write_end(&newfde->fde_seqc);
3846 #endif
3847 		break;
3848 	case ENXIO:
3849 		/*
3850 		 * Steal away the file pointer from dfd and stuff it into indx.
3851 		 */
3852 		newfde = &fdp->fd_ofiles[indx];
3853 		oldfde = &fdp->fd_ofiles[dfd];
3854 #ifdef CAPABILITIES
3855 		seqc_write_begin(&oldfde->fde_seqc);
3856 		seqc_write_begin(&newfde->fde_seqc);
3857 #endif
3858 		fde_copy(oldfde, newfde);
3859 		oldfde->fde_file = NULL;
3860 		fdunused(fdp, dfd);
3861 #ifdef CAPABILITIES
3862 		seqc_write_end(&newfde->fde_seqc);
3863 		seqc_write_end(&oldfde->fde_seqc);
3864 #endif
3865 		break;
3866 	}
3867 	FILEDESC_XUNLOCK(fdp);
3868 	*indxp = indx;
3869 	return (0);
3870 }
3871 
3872 /*
3873  * This sysctl determines if we will allow a process to chroot(2) if it
3874  * has a directory open:
3875  *	0: disallowed for all processes.
3876  *	1: allowed for processes that were not already chroot(2)'ed.
3877  *	2: allowed for all processes.
3878  */
3879 
3880 static int chroot_allow_open_directories = 1;
3881 
3882 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3883     &chroot_allow_open_directories, 0,
3884     "Allow a process to chroot(2) if it has a directory open");
3885 
3886 /*
3887  * Helper function for raised chroot(2) security function:  Refuse if
3888  * any filedescriptors are open directories.
3889  */
3890 static int
3891 chroot_refuse_vdir_fds(struct filedesc *fdp)
3892 {
3893 	struct vnode *vp;
3894 	struct file *fp;
3895 	int i;
3896 
3897 	FILEDESC_LOCK_ASSERT(fdp);
3898 
3899 	FILEDESC_FOREACH_FP(fdp, i, fp) {
3900 		if (fp->f_type == DTYPE_VNODE) {
3901 			vp = fp->f_vnode;
3902 			if (vp->v_type == VDIR)
3903 				return (EPERM);
3904 		}
3905 	}
3906 	return (0);
3907 }
3908 
3909 static void
3910 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3911 {
3912 
3913 	if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3914 		vrefact(oldpwd->pwd_cdir);
3915 		newpwd->pwd_cdir = oldpwd->pwd_cdir;
3916 	}
3917 
3918 	if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3919 		vrefact(oldpwd->pwd_rdir);
3920 		newpwd->pwd_rdir = oldpwd->pwd_rdir;
3921 	}
3922 
3923 	if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3924 		vrefact(oldpwd->pwd_jdir);
3925 		newpwd->pwd_jdir = oldpwd->pwd_jdir;
3926 	}
3927 
3928 	if (newpwd->pwd_adir == NULL && oldpwd->pwd_adir != NULL) {
3929 		vrefact(oldpwd->pwd_adir);
3930 		newpwd->pwd_adir = oldpwd->pwd_adir;
3931 	}
3932 }
3933 
3934 struct pwd *
3935 pwd_hold_pwddesc(struct pwddesc *pdp)
3936 {
3937 	struct pwd *pwd;
3938 
3939 	PWDDESC_ASSERT_XLOCKED(pdp);
3940 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3941 	if (pwd != NULL)
3942 		refcount_acquire(&pwd->pwd_refcount);
3943 	return (pwd);
3944 }
3945 
3946 bool
3947 pwd_hold_smr(struct pwd *pwd)
3948 {
3949 
3950 	MPASS(pwd != NULL);
3951 	if (__predict_true(refcount_acquire_if_not_zero(&pwd->pwd_refcount))) {
3952 		return (true);
3953 	}
3954 	return (false);
3955 }
3956 
3957 struct pwd *
3958 pwd_hold(struct thread *td)
3959 {
3960 	struct pwddesc *pdp;
3961 	struct pwd *pwd;
3962 
3963 	pdp = td->td_proc->p_pd;
3964 
3965 	vfs_smr_enter();
3966 	pwd = vfs_smr_entered_load(&pdp->pd_pwd);
3967 	if (pwd_hold_smr(pwd)) {
3968 		vfs_smr_exit();
3969 		return (pwd);
3970 	}
3971 	vfs_smr_exit();
3972 	PWDDESC_XLOCK(pdp);
3973 	pwd = pwd_hold_pwddesc(pdp);
3974 	MPASS(pwd != NULL);
3975 	PWDDESC_XUNLOCK(pdp);
3976 	return (pwd);
3977 }
3978 
3979 struct pwd *
3980 pwd_hold_proc(struct proc *p)
3981 {
3982 	struct pwddesc *pdp;
3983 	struct pwd *pwd;
3984 
3985 	PROC_ASSERT_HELD(p);
3986 	PROC_LOCK(p);
3987 	pdp = pdhold(p);
3988 	MPASS(pdp != NULL);
3989 	PROC_UNLOCK(p);
3990 
3991 	PWDDESC_XLOCK(pdp);
3992 	pwd = pwd_hold_pwddesc(pdp);
3993 	MPASS(pwd != NULL);
3994 	PWDDESC_XUNLOCK(pdp);
3995 	pddrop(pdp);
3996 	return (pwd);
3997 }
3998 
3999 static struct pwd *
4000 pwd_alloc(void)
4001 {
4002 	struct pwd *pwd;
4003 
4004 	pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
4005 	bzero(pwd, sizeof(*pwd));
4006 	refcount_init(&pwd->pwd_refcount, 1);
4007 	return (pwd);
4008 }
4009 
4010 void
4011 pwd_drop(struct pwd *pwd)
4012 {
4013 
4014 	if (!refcount_release(&pwd->pwd_refcount))
4015 		return;
4016 
4017 	if (pwd->pwd_cdir != NULL)
4018 		vrele(pwd->pwd_cdir);
4019 	if (pwd->pwd_rdir != NULL)
4020 		vrele(pwd->pwd_rdir);
4021 	if (pwd->pwd_jdir != NULL)
4022 		vrele(pwd->pwd_jdir);
4023 	if (pwd->pwd_adir != NULL)
4024 		vrele(pwd->pwd_adir);
4025 	uma_zfree_smr(pwd_zone, pwd);
4026 }
4027 
4028 /*
4029 * The caller is responsible for invoking priv_check() and
4030 * mac_vnode_check_chroot() to authorize this operation.
4031 */
4032 int
4033 pwd_chroot(struct thread *td, struct vnode *vp)
4034 {
4035 	struct pwddesc *pdp;
4036 	struct filedesc *fdp;
4037 	struct pwd *newpwd, *oldpwd;
4038 	int error;
4039 
4040 	fdp = td->td_proc->p_fd;
4041 	pdp = td->td_proc->p_pd;
4042 	newpwd = pwd_alloc();
4043 	FILEDESC_SLOCK(fdp);
4044 	PWDDESC_XLOCK(pdp);
4045 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4046 	if (chroot_allow_open_directories == 0 ||
4047 	    (chroot_allow_open_directories == 1 &&
4048 	    oldpwd->pwd_rdir != rootvnode)) {
4049 		error = chroot_refuse_vdir_fds(fdp);
4050 		FILEDESC_SUNLOCK(fdp);
4051 		if (error != 0) {
4052 			PWDDESC_XUNLOCK(pdp);
4053 			pwd_drop(newpwd);
4054 			return (error);
4055 		}
4056 	} else {
4057 		FILEDESC_SUNLOCK(fdp);
4058 	}
4059 
4060 	vrefact(vp);
4061 	newpwd->pwd_rdir = vp;
4062 	vrefact(vp);
4063 	newpwd->pwd_adir = vp;
4064 	if (oldpwd->pwd_jdir == NULL) {
4065 		vrefact(vp);
4066 		newpwd->pwd_jdir = vp;
4067 	}
4068 	pwd_fill(oldpwd, newpwd);
4069 	pwd_set(pdp, newpwd);
4070 	PWDDESC_XUNLOCK(pdp);
4071 	pwd_drop(oldpwd);
4072 	return (0);
4073 }
4074 
4075 void
4076 pwd_chdir(struct thread *td, struct vnode *vp)
4077 {
4078 	struct pwddesc *pdp;
4079 	struct pwd *newpwd, *oldpwd;
4080 
4081 	VNPASS(vp->v_usecount > 0, vp);
4082 
4083 	newpwd = pwd_alloc();
4084 	pdp = td->td_proc->p_pd;
4085 	PWDDESC_XLOCK(pdp);
4086 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4087 	newpwd->pwd_cdir = vp;
4088 	pwd_fill(oldpwd, newpwd);
4089 	pwd_set(pdp, newpwd);
4090 	PWDDESC_XUNLOCK(pdp);
4091 	pwd_drop(oldpwd);
4092 }
4093 
4094 /*
4095  * Process is transitioning to/from a non-native ABI.
4096  */
4097 void
4098 pwd_altroot(struct thread *td, struct vnode *altroot_vp)
4099 {
4100 	struct pwddesc *pdp;
4101 	struct pwd *newpwd, *oldpwd;
4102 
4103 	newpwd = pwd_alloc();
4104 	pdp = td->td_proc->p_pd;
4105 	PWDDESC_XLOCK(pdp);
4106 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4107 	if (altroot_vp != NULL) {
4108 		/*
4109 		 * Native process to a non-native ABI.
4110 		 */
4111 
4112 		vrefact(altroot_vp);
4113 		newpwd->pwd_adir = altroot_vp;
4114 	} else {
4115 		/*
4116 		 * Non-native process to the native ABI.
4117 		 */
4118 
4119 		vrefact(oldpwd->pwd_rdir);
4120 		newpwd->pwd_adir = oldpwd->pwd_rdir;
4121 	}
4122 	pwd_fill(oldpwd, newpwd);
4123 	pwd_set(pdp, newpwd);
4124 	PWDDESC_XUNLOCK(pdp);
4125 	pwd_drop(oldpwd);
4126 }
4127 
4128 /*
4129  * jail_attach(2) changes both root and working directories.
4130  */
4131 int
4132 pwd_chroot_chdir(struct thread *td, struct vnode *vp)
4133 {
4134 	struct pwddesc *pdp;
4135 	struct filedesc *fdp;
4136 	struct pwd *newpwd, *oldpwd;
4137 	int error;
4138 
4139 	fdp = td->td_proc->p_fd;
4140 	pdp = td->td_proc->p_pd;
4141 	newpwd = pwd_alloc();
4142 	FILEDESC_SLOCK(fdp);
4143 	PWDDESC_XLOCK(pdp);
4144 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4145 	error = chroot_refuse_vdir_fds(fdp);
4146 	FILEDESC_SUNLOCK(fdp);
4147 	if (error != 0) {
4148 		PWDDESC_XUNLOCK(pdp);
4149 		pwd_drop(newpwd);
4150 		return (error);
4151 	}
4152 
4153 	vrefact(vp);
4154 	newpwd->pwd_rdir = vp;
4155 	vrefact(vp);
4156 	newpwd->pwd_cdir = vp;
4157 	if (oldpwd->pwd_jdir == NULL) {
4158 		vrefact(vp);
4159 		newpwd->pwd_jdir = vp;
4160 	}
4161 	vrefact(vp);
4162 	newpwd->pwd_adir = vp;
4163 	pwd_fill(oldpwd, newpwd);
4164 	pwd_set(pdp, newpwd);
4165 	PWDDESC_XUNLOCK(pdp);
4166 	pwd_drop(oldpwd);
4167 	return (0);
4168 }
4169 
4170 void
4171 pwd_ensure_dirs(void)
4172 {
4173 	struct pwddesc *pdp;
4174 	struct pwd *oldpwd, *newpwd;
4175 
4176 	pdp = curproc->p_pd;
4177 	PWDDESC_XLOCK(pdp);
4178 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4179 	if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL &&
4180 	    oldpwd->pwd_adir != NULL) {
4181 		PWDDESC_XUNLOCK(pdp);
4182 		return;
4183 	}
4184 	PWDDESC_XUNLOCK(pdp);
4185 
4186 	newpwd = pwd_alloc();
4187 	PWDDESC_XLOCK(pdp);
4188 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4189 	pwd_fill(oldpwd, newpwd);
4190 	if (newpwd->pwd_cdir == NULL) {
4191 		vrefact(rootvnode);
4192 		newpwd->pwd_cdir = rootvnode;
4193 	}
4194 	if (newpwd->pwd_rdir == NULL) {
4195 		vrefact(rootvnode);
4196 		newpwd->pwd_rdir = rootvnode;
4197 	}
4198 	if (newpwd->pwd_adir == NULL) {
4199 		vrefact(rootvnode);
4200 		newpwd->pwd_adir = rootvnode;
4201 	}
4202 	pwd_set(pdp, newpwd);
4203 	PWDDESC_XUNLOCK(pdp);
4204 	pwd_drop(oldpwd);
4205 }
4206 
4207 void
4208 pwd_set_rootvnode(void)
4209 {
4210 	struct pwddesc *pdp;
4211 	struct pwd *oldpwd, *newpwd;
4212 
4213 	pdp = curproc->p_pd;
4214 
4215 	newpwd = pwd_alloc();
4216 	PWDDESC_XLOCK(pdp);
4217 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4218 	vrefact(rootvnode);
4219 	newpwd->pwd_cdir = rootvnode;
4220 	vrefact(rootvnode);
4221 	newpwd->pwd_rdir = rootvnode;
4222 	vrefact(rootvnode);
4223 	newpwd->pwd_adir = rootvnode;
4224 	pwd_fill(oldpwd, newpwd);
4225 	pwd_set(pdp, newpwd);
4226 	PWDDESC_XUNLOCK(pdp);
4227 	pwd_drop(oldpwd);
4228 }
4229 
4230 /*
4231  * Scan all active processes and prisons to see if any of them have a current
4232  * or root directory of `olddp'. If so, replace them with the new mount point.
4233  */
4234 void
4235 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
4236 {
4237 	struct pwddesc *pdp;
4238 	struct pwd *newpwd, *oldpwd;
4239 	struct prison *pr;
4240 	struct proc *p;
4241 	int nrele;
4242 
4243 	if (vrefcnt(olddp) == 1)
4244 		return;
4245 	nrele = 0;
4246 	newpwd = pwd_alloc();
4247 	sx_slock(&allproc_lock);
4248 	FOREACH_PROC_IN_SYSTEM(p) {
4249 		PROC_LOCK(p);
4250 		pdp = pdhold(p);
4251 		PROC_UNLOCK(p);
4252 		if (pdp == NULL)
4253 			continue;
4254 		PWDDESC_XLOCK(pdp);
4255 		oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4256 		if (oldpwd == NULL ||
4257 		    (oldpwd->pwd_cdir != olddp &&
4258 		    oldpwd->pwd_rdir != olddp &&
4259 		    oldpwd->pwd_jdir != olddp &&
4260 		    oldpwd->pwd_adir != olddp)) {
4261 			PWDDESC_XUNLOCK(pdp);
4262 			pddrop(pdp);
4263 			continue;
4264 		}
4265 		if (oldpwd->pwd_cdir == olddp) {
4266 			vrefact(newdp);
4267 			newpwd->pwd_cdir = newdp;
4268 		}
4269 		if (oldpwd->pwd_rdir == olddp) {
4270 			vrefact(newdp);
4271 			newpwd->pwd_rdir = newdp;
4272 		}
4273 		if (oldpwd->pwd_jdir == olddp) {
4274 			vrefact(newdp);
4275 			newpwd->pwd_jdir = newdp;
4276 		}
4277 		if (oldpwd->pwd_adir == olddp) {
4278 			vrefact(newdp);
4279 			newpwd->pwd_adir = newdp;
4280 		}
4281 		pwd_fill(oldpwd, newpwd);
4282 		pwd_set(pdp, newpwd);
4283 		PWDDESC_XUNLOCK(pdp);
4284 		pwd_drop(oldpwd);
4285 		pddrop(pdp);
4286 		newpwd = pwd_alloc();
4287 	}
4288 	sx_sunlock(&allproc_lock);
4289 	pwd_drop(newpwd);
4290 	if (rootvnode == olddp) {
4291 		vrefact(newdp);
4292 		rootvnode = newdp;
4293 		nrele++;
4294 	}
4295 	mtx_lock(&prison0.pr_mtx);
4296 	if (prison0.pr_root == olddp) {
4297 		vrefact(newdp);
4298 		prison0.pr_root = newdp;
4299 		nrele++;
4300 	}
4301 	mtx_unlock(&prison0.pr_mtx);
4302 	sx_slock(&allprison_lock);
4303 	TAILQ_FOREACH(pr, &allprison, pr_list) {
4304 		mtx_lock(&pr->pr_mtx);
4305 		if (pr->pr_root == olddp) {
4306 			vrefact(newdp);
4307 			pr->pr_root = newdp;
4308 			nrele++;
4309 		}
4310 		mtx_unlock(&pr->pr_mtx);
4311 	}
4312 	sx_sunlock(&allprison_lock);
4313 	while (nrele--)
4314 		vrele(olddp);
4315 }
4316 
4317 int
4318 descrip_check_write_mp(struct filedesc *fdp, struct mount *mp)
4319 {
4320 	struct file *fp;
4321 	struct vnode *vp;
4322 	int error, i;
4323 
4324 	error = 0;
4325 	FILEDESC_SLOCK(fdp);
4326 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4327 		if (fp->f_type != DTYPE_VNODE ||
4328 		    (atomic_load_int(&fp->f_flag) & FWRITE) == 0)
4329 			continue;
4330 		vp = fp->f_vnode;
4331 		if (vp->v_mount == mp) {
4332 			error = EDEADLK;
4333 			break;
4334 		}
4335 	}
4336 	FILEDESC_SUNLOCK(fdp);
4337 	return (error);
4338 }
4339 
4340 struct filedesc_to_leader *
4341 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp,
4342     struct proc *leader)
4343 {
4344 	struct filedesc_to_leader *fdtol;
4345 
4346 	fdtol = malloc(sizeof(struct filedesc_to_leader),
4347 	    M_FILEDESC_TO_LEADER, M_WAITOK);
4348 	fdtol->fdl_refcount = 1;
4349 	fdtol->fdl_holdcount = 0;
4350 	fdtol->fdl_wakeup = 0;
4351 	fdtol->fdl_leader = leader;
4352 	if (old != NULL) {
4353 		FILEDESC_XLOCK(fdp);
4354 		fdtol->fdl_next = old->fdl_next;
4355 		fdtol->fdl_prev = old;
4356 		old->fdl_next = fdtol;
4357 		fdtol->fdl_next->fdl_prev = fdtol;
4358 		FILEDESC_XUNLOCK(fdp);
4359 	} else {
4360 		fdtol->fdl_next = fdtol;
4361 		fdtol->fdl_prev = fdtol;
4362 	}
4363 	return (fdtol);
4364 }
4365 
4366 struct filedesc_to_leader *
4367 filedesc_to_leader_share(struct filedesc_to_leader *fdtol, struct filedesc *fdp)
4368 {
4369 	FILEDESC_XLOCK(fdp);
4370 	fdtol->fdl_refcount++;
4371 	FILEDESC_XUNLOCK(fdp);
4372 	return (fdtol);
4373 }
4374 
4375 static int
4376 filedesc_nfiles(struct filedesc *fdp)
4377 {
4378 	NDSLOTTYPE *map;
4379 	int count, off, minoff;
4380 
4381 	if (fdp == NULL)
4382 		return (0);
4383 	count = 0;
4384 	FILEDESC_SLOCK(fdp);
4385 	map = fdp->fd_map;
4386 	off = NDSLOT(fdp->fd_nfiles - 1);
4387 	for (minoff = NDSLOT(0); off >= minoff; --off)
4388 		count += bitcountl(map[off]);
4389 	FILEDESC_SUNLOCK(fdp);
4390 	return (count);
4391 }
4392 
4393 int
4394 proc_nfiles(struct proc *p)
4395 {
4396 	struct filedesc *fdp;
4397 	int res;
4398 
4399 	PROC_LOCK(p);
4400 	fdp = fdhold(p);
4401 	PROC_UNLOCK(p);
4402 	res = filedesc_nfiles(fdp);
4403 	fddrop(fdp);
4404 	return (res);
4405 }
4406 
4407 static int
4408 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
4409 {
4410 	u_int namelen;
4411 	int count;
4412 
4413 	namelen = arg2;
4414 	if (namelen != 1)
4415 		return (EINVAL);
4416 
4417 	if (*(int *)arg1 != 0)
4418 		return (EINVAL);
4419 
4420 	count = filedesc_nfiles(curproc->p_fd);
4421 	return (SYSCTL_OUT(req, &count, sizeof(count)));
4422 }
4423 
4424 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
4425     CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
4426     "Number of open file descriptors");
4427 
4428 /*
4429  * Get file structures globally.
4430  */
4431 static int
4432 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
4433 {
4434 	struct xfile xf;
4435 	struct filedesc *fdp;
4436 	struct file *fp;
4437 	struct proc *p;
4438 	int error, n;
4439 
4440 	error = sysctl_wire_old_buffer(req, 0);
4441 	if (error != 0)
4442 		return (error);
4443 	if (req->oldptr == NULL) {
4444 		n = 0;
4445 		sx_slock(&allproc_lock);
4446 		FOREACH_PROC_IN_SYSTEM(p) {
4447 			PROC_LOCK(p);
4448 			if (p->p_state == PRS_NEW) {
4449 				PROC_UNLOCK(p);
4450 				continue;
4451 			}
4452 			fdp = fdhold(p);
4453 			PROC_UNLOCK(p);
4454 			if (fdp == NULL)
4455 				continue;
4456 			/* overestimates sparse tables. */
4457 			n += fdp->fd_nfiles;
4458 			fddrop(fdp);
4459 		}
4460 		sx_sunlock(&allproc_lock);
4461 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
4462 	}
4463 	error = 0;
4464 	bzero(&xf, sizeof(xf));
4465 	xf.xf_size = sizeof(xf);
4466 	sx_slock(&allproc_lock);
4467 	FOREACH_PROC_IN_SYSTEM(p) {
4468 		PROC_LOCK(p);
4469 		if (p->p_state == PRS_NEW) {
4470 			PROC_UNLOCK(p);
4471 			continue;
4472 		}
4473 		if (p_cansee(req->td, p) != 0) {
4474 			PROC_UNLOCK(p);
4475 			continue;
4476 		}
4477 		xf.xf_pid = p->p_pid;
4478 		xf.xf_uid = p->p_ucred->cr_uid;
4479 		fdp = fdhold(p);
4480 		PROC_UNLOCK(p);
4481 		if (fdp == NULL)
4482 			continue;
4483 		FILEDESC_SLOCK(fdp);
4484 		if (refcount_load(&fdp->fd_refcnt) == 0)
4485 			goto nextproc;
4486 		FILEDESC_FOREACH_FP(fdp, n, fp) {
4487 			xf.xf_fd = n;
4488 			xf.xf_file = (uintptr_t)fp;
4489 			xf.xf_data = (uintptr_t)fp->f_data;
4490 			xf.xf_vnode = (uintptr_t)fp->f_vnode;
4491 			xf.xf_type = (uintptr_t)fp->f_type;
4492 			xf.xf_count = refcount_load(&fp->f_count);
4493 			xf.xf_msgcount = 0;
4494 			xf.xf_offset = foffset_get(fp);
4495 			xf.xf_flag = fp->f_flag;
4496 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
4497 
4498 			/*
4499 			 * There is no need to re-check the fdtable refcount
4500 			 * here since the filedesc lock is not dropped in the
4501 			 * loop body.
4502 			 */
4503 			if (error != 0)
4504 				break;
4505 		}
4506 nextproc:
4507 		FILEDESC_SUNLOCK(fdp);
4508 		fddrop(fdp);
4509 		if (error)
4510 			break;
4511 	}
4512 	sx_sunlock(&allproc_lock);
4513 	return (error);
4514 }
4515 
4516 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
4517     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
4518 
4519 #ifdef KINFO_FILE_SIZE
4520 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
4521 #endif
4522 
4523 static int
4524 xlate_fflags(int fflags)
4525 {
4526 	static const struct {
4527 		int	fflag;
4528 		int	kf_fflag;
4529 	} fflags_table[] = {
4530 		{ FAPPEND, KF_FLAG_APPEND },
4531 		{ FASYNC, KF_FLAG_ASYNC },
4532 		{ FFSYNC, KF_FLAG_FSYNC },
4533 		{ FHASLOCK, KF_FLAG_HASLOCK },
4534 		{ FNONBLOCK, KF_FLAG_NONBLOCK },
4535 		{ FREAD, KF_FLAG_READ },
4536 		{ FWRITE, KF_FLAG_WRITE },
4537 		{ O_CREAT, KF_FLAG_CREAT },
4538 		{ O_DIRECT, KF_FLAG_DIRECT },
4539 		{ O_EXCL, KF_FLAG_EXCL },
4540 		{ O_EXEC, KF_FLAG_EXEC },
4541 		{ O_EXLOCK, KF_FLAG_EXLOCK },
4542 		{ O_NOFOLLOW, KF_FLAG_NOFOLLOW },
4543 		{ O_SHLOCK, KF_FLAG_SHLOCK },
4544 		{ O_TRUNC, KF_FLAG_TRUNC }
4545 	};
4546 	unsigned int i;
4547 	int kflags;
4548 
4549 	kflags = 0;
4550 	for (i = 0; i < nitems(fflags_table); i++)
4551 		if (fflags & fflags_table[i].fflag)
4552 			kflags |=  fflags_table[i].kf_fflag;
4553 	return (kflags);
4554 }
4555 
4556 /* Trim unused data from kf_path by truncating the structure size. */
4557 void
4558 pack_kinfo(struct kinfo_file *kif)
4559 {
4560 
4561 	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
4562 	    strlen(kif->kf_path) + 1;
4563 	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
4564 }
4565 
4566 static void
4567 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
4568     struct kinfo_file *kif, struct filedesc *fdp, int flags)
4569 {
4570 	int error;
4571 
4572 	bzero(kif, sizeof(*kif));
4573 
4574 	/* Set a default type to allow for empty fill_kinfo() methods. */
4575 	kif->kf_type = KF_TYPE_UNKNOWN;
4576 	kif->kf_flags = xlate_fflags(fp->f_flag);
4577 	if (rightsp != NULL)
4578 		kif->kf_cap_rights = *rightsp;
4579 	else
4580 		cap_rights_init_zero(&kif->kf_cap_rights);
4581 	kif->kf_fd = fd;
4582 	kif->kf_ref_count = refcount_load(&fp->f_count);
4583 	kif->kf_offset = foffset_get(fp);
4584 
4585 	/*
4586 	 * This may drop the filedesc lock, so the 'fp' cannot be
4587 	 * accessed after this call.
4588 	 */
4589 	error = fo_fill_kinfo(fp, kif, fdp);
4590 	if (error == 0)
4591 		kif->kf_status |= KF_ATTR_VALID;
4592 	if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4593 		pack_kinfo(kif);
4594 	else
4595 		kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4596 }
4597 
4598 static void
4599 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
4600     struct kinfo_file *kif, int flags)
4601 {
4602 	int error;
4603 
4604 	bzero(kif, sizeof(*kif));
4605 
4606 	kif->kf_type = KF_TYPE_VNODE;
4607 	error = vn_fill_kinfo_vnode(vp, kif);
4608 	if (error == 0)
4609 		kif->kf_status |= KF_ATTR_VALID;
4610 	kif->kf_flags = xlate_fflags(fflags);
4611 	cap_rights_init_zero(&kif->kf_cap_rights);
4612 	kif->kf_fd = fd;
4613 	kif->kf_ref_count = -1;
4614 	kif->kf_offset = -1;
4615 	if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4616 		pack_kinfo(kif);
4617 	else
4618 		kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4619 	vrele(vp);
4620 }
4621 
4622 struct export_fd_buf {
4623 	struct filedesc		*fdp;
4624 	struct pwddesc	*pdp;
4625 	struct sbuf 		*sb;
4626 	ssize_t			remainder;
4627 	struct kinfo_file	kif;
4628 	int			flags;
4629 };
4630 
4631 static int
4632 export_kinfo_to_sb(struct export_fd_buf *efbuf)
4633 {
4634 	struct kinfo_file *kif;
4635 
4636 	kif = &efbuf->kif;
4637 	if (efbuf->remainder != -1) {
4638 		if (efbuf->remainder < kif->kf_structsize)
4639 			return (ENOMEM);
4640 		efbuf->remainder -= kif->kf_structsize;
4641 	}
4642 	if (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) != 0)
4643 		return (sbuf_error(efbuf->sb));
4644 	return (0);
4645 }
4646 
4647 static int
4648 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
4649     struct export_fd_buf *efbuf)
4650 {
4651 	int error;
4652 
4653 	if (efbuf->remainder == 0)
4654 		return (ENOMEM);
4655 	export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
4656 	    efbuf->flags);
4657 	FILEDESC_SUNLOCK(efbuf->fdp);
4658 	error = export_kinfo_to_sb(efbuf);
4659 	FILEDESC_SLOCK(efbuf->fdp);
4660 	return (error);
4661 }
4662 
4663 static int
4664 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
4665     struct export_fd_buf *efbuf)
4666 {
4667 	int error;
4668 
4669 	if (efbuf->remainder == 0)
4670 		return (ENOMEM);
4671 	if (efbuf->pdp != NULL)
4672 		PWDDESC_XUNLOCK(efbuf->pdp);
4673 	export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
4674 	error = export_kinfo_to_sb(efbuf);
4675 	if (efbuf->pdp != NULL)
4676 		PWDDESC_XLOCK(efbuf->pdp);
4677 	return (error);
4678 }
4679 
4680 /*
4681  * Store a process file descriptor information to sbuf.
4682  *
4683  * Takes a locked proc as argument, and returns with the proc unlocked.
4684  */
4685 int
4686 kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen,
4687     int flags)
4688 {
4689 	struct file *fp;
4690 	struct filedesc *fdp;
4691 	struct pwddesc *pdp;
4692 	struct export_fd_buf *efbuf;
4693 	struct vnode *cttyvp, *textvp, *tracevp;
4694 	struct pwd *pwd;
4695 	int error, i;
4696 	cap_rights_t rights;
4697 
4698 	PROC_LOCK_ASSERT(p, MA_OWNED);
4699 
4700 	/* ktrace vnode */
4701 	tracevp = ktr_get_tracevp(p, true);
4702 	/* text vnode */
4703 	textvp = p->p_textvp;
4704 	if (textvp != NULL)
4705 		vrefact(textvp);
4706 	/* Controlling tty. */
4707 	cttyvp = NULL;
4708 	if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
4709 		cttyvp = p->p_pgrp->pg_session->s_ttyvp;
4710 		if (cttyvp != NULL)
4711 			vrefact(cttyvp);
4712 	}
4713 	fdp = fdhold(p);
4714 	pdp = pdhold(p);
4715 	PROC_UNLOCK(p);
4716 
4717 	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4718 	efbuf->fdp = NULL;
4719 	efbuf->pdp = NULL;
4720 	efbuf->sb = sb;
4721 	efbuf->remainder = maxlen;
4722 	efbuf->flags = flags;
4723 
4724 	error = 0;
4725 	if (tracevp != NULL)
4726 		error = export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE,
4727 		    FREAD | FWRITE, efbuf);
4728 	if (error == 0 && textvp != NULL)
4729 		error = export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD,
4730 		    efbuf);
4731 	if (error == 0 && cttyvp != NULL)
4732 		error = export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY,
4733 		    FREAD | FWRITE, efbuf);
4734 	if (error != 0 || pdp == NULL || fdp == NULL)
4735 		goto fail;
4736 	efbuf->fdp = fdp;
4737 	efbuf->pdp = pdp;
4738 	PWDDESC_XLOCK(pdp);
4739 	pwd = pwd_hold_pwddesc(pdp);
4740 	if (pwd != NULL) {
4741 		/* working directory */
4742 		if (pwd->pwd_cdir != NULL) {
4743 			vrefact(pwd->pwd_cdir);
4744 			error = export_vnode_to_sb(pwd->pwd_cdir,
4745 			    KF_FD_TYPE_CWD, FREAD, efbuf);
4746 		}
4747 		/* root directory */
4748 		if (error == 0 && pwd->pwd_rdir != NULL) {
4749 			vrefact(pwd->pwd_rdir);
4750 			error = export_vnode_to_sb(pwd->pwd_rdir,
4751 			    KF_FD_TYPE_ROOT, FREAD, efbuf);
4752 		}
4753 		/* jail directory */
4754 		if (error == 0 && pwd->pwd_jdir != NULL) {
4755 			vrefact(pwd->pwd_jdir);
4756 			error = export_vnode_to_sb(pwd->pwd_jdir,
4757 			    KF_FD_TYPE_JAIL, FREAD, efbuf);
4758 		}
4759 	}
4760 	PWDDESC_XUNLOCK(pdp);
4761 	if (error != 0)
4762 		goto fail;
4763 	if (pwd != NULL)
4764 		pwd_drop(pwd);
4765 	FILEDESC_SLOCK(fdp);
4766 	if (refcount_load(&fdp->fd_refcnt) == 0)
4767 		goto skip;
4768 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4769 #ifdef CAPABILITIES
4770 		rights = *cap_rights(fdp, i);
4771 #else /* !CAPABILITIES */
4772 		rights = cap_no_rights;
4773 #endif
4774 		/*
4775 		 * Create sysctl entry.  It is OK to drop the filedesc
4776 		 * lock inside of export_file_to_sb() as we will
4777 		 * re-validate and re-evaluate its properties when the
4778 		 * loop continues.
4779 		 */
4780 		error = export_file_to_sb(fp, i, &rights, efbuf);
4781 		if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4782 			break;
4783 	}
4784 skip:
4785 	FILEDESC_SUNLOCK(fdp);
4786 fail:
4787 	if (fdp != NULL)
4788 		fddrop(fdp);
4789 	if (pdp != NULL)
4790 		pddrop(pdp);
4791 	free(efbuf, M_TEMP);
4792 	return (error);
4793 }
4794 
4795 #define FILEDESC_SBUF_SIZE	(sizeof(struct kinfo_file) * 5)
4796 
4797 /*
4798  * Get per-process file descriptors for use by procstat(1), et al.
4799  */
4800 static int
4801 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
4802 {
4803 	struct sbuf sb;
4804 	struct proc *p;
4805 	ssize_t maxlen;
4806 	u_int namelen;
4807 	int error, error2, *name;
4808 
4809 	namelen = arg2;
4810 	if (namelen != 1)
4811 		return (EINVAL);
4812 
4813 	name = (int *)arg1;
4814 
4815 	sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
4816 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4817 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4818 	if (error != 0) {
4819 		sbuf_delete(&sb);
4820 		return (error);
4821 	}
4822 	maxlen = req->oldptr != NULL ? req->oldlen : -1;
4823 	error = kern_proc_filedesc_out(p, &sb, maxlen,
4824 	    KERN_FILEDESC_PACK_KINFO);
4825 	error2 = sbuf_finish(&sb);
4826 	sbuf_delete(&sb);
4827 	return (error != 0 ? error : error2);
4828 }
4829 
4830 #ifdef COMPAT_FREEBSD7
4831 #ifdef KINFO_OFILE_SIZE
4832 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4833 #endif
4834 
4835 static void
4836 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4837 {
4838 
4839 	okif->kf_structsize = sizeof(*okif);
4840 	okif->kf_type = kif->kf_type;
4841 	okif->kf_fd = kif->kf_fd;
4842 	okif->kf_ref_count = kif->kf_ref_count;
4843 	okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4844 	    KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4845 	    KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4846 	okif->kf_offset = kif->kf_offset;
4847 	if (kif->kf_type == KF_TYPE_VNODE)
4848 		okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4849 	else
4850 		okif->kf_vnode_type = KF_VTYPE_VNON;
4851 	strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4852 	if (kif->kf_type == KF_TYPE_SOCKET) {
4853 		okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4854 		okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4855 		okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4856 		okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4857 		okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4858 	} else {
4859 		okif->kf_sa_local.ss_family = AF_UNSPEC;
4860 		okif->kf_sa_peer.ss_family = AF_UNSPEC;
4861 	}
4862 }
4863 
4864 static int
4865 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4866     struct kinfo_ofile *okif, struct pwddesc *pdp, struct sysctl_req *req)
4867 {
4868 	int error;
4869 
4870 	vrefact(vp);
4871 	PWDDESC_XUNLOCK(pdp);
4872 	export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4873 	kinfo_to_okinfo(kif, okif);
4874 	error = SYSCTL_OUT(req, okif, sizeof(*okif));
4875 	PWDDESC_XLOCK(pdp);
4876 	return (error);
4877 }
4878 
4879 /*
4880  * Get per-process file descriptors for use by procstat(1), et al.
4881  */
4882 static int
4883 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4884 {
4885 	struct kinfo_ofile *okif;
4886 	struct kinfo_file *kif;
4887 	struct filedesc *fdp;
4888 	struct pwddesc *pdp;
4889 	struct pwd *pwd;
4890 	u_int namelen;
4891 	int error, i, *name;
4892 	struct file *fp;
4893 	struct proc *p;
4894 
4895 	namelen = arg2;
4896 	if (namelen != 1)
4897 		return (EINVAL);
4898 
4899 	name = (int *)arg1;
4900 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4901 	if (error != 0)
4902 		return (error);
4903 	fdp = fdhold(p);
4904 	if (fdp != NULL)
4905 		pdp = pdhold(p);
4906 	PROC_UNLOCK(p);
4907 	if (fdp == NULL || pdp == NULL) {
4908 		if (fdp != NULL)
4909 			fddrop(fdp);
4910 		return (ENOENT);
4911 	}
4912 	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4913 	okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4914 	PWDDESC_XLOCK(pdp);
4915 	pwd = pwd_hold_pwddesc(pdp);
4916 	if (pwd != NULL) {
4917 		if (pwd->pwd_cdir != NULL)
4918 			export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4919 			    okif, pdp, req);
4920 		if (pwd->pwd_rdir != NULL)
4921 			export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4922 			    okif, pdp, req);
4923 		if (pwd->pwd_jdir != NULL)
4924 			export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4925 			    okif, pdp, req);
4926 	}
4927 	PWDDESC_XUNLOCK(pdp);
4928 	if (pwd != NULL)
4929 		pwd_drop(pwd);
4930 	FILEDESC_SLOCK(fdp);
4931 	if (refcount_load(&fdp->fd_refcnt) == 0)
4932 		goto skip;
4933 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4934 		export_file_to_kinfo(fp, i, NULL, kif, fdp,
4935 		    KERN_FILEDESC_PACK_KINFO);
4936 		FILEDESC_SUNLOCK(fdp);
4937 		kinfo_to_okinfo(kif, okif);
4938 		error = SYSCTL_OUT(req, okif, sizeof(*okif));
4939 		FILEDESC_SLOCK(fdp);
4940 		if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4941 			break;
4942 	}
4943 skip:
4944 	FILEDESC_SUNLOCK(fdp);
4945 	fddrop(fdp);
4946 	pddrop(pdp);
4947 	free(kif, M_TEMP);
4948 	free(okif, M_TEMP);
4949 	return (0);
4950 }
4951 
4952 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4953     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4954     "Process ofiledesc entries");
4955 #endif	/* COMPAT_FREEBSD7 */
4956 
4957 int
4958 vntype_to_kinfo(int vtype)
4959 {
4960 	struct {
4961 		int	vtype;
4962 		int	kf_vtype;
4963 	} vtypes_table[] = {
4964 		{ VBAD, KF_VTYPE_VBAD },
4965 		{ VBLK, KF_VTYPE_VBLK },
4966 		{ VCHR, KF_VTYPE_VCHR },
4967 		{ VDIR, KF_VTYPE_VDIR },
4968 		{ VFIFO, KF_VTYPE_VFIFO },
4969 		{ VLNK, KF_VTYPE_VLNK },
4970 		{ VNON, KF_VTYPE_VNON },
4971 		{ VREG, KF_VTYPE_VREG },
4972 		{ VSOCK, KF_VTYPE_VSOCK }
4973 	};
4974 	unsigned int i;
4975 
4976 	/*
4977 	 * Perform vtype translation.
4978 	 */
4979 	for (i = 0; i < nitems(vtypes_table); i++)
4980 		if (vtypes_table[i].vtype == vtype)
4981 			return (vtypes_table[i].kf_vtype);
4982 
4983 	return (KF_VTYPE_UNKNOWN);
4984 }
4985 
4986 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4987     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4988     "Process filedesc entries");
4989 
4990 /*
4991  * Store a process current working directory information to sbuf.
4992  *
4993  * Takes a locked proc as argument, and returns with the proc unlocked.
4994  */
4995 int
4996 kern_proc_cwd_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
4997 {
4998 	struct pwddesc *pdp;
4999 	struct pwd *pwd;
5000 	struct export_fd_buf *efbuf;
5001 	struct vnode *cdir;
5002 	int error;
5003 
5004 	PROC_LOCK_ASSERT(p, MA_OWNED);
5005 
5006 	pdp = pdhold(p);
5007 	PROC_UNLOCK(p);
5008 	if (pdp == NULL)
5009 		return (EINVAL);
5010 
5011 	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
5012 	efbuf->fdp = NULL;
5013 	efbuf->pdp = pdp;
5014 	efbuf->sb = sb;
5015 	efbuf->remainder = maxlen;
5016 	efbuf->flags = 0;
5017 
5018 	PWDDESC_XLOCK(pdp);
5019 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
5020 	cdir = pwd->pwd_cdir;
5021 	if (cdir == NULL) {
5022 		error = EINVAL;
5023 	} else {
5024 		vrefact(cdir);
5025 		error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
5026 	}
5027 	PWDDESC_XUNLOCK(pdp);
5028 	pddrop(pdp);
5029 	free(efbuf, M_TEMP);
5030 	return (error);
5031 }
5032 
5033 /*
5034  * Get per-process current working directory.
5035  */
5036 static int
5037 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
5038 {
5039 	struct sbuf sb;
5040 	struct proc *p;
5041 	ssize_t maxlen;
5042 	u_int namelen;
5043 	int error, error2, *name;
5044 
5045 	namelen = arg2;
5046 	if (namelen != 1)
5047 		return (EINVAL);
5048 
5049 	name = (int *)arg1;
5050 
5051 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
5052 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
5053 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
5054 	if (error != 0) {
5055 		sbuf_delete(&sb);
5056 		return (error);
5057 	}
5058 	maxlen = req->oldptr != NULL ? req->oldlen : -1;
5059 	error = kern_proc_cwd_out(p, &sb, maxlen);
5060 	error2 = sbuf_finish(&sb);
5061 	sbuf_delete(&sb);
5062 	return (error != 0 ? error : error2);
5063 }
5064 
5065 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
5066     sysctl_kern_proc_cwd, "Process current working directory");
5067 
5068 #ifdef DDB
5069 /*
5070  * For the purposes of debugging, generate a human-readable string for the
5071  * file type.
5072  */
5073 static const char *
5074 file_type_to_name(short type)
5075 {
5076 
5077 	switch (type) {
5078 	case 0:
5079 		return ("zero");
5080 	case DTYPE_VNODE:
5081 		return ("vnode");
5082 	case DTYPE_SOCKET:
5083 		return ("socket");
5084 	case DTYPE_PIPE:
5085 		return ("pipe");
5086 	case DTYPE_FIFO:
5087 		return ("fifo");
5088 	case DTYPE_KQUEUE:
5089 		return ("kqueue");
5090 	case DTYPE_CRYPTO:
5091 		return ("crypto");
5092 	case DTYPE_MQUEUE:
5093 		return ("mqueue");
5094 	case DTYPE_SHM:
5095 		return ("shm");
5096 	case DTYPE_SEM:
5097 		return ("ksem");
5098 	case DTYPE_PTS:
5099 		return ("pts");
5100 	case DTYPE_DEV:
5101 		return ("dev");
5102 	case DTYPE_PROCDESC:
5103 		return ("proc");
5104 	case DTYPE_EVENTFD:
5105 		return ("eventfd");
5106 	case DTYPE_TIMERFD:
5107 		return ("timerfd");
5108 	default:
5109 		return ("unkn");
5110 	}
5111 }
5112 
5113 /*
5114  * For the purposes of debugging, identify a process (if any, perhaps one of
5115  * many) that references the passed file in its file descriptor array. Return
5116  * NULL if none.
5117  */
5118 static struct proc *
5119 file_to_first_proc(struct file *fp)
5120 {
5121 	struct filedesc *fdp;
5122 	struct proc *p;
5123 	int n;
5124 
5125 	FOREACH_PROC_IN_SYSTEM(p) {
5126 		if (p->p_state == PRS_NEW)
5127 			continue;
5128 		fdp = p->p_fd;
5129 		if (fdp == NULL)
5130 			continue;
5131 		for (n = 0; n < fdp->fd_nfiles; n++) {
5132 			if (fp == fdp->fd_ofiles[n].fde_file)
5133 				return (p);
5134 		}
5135 	}
5136 	return (NULL);
5137 }
5138 
5139 static void
5140 db_print_file(struct file *fp, int header)
5141 {
5142 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
5143 	struct proc *p;
5144 
5145 	if (header)
5146 		db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
5147 		    XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
5148 		    "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
5149 		    "FCmd");
5150 	p = file_to_first_proc(fp);
5151 	db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
5152 	    fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
5153 	    fp->f_flag, 0, refcount_load(&fp->f_count), 0, XPTRWIDTH, fp->f_vnode,
5154 	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
5155 
5156 #undef XPTRWIDTH
5157 }
5158 
5159 DB_SHOW_COMMAND(file, db_show_file)
5160 {
5161 	struct file *fp;
5162 
5163 	if (!have_addr) {
5164 		db_printf("usage: show file <addr>\n");
5165 		return;
5166 	}
5167 	fp = (struct file *)addr;
5168 	db_print_file(fp, 1);
5169 }
5170 
5171 DB_SHOW_COMMAND_FLAGS(files, db_show_files, DB_CMD_MEMSAFE)
5172 {
5173 	struct filedesc *fdp;
5174 	struct file *fp;
5175 	struct proc *p;
5176 	int header;
5177 	int n;
5178 
5179 	header = 1;
5180 	FOREACH_PROC_IN_SYSTEM(p) {
5181 		if (p->p_state == PRS_NEW)
5182 			continue;
5183 		if ((fdp = p->p_fd) == NULL)
5184 			continue;
5185 		for (n = 0; n < fdp->fd_nfiles; ++n) {
5186 			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
5187 				continue;
5188 			db_print_file(fp, header);
5189 			header = 0;
5190 		}
5191 	}
5192 }
5193 #endif
5194 
5195 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc,
5196     CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5197     &maxfilesperproc, 0, "Maximum files allowed open per process");
5198 
5199 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5200     &maxfiles, 0, "Maximum number of files");
5201 
5202 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
5203     &openfiles, 0, "System-wide number of open files");
5204 
5205 /* ARGSUSED*/
5206 static void
5207 filelistinit(void *dummy)
5208 {
5209 
5210 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
5211 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
5212 	filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
5213 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
5214 	pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
5215 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
5216 	/*
5217 	 * XXXMJG this is a temporary hack due to boot ordering issues against
5218 	 * the vnode zone.
5219 	 */
5220 	vfs_smr = uma_zone_get_smr(pwd_zone);
5221 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
5222 }
5223 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
5224 
5225 /*-------------------------------------------------------------------*/
5226 
5227 static int
5228 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
5229     int flags, struct thread *td)
5230 {
5231 
5232 	return (EBADF);
5233 }
5234 
5235 static int
5236 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5237     struct thread *td)
5238 {
5239 
5240 	return (EINVAL);
5241 }
5242 
5243 static int
5244 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
5245     struct thread *td)
5246 {
5247 
5248 	return (EBADF);
5249 }
5250 
5251 static int
5252 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
5253     struct thread *td)
5254 {
5255 
5256 	return (0);
5257 }
5258 
5259 static int
5260 badfo_kqfilter(struct file *fp, struct knote *kn)
5261 {
5262 
5263 	return (EBADF);
5264 }
5265 
5266 static int
5267 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
5268 {
5269 
5270 	return (EBADF);
5271 }
5272 
5273 static int
5274 badfo_close(struct file *fp, struct thread *td)
5275 {
5276 
5277 	return (0);
5278 }
5279 
5280 static int
5281 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5282     struct thread *td)
5283 {
5284 
5285 	return (EBADF);
5286 }
5287 
5288 static int
5289 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5290     struct thread *td)
5291 {
5292 
5293 	return (EBADF);
5294 }
5295 
5296 static int
5297 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5298     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5299     struct thread *td)
5300 {
5301 
5302 	return (EBADF);
5303 }
5304 
5305 static int
5306 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
5307 {
5308 
5309 	return (0);
5310 }
5311 
5312 const struct fileops badfileops = {
5313 	.fo_read = badfo_readwrite,
5314 	.fo_write = badfo_readwrite,
5315 	.fo_truncate = badfo_truncate,
5316 	.fo_ioctl = badfo_ioctl,
5317 	.fo_poll = badfo_poll,
5318 	.fo_kqfilter = badfo_kqfilter,
5319 	.fo_stat = badfo_stat,
5320 	.fo_close = badfo_close,
5321 	.fo_chmod = badfo_chmod,
5322 	.fo_chown = badfo_chown,
5323 	.fo_sendfile = badfo_sendfile,
5324 	.fo_fill_kinfo = badfo_fill_kinfo,
5325 };
5326 
5327 static int
5328 path_poll(struct file *fp, int events, struct ucred *active_cred,
5329     struct thread *td)
5330 {
5331 	return (POLLNVAL);
5332 }
5333 
5334 static int
5335 path_close(struct file *fp, struct thread *td)
5336 {
5337 	MPASS(fp->f_type == DTYPE_VNODE);
5338 	fp->f_ops = &badfileops;
5339 	vrele(fp->f_vnode);
5340 	return (0);
5341 }
5342 
5343 const struct fileops path_fileops = {
5344 	.fo_read = badfo_readwrite,
5345 	.fo_write = badfo_readwrite,
5346 	.fo_truncate = badfo_truncate,
5347 	.fo_ioctl = badfo_ioctl,
5348 	.fo_poll = path_poll,
5349 	.fo_kqfilter = vn_kqfilter_opath,
5350 	.fo_stat = vn_statfile,
5351 	.fo_close = path_close,
5352 	.fo_chmod = badfo_chmod,
5353 	.fo_chown = badfo_chown,
5354 	.fo_sendfile = badfo_sendfile,
5355 	.fo_fill_kinfo = vn_fill_kinfo,
5356 	.fo_cmp = vn_cmp,
5357 	.fo_flags = DFLAG_PASSABLE,
5358 };
5359 
5360 int
5361 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
5362     int flags, struct thread *td)
5363 {
5364 
5365 	return (EOPNOTSUPP);
5366 }
5367 
5368 int
5369 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5370     struct thread *td)
5371 {
5372 
5373 	return (EINVAL);
5374 }
5375 
5376 int
5377 invfo_ioctl(struct file *fp, u_long com, void *data,
5378     struct ucred *active_cred, struct thread *td)
5379 {
5380 
5381 	return (ENOTTY);
5382 }
5383 
5384 int
5385 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
5386     struct thread *td)
5387 {
5388 
5389 	return (poll_no_poll(events));
5390 }
5391 
5392 int
5393 invfo_kqfilter(struct file *fp, struct knote *kn)
5394 {
5395 
5396 	return (EINVAL);
5397 }
5398 
5399 int
5400 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5401     struct thread *td)
5402 {
5403 
5404 	return (EINVAL);
5405 }
5406 
5407 int
5408 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5409     struct thread *td)
5410 {
5411 
5412 	return (EINVAL);
5413 }
5414 
5415 int
5416 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5417     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5418     struct thread *td)
5419 {
5420 
5421 	return (EINVAL);
5422 }
5423 
5424 /*-------------------------------------------------------------------*/
5425 
5426 /*
5427  * File Descriptor pseudo-device driver (/dev/fd/).
5428  *
5429  * Opening minor device N dup()s the file (if any) connected to file
5430  * descriptor N belonging to the calling process.  Note that this driver
5431  * consists of only the ``open()'' routine, because all subsequent
5432  * references to this file will be direct to the other driver.
5433  *
5434  * XXX: we could give this one a cloning event handler if necessary.
5435  */
5436 
5437 /* ARGSUSED */
5438 static int
5439 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
5440 {
5441 
5442 	/*
5443 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
5444 	 * the file descriptor being sought for duplication. The error
5445 	 * return ensures that the vnode for this device will be released
5446 	 * by vn_open. Open will detect this special error and take the
5447 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
5448 	 * will simply report the error.
5449 	 */
5450 	td->td_dupfd = dev2unit(dev);
5451 	return (ENODEV);
5452 }
5453 
5454 static struct cdevsw fildesc_cdevsw = {
5455 	.d_version =	D_VERSION,
5456 	.d_open =	fdopen,
5457 	.d_name =	"FD",
5458 };
5459 
5460 static void
5461 fildesc_drvinit(void *unused)
5462 {
5463 	struct cdev *dev;
5464 
5465 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
5466 	    UID_ROOT, GID_WHEEL, 0666, "fd/0");
5467 	make_dev_alias(dev, "stdin");
5468 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
5469 	    UID_ROOT, GID_WHEEL, 0666, "fd/1");
5470 	make_dev_alias(dev, "stdout");
5471 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
5472 	    UID_ROOT, GID_WHEEL, 0666, "fd/2");
5473 	make_dev_alias(dev, "stderr");
5474 }
5475 
5476 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
5477