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