xref: /freebsd/sys/kern/kern_descrip.c (revision 32100375a661c1e16588ddfa7b90ca8d26cb9786)
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[UIO_READ] = 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 #ifdef COMPAT_FREEBSD12
1376 /*
1377  * Close open file descriptors.
1378  */
1379 #ifndef _SYS_SYSPROTO_H_
1380 struct freebsd12_closefrom_args {
1381 	int	lowfd;
1382 };
1383 #endif
1384 /* ARGSUSED */
1385 int
1386 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1387 {
1388 	u_int lowfd;
1389 
1390 	AUDIT_ARG_FD(uap->lowfd);
1391 
1392 	/*
1393 	 * Treat negative starting file descriptor values identical to
1394 	 * closefrom(0) which closes all files.
1395 	 */
1396 	lowfd = MAX(0, uap->lowfd);
1397 	return (kern_close_range(td, lowfd, ~0U));
1398 }
1399 #endif	/* COMPAT_FREEBSD12 */
1400 
1401 #if defined(COMPAT_43)
1402 /*
1403  * Return status information about a file descriptor.
1404  */
1405 #ifndef _SYS_SYSPROTO_H_
1406 struct ofstat_args {
1407 	int	fd;
1408 	struct	ostat *sb;
1409 };
1410 #endif
1411 /* ARGSUSED */
1412 int
1413 ofstat(struct thread *td, struct ofstat_args *uap)
1414 {
1415 	struct ostat oub;
1416 	struct stat ub;
1417 	int error;
1418 
1419 	error = kern_fstat(td, uap->fd, &ub);
1420 	if (error == 0) {
1421 		cvtstat(&ub, &oub);
1422 		error = copyout(&oub, uap->sb, sizeof(oub));
1423 	}
1424 	return (error);
1425 }
1426 #endif /* COMPAT_43 */
1427 
1428 #if defined(COMPAT_FREEBSD11)
1429 int
1430 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1431 {
1432 	struct stat sb;
1433 	struct freebsd11_stat osb;
1434 	int error;
1435 
1436 	error = kern_fstat(td, uap->fd, &sb);
1437 	if (error != 0)
1438 		return (error);
1439 	error = freebsd11_cvtstat(&sb, &osb);
1440 	if (error == 0)
1441 		error = copyout(&osb, uap->sb, sizeof(osb));
1442 	return (error);
1443 }
1444 #endif	/* COMPAT_FREEBSD11 */
1445 
1446 /*
1447  * Return status information about a file descriptor.
1448  */
1449 #ifndef _SYS_SYSPROTO_H_
1450 struct fstat_args {
1451 	int	fd;
1452 	struct	stat *sb;
1453 };
1454 #endif
1455 /* ARGSUSED */
1456 int
1457 sys_fstat(struct thread *td, struct fstat_args *uap)
1458 {
1459 	struct stat ub;
1460 	int error;
1461 
1462 	error = kern_fstat(td, uap->fd, &ub);
1463 	if (error == 0)
1464 		error = copyout(&ub, uap->sb, sizeof(ub));
1465 	return (error);
1466 }
1467 
1468 int
1469 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1470 {
1471 	struct file *fp;
1472 	int error;
1473 
1474 	AUDIT_ARG_FD(fd);
1475 
1476 	error = fget(td, fd, &cap_fstat_rights, &fp);
1477 	if (__predict_false(error != 0))
1478 		return (error);
1479 
1480 	AUDIT_ARG_FILE(td->td_proc, fp);
1481 
1482 	error = fo_stat(fp, sbp, td->td_ucred, td);
1483 	fdrop(fp, td);
1484 #ifdef __STAT_TIME_T_EXT
1485 	sbp->st_atim_ext = 0;
1486 	sbp->st_mtim_ext = 0;
1487 	sbp->st_ctim_ext = 0;
1488 	sbp->st_btim_ext = 0;
1489 #endif
1490 #ifdef KTRACE
1491 	if (KTRPOINT(td, KTR_STRUCT))
1492 		ktrstat_error(sbp, error);
1493 #endif
1494 	return (error);
1495 }
1496 
1497 #if defined(COMPAT_FREEBSD11)
1498 /*
1499  * Return status information about a file descriptor.
1500  */
1501 #ifndef _SYS_SYSPROTO_H_
1502 struct freebsd11_nfstat_args {
1503 	int	fd;
1504 	struct	nstat *sb;
1505 };
1506 #endif
1507 /* ARGSUSED */
1508 int
1509 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1510 {
1511 	struct nstat nub;
1512 	struct stat ub;
1513 	int error;
1514 
1515 	error = kern_fstat(td, uap->fd, &ub);
1516 	if (error == 0) {
1517 		freebsd11_cvtnstat(&ub, &nub);
1518 		error = copyout(&nub, uap->sb, sizeof(nub));
1519 	}
1520 	return (error);
1521 }
1522 #endif /* COMPAT_FREEBSD11 */
1523 
1524 /*
1525  * Return pathconf information about a file descriptor.
1526  */
1527 #ifndef _SYS_SYSPROTO_H_
1528 struct fpathconf_args {
1529 	int	fd;
1530 	int	name;
1531 };
1532 #endif
1533 /* ARGSUSED */
1534 int
1535 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1536 {
1537 	long value;
1538 	int error;
1539 
1540 	error = kern_fpathconf(td, uap->fd, uap->name, &value);
1541 	if (error == 0)
1542 		td->td_retval[0] = value;
1543 	return (error);
1544 }
1545 
1546 int
1547 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1548 {
1549 	struct file *fp;
1550 	struct vnode *vp;
1551 	int error;
1552 
1553 	error = fget(td, fd, &cap_fpathconf_rights, &fp);
1554 	if (error != 0)
1555 		return (error);
1556 
1557 	if (name == _PC_ASYNC_IO) {
1558 		*valuep = _POSIX_ASYNCHRONOUS_IO;
1559 		goto out;
1560 	}
1561 	vp = fp->f_vnode;
1562 	if (vp != NULL) {
1563 		vn_lock(vp, LK_SHARED | LK_RETRY);
1564 		error = VOP_PATHCONF(vp, name, valuep);
1565 		VOP_UNLOCK(vp);
1566 	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1567 		if (name != _PC_PIPE_BUF) {
1568 			error = EINVAL;
1569 		} else {
1570 			*valuep = PIPE_BUF;
1571 			error = 0;
1572 		}
1573 	} else {
1574 		error = EOPNOTSUPP;
1575 	}
1576 out:
1577 	fdrop(fp, td);
1578 	return (error);
1579 }
1580 
1581 /*
1582  * Copy filecaps structure allocating memory for ioctls array if needed.
1583  *
1584  * The last parameter indicates whether the fdtable is locked. If it is not and
1585  * ioctls are encountered, copying fails and the caller must lock the table.
1586  *
1587  * Note that if the table was not locked, the caller has to check the relevant
1588  * sequence counter to determine whether the operation was successful.
1589  */
1590 bool
1591 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1592 {
1593 	size_t size;
1594 
1595 	if (src->fc_ioctls != NULL && !locked)
1596 		return (false);
1597 	memcpy(dst, src, sizeof(*src));
1598 	if (src->fc_ioctls == NULL)
1599 		return (true);
1600 
1601 	KASSERT(src->fc_nioctls > 0,
1602 	    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1603 
1604 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1605 	dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1606 	memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1607 	return (true);
1608 }
1609 
1610 static u_long *
1611 filecaps_copy_prep(const struct filecaps *src)
1612 {
1613 	u_long *ioctls;
1614 	size_t size;
1615 
1616 	if (__predict_true(src->fc_ioctls == NULL))
1617 		return (NULL);
1618 
1619 	KASSERT(src->fc_nioctls > 0,
1620 	    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1621 
1622 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1623 	ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1624 	return (ioctls);
1625 }
1626 
1627 static void
1628 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1629     u_long *ioctls)
1630 {
1631 	size_t size;
1632 
1633 	*dst = *src;
1634 	if (__predict_true(src->fc_ioctls == NULL)) {
1635 		MPASS(ioctls == NULL);
1636 		return;
1637 	}
1638 
1639 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1640 	dst->fc_ioctls = ioctls;
1641 	bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1642 }
1643 
1644 /*
1645  * Move filecaps structure to the new place and clear the old place.
1646  */
1647 void
1648 filecaps_move(struct filecaps *src, struct filecaps *dst)
1649 {
1650 
1651 	*dst = *src;
1652 	bzero(src, sizeof(*src));
1653 }
1654 
1655 /*
1656  * Fill the given filecaps structure with full rights.
1657  */
1658 static void
1659 filecaps_fill(struct filecaps *fcaps)
1660 {
1661 
1662 	CAP_ALL(&fcaps->fc_rights);
1663 	fcaps->fc_ioctls = NULL;
1664 	fcaps->fc_nioctls = -1;
1665 	fcaps->fc_fcntls = CAP_FCNTL_ALL;
1666 }
1667 
1668 /*
1669  * Free memory allocated within filecaps structure.
1670  */
1671 void
1672 filecaps_free(struct filecaps *fcaps)
1673 {
1674 
1675 	free(fcaps->fc_ioctls, M_FILECAPS);
1676 	bzero(fcaps, sizeof(*fcaps));
1677 }
1678 
1679 static u_long *
1680 filecaps_free_prep(struct filecaps *fcaps)
1681 {
1682 	u_long *ioctls;
1683 
1684 	ioctls = fcaps->fc_ioctls;
1685 	bzero(fcaps, sizeof(*fcaps));
1686 	return (ioctls);
1687 }
1688 
1689 static void
1690 filecaps_free_finish(u_long *ioctls)
1691 {
1692 
1693 	free(ioctls, M_FILECAPS);
1694 }
1695 
1696 /*
1697  * Validate the given filecaps structure.
1698  */
1699 static void
1700 filecaps_validate(const struct filecaps *fcaps, const char *func)
1701 {
1702 
1703 	KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1704 	    ("%s: invalid rights", func));
1705 	KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1706 	    ("%s: invalid fcntls", func));
1707 	KASSERT(fcaps->fc_fcntls == 0 ||
1708 	    cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1709 	    ("%s: fcntls without CAP_FCNTL", func));
1710 	KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1711 	    (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1712 	    ("%s: invalid ioctls", func));
1713 	KASSERT(fcaps->fc_nioctls == 0 ||
1714 	    cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1715 	    ("%s: ioctls without CAP_IOCTL", func));
1716 }
1717 
1718 static void
1719 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1720 {
1721 	int nfd1;
1722 
1723 	FILEDESC_XLOCK_ASSERT(fdp);
1724 
1725 	nfd1 = fdp->fd_nfiles * 2;
1726 	if (nfd1 < nfd)
1727 		nfd1 = nfd;
1728 	fdgrowtable(fdp, nfd1);
1729 }
1730 
1731 /*
1732  * Grow the file table to accommodate (at least) nfd descriptors.
1733  */
1734 static void
1735 fdgrowtable(struct filedesc *fdp, int nfd)
1736 {
1737 	struct filedesc0 *fdp0;
1738 	struct freetable *ft;
1739 	struct fdescenttbl *ntable;
1740 	struct fdescenttbl *otable;
1741 	int nnfiles, onfiles;
1742 	NDSLOTTYPE *nmap, *omap;
1743 
1744 	/*
1745 	 * If lastfile is -1 this struct filedesc was just allocated and we are
1746 	 * growing it to accommodate for the one we are going to copy from. There
1747 	 * is no need to have a lock on this one as it's not visible to anyone.
1748 	 */
1749 	if (fdp->fd_lastfile != -1)
1750 		FILEDESC_XLOCK_ASSERT(fdp);
1751 
1752 	KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1753 
1754 	/* save old values */
1755 	onfiles = fdp->fd_nfiles;
1756 	otable = fdp->fd_files;
1757 	omap = fdp->fd_map;
1758 
1759 	/* compute the size of the new table */
1760 	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1761 	if (nnfiles <= onfiles)
1762 		/* the table is already large enough */
1763 		return;
1764 
1765 	/*
1766 	 * Allocate a new table.  We need enough space for the number of
1767 	 * entries, file entries themselves and the struct freetable we will use
1768 	 * when we decommission the table and place it on the freelist.
1769 	 * We place the struct freetable in the middle so we don't have
1770 	 * to worry about padding.
1771 	 */
1772 	ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1773 	    nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1774 	    sizeof(struct freetable),
1775 	    M_FILEDESC, M_ZERO | M_WAITOK);
1776 	/* copy the old data */
1777 	ntable->fdt_nfiles = nnfiles;
1778 	memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1779 	    onfiles * sizeof(ntable->fdt_ofiles[0]));
1780 
1781 	/*
1782 	 * Allocate a new map only if the old is not large enough.  It will
1783 	 * grow at a slower rate than the table as it can map more
1784 	 * entries than the table can hold.
1785 	 */
1786 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1787 		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1788 		    M_ZERO | M_WAITOK);
1789 		/* copy over the old data and update the pointer */
1790 		memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1791 		fdp->fd_map = nmap;
1792 	}
1793 
1794 	/*
1795 	 * Make sure that ntable is correctly initialized before we replace
1796 	 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1797 	 * data.
1798 	 */
1799 	atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1800 
1801 	/*
1802 	 * Do not free the old file table, as some threads may still
1803 	 * reference entries within it.  Instead, place it on a freelist
1804 	 * which will be processed when the struct filedesc is released.
1805 	 *
1806 	 * Note that if onfiles == NDFILE, we're dealing with the original
1807 	 * static allocation contained within (struct filedesc0 *)fdp,
1808 	 * which must not be freed.
1809 	 */
1810 	if (onfiles > NDFILE) {
1811 		ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1812 		fdp0 = (struct filedesc0 *)fdp;
1813 		ft->ft_table = otable;
1814 		SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1815 	}
1816 	/*
1817 	 * The map does not have the same possibility of threads still
1818 	 * holding references to it.  So always free it as long as it
1819 	 * does not reference the original static allocation.
1820 	 */
1821 	if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1822 		free(omap, M_FILEDESC);
1823 }
1824 
1825 /*
1826  * Allocate a file descriptor for the process.
1827  */
1828 int
1829 fdalloc(struct thread *td, int minfd, int *result)
1830 {
1831 	struct proc *p = td->td_proc;
1832 	struct filedesc *fdp = p->p_fd;
1833 	int fd, maxfd, allocfd;
1834 #ifdef RACCT
1835 	int error;
1836 #endif
1837 
1838 	FILEDESC_XLOCK_ASSERT(fdp);
1839 
1840 	if (fdp->fd_freefile > minfd)
1841 		minfd = fdp->fd_freefile;
1842 
1843 	maxfd = getmaxfd(td);
1844 
1845 	/*
1846 	 * Search the bitmap for a free descriptor starting at minfd.
1847 	 * If none is found, grow the file table.
1848 	 */
1849 	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1850 	if (fd >= maxfd)
1851 		return (EMFILE);
1852 	if (fd >= fdp->fd_nfiles) {
1853 		allocfd = min(fd * 2, maxfd);
1854 #ifdef RACCT
1855 		if (RACCT_ENABLED()) {
1856 			error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
1857 			if (error != 0)
1858 				return (EMFILE);
1859 		}
1860 #endif
1861 		/*
1862 		 * fd is already equal to first free descriptor >= minfd, so
1863 		 * we only need to grow the table and we are done.
1864 		 */
1865 		fdgrowtable_exp(fdp, allocfd);
1866 	}
1867 
1868 	/*
1869 	 * Perform some sanity checks, then mark the file descriptor as
1870 	 * used and return it to the caller.
1871 	 */
1872 	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1873 	    ("invalid descriptor %d", fd));
1874 	KASSERT(!fdisused(fdp, fd),
1875 	    ("fd_first_free() returned non-free descriptor"));
1876 	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1877 	    ("file descriptor isn't free"));
1878 	fdused(fdp, fd);
1879 	*result = fd;
1880 	return (0);
1881 }
1882 
1883 /*
1884  * Allocate n file descriptors for the process.
1885  */
1886 int
1887 fdallocn(struct thread *td, int minfd, int *fds, int n)
1888 {
1889 	struct proc *p = td->td_proc;
1890 	struct filedesc *fdp = p->p_fd;
1891 	int i;
1892 
1893 	FILEDESC_XLOCK_ASSERT(fdp);
1894 
1895 	for (i = 0; i < n; i++)
1896 		if (fdalloc(td, 0, &fds[i]) != 0)
1897 			break;
1898 
1899 	if (i < n) {
1900 		for (i--; i >= 0; i--)
1901 			fdunused(fdp, fds[i]);
1902 		return (EMFILE);
1903 	}
1904 
1905 	return (0);
1906 }
1907 
1908 /*
1909  * Create a new open file structure and allocate a file descriptor for the
1910  * process that refers to it.  We add one reference to the file for the
1911  * descriptor table and one reference for resultfp. This is to prevent us
1912  * being preempted and the entry in the descriptor table closed after we
1913  * release the FILEDESC lock.
1914  */
1915 int
1916 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1917     struct filecaps *fcaps)
1918 {
1919 	struct file *fp;
1920 	int error, fd;
1921 
1922 	error = falloc_noinstall(td, &fp);
1923 	if (error)
1924 		return (error);		/* no reference held on error */
1925 
1926 	error = finstall(td, fp, &fd, flags, fcaps);
1927 	if (error) {
1928 		fdrop(fp, td);		/* one reference (fp only) */
1929 		return (error);
1930 	}
1931 
1932 	if (resultfp != NULL)
1933 		*resultfp = fp;		/* copy out result */
1934 	else
1935 		fdrop(fp, td);		/* release local reference */
1936 
1937 	if (resultfd != NULL)
1938 		*resultfd = fd;
1939 
1940 	return (0);
1941 }
1942 
1943 /*
1944  * Create a new open file structure without allocating a file descriptor.
1945  */
1946 int
1947 falloc_noinstall(struct thread *td, struct file **resultfp)
1948 {
1949 	struct file *fp;
1950 	int maxuserfiles = maxfiles - (maxfiles / 20);
1951 	int openfiles_new;
1952 	static struct timeval lastfail;
1953 	static int curfail;
1954 
1955 	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1956 
1957 	openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
1958 	if ((openfiles_new >= maxuserfiles &&
1959 	    priv_check(td, PRIV_MAXFILES) != 0) ||
1960 	    openfiles_new >= maxfiles) {
1961 		atomic_subtract_int(&openfiles, 1);
1962 		if (ppsratecheck(&lastfail, &curfail, 1)) {
1963 			printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1964 			    "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1965 		}
1966 		return (ENFILE);
1967 	}
1968 	fp = uma_zalloc(file_zone, M_WAITOK);
1969 	bzero(fp, sizeof(*fp));
1970 	refcount_init(&fp->f_count, 1);
1971 	fp->f_cred = crhold(td->td_ucred);
1972 	fp->f_ops = &badfileops;
1973 	*resultfp = fp;
1974 	return (0);
1975 }
1976 
1977 /*
1978  * Install a file in a file descriptor table.
1979  */
1980 void
1981 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1982     struct filecaps *fcaps)
1983 {
1984 	struct filedescent *fde;
1985 
1986 	MPASS(fp != NULL);
1987 	if (fcaps != NULL)
1988 		filecaps_validate(fcaps, __func__);
1989 	FILEDESC_XLOCK_ASSERT(fdp);
1990 
1991 	fde = &fdp->fd_ofiles[fd];
1992 #ifdef CAPABILITIES
1993 	seqc_write_begin(&fde->fde_seqc);
1994 #endif
1995 	fde->fde_file = fp;
1996 	fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1997 	if (fcaps != NULL)
1998 		filecaps_move(fcaps, &fde->fde_caps);
1999 	else
2000 		filecaps_fill(&fde->fde_caps);
2001 #ifdef CAPABILITIES
2002 	seqc_write_end(&fde->fde_seqc);
2003 #endif
2004 }
2005 
2006 int
2007 finstall(struct thread *td, struct file *fp, int *fd, int flags,
2008     struct filecaps *fcaps)
2009 {
2010 	struct filedesc *fdp = td->td_proc->p_fd;
2011 	int error;
2012 
2013 	MPASS(fd != NULL);
2014 
2015 	if (!fhold(fp))
2016 		return (EBADF);
2017 	FILEDESC_XLOCK(fdp);
2018 	error = fdalloc(td, 0, fd);
2019 	if (__predict_false(error != 0)) {
2020 		FILEDESC_XUNLOCK(fdp);
2021 		fdrop(fp, td);
2022 		return (error);
2023 	}
2024 	_finstall(fdp, fp, *fd, flags, fcaps);
2025 	FILEDESC_XUNLOCK(fdp);
2026 	return (0);
2027 }
2028 
2029 /*
2030  * Build a new filedesc structure from another.
2031  * Copy the current, root, and jail root vnode references.
2032  *
2033  * If fdp is not NULL, return with it shared locked.
2034  */
2035 struct filedesc *
2036 fdinit(struct filedesc *fdp, bool prepfiles)
2037 {
2038 	struct filedesc0 *newfdp0;
2039 	struct filedesc *newfdp;
2040 	struct pwd *newpwd;
2041 
2042 	newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2043 	newfdp = &newfdp0->fd_fd;
2044 
2045 	/* Create the file descriptor table. */
2046 	FILEDESC_LOCK_INIT(newfdp);
2047 	refcount_init(&newfdp->fd_refcnt, 1);
2048 	refcount_init(&newfdp->fd_holdcnt, 1);
2049 	newfdp->fd_cmask = CMASK;
2050 	newfdp->fd_map = newfdp0->fd_dmap;
2051 	newfdp->fd_lastfile = -1;
2052 	newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2053 	newfdp->fd_files->fdt_nfiles = NDFILE;
2054 
2055 	if (fdp == NULL) {
2056 		newpwd = pwd_alloc();
2057 		smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2058 		return (newfdp);
2059 	}
2060 
2061 	if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
2062 		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2063 
2064 	FILEDESC_SLOCK(fdp);
2065 	newpwd = pwd_hold_filedesc(fdp);
2066 	smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2067 
2068 	if (!prepfiles) {
2069 		FILEDESC_SUNLOCK(fdp);
2070 	} else {
2071 		while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
2072 			FILEDESC_SUNLOCK(fdp);
2073 			fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2074 			FILEDESC_SLOCK(fdp);
2075 		}
2076 	}
2077 
2078 	return (newfdp);
2079 }
2080 
2081 static struct filedesc *
2082 fdhold(struct proc *p)
2083 {
2084 	struct filedesc *fdp;
2085 
2086 	PROC_LOCK_ASSERT(p, MA_OWNED);
2087 	fdp = p->p_fd;
2088 	if (fdp != NULL)
2089 		refcount_acquire(&fdp->fd_holdcnt);
2090 	return (fdp);
2091 }
2092 
2093 static void
2094 fddrop(struct filedesc *fdp)
2095 {
2096 
2097 	if (fdp->fd_holdcnt > 1) {
2098 		if (refcount_release(&fdp->fd_holdcnt) == 0)
2099 			return;
2100 	}
2101 
2102 	FILEDESC_LOCK_DESTROY(fdp);
2103 	uma_zfree(filedesc0_zone, fdp);
2104 }
2105 
2106 /*
2107  * Share a filedesc structure.
2108  */
2109 struct filedesc *
2110 fdshare(struct filedesc *fdp)
2111 {
2112 
2113 	refcount_acquire(&fdp->fd_refcnt);
2114 	return (fdp);
2115 }
2116 
2117 /*
2118  * Unshare a filedesc structure, if necessary by making a copy
2119  */
2120 void
2121 fdunshare(struct thread *td)
2122 {
2123 	struct filedesc *tmp;
2124 	struct proc *p = td->td_proc;
2125 
2126 	if (p->p_fd->fd_refcnt == 1)
2127 		return;
2128 
2129 	tmp = fdcopy(p->p_fd);
2130 	fdescfree(td);
2131 	p->p_fd = tmp;
2132 }
2133 
2134 void
2135 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
2136 {
2137 
2138 	fdescfree(td);
2139 	td->td_proc->p_fd = fdp;
2140 }
2141 
2142 /*
2143  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
2144  * this is to ease callers, not catch errors.
2145  */
2146 struct filedesc *
2147 fdcopy(struct filedesc *fdp)
2148 {
2149 	struct filedesc *newfdp;
2150 	struct filedescent *nfde, *ofde;
2151 	int i;
2152 
2153 	MPASS(fdp != NULL);
2154 
2155 	newfdp = fdinit(fdp, true);
2156 	/* copy all passable descriptors (i.e. not kqueue) */
2157 	newfdp->fd_freefile = -1;
2158 	for (i = 0; i <= fdp->fd_lastfile; ++i) {
2159 		ofde = &fdp->fd_ofiles[i];
2160 		if (ofde->fde_file == NULL ||
2161 		    (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2162 		    !fhold(ofde->fde_file)) {
2163 			if (newfdp->fd_freefile == -1)
2164 				newfdp->fd_freefile = i;
2165 			continue;
2166 		}
2167 		nfde = &newfdp->fd_ofiles[i];
2168 		*nfde = *ofde;
2169 		filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2170 		fdused_init(newfdp, i);
2171 		newfdp->fd_lastfile = i;
2172 	}
2173 	if (newfdp->fd_freefile == -1)
2174 		newfdp->fd_freefile = i;
2175 	newfdp->fd_cmask = fdp->fd_cmask;
2176 	FILEDESC_SUNLOCK(fdp);
2177 	return (newfdp);
2178 }
2179 
2180 /*
2181  * Copies a filedesc structure, while remapping all file descriptors
2182  * stored inside using a translation table.
2183  *
2184  * File descriptors are copied over to the new file descriptor table,
2185  * regardless of whether the close-on-exec flag is set.
2186  */
2187 int
2188 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
2189     struct filedesc **ret)
2190 {
2191 	struct filedesc *newfdp;
2192 	struct filedescent *nfde, *ofde;
2193 	int error, i;
2194 
2195 	MPASS(fdp != NULL);
2196 
2197 	newfdp = fdinit(fdp, true);
2198 	if (nfds > fdp->fd_lastfile + 1) {
2199 		/* New table cannot be larger than the old one. */
2200 		error = E2BIG;
2201 		goto bad;
2202 	}
2203 	/* Copy all passable descriptors (i.e. not kqueue). */
2204 	newfdp->fd_freefile = nfds;
2205 	for (i = 0; i < nfds; ++i) {
2206 		if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2207 			/* File descriptor out of bounds. */
2208 			error = EBADF;
2209 			goto bad;
2210 		}
2211 		ofde = &fdp->fd_ofiles[fds[i]];
2212 		if (ofde->fde_file == NULL) {
2213 			/* Unused file descriptor. */
2214 			error = EBADF;
2215 			goto bad;
2216 		}
2217 		if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2218 			/* File descriptor cannot be passed. */
2219 			error = EINVAL;
2220 			goto bad;
2221 		}
2222 		if (!fhold(nfde->fde_file)) {
2223 			error = EBADF;
2224 			goto bad;
2225 		}
2226 		nfde = &newfdp->fd_ofiles[i];
2227 		*nfde = *ofde;
2228 		filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2229 		fdused_init(newfdp, i);
2230 		newfdp->fd_lastfile = i;
2231 	}
2232 	newfdp->fd_cmask = fdp->fd_cmask;
2233 	FILEDESC_SUNLOCK(fdp);
2234 	*ret = newfdp;
2235 	return (0);
2236 bad:
2237 	FILEDESC_SUNLOCK(fdp);
2238 	fdescfree_remapped(newfdp);
2239 	return (error);
2240 }
2241 
2242 /*
2243  * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2244  * one of processes using it exits) and the table used to be shared.
2245  */
2246 static void
2247 fdclearlocks(struct thread *td)
2248 {
2249 	struct filedesc *fdp;
2250 	struct filedesc_to_leader *fdtol;
2251 	struct flock lf;
2252 	struct file *fp;
2253 	struct proc *p;
2254 	struct vnode *vp;
2255 	int i;
2256 
2257 	p = td->td_proc;
2258 	fdp = p->p_fd;
2259 	fdtol = p->p_fdtol;
2260 	MPASS(fdtol != NULL);
2261 
2262 	FILEDESC_XLOCK(fdp);
2263 	KASSERT(fdtol->fdl_refcount > 0,
2264 	    ("filedesc_to_refcount botch: fdl_refcount=%d",
2265 	    fdtol->fdl_refcount));
2266 	if (fdtol->fdl_refcount == 1 &&
2267 	    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2268 		for (i = 0; i <= fdp->fd_lastfile; i++) {
2269 			fp = fdp->fd_ofiles[i].fde_file;
2270 			if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2271 			    !fhold(fp))
2272 				continue;
2273 			FILEDESC_XUNLOCK(fdp);
2274 			lf.l_whence = SEEK_SET;
2275 			lf.l_start = 0;
2276 			lf.l_len = 0;
2277 			lf.l_type = F_UNLCK;
2278 			vp = fp->f_vnode;
2279 			(void) VOP_ADVLOCK(vp,
2280 			    (caddr_t)p->p_leader, F_UNLCK,
2281 			    &lf, F_POSIX);
2282 			FILEDESC_XLOCK(fdp);
2283 			fdrop(fp, td);
2284 		}
2285 	}
2286 retry:
2287 	if (fdtol->fdl_refcount == 1) {
2288 		if (fdp->fd_holdleaderscount > 0 &&
2289 		    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2290 			/*
2291 			 * close() or kern_dup() has cleared a reference
2292 			 * in a shared file descriptor table.
2293 			 */
2294 			fdp->fd_holdleaderswakeup = 1;
2295 			sx_sleep(&fdp->fd_holdleaderscount,
2296 			    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2297 			goto retry;
2298 		}
2299 		if (fdtol->fdl_holdcount > 0) {
2300 			/*
2301 			 * Ensure that fdtol->fdl_leader remains
2302 			 * valid in closef().
2303 			 */
2304 			fdtol->fdl_wakeup = 1;
2305 			sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2306 			    "fdlhold", 0);
2307 			goto retry;
2308 		}
2309 	}
2310 	fdtol->fdl_refcount--;
2311 	if (fdtol->fdl_refcount == 0 &&
2312 	    fdtol->fdl_holdcount == 0) {
2313 		fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2314 		fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2315 	} else
2316 		fdtol = NULL;
2317 	p->p_fdtol = NULL;
2318 	FILEDESC_XUNLOCK(fdp);
2319 	if (fdtol != NULL)
2320 		free(fdtol, M_FILEDESC_TO_LEADER);
2321 }
2322 
2323 /*
2324  * Release a filedesc structure.
2325  */
2326 static void
2327 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2328 {
2329 	struct filedesc0 *fdp0;
2330 	struct freetable *ft, *tft;
2331 	struct filedescent *fde;
2332 	struct file *fp;
2333 	int i;
2334 
2335 	for (i = 0; i <= fdp->fd_lastfile; i++) {
2336 		fde = &fdp->fd_ofiles[i];
2337 		fp = fde->fde_file;
2338 		if (fp != NULL) {
2339 			fdefree_last(fde);
2340 			if (needclose)
2341 				(void) closef(fp, td);
2342 			else
2343 				fdrop(fp, td);
2344 		}
2345 	}
2346 
2347 	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2348 		free(fdp->fd_map, M_FILEDESC);
2349 	if (fdp->fd_nfiles > NDFILE)
2350 		free(fdp->fd_files, M_FILEDESC);
2351 
2352 	fdp0 = (struct filedesc0 *)fdp;
2353 	SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2354 		free(ft->ft_table, M_FILEDESC);
2355 
2356 	fddrop(fdp);
2357 }
2358 
2359 void
2360 fdescfree(struct thread *td)
2361 {
2362 	struct proc *p;
2363 	struct filedesc *fdp;
2364 	struct pwd *pwd;
2365 
2366 	p = td->td_proc;
2367 	fdp = p->p_fd;
2368 	MPASS(fdp != NULL);
2369 
2370 #ifdef RACCT
2371 	if (RACCT_ENABLED())
2372 		racct_set_unlocked(p, RACCT_NOFILE, 0);
2373 #endif
2374 
2375 	if (p->p_fdtol != NULL)
2376 		fdclearlocks(td);
2377 
2378 	PROC_LOCK(p);
2379 	p->p_fd = NULL;
2380 	PROC_UNLOCK(p);
2381 
2382 	if (refcount_release(&fdp->fd_refcnt) == 0)
2383 		return;
2384 
2385 	FILEDESC_XLOCK(fdp);
2386 	pwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
2387 	pwd_set(fdp, NULL);
2388 	FILEDESC_XUNLOCK(fdp);
2389 
2390 	pwd_drop(pwd);
2391 
2392 	fdescfree_fds(td, fdp, 1);
2393 }
2394 
2395 void
2396 fdescfree_remapped(struct filedesc *fdp)
2397 {
2398 
2399 	pwd_drop(smr_serialized_load(&fdp->fd_pwd, true));
2400 	fdescfree_fds(curthread, fdp, 0);
2401 }
2402 
2403 /*
2404  * For setugid programs, we don't want to people to use that setugidness
2405  * to generate error messages which write to a file which otherwise would
2406  * otherwise be off-limits to the process.  We check for filesystems where
2407  * the vnode can change out from under us after execve (like [lin]procfs).
2408  *
2409  * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2410  * sufficient.  We also don't check for setugidness since we know we are.
2411  */
2412 static bool
2413 is_unsafe(struct file *fp)
2414 {
2415 	struct vnode *vp;
2416 
2417 	if (fp->f_type != DTYPE_VNODE)
2418 		return (false);
2419 
2420 	vp = fp->f_vnode;
2421 	return ((vp->v_vflag & VV_PROCDEP) != 0);
2422 }
2423 
2424 /*
2425  * Make this setguid thing safe, if at all possible.
2426  */
2427 void
2428 fdsetugidsafety(struct thread *td)
2429 {
2430 	struct filedesc *fdp;
2431 	struct file *fp;
2432 	int i;
2433 
2434 	fdp = td->td_proc->p_fd;
2435 	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2436 	MPASS(fdp->fd_nfiles >= 3);
2437 	for (i = 0; i <= 2; i++) {
2438 		fp = fdp->fd_ofiles[i].fde_file;
2439 		if (fp != NULL && is_unsafe(fp)) {
2440 			FILEDESC_XLOCK(fdp);
2441 			knote_fdclose(td, i);
2442 			/*
2443 			 * NULL-out descriptor prior to close to avoid
2444 			 * a race while close blocks.
2445 			 */
2446 			fdfree(fdp, i);
2447 			FILEDESC_XUNLOCK(fdp);
2448 			(void) closef(fp, td);
2449 		}
2450 	}
2451 }
2452 
2453 /*
2454  * If a specific file object occupies a specific file descriptor, close the
2455  * file descriptor entry and drop a reference on the file object.  This is a
2456  * convenience function to handle a subsequent error in a function that calls
2457  * falloc() that handles the race that another thread might have closed the
2458  * file descriptor out from under the thread creating the file object.
2459  */
2460 void
2461 fdclose(struct thread *td, struct file *fp, int idx)
2462 {
2463 	struct filedesc *fdp = td->td_proc->p_fd;
2464 
2465 	FILEDESC_XLOCK(fdp);
2466 	if (fdp->fd_ofiles[idx].fde_file == fp) {
2467 		fdfree(fdp, idx);
2468 		FILEDESC_XUNLOCK(fdp);
2469 		fdrop(fp, td);
2470 	} else
2471 		FILEDESC_XUNLOCK(fdp);
2472 }
2473 
2474 /*
2475  * Close any files on exec?
2476  */
2477 void
2478 fdcloseexec(struct thread *td)
2479 {
2480 	struct filedesc *fdp;
2481 	struct filedescent *fde;
2482 	struct file *fp;
2483 	int i;
2484 
2485 	fdp = td->td_proc->p_fd;
2486 	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2487 	for (i = 0; i <= fdp->fd_lastfile; i++) {
2488 		fde = &fdp->fd_ofiles[i];
2489 		fp = fde->fde_file;
2490 		if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2491 		    (fde->fde_flags & UF_EXCLOSE))) {
2492 			FILEDESC_XLOCK(fdp);
2493 			fdfree(fdp, i);
2494 			(void) closefp(fdp, i, fp, td, 0);
2495 			FILEDESC_UNLOCK_ASSERT(fdp);
2496 		}
2497 	}
2498 }
2499 
2500 /*
2501  * It is unsafe for set[ug]id processes to be started with file
2502  * descriptors 0..2 closed, as these descriptors are given implicit
2503  * significance in the Standard C library.  fdcheckstd() will create a
2504  * descriptor referencing /dev/null for each of stdin, stdout, and
2505  * stderr that is not already open.
2506  */
2507 int
2508 fdcheckstd(struct thread *td)
2509 {
2510 	struct filedesc *fdp;
2511 	register_t save;
2512 	int i, error, devnull;
2513 
2514 	fdp = td->td_proc->p_fd;
2515 	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2516 	MPASS(fdp->fd_nfiles >= 3);
2517 	devnull = -1;
2518 	for (i = 0; i <= 2; i++) {
2519 		if (fdp->fd_ofiles[i].fde_file != NULL)
2520 			continue;
2521 
2522 		save = td->td_retval[0];
2523 		if (devnull != -1) {
2524 			error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2525 		} else {
2526 			error = kern_openat(td, AT_FDCWD, "/dev/null",
2527 			    UIO_SYSSPACE, O_RDWR, 0);
2528 			if (error == 0) {
2529 				devnull = td->td_retval[0];
2530 				KASSERT(devnull == i, ("we didn't get our fd"));
2531 			}
2532 		}
2533 		td->td_retval[0] = save;
2534 		if (error != 0)
2535 			return (error);
2536 	}
2537 	return (0);
2538 }
2539 
2540 /*
2541  * Internal form of close.  Decrement reference count on file structure.
2542  * Note: td may be NULL when closing a file that was being passed in a
2543  * message.
2544  */
2545 int
2546 closef(struct file *fp, struct thread *td)
2547 {
2548 	struct vnode *vp;
2549 	struct flock lf;
2550 	struct filedesc_to_leader *fdtol;
2551 	struct filedesc *fdp;
2552 
2553 	/*
2554 	 * POSIX record locking dictates that any close releases ALL
2555 	 * locks owned by this process.  This is handled by setting
2556 	 * a flag in the unlock to free ONLY locks obeying POSIX
2557 	 * semantics, and not to free BSD-style file locks.
2558 	 * If the descriptor was in a message, POSIX-style locks
2559 	 * aren't passed with the descriptor, and the thread pointer
2560 	 * will be NULL.  Callers should be careful only to pass a
2561 	 * NULL thread pointer when there really is no owning
2562 	 * context that might have locks, or the locks will be
2563 	 * leaked.
2564 	 */
2565 	if (fp->f_type == DTYPE_VNODE && td != NULL) {
2566 		vp = fp->f_vnode;
2567 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2568 			lf.l_whence = SEEK_SET;
2569 			lf.l_start = 0;
2570 			lf.l_len = 0;
2571 			lf.l_type = F_UNLCK;
2572 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2573 			    F_UNLCK, &lf, F_POSIX);
2574 		}
2575 		fdtol = td->td_proc->p_fdtol;
2576 		if (fdtol != NULL) {
2577 			/*
2578 			 * Handle special case where file descriptor table is
2579 			 * shared between multiple process leaders.
2580 			 */
2581 			fdp = td->td_proc->p_fd;
2582 			FILEDESC_XLOCK(fdp);
2583 			for (fdtol = fdtol->fdl_next;
2584 			    fdtol != td->td_proc->p_fdtol;
2585 			    fdtol = fdtol->fdl_next) {
2586 				if ((fdtol->fdl_leader->p_flag &
2587 				    P_ADVLOCK) == 0)
2588 					continue;
2589 				fdtol->fdl_holdcount++;
2590 				FILEDESC_XUNLOCK(fdp);
2591 				lf.l_whence = SEEK_SET;
2592 				lf.l_start = 0;
2593 				lf.l_len = 0;
2594 				lf.l_type = F_UNLCK;
2595 				vp = fp->f_vnode;
2596 				(void) VOP_ADVLOCK(vp,
2597 				    (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2598 				    F_POSIX);
2599 				FILEDESC_XLOCK(fdp);
2600 				fdtol->fdl_holdcount--;
2601 				if (fdtol->fdl_holdcount == 0 &&
2602 				    fdtol->fdl_wakeup != 0) {
2603 					fdtol->fdl_wakeup = 0;
2604 					wakeup(fdtol);
2605 				}
2606 			}
2607 			FILEDESC_XUNLOCK(fdp);
2608 		}
2609 	}
2610 	return (fdrop(fp, td));
2611 }
2612 
2613 /*
2614  * Initialize the file pointer with the specified properties.
2615  *
2616  * The ops are set with release semantics to be certain that the flags, type,
2617  * and data are visible when ops is.  This is to prevent ops methods from being
2618  * called with bad data.
2619  */
2620 void
2621 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2622 {
2623 	fp->f_data = data;
2624 	fp->f_flag = flag;
2625 	fp->f_type = type;
2626 	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2627 }
2628 
2629 int
2630 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2631     struct file **fpp, struct filecaps *havecapsp)
2632 {
2633 	struct filedescent *fde;
2634 	int error;
2635 
2636 	FILEDESC_LOCK_ASSERT(fdp);
2637 
2638 	fde = fdeget_locked(fdp, fd);
2639 	if (fde == NULL) {
2640 		error = EBADF;
2641 		goto out;
2642 	}
2643 
2644 #ifdef CAPABILITIES
2645 	error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2646 	if (error != 0)
2647 		goto out;
2648 #endif
2649 
2650 	if (havecapsp != NULL)
2651 		filecaps_copy(&fde->fde_caps, havecapsp, true);
2652 
2653 	*fpp = fde->fde_file;
2654 
2655 	error = 0;
2656 out:
2657 	return (error);
2658 }
2659 
2660 int
2661 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2662     struct file **fpp, struct filecaps *havecapsp)
2663 {
2664 	struct filedesc *fdp = td->td_proc->p_fd;
2665 	int error;
2666 #ifndef CAPABILITIES
2667 	error = fget_unlocked(fdp, fd, needrightsp, fpp);
2668 	if (havecapsp != NULL && error == 0)
2669 		filecaps_fill(havecapsp);
2670 #else
2671 	struct file *fp;
2672 	seqc_t seq;
2673 
2674 	*fpp = NULL;
2675 	for (;;) {
2676 		error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
2677 		if (error != 0)
2678 			return (error);
2679 
2680 		if (havecapsp != NULL) {
2681 			if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2682 			    havecapsp, false)) {
2683 				fdrop(fp, td);
2684 				goto get_locked;
2685 			}
2686 		}
2687 
2688 		if (!fd_modified(fdp, fd, seq))
2689 			break;
2690 		fdrop(fp, td);
2691 	}
2692 
2693 	*fpp = fp;
2694 	return (0);
2695 
2696 get_locked:
2697 	FILEDESC_SLOCK(fdp);
2698 	error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2699 	if (error == 0 && !fhold(*fpp))
2700 		error = EBADF;
2701 	FILEDESC_SUNLOCK(fdp);
2702 #endif
2703 	return (error);
2704 }
2705 
2706 int
2707 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2708     struct file **fpp, seqc_t *seqp)
2709 {
2710 #ifdef CAPABILITIES
2711 	const struct filedescent *fde;
2712 #endif
2713 	const struct fdescenttbl *fdt;
2714 	struct file *fp;
2715 #ifdef CAPABILITIES
2716 	seqc_t seq;
2717 	cap_rights_t haverights;
2718 	int error;
2719 #endif
2720 
2721 	fdt = fdp->fd_files;
2722 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2723 		return (EBADF);
2724 	/*
2725 	 * Fetch the descriptor locklessly.  We avoid fdrop() races by
2726 	 * never raising a refcount above 0.  To accomplish this we have
2727 	 * to use a cmpset loop rather than an atomic_add.  The descriptor
2728 	 * must be re-verified once we acquire a reference to be certain
2729 	 * that the identity is still correct and we did not lose a race
2730 	 * due to preemption.
2731 	 */
2732 	for (;;) {
2733 #ifdef CAPABILITIES
2734 		seq = seqc_read(fd_seqc(fdt, fd));
2735 		fde = &fdt->fdt_ofiles[fd];
2736 		haverights = *cap_rights_fde_inline(fde);
2737 		fp = fde->fde_file;
2738 		if (!seqc_consistent(fd_seqc(fdt, fd), seq))
2739 			continue;
2740 #else
2741 		fp = fdt->fdt_ofiles[fd].fde_file;
2742 #endif
2743 		if (fp == NULL)
2744 			return (EBADF);
2745 #ifdef CAPABILITIES
2746 		error = cap_check_inline(&haverights, needrightsp);
2747 		if (error != 0)
2748 			return (error);
2749 #endif
2750 		if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
2751 			/*
2752 			 * The count was found either saturated or zero.
2753 			 * This re-read is not any more racy than using the
2754 			 * return value from fcmpset.
2755 			 */
2756 			if (fp->f_count != 0)
2757 				return (EBADF);
2758 			/*
2759 			 * Force a reload. Other thread could reallocate the
2760 			 * table before this fd was closed, so it is possible
2761 			 * that there is a stale fp pointer in cached version.
2762 			 */
2763 			fdt = atomic_load_ptr(&fdp->fd_files);
2764 			continue;
2765 		}
2766 		/*
2767 		 * Use an acquire barrier to force re-reading of fdt so it is
2768 		 * refreshed for verification.
2769 		 */
2770 		atomic_thread_fence_acq();
2771 		fdt = fdp->fd_files;
2772 #ifdef	CAPABILITIES
2773 		if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
2774 #else
2775 		if (fp == fdt->fdt_ofiles[fd].fde_file)
2776 #endif
2777 			break;
2778 		fdrop(fp, curthread);
2779 	}
2780 	*fpp = fp;
2781 	if (seqp != NULL) {
2782 #ifdef CAPABILITIES
2783 		*seqp = seq;
2784 #endif
2785 	}
2786 	return (0);
2787 }
2788 
2789 /*
2790  * See the comments in fget_unlocked_seq for an explanation of how this works.
2791  *
2792  * This is a simplified variant which bails out to the aforementioned routine
2793  * if anything goes wrong. In practice this only happens when userspace is
2794  * racing with itself.
2795  */
2796 int
2797 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2798     struct file **fpp)
2799 {
2800 #ifdef CAPABILITIES
2801 	const struct filedescent *fde;
2802 #endif
2803 	const struct fdescenttbl *fdt;
2804 	struct file *fp;
2805 #ifdef CAPABILITIES
2806 	seqc_t seq;
2807 	const cap_rights_t *haverights;
2808 #endif
2809 
2810 	fdt = fdp->fd_files;
2811 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2812 		return (EBADF);
2813 #ifdef CAPABILITIES
2814 	seq = seqc_read_any(fd_seqc(fdt, fd));
2815 	if (__predict_false(seqc_in_modify(seq)))
2816 		goto out_fallback;
2817 	fde = &fdt->fdt_ofiles[fd];
2818 	haverights = cap_rights_fde_inline(fde);
2819 	fp = fde->fde_file;
2820 #else
2821 	fp = fdt->fdt_ofiles[fd].fde_file;
2822 #endif
2823 	if (__predict_false(fp == NULL))
2824 		goto out_fallback;
2825 #ifdef CAPABILITIES
2826 	if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
2827 		goto out_fallback;
2828 #endif
2829 	if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
2830 		goto out_fallback;
2831 
2832 	/*
2833 	 * Use an acquire barrier to force re-reading of fdt so it is
2834 	 * refreshed for verification.
2835 	 */
2836 	atomic_thread_fence_acq();
2837 	fdt = fdp->fd_files;
2838 #ifdef	CAPABILITIES
2839 	if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
2840 #else
2841 	if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
2842 #endif
2843 		goto out_fdrop;
2844 	*fpp = fp;
2845 	return (0);
2846 out_fdrop:
2847 	fdrop(fp, curthread);
2848 out_fallback:
2849 	return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
2850 }
2851 
2852 /*
2853  * Extract the file pointer associated with the specified descriptor for the
2854  * current user process.
2855  *
2856  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2857  * returned.
2858  *
2859  * File's rights will be checked against the capability rights mask.
2860  *
2861  * If an error occurred the non-zero error is returned and *fpp is set to
2862  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
2863  * responsible for fdrop().
2864  */
2865 static __inline int
2866 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2867     cap_rights_t *needrightsp)
2868 {
2869 	struct filedesc *fdp;
2870 	struct file *fp;
2871 	int error;
2872 
2873 	*fpp = NULL;
2874 	fdp = td->td_proc->p_fd;
2875 	error = fget_unlocked(fdp, fd, needrightsp, &fp);
2876 	if (__predict_false(error != 0))
2877 		return (error);
2878 	if (__predict_false(fp->f_ops == &badfileops)) {
2879 		fdrop(fp, td);
2880 		return (EBADF);
2881 	}
2882 
2883 	/*
2884 	 * FREAD and FWRITE failure return EBADF as per POSIX.
2885 	 */
2886 	error = 0;
2887 	switch (flags) {
2888 	case FREAD:
2889 	case FWRITE:
2890 		if ((fp->f_flag & flags) == 0)
2891 			error = EBADF;
2892 		break;
2893 	case FEXEC:
2894 	    	if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2895 		    ((fp->f_flag & FWRITE) != 0))
2896 			error = EBADF;
2897 		break;
2898 	case 0:
2899 		break;
2900 	default:
2901 		KASSERT(0, ("wrong flags"));
2902 	}
2903 
2904 	if (error != 0) {
2905 		fdrop(fp, td);
2906 		return (error);
2907 	}
2908 
2909 	*fpp = fp;
2910 	return (0);
2911 }
2912 
2913 int
2914 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2915 {
2916 
2917 	return (_fget(td, fd, fpp, 0, rightsp));
2918 }
2919 
2920 int
2921 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
2922     struct file **fpp)
2923 {
2924 	int error;
2925 #ifndef CAPABILITIES
2926 	error = _fget(td, fd, fpp, 0, rightsp);
2927 	if (maxprotp != NULL)
2928 		*maxprotp = VM_PROT_ALL;
2929 	return (error);
2930 #else
2931 	cap_rights_t fdrights;
2932 	struct filedesc *fdp;
2933 	struct file *fp;
2934 	seqc_t seq;
2935 
2936 	*fpp = NULL;
2937 	fdp = td->td_proc->p_fd;
2938 	MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2939 	for (;;) {
2940 		error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2941 		if (__predict_false(error != 0))
2942 			return (error);
2943 		if (__predict_false(fp->f_ops == &badfileops)) {
2944 			fdrop(fp, td);
2945 			return (EBADF);
2946 		}
2947 		if (maxprotp != NULL)
2948 			fdrights = *cap_rights(fdp, fd);
2949 		if (!fd_modified(fdp, fd, seq))
2950 			break;
2951 		fdrop(fp, td);
2952 	}
2953 
2954 	/*
2955 	 * If requested, convert capability rights to access flags.
2956 	 */
2957 	if (maxprotp != NULL)
2958 		*maxprotp = cap_rights_to_vmprot(&fdrights);
2959 	*fpp = fp;
2960 	return (0);
2961 #endif
2962 }
2963 
2964 int
2965 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2966 {
2967 
2968 	return (_fget(td, fd, fpp, FREAD, rightsp));
2969 }
2970 
2971 int
2972 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2973 {
2974 
2975 	return (_fget(td, fd, fpp, FWRITE, rightsp));
2976 }
2977 
2978 int
2979 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2980     struct file **fpp)
2981 {
2982 	struct filedesc *fdp = td->td_proc->p_fd;
2983 #ifndef CAPABILITIES
2984 	return (fget_unlocked(fdp, fd, rightsp, fpp));
2985 #else
2986 	struct file *fp;
2987 	int error;
2988 	seqc_t seq;
2989 
2990 	*fpp = NULL;
2991 	MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2992 	for (;;) {
2993 		error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2994 		if (error != 0)
2995 			return (error);
2996 		error = cap_fcntl_check(fdp, fd, needfcntl);
2997 		if (!fd_modified(fdp, fd, seq))
2998 			break;
2999 		fdrop(fp, td);
3000 	}
3001 	if (error != 0) {
3002 		fdrop(fp, td);
3003 		return (error);
3004 	}
3005 	*fpp = fp;
3006 	return (0);
3007 #endif
3008 }
3009 
3010 /*
3011  * Like fget() but loads the underlying vnode, or returns an error if the
3012  * descriptor does not represent a vnode.  Note that pipes use vnodes but
3013  * never have VM objects.  The returned vnode will be vref()'d.
3014  *
3015  * XXX: what about the unused flags ?
3016  */
3017 static __inline int
3018 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3019     struct vnode **vpp)
3020 {
3021 	struct file *fp;
3022 	int error;
3023 
3024 	*vpp = NULL;
3025 	error = _fget(td, fd, &fp, flags, needrightsp);
3026 	if (error != 0)
3027 		return (error);
3028 	if (fp->f_vnode == NULL) {
3029 		error = EINVAL;
3030 	} else {
3031 		*vpp = fp->f_vnode;
3032 		vrefact(*vpp);
3033 	}
3034 	fdrop(fp, td);
3035 
3036 	return (error);
3037 }
3038 
3039 int
3040 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3041 {
3042 
3043 	return (_fgetvp(td, fd, 0, rightsp, vpp));
3044 }
3045 
3046 int
3047 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3048     struct filecaps *havecaps, struct vnode **vpp)
3049 {
3050 	struct filecaps caps;
3051 	struct file *fp;
3052 	int error;
3053 
3054 	error = fget_cap(td, fd, needrightsp, &fp, &caps);
3055 	if (error != 0)
3056 		return (error);
3057 	if (fp->f_ops == &badfileops) {
3058 		error = EBADF;
3059 		goto out;
3060 	}
3061 	if (fp->f_vnode == NULL) {
3062 		error = EINVAL;
3063 		goto out;
3064 	}
3065 
3066 	*havecaps = caps;
3067 	*vpp = fp->f_vnode;
3068 	vrefact(*vpp);
3069 	fdrop(fp, td);
3070 
3071 	return (0);
3072 out:
3073 	filecaps_free(&caps);
3074 	fdrop(fp, td);
3075 	return (error);
3076 }
3077 
3078 int
3079 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3080 {
3081 
3082 	return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3083 }
3084 
3085 int
3086 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3087 {
3088 
3089 	return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3090 }
3091 
3092 #ifdef notyet
3093 int
3094 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3095     struct vnode **vpp)
3096 {
3097 
3098 	return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3099 }
3100 #endif
3101 
3102 /*
3103  * Handle the last reference to a file being closed.
3104  *
3105  * Without the noinline attribute clang keeps inlining the func thorough this
3106  * file when fdrop is used.
3107  */
3108 int __noinline
3109 _fdrop(struct file *fp, struct thread *td)
3110 {
3111 	int error;
3112 
3113 	if (fp->f_count != 0)
3114 		panic("fdrop: count %d", fp->f_count);
3115 	error = fo_close(fp, td);
3116 	atomic_subtract_int(&openfiles, 1);
3117 	crfree(fp->f_cred);
3118 	free(fp->f_advice, M_FADVISE);
3119 	uma_zfree(file_zone, fp);
3120 
3121 	return (error);
3122 }
3123 
3124 /*
3125  * Apply an advisory lock on a file descriptor.
3126  *
3127  * Just attempt to get a record lock of the requested type on the entire file
3128  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3129  */
3130 #ifndef _SYS_SYSPROTO_H_
3131 struct flock_args {
3132 	int	fd;
3133 	int	how;
3134 };
3135 #endif
3136 /* ARGSUSED */
3137 int
3138 sys_flock(struct thread *td, struct flock_args *uap)
3139 {
3140 	struct file *fp;
3141 	struct vnode *vp;
3142 	struct flock lf;
3143 	int error;
3144 
3145 	error = fget(td, uap->fd, &cap_flock_rights, &fp);
3146 	if (error != 0)
3147 		return (error);
3148 	if (fp->f_type != DTYPE_VNODE) {
3149 		fdrop(fp, td);
3150 		return (EOPNOTSUPP);
3151 	}
3152 
3153 	vp = fp->f_vnode;
3154 	lf.l_whence = SEEK_SET;
3155 	lf.l_start = 0;
3156 	lf.l_len = 0;
3157 	if (uap->how & LOCK_UN) {
3158 		lf.l_type = F_UNLCK;
3159 		atomic_clear_int(&fp->f_flag, FHASLOCK);
3160 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3161 		goto done2;
3162 	}
3163 	if (uap->how & LOCK_EX)
3164 		lf.l_type = F_WRLCK;
3165 	else if (uap->how & LOCK_SH)
3166 		lf.l_type = F_RDLCK;
3167 	else {
3168 		error = EBADF;
3169 		goto done2;
3170 	}
3171 	atomic_set_int(&fp->f_flag, FHASLOCK);
3172 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3173 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3174 done2:
3175 	fdrop(fp, td);
3176 	return (error);
3177 }
3178 /*
3179  * Duplicate the specified descriptor to a free descriptor.
3180  */
3181 int
3182 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3183     int openerror, int *indxp)
3184 {
3185 	struct filedescent *newfde, *oldfde;
3186 	struct file *fp;
3187 	u_long *ioctls;
3188 	int error, indx;
3189 
3190 	KASSERT(openerror == ENODEV || openerror == ENXIO,
3191 	    ("unexpected error %d in %s", openerror, __func__));
3192 
3193 	/*
3194 	 * If the to-be-dup'd fd number is greater than the allowed number
3195 	 * of file descriptors, or the fd to be dup'd has already been
3196 	 * closed, then reject.
3197 	 */
3198 	FILEDESC_XLOCK(fdp);
3199 	if ((fp = fget_locked(fdp, dfd)) == NULL) {
3200 		FILEDESC_XUNLOCK(fdp);
3201 		return (EBADF);
3202 	}
3203 
3204 	error = fdalloc(td, 0, &indx);
3205 	if (error != 0) {
3206 		FILEDESC_XUNLOCK(fdp);
3207 		return (error);
3208 	}
3209 
3210 	/*
3211 	 * There are two cases of interest here.
3212 	 *
3213 	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3214 	 *
3215 	 * For ENXIO steal away the file structure from (dfd) and store it in
3216 	 * (indx).  (dfd) is effectively closed by this operation.
3217 	 */
3218 	switch (openerror) {
3219 	case ENODEV:
3220 		/*
3221 		 * Check that the mode the file is being opened for is a
3222 		 * subset of the mode of the existing descriptor.
3223 		 */
3224 		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3225 			fdunused(fdp, indx);
3226 			FILEDESC_XUNLOCK(fdp);
3227 			return (EACCES);
3228 		}
3229 		if (!fhold(fp)) {
3230 			fdunused(fdp, indx);
3231 			FILEDESC_XUNLOCK(fdp);
3232 			return (EBADF);
3233 		}
3234 		newfde = &fdp->fd_ofiles[indx];
3235 		oldfde = &fdp->fd_ofiles[dfd];
3236 		ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3237 #ifdef CAPABILITIES
3238 		seqc_write_begin(&newfde->fde_seqc);
3239 #endif
3240 		memcpy(newfde, oldfde, fde_change_size);
3241 		filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3242 		    ioctls);
3243 #ifdef CAPABILITIES
3244 		seqc_write_end(&newfde->fde_seqc);
3245 #endif
3246 		break;
3247 	case ENXIO:
3248 		/*
3249 		 * Steal away the file pointer from dfd and stuff it into indx.
3250 		 */
3251 		newfde = &fdp->fd_ofiles[indx];
3252 		oldfde = &fdp->fd_ofiles[dfd];
3253 #ifdef CAPABILITIES
3254 		seqc_write_begin(&newfde->fde_seqc);
3255 #endif
3256 		memcpy(newfde, oldfde, fde_change_size);
3257 		oldfde->fde_file = NULL;
3258 		fdunused(fdp, dfd);
3259 #ifdef CAPABILITIES
3260 		seqc_write_end(&newfde->fde_seqc);
3261 #endif
3262 		break;
3263 	}
3264 	FILEDESC_XUNLOCK(fdp);
3265 	*indxp = indx;
3266 	return (0);
3267 }
3268 
3269 /*
3270  * This sysctl determines if we will allow a process to chroot(2) if it
3271  * has a directory open:
3272  *	0: disallowed for all processes.
3273  *	1: allowed for processes that were not already chroot(2)'ed.
3274  *	2: allowed for all processes.
3275  */
3276 
3277 static int chroot_allow_open_directories = 1;
3278 
3279 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3280     &chroot_allow_open_directories, 0,
3281     "Allow a process to chroot(2) if it has a directory open");
3282 
3283 /*
3284  * Helper function for raised chroot(2) security function:  Refuse if
3285  * any filedescriptors are open directories.
3286  */
3287 static int
3288 chroot_refuse_vdir_fds(struct filedesc *fdp)
3289 {
3290 	struct vnode *vp;
3291 	struct file *fp;
3292 	int fd;
3293 
3294 	FILEDESC_LOCK_ASSERT(fdp);
3295 
3296 	for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3297 		fp = fget_locked(fdp, fd);
3298 		if (fp == NULL)
3299 			continue;
3300 		if (fp->f_type == DTYPE_VNODE) {
3301 			vp = fp->f_vnode;
3302 			if (vp->v_type == VDIR)
3303 				return (EPERM);
3304 		}
3305 	}
3306 	return (0);
3307 }
3308 
3309 static void
3310 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3311 {
3312 
3313 	if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3314 		vrefact(oldpwd->pwd_cdir);
3315 		newpwd->pwd_cdir = oldpwd->pwd_cdir;
3316 	}
3317 
3318 	if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3319 		vrefact(oldpwd->pwd_rdir);
3320 		newpwd->pwd_rdir = oldpwd->pwd_rdir;
3321 	}
3322 
3323 	if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3324 		vrefact(oldpwd->pwd_jdir);
3325 		newpwd->pwd_jdir = oldpwd->pwd_jdir;
3326 	}
3327 }
3328 
3329 struct pwd *
3330 pwd_hold_filedesc(struct filedesc *fdp)
3331 {
3332 	struct pwd *pwd;
3333 
3334 	FILEDESC_LOCK_ASSERT(fdp);
3335 	pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
3336 	if (pwd != NULL)
3337 		refcount_acquire(&pwd->pwd_refcount);
3338 	return (pwd);
3339 }
3340 
3341 struct pwd *
3342 pwd_hold(struct thread *td)
3343 {
3344 	struct filedesc *fdp;
3345 	struct pwd *pwd;
3346 
3347 	fdp = td->td_proc->p_fd;
3348 
3349 	smr_enter(pwd_smr);
3350 	for (;;) {
3351 		pwd = smr_entered_load(&fdp->fd_pwd, pwd_smr);
3352 		MPASS(pwd != NULL);
3353 		if (refcount_acquire_if_not_zero(&pwd->pwd_refcount))
3354 			break;
3355 	}
3356 	smr_exit(pwd_smr);
3357 	return (pwd);
3358 }
3359 
3360 static struct pwd *
3361 pwd_alloc(void)
3362 {
3363 	struct pwd *pwd;
3364 
3365 	pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3366 	bzero(pwd, sizeof(*pwd));
3367 	refcount_init(&pwd->pwd_refcount, 1);
3368 	return (pwd);
3369 }
3370 
3371 void
3372 pwd_drop(struct pwd *pwd)
3373 {
3374 
3375 	if (!refcount_release(&pwd->pwd_refcount))
3376 		return;
3377 
3378 	if (pwd->pwd_cdir != NULL)
3379 		vrele(pwd->pwd_cdir);
3380 	if (pwd->pwd_rdir != NULL)
3381 		vrele(pwd->pwd_rdir);
3382 	if (pwd->pwd_jdir != NULL)
3383 		vrele(pwd->pwd_jdir);
3384 	uma_zfree_smr(pwd_zone, pwd);
3385 }
3386 
3387 /*
3388 * Common routine for kern_chroot() and jail_attach().  The caller is
3389 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3390 * authorize this operation.
3391 */
3392 int
3393 pwd_chroot(struct thread *td, struct vnode *vp)
3394 {
3395 	struct filedesc *fdp;
3396 	struct pwd *newpwd, *oldpwd;
3397 	int error;
3398 
3399 	fdp = td->td_proc->p_fd;
3400 	newpwd = pwd_alloc();
3401 	FILEDESC_XLOCK(fdp);
3402 	oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3403 	if (chroot_allow_open_directories == 0 ||
3404 	    (chroot_allow_open_directories == 1 &&
3405 	    oldpwd->pwd_rdir != rootvnode)) {
3406 		error = chroot_refuse_vdir_fds(fdp);
3407 		if (error != 0) {
3408 			FILEDESC_XUNLOCK(fdp);
3409 			pwd_drop(newpwd);
3410 			return (error);
3411 		}
3412 	}
3413 
3414 	vrefact(vp);
3415 	newpwd->pwd_rdir = vp;
3416 	if (oldpwd->pwd_jdir == NULL) {
3417 		vrefact(vp);
3418 		newpwd->pwd_jdir = vp;
3419 	}
3420 	pwd_fill(oldpwd, newpwd);
3421 	pwd_set(fdp, newpwd);
3422 	FILEDESC_XUNLOCK(fdp);
3423 	pwd_drop(oldpwd);
3424 	return (0);
3425 }
3426 
3427 void
3428 pwd_chdir(struct thread *td, struct vnode *vp)
3429 {
3430 	struct filedesc *fdp;
3431 	struct pwd *newpwd, *oldpwd;
3432 
3433 	VNPASS(vp->v_usecount > 0, vp);
3434 
3435 	newpwd = pwd_alloc();
3436 	fdp = td->td_proc->p_fd;
3437 	FILEDESC_XLOCK(fdp);
3438 	oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3439 	newpwd->pwd_cdir = vp;
3440 	pwd_fill(oldpwd, newpwd);
3441 	pwd_set(fdp, newpwd);
3442 	FILEDESC_XUNLOCK(fdp);
3443 	pwd_drop(oldpwd);
3444 }
3445 
3446 void
3447 pwd_ensure_dirs(void)
3448 {
3449 	struct filedesc *fdp;
3450 	struct pwd *oldpwd, *newpwd;
3451 
3452 	fdp = curproc->p_fd;
3453 	FILEDESC_XLOCK(fdp);
3454 	oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3455 	if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
3456 		FILEDESC_XUNLOCK(fdp);
3457 		return;
3458 	}
3459 	FILEDESC_XUNLOCK(fdp);
3460 
3461 	newpwd = pwd_alloc();
3462 	FILEDESC_XLOCK(fdp);
3463 	oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3464 	pwd_fill(oldpwd, newpwd);
3465 	if (newpwd->pwd_cdir == NULL) {
3466 		vrefact(rootvnode);
3467 		newpwd->pwd_cdir = rootvnode;
3468 	}
3469 	if (newpwd->pwd_rdir == NULL) {
3470 		vrefact(rootvnode);
3471 		newpwd->pwd_rdir = rootvnode;
3472 	}
3473 	pwd_set(fdp, newpwd);
3474 	FILEDESC_XUNLOCK(fdp);
3475 	pwd_drop(oldpwd);
3476 }
3477 
3478 void
3479 pwd_set_rootvnode(void)
3480 {
3481 	struct filedesc *fdp;
3482 	struct pwd *oldpwd, *newpwd;
3483 
3484 	fdp = curproc->p_fd;
3485 
3486 	newpwd = pwd_alloc();
3487 	FILEDESC_XLOCK(fdp);
3488 	oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3489 	vrefact(rootvnode);
3490 	newpwd->pwd_cdir = rootvnode;
3491 	vrefact(rootvnode);
3492 	newpwd->pwd_rdir = rootvnode;
3493 	pwd_fill(oldpwd, newpwd);
3494 	pwd_set(fdp, newpwd);
3495 	FILEDESC_XUNLOCK(fdp);
3496 	pwd_drop(oldpwd);
3497 }
3498 
3499 /*
3500  * Scan all active processes and prisons to see if any of them have a current
3501  * or root directory of `olddp'. If so, replace them with the new mount point.
3502  */
3503 void
3504 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3505 {
3506 	struct filedesc *fdp;
3507 	struct pwd *newpwd, *oldpwd;
3508 	struct prison *pr;
3509 	struct proc *p;
3510 	int nrele;
3511 
3512 	if (vrefcnt(olddp) == 1)
3513 		return;
3514 	nrele = 0;
3515 	newpwd = pwd_alloc();
3516 	sx_slock(&allproc_lock);
3517 	FOREACH_PROC_IN_SYSTEM(p) {
3518 		PROC_LOCK(p);
3519 		fdp = fdhold(p);
3520 		PROC_UNLOCK(p);
3521 		if (fdp == NULL)
3522 			continue;
3523 		FILEDESC_XLOCK(fdp);
3524 		oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3525 		if (oldpwd == NULL ||
3526 		    (oldpwd->pwd_cdir != olddp &&
3527 		    oldpwd->pwd_rdir != olddp &&
3528 		    oldpwd->pwd_jdir != olddp)) {
3529 			FILEDESC_XUNLOCK(fdp);
3530 			fddrop(fdp);
3531 			continue;
3532 		}
3533 		if (oldpwd->pwd_cdir == olddp) {
3534 			vrefact(newdp);
3535 			newpwd->pwd_cdir = newdp;
3536 		}
3537 		if (oldpwd->pwd_rdir == olddp) {
3538 			vrefact(newdp);
3539 			newpwd->pwd_rdir = newdp;
3540 		}
3541 		if (oldpwd->pwd_jdir == olddp) {
3542 			vrefact(newdp);
3543 			newpwd->pwd_jdir = newdp;
3544 		}
3545 		pwd_fill(oldpwd, newpwd);
3546 		pwd_set(fdp, newpwd);
3547 		FILEDESC_XUNLOCK(fdp);
3548 		pwd_drop(oldpwd);
3549 		fddrop(fdp);
3550 		newpwd = pwd_alloc();
3551 	}
3552 	sx_sunlock(&allproc_lock);
3553 	pwd_drop(newpwd);
3554 	if (rootvnode == olddp) {
3555 		vrefact(newdp);
3556 		rootvnode = newdp;
3557 		nrele++;
3558 	}
3559 	mtx_lock(&prison0.pr_mtx);
3560 	if (prison0.pr_root == olddp) {
3561 		vrefact(newdp);
3562 		prison0.pr_root = newdp;
3563 		nrele++;
3564 	}
3565 	mtx_unlock(&prison0.pr_mtx);
3566 	sx_slock(&allprison_lock);
3567 	TAILQ_FOREACH(pr, &allprison, pr_list) {
3568 		mtx_lock(&pr->pr_mtx);
3569 		if (pr->pr_root == olddp) {
3570 			vrefact(newdp);
3571 			pr->pr_root = newdp;
3572 			nrele++;
3573 		}
3574 		mtx_unlock(&pr->pr_mtx);
3575 	}
3576 	sx_sunlock(&allprison_lock);
3577 	while (nrele--)
3578 		vrele(olddp);
3579 }
3580 
3581 struct filedesc_to_leader *
3582 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3583 {
3584 	struct filedesc_to_leader *fdtol;
3585 
3586 	fdtol = malloc(sizeof(struct filedesc_to_leader),
3587 	    M_FILEDESC_TO_LEADER, M_WAITOK);
3588 	fdtol->fdl_refcount = 1;
3589 	fdtol->fdl_holdcount = 0;
3590 	fdtol->fdl_wakeup = 0;
3591 	fdtol->fdl_leader = leader;
3592 	if (old != NULL) {
3593 		FILEDESC_XLOCK(fdp);
3594 		fdtol->fdl_next = old->fdl_next;
3595 		fdtol->fdl_prev = old;
3596 		old->fdl_next = fdtol;
3597 		fdtol->fdl_next->fdl_prev = fdtol;
3598 		FILEDESC_XUNLOCK(fdp);
3599 	} else {
3600 		fdtol->fdl_next = fdtol;
3601 		fdtol->fdl_prev = fdtol;
3602 	}
3603 	return (fdtol);
3604 }
3605 
3606 static int
3607 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3608 {
3609 	struct filedesc *fdp;
3610 	int i, count, slots;
3611 
3612 	if (*(int *)arg1 != 0)
3613 		return (EINVAL);
3614 
3615 	fdp = curproc->p_fd;
3616 	count = 0;
3617 	FILEDESC_SLOCK(fdp);
3618 	slots = NDSLOTS(fdp->fd_lastfile + 1);
3619 	for (i = 0; i < slots; i++)
3620 		count += bitcountl(fdp->fd_map[i]);
3621 	FILEDESC_SUNLOCK(fdp);
3622 
3623 	return (SYSCTL_OUT(req, &count, sizeof(count)));
3624 }
3625 
3626 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3627     CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3628     "Number of open file descriptors");
3629 
3630 /*
3631  * Get file structures globally.
3632  */
3633 static int
3634 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3635 {
3636 	struct xfile xf;
3637 	struct filedesc *fdp;
3638 	struct file *fp;
3639 	struct proc *p;
3640 	int error, n;
3641 
3642 	error = sysctl_wire_old_buffer(req, 0);
3643 	if (error != 0)
3644 		return (error);
3645 	if (req->oldptr == NULL) {
3646 		n = 0;
3647 		sx_slock(&allproc_lock);
3648 		FOREACH_PROC_IN_SYSTEM(p) {
3649 			PROC_LOCK(p);
3650 			if (p->p_state == PRS_NEW) {
3651 				PROC_UNLOCK(p);
3652 				continue;
3653 			}
3654 			fdp = fdhold(p);
3655 			PROC_UNLOCK(p);
3656 			if (fdp == NULL)
3657 				continue;
3658 			/* overestimates sparse tables. */
3659 			if (fdp->fd_lastfile > 0)
3660 				n += fdp->fd_lastfile;
3661 			fddrop(fdp);
3662 		}
3663 		sx_sunlock(&allproc_lock);
3664 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3665 	}
3666 	error = 0;
3667 	bzero(&xf, sizeof(xf));
3668 	xf.xf_size = sizeof(xf);
3669 	sx_slock(&allproc_lock);
3670 	FOREACH_PROC_IN_SYSTEM(p) {
3671 		PROC_LOCK(p);
3672 		if (p->p_state == PRS_NEW) {
3673 			PROC_UNLOCK(p);
3674 			continue;
3675 		}
3676 		if (p_cansee(req->td, p) != 0) {
3677 			PROC_UNLOCK(p);
3678 			continue;
3679 		}
3680 		xf.xf_pid = p->p_pid;
3681 		xf.xf_uid = p->p_ucred->cr_uid;
3682 		fdp = fdhold(p);
3683 		PROC_UNLOCK(p);
3684 		if (fdp == NULL)
3685 			continue;
3686 		FILEDESC_SLOCK(fdp);
3687 		for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3688 			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3689 				continue;
3690 			xf.xf_fd = n;
3691 			xf.xf_file = (uintptr_t)fp;
3692 			xf.xf_data = (uintptr_t)fp->f_data;
3693 			xf.xf_vnode = (uintptr_t)fp->f_vnode;
3694 			xf.xf_type = (uintptr_t)fp->f_type;
3695 			xf.xf_count = fp->f_count;
3696 			xf.xf_msgcount = 0;
3697 			xf.xf_offset = foffset_get(fp);
3698 			xf.xf_flag = fp->f_flag;
3699 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
3700 			if (error)
3701 				break;
3702 		}
3703 		FILEDESC_SUNLOCK(fdp);
3704 		fddrop(fdp);
3705 		if (error)
3706 			break;
3707 	}
3708 	sx_sunlock(&allproc_lock);
3709 	return (error);
3710 }
3711 
3712 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3713     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3714 
3715 #ifdef KINFO_FILE_SIZE
3716 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3717 #endif
3718 
3719 static int
3720 xlate_fflags(int fflags)
3721 {
3722 	static const struct {
3723 		int	fflag;
3724 		int	kf_fflag;
3725 	} fflags_table[] = {
3726 		{ FAPPEND, KF_FLAG_APPEND },
3727 		{ FASYNC, KF_FLAG_ASYNC },
3728 		{ FFSYNC, KF_FLAG_FSYNC },
3729 		{ FHASLOCK, KF_FLAG_HASLOCK },
3730 		{ FNONBLOCK, KF_FLAG_NONBLOCK },
3731 		{ FREAD, KF_FLAG_READ },
3732 		{ FWRITE, KF_FLAG_WRITE },
3733 		{ O_CREAT, KF_FLAG_CREAT },
3734 		{ O_DIRECT, KF_FLAG_DIRECT },
3735 		{ O_EXCL, KF_FLAG_EXCL },
3736 		{ O_EXEC, KF_FLAG_EXEC },
3737 		{ O_EXLOCK, KF_FLAG_EXLOCK },
3738 		{ O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3739 		{ O_SHLOCK, KF_FLAG_SHLOCK },
3740 		{ O_TRUNC, KF_FLAG_TRUNC }
3741 	};
3742 	unsigned int i;
3743 	int kflags;
3744 
3745 	kflags = 0;
3746 	for (i = 0; i < nitems(fflags_table); i++)
3747 		if (fflags & fflags_table[i].fflag)
3748 			kflags |=  fflags_table[i].kf_fflag;
3749 	return (kflags);
3750 }
3751 
3752 /* Trim unused data from kf_path by truncating the structure size. */
3753 void
3754 pack_kinfo(struct kinfo_file *kif)
3755 {
3756 
3757 	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3758 	    strlen(kif->kf_path) + 1;
3759 	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3760 }
3761 
3762 static void
3763 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3764     struct kinfo_file *kif, struct filedesc *fdp, int flags)
3765 {
3766 	int error;
3767 
3768 	bzero(kif, sizeof(*kif));
3769 
3770 	/* Set a default type to allow for empty fill_kinfo() methods. */
3771 	kif->kf_type = KF_TYPE_UNKNOWN;
3772 	kif->kf_flags = xlate_fflags(fp->f_flag);
3773 	if (rightsp != NULL)
3774 		kif->kf_cap_rights = *rightsp;
3775 	else
3776 		cap_rights_init_zero(&kif->kf_cap_rights);
3777 	kif->kf_fd = fd;
3778 	kif->kf_ref_count = fp->f_count;
3779 	kif->kf_offset = foffset_get(fp);
3780 
3781 	/*
3782 	 * This may drop the filedesc lock, so the 'fp' cannot be
3783 	 * accessed after this call.
3784 	 */
3785 	error = fo_fill_kinfo(fp, kif, fdp);
3786 	if (error == 0)
3787 		kif->kf_status |= KF_ATTR_VALID;
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 }
3793 
3794 static void
3795 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3796     struct kinfo_file *kif, int flags)
3797 {
3798 	int error;
3799 
3800 	bzero(kif, sizeof(*kif));
3801 
3802 	kif->kf_type = KF_TYPE_VNODE;
3803 	error = vn_fill_kinfo_vnode(vp, kif);
3804 	if (error == 0)
3805 		kif->kf_status |= KF_ATTR_VALID;
3806 	kif->kf_flags = xlate_fflags(fflags);
3807 	cap_rights_init_zero(&kif->kf_cap_rights);
3808 	kif->kf_fd = fd;
3809 	kif->kf_ref_count = -1;
3810 	kif->kf_offset = -1;
3811 	if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3812 		pack_kinfo(kif);
3813 	else
3814 		kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3815 	vrele(vp);
3816 }
3817 
3818 struct export_fd_buf {
3819 	struct filedesc		*fdp;
3820 	struct sbuf 		*sb;
3821 	ssize_t			remainder;
3822 	struct kinfo_file	kif;
3823 	int			flags;
3824 };
3825 
3826 static int
3827 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3828 {
3829 	struct kinfo_file *kif;
3830 
3831 	kif = &efbuf->kif;
3832 	if (efbuf->remainder != -1) {
3833 		if (efbuf->remainder < kif->kf_structsize) {
3834 			/* Terminate export. */
3835 			efbuf->remainder = 0;
3836 			return (0);
3837 		}
3838 		efbuf->remainder -= kif->kf_structsize;
3839 	}
3840 	return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3841 }
3842 
3843 static int
3844 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3845     struct export_fd_buf *efbuf)
3846 {
3847 	int error;
3848 
3849 	if (efbuf->remainder == 0)
3850 		return (0);
3851 	export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3852 	    efbuf->flags);
3853 	FILEDESC_SUNLOCK(efbuf->fdp);
3854 	error = export_kinfo_to_sb(efbuf);
3855 	FILEDESC_SLOCK(efbuf->fdp);
3856 	return (error);
3857 }
3858 
3859 static int
3860 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3861     struct export_fd_buf *efbuf)
3862 {
3863 	int error;
3864 
3865 	if (efbuf->remainder == 0)
3866 		return (0);
3867 	if (efbuf->fdp != NULL)
3868 		FILEDESC_SUNLOCK(efbuf->fdp);
3869 	export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3870 	error = export_kinfo_to_sb(efbuf);
3871 	if (efbuf->fdp != NULL)
3872 		FILEDESC_SLOCK(efbuf->fdp);
3873 	return (error);
3874 }
3875 
3876 /*
3877  * Store a process file descriptor information to sbuf.
3878  *
3879  * Takes a locked proc as argument, and returns with the proc unlocked.
3880  */
3881 int
3882 kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen,
3883     int flags)
3884 {
3885 	struct file *fp;
3886 	struct filedesc *fdp;
3887 	struct export_fd_buf *efbuf;
3888 	struct vnode *cttyvp, *textvp, *tracevp;
3889 	struct pwd *pwd;
3890 	int error, i;
3891 	cap_rights_t rights;
3892 
3893 	PROC_LOCK_ASSERT(p, MA_OWNED);
3894 
3895 	/* ktrace vnode */
3896 	tracevp = p->p_tracevp;
3897 	if (tracevp != NULL)
3898 		vrefact(tracevp);
3899 	/* text vnode */
3900 	textvp = p->p_textvp;
3901 	if (textvp != NULL)
3902 		vrefact(textvp);
3903 	/* Controlling tty. */
3904 	cttyvp = NULL;
3905 	if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3906 		cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3907 		if (cttyvp != NULL)
3908 			vrefact(cttyvp);
3909 	}
3910 	fdp = fdhold(p);
3911 	PROC_UNLOCK(p);
3912 	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3913 	efbuf->fdp = NULL;
3914 	efbuf->sb = sb;
3915 	efbuf->remainder = maxlen;
3916 	efbuf->flags = flags;
3917 	if (tracevp != NULL)
3918 		export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3919 		    efbuf);
3920 	if (textvp != NULL)
3921 		export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3922 	if (cttyvp != NULL)
3923 		export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3924 		    efbuf);
3925 	error = 0;
3926 	if (fdp == NULL)
3927 		goto fail;
3928 	efbuf->fdp = fdp;
3929 	FILEDESC_SLOCK(fdp);
3930 	pwd = pwd_hold_filedesc(fdp);
3931 	if (pwd != NULL) {
3932 		/* working directory */
3933 		if (pwd->pwd_cdir != NULL) {
3934 			vrefact(pwd->pwd_cdir);
3935 			export_vnode_to_sb(pwd->pwd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3936 		}
3937 		/* root directory */
3938 		if (pwd->pwd_rdir != NULL) {
3939 			vrefact(pwd->pwd_rdir);
3940 			export_vnode_to_sb(pwd->pwd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3941 		}
3942 		/* jail directory */
3943 		if (pwd->pwd_jdir != NULL) {
3944 			vrefact(pwd->pwd_jdir);
3945 			export_vnode_to_sb(pwd->pwd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3946 		}
3947 		pwd_drop(pwd);
3948 	}
3949 	for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3950 		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3951 			continue;
3952 #ifdef CAPABILITIES
3953 		rights = *cap_rights(fdp, i);
3954 #else /* !CAPABILITIES */
3955 		rights = cap_no_rights;
3956 #endif
3957 		/*
3958 		 * Create sysctl entry.  It is OK to drop the filedesc
3959 		 * lock inside of export_file_to_sb() as we will
3960 		 * re-validate and re-evaluate its properties when the
3961 		 * loop continues.
3962 		 */
3963 		error = export_file_to_sb(fp, i, &rights, efbuf);
3964 		if (error != 0 || efbuf->remainder == 0)
3965 			break;
3966 	}
3967 	FILEDESC_SUNLOCK(fdp);
3968 	fddrop(fdp);
3969 fail:
3970 	free(efbuf, M_TEMP);
3971 	return (error);
3972 }
3973 
3974 #define FILEDESC_SBUF_SIZE	(sizeof(struct kinfo_file) * 5)
3975 
3976 /*
3977  * Get per-process file descriptors for use by procstat(1), et al.
3978  */
3979 static int
3980 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3981 {
3982 	struct sbuf sb;
3983 	struct proc *p;
3984 	ssize_t maxlen;
3985 	int error, error2, *name;
3986 
3987 	name = (int *)arg1;
3988 
3989 	sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3990 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3991 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3992 	if (error != 0) {
3993 		sbuf_delete(&sb);
3994 		return (error);
3995 	}
3996 	maxlen = req->oldptr != NULL ? req->oldlen : -1;
3997 	error = kern_proc_filedesc_out(p, &sb, maxlen,
3998 	    KERN_FILEDESC_PACK_KINFO);
3999 	error2 = sbuf_finish(&sb);
4000 	sbuf_delete(&sb);
4001 	return (error != 0 ? error : error2);
4002 }
4003 
4004 #ifdef COMPAT_FREEBSD7
4005 #ifdef KINFO_OFILE_SIZE
4006 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4007 #endif
4008 
4009 static void
4010 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4011 {
4012 
4013 	okif->kf_structsize = sizeof(*okif);
4014 	okif->kf_type = kif->kf_type;
4015 	okif->kf_fd = kif->kf_fd;
4016 	okif->kf_ref_count = kif->kf_ref_count;
4017 	okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4018 	    KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4019 	    KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4020 	okif->kf_offset = kif->kf_offset;
4021 	if (kif->kf_type == KF_TYPE_VNODE)
4022 		okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4023 	else
4024 		okif->kf_vnode_type = KF_VTYPE_VNON;
4025 	strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4026 	if (kif->kf_type == KF_TYPE_SOCKET) {
4027 		okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4028 		okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4029 		okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4030 		okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4031 		okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4032 	} else {
4033 		okif->kf_sa_local.ss_family = AF_UNSPEC;
4034 		okif->kf_sa_peer.ss_family = AF_UNSPEC;
4035 	}
4036 }
4037 
4038 static int
4039 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4040     struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
4041 {
4042 	int error;
4043 
4044 	vrefact(vp);
4045 	FILEDESC_SUNLOCK(fdp);
4046 	export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4047 	kinfo_to_okinfo(kif, okif);
4048 	error = SYSCTL_OUT(req, okif, sizeof(*okif));
4049 	FILEDESC_SLOCK(fdp);
4050 	return (error);
4051 }
4052 
4053 /*
4054  * Get per-process file descriptors for use by procstat(1), et al.
4055  */
4056 static int
4057 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4058 {
4059 	struct kinfo_ofile *okif;
4060 	struct kinfo_file *kif;
4061 	struct filedesc *fdp;
4062 	struct pwd *pwd;
4063 	int error, i, *name;
4064 	struct file *fp;
4065 	struct proc *p;
4066 
4067 	name = (int *)arg1;
4068 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4069 	if (error != 0)
4070 		return (error);
4071 	fdp = fdhold(p);
4072 	PROC_UNLOCK(p);
4073 	if (fdp == NULL)
4074 		return (ENOENT);
4075 	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4076 	okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4077 	FILEDESC_SLOCK(fdp);
4078 	pwd = pwd_hold_filedesc(fdp);
4079 	if (pwd != NULL) {
4080 		if (pwd->pwd_cdir != NULL)
4081 			export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4082 			    okif, fdp, req);
4083 		if (pwd->pwd_rdir != NULL)
4084 			export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4085 			    okif, fdp, req);
4086 		if (pwd->pwd_jdir != NULL)
4087 			export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4088 			    okif, fdp, req);
4089 		pwd_drop(pwd);
4090 	}
4091 	for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
4092 		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4093 			continue;
4094 		export_file_to_kinfo(fp, i, NULL, kif, fdp,
4095 		    KERN_FILEDESC_PACK_KINFO);
4096 		FILEDESC_SUNLOCK(fdp);
4097 		kinfo_to_okinfo(kif, okif);
4098 		error = SYSCTL_OUT(req, okif, sizeof(*okif));
4099 		FILEDESC_SLOCK(fdp);
4100 		if (error)
4101 			break;
4102 	}
4103 	FILEDESC_SUNLOCK(fdp);
4104 	fddrop(fdp);
4105 	free(kif, M_TEMP);
4106 	free(okif, M_TEMP);
4107 	return (0);
4108 }
4109 
4110 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4111     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4112     "Process ofiledesc entries");
4113 #endif	/* COMPAT_FREEBSD7 */
4114 
4115 int
4116 vntype_to_kinfo(int vtype)
4117 {
4118 	struct {
4119 		int	vtype;
4120 		int	kf_vtype;
4121 	} vtypes_table[] = {
4122 		{ VBAD, KF_VTYPE_VBAD },
4123 		{ VBLK, KF_VTYPE_VBLK },
4124 		{ VCHR, KF_VTYPE_VCHR },
4125 		{ VDIR, KF_VTYPE_VDIR },
4126 		{ VFIFO, KF_VTYPE_VFIFO },
4127 		{ VLNK, KF_VTYPE_VLNK },
4128 		{ VNON, KF_VTYPE_VNON },
4129 		{ VREG, KF_VTYPE_VREG },
4130 		{ VSOCK, KF_VTYPE_VSOCK }
4131 	};
4132 	unsigned int i;
4133 
4134 	/*
4135 	 * Perform vtype translation.
4136 	 */
4137 	for (i = 0; i < nitems(vtypes_table); i++)
4138 		if (vtypes_table[i].vtype == vtype)
4139 			return (vtypes_table[i].kf_vtype);
4140 
4141 	return (KF_VTYPE_UNKNOWN);
4142 }
4143 
4144 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4145     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4146     "Process filedesc entries");
4147 
4148 /*
4149  * Store a process current working directory information to sbuf.
4150  *
4151  * Takes a locked proc as argument, and returns with the proc unlocked.
4152  */
4153 int
4154 kern_proc_cwd_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
4155 {
4156 	struct filedesc *fdp;
4157 	struct pwd *pwd;
4158 	struct export_fd_buf *efbuf;
4159 	struct vnode *cdir;
4160 	int error;
4161 
4162 	PROC_LOCK_ASSERT(p, MA_OWNED);
4163 
4164 	fdp = fdhold(p);
4165 	PROC_UNLOCK(p);
4166 	if (fdp == NULL)
4167 		return (EINVAL);
4168 
4169 	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4170 	efbuf->fdp = fdp;
4171 	efbuf->sb = sb;
4172 	efbuf->remainder = maxlen;
4173 
4174 	FILEDESC_SLOCK(fdp);
4175 	pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
4176 	cdir = pwd->pwd_cdir;
4177 	if (cdir == NULL) {
4178 		error = EINVAL;
4179 	} else {
4180 		vrefact(cdir);
4181 		error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4182 	}
4183 	FILEDESC_SUNLOCK(fdp);
4184 	fddrop(fdp);
4185 	free(efbuf, M_TEMP);
4186 	return (error);
4187 }
4188 
4189 /*
4190  * Get per-process current working directory.
4191  */
4192 static int
4193 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4194 {
4195 	struct sbuf sb;
4196 	struct proc *p;
4197 	ssize_t maxlen;
4198 	int error, error2, *name;
4199 
4200 	name = (int *)arg1;
4201 
4202 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4203 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4204 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4205 	if (error != 0) {
4206 		sbuf_delete(&sb);
4207 		return (error);
4208 	}
4209 	maxlen = req->oldptr != NULL ? req->oldlen : -1;
4210 	error = kern_proc_cwd_out(p, &sb, maxlen);
4211 	error2 = sbuf_finish(&sb);
4212 	sbuf_delete(&sb);
4213 	return (error != 0 ? error : error2);
4214 }
4215 
4216 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4217     sysctl_kern_proc_cwd, "Process current working directory");
4218 
4219 #ifdef DDB
4220 /*
4221  * For the purposes of debugging, generate a human-readable string for the
4222  * file type.
4223  */
4224 static const char *
4225 file_type_to_name(short type)
4226 {
4227 
4228 	switch (type) {
4229 	case 0:
4230 		return ("zero");
4231 	case DTYPE_VNODE:
4232 		return ("vnode");
4233 	case DTYPE_SOCKET:
4234 		return ("socket");
4235 	case DTYPE_PIPE:
4236 		return ("pipe");
4237 	case DTYPE_FIFO:
4238 		return ("fifo");
4239 	case DTYPE_KQUEUE:
4240 		return ("kqueue");
4241 	case DTYPE_CRYPTO:
4242 		return ("crypto");
4243 	case DTYPE_MQUEUE:
4244 		return ("mqueue");
4245 	case DTYPE_SHM:
4246 		return ("shm");
4247 	case DTYPE_SEM:
4248 		return ("ksem");
4249 	case DTYPE_PTS:
4250 		return ("pts");
4251 	case DTYPE_DEV:
4252 		return ("dev");
4253 	case DTYPE_PROCDESC:
4254 		return ("proc");
4255 	case DTYPE_LINUXEFD:
4256 		return ("levent");
4257 	case DTYPE_LINUXTFD:
4258 		return ("ltimer");
4259 	default:
4260 		return ("unkn");
4261 	}
4262 }
4263 
4264 /*
4265  * For the purposes of debugging, identify a process (if any, perhaps one of
4266  * many) that references the passed file in its file descriptor array. Return
4267  * NULL if none.
4268  */
4269 static struct proc *
4270 file_to_first_proc(struct file *fp)
4271 {
4272 	struct filedesc *fdp;
4273 	struct proc *p;
4274 	int n;
4275 
4276 	FOREACH_PROC_IN_SYSTEM(p) {
4277 		if (p->p_state == PRS_NEW)
4278 			continue;
4279 		fdp = p->p_fd;
4280 		if (fdp == NULL)
4281 			continue;
4282 		for (n = 0; n <= fdp->fd_lastfile; n++) {
4283 			if (fp == fdp->fd_ofiles[n].fde_file)
4284 				return (p);
4285 		}
4286 	}
4287 	return (NULL);
4288 }
4289 
4290 static void
4291 db_print_file(struct file *fp, int header)
4292 {
4293 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
4294 	struct proc *p;
4295 
4296 	if (header)
4297 		db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
4298 		    XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
4299 		    "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
4300 		    "FCmd");
4301 	p = file_to_first_proc(fp);
4302 	db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
4303 	    fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
4304 	    fp->f_flag, 0, fp->f_count, 0, XPTRWIDTH, fp->f_vnode,
4305 	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
4306 
4307 #undef XPTRWIDTH
4308 }
4309 
4310 DB_SHOW_COMMAND(file, db_show_file)
4311 {
4312 	struct file *fp;
4313 
4314 	if (!have_addr) {
4315 		db_printf("usage: show file <addr>\n");
4316 		return;
4317 	}
4318 	fp = (struct file *)addr;
4319 	db_print_file(fp, 1);
4320 }
4321 
4322 DB_SHOW_COMMAND(files, db_show_files)
4323 {
4324 	struct filedesc *fdp;
4325 	struct file *fp;
4326 	struct proc *p;
4327 	int header;
4328 	int n;
4329 
4330 	header = 1;
4331 	FOREACH_PROC_IN_SYSTEM(p) {
4332 		if (p->p_state == PRS_NEW)
4333 			continue;
4334 		if ((fdp = p->p_fd) == NULL)
4335 			continue;
4336 		for (n = 0; n <= fdp->fd_lastfile; ++n) {
4337 			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4338 				continue;
4339 			db_print_file(fp, header);
4340 			header = 0;
4341 		}
4342 	}
4343 }
4344 #endif
4345 
4346 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
4347     &maxfilesperproc, 0, "Maximum files allowed open per process");
4348 
4349 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
4350     &maxfiles, 0, "Maximum number of files");
4351 
4352 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
4353     &openfiles, 0, "System-wide number of open files");
4354 
4355 /* ARGSUSED*/
4356 static void
4357 filelistinit(void *dummy)
4358 {
4359 
4360 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
4361 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
4362 	filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
4363 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4364 	pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
4365 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
4366 	pwd_smr = uma_zone_get_smr(pwd_zone);
4367 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
4368 }
4369 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
4370 
4371 /*-------------------------------------------------------------------*/
4372 
4373 static int
4374 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
4375     int flags, struct thread *td)
4376 {
4377 
4378 	return (EBADF);
4379 }
4380 
4381 static int
4382 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4383     struct thread *td)
4384 {
4385 
4386 	return (EINVAL);
4387 }
4388 
4389 static int
4390 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
4391     struct thread *td)
4392 {
4393 
4394 	return (EBADF);
4395 }
4396 
4397 static int
4398 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4399     struct thread *td)
4400 {
4401 
4402 	return (0);
4403 }
4404 
4405 static int
4406 badfo_kqfilter(struct file *fp, struct knote *kn)
4407 {
4408 
4409 	return (EBADF);
4410 }
4411 
4412 static int
4413 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4414     struct thread *td)
4415 {
4416 
4417 	return (EBADF);
4418 }
4419 
4420 static int
4421 badfo_close(struct file *fp, struct thread *td)
4422 {
4423 
4424 	return (0);
4425 }
4426 
4427 static int
4428 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4429     struct thread *td)
4430 {
4431 
4432 	return (EBADF);
4433 }
4434 
4435 static int
4436 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4437     struct thread *td)
4438 {
4439 
4440 	return (EBADF);
4441 }
4442 
4443 static int
4444 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4445     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4446     struct thread *td)
4447 {
4448 
4449 	return (EBADF);
4450 }
4451 
4452 static int
4453 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4454 {
4455 
4456 	return (0);
4457 }
4458 
4459 struct fileops badfileops = {
4460 	.fo_read = badfo_readwrite,
4461 	.fo_write = badfo_readwrite,
4462 	.fo_truncate = badfo_truncate,
4463 	.fo_ioctl = badfo_ioctl,
4464 	.fo_poll = badfo_poll,
4465 	.fo_kqfilter = badfo_kqfilter,
4466 	.fo_stat = badfo_stat,
4467 	.fo_close = badfo_close,
4468 	.fo_chmod = badfo_chmod,
4469 	.fo_chown = badfo_chown,
4470 	.fo_sendfile = badfo_sendfile,
4471 	.fo_fill_kinfo = badfo_fill_kinfo,
4472 };
4473 
4474 int
4475 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4476     int flags, struct thread *td)
4477 {
4478 
4479 	return (EOPNOTSUPP);
4480 }
4481 
4482 int
4483 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4484     struct thread *td)
4485 {
4486 
4487 	return (EINVAL);
4488 }
4489 
4490 int
4491 invfo_ioctl(struct file *fp, u_long com, void *data,
4492     struct ucred *active_cred, struct thread *td)
4493 {
4494 
4495 	return (ENOTTY);
4496 }
4497 
4498 int
4499 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4500     struct thread *td)
4501 {
4502 
4503 	return (poll_no_poll(events));
4504 }
4505 
4506 int
4507 invfo_kqfilter(struct file *fp, struct knote *kn)
4508 {
4509 
4510 	return (EINVAL);
4511 }
4512 
4513 int
4514 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4515     struct thread *td)
4516 {
4517 
4518 	return (EINVAL);
4519 }
4520 
4521 int
4522 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4523     struct thread *td)
4524 {
4525 
4526 	return (EINVAL);
4527 }
4528 
4529 int
4530 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4531     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4532     struct thread *td)
4533 {
4534 
4535 	return (EINVAL);
4536 }
4537 
4538 /*-------------------------------------------------------------------*/
4539 
4540 /*
4541  * File Descriptor pseudo-device driver (/dev/fd/).
4542  *
4543  * Opening minor device N dup()s the file (if any) connected to file
4544  * descriptor N belonging to the calling process.  Note that this driver
4545  * consists of only the ``open()'' routine, because all subsequent
4546  * references to this file will be direct to the other driver.
4547  *
4548  * XXX: we could give this one a cloning event handler if necessary.
4549  */
4550 
4551 /* ARGSUSED */
4552 static int
4553 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4554 {
4555 
4556 	/*
4557 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4558 	 * the file descriptor being sought for duplication. The error
4559 	 * return ensures that the vnode for this device will be released
4560 	 * by vn_open. Open will detect this special error and take the
4561 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4562 	 * will simply report the error.
4563 	 */
4564 	td->td_dupfd = dev2unit(dev);
4565 	return (ENODEV);
4566 }
4567 
4568 static struct cdevsw fildesc_cdevsw = {
4569 	.d_version =	D_VERSION,
4570 	.d_open =	fdopen,
4571 	.d_name =	"FD",
4572 };
4573 
4574 static void
4575 fildesc_drvinit(void *unused)
4576 {
4577 	struct cdev *dev;
4578 
4579 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4580 	    UID_ROOT, GID_WHEEL, 0666, "fd/0");
4581 	make_dev_alias(dev, "stdin");
4582 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4583 	    UID_ROOT, GID_WHEEL, 0666, "fd/1");
4584 	make_dev_alias(dev, "stdout");
4585 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4586 	    UID_ROOT, GID_WHEEL, 0666, "fd/2");
4587 	make_dev_alias(dev, "stderr");
4588 }
4589 
4590 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
4591