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