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