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