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