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