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