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