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