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