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