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