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