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