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