xref: /freebsd/sys/kern/kern_descrip.c (revision 195ebc7e9e4b129de810833791a19dfb4349d6a9)
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_compat.h"
41 #include "opt_ddb.h"
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 
47 #include <sys/conf.h>
48 #include <sys/domain.h>
49 #include <sys/fcntl.h>
50 #include <sys/file.h>
51 #include <sys/filedesc.h>
52 #include <sys/filio.h>
53 #include <sys/jail.h>
54 #include <sys/kernel.h>
55 #include <sys/limits.h>
56 #include <sys/lock.h>
57 #include <sys/malloc.h>
58 #include <sys/mount.h>
59 #include <sys/mqueue.h>
60 #include <sys/mutex.h>
61 #include <sys/namei.h>
62 #include <sys/priv.h>
63 #include <sys/proc.h>
64 #include <sys/protosw.h>
65 #include <sys/resourcevar.h>
66 #include <sys/signalvar.h>
67 #include <sys/socketvar.h>
68 #include <sys/stat.h>
69 #include <sys/sx.h>
70 #include <sys/syscallsubr.h>
71 #include <sys/sysctl.h>
72 #include <sys/sysproto.h>
73 #include <sys/tty.h>
74 #include <sys/unistd.h>
75 #include <sys/user.h>
76 #include <sys/vnode.h>
77 #ifdef KTRACE
78 #include <sys/ktrace.h>
79 #endif
80 
81 #include <security/audit/audit.h>
82 
83 #include <vm/uma.h>
84 
85 #include <ddb/ddb.h>
86 
87 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
88 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
89 		     "file desc to leader structures");
90 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
91 
92 static uma_zone_t file_zone;
93 
94 
95 /* Flags for do_dup() */
96 #define DUP_FIXED	0x1	/* Force fixed allocation */
97 #define DUP_FCNTL	0x2	/* fcntl()-style errors */
98 
99 static int do_dup(struct thread *td, int flags, int old, int new,
100     register_t *retval);
101 static int	fd_first_free(struct filedesc *, int, int);
102 static int	fd_last_used(struct filedesc *, int, int);
103 static void	fdgrowtable(struct filedesc *, int);
104 static void	fdunused(struct filedesc *fdp, int fd);
105 static void	fdused(struct filedesc *fdp, int fd);
106 
107 /*
108  * A process is initially started out with NDFILE descriptors stored within
109  * this structure, selected to be enough for typical applications based on
110  * the historical limit of 20 open files (and the usage of descriptors by
111  * shells).  If these descriptors are exhausted, a larger descriptor table
112  * may be allocated, up to a process' resource limit; the internal arrays
113  * are then unused.
114  */
115 #define NDFILE		20
116 #define NDSLOTSIZE	sizeof(NDSLOTTYPE)
117 #define	NDENTRIES	(NDSLOTSIZE * __CHAR_BIT)
118 #define NDSLOT(x)	((x) / NDENTRIES)
119 #define NDBIT(x)	((NDSLOTTYPE)1 << ((x) % NDENTRIES))
120 #define	NDSLOTS(x)	(((x) + NDENTRIES - 1) / NDENTRIES)
121 
122 /*
123  * Storage required per open file descriptor.
124  */
125 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
126 
127 /*
128  * Storage to hold unused ofiles that need to be reclaimed.
129  */
130 struct freetable {
131 	struct file	**ft_table;
132 	SLIST_ENTRY(freetable) ft_next;
133 };
134 
135 /*
136  * Basic allocation of descriptors:
137  * one of the above, plus arrays for NDFILE descriptors.
138  */
139 struct filedesc0 {
140 	struct	filedesc fd_fd;
141 	/*
142 	 * ofiles which need to be reclaimed on free.
143 	 */
144 	SLIST_HEAD(,freetable) fd_free;
145 	/*
146 	 * These arrays are used when the number of open files is
147 	 * <= NDFILE, and are then pointed to by the pointers above.
148 	 */
149 	struct	file *fd_dfiles[NDFILE];
150 	char	fd_dfileflags[NDFILE];
151 	NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
152 };
153 
154 /*
155  * Descriptor management.
156  */
157 volatile int openfiles;			/* actual number of open files */
158 struct mtx sigio_lock;		/* mtx to protect pointers to sigio */
159 void	(*mq_fdclose)(struct thread *td, int fd, struct file *fp);
160 
161 /* A mutex to protect the association between a proc and filedesc. */
162 static struct mtx	fdesc_mtx;
163 
164 /*
165  * Find the first zero bit in the given bitmap, starting at low and not
166  * exceeding size - 1.
167  */
168 static int
169 fd_first_free(struct filedesc *fdp, int low, int size)
170 {
171 	NDSLOTTYPE *map = fdp->fd_map;
172 	NDSLOTTYPE mask;
173 	int off, maxoff;
174 
175 	if (low >= size)
176 		return (low);
177 
178 	off = NDSLOT(low);
179 	if (low % NDENTRIES) {
180 		mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
181 		if ((mask &= ~map[off]) != 0UL)
182 			return (off * NDENTRIES + ffsl(mask) - 1);
183 		++off;
184 	}
185 	for (maxoff = NDSLOTS(size); off < maxoff; ++off)
186 		if (map[off] != ~0UL)
187 			return (off * NDENTRIES + ffsl(~map[off]) - 1);
188 	return (size);
189 }
190 
191 /*
192  * Find the highest non-zero bit in the given bitmap, starting at low and
193  * not exceeding size - 1.
194  */
195 static int
196 fd_last_used(struct filedesc *fdp, int low, int size)
197 {
198 	NDSLOTTYPE *map = fdp->fd_map;
199 	NDSLOTTYPE mask;
200 	int off, minoff;
201 
202 	if (low >= size)
203 		return (-1);
204 
205 	off = NDSLOT(size);
206 	if (size % NDENTRIES) {
207 		mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
208 		if ((mask &= map[off]) != 0)
209 			return (off * NDENTRIES + flsl(mask) - 1);
210 		--off;
211 	}
212 	for (minoff = NDSLOT(low); off >= minoff; --off)
213 		if (map[off] != 0)
214 			return (off * NDENTRIES + flsl(map[off]) - 1);
215 	return (low - 1);
216 }
217 
218 static int
219 fdisused(struct filedesc *fdp, int fd)
220 {
221         KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
222             ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
223 	return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
224 }
225 
226 /*
227  * Mark a file descriptor as used.
228  */
229 static void
230 fdused(struct filedesc *fdp, int fd)
231 {
232 
233 	FILEDESC_XLOCK_ASSERT(fdp);
234 	KASSERT(!fdisused(fdp, fd),
235 	    ("fd already used"));
236 
237 	fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
238 	if (fd > fdp->fd_lastfile)
239 		fdp->fd_lastfile = fd;
240 	if (fd == fdp->fd_freefile)
241 		fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
242 }
243 
244 /*
245  * Mark a file descriptor as unused.
246  */
247 static void
248 fdunused(struct filedesc *fdp, int fd)
249 {
250 
251 	FILEDESC_XLOCK_ASSERT(fdp);
252 	KASSERT(fdisused(fdp, fd),
253 	    ("fd is already unused"));
254 	KASSERT(fdp->fd_ofiles[fd] == NULL,
255 	    ("fd is still in use"));
256 
257 	fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
258 	if (fd < fdp->fd_freefile)
259 		fdp->fd_freefile = fd;
260 	if (fd == fdp->fd_lastfile)
261 		fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
262 }
263 
264 /*
265  * System calls on descriptors.
266  */
267 #ifndef _SYS_SYSPROTO_H_
268 struct getdtablesize_args {
269 	int	dummy;
270 };
271 #endif
272 /* ARGSUSED */
273 int
274 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
275 {
276 	struct proc *p = td->td_proc;
277 
278 	PROC_LOCK(p);
279 	td->td_retval[0] =
280 	    min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
281 	PROC_UNLOCK(p);
282 	return (0);
283 }
284 
285 /*
286  * Duplicate a file descriptor to a particular value.
287  *
288  * Note: keep in mind that a potential race condition exists when closing
289  * descriptors from a shared descriptor table (via rfork).
290  */
291 #ifndef _SYS_SYSPROTO_H_
292 struct dup2_args {
293 	u_int	from;
294 	u_int	to;
295 };
296 #endif
297 /* ARGSUSED */
298 int
299 dup2(struct thread *td, struct dup2_args *uap)
300 {
301 
302 	return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
303 		    td->td_retval));
304 }
305 
306 /*
307  * Duplicate a file descriptor.
308  */
309 #ifndef _SYS_SYSPROTO_H_
310 struct dup_args {
311 	u_int	fd;
312 };
313 #endif
314 /* ARGSUSED */
315 int
316 dup(struct thread *td, struct dup_args *uap)
317 {
318 
319 	return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
320 }
321 
322 /*
323  * The file control system call.
324  */
325 #ifndef _SYS_SYSPROTO_H_
326 struct fcntl_args {
327 	int	fd;
328 	int	cmd;
329 	long	arg;
330 };
331 #endif
332 /* ARGSUSED */
333 int
334 fcntl(struct thread *td, struct fcntl_args *uap)
335 {
336 	struct flock fl;
337 	struct oflock ofl;
338 	intptr_t arg;
339 	int error;
340 	int cmd;
341 
342 	error = 0;
343 	cmd = uap->cmd;
344 	switch (uap->cmd) {
345 	case F_OGETLK:
346 	case F_OSETLK:
347 	case F_OSETLKW:
348 		/*
349 		 * Convert old flock structure to new.
350 		 */
351 		error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
352 		fl.l_start = ofl.l_start;
353 		fl.l_len = ofl.l_len;
354 		fl.l_pid = ofl.l_pid;
355 		fl.l_type = ofl.l_type;
356 		fl.l_whence = ofl.l_whence;
357 		fl.l_sysid = 0;
358 
359 		switch (uap->cmd) {
360 		case F_OGETLK:
361 		    cmd = F_GETLK;
362 		    break;
363 		case F_OSETLK:
364 		    cmd = F_SETLK;
365 		    break;
366 		case F_OSETLKW:
367 		    cmd = F_SETLKW;
368 		    break;
369 		}
370 		arg = (intptr_t)&fl;
371 		break;
372         case F_GETLK:
373         case F_SETLK:
374         case F_SETLKW:
375 	case F_SETLK_REMOTE:
376                 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
377                 arg = (intptr_t)&fl;
378                 break;
379 	default:
380 		arg = uap->arg;
381 		break;
382 	}
383 	if (error)
384 		return (error);
385 	error = kern_fcntl(td, uap->fd, cmd, arg);
386 	if (error)
387 		return (error);
388 	if (uap->cmd == F_OGETLK) {
389 		ofl.l_start = fl.l_start;
390 		ofl.l_len = fl.l_len;
391 		ofl.l_pid = fl.l_pid;
392 		ofl.l_type = fl.l_type;
393 		ofl.l_whence = fl.l_whence;
394 		error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
395 	} else if (uap->cmd == F_GETLK) {
396 		error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
397 	}
398 	return (error);
399 }
400 
401 static inline struct file *
402 fdtofp(int fd, struct filedesc *fdp)
403 {
404 	struct file *fp;
405 
406 	FILEDESC_LOCK_ASSERT(fdp);
407 	if ((unsigned)fd >= fdp->fd_nfiles ||
408 	    (fp = fdp->fd_ofiles[fd]) == NULL)
409 		return (NULL);
410 	return (fp);
411 }
412 
413 int
414 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
415 {
416 	struct filedesc *fdp;
417 	struct flock *flp;
418 	struct file *fp;
419 	struct proc *p;
420 	char *pop;
421 	struct vnode *vp;
422 	int error, flg, tmp;
423 	int vfslocked;
424 
425 	vfslocked = 0;
426 	error = 0;
427 	flg = F_POSIX;
428 	p = td->td_proc;
429 	fdp = p->p_fd;
430 
431 	switch (cmd) {
432 	case F_DUPFD:
433 		tmp = arg;
434 		error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
435 		break;
436 
437 	case F_DUP2FD:
438 		tmp = arg;
439 		error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
440 		break;
441 
442 	case F_GETFD:
443 		FILEDESC_SLOCK(fdp);
444 		if ((fp = fdtofp(fd, fdp)) == NULL) {
445 			FILEDESC_SUNLOCK(fdp);
446 			error = EBADF;
447 			break;
448 		}
449 		pop = &fdp->fd_ofileflags[fd];
450 		td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
451 		FILEDESC_SUNLOCK(fdp);
452 		break;
453 
454 	case F_SETFD:
455 		FILEDESC_XLOCK(fdp);
456 		if ((fp = fdtofp(fd, fdp)) == NULL) {
457 			FILEDESC_XUNLOCK(fdp);
458 			error = EBADF;
459 			break;
460 		}
461 		pop = &fdp->fd_ofileflags[fd];
462 		*pop = (*pop &~ UF_EXCLOSE) |
463 		    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
464 		FILEDESC_XUNLOCK(fdp);
465 		break;
466 
467 	case F_GETFL:
468 		FILEDESC_SLOCK(fdp);
469 		if ((fp = fdtofp(fd, fdp)) == NULL) {
470 			FILEDESC_SUNLOCK(fdp);
471 			error = EBADF;
472 			break;
473 		}
474 		td->td_retval[0] = OFLAGS(fp->f_flag);
475 		FILEDESC_SUNLOCK(fdp);
476 		break;
477 
478 	case F_SETFL:
479 		FILEDESC_SLOCK(fdp);
480 		if ((fp = fdtofp(fd, fdp)) == NULL) {
481 			FILEDESC_SUNLOCK(fdp);
482 			error = EBADF;
483 			break;
484 		}
485 		fhold(fp);
486 		FILEDESC_SUNLOCK(fdp);
487 		do {
488 			tmp = flg = fp->f_flag;
489 			tmp &= ~FCNTLFLAGS;
490 			tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
491 		} while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
492 		tmp = fp->f_flag & FNONBLOCK;
493 		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
494 		if (error) {
495 			fdrop(fp, td);
496 			break;
497 		}
498 		tmp = fp->f_flag & FASYNC;
499 		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
500 		if (error == 0) {
501 			fdrop(fp, td);
502 			break;
503 		}
504 		atomic_clear_int(&fp->f_flag, FNONBLOCK);
505 		tmp = 0;
506 		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
507 		fdrop(fp, td);
508 		break;
509 
510 	case F_GETOWN:
511 		FILEDESC_SLOCK(fdp);
512 		if ((fp = fdtofp(fd, fdp)) == NULL) {
513 			FILEDESC_SUNLOCK(fdp);
514 			error = EBADF;
515 			break;
516 		}
517 		fhold(fp);
518 		FILEDESC_SUNLOCK(fdp);
519 		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
520 		if (error == 0)
521 			td->td_retval[0] = tmp;
522 		fdrop(fp, td);
523 		break;
524 
525 	case F_SETOWN:
526 		FILEDESC_SLOCK(fdp);
527 		if ((fp = fdtofp(fd, fdp)) == NULL) {
528 			FILEDESC_SUNLOCK(fdp);
529 			error = EBADF;
530 			break;
531 		}
532 		fhold(fp);
533 		FILEDESC_SUNLOCK(fdp);
534 		tmp = arg;
535 		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
536 		fdrop(fp, td);
537 		break;
538 
539 	case F_SETLK_REMOTE:
540 		error = priv_check(td, PRIV_NFS_LOCKD);
541 		if (error)
542 			return (error);
543 		flg = F_REMOTE;
544 		goto do_setlk;
545 
546 	case F_SETLKW:
547 		flg |= F_WAIT;
548 		/* FALLTHROUGH F_SETLK */
549 
550 	case F_SETLK:
551 	do_setlk:
552 		FILEDESC_SLOCK(fdp);
553 		if ((fp = fdtofp(fd, fdp)) == NULL) {
554 			FILEDESC_SUNLOCK(fdp);
555 			error = EBADF;
556 			break;
557 		}
558 		if (fp->f_type != DTYPE_VNODE) {
559 			FILEDESC_SUNLOCK(fdp);
560 			error = EBADF;
561 			break;
562 		}
563 		flp = (struct flock *)arg;
564 		if (flp->l_whence == SEEK_CUR) {
565 			if (fp->f_offset < 0 ||
566 			    (flp->l_start > 0 &&
567 			     fp->f_offset > OFF_MAX - flp->l_start)) {
568 				FILEDESC_SUNLOCK(fdp);
569 				error = EOVERFLOW;
570 				break;
571 			}
572 			flp->l_start += fp->f_offset;
573 		}
574 
575 		/*
576 		 * VOP_ADVLOCK() may block.
577 		 */
578 		fhold(fp);
579 		FILEDESC_SUNLOCK(fdp);
580 		vp = fp->f_vnode;
581 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
582 		switch (flp->l_type) {
583 		case F_RDLCK:
584 			if ((fp->f_flag & FREAD) == 0) {
585 				error = EBADF;
586 				break;
587 			}
588 			PROC_LOCK(p->p_leader);
589 			p->p_leader->p_flag |= P_ADVLOCK;
590 			PROC_UNLOCK(p->p_leader);
591 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
592 			    flp, flg);
593 			break;
594 		case F_WRLCK:
595 			if ((fp->f_flag & FWRITE) == 0) {
596 				error = EBADF;
597 				break;
598 			}
599 			PROC_LOCK(p->p_leader);
600 			p->p_leader->p_flag |= P_ADVLOCK;
601 			PROC_UNLOCK(p->p_leader);
602 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
603 			    flp, flg);
604 			break;
605 		case F_UNLCK:
606 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
607 			    flp, flg);
608 			break;
609 		case F_UNLCKSYS:
610 			/*
611 			 * Temporary api for testing remote lock
612 			 * infrastructure.
613 			 */
614 			if (flg != F_REMOTE) {
615 				error = EINVAL;
616 				break;
617 			}
618 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
619 			    F_UNLCKSYS, flp, flg);
620 			break;
621 		default:
622 			error = EINVAL;
623 			break;
624 		}
625 		VFS_UNLOCK_GIANT(vfslocked);
626 		vfslocked = 0;
627 		/* Check for race with close */
628 		FILEDESC_SLOCK(fdp);
629 		if ((unsigned) fd >= fdp->fd_nfiles ||
630 		    fp != fdp->fd_ofiles[fd]) {
631 			FILEDESC_SUNLOCK(fdp);
632 			flp->l_whence = SEEK_SET;
633 			flp->l_start = 0;
634 			flp->l_len = 0;
635 			flp->l_type = F_UNLCK;
636 			vfslocked = VFS_LOCK_GIANT(vp->v_mount);
637 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
638 					   F_UNLCK, flp, F_POSIX);
639 			VFS_UNLOCK_GIANT(vfslocked);
640 			vfslocked = 0;
641 		} else
642 			FILEDESC_SUNLOCK(fdp);
643 		fdrop(fp, td);
644 		break;
645 
646 	case F_GETLK:
647 		FILEDESC_SLOCK(fdp);
648 		if ((fp = fdtofp(fd, fdp)) == NULL) {
649 			FILEDESC_SUNLOCK(fdp);
650 			error = EBADF;
651 			break;
652 		}
653 		if (fp->f_type != DTYPE_VNODE) {
654 			FILEDESC_SUNLOCK(fdp);
655 			error = EBADF;
656 			break;
657 		}
658 		flp = (struct flock *)arg;
659 		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
660 		    flp->l_type != F_UNLCK) {
661 			FILEDESC_SUNLOCK(fdp);
662 			error = EINVAL;
663 			break;
664 		}
665 		if (flp->l_whence == SEEK_CUR) {
666 			if ((flp->l_start > 0 &&
667 			    fp->f_offset > OFF_MAX - flp->l_start) ||
668 			    (flp->l_start < 0 &&
669 			     fp->f_offset < OFF_MIN - flp->l_start)) {
670 				FILEDESC_SUNLOCK(fdp);
671 				error = EOVERFLOW;
672 				break;
673 			}
674 			flp->l_start += fp->f_offset;
675 		}
676 		/*
677 		 * VOP_ADVLOCK() may block.
678 		 */
679 		fhold(fp);
680 		FILEDESC_SUNLOCK(fdp);
681 		vp = fp->f_vnode;
682 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
683 		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
684 		    F_POSIX);
685 		VFS_UNLOCK_GIANT(vfslocked);
686 		vfslocked = 0;
687 		fdrop(fp, td);
688 		break;
689 	default:
690 		error = EINVAL;
691 		break;
692 	}
693 	VFS_UNLOCK_GIANT(vfslocked);
694 	return (error);
695 }
696 
697 /*
698  * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
699  */
700 static int
701 do_dup(struct thread *td, int flags, int old, int new,
702     register_t *retval)
703 {
704 	struct filedesc *fdp;
705 	struct proc *p;
706 	struct file *fp;
707 	struct file *delfp;
708 	int error, holdleaders, maxfd;
709 
710 	p = td->td_proc;
711 	fdp = p->p_fd;
712 
713 	/*
714 	 * Verify we have a valid descriptor to dup from and possibly to
715 	 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
716 	 * return EINVAL when the new descriptor is out of bounds.
717 	 */
718 	if (old < 0)
719 		return (EBADF);
720 	if (new < 0)
721 		return (flags & DUP_FCNTL ? EINVAL : EBADF);
722 	PROC_LOCK(p);
723 	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
724 	PROC_UNLOCK(p);
725 	if (new >= maxfd)
726 		return (flags & DUP_FCNTL ? EINVAL : EMFILE);
727 
728 	FILEDESC_XLOCK(fdp);
729 	if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
730 		FILEDESC_XUNLOCK(fdp);
731 		return (EBADF);
732 	}
733 	if (flags & DUP_FIXED && old == new) {
734 		*retval = new;
735 		FILEDESC_XUNLOCK(fdp);
736 		return (0);
737 	}
738 	fp = fdp->fd_ofiles[old];
739 	fhold(fp);
740 
741 	/*
742 	 * If the caller specified a file descriptor, make sure the file
743 	 * table is large enough to hold it, and grab it.  Otherwise, just
744 	 * allocate a new descriptor the usual way.  Since the filedesc
745 	 * lock may be temporarily dropped in the process, we have to look
746 	 * out for a race.
747 	 */
748 	if (flags & DUP_FIXED) {
749 		if (new >= fdp->fd_nfiles)
750 			fdgrowtable(fdp, new + 1);
751 		if (fdp->fd_ofiles[new] == NULL)
752 			fdused(fdp, new);
753 	} else {
754 		if ((error = fdalloc(td, new, &new)) != 0) {
755 			FILEDESC_XUNLOCK(fdp);
756 			fdrop(fp, td);
757 			return (error);
758 		}
759 	}
760 
761 	/*
762 	 * If the old file changed out from under us then treat it as a
763 	 * bad file descriptor.  Userland should do its own locking to
764 	 * avoid this case.
765 	 */
766 	if (fdp->fd_ofiles[old] != fp) {
767 		/* we've allocated a descriptor which we won't use */
768 		if (fdp->fd_ofiles[new] == NULL)
769 			fdunused(fdp, new);
770 		FILEDESC_XUNLOCK(fdp);
771 		fdrop(fp, td);
772 		return (EBADF);
773 	}
774 	KASSERT(old != new,
775 	    ("new fd is same as old"));
776 
777 	/*
778 	 * Save info on the descriptor being overwritten.  We cannot close
779 	 * it without introducing an ownership race for the slot, since we
780 	 * need to drop the filedesc lock to call closef().
781 	 *
782 	 * XXX this duplicates parts of close().
783 	 */
784 	delfp = fdp->fd_ofiles[new];
785 	holdleaders = 0;
786 	if (delfp != NULL) {
787 		if (td->td_proc->p_fdtol != NULL) {
788 			/*
789 			 * Ask fdfree() to sleep to ensure that all relevant
790 			 * process leaders can be traversed in closef().
791 			 */
792 			fdp->fd_holdleaderscount++;
793 			holdleaders = 1;
794 		}
795 	}
796 
797 	/*
798 	 * Duplicate the source descriptor
799 	 */
800 	fdp->fd_ofiles[new] = fp;
801 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
802 	if (new > fdp->fd_lastfile)
803 		fdp->fd_lastfile = new;
804 	*retval = new;
805 
806 	/*
807 	 * If we dup'd over a valid file, we now own the reference to it
808 	 * and must dispose of it using closef() semantics (as if a
809 	 * close() were performed on it).
810 	 *
811 	 * XXX this duplicates parts of close().
812 	 */
813 	if (delfp != NULL) {
814 		knote_fdclose(td, new);
815 		if (delfp->f_type == DTYPE_MQUEUE)
816 			mq_fdclose(td, new, delfp);
817 		FILEDESC_XUNLOCK(fdp);
818 		(void) closef(delfp, td);
819 		if (holdleaders) {
820 			FILEDESC_XLOCK(fdp);
821 			fdp->fd_holdleaderscount--;
822 			if (fdp->fd_holdleaderscount == 0 &&
823 			    fdp->fd_holdleaderswakeup != 0) {
824 				fdp->fd_holdleaderswakeup = 0;
825 				wakeup(&fdp->fd_holdleaderscount);
826 			}
827 			FILEDESC_XUNLOCK(fdp);
828 		}
829 	} else {
830 		FILEDESC_XUNLOCK(fdp);
831 	}
832 	return (0);
833 }
834 
835 /*
836  * If sigio is on the list associated with a process or process group,
837  * disable signalling from the device, remove sigio from the list and
838  * free sigio.
839  */
840 void
841 funsetown(struct sigio **sigiop)
842 {
843 	struct sigio *sigio;
844 
845 	SIGIO_LOCK();
846 	sigio = *sigiop;
847 	if (sigio == NULL) {
848 		SIGIO_UNLOCK();
849 		return;
850 	}
851 	*(sigio->sio_myref) = NULL;
852 	if ((sigio)->sio_pgid < 0) {
853 		struct pgrp *pg = (sigio)->sio_pgrp;
854 		PGRP_LOCK(pg);
855 		SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
856 			     sigio, sio_pgsigio);
857 		PGRP_UNLOCK(pg);
858 	} else {
859 		struct proc *p = (sigio)->sio_proc;
860 		PROC_LOCK(p);
861 		SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
862 			     sigio, sio_pgsigio);
863 		PROC_UNLOCK(p);
864 	}
865 	SIGIO_UNLOCK();
866 	crfree(sigio->sio_ucred);
867 	free(sigio, M_SIGIO);
868 }
869 
870 /*
871  * Free a list of sigio structures.
872  * We only need to lock the SIGIO_LOCK because we have made ourselves
873  * inaccessible to callers of fsetown and therefore do not need to lock
874  * the proc or pgrp struct for the list manipulation.
875  */
876 void
877 funsetownlst(struct sigiolst *sigiolst)
878 {
879 	struct proc *p;
880 	struct pgrp *pg;
881 	struct sigio *sigio;
882 
883 	sigio = SLIST_FIRST(sigiolst);
884 	if (sigio == NULL)
885 		return;
886 	p = NULL;
887 	pg = NULL;
888 
889 	/*
890 	 * Every entry of the list should belong
891 	 * to a single proc or pgrp.
892 	 */
893 	if (sigio->sio_pgid < 0) {
894 		pg = sigio->sio_pgrp;
895 		PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
896 	} else /* if (sigio->sio_pgid > 0) */ {
897 		p = sigio->sio_proc;
898 		PROC_LOCK_ASSERT(p, MA_NOTOWNED);
899 	}
900 
901 	SIGIO_LOCK();
902 	while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
903 		*(sigio->sio_myref) = NULL;
904 		if (pg != NULL) {
905 			KASSERT(sigio->sio_pgid < 0,
906 			    ("Proc sigio in pgrp sigio list"));
907 			KASSERT(sigio->sio_pgrp == pg,
908 			    ("Bogus pgrp in sigio list"));
909 			PGRP_LOCK(pg);
910 			SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
911 			    sio_pgsigio);
912 			PGRP_UNLOCK(pg);
913 		} else /* if (p != NULL) */ {
914 			KASSERT(sigio->sio_pgid > 0,
915 			    ("Pgrp sigio in proc sigio list"));
916 			KASSERT(sigio->sio_proc == p,
917 			    ("Bogus proc in sigio list"));
918 			PROC_LOCK(p);
919 			SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
920 			    sio_pgsigio);
921 			PROC_UNLOCK(p);
922 		}
923 		SIGIO_UNLOCK();
924 		crfree(sigio->sio_ucred);
925 		free(sigio, M_SIGIO);
926 		SIGIO_LOCK();
927 	}
928 	SIGIO_UNLOCK();
929 }
930 
931 /*
932  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
933  *
934  * After permission checking, add a sigio structure to the sigio list for
935  * the process or process group.
936  */
937 int
938 fsetown(pid_t pgid, struct sigio **sigiop)
939 {
940 	struct proc *proc;
941 	struct pgrp *pgrp;
942 	struct sigio *sigio;
943 	int ret;
944 
945 	if (pgid == 0) {
946 		funsetown(sigiop);
947 		return (0);
948 	}
949 
950 	ret = 0;
951 
952 	/* Allocate and fill in the new sigio out of locks. */
953 	sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
954 	sigio->sio_pgid = pgid;
955 	sigio->sio_ucred = crhold(curthread->td_ucred);
956 	sigio->sio_myref = sigiop;
957 
958 	sx_slock(&proctree_lock);
959 	if (pgid > 0) {
960 		proc = pfind(pgid);
961 		if (proc == NULL) {
962 			ret = ESRCH;
963 			goto fail;
964 		}
965 
966 		/*
967 		 * Policy - Don't allow a process to FSETOWN a process
968 		 * in another session.
969 		 *
970 		 * Remove this test to allow maximum flexibility or
971 		 * restrict FSETOWN to the current process or process
972 		 * group for maximum safety.
973 		 */
974 		PROC_UNLOCK(proc);
975 		if (proc->p_session != curthread->td_proc->p_session) {
976 			ret = EPERM;
977 			goto fail;
978 		}
979 
980 		pgrp = NULL;
981 	} else /* if (pgid < 0) */ {
982 		pgrp = pgfind(-pgid);
983 		if (pgrp == NULL) {
984 			ret = ESRCH;
985 			goto fail;
986 		}
987 		PGRP_UNLOCK(pgrp);
988 
989 		/*
990 		 * Policy - Don't allow a process to FSETOWN a process
991 		 * in another session.
992 		 *
993 		 * Remove this test to allow maximum flexibility or
994 		 * restrict FSETOWN to the current process or process
995 		 * group for maximum safety.
996 		 */
997 		if (pgrp->pg_session != curthread->td_proc->p_session) {
998 			ret = EPERM;
999 			goto fail;
1000 		}
1001 
1002 		proc = NULL;
1003 	}
1004 	funsetown(sigiop);
1005 	if (pgid > 0) {
1006 		PROC_LOCK(proc);
1007 		/*
1008 		 * Since funsetownlst() is called without the proctree
1009 		 * locked, we need to check for P_WEXIT.
1010 		 * XXX: is ESRCH correct?
1011 		 */
1012 		if ((proc->p_flag & P_WEXIT) != 0) {
1013 			PROC_UNLOCK(proc);
1014 			ret = ESRCH;
1015 			goto fail;
1016 		}
1017 		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1018 		sigio->sio_proc = proc;
1019 		PROC_UNLOCK(proc);
1020 	} else {
1021 		PGRP_LOCK(pgrp);
1022 		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1023 		sigio->sio_pgrp = pgrp;
1024 		PGRP_UNLOCK(pgrp);
1025 	}
1026 	sx_sunlock(&proctree_lock);
1027 	SIGIO_LOCK();
1028 	*sigiop = sigio;
1029 	SIGIO_UNLOCK();
1030 	return (0);
1031 
1032 fail:
1033 	sx_sunlock(&proctree_lock);
1034 	crfree(sigio->sio_ucred);
1035 	free(sigio, M_SIGIO);
1036 	return (ret);
1037 }
1038 
1039 /*
1040  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1041  */
1042 pid_t
1043 fgetown(sigiop)
1044 	struct sigio **sigiop;
1045 {
1046 	pid_t pgid;
1047 
1048 	SIGIO_LOCK();
1049 	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1050 	SIGIO_UNLOCK();
1051 	return (pgid);
1052 }
1053 
1054 /*
1055  * Close a file descriptor.
1056  */
1057 #ifndef _SYS_SYSPROTO_H_
1058 struct close_args {
1059 	int     fd;
1060 };
1061 #endif
1062 /* ARGSUSED */
1063 int
1064 close(td, uap)
1065 	struct thread *td;
1066 	struct close_args *uap;
1067 {
1068 
1069 	return (kern_close(td, uap->fd));
1070 }
1071 
1072 int
1073 kern_close(td, fd)
1074 	struct thread *td;
1075 	int fd;
1076 {
1077 	struct filedesc *fdp;
1078 	struct file *fp;
1079 	int error;
1080 	int holdleaders;
1081 
1082 	error = 0;
1083 	holdleaders = 0;
1084 	fdp = td->td_proc->p_fd;
1085 
1086 	AUDIT_SYSCLOSE(td, fd);
1087 
1088 	FILEDESC_XLOCK(fdp);
1089 	if ((unsigned)fd >= fdp->fd_nfiles ||
1090 	    (fp = fdp->fd_ofiles[fd]) == NULL) {
1091 		FILEDESC_XUNLOCK(fdp);
1092 		return (EBADF);
1093 	}
1094 	fdp->fd_ofiles[fd] = NULL;
1095 	fdp->fd_ofileflags[fd] = 0;
1096 	fdunused(fdp, fd);
1097 	if (td->td_proc->p_fdtol != NULL) {
1098 		/*
1099 		 * Ask fdfree() to sleep to ensure that all relevant
1100 		 * process leaders can be traversed in closef().
1101 		 */
1102 		fdp->fd_holdleaderscount++;
1103 		holdleaders = 1;
1104 	}
1105 
1106 	/*
1107 	 * We now hold the fp reference that used to be owned by the
1108 	 * descriptor array.  We have to unlock the FILEDESC *AFTER*
1109 	 * knote_fdclose to prevent a race of the fd getting opened, a knote
1110 	 * added, and deleteing a knote for the new fd.
1111 	 */
1112 	knote_fdclose(td, fd);
1113 	if (fp->f_type == DTYPE_MQUEUE)
1114 		mq_fdclose(td, fd, fp);
1115 	FILEDESC_XUNLOCK(fdp);
1116 
1117 	error = closef(fp, td);
1118 	if (holdleaders) {
1119 		FILEDESC_XLOCK(fdp);
1120 		fdp->fd_holdleaderscount--;
1121 		if (fdp->fd_holdleaderscount == 0 &&
1122 		    fdp->fd_holdleaderswakeup != 0) {
1123 			fdp->fd_holdleaderswakeup = 0;
1124 			wakeup(&fdp->fd_holdleaderscount);
1125 		}
1126 		FILEDESC_XUNLOCK(fdp);
1127 	}
1128 	return (error);
1129 }
1130 
1131 #if defined(COMPAT_43)
1132 /*
1133  * Return status information about a file descriptor.
1134  */
1135 #ifndef _SYS_SYSPROTO_H_
1136 struct ofstat_args {
1137 	int	fd;
1138 	struct	ostat *sb;
1139 };
1140 #endif
1141 /* ARGSUSED */
1142 int
1143 ofstat(struct thread *td, struct ofstat_args *uap)
1144 {
1145 	struct ostat oub;
1146 	struct stat ub;
1147 	int error;
1148 
1149 	error = kern_fstat(td, uap->fd, &ub);
1150 	if (error == 0) {
1151 		cvtstat(&ub, &oub);
1152 		error = copyout(&oub, uap->sb, sizeof(oub));
1153 	}
1154 	return (error);
1155 }
1156 #endif /* COMPAT_43 */
1157 
1158 /*
1159  * Return status information about a file descriptor.
1160  */
1161 #ifndef _SYS_SYSPROTO_H_
1162 struct fstat_args {
1163 	int	fd;
1164 	struct	stat *sb;
1165 };
1166 #endif
1167 /* ARGSUSED */
1168 int
1169 fstat(struct thread *td, struct fstat_args *uap)
1170 {
1171 	struct stat ub;
1172 	int error;
1173 
1174 	error = kern_fstat(td, uap->fd, &ub);
1175 	if (error == 0)
1176 		error = copyout(&ub, uap->sb, sizeof(ub));
1177 	return (error);
1178 }
1179 
1180 int
1181 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1182 {
1183 	struct file *fp;
1184 	int error;
1185 
1186 	AUDIT_ARG(fd, fd);
1187 
1188 	if ((error = fget(td, fd, &fp)) != 0)
1189 		return (error);
1190 
1191 	AUDIT_ARG(file, td->td_proc, fp);
1192 
1193 	error = fo_stat(fp, sbp, td->td_ucred, td);
1194 	fdrop(fp, td);
1195 #ifdef KTRACE
1196 	if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1197 		ktrstat(sbp);
1198 #endif
1199 	return (error);
1200 }
1201 
1202 /*
1203  * Return status information about a file descriptor.
1204  */
1205 #ifndef _SYS_SYSPROTO_H_
1206 struct nfstat_args {
1207 	int	fd;
1208 	struct	nstat *sb;
1209 };
1210 #endif
1211 /* ARGSUSED */
1212 int
1213 nfstat(struct thread *td, struct nfstat_args *uap)
1214 {
1215 	struct nstat nub;
1216 	struct stat ub;
1217 	int error;
1218 
1219 	error = kern_fstat(td, uap->fd, &ub);
1220 	if (error == 0) {
1221 		cvtnstat(&ub, &nub);
1222 		error = copyout(&nub, uap->sb, sizeof(nub));
1223 	}
1224 	return (error);
1225 }
1226 
1227 /*
1228  * Return pathconf information about a file descriptor.
1229  */
1230 #ifndef _SYS_SYSPROTO_H_
1231 struct fpathconf_args {
1232 	int	fd;
1233 	int	name;
1234 };
1235 #endif
1236 /* ARGSUSED */
1237 int
1238 fpathconf(struct thread *td, struct fpathconf_args *uap)
1239 {
1240 	struct file *fp;
1241 	struct vnode *vp;
1242 	int error;
1243 
1244 	if ((error = fget(td, uap->fd, &fp)) != 0)
1245 		return (error);
1246 
1247 	/* If asynchronous I/O is available, it works for all descriptors. */
1248 	if (uap->name == _PC_ASYNC_IO) {
1249 		td->td_retval[0] = async_io_version;
1250 		goto out;
1251 	}
1252 	vp = fp->f_vnode;
1253 	if (vp != NULL) {
1254 		int vfslocked;
1255 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1256 		vn_lock(vp, LK_SHARED | LK_RETRY);
1257 		error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1258 		VOP_UNLOCK(vp, 0);
1259 		VFS_UNLOCK_GIANT(vfslocked);
1260 	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1261 		if (uap->name != _PC_PIPE_BUF) {
1262 			error = EINVAL;
1263 		} else {
1264 			td->td_retval[0] = PIPE_BUF;
1265 		error = 0;
1266 		}
1267 	} else {
1268 		error = EOPNOTSUPP;
1269 	}
1270 out:
1271 	fdrop(fp, td);
1272 	return (error);
1273 }
1274 
1275 /*
1276  * Grow the file table to accomodate (at least) nfd descriptors.  This may
1277  * block and drop the filedesc lock, but it will reacquire it before
1278  * returning.
1279  */
1280 static void
1281 fdgrowtable(struct filedesc *fdp, int nfd)
1282 {
1283 	struct filedesc0 *fdp0;
1284 	struct freetable *fo;
1285 	struct file **ntable;
1286 	struct file **otable;
1287 	char *nfileflags;
1288 	int nnfiles, onfiles;
1289 	NDSLOTTYPE *nmap;
1290 
1291 	FILEDESC_XLOCK_ASSERT(fdp);
1292 
1293 	KASSERT(fdp->fd_nfiles > 0,
1294 	    ("zero-length file table"));
1295 
1296 	/* compute the size of the new table */
1297 	onfiles = fdp->fd_nfiles;
1298 	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1299 	if (nnfiles <= onfiles)
1300 		/* the table is already large enough */
1301 		return;
1302 
1303 	/* allocate a new table and (if required) new bitmaps */
1304 	FILEDESC_XUNLOCK(fdp);
1305 	ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1306 	    M_FILEDESC, M_ZERO | M_WAITOK);
1307 	nfileflags = (char *)&ntable[nnfiles];
1308 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1309 		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1310 		    M_FILEDESC, M_ZERO | M_WAITOK);
1311 	else
1312 		nmap = NULL;
1313 	FILEDESC_XLOCK(fdp);
1314 
1315 	/*
1316 	 * We now have new tables ready to go.  Since we dropped the
1317 	 * filedesc lock to call malloc(), watch out for a race.
1318 	 */
1319 	onfiles = fdp->fd_nfiles;
1320 	if (onfiles >= nnfiles) {
1321 		/* we lost the race, but that's OK */
1322 		free(ntable, M_FILEDESC);
1323 		if (nmap != NULL)
1324 			free(nmap, M_FILEDESC);
1325 		return;
1326 	}
1327 	bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1328 	bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1329 	otable = fdp->fd_ofiles;
1330 	fdp->fd_ofileflags = nfileflags;
1331 	fdp->fd_ofiles = ntable;
1332 	/*
1333 	 * We must preserve ofiles until the process exits because we can't
1334 	 * be certain that no threads have references to the old table via
1335 	 * _fget().
1336 	 */
1337 	if (onfiles > NDFILE) {
1338 		fo = (struct freetable *)&otable[onfiles];
1339 		fdp0 = (struct filedesc0 *)fdp;
1340 		fo->ft_table = otable;
1341 		SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1342 	}
1343 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1344 		bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1345 		if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1346 			free(fdp->fd_map, M_FILEDESC);
1347 		fdp->fd_map = nmap;
1348 	}
1349 	fdp->fd_nfiles = nnfiles;
1350 }
1351 
1352 /*
1353  * Allocate a file descriptor for the process.
1354  */
1355 int
1356 fdalloc(struct thread *td, int minfd, int *result)
1357 {
1358 	struct proc *p = td->td_proc;
1359 	struct filedesc *fdp = p->p_fd;
1360 	int fd = -1, maxfd;
1361 
1362 	FILEDESC_XLOCK_ASSERT(fdp);
1363 
1364 	if (fdp->fd_freefile > minfd)
1365 		minfd = fdp->fd_freefile;
1366 
1367 	PROC_LOCK(p);
1368 	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1369 	PROC_UNLOCK(p);
1370 
1371 	/*
1372 	 * Search the bitmap for a free descriptor.  If none is found, try
1373 	 * to grow the file table.  Keep at it until we either get a file
1374 	 * descriptor or run into process or system limits; fdgrowtable()
1375 	 * may drop the filedesc lock, so we're in a race.
1376 	 */
1377 	for (;;) {
1378 		fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1379 		if (fd >= maxfd)
1380 			return (EMFILE);
1381 		if (fd < fdp->fd_nfiles)
1382 			break;
1383 		fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1384 	}
1385 
1386 	/*
1387 	 * Perform some sanity checks, then mark the file descriptor as
1388 	 * used and return it to the caller.
1389 	 */
1390 	KASSERT(!fdisused(fdp, fd),
1391 	    ("fd_first_free() returned non-free descriptor"));
1392 	KASSERT(fdp->fd_ofiles[fd] == NULL,
1393 	    ("free descriptor isn't"));
1394 	fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1395 	fdused(fdp, fd);
1396 	*result = fd;
1397 	return (0);
1398 }
1399 
1400 /*
1401  * Check to see whether n user file descriptors are available to the process
1402  * p.
1403  */
1404 int
1405 fdavail(struct thread *td, int n)
1406 {
1407 	struct proc *p = td->td_proc;
1408 	struct filedesc *fdp = td->td_proc->p_fd;
1409 	struct file **fpp;
1410 	int i, lim, last;
1411 
1412 	FILEDESC_LOCK_ASSERT(fdp);
1413 
1414 	PROC_LOCK(p);
1415 	lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1416 	PROC_UNLOCK(p);
1417 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1418 		return (1);
1419 	last = min(fdp->fd_nfiles, lim);
1420 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1421 	for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1422 		if (*fpp == NULL && --n <= 0)
1423 			return (1);
1424 	}
1425 	return (0);
1426 }
1427 
1428 /*
1429  * Create a new open file structure and allocate a file decriptor for the
1430  * process that refers to it.  We add one reference to the file for the
1431  * descriptor table and one reference for resultfp. This is to prevent us
1432  * being preempted and the entry in the descriptor table closed after we
1433  * release the FILEDESC lock.
1434  */
1435 int
1436 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1437 {
1438 	struct proc *p = td->td_proc;
1439 	struct file *fp;
1440 	int error, i;
1441 	int maxuserfiles = maxfiles - (maxfiles / 20);
1442 	static struct timeval lastfail;
1443 	static int curfail;
1444 
1445 	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1446 	if ((openfiles >= maxuserfiles &&
1447 	    priv_check(td, PRIV_MAXFILES) != 0) ||
1448 	    openfiles >= maxfiles) {
1449 		if (ppsratecheck(&lastfail, &curfail, 1)) {
1450 			printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1451 				td->td_ucred->cr_ruid);
1452 		}
1453 		uma_zfree(file_zone, fp);
1454 		return (ENFILE);
1455 	}
1456 	atomic_add_int(&openfiles, 1);
1457 
1458 	/*
1459 	 * If the process has file descriptor zero open, add the new file
1460 	 * descriptor to the list of open files at that point, otherwise
1461 	 * put it at the front of the list of open files.
1462 	 */
1463 	refcount_init(&fp->f_count, 1);
1464 	if (resultfp)
1465 		fhold(fp);
1466 	fp->f_cred = crhold(td->td_ucred);
1467 	fp->f_ops = &badfileops;
1468 	fp->f_data = NULL;
1469 	fp->f_vnode = NULL;
1470 	FILEDESC_XLOCK(p->p_fd);
1471 	if ((error = fdalloc(td, 0, &i))) {
1472 		FILEDESC_XUNLOCK(p->p_fd);
1473 		fdrop(fp, td);
1474 		if (resultfp)
1475 			fdrop(fp, td);
1476 		return (error);
1477 	}
1478 	p->p_fd->fd_ofiles[i] = fp;
1479 	FILEDESC_XUNLOCK(p->p_fd);
1480 	if (resultfp)
1481 		*resultfp = fp;
1482 	if (resultfd)
1483 		*resultfd = i;
1484 	return (0);
1485 }
1486 
1487 /*
1488  * Build a new filedesc structure from another.
1489  * Copy the current, root, and jail root vnode references.
1490  */
1491 struct filedesc *
1492 fdinit(struct filedesc *fdp)
1493 {
1494 	struct filedesc0 *newfdp;
1495 
1496 	newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1497 	FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1498 	if (fdp != NULL) {
1499 		FILEDESC_XLOCK(fdp);
1500 		newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1501 		if (newfdp->fd_fd.fd_cdir)
1502 			VREF(newfdp->fd_fd.fd_cdir);
1503 		newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1504 		if (newfdp->fd_fd.fd_rdir)
1505 			VREF(newfdp->fd_fd.fd_rdir);
1506 		newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1507 		if (newfdp->fd_fd.fd_jdir)
1508 			VREF(newfdp->fd_fd.fd_jdir);
1509 		FILEDESC_XUNLOCK(fdp);
1510 	}
1511 
1512 	/* Create the file descriptor table. */
1513 	newfdp->fd_fd.fd_refcnt = 1;
1514 	newfdp->fd_fd.fd_holdcnt = 1;
1515 	newfdp->fd_fd.fd_cmask = CMASK;
1516 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1517 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1518 	newfdp->fd_fd.fd_nfiles = NDFILE;
1519 	newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1520 	newfdp->fd_fd.fd_lastfile = -1;
1521 	return (&newfdp->fd_fd);
1522 }
1523 
1524 static struct filedesc *
1525 fdhold(struct proc *p)
1526 {
1527 	struct filedesc *fdp;
1528 
1529 	mtx_lock(&fdesc_mtx);
1530 	fdp = p->p_fd;
1531 	if (fdp != NULL)
1532 		fdp->fd_holdcnt++;
1533 	mtx_unlock(&fdesc_mtx);
1534 	return (fdp);
1535 }
1536 
1537 static void
1538 fddrop(struct filedesc *fdp)
1539 {
1540 	struct filedesc0 *fdp0;
1541 	struct freetable *ft;
1542 	int i;
1543 
1544 	mtx_lock(&fdesc_mtx);
1545 	i = --fdp->fd_holdcnt;
1546 	mtx_unlock(&fdesc_mtx);
1547 	if (i > 0)
1548 		return;
1549 
1550 	FILEDESC_LOCK_DESTROY(fdp);
1551 	fdp0 = (struct filedesc0 *)fdp;
1552 	while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1553 		SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1554 		free(ft->ft_table, M_FILEDESC);
1555 	}
1556 	free(fdp, M_FILEDESC);
1557 }
1558 
1559 /*
1560  * Share a filedesc structure.
1561  */
1562 struct filedesc *
1563 fdshare(struct filedesc *fdp)
1564 {
1565 
1566 	FILEDESC_XLOCK(fdp);
1567 	fdp->fd_refcnt++;
1568 	FILEDESC_XUNLOCK(fdp);
1569 	return (fdp);
1570 }
1571 
1572 /*
1573  * Unshare a filedesc structure, if necessary by making a copy
1574  */
1575 void
1576 fdunshare(struct proc *p, struct thread *td)
1577 {
1578 
1579 	FILEDESC_XLOCK(p->p_fd);
1580 	if (p->p_fd->fd_refcnt > 1) {
1581 		struct filedesc *tmp;
1582 
1583 		FILEDESC_XUNLOCK(p->p_fd);
1584 		tmp = fdcopy(p->p_fd);
1585 		fdfree(td);
1586 		p->p_fd = tmp;
1587 	} else
1588 		FILEDESC_XUNLOCK(p->p_fd);
1589 }
1590 
1591 /*
1592  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
1593  * this is to ease callers, not catch errors.
1594  */
1595 struct filedesc *
1596 fdcopy(struct filedesc *fdp)
1597 {
1598 	struct filedesc *newfdp;
1599 	int i;
1600 
1601 	/* Certain daemons might not have file descriptors. */
1602 	if (fdp == NULL)
1603 		return (NULL);
1604 
1605 	newfdp = fdinit(fdp);
1606 	FILEDESC_SLOCK(fdp);
1607 	while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1608 		FILEDESC_SUNLOCK(fdp);
1609 		FILEDESC_XLOCK(newfdp);
1610 		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1611 		FILEDESC_XUNLOCK(newfdp);
1612 		FILEDESC_SLOCK(fdp);
1613 	}
1614 	/* copy everything except kqueue descriptors */
1615 	newfdp->fd_freefile = -1;
1616 	for (i = 0; i <= fdp->fd_lastfile; ++i) {
1617 		if (fdisused(fdp, i) &&
1618 		    fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1619 		    fdp->fd_ofiles[i]->f_ops != &badfileops) {
1620 			newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1621 			newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1622 			fhold(newfdp->fd_ofiles[i]);
1623 			newfdp->fd_lastfile = i;
1624 		} else {
1625 			if (newfdp->fd_freefile == -1)
1626 				newfdp->fd_freefile = i;
1627 		}
1628 	}
1629 	newfdp->fd_cmask = fdp->fd_cmask;
1630 	FILEDESC_SUNLOCK(fdp);
1631 	FILEDESC_XLOCK(newfdp);
1632 	for (i = 0; i <= newfdp->fd_lastfile; ++i)
1633 		if (newfdp->fd_ofiles[i] != NULL)
1634 			fdused(newfdp, i);
1635 	if (newfdp->fd_freefile == -1)
1636 		newfdp->fd_freefile = i;
1637 	FILEDESC_XUNLOCK(newfdp);
1638 	return (newfdp);
1639 }
1640 
1641 /*
1642  * Release a filedesc structure.
1643  */
1644 void
1645 fdfree(struct thread *td)
1646 {
1647 	struct filedesc *fdp;
1648 	struct file **fpp;
1649 	int i, locked;
1650 	struct filedesc_to_leader *fdtol;
1651 	struct file *fp;
1652 	struct vnode *cdir, *jdir, *rdir, *vp;
1653 	struct flock lf;
1654 
1655 	/* Certain daemons might not have file descriptors. */
1656 	fdp = td->td_proc->p_fd;
1657 	if (fdp == NULL)
1658 		return;
1659 
1660 	/* Check for special need to clear POSIX style locks */
1661 	fdtol = td->td_proc->p_fdtol;
1662 	if (fdtol != NULL) {
1663 		FILEDESC_XLOCK(fdp);
1664 		KASSERT(fdtol->fdl_refcount > 0,
1665 			("filedesc_to_refcount botch: fdl_refcount=%d",
1666 			 fdtol->fdl_refcount));
1667 		if (fdtol->fdl_refcount == 1 &&
1668 		    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1669 			for (i = 0, fpp = fdp->fd_ofiles;
1670 			     i <= fdp->fd_lastfile;
1671 			     i++, fpp++) {
1672 				if (*fpp == NULL ||
1673 				    (*fpp)->f_type != DTYPE_VNODE)
1674 					continue;
1675 				fp = *fpp;
1676 				fhold(fp);
1677 				FILEDESC_XUNLOCK(fdp);
1678 				lf.l_whence = SEEK_SET;
1679 				lf.l_start = 0;
1680 				lf.l_len = 0;
1681 				lf.l_type = F_UNLCK;
1682 				vp = fp->f_vnode;
1683 				locked = VFS_LOCK_GIANT(vp->v_mount);
1684 				(void) VOP_ADVLOCK(vp,
1685 						   (caddr_t)td->td_proc->
1686 						   p_leader,
1687 						   F_UNLCK,
1688 						   &lf,
1689 						   F_POSIX);
1690 				VFS_UNLOCK_GIANT(locked);
1691 				FILEDESC_XLOCK(fdp);
1692 				fdrop(fp, td);
1693 				fpp = fdp->fd_ofiles + i;
1694 			}
1695 		}
1696 	retry:
1697 		if (fdtol->fdl_refcount == 1) {
1698 			if (fdp->fd_holdleaderscount > 0 &&
1699 			    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1700 				/*
1701 				 * close() or do_dup() has cleared a reference
1702 				 * in a shared file descriptor table.
1703 				 */
1704 				fdp->fd_holdleaderswakeup = 1;
1705 				sx_sleep(&fdp->fd_holdleaderscount,
1706 				    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1707 				goto retry;
1708 			}
1709 			if (fdtol->fdl_holdcount > 0) {
1710 				/*
1711 				 * Ensure that fdtol->fdl_leader remains
1712 				 * valid in closef().
1713 				 */
1714 				fdtol->fdl_wakeup = 1;
1715 				sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1716 				    "fdlhold", 0);
1717 				goto retry;
1718 			}
1719 		}
1720 		fdtol->fdl_refcount--;
1721 		if (fdtol->fdl_refcount == 0 &&
1722 		    fdtol->fdl_holdcount == 0) {
1723 			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1724 			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1725 		} else
1726 			fdtol = NULL;
1727 		td->td_proc->p_fdtol = NULL;
1728 		FILEDESC_XUNLOCK(fdp);
1729 		if (fdtol != NULL)
1730 			free(fdtol, M_FILEDESC_TO_LEADER);
1731 	}
1732 	FILEDESC_XLOCK(fdp);
1733 	i = --fdp->fd_refcnt;
1734 	FILEDESC_XUNLOCK(fdp);
1735 	if (i > 0)
1736 		return;
1737 
1738 	fpp = fdp->fd_ofiles;
1739 	for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1740 		if (*fpp) {
1741 			FILEDESC_XLOCK(fdp);
1742 			fp = *fpp;
1743 			*fpp = NULL;
1744 			FILEDESC_XUNLOCK(fdp);
1745 			(void) closef(fp, td);
1746 		}
1747 	}
1748 	FILEDESC_XLOCK(fdp);
1749 
1750 	/* XXX This should happen earlier. */
1751 	mtx_lock(&fdesc_mtx);
1752 	td->td_proc->p_fd = NULL;
1753 	mtx_unlock(&fdesc_mtx);
1754 
1755 	if (fdp->fd_nfiles > NDFILE)
1756 		free(fdp->fd_ofiles, M_FILEDESC);
1757 	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1758 		free(fdp->fd_map, M_FILEDESC);
1759 
1760 	fdp->fd_nfiles = 0;
1761 
1762 	cdir = fdp->fd_cdir;
1763 	fdp->fd_cdir = NULL;
1764 	rdir = fdp->fd_rdir;
1765 	fdp->fd_rdir = NULL;
1766 	jdir = fdp->fd_jdir;
1767 	fdp->fd_jdir = NULL;
1768 	FILEDESC_XUNLOCK(fdp);
1769 
1770 	if (cdir) {
1771 		locked = VFS_LOCK_GIANT(cdir->v_mount);
1772 		vrele(cdir);
1773 		VFS_UNLOCK_GIANT(locked);
1774 	}
1775 	if (rdir) {
1776 		locked = VFS_LOCK_GIANT(rdir->v_mount);
1777 		vrele(rdir);
1778 		VFS_UNLOCK_GIANT(locked);
1779 	}
1780 	if (jdir) {
1781 		locked = VFS_LOCK_GIANT(jdir->v_mount);
1782 		vrele(jdir);
1783 		VFS_UNLOCK_GIANT(locked);
1784 	}
1785 
1786 	fddrop(fdp);
1787 }
1788 
1789 /*
1790  * For setugid programs, we don't want to people to use that setugidness
1791  * to generate error messages which write to a file which otherwise would
1792  * otherwise be off-limits to the process.  We check for filesystems where
1793  * the vnode can change out from under us after execve (like [lin]procfs).
1794  *
1795  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1796  * sufficient.  We also don't check for setugidness since we know we are.
1797  */
1798 static int
1799 is_unsafe(struct file *fp)
1800 {
1801 	if (fp->f_type == DTYPE_VNODE) {
1802 		struct vnode *vp = fp->f_vnode;
1803 
1804 		if ((vp->v_vflag & VV_PROCDEP) != 0)
1805 			return (1);
1806 	}
1807 	return (0);
1808 }
1809 
1810 /*
1811  * Make this setguid thing safe, if at all possible.
1812  */
1813 void
1814 setugidsafety(struct thread *td)
1815 {
1816 	struct filedesc *fdp;
1817 	int i;
1818 
1819 	/* Certain daemons might not have file descriptors. */
1820 	fdp = td->td_proc->p_fd;
1821 	if (fdp == NULL)
1822 		return;
1823 
1824 	/*
1825 	 * Note: fdp->fd_ofiles may be reallocated out from under us while
1826 	 * we are blocked in a close.  Be careful!
1827 	 */
1828 	FILEDESC_XLOCK(fdp);
1829 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1830 		if (i > 2)
1831 			break;
1832 		if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1833 			struct file *fp;
1834 
1835 			knote_fdclose(td, i);
1836 			/*
1837 			 * NULL-out descriptor prior to close to avoid
1838 			 * a race while close blocks.
1839 			 */
1840 			fp = fdp->fd_ofiles[i];
1841 			fdp->fd_ofiles[i] = NULL;
1842 			fdp->fd_ofileflags[i] = 0;
1843 			fdunused(fdp, i);
1844 			FILEDESC_XUNLOCK(fdp);
1845 			(void) closef(fp, td);
1846 			FILEDESC_XLOCK(fdp);
1847 		}
1848 	}
1849 	FILEDESC_XUNLOCK(fdp);
1850 }
1851 
1852 /*
1853  * If a specific file object occupies a specific file descriptor, close the
1854  * file descriptor entry and drop a reference on the file object.  This is a
1855  * convenience function to handle a subsequent error in a function that calls
1856  * falloc() that handles the race that another thread might have closed the
1857  * file descriptor out from under the thread creating the file object.
1858  */
1859 void
1860 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1861 {
1862 
1863 	FILEDESC_XLOCK(fdp);
1864 	if (fdp->fd_ofiles[idx] == fp) {
1865 		fdp->fd_ofiles[idx] = NULL;
1866 		fdunused(fdp, idx);
1867 		FILEDESC_XUNLOCK(fdp);
1868 		fdrop(fp, td);
1869 	} else
1870 		FILEDESC_XUNLOCK(fdp);
1871 }
1872 
1873 /*
1874  * Close any files on exec?
1875  */
1876 void
1877 fdcloseexec(struct thread *td)
1878 {
1879 	struct filedesc *fdp;
1880 	int i;
1881 
1882 	/* Certain daemons might not have file descriptors. */
1883 	fdp = td->td_proc->p_fd;
1884 	if (fdp == NULL)
1885 		return;
1886 
1887 	FILEDESC_XLOCK(fdp);
1888 
1889 	/*
1890 	 * We cannot cache fd_ofiles or fd_ofileflags since operations
1891 	 * may block and rip them out from under us.
1892 	 */
1893 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1894 		if (fdp->fd_ofiles[i] != NULL &&
1895 		    (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1896 		    (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1897 			struct file *fp;
1898 
1899 			knote_fdclose(td, i);
1900 			/*
1901 			 * NULL-out descriptor prior to close to avoid
1902 			 * a race while close blocks.
1903 			 */
1904 			fp = fdp->fd_ofiles[i];
1905 			fdp->fd_ofiles[i] = NULL;
1906 			fdp->fd_ofileflags[i] = 0;
1907 			fdunused(fdp, i);
1908 			if (fp->f_type == DTYPE_MQUEUE)
1909 				mq_fdclose(td, i, fp);
1910 			FILEDESC_XUNLOCK(fdp);
1911 			(void) closef(fp, td);
1912 			FILEDESC_XLOCK(fdp);
1913 		}
1914 	}
1915 	FILEDESC_XUNLOCK(fdp);
1916 }
1917 
1918 /*
1919  * It is unsafe for set[ug]id processes to be started with file
1920  * descriptors 0..2 closed, as these descriptors are given implicit
1921  * significance in the Standard C library.  fdcheckstd() will create a
1922  * descriptor referencing /dev/null for each of stdin, stdout, and
1923  * stderr that is not already open.
1924  */
1925 int
1926 fdcheckstd(struct thread *td)
1927 {
1928 	struct filedesc *fdp;
1929 	register_t retval, save;
1930 	int i, error, devnull;
1931 
1932 	fdp = td->td_proc->p_fd;
1933 	if (fdp == NULL)
1934 		return (0);
1935 	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1936 	devnull = -1;
1937 	error = 0;
1938 	for (i = 0; i < 3; i++) {
1939 		if (fdp->fd_ofiles[i] != NULL)
1940 			continue;
1941 		if (devnull < 0) {
1942 			save = td->td_retval[0];
1943 			error = kern_open(td, "/dev/null", UIO_SYSSPACE,
1944 			    O_RDWR, 0);
1945 			devnull = td->td_retval[0];
1946 			KASSERT(devnull == i, ("oof, we didn't get our fd"));
1947 			td->td_retval[0] = save;
1948 			if (error)
1949 				break;
1950 		} else {
1951 			error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1952 			if (error != 0)
1953 				break;
1954 		}
1955 	}
1956 	return (error);
1957 }
1958 
1959 /*
1960  * Internal form of close.  Decrement reference count on file structure.
1961  * Note: td may be NULL when closing a file that was being passed in a
1962  * message.
1963  *
1964  * XXXRW: Giant is not required for the caller, but often will be held; this
1965  * makes it moderately likely the Giant will be recursed in the VFS case.
1966  */
1967 int
1968 closef(struct file *fp, struct thread *td)
1969 {
1970 	struct vnode *vp;
1971 	struct flock lf;
1972 	struct filedesc_to_leader *fdtol;
1973 	struct filedesc *fdp;
1974 
1975 	/*
1976 	 * POSIX record locking dictates that any close releases ALL
1977 	 * locks owned by this process.  This is handled by setting
1978 	 * a flag in the unlock to free ONLY locks obeying POSIX
1979 	 * semantics, and not to free BSD-style file locks.
1980 	 * If the descriptor was in a message, POSIX-style locks
1981 	 * aren't passed with the descriptor, and the thread pointer
1982 	 * will be NULL.  Callers should be careful only to pass a
1983 	 * NULL thread pointer when there really is no owning
1984 	 * context that might have locks, or the locks will be
1985 	 * leaked.
1986 	 */
1987 	if (fp->f_type == DTYPE_VNODE && td != NULL) {
1988 		int vfslocked;
1989 
1990 		vp = fp->f_vnode;
1991 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1992 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1993 			lf.l_whence = SEEK_SET;
1994 			lf.l_start = 0;
1995 			lf.l_len = 0;
1996 			lf.l_type = F_UNLCK;
1997 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1998 					   F_UNLCK, &lf, F_POSIX);
1999 		}
2000 		fdtol = td->td_proc->p_fdtol;
2001 		if (fdtol != NULL) {
2002 			/*
2003 			 * Handle special case where file descriptor table is
2004 			 * shared between multiple process leaders.
2005 			 */
2006 			fdp = td->td_proc->p_fd;
2007 			FILEDESC_XLOCK(fdp);
2008 			for (fdtol = fdtol->fdl_next;
2009 			     fdtol != td->td_proc->p_fdtol;
2010 			     fdtol = fdtol->fdl_next) {
2011 				if ((fdtol->fdl_leader->p_flag &
2012 				     P_ADVLOCK) == 0)
2013 					continue;
2014 				fdtol->fdl_holdcount++;
2015 				FILEDESC_XUNLOCK(fdp);
2016 				lf.l_whence = SEEK_SET;
2017 				lf.l_start = 0;
2018 				lf.l_len = 0;
2019 				lf.l_type = F_UNLCK;
2020 				vp = fp->f_vnode;
2021 				(void) VOP_ADVLOCK(vp,
2022 						   (caddr_t)fdtol->fdl_leader,
2023 						   F_UNLCK, &lf, F_POSIX);
2024 				FILEDESC_XLOCK(fdp);
2025 				fdtol->fdl_holdcount--;
2026 				if (fdtol->fdl_holdcount == 0 &&
2027 				    fdtol->fdl_wakeup != 0) {
2028 					fdtol->fdl_wakeup = 0;
2029 					wakeup(fdtol);
2030 				}
2031 			}
2032 			FILEDESC_XUNLOCK(fdp);
2033 		}
2034 		VFS_UNLOCK_GIANT(vfslocked);
2035 	}
2036 	return (fdrop(fp, td));
2037 }
2038 
2039 /*
2040  * Initialize the file pointer with the specified properties.
2041  *
2042  * The ops are set with release semantics to be certain that the flags, type,
2043  * and data are visible when ops is.  This is to prevent ops methods from being
2044  * called with bad data.
2045  */
2046 void
2047 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2048 {
2049 	fp->f_data = data;
2050 	fp->f_flag = flag;
2051 	fp->f_type = type;
2052 	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2053 }
2054 
2055 struct file *
2056 fget_unlocked(struct filedesc *fdp, int fd)
2057 {
2058 	struct file *fp;
2059 	u_int count;
2060 
2061 	if (fd < 0 || fd >= fdp->fd_nfiles)
2062 		return (NULL);
2063 	/*
2064 	 * Fetch the descriptor locklessly.  We avoid fdrop() races by
2065 	 * never raising a refcount above 0.  To accomplish this we have
2066 	 * to use a cmpset loop rather than an atomic_add.  The descriptor
2067 	 * must be re-verified once we acquire a reference to be certain
2068 	 * that the identity is still correct and we did not lose a race
2069 	 * due to preemption.
2070 	 */
2071 	for (;;) {
2072 		fp = fdp->fd_ofiles[fd];
2073 		if (fp == NULL)
2074 			break;
2075 		count = fp->f_count;
2076 		if (count == 0)
2077 			continue;
2078 		/*
2079 		 * Use an acquire barrier to prevent caching of fd_ofiles
2080 		 * so it is refreshed for verification.
2081 		 */
2082 		if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2083 			continue;
2084 		if (fp == fdp->fd_ofiles[fd])
2085 			break;
2086 		fdrop(fp, curthread);
2087 	}
2088 
2089 	return (fp);
2090 }
2091 
2092 /*
2093  * Extract the file pointer associated with the specified descriptor for the
2094  * current user process.
2095  *
2096  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2097  * returned.
2098  *
2099  * If an error occured the non-zero error is returned and *fpp is set to
2100  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
2101  * responsible for fdrop().
2102  */
2103 static __inline int
2104 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2105 {
2106 	struct filedesc *fdp;
2107 	struct file *fp;
2108 
2109 	*fpp = NULL;
2110 	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2111 		return (EBADF);
2112 	if ((fp = fget_unlocked(fdp, fd)) == NULL)
2113 		return (EBADF);
2114 	if (fp->f_ops == &badfileops) {
2115 		fdrop(fp, td);
2116 		return (EBADF);
2117 	}
2118 	/*
2119 	 * FREAD and FWRITE failure return EBADF as per POSIX.
2120 	 *
2121 	 * Only one flag, or 0, may be specified.
2122 	 */
2123 	if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2124 	    (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2125 		fdrop(fp, td);
2126 		return (EBADF);
2127 	}
2128 	*fpp = fp;
2129 	return (0);
2130 }
2131 
2132 int
2133 fget(struct thread *td, int fd, struct file **fpp)
2134 {
2135 
2136 	return(_fget(td, fd, fpp, 0));
2137 }
2138 
2139 int
2140 fget_read(struct thread *td, int fd, struct file **fpp)
2141 {
2142 
2143 	return(_fget(td, fd, fpp, FREAD));
2144 }
2145 
2146 int
2147 fget_write(struct thread *td, int fd, struct file **fpp)
2148 {
2149 
2150 	return(_fget(td, fd, fpp, FWRITE));
2151 }
2152 
2153 /*
2154  * Like fget() but loads the underlying vnode, or returns an error if the
2155  * descriptor does not represent a vnode.  Note that pipes use vnodes but
2156  * never have VM objects.  The returned vnode will be vref()'d.
2157  *
2158  * XXX: what about the unused flags ?
2159  */
2160 static __inline int
2161 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2162 {
2163 	struct file *fp;
2164 	int error;
2165 
2166 	*vpp = NULL;
2167 	if ((error = _fget(td, fd, &fp, flags)) != 0)
2168 		return (error);
2169 	if (fp->f_vnode == NULL) {
2170 		error = EINVAL;
2171 	} else {
2172 		*vpp = fp->f_vnode;
2173 		vref(*vpp);
2174 	}
2175 	fdrop(fp, td);
2176 
2177 	return (error);
2178 }
2179 
2180 int
2181 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2182 {
2183 
2184 	return (_fgetvp(td, fd, vpp, 0));
2185 }
2186 
2187 int
2188 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2189 {
2190 
2191 	return (_fgetvp(td, fd, vpp, FREAD));
2192 }
2193 
2194 #ifdef notyet
2195 int
2196 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2197 {
2198 
2199 	return (_fgetvp(td, fd, vpp, FWRITE));
2200 }
2201 #endif
2202 
2203 /*
2204  * Like fget() but loads the underlying socket, or returns an error if the
2205  * descriptor does not represent a socket.
2206  *
2207  * We bump the ref count on the returned socket.  XXX Also obtain the SX lock
2208  * in the future.
2209  *
2210  * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2211  * on their file descriptor reference to prevent the socket from being free'd
2212  * during use.
2213  */
2214 int
2215 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2216 {
2217 	struct file *fp;
2218 	int error;
2219 
2220 	*spp = NULL;
2221 	if (fflagp != NULL)
2222 		*fflagp = 0;
2223 	if ((error = _fget(td, fd, &fp, 0)) != 0)
2224 		return (error);
2225 	if (fp->f_type != DTYPE_SOCKET) {
2226 		error = ENOTSOCK;
2227 	} else {
2228 		*spp = fp->f_data;
2229 		if (fflagp)
2230 			*fflagp = fp->f_flag;
2231 		SOCK_LOCK(*spp);
2232 		soref(*spp);
2233 		SOCK_UNLOCK(*spp);
2234 	}
2235 	fdrop(fp, td);
2236 
2237 	return (error);
2238 }
2239 
2240 /*
2241  * Drop the reference count on the socket and XXX release the SX lock in the
2242  * future.  The last reference closes the socket.
2243  *
2244  * Note: fputsock() is deprecated, see comment for fgetsock().
2245  */
2246 void
2247 fputsock(struct socket *so)
2248 {
2249 
2250 	ACCEPT_LOCK();
2251 	SOCK_LOCK(so);
2252 	sorele(so);
2253 }
2254 
2255 /*
2256  * Handle the last reference to a file being closed.
2257  */
2258 int
2259 _fdrop(struct file *fp, struct thread *td)
2260 {
2261 	int error;
2262 
2263 	error = 0;
2264 	if (fp->f_count != 0)
2265 		panic("fdrop: count %d", fp->f_count);
2266 	if (fp->f_ops != &badfileops)
2267 		error = fo_close(fp, td);
2268 	/*
2269 	 * The f_cdevpriv cannot be assigned non-NULL value while we
2270 	 * are destroying the file.
2271 	 */
2272 	if (fp->f_cdevpriv != NULL)
2273 		devfs_fpdrop(fp);
2274 	atomic_subtract_int(&openfiles, 1);
2275 	crfree(fp->f_cred);
2276 	uma_zfree(file_zone, fp);
2277 
2278 	return (error);
2279 }
2280 
2281 /*
2282  * Apply an advisory lock on a file descriptor.
2283  *
2284  * Just attempt to get a record lock of the requested type on the entire file
2285  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2286  */
2287 #ifndef _SYS_SYSPROTO_H_
2288 struct flock_args {
2289 	int	fd;
2290 	int	how;
2291 };
2292 #endif
2293 /* ARGSUSED */
2294 int
2295 flock(struct thread *td, struct flock_args *uap)
2296 {
2297 	struct file *fp;
2298 	struct vnode *vp;
2299 	struct flock lf;
2300 	int vfslocked;
2301 	int error;
2302 
2303 	if ((error = fget(td, uap->fd, &fp)) != 0)
2304 		return (error);
2305 	if (fp->f_type != DTYPE_VNODE) {
2306 		fdrop(fp, td);
2307 		return (EOPNOTSUPP);
2308 	}
2309 
2310 	vp = fp->f_vnode;
2311 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2312 	lf.l_whence = SEEK_SET;
2313 	lf.l_start = 0;
2314 	lf.l_len = 0;
2315 	if (uap->how & LOCK_UN) {
2316 		lf.l_type = F_UNLCK;
2317 		atomic_clear_int(&fp->f_flag, FHASLOCK);
2318 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2319 		goto done2;
2320 	}
2321 	if (uap->how & LOCK_EX)
2322 		lf.l_type = F_WRLCK;
2323 	else if (uap->how & LOCK_SH)
2324 		lf.l_type = F_RDLCK;
2325 	else {
2326 		error = EBADF;
2327 		goto done2;
2328 	}
2329 	atomic_set_int(&fp->f_flag, FHASLOCK);
2330 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2331 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2332 done2:
2333 	fdrop(fp, td);
2334 	VFS_UNLOCK_GIANT(vfslocked);
2335 	return (error);
2336 }
2337 /*
2338  * Duplicate the specified descriptor to a free descriptor.
2339  */
2340 int
2341 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2342 {
2343 	struct file *wfp;
2344 	struct file *fp;
2345 
2346 	/*
2347 	 * If the to-be-dup'd fd number is greater than the allowed number
2348 	 * of file descriptors, or the fd to be dup'd has already been
2349 	 * closed, then reject.
2350 	 */
2351 	FILEDESC_XLOCK(fdp);
2352 	if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2353 	    (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2354 		FILEDESC_XUNLOCK(fdp);
2355 		return (EBADF);
2356 	}
2357 
2358 	/*
2359 	 * There are two cases of interest here.
2360 	 *
2361 	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2362 	 *
2363 	 * For ENXIO steal away the file structure from (dfd) and store it in
2364 	 * (indx).  (dfd) is effectively closed by this operation.
2365 	 *
2366 	 * Any other error code is just returned.
2367 	 */
2368 	switch (error) {
2369 	case ENODEV:
2370 		/*
2371 		 * Check that the mode the file is being opened for is a
2372 		 * subset of the mode of the existing descriptor.
2373 		 */
2374 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2375 			FILEDESC_XUNLOCK(fdp);
2376 			return (EACCES);
2377 		}
2378 		fp = fdp->fd_ofiles[indx];
2379 		fdp->fd_ofiles[indx] = wfp;
2380 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2381 		if (fp == NULL)
2382 			fdused(fdp, indx);
2383 		fhold(wfp);
2384 		FILEDESC_XUNLOCK(fdp);
2385 		if (fp != NULL)
2386 			/*
2387 			 * We now own the reference to fp that the ofiles[]
2388 			 * array used to own.  Release it.
2389 			 */
2390 			fdrop(fp, td);
2391 		return (0);
2392 
2393 	case ENXIO:
2394 		/*
2395 		 * Steal away the file pointer from dfd and stuff it into indx.
2396 		 */
2397 		fp = fdp->fd_ofiles[indx];
2398 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2399 		fdp->fd_ofiles[dfd] = NULL;
2400 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2401 		fdp->fd_ofileflags[dfd] = 0;
2402 		fdunused(fdp, dfd);
2403 		if (fp == NULL)
2404 			fdused(fdp, indx);
2405 		FILEDESC_XUNLOCK(fdp);
2406 
2407 		/*
2408 		 * We now own the reference to fp that the ofiles[] array
2409 		 * used to own.  Release it.
2410 		 */
2411 		if (fp != NULL)
2412 			fdrop(fp, td);
2413 		return (0);
2414 
2415 	default:
2416 		FILEDESC_XUNLOCK(fdp);
2417 		return (error);
2418 	}
2419 	/* NOTREACHED */
2420 }
2421 
2422 /*
2423  * Scan all active processes and prisons to see if any of them have a current
2424  * or root directory of `olddp'. If so, replace them with the new mount point.
2425  */
2426 void
2427 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2428 {
2429 	struct filedesc *fdp;
2430 	struct prison *pr;
2431 	struct proc *p;
2432 	int nrele;
2433 
2434 	if (vrefcnt(olddp) == 1)
2435 		return;
2436 	nrele = 0;
2437 	sx_slock(&allproc_lock);
2438 	FOREACH_PROC_IN_SYSTEM(p) {
2439 		fdp = fdhold(p);
2440 		if (fdp == NULL)
2441 			continue;
2442 		FILEDESC_XLOCK(fdp);
2443 		if (fdp->fd_cdir == olddp) {
2444 			vref(newdp);
2445 			fdp->fd_cdir = newdp;
2446 			nrele++;
2447 		}
2448 		if (fdp->fd_rdir == olddp) {
2449 			vref(newdp);
2450 			fdp->fd_rdir = newdp;
2451 			nrele++;
2452 		}
2453 		if (fdp->fd_jdir == olddp) {
2454 			vref(newdp);
2455 			fdp->fd_jdir = newdp;
2456 			nrele++;
2457 		}
2458 		FILEDESC_XUNLOCK(fdp);
2459 		fddrop(fdp);
2460 	}
2461 	sx_sunlock(&allproc_lock);
2462 	if (rootvnode == olddp) {
2463 		vref(newdp);
2464 		rootvnode = newdp;
2465 		nrele++;
2466 	}
2467 	mtx_lock(&prison0.pr_mtx);
2468 	if (prison0.pr_root == olddp) {
2469 		vref(newdp);
2470 		prison0.pr_root = newdp;
2471 		nrele++;
2472 	}
2473 	mtx_unlock(&prison0.pr_mtx);
2474 	sx_slock(&allprison_lock);
2475 	TAILQ_FOREACH(pr, &allprison, pr_list) {
2476 		mtx_lock(&pr->pr_mtx);
2477 		if (pr->pr_root == olddp) {
2478 			vref(newdp);
2479 			pr->pr_root = newdp;
2480 			nrele++;
2481 		}
2482 		mtx_unlock(&pr->pr_mtx);
2483 	}
2484 	sx_sunlock(&allprison_lock);
2485 	while (nrele--)
2486 		vrele(olddp);
2487 }
2488 
2489 struct filedesc_to_leader *
2490 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2491 {
2492 	struct filedesc_to_leader *fdtol;
2493 
2494 	fdtol = malloc(sizeof(struct filedesc_to_leader),
2495 	       M_FILEDESC_TO_LEADER,
2496 	       M_WAITOK);
2497 	fdtol->fdl_refcount = 1;
2498 	fdtol->fdl_holdcount = 0;
2499 	fdtol->fdl_wakeup = 0;
2500 	fdtol->fdl_leader = leader;
2501 	if (old != NULL) {
2502 		FILEDESC_XLOCK(fdp);
2503 		fdtol->fdl_next = old->fdl_next;
2504 		fdtol->fdl_prev = old;
2505 		old->fdl_next = fdtol;
2506 		fdtol->fdl_next->fdl_prev = fdtol;
2507 		FILEDESC_XUNLOCK(fdp);
2508 	} else {
2509 		fdtol->fdl_next = fdtol;
2510 		fdtol->fdl_prev = fdtol;
2511 	}
2512 	return (fdtol);
2513 }
2514 
2515 /*
2516  * Get file structures globally.
2517  */
2518 static int
2519 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2520 {
2521 	struct xfile xf;
2522 	struct filedesc *fdp;
2523 	struct file *fp;
2524 	struct proc *p;
2525 	int error, n;
2526 
2527 	error = sysctl_wire_old_buffer(req, 0);
2528 	if (error != 0)
2529 		return (error);
2530 	if (req->oldptr == NULL) {
2531 		n = 0;
2532 		sx_slock(&allproc_lock);
2533 		FOREACH_PROC_IN_SYSTEM(p) {
2534 			if (p->p_state == PRS_NEW)
2535 				continue;
2536 			fdp = fdhold(p);
2537 			if (fdp == NULL)
2538 				continue;
2539 			/* overestimates sparse tables. */
2540 			if (fdp->fd_lastfile > 0)
2541 				n += fdp->fd_lastfile;
2542 			fddrop(fdp);
2543 		}
2544 		sx_sunlock(&allproc_lock);
2545 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2546 	}
2547 	error = 0;
2548 	bzero(&xf, sizeof(xf));
2549 	xf.xf_size = sizeof(xf);
2550 	sx_slock(&allproc_lock);
2551 	FOREACH_PROC_IN_SYSTEM(p) {
2552 		if (p->p_state == PRS_NEW)
2553 			continue;
2554 		PROC_LOCK(p);
2555 		if (p_cansee(req->td, p) != 0) {
2556 			PROC_UNLOCK(p);
2557 			continue;
2558 		}
2559 		xf.xf_pid = p->p_pid;
2560 		xf.xf_uid = p->p_ucred->cr_uid;
2561 		PROC_UNLOCK(p);
2562 		fdp = fdhold(p);
2563 		if (fdp == NULL)
2564 			continue;
2565 		FILEDESC_SLOCK(fdp);
2566 		for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2567 			if ((fp = fdp->fd_ofiles[n]) == NULL)
2568 				continue;
2569 			xf.xf_fd = n;
2570 			xf.xf_file = fp;
2571 			xf.xf_data = fp->f_data;
2572 			xf.xf_vnode = fp->f_vnode;
2573 			xf.xf_type = fp->f_type;
2574 			xf.xf_count = fp->f_count;
2575 			xf.xf_msgcount = 0;
2576 			xf.xf_offset = fp->f_offset;
2577 			xf.xf_flag = fp->f_flag;
2578 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
2579 			if (error)
2580 				break;
2581 		}
2582 		FILEDESC_SUNLOCK(fdp);
2583 		fddrop(fdp);
2584 		if (error)
2585 			break;
2586 	}
2587 	sx_sunlock(&allproc_lock);
2588 	return (error);
2589 }
2590 
2591 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2592     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2593 
2594 #ifdef KINFO_OFILE_SIZE
2595 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2596 #endif
2597 
2598 #ifdef COMPAT_FREEBSD7
2599 static int
2600 export_vnode_for_osysctl(struct vnode *vp, int type,
2601     struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2602 {
2603 	int error;
2604 	char *fullpath, *freepath;
2605 	int vfslocked;
2606 
2607 	bzero(kif, sizeof(*kif));
2608 	kif->kf_structsize = sizeof(*kif);
2609 
2610 	vref(vp);
2611 	kif->kf_fd = type;
2612 	kif->kf_type = KF_TYPE_VNODE;
2613 	/* This function only handles directories. */
2614 	if (vp->v_type != VDIR) {
2615 		vrele(vp);
2616 		return (ENOTDIR);
2617 	}
2618 	kif->kf_vnode_type = KF_VTYPE_VDIR;
2619 
2620 	/*
2621 	 * This is not a true file descriptor, so we set a bogus refcount
2622 	 * and offset to indicate these fields should be ignored.
2623 	 */
2624 	kif->kf_ref_count = -1;
2625 	kif->kf_offset = -1;
2626 
2627 	freepath = NULL;
2628 	fullpath = "-";
2629 	FILEDESC_SUNLOCK(fdp);
2630 	vn_fullpath(curthread, vp, &fullpath, &freepath);
2631 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2632 	vrele(vp);
2633 	VFS_UNLOCK_GIANT(vfslocked);
2634 	strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2635 	if (freepath != NULL)
2636 		free(freepath, M_TEMP);
2637 	error = SYSCTL_OUT(req, kif, sizeof(*kif));
2638 	FILEDESC_SLOCK(fdp);
2639 	return (error);
2640 }
2641 
2642 /*
2643  * Get per-process file descriptors for use by procstat(1), et al.
2644  */
2645 static int
2646 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2647 {
2648 	char *fullpath, *freepath;
2649 	struct kinfo_ofile *kif;
2650 	struct filedesc *fdp;
2651 	int error, i, *name;
2652 	struct socket *so;
2653 	struct vnode *vp;
2654 	struct file *fp;
2655 	struct proc *p;
2656 	struct tty *tp;
2657 	int vfslocked;
2658 
2659 	name = (int *)arg1;
2660 	if ((p = pfind((pid_t)name[0])) == NULL)
2661 		return (ESRCH);
2662 	if ((error = p_candebug(curthread, p))) {
2663 		PROC_UNLOCK(p);
2664 		return (error);
2665 	}
2666 	fdp = fdhold(p);
2667 	PROC_UNLOCK(p);
2668 	if (fdp == NULL)
2669 		return (ENOENT);
2670 	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2671 	FILEDESC_SLOCK(fdp);
2672 	if (fdp->fd_cdir != NULL)
2673 		export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2674 				fdp, req);
2675 	if (fdp->fd_rdir != NULL)
2676 		export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2677 				fdp, req);
2678 	if (fdp->fd_jdir != NULL)
2679 		export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2680 				fdp, req);
2681 	for (i = 0; i < fdp->fd_nfiles; i++) {
2682 		if ((fp = fdp->fd_ofiles[i]) == NULL)
2683 			continue;
2684 		bzero(kif, sizeof(*kif));
2685 		kif->kf_structsize = sizeof(*kif);
2686 		vp = NULL;
2687 		so = NULL;
2688 		tp = NULL;
2689 		kif->kf_fd = i;
2690 		switch (fp->f_type) {
2691 		case DTYPE_VNODE:
2692 			kif->kf_type = KF_TYPE_VNODE;
2693 			vp = fp->f_vnode;
2694 			break;
2695 
2696 		case DTYPE_SOCKET:
2697 			kif->kf_type = KF_TYPE_SOCKET;
2698 			so = fp->f_data;
2699 			break;
2700 
2701 		case DTYPE_PIPE:
2702 			kif->kf_type = KF_TYPE_PIPE;
2703 			break;
2704 
2705 		case DTYPE_FIFO:
2706 			kif->kf_type = KF_TYPE_FIFO;
2707 			vp = fp->f_vnode;
2708 			vref(vp);
2709 			break;
2710 
2711 		case DTYPE_KQUEUE:
2712 			kif->kf_type = KF_TYPE_KQUEUE;
2713 			break;
2714 
2715 		case DTYPE_CRYPTO:
2716 			kif->kf_type = KF_TYPE_CRYPTO;
2717 			break;
2718 
2719 		case DTYPE_MQUEUE:
2720 			kif->kf_type = KF_TYPE_MQUEUE;
2721 			break;
2722 
2723 		case DTYPE_SHM:
2724 			kif->kf_type = KF_TYPE_SHM;
2725 			break;
2726 
2727 		case DTYPE_SEM:
2728 			kif->kf_type = KF_TYPE_SEM;
2729 			break;
2730 
2731 		case DTYPE_PTS:
2732 			kif->kf_type = KF_TYPE_PTS;
2733 			tp = fp->f_data;
2734 			break;
2735 
2736 		default:
2737 			kif->kf_type = KF_TYPE_UNKNOWN;
2738 			break;
2739 		}
2740 		kif->kf_ref_count = fp->f_count;
2741 		if (fp->f_flag & FREAD)
2742 			kif->kf_flags |= KF_FLAG_READ;
2743 		if (fp->f_flag & FWRITE)
2744 			kif->kf_flags |= KF_FLAG_WRITE;
2745 		if (fp->f_flag & FAPPEND)
2746 			kif->kf_flags |= KF_FLAG_APPEND;
2747 		if (fp->f_flag & FASYNC)
2748 			kif->kf_flags |= KF_FLAG_ASYNC;
2749 		if (fp->f_flag & FFSYNC)
2750 			kif->kf_flags |= KF_FLAG_FSYNC;
2751 		if (fp->f_flag & FNONBLOCK)
2752 			kif->kf_flags |= KF_FLAG_NONBLOCK;
2753 		if (fp->f_flag & O_DIRECT)
2754 			kif->kf_flags |= KF_FLAG_DIRECT;
2755 		if (fp->f_flag & FHASLOCK)
2756 			kif->kf_flags |= KF_FLAG_HASLOCK;
2757 		kif->kf_offset = fp->f_offset;
2758 		if (vp != NULL) {
2759 			vref(vp);
2760 			switch (vp->v_type) {
2761 			case VNON:
2762 				kif->kf_vnode_type = KF_VTYPE_VNON;
2763 				break;
2764 			case VREG:
2765 				kif->kf_vnode_type = KF_VTYPE_VREG;
2766 				break;
2767 			case VDIR:
2768 				kif->kf_vnode_type = KF_VTYPE_VDIR;
2769 				break;
2770 			case VBLK:
2771 				kif->kf_vnode_type = KF_VTYPE_VBLK;
2772 				break;
2773 			case VCHR:
2774 				kif->kf_vnode_type = KF_VTYPE_VCHR;
2775 				break;
2776 			case VLNK:
2777 				kif->kf_vnode_type = KF_VTYPE_VLNK;
2778 				break;
2779 			case VSOCK:
2780 				kif->kf_vnode_type = KF_VTYPE_VSOCK;
2781 				break;
2782 			case VFIFO:
2783 				kif->kf_vnode_type = KF_VTYPE_VFIFO;
2784 				break;
2785 			case VBAD:
2786 				kif->kf_vnode_type = KF_VTYPE_VBAD;
2787 				break;
2788 			default:
2789 				kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2790 				break;
2791 			}
2792 			/*
2793 			 * It is OK to drop the filedesc lock here as we will
2794 			 * re-validate and re-evaluate its properties when
2795 			 * the loop continues.
2796 			 */
2797 			freepath = NULL;
2798 			fullpath = "-";
2799 			FILEDESC_SUNLOCK(fdp);
2800 			vn_fullpath(curthread, vp, &fullpath, &freepath);
2801 			vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2802 			vrele(vp);
2803 			VFS_UNLOCK_GIANT(vfslocked);
2804 			strlcpy(kif->kf_path, fullpath,
2805 			    sizeof(kif->kf_path));
2806 			if (freepath != NULL)
2807 				free(freepath, M_TEMP);
2808 			FILEDESC_SLOCK(fdp);
2809 		}
2810 		if (so != NULL) {
2811 			struct sockaddr *sa;
2812 
2813 			if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2814 			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2815 				bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2816 				free(sa, M_SONAME);
2817 			}
2818 			if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2819 			    == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2820 				bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2821 				free(sa, M_SONAME);
2822 			}
2823 			kif->kf_sock_domain =
2824 			    so->so_proto->pr_domain->dom_family;
2825 			kif->kf_sock_type = so->so_type;
2826 			kif->kf_sock_protocol = so->so_proto->pr_protocol;
2827 		}
2828 		if (tp != NULL) {
2829 			strlcpy(kif->kf_path, tty_devname(tp),
2830 			    sizeof(kif->kf_path));
2831 		}
2832 		error = SYSCTL_OUT(req, kif, sizeof(*kif));
2833 		if (error)
2834 			break;
2835 	}
2836 	FILEDESC_SUNLOCK(fdp);
2837 	fddrop(fdp);
2838 	free(kif, M_TEMP);
2839 	return (0);
2840 }
2841 
2842 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2843     sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2844 #endif	/* COMPAT_FREEBSD7 */
2845 
2846 #ifdef KINFO_FILE_SIZE
2847 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2848 #endif
2849 
2850 static int
2851 export_vnode_for_sysctl(struct vnode *vp, int type,
2852     struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2853 {
2854 	int error;
2855 	char *fullpath, *freepath;
2856 	int vfslocked;
2857 
2858 	bzero(kif, sizeof(*kif));
2859 
2860 	vref(vp);
2861 	kif->kf_fd = type;
2862 	kif->kf_type = KF_TYPE_VNODE;
2863 	/* This function only handles directories. */
2864 	if (vp->v_type != VDIR) {
2865 		vrele(vp);
2866 		return (ENOTDIR);
2867 	}
2868 	kif->kf_vnode_type = KF_VTYPE_VDIR;
2869 
2870 	/*
2871 	 * This is not a true file descriptor, so we set a bogus refcount
2872 	 * and offset to indicate these fields should be ignored.
2873 	 */
2874 	kif->kf_ref_count = -1;
2875 	kif->kf_offset = -1;
2876 
2877 	freepath = NULL;
2878 	fullpath = "-";
2879 	FILEDESC_SUNLOCK(fdp);
2880 	vn_fullpath(curthread, vp, &fullpath, &freepath);
2881 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2882 	vrele(vp);
2883 	VFS_UNLOCK_GIANT(vfslocked);
2884 	strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2885 	if (freepath != NULL)
2886 		free(freepath, M_TEMP);
2887 	/* Pack record size down */
2888 	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2889 	    strlen(kif->kf_path) + 1;
2890 	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2891 	error = SYSCTL_OUT(req, kif, kif->kf_structsize);
2892 	FILEDESC_SLOCK(fdp);
2893 	return (error);
2894 }
2895 
2896 /*
2897  * Get per-process file descriptors for use by procstat(1), et al.
2898  */
2899 static int
2900 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
2901 {
2902 	char *fullpath, *freepath;
2903 	struct kinfo_file *kif;
2904 	struct filedesc *fdp;
2905 	int error, i, *name;
2906 	struct socket *so;
2907 	struct vnode *vp;
2908 	struct file *fp;
2909 	struct proc *p;
2910 	struct tty *tp;
2911 	int vfslocked;
2912 	size_t oldidx;
2913 
2914 	name = (int *)arg1;
2915 	if ((p = pfind((pid_t)name[0])) == NULL)
2916 		return (ESRCH);
2917 	if ((error = p_candebug(curthread, p))) {
2918 		PROC_UNLOCK(p);
2919 		return (error);
2920 	}
2921 	fdp = fdhold(p);
2922 	PROC_UNLOCK(p);
2923 	if (fdp == NULL)
2924 		return (ENOENT);
2925 	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2926 	FILEDESC_SLOCK(fdp);
2927 	if (fdp->fd_cdir != NULL)
2928 		export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2929 				fdp, req);
2930 	if (fdp->fd_rdir != NULL)
2931 		export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2932 				fdp, req);
2933 	if (fdp->fd_jdir != NULL)
2934 		export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2935 				fdp, req);
2936 	for (i = 0; i < fdp->fd_nfiles; i++) {
2937 		if ((fp = fdp->fd_ofiles[i]) == NULL)
2938 			continue;
2939 		bzero(kif, sizeof(*kif));
2940 		vp = NULL;
2941 		so = NULL;
2942 		tp = NULL;
2943 		kif->kf_fd = i;
2944 		switch (fp->f_type) {
2945 		case DTYPE_VNODE:
2946 			kif->kf_type = KF_TYPE_VNODE;
2947 			vp = fp->f_vnode;
2948 			break;
2949 
2950 		case DTYPE_SOCKET:
2951 			kif->kf_type = KF_TYPE_SOCKET;
2952 			so = fp->f_data;
2953 			break;
2954 
2955 		case DTYPE_PIPE:
2956 			kif->kf_type = KF_TYPE_PIPE;
2957 			break;
2958 
2959 		case DTYPE_FIFO:
2960 			kif->kf_type = KF_TYPE_FIFO;
2961 			vp = fp->f_vnode;
2962 			vref(vp);
2963 			break;
2964 
2965 		case DTYPE_KQUEUE:
2966 			kif->kf_type = KF_TYPE_KQUEUE;
2967 			break;
2968 
2969 		case DTYPE_CRYPTO:
2970 			kif->kf_type = KF_TYPE_CRYPTO;
2971 			break;
2972 
2973 		case DTYPE_MQUEUE:
2974 			kif->kf_type = KF_TYPE_MQUEUE;
2975 			break;
2976 
2977 		case DTYPE_SHM:
2978 			kif->kf_type = KF_TYPE_SHM;
2979 			break;
2980 
2981 		case DTYPE_SEM:
2982 			kif->kf_type = KF_TYPE_SEM;
2983 			break;
2984 
2985 		case DTYPE_PTS:
2986 			kif->kf_type = KF_TYPE_PTS;
2987 			tp = fp->f_data;
2988 			break;
2989 
2990 		default:
2991 			kif->kf_type = KF_TYPE_UNKNOWN;
2992 			break;
2993 		}
2994 		kif->kf_ref_count = fp->f_count;
2995 		if (fp->f_flag & FREAD)
2996 			kif->kf_flags |= KF_FLAG_READ;
2997 		if (fp->f_flag & FWRITE)
2998 			kif->kf_flags |= KF_FLAG_WRITE;
2999 		if (fp->f_flag & FAPPEND)
3000 			kif->kf_flags |= KF_FLAG_APPEND;
3001 		if (fp->f_flag & FASYNC)
3002 			kif->kf_flags |= KF_FLAG_ASYNC;
3003 		if (fp->f_flag & FFSYNC)
3004 			kif->kf_flags |= KF_FLAG_FSYNC;
3005 		if (fp->f_flag & FNONBLOCK)
3006 			kif->kf_flags |= KF_FLAG_NONBLOCK;
3007 		if (fp->f_flag & O_DIRECT)
3008 			kif->kf_flags |= KF_FLAG_DIRECT;
3009 		if (fp->f_flag & FHASLOCK)
3010 			kif->kf_flags |= KF_FLAG_HASLOCK;
3011 		kif->kf_offset = fp->f_offset;
3012 		if (vp != NULL) {
3013 			vref(vp);
3014 			switch (vp->v_type) {
3015 			case VNON:
3016 				kif->kf_vnode_type = KF_VTYPE_VNON;
3017 				break;
3018 			case VREG:
3019 				kif->kf_vnode_type = KF_VTYPE_VREG;
3020 				break;
3021 			case VDIR:
3022 				kif->kf_vnode_type = KF_VTYPE_VDIR;
3023 				break;
3024 			case VBLK:
3025 				kif->kf_vnode_type = KF_VTYPE_VBLK;
3026 				break;
3027 			case VCHR:
3028 				kif->kf_vnode_type = KF_VTYPE_VCHR;
3029 				break;
3030 			case VLNK:
3031 				kif->kf_vnode_type = KF_VTYPE_VLNK;
3032 				break;
3033 			case VSOCK:
3034 				kif->kf_vnode_type = KF_VTYPE_VSOCK;
3035 				break;
3036 			case VFIFO:
3037 				kif->kf_vnode_type = KF_VTYPE_VFIFO;
3038 				break;
3039 			case VBAD:
3040 				kif->kf_vnode_type = KF_VTYPE_VBAD;
3041 				break;
3042 			default:
3043 				kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3044 				break;
3045 			}
3046 			/*
3047 			 * It is OK to drop the filedesc lock here as we will
3048 			 * re-validate and re-evaluate its properties when
3049 			 * the loop continues.
3050 			 */
3051 			freepath = NULL;
3052 			fullpath = "-";
3053 			FILEDESC_SUNLOCK(fdp);
3054 			vn_fullpath(curthread, vp, &fullpath, &freepath);
3055 			vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3056 			vrele(vp);
3057 			VFS_UNLOCK_GIANT(vfslocked);
3058 			strlcpy(kif->kf_path, fullpath,
3059 			    sizeof(kif->kf_path));
3060 			if (freepath != NULL)
3061 				free(freepath, M_TEMP);
3062 			FILEDESC_SLOCK(fdp);
3063 		}
3064 		if (so != NULL) {
3065 			struct sockaddr *sa;
3066 
3067 			if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3068 			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3069 				bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3070 				free(sa, M_SONAME);
3071 			}
3072 			if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3073 			    == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3074 				bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3075 				free(sa, M_SONAME);
3076 			}
3077 			kif->kf_sock_domain =
3078 			    so->so_proto->pr_domain->dom_family;
3079 			kif->kf_sock_type = so->so_type;
3080 			kif->kf_sock_protocol = so->so_proto->pr_protocol;
3081 		}
3082 		if (tp != NULL) {
3083 			strlcpy(kif->kf_path, tty_devname(tp),
3084 			    sizeof(kif->kf_path));
3085 		}
3086 		/* Pack record size down */
3087 		kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3088 		    strlen(kif->kf_path) + 1;
3089 		kif->kf_structsize = roundup(kif->kf_structsize,
3090 		    sizeof(uint64_t));
3091 		oldidx = req->oldidx;
3092 		error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3093 		if (error) {
3094 			if (error == ENOMEM) {
3095 				/*
3096 				 * The hack to keep the ABI of sysctl
3097 				 * kern.proc.filedesc intact, but not
3098 				 * to account a partially copied
3099 				 * kinfo_file into the oldidx.
3100 				 */
3101 				req->oldidx = oldidx;
3102 				error = 0;
3103 			}
3104 			break;
3105 		}
3106 	}
3107 	FILEDESC_SUNLOCK(fdp);
3108 	fddrop(fdp);
3109 	free(kif, M_TEMP);
3110 	return (error);
3111 }
3112 
3113 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3114     sysctl_kern_proc_filedesc, "Process filedesc entries");
3115 
3116 #ifdef DDB
3117 /*
3118  * For the purposes of debugging, generate a human-readable string for the
3119  * file type.
3120  */
3121 static const char *
3122 file_type_to_name(short type)
3123 {
3124 
3125 	switch (type) {
3126 	case 0:
3127 		return ("zero");
3128 	case DTYPE_VNODE:
3129 		return ("vnod");
3130 	case DTYPE_SOCKET:
3131 		return ("sock");
3132 	case DTYPE_PIPE:
3133 		return ("pipe");
3134 	case DTYPE_FIFO:
3135 		return ("fifo");
3136 	case DTYPE_KQUEUE:
3137 		return ("kque");
3138 	case DTYPE_CRYPTO:
3139 		return ("crpt");
3140 	case DTYPE_MQUEUE:
3141 		return ("mque");
3142 	case DTYPE_SHM:
3143 		return ("shm");
3144 	case DTYPE_SEM:
3145 		return ("ksem");
3146 	default:
3147 		return ("unkn");
3148 	}
3149 }
3150 
3151 /*
3152  * For the purposes of debugging, identify a process (if any, perhaps one of
3153  * many) that references the passed file in its file descriptor array. Return
3154  * NULL if none.
3155  */
3156 static struct proc *
3157 file_to_first_proc(struct file *fp)
3158 {
3159 	struct filedesc *fdp;
3160 	struct proc *p;
3161 	int n;
3162 
3163 	FOREACH_PROC_IN_SYSTEM(p) {
3164 		if (p->p_state == PRS_NEW)
3165 			continue;
3166 		fdp = p->p_fd;
3167 		if (fdp == NULL)
3168 			continue;
3169 		for (n = 0; n < fdp->fd_nfiles; n++) {
3170 			if (fp == fdp->fd_ofiles[n])
3171 				return (p);
3172 		}
3173 	}
3174 	return (NULL);
3175 }
3176 
3177 static void
3178 db_print_file(struct file *fp, int header)
3179 {
3180 	struct proc *p;
3181 
3182 	if (header)
3183 		db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3184 		    "File", "Type", "Data", "Flag", "GCFl", "Count",
3185 		    "MCount", "Vnode", "FPID", "FCmd");
3186 	p = file_to_first_proc(fp);
3187 	db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3188 	    file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3189 	    0, fp->f_count, 0, fp->f_vnode,
3190 	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3191 }
3192 
3193 DB_SHOW_COMMAND(file, db_show_file)
3194 {
3195 	struct file *fp;
3196 
3197 	if (!have_addr) {
3198 		db_printf("usage: show file <addr>\n");
3199 		return;
3200 	}
3201 	fp = (struct file *)addr;
3202 	db_print_file(fp, 1);
3203 }
3204 
3205 DB_SHOW_COMMAND(files, db_show_files)
3206 {
3207 	struct filedesc *fdp;
3208 	struct file *fp;
3209 	struct proc *p;
3210 	int header;
3211 	int n;
3212 
3213 	header = 1;
3214 	FOREACH_PROC_IN_SYSTEM(p) {
3215 		if (p->p_state == PRS_NEW)
3216 			continue;
3217 		if ((fdp = p->p_fd) == NULL)
3218 			continue;
3219 		for (n = 0; n < fdp->fd_nfiles; ++n) {
3220 			if ((fp = fdp->fd_ofiles[n]) == NULL)
3221 				continue;
3222 			db_print_file(fp, header);
3223 			header = 0;
3224 		}
3225 	}
3226 }
3227 #endif
3228 
3229 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3230     &maxfilesperproc, 0, "Maximum files allowed open per process");
3231 
3232 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3233     &maxfiles, 0, "Maximum number of files");
3234 
3235 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3236     __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3237 
3238 /* ARGSUSED*/
3239 static void
3240 filelistinit(void *dummy)
3241 {
3242 
3243 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3244 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3245 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3246 	mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3247 }
3248 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3249 
3250 /*-------------------------------------------------------------------*/
3251 
3252 static int
3253 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3254 {
3255 
3256 	return (EBADF);
3257 }
3258 
3259 static int
3260 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3261 {
3262 
3263 	return (EINVAL);
3264 }
3265 
3266 static int
3267 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3268 {
3269 
3270 	return (EBADF);
3271 }
3272 
3273 static int
3274 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3275 {
3276 
3277 	return (0);
3278 }
3279 
3280 static int
3281 badfo_kqfilter(struct file *fp, struct knote *kn)
3282 {
3283 
3284 	return (EBADF);
3285 }
3286 
3287 static int
3288 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3289 {
3290 
3291 	return (EBADF);
3292 }
3293 
3294 static int
3295 badfo_close(struct file *fp, struct thread *td)
3296 {
3297 
3298 	return (EBADF);
3299 }
3300 
3301 struct fileops badfileops = {
3302 	.fo_read = badfo_readwrite,
3303 	.fo_write = badfo_readwrite,
3304 	.fo_truncate = badfo_truncate,
3305 	.fo_ioctl = badfo_ioctl,
3306 	.fo_poll = badfo_poll,
3307 	.fo_kqfilter = badfo_kqfilter,
3308 	.fo_stat = badfo_stat,
3309 	.fo_close = badfo_close,
3310 };
3311 
3312 
3313 /*-------------------------------------------------------------------*/
3314 
3315 /*
3316  * File Descriptor pseudo-device driver (/dev/fd/).
3317  *
3318  * Opening minor device N dup()s the file (if any) connected to file
3319  * descriptor N belonging to the calling process.  Note that this driver
3320  * consists of only the ``open()'' routine, because all subsequent
3321  * references to this file will be direct to the other driver.
3322  *
3323  * XXX: we could give this one a cloning event handler if necessary.
3324  */
3325 
3326 /* ARGSUSED */
3327 static int
3328 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3329 {
3330 
3331 	/*
3332 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3333 	 * the file descriptor being sought for duplication. The error
3334 	 * return ensures that the vnode for this device will be released
3335 	 * by vn_open. Open will detect this special error and take the
3336 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3337 	 * will simply report the error.
3338 	 */
3339 	td->td_dupfd = dev2unit(dev);
3340 	return (ENODEV);
3341 }
3342 
3343 static struct cdevsw fildesc_cdevsw = {
3344 	.d_version =	D_VERSION,
3345 	.d_open =	fdopen,
3346 	.d_name =	"FD",
3347 };
3348 
3349 static void
3350 fildesc_drvinit(void *unused)
3351 {
3352 	struct cdev *dev;
3353 
3354 	dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
3355 	make_dev_alias(dev, "stdin");
3356 	dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
3357 	make_dev_alias(dev, "stdout");
3358 	dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
3359 	make_dev_alias(dev, "stderr");
3360 }
3361 
3362 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
3363