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