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