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