xref: /freebsd/sys/kern/kern_descrip.c (revision 5861f9665471e98e544f6fa3ce73c4912229ff82)
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 /*
1132  * Close open file descriptors.
1133  */
1134 #ifndef _SYS_SYSPROTO_H_
1135 struct closefrom_args {
1136 	int	lowfd;
1137 };
1138 #endif
1139 /* ARGSUSED */
1140 int
1141 closefrom(struct thread *td, struct closefrom_args *uap)
1142 {
1143 	struct filedesc *fdp;
1144 	int fd;
1145 
1146 	fdp = td->td_proc->p_fd;
1147 	AUDIT_ARG_FD(uap->lowfd);
1148 
1149 	/*
1150 	 * Treat negative starting file descriptor values identical to
1151 	 * closefrom(0) which closes all files.
1152 	 */
1153 	if (uap->lowfd < 0)
1154 		uap->lowfd = 0;
1155 	FILEDESC_SLOCK(fdp);
1156 	for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1157 		if (fdp->fd_ofiles[fd] != NULL) {
1158 			FILEDESC_SUNLOCK(fdp);
1159 			(void)kern_close(td, fd);
1160 			FILEDESC_SLOCK(fdp);
1161 		}
1162 	}
1163 	FILEDESC_SUNLOCK(fdp);
1164 	return (0);
1165 }
1166 
1167 #if defined(COMPAT_43)
1168 /*
1169  * Return status information about a file descriptor.
1170  */
1171 #ifndef _SYS_SYSPROTO_H_
1172 struct ofstat_args {
1173 	int	fd;
1174 	struct	ostat *sb;
1175 };
1176 #endif
1177 /* ARGSUSED */
1178 int
1179 ofstat(struct thread *td, struct ofstat_args *uap)
1180 {
1181 	struct ostat oub;
1182 	struct stat ub;
1183 	int error;
1184 
1185 	error = kern_fstat(td, uap->fd, &ub);
1186 	if (error == 0) {
1187 		cvtstat(&ub, &oub);
1188 		error = copyout(&oub, uap->sb, sizeof(oub));
1189 	}
1190 	return (error);
1191 }
1192 #endif /* COMPAT_43 */
1193 
1194 /*
1195  * Return status information about a file descriptor.
1196  */
1197 #ifndef _SYS_SYSPROTO_H_
1198 struct fstat_args {
1199 	int	fd;
1200 	struct	stat *sb;
1201 };
1202 #endif
1203 /* ARGSUSED */
1204 int
1205 fstat(struct thread *td, struct fstat_args *uap)
1206 {
1207 	struct stat ub;
1208 	int error;
1209 
1210 	error = kern_fstat(td, uap->fd, &ub);
1211 	if (error == 0)
1212 		error = copyout(&ub, uap->sb, sizeof(ub));
1213 	return (error);
1214 }
1215 
1216 int
1217 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1218 {
1219 	struct file *fp;
1220 	int error;
1221 
1222 	AUDIT_ARG_FD(fd);
1223 
1224 	if ((error = fget(td, fd, &fp)) != 0)
1225 		return (error);
1226 
1227 	AUDIT_ARG_FILE(td->td_proc, fp);
1228 
1229 	error = fo_stat(fp, sbp, td->td_ucred, td);
1230 	fdrop(fp, td);
1231 #ifdef KTRACE
1232 	if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1233 		ktrstat(sbp);
1234 #endif
1235 	return (error);
1236 }
1237 
1238 /*
1239  * Return status information about a file descriptor.
1240  */
1241 #ifndef _SYS_SYSPROTO_H_
1242 struct nfstat_args {
1243 	int	fd;
1244 	struct	nstat *sb;
1245 };
1246 #endif
1247 /* ARGSUSED */
1248 int
1249 nfstat(struct thread *td, struct nfstat_args *uap)
1250 {
1251 	struct nstat nub;
1252 	struct stat ub;
1253 	int error;
1254 
1255 	error = kern_fstat(td, uap->fd, &ub);
1256 	if (error == 0) {
1257 		cvtnstat(&ub, &nub);
1258 		error = copyout(&nub, uap->sb, sizeof(nub));
1259 	}
1260 	return (error);
1261 }
1262 
1263 /*
1264  * Return pathconf information about a file descriptor.
1265  */
1266 #ifndef _SYS_SYSPROTO_H_
1267 struct fpathconf_args {
1268 	int	fd;
1269 	int	name;
1270 };
1271 #endif
1272 /* ARGSUSED */
1273 int
1274 fpathconf(struct thread *td, struct fpathconf_args *uap)
1275 {
1276 	struct file *fp;
1277 	struct vnode *vp;
1278 	int error;
1279 
1280 	if ((error = fget(td, uap->fd, &fp)) != 0)
1281 		return (error);
1282 
1283 	/* If asynchronous I/O is available, it works for all descriptors. */
1284 	if (uap->name == _PC_ASYNC_IO) {
1285 		td->td_retval[0] = async_io_version;
1286 		goto out;
1287 	}
1288 	vp = fp->f_vnode;
1289 	if (vp != NULL) {
1290 		int vfslocked;
1291 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1292 		vn_lock(vp, LK_SHARED | LK_RETRY);
1293 		error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1294 		VOP_UNLOCK(vp, 0);
1295 		VFS_UNLOCK_GIANT(vfslocked);
1296 	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1297 		if (uap->name != _PC_PIPE_BUF) {
1298 			error = EINVAL;
1299 		} else {
1300 			td->td_retval[0] = PIPE_BUF;
1301 		error = 0;
1302 		}
1303 	} else {
1304 		error = EOPNOTSUPP;
1305 	}
1306 out:
1307 	fdrop(fp, td);
1308 	return (error);
1309 }
1310 
1311 /*
1312  * Grow the file table to accomodate (at least) nfd descriptors.  This may
1313  * block and drop the filedesc lock, but it will reacquire it before
1314  * returning.
1315  */
1316 static void
1317 fdgrowtable(struct filedesc *fdp, int nfd)
1318 {
1319 	struct filedesc0 *fdp0;
1320 	struct freetable *fo;
1321 	struct file **ntable;
1322 	struct file **otable;
1323 	char *nfileflags;
1324 	int nnfiles, onfiles;
1325 	NDSLOTTYPE *nmap;
1326 
1327 	FILEDESC_XLOCK_ASSERT(fdp);
1328 
1329 	KASSERT(fdp->fd_nfiles > 0,
1330 	    ("zero-length file table"));
1331 
1332 	/* compute the size of the new table */
1333 	onfiles = fdp->fd_nfiles;
1334 	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1335 	if (nnfiles <= onfiles)
1336 		/* the table is already large enough */
1337 		return;
1338 
1339 	/* allocate a new table and (if required) new bitmaps */
1340 	FILEDESC_XUNLOCK(fdp);
1341 	ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1342 	    M_FILEDESC, M_ZERO | M_WAITOK);
1343 	nfileflags = (char *)&ntable[nnfiles];
1344 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1345 		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1346 		    M_FILEDESC, M_ZERO | M_WAITOK);
1347 	else
1348 		nmap = NULL;
1349 	FILEDESC_XLOCK(fdp);
1350 
1351 	/*
1352 	 * We now have new tables ready to go.  Since we dropped the
1353 	 * filedesc lock to call malloc(), watch out for a race.
1354 	 */
1355 	onfiles = fdp->fd_nfiles;
1356 	if (onfiles >= nnfiles) {
1357 		/* we lost the race, but that's OK */
1358 		free(ntable, M_FILEDESC);
1359 		if (nmap != NULL)
1360 			free(nmap, M_FILEDESC);
1361 		return;
1362 	}
1363 	bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1364 	bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1365 	otable = fdp->fd_ofiles;
1366 	fdp->fd_ofileflags = nfileflags;
1367 	fdp->fd_ofiles = ntable;
1368 	/*
1369 	 * We must preserve ofiles until the process exits because we can't
1370 	 * be certain that no threads have references to the old table via
1371 	 * _fget().
1372 	 */
1373 	if (onfiles > NDFILE) {
1374 		fo = (struct freetable *)&otable[onfiles];
1375 		fdp0 = (struct filedesc0 *)fdp;
1376 		fo->ft_table = otable;
1377 		SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1378 	}
1379 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1380 		bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1381 		if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1382 			free(fdp->fd_map, M_FILEDESC);
1383 		fdp->fd_map = nmap;
1384 	}
1385 	fdp->fd_nfiles = nnfiles;
1386 }
1387 
1388 /*
1389  * Allocate a file descriptor for the process.
1390  */
1391 int
1392 fdalloc(struct thread *td, int minfd, int *result)
1393 {
1394 	struct proc *p = td->td_proc;
1395 	struct filedesc *fdp = p->p_fd;
1396 	int fd = -1, maxfd;
1397 
1398 	FILEDESC_XLOCK_ASSERT(fdp);
1399 
1400 	if (fdp->fd_freefile > minfd)
1401 		minfd = fdp->fd_freefile;
1402 
1403 	PROC_LOCK(p);
1404 	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1405 	PROC_UNLOCK(p);
1406 
1407 	/*
1408 	 * Search the bitmap for a free descriptor.  If none is found, try
1409 	 * to grow the file table.  Keep at it until we either get a file
1410 	 * descriptor or run into process or system limits; fdgrowtable()
1411 	 * may drop the filedesc lock, so we're in a race.
1412 	 */
1413 	for (;;) {
1414 		fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1415 		if (fd >= maxfd)
1416 			return (EMFILE);
1417 		if (fd < fdp->fd_nfiles)
1418 			break;
1419 		fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1420 	}
1421 
1422 	/*
1423 	 * Perform some sanity checks, then mark the file descriptor as
1424 	 * used and return it to the caller.
1425 	 */
1426 	KASSERT(!fdisused(fdp, fd),
1427 	    ("fd_first_free() returned non-free descriptor"));
1428 	KASSERT(fdp->fd_ofiles[fd] == NULL,
1429 	    ("free descriptor isn't"));
1430 	fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1431 	fdused(fdp, fd);
1432 	*result = fd;
1433 	return (0);
1434 }
1435 
1436 /*
1437  * Check to see whether n user file descriptors are available to the process
1438  * p.
1439  */
1440 int
1441 fdavail(struct thread *td, int n)
1442 {
1443 	struct proc *p = td->td_proc;
1444 	struct filedesc *fdp = td->td_proc->p_fd;
1445 	struct file **fpp;
1446 	int i, lim, last;
1447 
1448 	FILEDESC_LOCK_ASSERT(fdp);
1449 
1450 	PROC_LOCK(p);
1451 	lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1452 	PROC_UNLOCK(p);
1453 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1454 		return (1);
1455 	last = min(fdp->fd_nfiles, lim);
1456 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1457 	for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1458 		if (*fpp == NULL && --n <= 0)
1459 			return (1);
1460 	}
1461 	return (0);
1462 }
1463 
1464 /*
1465  * Create a new open file structure and allocate a file decriptor for the
1466  * process that refers to it.  We add one reference to the file for the
1467  * descriptor table and one reference for resultfp. This is to prevent us
1468  * being preempted and the entry in the descriptor table closed after we
1469  * release the FILEDESC lock.
1470  */
1471 int
1472 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1473 {
1474 	struct proc *p = td->td_proc;
1475 	struct file *fp;
1476 	int error, i;
1477 	int maxuserfiles = maxfiles - (maxfiles / 20);
1478 	static struct timeval lastfail;
1479 	static int curfail;
1480 
1481 	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1482 	if ((openfiles >= maxuserfiles &&
1483 	    priv_check(td, PRIV_MAXFILES) != 0) ||
1484 	    openfiles >= maxfiles) {
1485 		if (ppsratecheck(&lastfail, &curfail, 1)) {
1486 			printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1487 				td->td_ucred->cr_ruid);
1488 		}
1489 		uma_zfree(file_zone, fp);
1490 		return (ENFILE);
1491 	}
1492 	atomic_add_int(&openfiles, 1);
1493 
1494 	/*
1495 	 * If the process has file descriptor zero open, add the new file
1496 	 * descriptor to the list of open files at that point, otherwise
1497 	 * put it at the front of the list of open files.
1498 	 */
1499 	refcount_init(&fp->f_count, 1);
1500 	if (resultfp)
1501 		fhold(fp);
1502 	fp->f_cred = crhold(td->td_ucred);
1503 	fp->f_ops = &badfileops;
1504 	fp->f_data = NULL;
1505 	fp->f_vnode = NULL;
1506 	FILEDESC_XLOCK(p->p_fd);
1507 	if ((error = fdalloc(td, 0, &i))) {
1508 		FILEDESC_XUNLOCK(p->p_fd);
1509 		fdrop(fp, td);
1510 		if (resultfp)
1511 			fdrop(fp, td);
1512 		return (error);
1513 	}
1514 	p->p_fd->fd_ofiles[i] = fp;
1515 	FILEDESC_XUNLOCK(p->p_fd);
1516 	if (resultfp)
1517 		*resultfp = fp;
1518 	if (resultfd)
1519 		*resultfd = i;
1520 	return (0);
1521 }
1522 
1523 /*
1524  * Build a new filedesc structure from another.
1525  * Copy the current, root, and jail root vnode references.
1526  */
1527 struct filedesc *
1528 fdinit(struct filedesc *fdp)
1529 {
1530 	struct filedesc0 *newfdp;
1531 
1532 	newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1533 	FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1534 	if (fdp != NULL) {
1535 		FILEDESC_XLOCK(fdp);
1536 		newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1537 		if (newfdp->fd_fd.fd_cdir)
1538 			VREF(newfdp->fd_fd.fd_cdir);
1539 		newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1540 		if (newfdp->fd_fd.fd_rdir)
1541 			VREF(newfdp->fd_fd.fd_rdir);
1542 		newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1543 		if (newfdp->fd_fd.fd_jdir)
1544 			VREF(newfdp->fd_fd.fd_jdir);
1545 		FILEDESC_XUNLOCK(fdp);
1546 	}
1547 
1548 	/* Create the file descriptor table. */
1549 	newfdp->fd_fd.fd_refcnt = 1;
1550 	newfdp->fd_fd.fd_holdcnt = 1;
1551 	newfdp->fd_fd.fd_cmask = CMASK;
1552 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1553 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1554 	newfdp->fd_fd.fd_nfiles = NDFILE;
1555 	newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1556 	newfdp->fd_fd.fd_lastfile = -1;
1557 	return (&newfdp->fd_fd);
1558 }
1559 
1560 static struct filedesc *
1561 fdhold(struct proc *p)
1562 {
1563 	struct filedesc *fdp;
1564 
1565 	mtx_lock(&fdesc_mtx);
1566 	fdp = p->p_fd;
1567 	if (fdp != NULL)
1568 		fdp->fd_holdcnt++;
1569 	mtx_unlock(&fdesc_mtx);
1570 	return (fdp);
1571 }
1572 
1573 static void
1574 fddrop(struct filedesc *fdp)
1575 {
1576 	struct filedesc0 *fdp0;
1577 	struct freetable *ft;
1578 	int i;
1579 
1580 	mtx_lock(&fdesc_mtx);
1581 	i = --fdp->fd_holdcnt;
1582 	mtx_unlock(&fdesc_mtx);
1583 	if (i > 0)
1584 		return;
1585 
1586 	FILEDESC_LOCK_DESTROY(fdp);
1587 	fdp0 = (struct filedesc0 *)fdp;
1588 	while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1589 		SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1590 		free(ft->ft_table, M_FILEDESC);
1591 	}
1592 	free(fdp, M_FILEDESC);
1593 }
1594 
1595 /*
1596  * Share a filedesc structure.
1597  */
1598 struct filedesc *
1599 fdshare(struct filedesc *fdp)
1600 {
1601 
1602 	FILEDESC_XLOCK(fdp);
1603 	fdp->fd_refcnt++;
1604 	FILEDESC_XUNLOCK(fdp);
1605 	return (fdp);
1606 }
1607 
1608 /*
1609  * Unshare a filedesc structure, if necessary by making a copy
1610  */
1611 void
1612 fdunshare(struct proc *p, struct thread *td)
1613 {
1614 
1615 	FILEDESC_XLOCK(p->p_fd);
1616 	if (p->p_fd->fd_refcnt > 1) {
1617 		struct filedesc *tmp;
1618 
1619 		FILEDESC_XUNLOCK(p->p_fd);
1620 		tmp = fdcopy(p->p_fd);
1621 		fdfree(td);
1622 		p->p_fd = tmp;
1623 	} else
1624 		FILEDESC_XUNLOCK(p->p_fd);
1625 }
1626 
1627 /*
1628  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
1629  * this is to ease callers, not catch errors.
1630  */
1631 struct filedesc *
1632 fdcopy(struct filedesc *fdp)
1633 {
1634 	struct filedesc *newfdp;
1635 	int i;
1636 
1637 	/* Certain daemons might not have file descriptors. */
1638 	if (fdp == NULL)
1639 		return (NULL);
1640 
1641 	newfdp = fdinit(fdp);
1642 	FILEDESC_SLOCK(fdp);
1643 	while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1644 		FILEDESC_SUNLOCK(fdp);
1645 		FILEDESC_XLOCK(newfdp);
1646 		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1647 		FILEDESC_XUNLOCK(newfdp);
1648 		FILEDESC_SLOCK(fdp);
1649 	}
1650 	/* copy everything except kqueue descriptors */
1651 	newfdp->fd_freefile = -1;
1652 	for (i = 0; i <= fdp->fd_lastfile; ++i) {
1653 		if (fdisused(fdp, i) &&
1654 		    fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1655 		    fdp->fd_ofiles[i]->f_ops != &badfileops) {
1656 			newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1657 			newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1658 			fhold(newfdp->fd_ofiles[i]);
1659 			newfdp->fd_lastfile = i;
1660 		} else {
1661 			if (newfdp->fd_freefile == -1)
1662 				newfdp->fd_freefile = i;
1663 		}
1664 	}
1665 	newfdp->fd_cmask = fdp->fd_cmask;
1666 	FILEDESC_SUNLOCK(fdp);
1667 	FILEDESC_XLOCK(newfdp);
1668 	for (i = 0; i <= newfdp->fd_lastfile; ++i)
1669 		if (newfdp->fd_ofiles[i] != NULL)
1670 			fdused(newfdp, i);
1671 	if (newfdp->fd_freefile == -1)
1672 		newfdp->fd_freefile = i;
1673 	FILEDESC_XUNLOCK(newfdp);
1674 	return (newfdp);
1675 }
1676 
1677 /*
1678  * Release a filedesc structure.
1679  */
1680 void
1681 fdfree(struct thread *td)
1682 {
1683 	struct filedesc *fdp;
1684 	struct file **fpp;
1685 	int i, locked;
1686 	struct filedesc_to_leader *fdtol;
1687 	struct file *fp;
1688 	struct vnode *cdir, *jdir, *rdir, *vp;
1689 	struct flock lf;
1690 
1691 	/* Certain daemons might not have file descriptors. */
1692 	fdp = td->td_proc->p_fd;
1693 	if (fdp == NULL)
1694 		return;
1695 
1696 	/* Check for special need to clear POSIX style locks */
1697 	fdtol = td->td_proc->p_fdtol;
1698 	if (fdtol != NULL) {
1699 		FILEDESC_XLOCK(fdp);
1700 		KASSERT(fdtol->fdl_refcount > 0,
1701 			("filedesc_to_refcount botch: fdl_refcount=%d",
1702 			 fdtol->fdl_refcount));
1703 		if (fdtol->fdl_refcount == 1 &&
1704 		    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1705 			for (i = 0, fpp = fdp->fd_ofiles;
1706 			     i <= fdp->fd_lastfile;
1707 			     i++, fpp++) {
1708 				if (*fpp == NULL ||
1709 				    (*fpp)->f_type != DTYPE_VNODE)
1710 					continue;
1711 				fp = *fpp;
1712 				fhold(fp);
1713 				FILEDESC_XUNLOCK(fdp);
1714 				lf.l_whence = SEEK_SET;
1715 				lf.l_start = 0;
1716 				lf.l_len = 0;
1717 				lf.l_type = F_UNLCK;
1718 				vp = fp->f_vnode;
1719 				locked = VFS_LOCK_GIANT(vp->v_mount);
1720 				(void) VOP_ADVLOCK(vp,
1721 						   (caddr_t)td->td_proc->
1722 						   p_leader,
1723 						   F_UNLCK,
1724 						   &lf,
1725 						   F_POSIX);
1726 				VFS_UNLOCK_GIANT(locked);
1727 				FILEDESC_XLOCK(fdp);
1728 				fdrop(fp, td);
1729 				fpp = fdp->fd_ofiles + i;
1730 			}
1731 		}
1732 	retry:
1733 		if (fdtol->fdl_refcount == 1) {
1734 			if (fdp->fd_holdleaderscount > 0 &&
1735 			    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1736 				/*
1737 				 * close() or do_dup() has cleared a reference
1738 				 * in a shared file descriptor table.
1739 				 */
1740 				fdp->fd_holdleaderswakeup = 1;
1741 				sx_sleep(&fdp->fd_holdleaderscount,
1742 				    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1743 				goto retry;
1744 			}
1745 			if (fdtol->fdl_holdcount > 0) {
1746 				/*
1747 				 * Ensure that fdtol->fdl_leader remains
1748 				 * valid in closef().
1749 				 */
1750 				fdtol->fdl_wakeup = 1;
1751 				sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1752 				    "fdlhold", 0);
1753 				goto retry;
1754 			}
1755 		}
1756 		fdtol->fdl_refcount--;
1757 		if (fdtol->fdl_refcount == 0 &&
1758 		    fdtol->fdl_holdcount == 0) {
1759 			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1760 			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1761 		} else
1762 			fdtol = NULL;
1763 		td->td_proc->p_fdtol = NULL;
1764 		FILEDESC_XUNLOCK(fdp);
1765 		if (fdtol != NULL)
1766 			free(fdtol, M_FILEDESC_TO_LEADER);
1767 	}
1768 	FILEDESC_XLOCK(fdp);
1769 	i = --fdp->fd_refcnt;
1770 	FILEDESC_XUNLOCK(fdp);
1771 	if (i > 0)
1772 		return;
1773 
1774 	fpp = fdp->fd_ofiles;
1775 	for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1776 		if (*fpp) {
1777 			FILEDESC_XLOCK(fdp);
1778 			fp = *fpp;
1779 			*fpp = NULL;
1780 			FILEDESC_XUNLOCK(fdp);
1781 			(void) closef(fp, td);
1782 		}
1783 	}
1784 	FILEDESC_XLOCK(fdp);
1785 
1786 	/* XXX This should happen earlier. */
1787 	mtx_lock(&fdesc_mtx);
1788 	td->td_proc->p_fd = NULL;
1789 	mtx_unlock(&fdesc_mtx);
1790 
1791 	if (fdp->fd_nfiles > NDFILE)
1792 		free(fdp->fd_ofiles, M_FILEDESC);
1793 	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1794 		free(fdp->fd_map, M_FILEDESC);
1795 
1796 	fdp->fd_nfiles = 0;
1797 
1798 	cdir = fdp->fd_cdir;
1799 	fdp->fd_cdir = NULL;
1800 	rdir = fdp->fd_rdir;
1801 	fdp->fd_rdir = NULL;
1802 	jdir = fdp->fd_jdir;
1803 	fdp->fd_jdir = NULL;
1804 	FILEDESC_XUNLOCK(fdp);
1805 
1806 	if (cdir) {
1807 		locked = VFS_LOCK_GIANT(cdir->v_mount);
1808 		vrele(cdir);
1809 		VFS_UNLOCK_GIANT(locked);
1810 	}
1811 	if (rdir) {
1812 		locked = VFS_LOCK_GIANT(rdir->v_mount);
1813 		vrele(rdir);
1814 		VFS_UNLOCK_GIANT(locked);
1815 	}
1816 	if (jdir) {
1817 		locked = VFS_LOCK_GIANT(jdir->v_mount);
1818 		vrele(jdir);
1819 		VFS_UNLOCK_GIANT(locked);
1820 	}
1821 
1822 	fddrop(fdp);
1823 }
1824 
1825 /*
1826  * For setugid programs, we don't want to people to use that setugidness
1827  * to generate error messages which write to a file which otherwise would
1828  * otherwise be off-limits to the process.  We check for filesystems where
1829  * the vnode can change out from under us after execve (like [lin]procfs).
1830  *
1831  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1832  * sufficient.  We also don't check for setugidness since we know we are.
1833  */
1834 static int
1835 is_unsafe(struct file *fp)
1836 {
1837 	if (fp->f_type == DTYPE_VNODE) {
1838 		struct vnode *vp = fp->f_vnode;
1839 
1840 		if ((vp->v_vflag & VV_PROCDEP) != 0)
1841 			return (1);
1842 	}
1843 	return (0);
1844 }
1845 
1846 /*
1847  * Make this setguid thing safe, if at all possible.
1848  */
1849 void
1850 setugidsafety(struct thread *td)
1851 {
1852 	struct filedesc *fdp;
1853 	int i;
1854 
1855 	/* Certain daemons might not have file descriptors. */
1856 	fdp = td->td_proc->p_fd;
1857 	if (fdp == NULL)
1858 		return;
1859 
1860 	/*
1861 	 * Note: fdp->fd_ofiles may be reallocated out from under us while
1862 	 * we are blocked in a close.  Be careful!
1863 	 */
1864 	FILEDESC_XLOCK(fdp);
1865 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1866 		if (i > 2)
1867 			break;
1868 		if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1869 			struct file *fp;
1870 
1871 			knote_fdclose(td, i);
1872 			/*
1873 			 * NULL-out descriptor prior to close to avoid
1874 			 * a race while close blocks.
1875 			 */
1876 			fp = fdp->fd_ofiles[i];
1877 			fdp->fd_ofiles[i] = NULL;
1878 			fdp->fd_ofileflags[i] = 0;
1879 			fdunused(fdp, i);
1880 			FILEDESC_XUNLOCK(fdp);
1881 			(void) closef(fp, td);
1882 			FILEDESC_XLOCK(fdp);
1883 		}
1884 	}
1885 	FILEDESC_XUNLOCK(fdp);
1886 }
1887 
1888 /*
1889  * If a specific file object occupies a specific file descriptor, close the
1890  * file descriptor entry and drop a reference on the file object.  This is a
1891  * convenience function to handle a subsequent error in a function that calls
1892  * falloc() that handles the race that another thread might have closed the
1893  * file descriptor out from under the thread creating the file object.
1894  */
1895 void
1896 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1897 {
1898 
1899 	FILEDESC_XLOCK(fdp);
1900 	if (fdp->fd_ofiles[idx] == fp) {
1901 		fdp->fd_ofiles[idx] = NULL;
1902 		fdunused(fdp, idx);
1903 		FILEDESC_XUNLOCK(fdp);
1904 		fdrop(fp, td);
1905 	} else
1906 		FILEDESC_XUNLOCK(fdp);
1907 }
1908 
1909 /*
1910  * Close any files on exec?
1911  */
1912 void
1913 fdcloseexec(struct thread *td)
1914 {
1915 	struct filedesc *fdp;
1916 	int i;
1917 
1918 	/* Certain daemons might not have file descriptors. */
1919 	fdp = td->td_proc->p_fd;
1920 	if (fdp == NULL)
1921 		return;
1922 
1923 	FILEDESC_XLOCK(fdp);
1924 
1925 	/*
1926 	 * We cannot cache fd_ofiles or fd_ofileflags since operations
1927 	 * may block and rip them out from under us.
1928 	 */
1929 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1930 		if (fdp->fd_ofiles[i] != NULL &&
1931 		    (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1932 		    (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1933 			struct file *fp;
1934 
1935 			knote_fdclose(td, i);
1936 			/*
1937 			 * NULL-out descriptor prior to close to avoid
1938 			 * a race while close blocks.
1939 			 */
1940 			fp = fdp->fd_ofiles[i];
1941 			fdp->fd_ofiles[i] = NULL;
1942 			fdp->fd_ofileflags[i] = 0;
1943 			fdunused(fdp, i);
1944 			if (fp->f_type == DTYPE_MQUEUE)
1945 				mq_fdclose(td, i, fp);
1946 			FILEDESC_XUNLOCK(fdp);
1947 			(void) closef(fp, td);
1948 			FILEDESC_XLOCK(fdp);
1949 		}
1950 	}
1951 	FILEDESC_XUNLOCK(fdp);
1952 }
1953 
1954 /*
1955  * It is unsafe for set[ug]id processes to be started with file
1956  * descriptors 0..2 closed, as these descriptors are given implicit
1957  * significance in the Standard C library.  fdcheckstd() will create a
1958  * descriptor referencing /dev/null for each of stdin, stdout, and
1959  * stderr that is not already open.
1960  */
1961 int
1962 fdcheckstd(struct thread *td)
1963 {
1964 	struct filedesc *fdp;
1965 	register_t retval, save;
1966 	int i, error, devnull;
1967 
1968 	fdp = td->td_proc->p_fd;
1969 	if (fdp == NULL)
1970 		return (0);
1971 	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1972 	devnull = -1;
1973 	error = 0;
1974 	for (i = 0; i < 3; i++) {
1975 		if (fdp->fd_ofiles[i] != NULL)
1976 			continue;
1977 		if (devnull < 0) {
1978 			save = td->td_retval[0];
1979 			error = kern_open(td, "/dev/null", UIO_SYSSPACE,
1980 			    O_RDWR, 0);
1981 			devnull = td->td_retval[0];
1982 			KASSERT(devnull == i, ("oof, we didn't get our fd"));
1983 			td->td_retval[0] = save;
1984 			if (error)
1985 				break;
1986 		} else {
1987 			error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1988 			if (error != 0)
1989 				break;
1990 		}
1991 	}
1992 	return (error);
1993 }
1994 
1995 /*
1996  * Internal form of close.  Decrement reference count on file structure.
1997  * Note: td may be NULL when closing a file that was being passed in a
1998  * message.
1999  *
2000  * XXXRW: Giant is not required for the caller, but often will be held; this
2001  * makes it moderately likely the Giant will be recursed in the VFS case.
2002  */
2003 int
2004 closef(struct file *fp, struct thread *td)
2005 {
2006 	struct vnode *vp;
2007 	struct flock lf;
2008 	struct filedesc_to_leader *fdtol;
2009 	struct filedesc *fdp;
2010 
2011 	/*
2012 	 * POSIX record locking dictates that any close releases ALL
2013 	 * locks owned by this process.  This is handled by setting
2014 	 * a flag in the unlock to free ONLY locks obeying POSIX
2015 	 * semantics, and not to free BSD-style file locks.
2016 	 * If the descriptor was in a message, POSIX-style locks
2017 	 * aren't passed with the descriptor, and the thread pointer
2018 	 * will be NULL.  Callers should be careful only to pass a
2019 	 * NULL thread pointer when there really is no owning
2020 	 * context that might have locks, or the locks will be
2021 	 * leaked.
2022 	 */
2023 	if (fp->f_type == DTYPE_VNODE && td != NULL) {
2024 		int vfslocked;
2025 
2026 		vp = fp->f_vnode;
2027 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2028 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2029 			lf.l_whence = SEEK_SET;
2030 			lf.l_start = 0;
2031 			lf.l_len = 0;
2032 			lf.l_type = F_UNLCK;
2033 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2034 					   F_UNLCK, &lf, F_POSIX);
2035 		}
2036 		fdtol = td->td_proc->p_fdtol;
2037 		if (fdtol != NULL) {
2038 			/*
2039 			 * Handle special case where file descriptor table is
2040 			 * shared between multiple process leaders.
2041 			 */
2042 			fdp = td->td_proc->p_fd;
2043 			FILEDESC_XLOCK(fdp);
2044 			for (fdtol = fdtol->fdl_next;
2045 			     fdtol != td->td_proc->p_fdtol;
2046 			     fdtol = fdtol->fdl_next) {
2047 				if ((fdtol->fdl_leader->p_flag &
2048 				     P_ADVLOCK) == 0)
2049 					continue;
2050 				fdtol->fdl_holdcount++;
2051 				FILEDESC_XUNLOCK(fdp);
2052 				lf.l_whence = SEEK_SET;
2053 				lf.l_start = 0;
2054 				lf.l_len = 0;
2055 				lf.l_type = F_UNLCK;
2056 				vp = fp->f_vnode;
2057 				(void) VOP_ADVLOCK(vp,
2058 						   (caddr_t)fdtol->fdl_leader,
2059 						   F_UNLCK, &lf, F_POSIX);
2060 				FILEDESC_XLOCK(fdp);
2061 				fdtol->fdl_holdcount--;
2062 				if (fdtol->fdl_holdcount == 0 &&
2063 				    fdtol->fdl_wakeup != 0) {
2064 					fdtol->fdl_wakeup = 0;
2065 					wakeup(fdtol);
2066 				}
2067 			}
2068 			FILEDESC_XUNLOCK(fdp);
2069 		}
2070 		VFS_UNLOCK_GIANT(vfslocked);
2071 	}
2072 	return (fdrop(fp, td));
2073 }
2074 
2075 /*
2076  * Initialize the file pointer with the specified properties.
2077  *
2078  * The ops are set with release semantics to be certain that the flags, type,
2079  * and data are visible when ops is.  This is to prevent ops methods from being
2080  * called with bad data.
2081  */
2082 void
2083 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2084 {
2085 	fp->f_data = data;
2086 	fp->f_flag = flag;
2087 	fp->f_type = type;
2088 	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2089 }
2090 
2091 struct file *
2092 fget_unlocked(struct filedesc *fdp, int fd)
2093 {
2094 	struct file *fp;
2095 	u_int count;
2096 
2097 	if (fd < 0 || fd >= fdp->fd_nfiles)
2098 		return (NULL);
2099 	/*
2100 	 * Fetch the descriptor locklessly.  We avoid fdrop() races by
2101 	 * never raising a refcount above 0.  To accomplish this we have
2102 	 * to use a cmpset loop rather than an atomic_add.  The descriptor
2103 	 * must be re-verified once we acquire a reference to be certain
2104 	 * that the identity is still correct and we did not lose a race
2105 	 * due to preemption.
2106 	 */
2107 	for (;;) {
2108 		fp = fdp->fd_ofiles[fd];
2109 		if (fp == NULL)
2110 			break;
2111 		count = fp->f_count;
2112 		if (count == 0)
2113 			continue;
2114 		/*
2115 		 * Use an acquire barrier to prevent caching of fd_ofiles
2116 		 * so it is refreshed for verification.
2117 		 */
2118 		if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2119 			continue;
2120 		if (fp == fdp->fd_ofiles[fd])
2121 			break;
2122 		fdrop(fp, curthread);
2123 	}
2124 
2125 	return (fp);
2126 }
2127 
2128 /*
2129  * Extract the file pointer associated with the specified descriptor for the
2130  * current user process.
2131  *
2132  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2133  * returned.
2134  *
2135  * If an error occured the non-zero error is returned and *fpp is set to
2136  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
2137  * responsible for fdrop().
2138  */
2139 static __inline int
2140 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2141 {
2142 	struct filedesc *fdp;
2143 	struct file *fp;
2144 
2145 	*fpp = NULL;
2146 	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2147 		return (EBADF);
2148 	if ((fp = fget_unlocked(fdp, fd)) == NULL)
2149 		return (EBADF);
2150 	if (fp->f_ops == &badfileops) {
2151 		fdrop(fp, td);
2152 		return (EBADF);
2153 	}
2154 	/*
2155 	 * FREAD and FWRITE failure return EBADF as per POSIX.
2156 	 *
2157 	 * Only one flag, or 0, may be specified.
2158 	 */
2159 	if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2160 	    (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2161 		fdrop(fp, td);
2162 		return (EBADF);
2163 	}
2164 	*fpp = fp;
2165 	return (0);
2166 }
2167 
2168 int
2169 fget(struct thread *td, int fd, struct file **fpp)
2170 {
2171 
2172 	return(_fget(td, fd, fpp, 0));
2173 }
2174 
2175 int
2176 fget_read(struct thread *td, int fd, struct file **fpp)
2177 {
2178 
2179 	return(_fget(td, fd, fpp, FREAD));
2180 }
2181 
2182 int
2183 fget_write(struct thread *td, int fd, struct file **fpp)
2184 {
2185 
2186 	return(_fget(td, fd, fpp, FWRITE));
2187 }
2188 
2189 /*
2190  * Like fget() but loads the underlying vnode, or returns an error if the
2191  * descriptor does not represent a vnode.  Note that pipes use vnodes but
2192  * never have VM objects.  The returned vnode will be vref()'d.
2193  *
2194  * XXX: what about the unused flags ?
2195  */
2196 static __inline int
2197 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2198 {
2199 	struct file *fp;
2200 	int error;
2201 
2202 	*vpp = NULL;
2203 	if ((error = _fget(td, fd, &fp, flags)) != 0)
2204 		return (error);
2205 	if (fp->f_vnode == NULL) {
2206 		error = EINVAL;
2207 	} else {
2208 		*vpp = fp->f_vnode;
2209 		vref(*vpp);
2210 	}
2211 	fdrop(fp, td);
2212 
2213 	return (error);
2214 }
2215 
2216 int
2217 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2218 {
2219 
2220 	return (_fgetvp(td, fd, vpp, 0));
2221 }
2222 
2223 int
2224 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2225 {
2226 
2227 	return (_fgetvp(td, fd, vpp, FREAD));
2228 }
2229 
2230 #ifdef notyet
2231 int
2232 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2233 {
2234 
2235 	return (_fgetvp(td, fd, vpp, FWRITE));
2236 }
2237 #endif
2238 
2239 /*
2240  * Like fget() but loads the underlying socket, or returns an error if the
2241  * descriptor does not represent a socket.
2242  *
2243  * We bump the ref count on the returned socket.  XXX Also obtain the SX lock
2244  * in the future.
2245  *
2246  * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2247  * on their file descriptor reference to prevent the socket from being free'd
2248  * during use.
2249  */
2250 int
2251 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2252 {
2253 	struct file *fp;
2254 	int error;
2255 
2256 	*spp = NULL;
2257 	if (fflagp != NULL)
2258 		*fflagp = 0;
2259 	if ((error = _fget(td, fd, &fp, 0)) != 0)
2260 		return (error);
2261 	if (fp->f_type != DTYPE_SOCKET) {
2262 		error = ENOTSOCK;
2263 	} else {
2264 		*spp = fp->f_data;
2265 		if (fflagp)
2266 			*fflagp = fp->f_flag;
2267 		SOCK_LOCK(*spp);
2268 		soref(*spp);
2269 		SOCK_UNLOCK(*spp);
2270 	}
2271 	fdrop(fp, td);
2272 
2273 	return (error);
2274 }
2275 
2276 /*
2277  * Drop the reference count on the socket and XXX release the SX lock in the
2278  * future.  The last reference closes the socket.
2279  *
2280  * Note: fputsock() is deprecated, see comment for fgetsock().
2281  */
2282 void
2283 fputsock(struct socket *so)
2284 {
2285 
2286 	ACCEPT_LOCK();
2287 	SOCK_LOCK(so);
2288 	sorele(so);
2289 }
2290 
2291 /*
2292  * Handle the last reference to a file being closed.
2293  */
2294 int
2295 _fdrop(struct file *fp, struct thread *td)
2296 {
2297 	int error;
2298 
2299 	error = 0;
2300 	if (fp->f_count != 0)
2301 		panic("fdrop: count %d", fp->f_count);
2302 	if (fp->f_ops != &badfileops)
2303 		error = fo_close(fp, td);
2304 	/*
2305 	 * The f_cdevpriv cannot be assigned non-NULL value while we
2306 	 * are destroying the file.
2307 	 */
2308 	if (fp->f_cdevpriv != NULL)
2309 		devfs_fpdrop(fp);
2310 	atomic_subtract_int(&openfiles, 1);
2311 	crfree(fp->f_cred);
2312 	uma_zfree(file_zone, fp);
2313 
2314 	return (error);
2315 }
2316 
2317 /*
2318  * Apply an advisory lock on a file descriptor.
2319  *
2320  * Just attempt to get a record lock of the requested type on the entire file
2321  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2322  */
2323 #ifndef _SYS_SYSPROTO_H_
2324 struct flock_args {
2325 	int	fd;
2326 	int	how;
2327 };
2328 #endif
2329 /* ARGSUSED */
2330 int
2331 flock(struct thread *td, struct flock_args *uap)
2332 {
2333 	struct file *fp;
2334 	struct vnode *vp;
2335 	struct flock lf;
2336 	int vfslocked;
2337 	int error;
2338 
2339 	if ((error = fget(td, uap->fd, &fp)) != 0)
2340 		return (error);
2341 	if (fp->f_type != DTYPE_VNODE) {
2342 		fdrop(fp, td);
2343 		return (EOPNOTSUPP);
2344 	}
2345 
2346 	vp = fp->f_vnode;
2347 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2348 	lf.l_whence = SEEK_SET;
2349 	lf.l_start = 0;
2350 	lf.l_len = 0;
2351 	if (uap->how & LOCK_UN) {
2352 		lf.l_type = F_UNLCK;
2353 		atomic_clear_int(&fp->f_flag, FHASLOCK);
2354 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2355 		goto done2;
2356 	}
2357 	if (uap->how & LOCK_EX)
2358 		lf.l_type = F_WRLCK;
2359 	else if (uap->how & LOCK_SH)
2360 		lf.l_type = F_RDLCK;
2361 	else {
2362 		error = EBADF;
2363 		goto done2;
2364 	}
2365 	atomic_set_int(&fp->f_flag, FHASLOCK);
2366 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2367 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2368 done2:
2369 	fdrop(fp, td);
2370 	VFS_UNLOCK_GIANT(vfslocked);
2371 	return (error);
2372 }
2373 /*
2374  * Duplicate the specified descriptor to a free descriptor.
2375  */
2376 int
2377 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2378 {
2379 	struct file *wfp;
2380 	struct file *fp;
2381 
2382 	/*
2383 	 * If the to-be-dup'd fd number is greater than the allowed number
2384 	 * of file descriptors, or the fd to be dup'd has already been
2385 	 * closed, then reject.
2386 	 */
2387 	FILEDESC_XLOCK(fdp);
2388 	if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2389 	    (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2390 		FILEDESC_XUNLOCK(fdp);
2391 		return (EBADF);
2392 	}
2393 
2394 	/*
2395 	 * There are two cases of interest here.
2396 	 *
2397 	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2398 	 *
2399 	 * For ENXIO steal away the file structure from (dfd) and store it in
2400 	 * (indx).  (dfd) is effectively closed by this operation.
2401 	 *
2402 	 * Any other error code is just returned.
2403 	 */
2404 	switch (error) {
2405 	case ENODEV:
2406 		/*
2407 		 * Check that the mode the file is being opened for is a
2408 		 * subset of the mode of the existing descriptor.
2409 		 */
2410 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2411 			FILEDESC_XUNLOCK(fdp);
2412 			return (EACCES);
2413 		}
2414 		fp = fdp->fd_ofiles[indx];
2415 		fdp->fd_ofiles[indx] = wfp;
2416 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2417 		if (fp == NULL)
2418 			fdused(fdp, indx);
2419 		fhold(wfp);
2420 		FILEDESC_XUNLOCK(fdp);
2421 		if (fp != NULL)
2422 			/*
2423 			 * We now own the reference to fp that the ofiles[]
2424 			 * array used to own.  Release it.
2425 			 */
2426 			fdrop(fp, td);
2427 		return (0);
2428 
2429 	case ENXIO:
2430 		/*
2431 		 * Steal away the file pointer from dfd and stuff it into indx.
2432 		 */
2433 		fp = fdp->fd_ofiles[indx];
2434 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2435 		fdp->fd_ofiles[dfd] = NULL;
2436 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2437 		fdp->fd_ofileflags[dfd] = 0;
2438 		fdunused(fdp, dfd);
2439 		if (fp == NULL)
2440 			fdused(fdp, indx);
2441 		FILEDESC_XUNLOCK(fdp);
2442 
2443 		/*
2444 		 * We now own the reference to fp that the ofiles[] array
2445 		 * used to own.  Release it.
2446 		 */
2447 		if (fp != NULL)
2448 			fdrop(fp, td);
2449 		return (0);
2450 
2451 	default:
2452 		FILEDESC_XUNLOCK(fdp);
2453 		return (error);
2454 	}
2455 	/* NOTREACHED */
2456 }
2457 
2458 /*
2459  * Scan all active processes and prisons to see if any of them have a current
2460  * or root directory of `olddp'. If so, replace them with the new mount point.
2461  */
2462 void
2463 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2464 {
2465 	struct filedesc *fdp;
2466 	struct prison *pr;
2467 	struct proc *p;
2468 	int nrele;
2469 
2470 	if (vrefcnt(olddp) == 1)
2471 		return;
2472 	nrele = 0;
2473 	sx_slock(&allproc_lock);
2474 	FOREACH_PROC_IN_SYSTEM(p) {
2475 		fdp = fdhold(p);
2476 		if (fdp == NULL)
2477 			continue;
2478 		FILEDESC_XLOCK(fdp);
2479 		if (fdp->fd_cdir == olddp) {
2480 			vref(newdp);
2481 			fdp->fd_cdir = newdp;
2482 			nrele++;
2483 		}
2484 		if (fdp->fd_rdir == olddp) {
2485 			vref(newdp);
2486 			fdp->fd_rdir = newdp;
2487 			nrele++;
2488 		}
2489 		if (fdp->fd_jdir == olddp) {
2490 			vref(newdp);
2491 			fdp->fd_jdir = newdp;
2492 			nrele++;
2493 		}
2494 		FILEDESC_XUNLOCK(fdp);
2495 		fddrop(fdp);
2496 	}
2497 	sx_sunlock(&allproc_lock);
2498 	if (rootvnode == olddp) {
2499 		vref(newdp);
2500 		rootvnode = newdp;
2501 		nrele++;
2502 	}
2503 	mtx_lock(&prison0.pr_mtx);
2504 	if (prison0.pr_root == olddp) {
2505 		vref(newdp);
2506 		prison0.pr_root = newdp;
2507 		nrele++;
2508 	}
2509 	mtx_unlock(&prison0.pr_mtx);
2510 	sx_slock(&allprison_lock);
2511 	TAILQ_FOREACH(pr, &allprison, pr_list) {
2512 		mtx_lock(&pr->pr_mtx);
2513 		if (pr->pr_root == olddp) {
2514 			vref(newdp);
2515 			pr->pr_root = newdp;
2516 			nrele++;
2517 		}
2518 		mtx_unlock(&pr->pr_mtx);
2519 	}
2520 	sx_sunlock(&allprison_lock);
2521 	while (nrele--)
2522 		vrele(olddp);
2523 }
2524 
2525 struct filedesc_to_leader *
2526 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2527 {
2528 	struct filedesc_to_leader *fdtol;
2529 
2530 	fdtol = malloc(sizeof(struct filedesc_to_leader),
2531 	       M_FILEDESC_TO_LEADER,
2532 	       M_WAITOK);
2533 	fdtol->fdl_refcount = 1;
2534 	fdtol->fdl_holdcount = 0;
2535 	fdtol->fdl_wakeup = 0;
2536 	fdtol->fdl_leader = leader;
2537 	if (old != NULL) {
2538 		FILEDESC_XLOCK(fdp);
2539 		fdtol->fdl_next = old->fdl_next;
2540 		fdtol->fdl_prev = old;
2541 		old->fdl_next = fdtol;
2542 		fdtol->fdl_next->fdl_prev = fdtol;
2543 		FILEDESC_XUNLOCK(fdp);
2544 	} else {
2545 		fdtol->fdl_next = fdtol;
2546 		fdtol->fdl_prev = fdtol;
2547 	}
2548 	return (fdtol);
2549 }
2550 
2551 /*
2552  * Get file structures globally.
2553  */
2554 static int
2555 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2556 {
2557 	struct xfile xf;
2558 	struct filedesc *fdp;
2559 	struct file *fp;
2560 	struct proc *p;
2561 	int error, n;
2562 
2563 	error = sysctl_wire_old_buffer(req, 0);
2564 	if (error != 0)
2565 		return (error);
2566 	if (req->oldptr == NULL) {
2567 		n = 0;
2568 		sx_slock(&allproc_lock);
2569 		FOREACH_PROC_IN_SYSTEM(p) {
2570 			if (p->p_state == PRS_NEW)
2571 				continue;
2572 			fdp = fdhold(p);
2573 			if (fdp == NULL)
2574 				continue;
2575 			/* overestimates sparse tables. */
2576 			if (fdp->fd_lastfile > 0)
2577 				n += fdp->fd_lastfile;
2578 			fddrop(fdp);
2579 		}
2580 		sx_sunlock(&allproc_lock);
2581 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2582 	}
2583 	error = 0;
2584 	bzero(&xf, sizeof(xf));
2585 	xf.xf_size = sizeof(xf);
2586 	sx_slock(&allproc_lock);
2587 	FOREACH_PROC_IN_SYSTEM(p) {
2588 		if (p->p_state == PRS_NEW)
2589 			continue;
2590 		PROC_LOCK(p);
2591 		if (p_cansee(req->td, p) != 0) {
2592 			PROC_UNLOCK(p);
2593 			continue;
2594 		}
2595 		xf.xf_pid = p->p_pid;
2596 		xf.xf_uid = p->p_ucred->cr_uid;
2597 		PROC_UNLOCK(p);
2598 		fdp = fdhold(p);
2599 		if (fdp == NULL)
2600 			continue;
2601 		FILEDESC_SLOCK(fdp);
2602 		for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2603 			if ((fp = fdp->fd_ofiles[n]) == NULL)
2604 				continue;
2605 			xf.xf_fd = n;
2606 			xf.xf_file = fp;
2607 			xf.xf_data = fp->f_data;
2608 			xf.xf_vnode = fp->f_vnode;
2609 			xf.xf_type = fp->f_type;
2610 			xf.xf_count = fp->f_count;
2611 			xf.xf_msgcount = 0;
2612 			xf.xf_offset = fp->f_offset;
2613 			xf.xf_flag = fp->f_flag;
2614 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
2615 			if (error)
2616 				break;
2617 		}
2618 		FILEDESC_SUNLOCK(fdp);
2619 		fddrop(fdp);
2620 		if (error)
2621 			break;
2622 	}
2623 	sx_sunlock(&allproc_lock);
2624 	return (error);
2625 }
2626 
2627 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2628     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2629 
2630 #ifdef KINFO_OFILE_SIZE
2631 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2632 #endif
2633 
2634 #ifdef COMPAT_FREEBSD7
2635 static int
2636 export_vnode_for_osysctl(struct vnode *vp, int type,
2637     struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2638 {
2639 	int error;
2640 	char *fullpath, *freepath;
2641 	int vfslocked;
2642 
2643 	bzero(kif, sizeof(*kif));
2644 	kif->kf_structsize = sizeof(*kif);
2645 
2646 	vref(vp);
2647 	kif->kf_fd = type;
2648 	kif->kf_type = KF_TYPE_VNODE;
2649 	/* This function only handles directories. */
2650 	if (vp->v_type != VDIR) {
2651 		vrele(vp);
2652 		return (ENOTDIR);
2653 	}
2654 	kif->kf_vnode_type = KF_VTYPE_VDIR;
2655 
2656 	/*
2657 	 * This is not a true file descriptor, so we set a bogus refcount
2658 	 * and offset to indicate these fields should be ignored.
2659 	 */
2660 	kif->kf_ref_count = -1;
2661 	kif->kf_offset = -1;
2662 
2663 	freepath = NULL;
2664 	fullpath = "-";
2665 	FILEDESC_SUNLOCK(fdp);
2666 	vn_fullpath(curthread, vp, &fullpath, &freepath);
2667 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2668 	vrele(vp);
2669 	VFS_UNLOCK_GIANT(vfslocked);
2670 	strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2671 	if (freepath != NULL)
2672 		free(freepath, M_TEMP);
2673 	error = SYSCTL_OUT(req, kif, sizeof(*kif));
2674 	FILEDESC_SLOCK(fdp);
2675 	return (error);
2676 }
2677 
2678 /*
2679  * Get per-process file descriptors for use by procstat(1), et al.
2680  */
2681 static int
2682 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2683 {
2684 	char *fullpath, *freepath;
2685 	struct kinfo_ofile *kif;
2686 	struct filedesc *fdp;
2687 	int error, i, *name;
2688 	struct socket *so;
2689 	struct vnode *vp;
2690 	struct file *fp;
2691 	struct proc *p;
2692 	struct tty *tp;
2693 	int vfslocked;
2694 
2695 	name = (int *)arg1;
2696 	if ((p = pfind((pid_t)name[0])) == NULL)
2697 		return (ESRCH);
2698 	if ((error = p_candebug(curthread, p))) {
2699 		PROC_UNLOCK(p);
2700 		return (error);
2701 	}
2702 	fdp = fdhold(p);
2703 	PROC_UNLOCK(p);
2704 	if (fdp == NULL)
2705 		return (ENOENT);
2706 	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2707 	FILEDESC_SLOCK(fdp);
2708 	if (fdp->fd_cdir != NULL)
2709 		export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2710 				fdp, req);
2711 	if (fdp->fd_rdir != NULL)
2712 		export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2713 				fdp, req);
2714 	if (fdp->fd_jdir != NULL)
2715 		export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2716 				fdp, req);
2717 	for (i = 0; i < fdp->fd_nfiles; i++) {
2718 		if ((fp = fdp->fd_ofiles[i]) == NULL)
2719 			continue;
2720 		bzero(kif, sizeof(*kif));
2721 		kif->kf_structsize = sizeof(*kif);
2722 		vp = NULL;
2723 		so = NULL;
2724 		tp = NULL;
2725 		kif->kf_fd = i;
2726 		switch (fp->f_type) {
2727 		case DTYPE_VNODE:
2728 			kif->kf_type = KF_TYPE_VNODE;
2729 			vp = fp->f_vnode;
2730 			break;
2731 
2732 		case DTYPE_SOCKET:
2733 			kif->kf_type = KF_TYPE_SOCKET;
2734 			so = fp->f_data;
2735 			break;
2736 
2737 		case DTYPE_PIPE:
2738 			kif->kf_type = KF_TYPE_PIPE;
2739 			break;
2740 
2741 		case DTYPE_FIFO:
2742 			kif->kf_type = KF_TYPE_FIFO;
2743 			vp = fp->f_vnode;
2744 			break;
2745 
2746 		case DTYPE_KQUEUE:
2747 			kif->kf_type = KF_TYPE_KQUEUE;
2748 			break;
2749 
2750 		case DTYPE_CRYPTO:
2751 			kif->kf_type = KF_TYPE_CRYPTO;
2752 			break;
2753 
2754 		case DTYPE_MQUEUE:
2755 			kif->kf_type = KF_TYPE_MQUEUE;
2756 			break;
2757 
2758 		case DTYPE_SHM:
2759 			kif->kf_type = KF_TYPE_SHM;
2760 			break;
2761 
2762 		case DTYPE_SEM:
2763 			kif->kf_type = KF_TYPE_SEM;
2764 			break;
2765 
2766 		case DTYPE_PTS:
2767 			kif->kf_type = KF_TYPE_PTS;
2768 			tp = fp->f_data;
2769 			break;
2770 
2771 		default:
2772 			kif->kf_type = KF_TYPE_UNKNOWN;
2773 			break;
2774 		}
2775 		kif->kf_ref_count = fp->f_count;
2776 		if (fp->f_flag & FREAD)
2777 			kif->kf_flags |= KF_FLAG_READ;
2778 		if (fp->f_flag & FWRITE)
2779 			kif->kf_flags |= KF_FLAG_WRITE;
2780 		if (fp->f_flag & FAPPEND)
2781 			kif->kf_flags |= KF_FLAG_APPEND;
2782 		if (fp->f_flag & FASYNC)
2783 			kif->kf_flags |= KF_FLAG_ASYNC;
2784 		if (fp->f_flag & FFSYNC)
2785 			kif->kf_flags |= KF_FLAG_FSYNC;
2786 		if (fp->f_flag & FNONBLOCK)
2787 			kif->kf_flags |= KF_FLAG_NONBLOCK;
2788 		if (fp->f_flag & O_DIRECT)
2789 			kif->kf_flags |= KF_FLAG_DIRECT;
2790 		if (fp->f_flag & FHASLOCK)
2791 			kif->kf_flags |= KF_FLAG_HASLOCK;
2792 		kif->kf_offset = fp->f_offset;
2793 		if (vp != NULL) {
2794 			vref(vp);
2795 			switch (vp->v_type) {
2796 			case VNON:
2797 				kif->kf_vnode_type = KF_VTYPE_VNON;
2798 				break;
2799 			case VREG:
2800 				kif->kf_vnode_type = KF_VTYPE_VREG;
2801 				break;
2802 			case VDIR:
2803 				kif->kf_vnode_type = KF_VTYPE_VDIR;
2804 				break;
2805 			case VBLK:
2806 				kif->kf_vnode_type = KF_VTYPE_VBLK;
2807 				break;
2808 			case VCHR:
2809 				kif->kf_vnode_type = KF_VTYPE_VCHR;
2810 				break;
2811 			case VLNK:
2812 				kif->kf_vnode_type = KF_VTYPE_VLNK;
2813 				break;
2814 			case VSOCK:
2815 				kif->kf_vnode_type = KF_VTYPE_VSOCK;
2816 				break;
2817 			case VFIFO:
2818 				kif->kf_vnode_type = KF_VTYPE_VFIFO;
2819 				break;
2820 			case VBAD:
2821 				kif->kf_vnode_type = KF_VTYPE_VBAD;
2822 				break;
2823 			default:
2824 				kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2825 				break;
2826 			}
2827 			/*
2828 			 * It is OK to drop the filedesc lock here as we will
2829 			 * re-validate and re-evaluate its properties when
2830 			 * the loop continues.
2831 			 */
2832 			freepath = NULL;
2833 			fullpath = "-";
2834 			FILEDESC_SUNLOCK(fdp);
2835 			vn_fullpath(curthread, vp, &fullpath, &freepath);
2836 			vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2837 			vrele(vp);
2838 			VFS_UNLOCK_GIANT(vfslocked);
2839 			strlcpy(kif->kf_path, fullpath,
2840 			    sizeof(kif->kf_path));
2841 			if (freepath != NULL)
2842 				free(freepath, M_TEMP);
2843 			FILEDESC_SLOCK(fdp);
2844 		}
2845 		if (so != NULL) {
2846 			struct sockaddr *sa;
2847 
2848 			if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2849 			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2850 				bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2851 				free(sa, M_SONAME);
2852 			}
2853 			if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2854 			    == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2855 				bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2856 				free(sa, M_SONAME);
2857 			}
2858 			kif->kf_sock_domain =
2859 			    so->so_proto->pr_domain->dom_family;
2860 			kif->kf_sock_type = so->so_type;
2861 			kif->kf_sock_protocol = so->so_proto->pr_protocol;
2862 		}
2863 		if (tp != NULL) {
2864 			strlcpy(kif->kf_path, tty_devname(tp),
2865 			    sizeof(kif->kf_path));
2866 		}
2867 		error = SYSCTL_OUT(req, kif, sizeof(*kif));
2868 		if (error)
2869 			break;
2870 	}
2871 	FILEDESC_SUNLOCK(fdp);
2872 	fddrop(fdp);
2873 	free(kif, M_TEMP);
2874 	return (0);
2875 }
2876 
2877 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2878     sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2879 #endif	/* COMPAT_FREEBSD7 */
2880 
2881 #ifdef KINFO_FILE_SIZE
2882 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2883 #endif
2884 
2885 static int
2886 export_vnode_for_sysctl(struct vnode *vp, int type,
2887     struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2888 {
2889 	int error;
2890 	char *fullpath, *freepath;
2891 	int vfslocked;
2892 
2893 	bzero(kif, sizeof(*kif));
2894 
2895 	vref(vp);
2896 	kif->kf_fd = type;
2897 	kif->kf_type = KF_TYPE_VNODE;
2898 	/* This function only handles directories. */
2899 	if (vp->v_type != VDIR) {
2900 		vrele(vp);
2901 		return (ENOTDIR);
2902 	}
2903 	kif->kf_vnode_type = KF_VTYPE_VDIR;
2904 
2905 	/*
2906 	 * This is not a true file descriptor, so we set a bogus refcount
2907 	 * and offset to indicate these fields should be ignored.
2908 	 */
2909 	kif->kf_ref_count = -1;
2910 	kif->kf_offset = -1;
2911 
2912 	freepath = NULL;
2913 	fullpath = "-";
2914 	FILEDESC_SUNLOCK(fdp);
2915 	vn_fullpath(curthread, vp, &fullpath, &freepath);
2916 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2917 	vrele(vp);
2918 	VFS_UNLOCK_GIANT(vfslocked);
2919 	strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2920 	if (freepath != NULL)
2921 		free(freepath, M_TEMP);
2922 	/* Pack record size down */
2923 	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2924 	    strlen(kif->kf_path) + 1;
2925 	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2926 	error = SYSCTL_OUT(req, kif, kif->kf_structsize);
2927 	FILEDESC_SLOCK(fdp);
2928 	return (error);
2929 }
2930 
2931 /*
2932  * Get per-process file descriptors for use by procstat(1), et al.
2933  */
2934 static int
2935 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
2936 {
2937 	char *fullpath, *freepath;
2938 	struct kinfo_file *kif;
2939 	struct filedesc *fdp;
2940 	int error, i, *name;
2941 	struct socket *so;
2942 	struct vnode *vp;
2943 	struct file *fp;
2944 	struct proc *p;
2945 	struct tty *tp;
2946 	int vfslocked;
2947 	size_t oldidx;
2948 
2949 	name = (int *)arg1;
2950 	if ((p = pfind((pid_t)name[0])) == NULL)
2951 		return (ESRCH);
2952 	if ((error = p_candebug(curthread, p))) {
2953 		PROC_UNLOCK(p);
2954 		return (error);
2955 	}
2956 	fdp = fdhold(p);
2957 	PROC_UNLOCK(p);
2958 	if (fdp == NULL)
2959 		return (ENOENT);
2960 	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2961 	FILEDESC_SLOCK(fdp);
2962 	if (fdp->fd_cdir != NULL)
2963 		export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2964 				fdp, req);
2965 	if (fdp->fd_rdir != NULL)
2966 		export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2967 				fdp, req);
2968 	if (fdp->fd_jdir != NULL)
2969 		export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2970 				fdp, req);
2971 	for (i = 0; i < fdp->fd_nfiles; i++) {
2972 		if ((fp = fdp->fd_ofiles[i]) == NULL)
2973 			continue;
2974 		bzero(kif, sizeof(*kif));
2975 		vp = NULL;
2976 		so = NULL;
2977 		tp = NULL;
2978 		kif->kf_fd = i;
2979 		switch (fp->f_type) {
2980 		case DTYPE_VNODE:
2981 			kif->kf_type = KF_TYPE_VNODE;
2982 			vp = fp->f_vnode;
2983 			break;
2984 
2985 		case DTYPE_SOCKET:
2986 			kif->kf_type = KF_TYPE_SOCKET;
2987 			so = fp->f_data;
2988 			break;
2989 
2990 		case DTYPE_PIPE:
2991 			kif->kf_type = KF_TYPE_PIPE;
2992 			break;
2993 
2994 		case DTYPE_FIFO:
2995 			kif->kf_type = KF_TYPE_FIFO;
2996 			vp = fp->f_vnode;
2997 			break;
2998 
2999 		case DTYPE_KQUEUE:
3000 			kif->kf_type = KF_TYPE_KQUEUE;
3001 			break;
3002 
3003 		case DTYPE_CRYPTO:
3004 			kif->kf_type = KF_TYPE_CRYPTO;
3005 			break;
3006 
3007 		case DTYPE_MQUEUE:
3008 			kif->kf_type = KF_TYPE_MQUEUE;
3009 			break;
3010 
3011 		case DTYPE_SHM:
3012 			kif->kf_type = KF_TYPE_SHM;
3013 			break;
3014 
3015 		case DTYPE_SEM:
3016 			kif->kf_type = KF_TYPE_SEM;
3017 			break;
3018 
3019 		case DTYPE_PTS:
3020 			kif->kf_type = KF_TYPE_PTS;
3021 			tp = fp->f_data;
3022 			break;
3023 
3024 		default:
3025 			kif->kf_type = KF_TYPE_UNKNOWN;
3026 			break;
3027 		}
3028 		kif->kf_ref_count = fp->f_count;
3029 		if (fp->f_flag & FREAD)
3030 			kif->kf_flags |= KF_FLAG_READ;
3031 		if (fp->f_flag & FWRITE)
3032 			kif->kf_flags |= KF_FLAG_WRITE;
3033 		if (fp->f_flag & FAPPEND)
3034 			kif->kf_flags |= KF_FLAG_APPEND;
3035 		if (fp->f_flag & FASYNC)
3036 			kif->kf_flags |= KF_FLAG_ASYNC;
3037 		if (fp->f_flag & FFSYNC)
3038 			kif->kf_flags |= KF_FLAG_FSYNC;
3039 		if (fp->f_flag & FNONBLOCK)
3040 			kif->kf_flags |= KF_FLAG_NONBLOCK;
3041 		if (fp->f_flag & O_DIRECT)
3042 			kif->kf_flags |= KF_FLAG_DIRECT;
3043 		if (fp->f_flag & FHASLOCK)
3044 			kif->kf_flags |= KF_FLAG_HASLOCK;
3045 		kif->kf_offset = fp->f_offset;
3046 		if (vp != NULL) {
3047 			vref(vp);
3048 			switch (vp->v_type) {
3049 			case VNON:
3050 				kif->kf_vnode_type = KF_VTYPE_VNON;
3051 				break;
3052 			case VREG:
3053 				kif->kf_vnode_type = KF_VTYPE_VREG;
3054 				break;
3055 			case VDIR:
3056 				kif->kf_vnode_type = KF_VTYPE_VDIR;
3057 				break;
3058 			case VBLK:
3059 				kif->kf_vnode_type = KF_VTYPE_VBLK;
3060 				break;
3061 			case VCHR:
3062 				kif->kf_vnode_type = KF_VTYPE_VCHR;
3063 				break;
3064 			case VLNK:
3065 				kif->kf_vnode_type = KF_VTYPE_VLNK;
3066 				break;
3067 			case VSOCK:
3068 				kif->kf_vnode_type = KF_VTYPE_VSOCK;
3069 				break;
3070 			case VFIFO:
3071 				kif->kf_vnode_type = KF_VTYPE_VFIFO;
3072 				break;
3073 			case VBAD:
3074 				kif->kf_vnode_type = KF_VTYPE_VBAD;
3075 				break;
3076 			default:
3077 				kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3078 				break;
3079 			}
3080 			/*
3081 			 * It is OK to drop the filedesc lock here as we will
3082 			 * re-validate and re-evaluate its properties when
3083 			 * the loop continues.
3084 			 */
3085 			freepath = NULL;
3086 			fullpath = "-";
3087 			FILEDESC_SUNLOCK(fdp);
3088 			vn_fullpath(curthread, vp, &fullpath, &freepath);
3089 			vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3090 			vrele(vp);
3091 			VFS_UNLOCK_GIANT(vfslocked);
3092 			strlcpy(kif->kf_path, fullpath,
3093 			    sizeof(kif->kf_path));
3094 			if (freepath != NULL)
3095 				free(freepath, M_TEMP);
3096 			FILEDESC_SLOCK(fdp);
3097 		}
3098 		if (so != NULL) {
3099 			struct sockaddr *sa;
3100 
3101 			if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3102 			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3103 				bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3104 				free(sa, M_SONAME);
3105 			}
3106 			if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3107 			    == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3108 				bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3109 				free(sa, M_SONAME);
3110 			}
3111 			kif->kf_sock_domain =
3112 			    so->so_proto->pr_domain->dom_family;
3113 			kif->kf_sock_type = so->so_type;
3114 			kif->kf_sock_protocol = so->so_proto->pr_protocol;
3115 		}
3116 		if (tp != NULL) {
3117 			strlcpy(kif->kf_path, tty_devname(tp),
3118 			    sizeof(kif->kf_path));
3119 		}
3120 		/* Pack record size down */
3121 		kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3122 		    strlen(kif->kf_path) + 1;
3123 		kif->kf_structsize = roundup(kif->kf_structsize,
3124 		    sizeof(uint64_t));
3125 		oldidx = req->oldidx;
3126 		error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3127 		if (error) {
3128 			if (error == ENOMEM) {
3129 				/*
3130 				 * The hack to keep the ABI of sysctl
3131 				 * kern.proc.filedesc intact, but not
3132 				 * to account a partially copied
3133 				 * kinfo_file into the oldidx.
3134 				 */
3135 				req->oldidx = oldidx;
3136 				error = 0;
3137 			}
3138 			break;
3139 		}
3140 	}
3141 	FILEDESC_SUNLOCK(fdp);
3142 	fddrop(fdp);
3143 	free(kif, M_TEMP);
3144 	return (error);
3145 }
3146 
3147 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3148     sysctl_kern_proc_filedesc, "Process filedesc entries");
3149 
3150 #ifdef DDB
3151 /*
3152  * For the purposes of debugging, generate a human-readable string for the
3153  * file type.
3154  */
3155 static const char *
3156 file_type_to_name(short type)
3157 {
3158 
3159 	switch (type) {
3160 	case 0:
3161 		return ("zero");
3162 	case DTYPE_VNODE:
3163 		return ("vnod");
3164 	case DTYPE_SOCKET:
3165 		return ("sock");
3166 	case DTYPE_PIPE:
3167 		return ("pipe");
3168 	case DTYPE_FIFO:
3169 		return ("fifo");
3170 	case DTYPE_KQUEUE:
3171 		return ("kque");
3172 	case DTYPE_CRYPTO:
3173 		return ("crpt");
3174 	case DTYPE_MQUEUE:
3175 		return ("mque");
3176 	case DTYPE_SHM:
3177 		return ("shm");
3178 	case DTYPE_SEM:
3179 		return ("ksem");
3180 	default:
3181 		return ("unkn");
3182 	}
3183 }
3184 
3185 /*
3186  * For the purposes of debugging, identify a process (if any, perhaps one of
3187  * many) that references the passed file in its file descriptor array. Return
3188  * NULL if none.
3189  */
3190 static struct proc *
3191 file_to_first_proc(struct file *fp)
3192 {
3193 	struct filedesc *fdp;
3194 	struct proc *p;
3195 	int n;
3196 
3197 	FOREACH_PROC_IN_SYSTEM(p) {
3198 		if (p->p_state == PRS_NEW)
3199 			continue;
3200 		fdp = p->p_fd;
3201 		if (fdp == NULL)
3202 			continue;
3203 		for (n = 0; n < fdp->fd_nfiles; n++) {
3204 			if (fp == fdp->fd_ofiles[n])
3205 				return (p);
3206 		}
3207 	}
3208 	return (NULL);
3209 }
3210 
3211 static void
3212 db_print_file(struct file *fp, int header)
3213 {
3214 	struct proc *p;
3215 
3216 	if (header)
3217 		db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3218 		    "File", "Type", "Data", "Flag", "GCFl", "Count",
3219 		    "MCount", "Vnode", "FPID", "FCmd");
3220 	p = file_to_first_proc(fp);
3221 	db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3222 	    file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3223 	    0, fp->f_count, 0, fp->f_vnode,
3224 	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3225 }
3226 
3227 DB_SHOW_COMMAND(file, db_show_file)
3228 {
3229 	struct file *fp;
3230 
3231 	if (!have_addr) {
3232 		db_printf("usage: show file <addr>\n");
3233 		return;
3234 	}
3235 	fp = (struct file *)addr;
3236 	db_print_file(fp, 1);
3237 }
3238 
3239 DB_SHOW_COMMAND(files, db_show_files)
3240 {
3241 	struct filedesc *fdp;
3242 	struct file *fp;
3243 	struct proc *p;
3244 	int header;
3245 	int n;
3246 
3247 	header = 1;
3248 	FOREACH_PROC_IN_SYSTEM(p) {
3249 		if (p->p_state == PRS_NEW)
3250 			continue;
3251 		if ((fdp = p->p_fd) == NULL)
3252 			continue;
3253 		for (n = 0; n < fdp->fd_nfiles; ++n) {
3254 			if ((fp = fdp->fd_ofiles[n]) == NULL)
3255 				continue;
3256 			db_print_file(fp, header);
3257 			header = 0;
3258 		}
3259 	}
3260 }
3261 #endif
3262 
3263 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3264     &maxfilesperproc, 0, "Maximum files allowed open per process");
3265 
3266 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3267     &maxfiles, 0, "Maximum number of files");
3268 
3269 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3270     __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3271 
3272 /* ARGSUSED*/
3273 static void
3274 filelistinit(void *dummy)
3275 {
3276 
3277 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3278 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3279 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3280 	mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3281 }
3282 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3283 
3284 /*-------------------------------------------------------------------*/
3285 
3286 static int
3287 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3288 {
3289 
3290 	return (EBADF);
3291 }
3292 
3293 static int
3294 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3295 {
3296 
3297 	return (EINVAL);
3298 }
3299 
3300 static int
3301 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3302 {
3303 
3304 	return (EBADF);
3305 }
3306 
3307 static int
3308 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3309 {
3310 
3311 	return (0);
3312 }
3313 
3314 static int
3315 badfo_kqfilter(struct file *fp, struct knote *kn)
3316 {
3317 
3318 	return (EBADF);
3319 }
3320 
3321 static int
3322 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3323 {
3324 
3325 	return (EBADF);
3326 }
3327 
3328 static int
3329 badfo_close(struct file *fp, struct thread *td)
3330 {
3331 
3332 	return (EBADF);
3333 }
3334 
3335 struct fileops badfileops = {
3336 	.fo_read = badfo_readwrite,
3337 	.fo_write = badfo_readwrite,
3338 	.fo_truncate = badfo_truncate,
3339 	.fo_ioctl = badfo_ioctl,
3340 	.fo_poll = badfo_poll,
3341 	.fo_kqfilter = badfo_kqfilter,
3342 	.fo_stat = badfo_stat,
3343 	.fo_close = badfo_close,
3344 };
3345 
3346 
3347 /*-------------------------------------------------------------------*/
3348 
3349 /*
3350  * File Descriptor pseudo-device driver (/dev/fd/).
3351  *
3352  * Opening minor device N dup()s the file (if any) connected to file
3353  * descriptor N belonging to the calling process.  Note that this driver
3354  * consists of only the ``open()'' routine, because all subsequent
3355  * references to this file will be direct to the other driver.
3356  *
3357  * XXX: we could give this one a cloning event handler if necessary.
3358  */
3359 
3360 /* ARGSUSED */
3361 static int
3362 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3363 {
3364 
3365 	/*
3366 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3367 	 * the file descriptor being sought for duplication. The error
3368 	 * return ensures that the vnode for this device will be released
3369 	 * by vn_open. Open will detect this special error and take the
3370 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3371 	 * will simply report the error.
3372 	 */
3373 	td->td_dupfd = dev2unit(dev);
3374 	return (ENODEV);
3375 }
3376 
3377 static struct cdevsw fildesc_cdevsw = {
3378 	.d_version =	D_VERSION,
3379 	.d_open =	fdopen,
3380 	.d_name =	"FD",
3381 };
3382 
3383 static void
3384 fildesc_drvinit(void *unused)
3385 {
3386 	struct cdev *dev;
3387 
3388 	dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
3389 	make_dev_alias(dev, "stdin");
3390 	dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
3391 	make_dev_alias(dev, "stdout");
3392 	dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
3393 	make_dev_alias(dev, "stderr");
3394 }
3395 
3396 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
3397