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