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