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