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