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