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