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