xref: /freebsd/sys/kern/kern_descrip.c (revision c37420b0d5b3b6ef875fbf0b84a13f6f09be56d6)
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_compat.h"
41 
42 #include <sys/param.h>
43 #include <sys/limits.h>
44 #include <sys/systm.h>
45 #include <sys/syscallsubr.h>
46 #include <sys/sysproto.h>
47 #include <sys/conf.h>
48 #include <sys/filedesc.h>
49 #include <sys/lock.h>
50 #include <sys/jail.h>
51 #include <sys/kernel.h>
52 #include <sys/limits.h>
53 #include <sys/malloc.h>
54 #include <sys/mutex.h>
55 #include <sys/sysctl.h>
56 #include <sys/vnode.h>
57 #include <sys/mount.h>
58 #include <sys/proc.h>
59 #include <sys/namei.h>
60 #include <sys/file.h>
61 #include <sys/stat.h>
62 #include <sys/filio.h>
63 #include <sys/fcntl.h>
64 #include <sys/unistd.h>
65 #include <sys/resourcevar.h>
66 #include <sys/event.h>
67 #include <sys/sx.h>
68 #include <sys/socketvar.h>
69 #include <sys/signalvar.h>
70 
71 #include <vm/vm.h>
72 #include <vm/vm_extern.h>
73 #include <vm/uma.h>
74 
75 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
76 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
77 		     "file desc to leader structures");
78 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
79 
80 static uma_zone_t file_zone;
81 
82 static	 d_open_t  fdopen;
83 #define	NUMFDESC 64
84 
85 #define	CDEV_MAJOR 22
86 static struct cdevsw fildesc_cdevsw = {
87 	.d_version =	D_VERSION,
88 	.d_flags =	D_NEEDGIANT,
89 	.d_open =	fdopen,
90 	.d_name =	"FD",
91 	.d_maj =	CDEV_MAJOR,
92 };
93 
94 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
95 enum dup_type { DUP_VARIABLE, DUP_FIXED };
96 
97 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
98     register_t *retval);
99 static int	fd_first_free(struct filedesc *, int, int);
100 static int	fd_last_used(struct filedesc *, int, int);
101 static void	fdgrowtable(struct filedesc *, int);
102 
103 /*
104  * Descriptor management.
105  */
106 struct filelist filehead;	/* head of list of open files */
107 int nfiles;			/* actual number of open files */
108 struct sx filelist_lock;	/* sx to protect filelist */
109 struct mtx sigio_lock;		/* mtx to protect pointers to sigio */
110 
111 /*
112  * Find the first zero bit in the given bitmap, starting at low and not
113  * exceeding size - 1.
114  */
115 static int
116 fd_first_free(struct filedesc *fdp, int low, int size)
117 {
118 	NDSLOTTYPE *map = fdp->fd_map;
119 	NDSLOTTYPE mask;
120 	int off, maxoff;
121 
122 	if (low >= size)
123 		return (low);
124 
125 	off = NDSLOT(low);
126 	if (low % NDENTRIES) {
127 		mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
128 		if ((mask &= ~map[off]) != 0UL)
129 			return (off * NDENTRIES + ffsl(mask) - 1);
130 		++off;
131 	}
132 	for (maxoff = NDSLOTS(size); off < maxoff; ++off)
133 		if (map[off] != ~0UL)
134 			return (off * NDENTRIES + ffsl(~map[off]) - 1);
135 	return (size);
136 }
137 
138 /*
139  * Find the highest non-zero bit in the given bitmap, starting at low and
140  * not exceeding size - 1.
141  */
142 static int
143 fd_last_used(struct filedesc *fdp, int low, int size)
144 {
145 	NDSLOTTYPE *map = fdp->fd_map;
146 	NDSLOTTYPE mask;
147 	int off, minoff;
148 
149 	if (low >= size)
150 		return (-1);
151 
152 	off = NDSLOT(size);
153 	if (size % NDENTRIES) {
154 		mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
155 		if ((mask &= map[off]) != 0)
156 			return (off * NDENTRIES + flsl(mask) - 1);
157 		--off;
158 	}
159 	for (minoff = NDSLOT(low); off >= minoff; --off)
160 		if (map[off] != 0)
161 			return (off * NDENTRIES + flsl(map[off]) - 1);
162 	return (size - 1);
163 }
164 
165 static int
166 fdisused(struct filedesc *fdp, int fd)
167 {
168         KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
169             ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
170 	return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
171 }
172 
173 /*
174  * Mark a file descriptor as used.
175  */
176 void
177 fdused(struct filedesc *fdp, int fd)
178 {
179 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
180 	KASSERT(!fdisused(fdp, fd),
181 	    ("fd already used"));
182 	fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
183 	if (fd > fdp->fd_lastfile)
184 		fdp->fd_lastfile = fd;
185 	if (fd == fdp->fd_freefile)
186 		fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
187 }
188 
189 /*
190  * Mark a file descriptor as unused.
191  */
192 void
193 fdunused(struct filedesc *fdp, int fd)
194 {
195 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
196 	KASSERT(fdisused(fdp, fd),
197 	    ("fd is already unused"));
198 	KASSERT(fdp->fd_ofiles[fd] == NULL,
199 	    ("fd is still in use"));
200 	fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
201 	if (fd < fdp->fd_freefile)
202 		fdp->fd_freefile = fd;
203 	if (fd == fdp->fd_lastfile)
204 		fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
205 }
206 
207 /*
208  * System calls on descriptors.
209  */
210 #ifndef _SYS_SYSPROTO_H_
211 struct getdtablesize_args {
212 	int	dummy;
213 };
214 #endif
215 /*
216  * MPSAFE
217  */
218 /* ARGSUSED */
219 int
220 getdtablesize(td, uap)
221 	struct thread *td;
222 	struct getdtablesize_args *uap;
223 {
224 	struct proc *p = td->td_proc;
225 
226 	PROC_LOCK(p);
227 	td->td_retval[0] =
228 	    min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
229 	PROC_UNLOCK(p);
230 	return (0);
231 }
232 
233 /*
234  * Duplicate a file descriptor to a particular value.
235  *
236  * note: keep in mind that a potential race condition exists when closing
237  * descriptors from a shared descriptor table (via rfork).
238  */
239 #ifndef _SYS_SYSPROTO_H_
240 struct dup2_args {
241 	u_int	from;
242 	u_int	to;
243 };
244 #endif
245 /*
246  * MPSAFE
247  */
248 /* ARGSUSED */
249 int
250 dup2(td, uap)
251 	struct thread *td;
252 	struct dup2_args *uap;
253 {
254 
255 	return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
256 		    td->td_retval));
257 }
258 
259 /*
260  * Duplicate a file descriptor.
261  */
262 #ifndef _SYS_SYSPROTO_H_
263 struct dup_args {
264 	u_int	fd;
265 };
266 #endif
267 /*
268  * MPSAFE
269  */
270 /* ARGSUSED */
271 int
272 dup(td, uap)
273 	struct thread *td;
274 	struct dup_args *uap;
275 {
276 
277 	return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
278 }
279 
280 /*
281  * The file control system call.
282  */
283 #ifndef _SYS_SYSPROTO_H_
284 struct fcntl_args {
285 	int	fd;
286 	int	cmd;
287 	long	arg;
288 };
289 #endif
290 /*
291  * MPSAFE
292  */
293 /* ARGSUSED */
294 int
295 fcntl(td, uap)
296 	struct thread *td;
297 	struct fcntl_args *uap;
298 {
299 	struct flock fl;
300 	intptr_t arg;
301 	int error;
302 
303 	error = 0;
304 	switch (uap->cmd) {
305 	case F_GETLK:
306 	case F_SETLK:
307 	case F_SETLKW:
308 		error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
309 		arg = (intptr_t)&fl;
310 		break;
311 	default:
312 		arg = uap->arg;
313 		break;
314 	}
315 	if (error)
316 		return (error);
317 	error = kern_fcntl(td, uap->fd, uap->cmd, arg);
318 	if (error)
319 		return (error);
320 	if (uap->cmd == F_GETLK)
321 		error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
322 	return (error);
323 }
324 
325 int
326 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
327 {
328 	struct filedesc *fdp;
329 	struct flock *flp;
330 	struct file *fp;
331 	struct proc *p;
332 	char *pop;
333 	struct vnode *vp;
334 	u_int newmin;
335 	int error, flg, tmp;
336 	int giant_locked;
337 
338 	/*
339 	 * XXXRW: Some fcntl() calls require Giant -- others don't.  Try to
340 	 * avoid grabbing Giant for calls we know don't need it.
341 	 */
342 	switch (cmd) {
343 	case F_DUPFD:
344 	case F_GETFD:
345 	case F_SETFD:
346 	case F_GETFL:
347 		giant_locked = 0;
348 		break;
349 
350 	default:
351 		giant_locked = 1;
352 		mtx_lock(&Giant);
353 	}
354 
355 	error = 0;
356 	flg = F_POSIX;
357 	p = td->td_proc;
358 	fdp = p->p_fd;
359 	FILEDESC_LOCK(fdp);
360 	if ((unsigned)fd >= fdp->fd_nfiles ||
361 	    (fp = fdp->fd_ofiles[fd]) == NULL) {
362 		FILEDESC_UNLOCK(fdp);
363 		error = EBADF;
364 		goto done2;
365 	}
366 	pop = &fdp->fd_ofileflags[fd];
367 
368 	switch (cmd) {
369 	case F_DUPFD:
370 		/* mtx_assert(&Giant, MA_NOTOWNED); */
371 		FILEDESC_UNLOCK(fdp);
372 		newmin = arg;
373 		PROC_LOCK(p);
374 		if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
375 		    newmin >= maxfilesperproc) {
376 			PROC_UNLOCK(p);
377 			error = EINVAL;
378 			break;
379 		}
380 		PROC_UNLOCK(p);
381 		error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
382 		break;
383 
384 	case F_GETFD:
385 		/* mtx_assert(&Giant, MA_NOTOWNED); */
386 		td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
387 		FILEDESC_UNLOCK(fdp);
388 		break;
389 
390 	case F_SETFD:
391 		/* mtx_assert(&Giant, MA_NOTOWNED); */
392 		*pop = (*pop &~ UF_EXCLOSE) |
393 		    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
394 		FILEDESC_UNLOCK(fdp);
395 		break;
396 
397 	case F_GETFL:
398 		/* mtx_assert(&Giant, MA_NOTOWNED); */
399 		FILE_LOCK(fp);
400 		FILEDESC_UNLOCK(fdp);
401 		td->td_retval[0] = OFLAGS(fp->f_flag);
402 		FILE_UNLOCK(fp);
403 		break;
404 
405 	case F_SETFL:
406 		mtx_assert(&Giant, MA_OWNED);
407 		FILE_LOCK(fp);
408 		FILEDESC_UNLOCK(fdp);
409 		fhold_locked(fp);
410 		fp->f_flag &= ~FCNTLFLAGS;
411 		fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
412 		FILE_UNLOCK(fp);
413 		tmp = fp->f_flag & FNONBLOCK;
414 		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
415 		if (error) {
416 			fdrop(fp, td);
417 			break;
418 		}
419 		tmp = fp->f_flag & FASYNC;
420 		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
421 		if (error == 0) {
422 			fdrop(fp, td);
423 			break;
424 		}
425 		FILE_LOCK(fp);
426 		fp->f_flag &= ~FNONBLOCK;
427 		FILE_UNLOCK(fp);
428 		tmp = 0;
429 		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
430 		fdrop(fp, td);
431 		break;
432 
433 	case F_GETOWN:
434 		mtx_assert(&Giant, MA_OWNED);
435 		fhold(fp);
436 		FILEDESC_UNLOCK(fdp);
437 		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
438 		if (error == 0)
439 			td->td_retval[0] = tmp;
440 		fdrop(fp, td);
441 		break;
442 
443 	case F_SETOWN:
444 		mtx_assert(&Giant, MA_OWNED);
445 		fhold(fp);
446 		FILEDESC_UNLOCK(fdp);
447 		tmp = arg;
448 		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
449 		fdrop(fp, td);
450 		break;
451 
452 	case F_SETLKW:
453 		mtx_assert(&Giant, MA_OWNED);
454 		flg |= F_WAIT;
455 		/* FALLTHROUGH F_SETLK */
456 
457 	case F_SETLK:
458 		mtx_assert(&Giant, MA_OWNED);
459 		if (fp->f_type != DTYPE_VNODE) {
460 			FILEDESC_UNLOCK(fdp);
461 			error = EBADF;
462 			break;
463 		}
464 
465 		flp = (struct flock *)arg;
466 		if (flp->l_whence == SEEK_CUR) {
467 			if (fp->f_offset < 0 ||
468 			    (flp->l_start > 0 &&
469 			     fp->f_offset > OFF_MAX - flp->l_start)) {
470 				FILEDESC_UNLOCK(fdp);
471 				error = EOVERFLOW;
472 				break;
473 			}
474 			flp->l_start += fp->f_offset;
475 		}
476 
477 		/*
478 		 * VOP_ADVLOCK() may block.
479 		 */
480 		fhold(fp);
481 		FILEDESC_UNLOCK(fdp);
482 		vp = fp->f_vnode;
483 
484 		switch (flp->l_type) {
485 		case F_RDLCK:
486 			if ((fp->f_flag & FREAD) == 0) {
487 				error = EBADF;
488 				break;
489 			}
490 			PROC_LOCK(p->p_leader);
491 			p->p_leader->p_flag |= P_ADVLOCK;
492 			PROC_UNLOCK(p->p_leader);
493 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
494 			    flp, flg);
495 			break;
496 		case F_WRLCK:
497 			if ((fp->f_flag & FWRITE) == 0) {
498 				error = EBADF;
499 				break;
500 			}
501 			PROC_LOCK(p->p_leader);
502 			p->p_leader->p_flag |= P_ADVLOCK;
503 			PROC_UNLOCK(p->p_leader);
504 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
505 			    flp, flg);
506 			break;
507 		case F_UNLCK:
508 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
509 			    flp, F_POSIX);
510 			break;
511 		default:
512 			error = EINVAL;
513 			break;
514 		}
515 		/* Check for race with close */
516 		FILEDESC_LOCK(fdp);
517 		if ((unsigned) fd >= fdp->fd_nfiles ||
518 		    fp != fdp->fd_ofiles[fd]) {
519 			FILEDESC_UNLOCK(fdp);
520 			flp->l_whence = SEEK_SET;
521 			flp->l_start = 0;
522 			flp->l_len = 0;
523 			flp->l_type = F_UNLCK;
524 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
525 					   F_UNLCK, flp, F_POSIX);
526 		} else
527 			FILEDESC_UNLOCK(fdp);
528 		fdrop(fp, td);
529 		break;
530 
531 	case F_GETLK:
532 		mtx_assert(&Giant, MA_OWNED);
533 		if (fp->f_type != DTYPE_VNODE) {
534 			FILEDESC_UNLOCK(fdp);
535 			error = EBADF;
536 			break;
537 		}
538 		flp = (struct flock *)arg;
539 		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
540 		    flp->l_type != F_UNLCK) {
541 			FILEDESC_UNLOCK(fdp);
542 			error = EINVAL;
543 			break;
544 		}
545 		if (flp->l_whence == SEEK_CUR) {
546 			if ((flp->l_start > 0 &&
547 			    fp->f_offset > OFF_MAX - flp->l_start) ||
548 			    (flp->l_start < 0 &&
549 			     fp->f_offset < OFF_MIN - flp->l_start)) {
550 				FILEDESC_UNLOCK(fdp);
551 				error = EOVERFLOW;
552 				break;
553 			}
554 			flp->l_start += fp->f_offset;
555 		}
556 		/*
557 		 * VOP_ADVLOCK() may block.
558 		 */
559 		fhold(fp);
560 		FILEDESC_UNLOCK(fdp);
561 		vp = fp->f_vnode;
562 		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
563 		    F_POSIX);
564 		fdrop(fp, td);
565 		break;
566 	default:
567 		FILEDESC_UNLOCK(fdp);
568 		error = EINVAL;
569 		break;
570 	}
571 done2:
572 	if (giant_locked)
573 		mtx_unlock(&Giant);
574 	return (error);
575 }
576 
577 /*
578  * Common code for dup, dup2, and fcntl(F_DUPFD).
579  */
580 static int
581 do_dup(td, type, old, new, retval)
582 	enum dup_type type;
583 	int old, new;
584 	register_t *retval;
585 	struct thread *td;
586 {
587 	struct filedesc *fdp;
588 	struct proc *p;
589 	struct file *fp;
590 	struct file *delfp;
591 	int error, holdleaders, maxfd;
592 
593 	KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
594 	    ("invalid dup type %d", type));
595 
596 	p = td->td_proc;
597 	fdp = p->p_fd;
598 
599 	/*
600 	 * Verify we have a valid descriptor to dup from and possibly to
601 	 * dup to.
602 	 */
603 	if (old < 0 || new < 0)
604 		return (EBADF);
605 	PROC_LOCK(p);
606 	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
607 	PROC_UNLOCK(p);
608 	if (new >= maxfd)
609 		return (EMFILE);
610 
611 	FILEDESC_LOCK(fdp);
612 	if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
613 		FILEDESC_UNLOCK(fdp);
614 		return (EBADF);
615 	}
616 	if (type == DUP_FIXED && old == new) {
617 		*retval = new;
618 		FILEDESC_UNLOCK(fdp);
619 		return (0);
620 	}
621 	fp = fdp->fd_ofiles[old];
622 	fhold(fp);
623 
624 	/*
625 	 * If the caller specified a file descriptor, make sure the file
626 	 * table is large enough to hold it, and grab it.  Otherwise, just
627 	 * allocate a new descriptor the usual way.  Since the filedesc
628 	 * lock may be temporarily dropped in the process, we have to look
629 	 * out for a race.
630 	 */
631 	if (type == DUP_FIXED) {
632 		if (new >= fdp->fd_nfiles)
633 			fdgrowtable(fdp, new + 1);
634 		if (fdp->fd_ofiles[new] == NULL)
635 			fdused(fdp, new);
636 	} else {
637 		if ((error = fdalloc(td, new, &new)) != 0) {
638 			FILEDESC_UNLOCK(fdp);
639 			fdrop(fp, td);
640 			return (error);
641 		}
642 	}
643 
644 	/*
645 	 * If the old file changed out from under us then treat it as a
646 	 * bad file descriptor.  Userland should do its own locking to
647 	 * avoid this case.
648 	 */
649 	if (fdp->fd_ofiles[old] != fp) {
650 		/* we've allocated a descriptor which we won't use */
651 		if (fdp->fd_ofiles[new] == NULL)
652 			fdunused(fdp, new);
653 		FILEDESC_UNLOCK(fdp);
654 		fdrop(fp, td);
655 		return (EBADF);
656 	}
657 	KASSERT(old != new,
658 	    ("new fd is same as old"));
659 
660 	/*
661 	 * Save info on the descriptor being overwritten.  We cannot close
662 	 * it without introducing an ownership race for the slot, since we
663 	 * need to drop the filedesc lock to call closef().
664 	 *
665 	 * XXX this duplicates parts of close().
666 	 */
667 	delfp = fdp->fd_ofiles[new];
668 	holdleaders = 0;
669 	if (delfp != NULL) {
670 		if (td->td_proc->p_fdtol != NULL) {
671 			/*
672 			 * Ask fdfree() to sleep to ensure that all relevant
673 			 * process leaders can be traversed in closef().
674 			 */
675 			fdp->fd_holdleaderscount++;
676 			holdleaders = 1;
677 		}
678 	}
679 
680 	/*
681 	 * Duplicate the source descriptor
682 	 */
683 	fdp->fd_ofiles[new] = fp;
684 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
685 	if (new > fdp->fd_lastfile)
686 		fdp->fd_lastfile = new;
687 	*retval = new;
688 
689 	/*
690 	 * If we dup'd over a valid file, we now own the reference to it
691 	 * and must dispose of it using closef() semantics (as if a
692 	 * close() were performed on it).
693 	 *
694 	 * XXX this duplicates parts of close().
695 	 */
696 	if (delfp != NULL) {
697 		knote_fdclose(td, new);
698 		FILEDESC_UNLOCK(fdp);
699 		mtx_lock(&Giant);
700 		(void) closef(delfp, td);
701 		mtx_unlock(&Giant);
702 		if (holdleaders) {
703 			FILEDESC_LOCK(fdp);
704 			fdp->fd_holdleaderscount--;
705 			if (fdp->fd_holdleaderscount == 0 &&
706 			    fdp->fd_holdleaderswakeup != 0) {
707 				fdp->fd_holdleaderswakeup = 0;
708 				wakeup(&fdp->fd_holdleaderscount);
709 			}
710 			FILEDESC_UNLOCK(fdp);
711 		}
712 	} else {
713 		FILEDESC_UNLOCK(fdp);
714 	}
715 	return (0);
716 }
717 
718 /*
719  * If sigio is on the list associated with a process or process group,
720  * disable signalling from the device, remove sigio from the list and
721  * free sigio.
722  */
723 void
724 funsetown(sigiop)
725 	struct sigio **sigiop;
726 {
727 	struct sigio *sigio;
728 
729 	SIGIO_LOCK();
730 	sigio = *sigiop;
731 	if (sigio == NULL) {
732 		SIGIO_UNLOCK();
733 		return;
734 	}
735 	*(sigio->sio_myref) = NULL;
736 	if ((sigio)->sio_pgid < 0) {
737 		struct pgrp *pg = (sigio)->sio_pgrp;
738 		PGRP_LOCK(pg);
739 		SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
740 			     sigio, sio_pgsigio);
741 		PGRP_UNLOCK(pg);
742 	} else {
743 		struct proc *p = (sigio)->sio_proc;
744 		PROC_LOCK(p);
745 		SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
746 			     sigio, sio_pgsigio);
747 		PROC_UNLOCK(p);
748 	}
749 	SIGIO_UNLOCK();
750 	crfree(sigio->sio_ucred);
751 	FREE(sigio, M_SIGIO);
752 }
753 
754 /*
755  * Free a list of sigio structures.
756  * We only need to lock the SIGIO_LOCK because we have made ourselves
757  * inaccessable to callers of fsetown and therefore do not need to lock
758  * the proc or pgrp struct for the list manipulation.
759  */
760 void
761 funsetownlst(sigiolst)
762 	struct sigiolst *sigiolst;
763 {
764 	struct proc *p;
765 	struct pgrp *pg;
766 	struct sigio *sigio;
767 
768 	sigio = SLIST_FIRST(sigiolst);
769 	if (sigio == NULL)
770 		return;
771 	p = NULL;
772 	pg = NULL;
773 
774 	/*
775 	 * Every entry of the list should belong
776 	 * to a single proc or pgrp.
777 	 */
778 	if (sigio->sio_pgid < 0) {
779 		pg = sigio->sio_pgrp;
780 		PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
781 	} else /* if (sigio->sio_pgid > 0) */ {
782 		p = sigio->sio_proc;
783 		PROC_LOCK_ASSERT(p, MA_NOTOWNED);
784 	}
785 
786 	SIGIO_LOCK();
787 	while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
788 		*(sigio->sio_myref) = NULL;
789 		if (pg != NULL) {
790 			KASSERT(sigio->sio_pgid < 0,
791 			    ("Proc sigio in pgrp sigio list"));
792 			KASSERT(sigio->sio_pgrp == pg,
793 			    ("Bogus pgrp in sigio list"));
794 			PGRP_LOCK(pg);
795 			SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
796 			    sio_pgsigio);
797 			PGRP_UNLOCK(pg);
798 		} else /* if (p != NULL) */ {
799 			KASSERT(sigio->sio_pgid > 0,
800 			    ("Pgrp sigio in proc sigio list"));
801 			KASSERT(sigio->sio_proc == p,
802 			    ("Bogus proc in sigio list"));
803 			PROC_LOCK(p);
804 			SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
805 			    sio_pgsigio);
806 			PROC_UNLOCK(p);
807 		}
808 		SIGIO_UNLOCK();
809 		crfree(sigio->sio_ucred);
810 		FREE(sigio, M_SIGIO);
811 		SIGIO_LOCK();
812 	}
813 	SIGIO_UNLOCK();
814 }
815 
816 /*
817  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
818  *
819  * After permission checking, add a sigio structure to the sigio list for
820  * the process or process group.
821  */
822 int
823 fsetown(pgid, sigiop)
824 	pid_t pgid;
825 	struct sigio **sigiop;
826 {
827 	struct proc *proc;
828 	struct pgrp *pgrp;
829 	struct sigio *sigio;
830 	int ret;
831 
832 	if (pgid == 0) {
833 		funsetown(sigiop);
834 		return (0);
835 	}
836 
837 	ret = 0;
838 
839 	/* Allocate and fill in the new sigio out of locks. */
840 	MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
841 	sigio->sio_pgid = pgid;
842 	sigio->sio_ucred = crhold(curthread->td_ucred);
843 	sigio->sio_myref = sigiop;
844 
845 	sx_slock(&proctree_lock);
846 	if (pgid > 0) {
847 		proc = pfind(pgid);
848 		if (proc == NULL) {
849 			ret = ESRCH;
850 			goto fail;
851 		}
852 
853 		/*
854 		 * Policy - Don't allow a process to FSETOWN a process
855 		 * in another session.
856 		 *
857 		 * Remove this test to allow maximum flexibility or
858 		 * restrict FSETOWN to the current process or process
859 		 * group for maximum safety.
860 		 */
861 		PROC_UNLOCK(proc);
862 		if (proc->p_session != curthread->td_proc->p_session) {
863 			ret = EPERM;
864 			goto fail;
865 		}
866 
867 		pgrp = NULL;
868 	} else /* if (pgid < 0) */ {
869 		pgrp = pgfind(-pgid);
870 		if (pgrp == NULL) {
871 			ret = ESRCH;
872 			goto fail;
873 		}
874 		PGRP_UNLOCK(pgrp);
875 
876 		/*
877 		 * Policy - Don't allow a process to FSETOWN a process
878 		 * in another session.
879 		 *
880 		 * Remove this test to allow maximum flexibility or
881 		 * restrict FSETOWN to the current process or process
882 		 * group for maximum safety.
883 		 */
884 		if (pgrp->pg_session != curthread->td_proc->p_session) {
885 			ret = EPERM;
886 			goto fail;
887 		}
888 
889 		proc = NULL;
890 	}
891 	funsetown(sigiop);
892 	if (pgid > 0) {
893 		PROC_LOCK(proc);
894 		/*
895 		 * Since funsetownlst() is called without the proctree
896 		 * locked, we need to check for P_WEXIT.
897 		 * XXX: is ESRCH correct?
898 		 */
899 		if ((proc->p_flag & P_WEXIT) != 0) {
900 			PROC_UNLOCK(proc);
901 			ret = ESRCH;
902 			goto fail;
903 		}
904 		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
905 		sigio->sio_proc = proc;
906 		PROC_UNLOCK(proc);
907 	} else {
908 		PGRP_LOCK(pgrp);
909 		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
910 		sigio->sio_pgrp = pgrp;
911 		PGRP_UNLOCK(pgrp);
912 	}
913 	sx_sunlock(&proctree_lock);
914 	SIGIO_LOCK();
915 	*sigiop = sigio;
916 	SIGIO_UNLOCK();
917 	return (0);
918 
919 fail:
920 	sx_sunlock(&proctree_lock);
921 	crfree(sigio->sio_ucred);
922 	FREE(sigio, M_SIGIO);
923 	return (ret);
924 }
925 
926 /*
927  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
928  */
929 pid_t
930 fgetown(sigiop)
931 	struct sigio **sigiop;
932 {
933 	pid_t pgid;
934 
935 	SIGIO_LOCK();
936 	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
937 	SIGIO_UNLOCK();
938 	return (pgid);
939 }
940 
941 /*
942  * Close a file descriptor.
943  */
944 #ifndef _SYS_SYSPROTO_H_
945 struct close_args {
946 	int     fd;
947 };
948 #endif
949 /*
950  * MPSAFE
951  */
952 /* ARGSUSED */
953 int
954 close(td, uap)
955 	struct thread *td;
956 	struct close_args *uap;
957 {
958 	struct filedesc *fdp;
959 	struct file *fp;
960 	int fd, error;
961 	int holdleaders;
962 
963 	fd = uap->fd;
964 	error = 0;
965 	holdleaders = 0;
966 	fdp = td->td_proc->p_fd;
967 	mtx_lock(&Giant);
968 	FILEDESC_LOCK(fdp);
969 	if ((unsigned)fd >= fdp->fd_nfiles ||
970 	    (fp = fdp->fd_ofiles[fd]) == NULL) {
971 		FILEDESC_UNLOCK(fdp);
972 		mtx_unlock(&Giant);
973 		return (EBADF);
974 	}
975 	fdp->fd_ofiles[fd] = NULL;
976 	fdp->fd_ofileflags[fd] = 0;
977 	fdunused(fdp, fd);
978 	if (td->td_proc->p_fdtol != NULL) {
979 		/*
980 		 * Ask fdfree() to sleep to ensure that all relevant
981 		 * process leaders can be traversed in closef().
982 		 */
983 		fdp->fd_holdleaderscount++;
984 		holdleaders = 1;
985 	}
986 
987 	/*
988 	 * we now hold the fp reference that used to be owned by the descriptor
989 	 * array.
990 	 * We have to unlock the FILEDESC *AFTER* knote_fdclose to prevent a
991 	 * race of the fd getting opened, a knote added, and deleteing a knote
992 	 * for the new fd.
993 	 */
994 	knote_fdclose(td, fd);
995 	FILEDESC_UNLOCK(fdp);
996 
997 	error = closef(fp, td);
998 	mtx_unlock(&Giant);
999 	if (holdleaders) {
1000 		FILEDESC_LOCK(fdp);
1001 		fdp->fd_holdleaderscount--;
1002 		if (fdp->fd_holdleaderscount == 0 &&
1003 		    fdp->fd_holdleaderswakeup != 0) {
1004 			fdp->fd_holdleaderswakeup = 0;
1005 			wakeup(&fdp->fd_holdleaderscount);
1006 		}
1007 		FILEDESC_UNLOCK(fdp);
1008 	}
1009 	return (error);
1010 }
1011 
1012 #if defined(COMPAT_43)
1013 /*
1014  * Return status information about a file descriptor.
1015  */
1016 #ifndef _SYS_SYSPROTO_H_
1017 struct ofstat_args {
1018 	int	fd;
1019 	struct	ostat *sb;
1020 };
1021 #endif
1022 /*
1023  * MPSAFE
1024  */
1025 /* ARGSUSED */
1026 int
1027 ofstat(td, uap)
1028 	struct thread *td;
1029 	struct ofstat_args *uap;
1030 {
1031 	struct file *fp;
1032 	struct stat ub;
1033 	struct ostat oub;
1034 	int error;
1035 
1036 	if ((error = fget(td, uap->fd, &fp)) != 0)
1037 		goto done2;
1038 	error = fo_stat(fp, &ub, td->td_ucred, td);
1039 	if (error == 0) {
1040 		cvtstat(&ub, &oub);
1041 		error = copyout(&oub, uap->sb, sizeof(oub));
1042 	}
1043 	fdrop(fp, td);
1044 done2:
1045 	return (error);
1046 }
1047 #endif /* COMPAT_43 */
1048 
1049 /*
1050  * Return status information about a file descriptor.
1051  */
1052 #ifndef _SYS_SYSPROTO_H_
1053 struct fstat_args {
1054 	int	fd;
1055 	struct	stat *sb;
1056 };
1057 #endif
1058 /*
1059  * MPSAFE
1060  */
1061 /* ARGSUSED */
1062 int
1063 fstat(td, uap)
1064 	struct thread *td;
1065 	struct fstat_args *uap;
1066 {
1067 	struct file *fp;
1068 	struct stat ub;
1069 	int error;
1070 
1071 	if ((error = fget(td, uap->fd, &fp)) != 0)
1072 		goto done2;
1073 	error = fo_stat(fp, &ub, td->td_ucred, td);
1074 	if (error == 0)
1075 		error = copyout(&ub, uap->sb, sizeof(ub));
1076 	fdrop(fp, td);
1077 done2:
1078 	return (error);
1079 }
1080 
1081 /*
1082  * Return status information about a file descriptor.
1083  */
1084 #ifndef _SYS_SYSPROTO_H_
1085 struct nfstat_args {
1086 	int	fd;
1087 	struct	nstat *sb;
1088 };
1089 #endif
1090 /*
1091  * MPSAFE
1092  */
1093 /* ARGSUSED */
1094 int
1095 nfstat(td, uap)
1096 	struct thread *td;
1097 	struct nfstat_args *uap;
1098 {
1099 	struct file *fp;
1100 	struct stat ub;
1101 	struct nstat nub;
1102 	int error;
1103 
1104 	if ((error = fget(td, uap->fd, &fp)) != 0)
1105 		goto done2;
1106 	error = fo_stat(fp, &ub, td->td_ucred, td);
1107 	if (error == 0) {
1108 		cvtnstat(&ub, &nub);
1109 		error = copyout(&nub, uap->sb, sizeof(nub));
1110 	}
1111 	fdrop(fp, td);
1112 done2:
1113 	return (error);
1114 }
1115 
1116 /*
1117  * Return pathconf information about a file descriptor.
1118  */
1119 #ifndef _SYS_SYSPROTO_H_
1120 struct fpathconf_args {
1121 	int	fd;
1122 	int	name;
1123 };
1124 #endif
1125 /*
1126  * MPSAFE
1127  */
1128 /* ARGSUSED */
1129 int
1130 fpathconf(td, uap)
1131 	struct thread *td;
1132 	struct fpathconf_args *uap;
1133 {
1134 	struct file *fp;
1135 	struct vnode *vp;
1136 	int error;
1137 
1138 	if ((error = fget(td, uap->fd, &fp)) != 0)
1139 		return (error);
1140 
1141 	/* If asynchronous I/O is available, it works for all descriptors. */
1142 	if (uap->name == _PC_ASYNC_IO) {
1143 		td->td_retval[0] = async_io_version;
1144 		goto out;
1145 	}
1146 	vp = fp->f_vnode;
1147 	if (vp != NULL) {
1148 		mtx_lock(&Giant);
1149 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1150 		error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1151 		VOP_UNLOCK(vp, 0, td);
1152 		mtx_unlock(&Giant);
1153 	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1154 		if (uap->name != _PC_PIPE_BUF) {
1155 			error = EINVAL;
1156 		} else {
1157 			td->td_retval[0] = PIPE_BUF;
1158 		error = 0;
1159 		}
1160 	} else {
1161 		error = EOPNOTSUPP;
1162 	}
1163 out:
1164 	fdrop(fp, td);
1165 	return (error);
1166 }
1167 
1168 /*
1169  * Grow the file table to accomodate (at least) nfd descriptors.  This may
1170  * block and drop the filedesc lock, but it will reacquire it before
1171  * returing.
1172  */
1173 static void
1174 fdgrowtable(struct filedesc *fdp, int nfd)
1175 {
1176 	struct file **ntable;
1177 	char *nfileflags;
1178 	int nnfiles, onfiles;
1179 	NDSLOTTYPE *nmap;
1180 
1181 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1182 
1183 	KASSERT(fdp->fd_nfiles > 0,
1184 	    ("zero-length file table"));
1185 
1186 	/* compute the size of the new table */
1187 	onfiles = fdp->fd_nfiles;
1188 	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1189 	if (nnfiles <= onfiles)
1190 		/* the table is already large enough */
1191 		return;
1192 
1193 	/* allocate a new table and (if required) new bitmaps */
1194 	FILEDESC_UNLOCK(fdp);
1195 	MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1196 	    M_FILEDESC, M_ZERO | M_WAITOK);
1197 	nfileflags = (char *)&ntable[nnfiles];
1198 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1199 		MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1200 		    M_FILEDESC, M_ZERO | M_WAITOK);
1201 	else
1202 		nmap = NULL;
1203 	FILEDESC_LOCK(fdp);
1204 
1205 	/*
1206 	 * We now have new tables ready to go.  Since we dropped the
1207 	 * filedesc lock to call malloc(), watch out for a race.
1208 	 */
1209 	onfiles = fdp->fd_nfiles;
1210 	if (onfiles >= nnfiles) {
1211 		/* we lost the race, but that's OK */
1212 		free(ntable, M_FILEDESC);
1213 		if (nmap != NULL)
1214 			free(nmap, M_FILEDESC);
1215 		return;
1216 	}
1217 	bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1218 	bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1219 	if (onfiles > NDFILE)
1220 		free(fdp->fd_ofiles, M_FILEDESC);
1221 	fdp->fd_ofiles = ntable;
1222 	fdp->fd_ofileflags = nfileflags;
1223 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1224 		bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1225 		if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1226 			free(fdp->fd_map, M_FILEDESC);
1227 		fdp->fd_map = nmap;
1228 	}
1229 	fdp->fd_nfiles = nnfiles;
1230 }
1231 
1232 /*
1233  * Allocate a file descriptor for the process.
1234  */
1235 int
1236 fdalloc(struct thread *td, int minfd, int *result)
1237 {
1238 	struct proc *p = td->td_proc;
1239 	struct filedesc *fdp = p->p_fd;
1240 	int fd = -1, maxfd;
1241 
1242 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1243 
1244 	PROC_LOCK(p);
1245 	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1246 	PROC_UNLOCK(p);
1247 
1248 	/*
1249 	 * Search the bitmap for a free descriptor.  If none is found, try
1250 	 * to grow the file table.  Keep at it until we either get a file
1251 	 * descriptor or run into process or system limits; fdgrowtable()
1252 	 * may drop the filedesc lock, so we're in a race.
1253 	 */
1254 	for (;;) {
1255 		fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1256 		if (fd >= maxfd)
1257 			return (EMFILE);
1258 		if (fd < fdp->fd_nfiles)
1259 			break;
1260 		fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1261 	}
1262 
1263 	/*
1264 	 * Perform some sanity checks, then mark the file descriptor as
1265 	 * used and return it to the caller.
1266 	 */
1267 	KASSERT(!fdisused(fdp, fd),
1268 	    ("fd_first_free() returned non-free descriptor"));
1269 	KASSERT(fdp->fd_ofiles[fd] == NULL,
1270 	    ("free descriptor isn't"));
1271 	fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1272 	fdused(fdp, fd);
1273 	fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
1274 	*result = fd;
1275 	return (0);
1276 }
1277 
1278 /*
1279  * Check to see whether n user file descriptors
1280  * are available to the process p.
1281  */
1282 int
1283 fdavail(td, n)
1284 	struct thread *td;
1285 	int n;
1286 {
1287 	struct proc *p = td->td_proc;
1288 	struct filedesc *fdp = td->td_proc->p_fd;
1289 	struct file **fpp;
1290 	int i, lim, last;
1291 
1292 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1293 
1294 	PROC_LOCK(p);
1295 	lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1296 	PROC_UNLOCK(p);
1297 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1298 		return (1);
1299 	last = min(fdp->fd_nfiles, lim);
1300 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1301 	for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1302 		if (*fpp == NULL && --n <= 0)
1303 			return (1);
1304 	}
1305 	return (0);
1306 }
1307 
1308 /*
1309  * Create a new open file structure and allocate
1310  * a file decriptor for the process that refers to it.
1311  * We add one reference to the file for the descriptor table
1312  * and one reference for resultfp. This is to prevent us being
1313  * prempted and the entry in the descriptor table closed after
1314  * we release the FILEDESC lock.
1315  */
1316 int
1317 falloc(td, resultfp, resultfd)
1318 	struct thread *td;
1319 	struct file **resultfp;
1320 	int *resultfd;
1321 {
1322 	struct proc *p = td->td_proc;
1323 	struct file *fp, *fq;
1324 	int error, i;
1325 	int maxuserfiles = maxfiles - (maxfiles / 20);
1326 	static struct timeval lastfail;
1327 	static int curfail;
1328 
1329 	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1330 	sx_xlock(&filelist_lock);
1331 	if ((nfiles >= maxuserfiles && (td->td_ucred->cr_ruid != 0 ||
1332 	   jailed(td->td_ucred))) || nfiles >= maxfiles) {
1333 		if (ppsratecheck(&lastfail, &curfail, 1)) {
1334 			printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1335 				td->td_ucred->cr_ruid);
1336 		}
1337 		sx_xunlock(&filelist_lock);
1338 		uma_zfree(file_zone, fp);
1339 		return (ENFILE);
1340 	}
1341 	nfiles++;
1342 
1343 	/*
1344 	 * If the process has file descriptor zero open, add the new file
1345 	 * descriptor to the list of open files at that point, otherwise
1346 	 * put it at the front of the list of open files.
1347 	 */
1348 	fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1349 	fp->f_count = 1;
1350 	if (resultfp)
1351 		fp->f_count++;
1352 	fp->f_cred = crhold(td->td_ucred);
1353 	fp->f_ops = &badfileops;
1354 	fp->f_data = NULL;
1355 	fp->f_vnode = NULL;
1356 	FILEDESC_LOCK(p->p_fd);
1357 	if ((fq = p->p_fd->fd_ofiles[0])) {
1358 		LIST_INSERT_AFTER(fq, fp, f_list);
1359 	} else {
1360 		LIST_INSERT_HEAD(&filehead, fp, f_list);
1361 	}
1362 	sx_xunlock(&filelist_lock);
1363 	if ((error = fdalloc(td, 0, &i))) {
1364 		FILEDESC_UNLOCK(p->p_fd);
1365 		fdrop(fp, td);
1366 		if (resultfp)
1367 			fdrop(fp, td);
1368 		return (error);
1369 	}
1370 	p->p_fd->fd_ofiles[i] = fp;
1371 	FILEDESC_UNLOCK(p->p_fd);
1372 	if (resultfp)
1373 		*resultfp = fp;
1374 	if (resultfd)
1375 		*resultfd = i;
1376 	return (0);
1377 }
1378 
1379 /*
1380  * Free a file descriptor.
1381  */
1382 void
1383 ffree(fp)
1384 	struct file *fp;
1385 {
1386 
1387 	KASSERT(fp->f_count == 0, ("ffree: fp_fcount not 0!"));
1388 	sx_xlock(&filelist_lock);
1389 	LIST_REMOVE(fp, f_list);
1390 	nfiles--;
1391 	sx_xunlock(&filelist_lock);
1392 	crfree(fp->f_cred);
1393 	uma_zfree(file_zone, fp);
1394 }
1395 
1396 /*
1397  * Build a new filedesc structure from another.
1398  * Copy the current, root, and jail root vnode references.
1399  */
1400 struct filedesc *
1401 fdinit(fdp)
1402 	struct filedesc *fdp;
1403 {
1404 	struct filedesc0 *newfdp;
1405 
1406 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1407 
1408 	FILEDESC_UNLOCK(fdp);
1409 	MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
1410 	    M_FILEDESC, M_WAITOK | M_ZERO);
1411 	FILEDESC_LOCK(fdp);
1412 	mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1413 	newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1414 	if (newfdp->fd_fd.fd_cdir)
1415 		VREF(newfdp->fd_fd.fd_cdir);
1416 	newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1417 	if (newfdp->fd_fd.fd_rdir)
1418 		VREF(newfdp->fd_fd.fd_rdir);
1419 	newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1420 	if (newfdp->fd_fd.fd_jdir)
1421 		VREF(newfdp->fd_fd.fd_jdir);
1422 
1423 	/* Create the file descriptor table. */
1424 	newfdp->fd_fd.fd_refcnt = 1;
1425 	newfdp->fd_fd.fd_cmask = CMASK;
1426 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1427 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1428 	newfdp->fd_fd.fd_nfiles = NDFILE;
1429 	newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1430 	return (&newfdp->fd_fd);
1431 }
1432 
1433 /*
1434  * Share a filedesc structure.
1435  */
1436 struct filedesc *
1437 fdshare(fdp)
1438 	struct filedesc *fdp;
1439 {
1440 	FILEDESC_LOCK(fdp);
1441 	fdp->fd_refcnt++;
1442 	FILEDESC_UNLOCK(fdp);
1443 	return (fdp);
1444 }
1445 
1446 /*
1447  * Copy a filedesc structure.
1448  * A NULL pointer in returns a NULL reference, this is to ease callers,
1449  * not catch errors.
1450  */
1451 struct filedesc *
1452 fdcopy(fdp)
1453 	struct filedesc *fdp;
1454 {
1455 	struct filedesc *newfdp;
1456 	int i;
1457 
1458 	/* Certain daemons might not have file descriptors. */
1459 	if (fdp == NULL)
1460 		return (NULL);
1461 
1462 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1463 	newfdp = fdinit(fdp);
1464 	while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1465 		FILEDESC_UNLOCK(fdp);
1466 		FILEDESC_LOCK(newfdp);
1467 		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1468 		FILEDESC_UNLOCK(newfdp);
1469 		FILEDESC_LOCK(fdp);
1470 	}
1471 	/* copy everything except kqueue descriptors */
1472 	newfdp->fd_freefile = -1;
1473 	for (i = 0; i <= fdp->fd_lastfile; ++i) {
1474 		if (fdisused(fdp, i) &&
1475 		    fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE) {
1476 			newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1477 			newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1478 			fhold(newfdp->fd_ofiles[i]);
1479 			newfdp->fd_lastfile = i;
1480 		} else {
1481 			if (newfdp->fd_freefile == -1)
1482 				newfdp->fd_freefile = i;
1483 		}
1484 	}
1485 	FILEDESC_UNLOCK(fdp);
1486 	FILEDESC_LOCK(newfdp);
1487 	for (i = 0; i <= newfdp->fd_lastfile; ++i)
1488 		if (newfdp->fd_ofiles[i] != NULL)
1489 			fdused(newfdp, i);
1490 	FILEDESC_UNLOCK(newfdp);
1491 	FILEDESC_LOCK(fdp);
1492 	if (newfdp->fd_freefile == -1)
1493 		newfdp->fd_freefile = i;
1494 	newfdp->fd_cmask = fdp->fd_cmask;
1495 	return (newfdp);
1496 }
1497 
1498 /* A mutex to protect the association between a proc and filedesc. */
1499 struct mtx	fdesc_mtx;
1500 MTX_SYSINIT(fdesc, &fdesc_mtx, "fdesc", MTX_DEF);
1501 
1502 /*
1503  * Release a filedesc structure.
1504  */
1505 void
1506 fdfree(td)
1507 	struct thread *td;
1508 {
1509 	struct filedesc *fdp;
1510 	struct file **fpp;
1511 	int i;
1512 	struct filedesc_to_leader *fdtol;
1513 	struct file *fp;
1514 	struct vnode *vp;
1515 	struct flock lf;
1516 
1517 	GIANT_REQUIRED;		/* VFS */
1518 
1519 	/* Certain daemons might not have file descriptors. */
1520 	fdp = td->td_proc->p_fd;
1521 	if (fdp == NULL)
1522 		return;
1523 
1524 	/* Check for special need to clear POSIX style locks */
1525 	fdtol = td->td_proc->p_fdtol;
1526 	if (fdtol != NULL) {
1527 		FILEDESC_LOCK(fdp);
1528 		KASSERT(fdtol->fdl_refcount > 0,
1529 			("filedesc_to_refcount botch: fdl_refcount=%d",
1530 			 fdtol->fdl_refcount));
1531 		if (fdtol->fdl_refcount == 1 &&
1532 		    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1533 			i = 0;
1534 			fpp = fdp->fd_ofiles;
1535 			for (i = 0, fpp = fdp->fd_ofiles;
1536 			     i <= fdp->fd_lastfile;
1537 			     i++, fpp++) {
1538 				if (*fpp == NULL ||
1539 				    (*fpp)->f_type != DTYPE_VNODE)
1540 					continue;
1541 				fp = *fpp;
1542 				fhold(fp);
1543 				FILEDESC_UNLOCK(fdp);
1544 				lf.l_whence = SEEK_SET;
1545 				lf.l_start = 0;
1546 				lf.l_len = 0;
1547 				lf.l_type = F_UNLCK;
1548 				vp = fp->f_vnode;
1549 				(void) VOP_ADVLOCK(vp,
1550 						   (caddr_t)td->td_proc->
1551 						   p_leader,
1552 						   F_UNLCK,
1553 						   &lf,
1554 						   F_POSIX);
1555 				FILEDESC_LOCK(fdp);
1556 				fdrop(fp, td);
1557 				fpp = fdp->fd_ofiles + i;
1558 			}
1559 		}
1560 	retry:
1561 		if (fdtol->fdl_refcount == 1) {
1562 			if (fdp->fd_holdleaderscount > 0 &&
1563 			    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1564 				/*
1565 				 * close() or do_dup() has cleared a reference
1566 				 * in a shared file descriptor table.
1567 				 */
1568 				fdp->fd_holdleaderswakeup = 1;
1569 				msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
1570 				       PLOCK, "fdlhold", 0);
1571 				goto retry;
1572 			}
1573 			if (fdtol->fdl_holdcount > 0) {
1574 				/*
1575 				 * Ensure that fdtol->fdl_leader
1576 				 * remains valid in closef().
1577 				 */
1578 				fdtol->fdl_wakeup = 1;
1579 				msleep(fdtol, &fdp->fd_mtx,
1580 				       PLOCK, "fdlhold", 0);
1581 				goto retry;
1582 			}
1583 		}
1584 		fdtol->fdl_refcount--;
1585 		if (fdtol->fdl_refcount == 0 &&
1586 		    fdtol->fdl_holdcount == 0) {
1587 			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1588 			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1589 		} else
1590 			fdtol = NULL;
1591 		td->td_proc->p_fdtol = NULL;
1592 		FILEDESC_UNLOCK(fdp);
1593 		if (fdtol != NULL)
1594 			FREE(fdtol, M_FILEDESC_TO_LEADER);
1595 	}
1596 	FILEDESC_LOCK(fdp);
1597 	if (--fdp->fd_refcnt > 0) {
1598 		FILEDESC_UNLOCK(fdp);
1599 		return;
1600 	}
1601 
1602 	/*
1603 	 * We are the last reference to the structure, so we can
1604 	 * safely assume it will not change out from under us.
1605 	 */
1606 	FILEDESC_UNLOCK(fdp);
1607 	fpp = fdp->fd_ofiles;
1608 	for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1609 		if (*fpp)
1610 			(void) closef(*fpp, td);
1611 	}
1612 
1613 	/* XXX This should happen earlier. */
1614 	mtx_lock(&fdesc_mtx);
1615 	td->td_proc->p_fd = NULL;
1616 	mtx_unlock(&fdesc_mtx);
1617 
1618 	if (fdp->fd_nfiles > NDFILE)
1619 		FREE(fdp->fd_ofiles, M_FILEDESC);
1620 	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1621 		FREE(fdp->fd_map, M_FILEDESC);
1622 	if (fdp->fd_cdir)
1623 		vrele(fdp->fd_cdir);
1624 	if (fdp->fd_rdir)
1625 		vrele(fdp->fd_rdir);
1626 	if (fdp->fd_jdir)
1627 		vrele(fdp->fd_jdir);
1628 	mtx_destroy(&fdp->fd_mtx);
1629 	FREE(fdp, M_FILEDESC);
1630 }
1631 
1632 /*
1633  * For setugid programs, we don't want to people to use that setugidness
1634  * to generate error messages which write to a file which otherwise would
1635  * otherwise be off-limits to the process.  We check for filesystems where
1636  * the vnode can change out from under us after execve (like [lin]procfs).
1637  *
1638  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1639  * sufficient.  We also don't for check setugidness since we know we are.
1640  */
1641 static int
1642 is_unsafe(struct file *fp)
1643 {
1644 	if (fp->f_type == DTYPE_VNODE) {
1645 		struct vnode *vp = fp->f_vnode;
1646 
1647 		if ((vp->v_vflag & VV_PROCDEP) != 0)
1648 			return (1);
1649 	}
1650 	return (0);
1651 }
1652 
1653 /*
1654  * Make this setguid thing safe, if at all possible.
1655  */
1656 void
1657 setugidsafety(td)
1658 	struct thread *td;
1659 {
1660 	struct filedesc *fdp;
1661 	int i;
1662 
1663 	GIANT_REQUIRED;		/* kqueue */
1664 
1665 	/* Certain daemons might not have file descriptors. */
1666 	fdp = td->td_proc->p_fd;
1667 	if (fdp == NULL)
1668 		return;
1669 
1670 	/*
1671 	 * Note: fdp->fd_ofiles may be reallocated out from under us while
1672 	 * we are blocked in a close.  Be careful!
1673 	 */
1674 	FILEDESC_LOCK(fdp);
1675 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1676 		if (i > 2)
1677 			break;
1678 		if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1679 			struct file *fp;
1680 
1681 			knote_fdclose(td, i);
1682 			/*
1683 			 * NULL-out descriptor prior to close to avoid
1684 			 * a race while close blocks.
1685 			 */
1686 			fp = fdp->fd_ofiles[i];
1687 			fdp->fd_ofiles[i] = NULL;
1688 			fdp->fd_ofileflags[i] = 0;
1689 			fdunused(fdp, i);
1690 			FILEDESC_UNLOCK(fdp);
1691 			(void) closef(fp, td);
1692 			FILEDESC_LOCK(fdp);
1693 		}
1694 	}
1695 	FILEDESC_UNLOCK(fdp);
1696 }
1697 
1698 /*
1699  * Close any files on exec?
1700  */
1701 void
1702 fdcloseexec(td)
1703 	struct thread *td;
1704 {
1705 	struct filedesc *fdp;
1706 	int i;
1707 
1708 	/* Certain daemons might not have file descriptors. */
1709 	fdp = td->td_proc->p_fd;
1710 	if (fdp == NULL)
1711 		return;
1712 
1713 	FILEDESC_LOCK(fdp);
1714 
1715 	/*
1716 	 * We cannot cache fd_ofiles or fd_ofileflags since operations
1717 	 * may block and rip them out from under us.
1718 	 */
1719 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1720 		if (fdp->fd_ofiles[i] != NULL &&
1721 		    (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1722 			struct file *fp;
1723 
1724 			knote_fdclose(td, i);
1725 			/*
1726 			 * NULL-out descriptor prior to close to avoid
1727 			 * a race while close blocks.
1728 			 */
1729 			fp = fdp->fd_ofiles[i];
1730 			fdp->fd_ofiles[i] = NULL;
1731 			fdp->fd_ofileflags[i] = 0;
1732 			fdunused(fdp, i);
1733 			FILEDESC_UNLOCK(fdp);
1734 			(void) closef(fp, td);
1735 			FILEDESC_LOCK(fdp);
1736 		}
1737 	}
1738 	FILEDESC_UNLOCK(fdp);
1739 }
1740 
1741 /*
1742  * It is unsafe for set[ug]id processes to be started with file
1743  * descriptors 0..2 closed, as these descriptors are given implicit
1744  * significance in the Standard C library.  fdcheckstd() will create a
1745  * descriptor referencing /dev/null for each of stdin, stdout, and
1746  * stderr that is not already open.
1747  */
1748 int
1749 fdcheckstd(td)
1750 	struct thread *td;
1751 {
1752 	struct nameidata nd;
1753 	struct filedesc *fdp;
1754 	struct file *fp;
1755 	register_t retval;
1756 	int fd, i, error, flags, devnull;
1757 
1758 	GIANT_REQUIRED;		/* VFS */
1759 
1760 	fdp = td->td_proc->p_fd;
1761 	if (fdp == NULL)
1762 		return (0);
1763 	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1764 	devnull = -1;
1765 	error = 0;
1766 	for (i = 0; i < 3; i++) {
1767 		if (fdp->fd_ofiles[i] != NULL)
1768 			continue;
1769 		if (devnull < 0) {
1770 			error = falloc(td, &fp, &fd);
1771 			if (error != 0)
1772 				break;
1773 			/* Note extra ref on `fp' held for us by falloc(). */
1774 			KASSERT(fd == i, ("oof, we didn't get our fd"));
1775 			NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null",
1776 			    td);
1777 			flags = FREAD | FWRITE;
1778 			error = vn_open(&nd, &flags, 0, -1);
1779 			if (error != 0) {
1780 				/*
1781 				 * Someone may have closed the entry in the
1782 				 * file descriptor table, so check it hasn't
1783 				 * changed before dropping the reference count.
1784 				 */
1785 				FILEDESC_LOCK(fdp);
1786 				KASSERT(fdp->fd_ofiles[fd] == fp,
1787 				    ("table not shared, how did it change?"));
1788 				fdp->fd_ofiles[fd] = NULL;
1789 				fdunused(fdp, fd);
1790 				FILEDESC_UNLOCK(fdp);
1791 				fdrop(fp, td);
1792 				fdrop(fp, td);
1793 				break;
1794 			}
1795 			NDFREE(&nd, NDF_ONLY_PNBUF);
1796 			fp->f_vnode = nd.ni_vp;
1797 			fp->f_data = nd.ni_vp;
1798 			fp->f_flag = flags;
1799 			fp->f_ops = &vnops;
1800 			fp->f_type = DTYPE_VNODE;
1801 			VOP_UNLOCK(nd.ni_vp, 0, td);
1802 			devnull = fd;
1803 			fdrop(fp, td);
1804 		} else {
1805 			error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1806 			if (error != 0)
1807 				break;
1808 		}
1809 	}
1810 	return (error);
1811 }
1812 
1813 /*
1814  * Internal form of close.
1815  * Decrement reference count on file structure.
1816  * Note: td may be NULL when closing a file
1817  * that was being passed in a message.
1818  */
1819 int
1820 closef(fp, td)
1821 	struct file *fp;
1822 	struct thread *td;
1823 {
1824 	struct vnode *vp;
1825 	struct flock lf;
1826 	struct filedesc_to_leader *fdtol;
1827 	struct filedesc *fdp;
1828 
1829 	if (fp == NULL)
1830 		return (0);
1831 	/*
1832 	 * POSIX record locking dictates that any close releases ALL
1833 	 * locks owned by this process.  This is handled by setting
1834 	 * a flag in the unlock to free ONLY locks obeying POSIX
1835 	 * semantics, and not to free BSD-style file locks.
1836 	 * If the descriptor was in a message, POSIX-style locks
1837 	 * aren't passed with the descriptor.
1838 	 */
1839 	if (td != NULL &&
1840 	    fp->f_type == DTYPE_VNODE) {
1841 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1842 			lf.l_whence = SEEK_SET;
1843 			lf.l_start = 0;
1844 			lf.l_len = 0;
1845 			lf.l_type = F_UNLCK;
1846 			vp = fp->f_vnode;
1847 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1848 					   F_UNLCK, &lf, F_POSIX);
1849 		}
1850 		fdtol = td->td_proc->p_fdtol;
1851 		if (fdtol != NULL) {
1852 			/*
1853 			 * Handle special case where file descriptor table
1854 			 * is shared between multiple process leaders.
1855 			 */
1856 			fdp = td->td_proc->p_fd;
1857 			FILEDESC_LOCK(fdp);
1858 			for (fdtol = fdtol->fdl_next;
1859 			     fdtol != td->td_proc->p_fdtol;
1860 			     fdtol = fdtol->fdl_next) {
1861 				if ((fdtol->fdl_leader->p_flag &
1862 				     P_ADVLOCK) == 0)
1863 					continue;
1864 				fdtol->fdl_holdcount++;
1865 				FILEDESC_UNLOCK(fdp);
1866 				lf.l_whence = SEEK_SET;
1867 				lf.l_start = 0;
1868 				lf.l_len = 0;
1869 				lf.l_type = F_UNLCK;
1870 				vp = fp->f_vnode;
1871 				(void) VOP_ADVLOCK(vp,
1872 						   (caddr_t)fdtol->fdl_leader,
1873 						   F_UNLCK, &lf, F_POSIX);
1874 				FILEDESC_LOCK(fdp);
1875 				fdtol->fdl_holdcount--;
1876 				if (fdtol->fdl_holdcount == 0 &&
1877 				    fdtol->fdl_wakeup != 0) {
1878 					fdtol->fdl_wakeup = 0;
1879 					wakeup(fdtol);
1880 				}
1881 			}
1882 			FILEDESC_UNLOCK(fdp);
1883 		}
1884 	}
1885 	return (fdrop(fp, td));
1886 }
1887 
1888 /*
1889  * Drop reference on struct file passed in, may call closef if the
1890  * reference hits zero.
1891  */
1892 int
1893 fdrop(fp, td)
1894 	struct file *fp;
1895 	struct thread *td;
1896 {
1897 
1898 	FILE_LOCK(fp);
1899 	return (fdrop_locked(fp, td));
1900 }
1901 
1902 /*
1903  * Extract the file pointer associated with the specified descriptor for
1904  * the current user process.
1905  *
1906  * If the descriptor doesn't exist, EBADF is returned.
1907  *
1908  * If the descriptor exists but doesn't match 'flags' then
1909  * return EBADF for read attempts and EINVAL for write attempts.
1910  *
1911  * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1912  * It should be droped with fdrop().
1913  * If it is not set, then the refcount will not be bumped however the
1914  * thread's filedesc struct will be returned locked (for fgetsock).
1915  *
1916  * If an error occured the non-zero error is returned and *fpp is set to NULL.
1917  * Otherwise *fpp is set and zero is returned.
1918  */
1919 static __inline int
1920 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1921 {
1922 	struct filedesc *fdp;
1923 	struct file *fp;
1924 
1925 	*fpp = NULL;
1926 	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1927 		return (EBADF);
1928 	FILEDESC_LOCK(fdp);
1929 	if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1930 		FILEDESC_UNLOCK(fdp);
1931 		return (EBADF);
1932 	}
1933 
1934 	/*
1935 	 * Note: FREAD failures returns EBADF to maintain backwards
1936 	 * compatibility with what routines returned before.
1937 	 *
1938 	 * Only one flag, or 0, may be specified.
1939 	 */
1940 	if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1941 		FILEDESC_UNLOCK(fdp);
1942 		return (EBADF);
1943 	}
1944 	if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
1945 		FILEDESC_UNLOCK(fdp);
1946 		return (EINVAL);
1947 	}
1948 	if (hold) {
1949 		fhold(fp);
1950 		FILEDESC_UNLOCK(fdp);
1951 	}
1952 	*fpp = fp;
1953 	return (0);
1954 }
1955 
1956 int
1957 fget(struct thread *td, int fd, struct file **fpp)
1958 {
1959 
1960 	return(_fget(td, fd, fpp, 0, 1));
1961 }
1962 
1963 int
1964 fget_read(struct thread *td, int fd, struct file **fpp)
1965 {
1966 
1967 	return(_fget(td, fd, fpp, FREAD, 1));
1968 }
1969 
1970 int
1971 fget_write(struct thread *td, int fd, struct file **fpp)
1972 {
1973 
1974 	return(_fget(td, fd, fpp, FWRITE, 1));
1975 }
1976 
1977 /*
1978  * Like fget() but loads the underlying vnode, or returns an error if
1979  * the descriptor does not represent a vnode.  Note that pipes use vnodes
1980  * but never have VM objects (so VOP_GETVOBJECT() calls will return an
1981  * error).  The returned vnode will be vref()d.
1982  */
1983 static __inline int
1984 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
1985 {
1986 	struct file *fp;
1987 	int error;
1988 
1989 	GIANT_REQUIRED;		/* VFS */
1990 
1991 	*vpp = NULL;
1992 	if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
1993 		return (error);
1994 	if (fp->f_vnode == NULL) {
1995 		error = EINVAL;
1996 	} else {
1997 		*vpp = fp->f_vnode;
1998 		vref(*vpp);
1999 	}
2000 	FILEDESC_UNLOCK(td->td_proc->p_fd);
2001 	return (error);
2002 }
2003 
2004 int
2005 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2006 {
2007 
2008 	return (_fgetvp(td, fd, vpp, 0));
2009 }
2010 
2011 int
2012 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2013 {
2014 
2015 	return (_fgetvp(td, fd, vpp, FREAD));
2016 }
2017 
2018 int
2019 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2020 {
2021 
2022 	return (_fgetvp(td, fd, vpp, FWRITE));
2023 }
2024 
2025 /*
2026  * Like fget() but loads the underlying socket, or returns an error if
2027  * the descriptor does not represent a socket.
2028  *
2029  * We bump the ref count on the returned socket.  XXX Also obtain the SX
2030  * lock in the future.
2031  */
2032 int
2033 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2034 {
2035 	struct file *fp;
2036 	int error;
2037 
2038 	NET_ASSERT_GIANT();
2039 
2040 	*spp = NULL;
2041 	if (fflagp != NULL)
2042 		*fflagp = 0;
2043 	if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2044 		return (error);
2045 	if (fp->f_type != DTYPE_SOCKET) {
2046 		error = ENOTSOCK;
2047 	} else {
2048 		*spp = fp->f_data;
2049 		if (fflagp)
2050 			*fflagp = fp->f_flag;
2051 		SOCK_LOCK(*spp);
2052 		soref(*spp);
2053 		SOCK_UNLOCK(*spp);
2054 	}
2055 	FILEDESC_UNLOCK(td->td_proc->p_fd);
2056 	return (error);
2057 }
2058 
2059 /*
2060  * Drop the reference count on the the socket and XXX release the SX lock in
2061  * the future.  The last reference closes the socket.
2062  */
2063 void
2064 fputsock(struct socket *so)
2065 {
2066 
2067 	NET_ASSERT_GIANT();
2068 	SOCK_LOCK(so);
2069 	sorele(so);
2070 }
2071 
2072 /*
2073  * Drop reference on struct file passed in, may call closef if the
2074  * reference hits zero.
2075  * Expects struct file locked, and will unlock it.
2076  */
2077 int
2078 fdrop_locked(fp, td)
2079 	struct file *fp;
2080 	struct thread *td;
2081 {
2082 	int error;
2083 
2084 	FILE_LOCK_ASSERT(fp, MA_OWNED);
2085 
2086 	if (--fp->f_count > 0) {
2087 		FILE_UNLOCK(fp);
2088 		return (0);
2089 	}
2090 	/* We have the last ref so we can proceed without the file lock. */
2091 	FILE_UNLOCK(fp);
2092 	if (fp->f_count < 0)
2093 		panic("fdrop: count < 0");
2094 	if (fp->f_ops != &badfileops)
2095 		error = fo_close(fp, td);
2096 	else
2097 		error = 0;
2098 	ffree(fp);
2099 	return (error);
2100 }
2101 
2102 /*
2103  * Apply an advisory lock on a file descriptor.
2104  *
2105  * Just attempt to get a record lock of the requested type on
2106  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2107  */
2108 #ifndef _SYS_SYSPROTO_H_
2109 struct flock_args {
2110 	int	fd;
2111 	int	how;
2112 };
2113 #endif
2114 /*
2115  * MPSAFE
2116  */
2117 /* ARGSUSED */
2118 int
2119 flock(td, uap)
2120 	struct thread *td;
2121 	struct flock_args *uap;
2122 {
2123 	struct file *fp;
2124 	struct vnode *vp;
2125 	struct flock lf;
2126 	int error;
2127 
2128 	if ((error = fget(td, uap->fd, &fp)) != 0)
2129 		return (error);
2130 	if (fp->f_type != DTYPE_VNODE) {
2131 		fdrop(fp, td);
2132 		return (EOPNOTSUPP);
2133 	}
2134 
2135 	mtx_lock(&Giant);
2136 	vp = fp->f_vnode;
2137 	lf.l_whence = SEEK_SET;
2138 	lf.l_start = 0;
2139 	lf.l_len = 0;
2140 	if (uap->how & LOCK_UN) {
2141 		lf.l_type = F_UNLCK;
2142 		FILE_LOCK(fp);
2143 		fp->f_flag &= ~FHASLOCK;
2144 		FILE_UNLOCK(fp);
2145 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2146 		goto done2;
2147 	}
2148 	if (uap->how & LOCK_EX)
2149 		lf.l_type = F_WRLCK;
2150 	else if (uap->how & LOCK_SH)
2151 		lf.l_type = F_RDLCK;
2152 	else {
2153 		error = EBADF;
2154 		goto done2;
2155 	}
2156 	FILE_LOCK(fp);
2157 	fp->f_flag |= FHASLOCK;
2158 	FILE_UNLOCK(fp);
2159 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2160 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2161 done2:
2162 	fdrop(fp, td);
2163 	mtx_unlock(&Giant);
2164 	return (error);
2165 }
2166 
2167 /*
2168  * File Descriptor pseudo-device driver (/dev/fd/).
2169  *
2170  * Opening minor device N dup()s the file (if any) connected to file
2171  * descriptor N belonging to the calling process.  Note that this driver
2172  * consists of only the ``open()'' routine, because all subsequent
2173  * references to this file will be direct to the other driver.
2174  */
2175 /* ARGSUSED */
2176 static int
2177 fdopen(dev, mode, type, td)
2178 	struct cdev *dev;
2179 	int mode, type;
2180 	struct thread *td;
2181 {
2182 
2183 	/*
2184 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2185 	 * the file descriptor being sought for duplication. The error
2186 	 * return ensures that the vnode for this device will be released
2187 	 * by vn_open. Open will detect this special error and take the
2188 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2189 	 * will simply report the error.
2190 	 */
2191 	td->td_dupfd = dev2unit(dev);
2192 	return (ENODEV);
2193 }
2194 
2195 /*
2196  * Duplicate the specified descriptor to a free descriptor.
2197  */
2198 int
2199 dupfdopen(td, fdp, indx, dfd, mode, error)
2200 	struct thread *td;
2201 	struct filedesc *fdp;
2202 	int indx, dfd;
2203 	int mode;
2204 	int error;
2205 {
2206 	struct file *wfp;
2207 	struct file *fp;
2208 
2209 	/*
2210 	 * If the to-be-dup'd fd number is greater than the allowed number
2211 	 * of file descriptors, or the fd to be dup'd has already been
2212 	 * closed, then reject.
2213 	 */
2214 	FILEDESC_LOCK(fdp);
2215 	if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2216 	    (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2217 		FILEDESC_UNLOCK(fdp);
2218 		return (EBADF);
2219 	}
2220 
2221 	/*
2222 	 * There are two cases of interest here.
2223 	 *
2224 	 * For ENODEV simply dup (dfd) to file descriptor
2225 	 * (indx) and return.
2226 	 *
2227 	 * For ENXIO steal away the file structure from (dfd) and
2228 	 * store it in (indx).  (dfd) is effectively closed by
2229 	 * this operation.
2230 	 *
2231 	 * Any other error code is just returned.
2232 	 */
2233 	switch (error) {
2234 	case ENODEV:
2235 		/*
2236 		 * Check that the mode the file is being opened for is a
2237 		 * subset of the mode of the existing descriptor.
2238 		 */
2239 		FILE_LOCK(wfp);
2240 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2241 			FILE_UNLOCK(wfp);
2242 			FILEDESC_UNLOCK(fdp);
2243 			return (EACCES);
2244 		}
2245 		fp = fdp->fd_ofiles[indx];
2246 		fdp->fd_ofiles[indx] = wfp;
2247 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2248 		if (fp == NULL)
2249 			fdused(fdp, indx);
2250 		fhold_locked(wfp);
2251 		FILE_UNLOCK(wfp);
2252 		if (fp != NULL)
2253 			FILE_LOCK(fp);
2254 		FILEDESC_UNLOCK(fdp);
2255 		/*
2256 		 * We now own the reference to fp that the ofiles[] array
2257 		 * used to own.  Release it.
2258 		 */
2259 		if (fp != NULL)
2260 			fdrop_locked(fp, td);
2261 		return (0);
2262 
2263 	case ENXIO:
2264 		/*
2265 		 * Steal away the file pointer from dfd and stuff it into indx.
2266 		 */
2267 		fp = fdp->fd_ofiles[indx];
2268 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2269 		fdp->fd_ofiles[dfd] = NULL;
2270 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2271 		fdp->fd_ofileflags[dfd] = 0;
2272 		fdunused(fdp, dfd);
2273 		if (fp == NULL)
2274 			fdused(fdp, indx);
2275 		if (fp != NULL)
2276 			FILE_LOCK(fp);
2277 		FILEDESC_UNLOCK(fdp);
2278 
2279 		/*
2280 		 * we now own the reference to fp that the ofiles[] array
2281 		 * used to own.  Release it.
2282 		 */
2283 		if (fp != NULL)
2284 			fdrop_locked(fp, td);
2285 		return (0);
2286 
2287 	default:
2288 		FILEDESC_UNLOCK(fdp);
2289 		return (error);
2290 	}
2291 	/* NOTREACHED */
2292 }
2293 
2294 struct filedesc_to_leader *
2295 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2296 			 struct filedesc *fdp,
2297 			 struct proc *leader)
2298 {
2299 	struct filedesc_to_leader *fdtol;
2300 
2301 	MALLOC(fdtol, struct filedesc_to_leader *,
2302 	       sizeof(struct filedesc_to_leader),
2303 	       M_FILEDESC_TO_LEADER,
2304 	       M_WAITOK);
2305 	fdtol->fdl_refcount = 1;
2306 	fdtol->fdl_holdcount = 0;
2307 	fdtol->fdl_wakeup = 0;
2308 	fdtol->fdl_leader = leader;
2309 	if (old != NULL) {
2310 		FILEDESC_LOCK(fdp);
2311 		fdtol->fdl_next = old->fdl_next;
2312 		fdtol->fdl_prev = old;
2313 		old->fdl_next = fdtol;
2314 		fdtol->fdl_next->fdl_prev = fdtol;
2315 		FILEDESC_UNLOCK(fdp);
2316 	} else {
2317 		fdtol->fdl_next = fdtol;
2318 		fdtol->fdl_prev = fdtol;
2319 	}
2320 	return (fdtol);
2321 }
2322 
2323 /*
2324  * Get file structures.
2325  */
2326 static int
2327 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2328 {
2329 	struct xfile xf;
2330 	struct filedesc *fdp;
2331 	struct file *fp;
2332 	struct proc *p;
2333 	int error, n;
2334 
2335 	/*
2336 	 * Note: because the number of file descriptors is calculated
2337 	 * in different ways for sizing vs returning the data,
2338 	 * there is information leakage from the first loop.  However,
2339 	 * it is of a similar order of magnitude to the leakage from
2340 	 * global system statistics such as kern.openfiles.
2341 	 */
2342 	error = sysctl_wire_old_buffer(req, 0);
2343 	if (error != 0)
2344 		return (error);
2345 	if (req->oldptr == NULL) {
2346 		n = 16;		/* A slight overestimate. */
2347 		sx_slock(&filelist_lock);
2348 		LIST_FOREACH(fp, &filehead, f_list) {
2349 			/*
2350 			 * We should grab the lock, but this is an
2351 			 * estimate, so does it really matter?
2352 			 */
2353 			/* mtx_lock(fp->f_mtxp); */
2354 			n += fp->f_count;
2355 			/* mtx_unlock(f->f_mtxp); */
2356 		}
2357 		sx_sunlock(&filelist_lock);
2358 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2359 	}
2360 	error = 0;
2361 	bzero(&xf, sizeof(xf));
2362 	xf.xf_size = sizeof(xf);
2363 	sx_slock(&allproc_lock);
2364 	LIST_FOREACH(p, &allproc, p_list) {
2365 		PROC_LOCK(p);
2366 		if (p_cansee(req->td, p) != 0) {
2367 			PROC_UNLOCK(p);
2368 			continue;
2369 		}
2370 		xf.xf_pid = p->p_pid;
2371 		xf.xf_uid = p->p_ucred->cr_uid;
2372 		PROC_UNLOCK(p);
2373 		mtx_lock(&fdesc_mtx);
2374 		if ((fdp = p->p_fd) == NULL) {
2375 			mtx_unlock(&fdesc_mtx);
2376 			continue;
2377 		}
2378 		FILEDESC_LOCK(fdp);
2379 		for (n = 0; n < fdp->fd_nfiles; ++n) {
2380 			if ((fp = fdp->fd_ofiles[n]) == NULL)
2381 				continue;
2382 			xf.xf_fd = n;
2383 			xf.xf_file = fp;
2384 			xf.xf_data = fp->f_data;
2385 			xf.xf_vnode = fp->f_vnode;
2386 			xf.xf_type = fp->f_type;
2387 			xf.xf_count = fp->f_count;
2388 			xf.xf_msgcount = fp->f_msgcount;
2389 			xf.xf_offset = fp->f_offset;
2390 			xf.xf_flag = fp->f_flag;
2391 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
2392 			if (error)
2393 				break;
2394 		}
2395 		FILEDESC_UNLOCK(fdp);
2396 		mtx_unlock(&fdesc_mtx);
2397 		if (error)
2398 			break;
2399 	}
2400 	sx_sunlock(&allproc_lock);
2401 	return (error);
2402 }
2403 
2404 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2405     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2406 
2407 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2408     &maxfilesperproc, 0, "Maximum files allowed open per process");
2409 
2410 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2411     &maxfiles, 0, "Maximum number of files");
2412 
2413 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2414     &nfiles, 0, "System-wide number of open files");
2415 
2416 static void
2417 fildesc_drvinit(void *unused)
2418 {
2419 	struct cdev *dev;
2420 
2421 	dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2422 	make_dev_alias(dev, "stdin");
2423 	dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2424 	make_dev_alias(dev, "stdout");
2425 	dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2426 	make_dev_alias(dev, "stderr");
2427 }
2428 
2429 static fo_rdwr_t	badfo_readwrite;
2430 static fo_ioctl_t	badfo_ioctl;
2431 static fo_poll_t	badfo_poll;
2432 static fo_kqfilter_t	badfo_kqfilter;
2433 static fo_stat_t	badfo_stat;
2434 static fo_close_t	badfo_close;
2435 
2436 struct fileops badfileops = {
2437 	.fo_read = badfo_readwrite,
2438 	.fo_write = badfo_readwrite,
2439 	.fo_ioctl = badfo_ioctl,
2440 	.fo_poll = badfo_poll,
2441 	.fo_kqfilter = badfo_kqfilter,
2442 	.fo_stat = badfo_stat,
2443 	.fo_close = badfo_close,
2444 };
2445 
2446 static int
2447 badfo_readwrite(fp, uio, active_cred, flags, td)
2448 	struct file *fp;
2449 	struct uio *uio;
2450 	struct ucred *active_cred;
2451 	struct thread *td;
2452 	int flags;
2453 {
2454 
2455 	return (EBADF);
2456 }
2457 
2458 static int
2459 badfo_ioctl(fp, com, data, active_cred, td)
2460 	struct file *fp;
2461 	u_long com;
2462 	void *data;
2463 	struct ucred *active_cred;
2464 	struct thread *td;
2465 {
2466 
2467 	return (EBADF);
2468 }
2469 
2470 static int
2471 badfo_poll(fp, events, active_cred, td)
2472 	struct file *fp;
2473 	int events;
2474 	struct ucred *active_cred;
2475 	struct thread *td;
2476 {
2477 
2478 	return (0);
2479 }
2480 
2481 static int
2482 badfo_kqfilter(fp, kn)
2483 	struct file *fp;
2484 	struct knote *kn;
2485 {
2486 
2487 	return (0);
2488 }
2489 
2490 static int
2491 badfo_stat(fp, sb, active_cred, td)
2492 	struct file *fp;
2493 	struct stat *sb;
2494 	struct ucred *active_cred;
2495 	struct thread *td;
2496 {
2497 
2498 	return (EBADF);
2499 }
2500 
2501 static int
2502 badfo_close(fp, td)
2503 	struct file *fp;
2504 	struct thread *td;
2505 {
2506 
2507 	return (EBADF);
2508 }
2509 
2510 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2511 					fildesc_drvinit,NULL)
2512 
2513 static void filelistinit(void *);
2514 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2515 
2516 /* ARGSUSED*/
2517 static void
2518 filelistinit(dummy)
2519 	void *dummy;
2520 {
2521 
2522 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2523 	    NULL, NULL, UMA_ALIGN_PTR, 0);
2524 	sx_init(&filelist_lock, "filelist lock");
2525 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2526 }
2527