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