xref: /freebsd/sys/kern/kern_descrip.c (revision 74bf4e164ba5851606a27d4feff27717452583e5)
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 	/* Certain daemons might not have file descriptors. */
1664 	fdp = td->td_proc->p_fd;
1665 	if (fdp == NULL)
1666 		return;
1667 
1668 	/*
1669 	 * Note: fdp->fd_ofiles may be reallocated out from under us while
1670 	 * we are blocked in a close.  Be careful!
1671 	 */
1672 	FILEDESC_LOCK(fdp);
1673 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1674 		if (i > 2)
1675 			break;
1676 		if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1677 			struct file *fp;
1678 
1679 			knote_fdclose(td, i);
1680 			/*
1681 			 * NULL-out descriptor prior to close to avoid
1682 			 * a race while close blocks.
1683 			 */
1684 			fp = fdp->fd_ofiles[i];
1685 			fdp->fd_ofiles[i] = NULL;
1686 			fdp->fd_ofileflags[i] = 0;
1687 			fdunused(fdp, i);
1688 			FILEDESC_UNLOCK(fdp);
1689 			(void) closef(fp, td);
1690 			FILEDESC_LOCK(fdp);
1691 		}
1692 	}
1693 	FILEDESC_UNLOCK(fdp);
1694 }
1695 
1696 /*
1697  * Close any files on exec?
1698  */
1699 void
1700 fdcloseexec(td)
1701 	struct thread *td;
1702 {
1703 	struct filedesc *fdp;
1704 	int i;
1705 
1706 	/* Certain daemons might not have file descriptors. */
1707 	fdp = td->td_proc->p_fd;
1708 	if (fdp == NULL)
1709 		return;
1710 
1711 	FILEDESC_LOCK(fdp);
1712 
1713 	/*
1714 	 * We cannot cache fd_ofiles or fd_ofileflags since operations
1715 	 * may block and rip them out from under us.
1716 	 */
1717 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1718 		if (fdp->fd_ofiles[i] != NULL &&
1719 		    (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1720 			struct file *fp;
1721 
1722 			knote_fdclose(td, i);
1723 			/*
1724 			 * NULL-out descriptor prior to close to avoid
1725 			 * a race while close blocks.
1726 			 */
1727 			fp = fdp->fd_ofiles[i];
1728 			fdp->fd_ofiles[i] = NULL;
1729 			fdp->fd_ofileflags[i] = 0;
1730 			fdunused(fdp, i);
1731 			FILEDESC_UNLOCK(fdp);
1732 			(void) closef(fp, td);
1733 			FILEDESC_LOCK(fdp);
1734 		}
1735 	}
1736 	FILEDESC_UNLOCK(fdp);
1737 }
1738 
1739 /*
1740  * It is unsafe for set[ug]id processes to be started with file
1741  * descriptors 0..2 closed, as these descriptors are given implicit
1742  * significance in the Standard C library.  fdcheckstd() will create a
1743  * descriptor referencing /dev/null for each of stdin, stdout, and
1744  * stderr that is not already open.
1745  */
1746 int
1747 fdcheckstd(td)
1748 	struct thread *td;
1749 {
1750 	struct nameidata nd;
1751 	struct filedesc *fdp;
1752 	struct file *fp;
1753 	register_t retval;
1754 	int fd, i, error, flags, devnull;
1755 
1756 	GIANT_REQUIRED;		/* VFS */
1757 
1758 	fdp = td->td_proc->p_fd;
1759 	if (fdp == NULL)
1760 		return (0);
1761 	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1762 	devnull = -1;
1763 	error = 0;
1764 	for (i = 0; i < 3; i++) {
1765 		if (fdp->fd_ofiles[i] != NULL)
1766 			continue;
1767 		if (devnull < 0) {
1768 			error = falloc(td, &fp, &fd);
1769 			if (error != 0)
1770 				break;
1771 			/* Note extra ref on `fp' held for us by falloc(). */
1772 			KASSERT(fd == i, ("oof, we didn't get our fd"));
1773 			NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null",
1774 			    td);
1775 			flags = FREAD | FWRITE;
1776 			error = vn_open(&nd, &flags, 0, -1);
1777 			if (error != 0) {
1778 				/*
1779 				 * Someone may have closed the entry in the
1780 				 * file descriptor table, so check it hasn't
1781 				 * changed before dropping the reference count.
1782 				 */
1783 				FILEDESC_LOCK(fdp);
1784 				KASSERT(fdp->fd_ofiles[fd] == fp,
1785 				    ("table not shared, how did it change?"));
1786 				fdp->fd_ofiles[fd] = NULL;
1787 				fdunused(fdp, fd);
1788 				FILEDESC_UNLOCK(fdp);
1789 				fdrop(fp, td);
1790 				fdrop(fp, td);
1791 				break;
1792 			}
1793 			NDFREE(&nd, NDF_ONLY_PNBUF);
1794 			fp->f_vnode = nd.ni_vp;
1795 			fp->f_data = nd.ni_vp;
1796 			fp->f_flag = flags;
1797 			fp->f_ops = &vnops;
1798 			fp->f_type = DTYPE_VNODE;
1799 			VOP_UNLOCK(nd.ni_vp, 0, td);
1800 			devnull = fd;
1801 			fdrop(fp, td);
1802 		} else {
1803 			error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1804 			if (error != 0)
1805 				break;
1806 		}
1807 	}
1808 	return (error);
1809 }
1810 
1811 /*
1812  * Internal form of close.
1813  * Decrement reference count on file structure.
1814  * Note: td may be NULL when closing a file
1815  * that was being passed in a message.
1816  */
1817 int
1818 closef(fp, td)
1819 	struct file *fp;
1820 	struct thread *td;
1821 {
1822 	struct vnode *vp;
1823 	struct flock lf;
1824 	struct filedesc_to_leader *fdtol;
1825 	struct filedesc *fdp;
1826 
1827 	if (fp == NULL)
1828 		return (0);
1829 	/*
1830 	 * POSIX record locking dictates that any close releases ALL
1831 	 * locks owned by this process.  This is handled by setting
1832 	 * a flag in the unlock to free ONLY locks obeying POSIX
1833 	 * semantics, and not to free BSD-style file locks.
1834 	 * If the descriptor was in a message, POSIX-style locks
1835 	 * aren't passed with the descriptor.
1836 	 */
1837 	if (td != NULL &&
1838 	    fp->f_type == DTYPE_VNODE) {
1839 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1840 			lf.l_whence = SEEK_SET;
1841 			lf.l_start = 0;
1842 			lf.l_len = 0;
1843 			lf.l_type = F_UNLCK;
1844 			vp = fp->f_vnode;
1845 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1846 					   F_UNLCK, &lf, F_POSIX);
1847 		}
1848 		fdtol = td->td_proc->p_fdtol;
1849 		if (fdtol != NULL) {
1850 			/*
1851 			 * Handle special case where file descriptor table
1852 			 * is shared between multiple process leaders.
1853 			 */
1854 			fdp = td->td_proc->p_fd;
1855 			FILEDESC_LOCK(fdp);
1856 			for (fdtol = fdtol->fdl_next;
1857 			     fdtol != td->td_proc->p_fdtol;
1858 			     fdtol = fdtol->fdl_next) {
1859 				if ((fdtol->fdl_leader->p_flag &
1860 				     P_ADVLOCK) == 0)
1861 					continue;
1862 				fdtol->fdl_holdcount++;
1863 				FILEDESC_UNLOCK(fdp);
1864 				lf.l_whence = SEEK_SET;
1865 				lf.l_start = 0;
1866 				lf.l_len = 0;
1867 				lf.l_type = F_UNLCK;
1868 				vp = fp->f_vnode;
1869 				(void) VOP_ADVLOCK(vp,
1870 						   (caddr_t)fdtol->fdl_leader,
1871 						   F_UNLCK, &lf, F_POSIX);
1872 				FILEDESC_LOCK(fdp);
1873 				fdtol->fdl_holdcount--;
1874 				if (fdtol->fdl_holdcount == 0 &&
1875 				    fdtol->fdl_wakeup != 0) {
1876 					fdtol->fdl_wakeup = 0;
1877 					wakeup(fdtol);
1878 				}
1879 			}
1880 			FILEDESC_UNLOCK(fdp);
1881 		}
1882 	}
1883 	return (fdrop(fp, td));
1884 }
1885 
1886 /*
1887  * Drop reference on struct file passed in, may call closef if the
1888  * reference hits zero.
1889  */
1890 int
1891 fdrop(fp, td)
1892 	struct file *fp;
1893 	struct thread *td;
1894 {
1895 
1896 	FILE_LOCK(fp);
1897 	return (fdrop_locked(fp, td));
1898 }
1899 
1900 /*
1901  * Extract the file pointer associated with the specified descriptor for
1902  * the current user process.
1903  *
1904  * If the descriptor doesn't exist, EBADF is returned.
1905  *
1906  * If the descriptor exists but doesn't match 'flags' then
1907  * return EBADF for read attempts and EINVAL for write attempts.
1908  *
1909  * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1910  * It should be droped with fdrop().
1911  * If it is not set, then the refcount will not be bumped however the
1912  * thread's filedesc struct will be returned locked (for fgetsock).
1913  *
1914  * If an error occured the non-zero error is returned and *fpp is set to NULL.
1915  * Otherwise *fpp is set and zero is returned.
1916  */
1917 static __inline int
1918 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1919 {
1920 	struct filedesc *fdp;
1921 	struct file *fp;
1922 
1923 	*fpp = NULL;
1924 	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1925 		return (EBADF);
1926 	FILEDESC_LOCK(fdp);
1927 	if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1928 		FILEDESC_UNLOCK(fdp);
1929 		return (EBADF);
1930 	}
1931 
1932 	/*
1933 	 * Note: FREAD failures returns EBADF to maintain backwards
1934 	 * compatibility with what routines returned before.
1935 	 *
1936 	 * Only one flag, or 0, may be specified.
1937 	 */
1938 	if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1939 		FILEDESC_UNLOCK(fdp);
1940 		return (EBADF);
1941 	}
1942 	if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
1943 		FILEDESC_UNLOCK(fdp);
1944 		return (EINVAL);
1945 	}
1946 	if (hold) {
1947 		fhold(fp);
1948 		FILEDESC_UNLOCK(fdp);
1949 	}
1950 	*fpp = fp;
1951 	return (0);
1952 }
1953 
1954 int
1955 fget(struct thread *td, int fd, struct file **fpp)
1956 {
1957 
1958 	return(_fget(td, fd, fpp, 0, 1));
1959 }
1960 
1961 int
1962 fget_read(struct thread *td, int fd, struct file **fpp)
1963 {
1964 
1965 	return(_fget(td, fd, fpp, FREAD, 1));
1966 }
1967 
1968 int
1969 fget_write(struct thread *td, int fd, struct file **fpp)
1970 {
1971 
1972 	return(_fget(td, fd, fpp, FWRITE, 1));
1973 }
1974 
1975 /*
1976  * Like fget() but loads the underlying vnode, or returns an error if
1977  * the descriptor does not represent a vnode.  Note that pipes use vnodes
1978  * but never have VM objects (so VOP_GETVOBJECT() calls will return an
1979  * error).  The returned vnode will be vref()d.
1980  */
1981 static __inline int
1982 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
1983 {
1984 	struct file *fp;
1985 	int error;
1986 
1987 	GIANT_REQUIRED;		/* VFS */
1988 
1989 	*vpp = NULL;
1990 	if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
1991 		return (error);
1992 	if (fp->f_vnode == NULL) {
1993 		error = EINVAL;
1994 	} else {
1995 		*vpp = fp->f_vnode;
1996 		vref(*vpp);
1997 	}
1998 	FILEDESC_UNLOCK(td->td_proc->p_fd);
1999 	return (error);
2000 }
2001 
2002 int
2003 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2004 {
2005 
2006 	return (_fgetvp(td, fd, vpp, 0));
2007 }
2008 
2009 int
2010 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2011 {
2012 
2013 	return (_fgetvp(td, fd, vpp, FREAD));
2014 }
2015 
2016 int
2017 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2018 {
2019 
2020 	return (_fgetvp(td, fd, vpp, FWRITE));
2021 }
2022 
2023 /*
2024  * Like fget() but loads the underlying socket, or returns an error if
2025  * the descriptor does not represent a socket.
2026  *
2027  * We bump the ref count on the returned socket.  XXX Also obtain the SX
2028  * lock in the future.
2029  */
2030 int
2031 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2032 {
2033 	struct file *fp;
2034 	int error;
2035 
2036 	NET_ASSERT_GIANT();
2037 
2038 	*spp = NULL;
2039 	if (fflagp != NULL)
2040 		*fflagp = 0;
2041 	if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2042 		return (error);
2043 	if (fp->f_type != DTYPE_SOCKET) {
2044 		error = ENOTSOCK;
2045 	} else {
2046 		*spp = fp->f_data;
2047 		if (fflagp)
2048 			*fflagp = fp->f_flag;
2049 		SOCK_LOCK(*spp);
2050 		soref(*spp);
2051 		SOCK_UNLOCK(*spp);
2052 	}
2053 	FILEDESC_UNLOCK(td->td_proc->p_fd);
2054 	return (error);
2055 }
2056 
2057 /*
2058  * Drop the reference count on the the socket and XXX release the SX lock in
2059  * the future.  The last reference closes the socket.
2060  */
2061 void
2062 fputsock(struct socket *so)
2063 {
2064 
2065 	NET_ASSERT_GIANT();
2066 	SOCK_LOCK(so);
2067 	sorele(so);
2068 }
2069 
2070 /*
2071  * Drop reference on struct file passed in, may call closef if the
2072  * reference hits zero.
2073  * Expects struct file locked, and will unlock it.
2074  */
2075 int
2076 fdrop_locked(fp, td)
2077 	struct file *fp;
2078 	struct thread *td;
2079 {
2080 	int error;
2081 
2082 	FILE_LOCK_ASSERT(fp, MA_OWNED);
2083 
2084 	if (--fp->f_count > 0) {
2085 		FILE_UNLOCK(fp);
2086 		return (0);
2087 	}
2088 	/* We have the last ref so we can proceed without the file lock. */
2089 	FILE_UNLOCK(fp);
2090 	if (fp->f_count < 0)
2091 		panic("fdrop: count < 0");
2092 	if (fp->f_ops != &badfileops)
2093 		error = fo_close(fp, td);
2094 	else
2095 		error = 0;
2096 	ffree(fp);
2097 	return (error);
2098 }
2099 
2100 /*
2101  * Apply an advisory lock on a file descriptor.
2102  *
2103  * Just attempt to get a record lock of the requested type on
2104  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2105  */
2106 #ifndef _SYS_SYSPROTO_H_
2107 struct flock_args {
2108 	int	fd;
2109 	int	how;
2110 };
2111 #endif
2112 /*
2113  * MPSAFE
2114  */
2115 /* ARGSUSED */
2116 int
2117 flock(td, uap)
2118 	struct thread *td;
2119 	struct flock_args *uap;
2120 {
2121 	struct file *fp;
2122 	struct vnode *vp;
2123 	struct flock lf;
2124 	int error;
2125 
2126 	if ((error = fget(td, uap->fd, &fp)) != 0)
2127 		return (error);
2128 	if (fp->f_type != DTYPE_VNODE) {
2129 		fdrop(fp, td);
2130 		return (EOPNOTSUPP);
2131 	}
2132 
2133 	mtx_lock(&Giant);
2134 	vp = fp->f_vnode;
2135 	lf.l_whence = SEEK_SET;
2136 	lf.l_start = 0;
2137 	lf.l_len = 0;
2138 	if (uap->how & LOCK_UN) {
2139 		lf.l_type = F_UNLCK;
2140 		FILE_LOCK(fp);
2141 		fp->f_flag &= ~FHASLOCK;
2142 		FILE_UNLOCK(fp);
2143 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2144 		goto done2;
2145 	}
2146 	if (uap->how & LOCK_EX)
2147 		lf.l_type = F_WRLCK;
2148 	else if (uap->how & LOCK_SH)
2149 		lf.l_type = F_RDLCK;
2150 	else {
2151 		error = EBADF;
2152 		goto done2;
2153 	}
2154 	FILE_LOCK(fp);
2155 	fp->f_flag |= FHASLOCK;
2156 	FILE_UNLOCK(fp);
2157 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2158 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2159 done2:
2160 	fdrop(fp, td);
2161 	mtx_unlock(&Giant);
2162 	return (error);
2163 }
2164 
2165 /*
2166  * File Descriptor pseudo-device driver (/dev/fd/).
2167  *
2168  * Opening minor device N dup()s the file (if any) connected to file
2169  * descriptor N belonging to the calling process.  Note that this driver
2170  * consists of only the ``open()'' routine, because all subsequent
2171  * references to this file will be direct to the other driver.
2172  */
2173 /* ARGSUSED */
2174 static int
2175 fdopen(dev, mode, type, td)
2176 	struct cdev *dev;
2177 	int mode, type;
2178 	struct thread *td;
2179 {
2180 
2181 	/*
2182 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2183 	 * the file descriptor being sought for duplication. The error
2184 	 * return ensures that the vnode for this device will be released
2185 	 * by vn_open. Open will detect this special error and take the
2186 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2187 	 * will simply report the error.
2188 	 */
2189 	td->td_dupfd = dev2unit(dev);
2190 	return (ENODEV);
2191 }
2192 
2193 /*
2194  * Duplicate the specified descriptor to a free descriptor.
2195  */
2196 int
2197 dupfdopen(td, fdp, indx, dfd, mode, error)
2198 	struct thread *td;
2199 	struct filedesc *fdp;
2200 	int indx, dfd;
2201 	int mode;
2202 	int error;
2203 {
2204 	struct file *wfp;
2205 	struct file *fp;
2206 
2207 	/*
2208 	 * If the to-be-dup'd fd number is greater than the allowed number
2209 	 * of file descriptors, or the fd to be dup'd has already been
2210 	 * closed, then reject.
2211 	 */
2212 	FILEDESC_LOCK(fdp);
2213 	if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2214 	    (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2215 		FILEDESC_UNLOCK(fdp);
2216 		return (EBADF);
2217 	}
2218 
2219 	/*
2220 	 * There are two cases of interest here.
2221 	 *
2222 	 * For ENODEV simply dup (dfd) to file descriptor
2223 	 * (indx) and return.
2224 	 *
2225 	 * For ENXIO steal away the file structure from (dfd) and
2226 	 * store it in (indx).  (dfd) is effectively closed by
2227 	 * this operation.
2228 	 *
2229 	 * Any other error code is just returned.
2230 	 */
2231 	switch (error) {
2232 	case ENODEV:
2233 		/*
2234 		 * Check that the mode the file is being opened for is a
2235 		 * subset of the mode of the existing descriptor.
2236 		 */
2237 		FILE_LOCK(wfp);
2238 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2239 			FILE_UNLOCK(wfp);
2240 			FILEDESC_UNLOCK(fdp);
2241 			return (EACCES);
2242 		}
2243 		fp = fdp->fd_ofiles[indx];
2244 		fdp->fd_ofiles[indx] = wfp;
2245 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2246 		if (fp == NULL)
2247 			fdused(fdp, indx);
2248 		fhold_locked(wfp);
2249 		FILE_UNLOCK(wfp);
2250 		if (fp != NULL)
2251 			FILE_LOCK(fp);
2252 		FILEDESC_UNLOCK(fdp);
2253 		/*
2254 		 * We now own the reference to fp that the ofiles[] array
2255 		 * used to own.  Release it.
2256 		 */
2257 		if (fp != NULL)
2258 			fdrop_locked(fp, td);
2259 		return (0);
2260 
2261 	case ENXIO:
2262 		/*
2263 		 * Steal away the file pointer from dfd and stuff it into indx.
2264 		 */
2265 		fp = fdp->fd_ofiles[indx];
2266 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2267 		fdp->fd_ofiles[dfd] = NULL;
2268 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2269 		fdp->fd_ofileflags[dfd] = 0;
2270 		fdunused(fdp, dfd);
2271 		if (fp == NULL)
2272 			fdused(fdp, indx);
2273 		if (fp != NULL)
2274 			FILE_LOCK(fp);
2275 		FILEDESC_UNLOCK(fdp);
2276 
2277 		/*
2278 		 * we now own the reference to fp that the ofiles[] array
2279 		 * used to own.  Release it.
2280 		 */
2281 		if (fp != NULL)
2282 			fdrop_locked(fp, td);
2283 		return (0);
2284 
2285 	default:
2286 		FILEDESC_UNLOCK(fdp);
2287 		return (error);
2288 	}
2289 	/* NOTREACHED */
2290 }
2291 
2292 struct filedesc_to_leader *
2293 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2294 			 struct filedesc *fdp,
2295 			 struct proc *leader)
2296 {
2297 	struct filedesc_to_leader *fdtol;
2298 
2299 	MALLOC(fdtol, struct filedesc_to_leader *,
2300 	       sizeof(struct filedesc_to_leader),
2301 	       M_FILEDESC_TO_LEADER,
2302 	       M_WAITOK);
2303 	fdtol->fdl_refcount = 1;
2304 	fdtol->fdl_holdcount = 0;
2305 	fdtol->fdl_wakeup = 0;
2306 	fdtol->fdl_leader = leader;
2307 	if (old != NULL) {
2308 		FILEDESC_LOCK(fdp);
2309 		fdtol->fdl_next = old->fdl_next;
2310 		fdtol->fdl_prev = old;
2311 		old->fdl_next = fdtol;
2312 		fdtol->fdl_next->fdl_prev = fdtol;
2313 		FILEDESC_UNLOCK(fdp);
2314 	} else {
2315 		fdtol->fdl_next = fdtol;
2316 		fdtol->fdl_prev = fdtol;
2317 	}
2318 	return (fdtol);
2319 }
2320 
2321 /*
2322  * Get file structures.
2323  */
2324 static int
2325 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2326 {
2327 	struct xfile xf;
2328 	struct filedesc *fdp;
2329 	struct file *fp;
2330 	struct proc *p;
2331 	int error, n;
2332 
2333 	/*
2334 	 * Note: because the number of file descriptors is calculated
2335 	 * in different ways for sizing vs returning the data,
2336 	 * there is information leakage from the first loop.  However,
2337 	 * it is of a similar order of magnitude to the leakage from
2338 	 * global system statistics such as kern.openfiles.
2339 	 */
2340 	error = sysctl_wire_old_buffer(req, 0);
2341 	if (error != 0)
2342 		return (error);
2343 	if (req->oldptr == NULL) {
2344 		n = 16;		/* A slight overestimate. */
2345 		sx_slock(&filelist_lock);
2346 		LIST_FOREACH(fp, &filehead, f_list) {
2347 			/*
2348 			 * We should grab the lock, but this is an
2349 			 * estimate, so does it really matter?
2350 			 */
2351 			/* mtx_lock(fp->f_mtxp); */
2352 			n += fp->f_count;
2353 			/* mtx_unlock(f->f_mtxp); */
2354 		}
2355 		sx_sunlock(&filelist_lock);
2356 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2357 	}
2358 	error = 0;
2359 	bzero(&xf, sizeof(xf));
2360 	xf.xf_size = sizeof(xf);
2361 	sx_slock(&allproc_lock);
2362 	LIST_FOREACH(p, &allproc, p_list) {
2363 		PROC_LOCK(p);
2364 		if (p_cansee(req->td, p) != 0) {
2365 			PROC_UNLOCK(p);
2366 			continue;
2367 		}
2368 		xf.xf_pid = p->p_pid;
2369 		xf.xf_uid = p->p_ucred->cr_uid;
2370 		PROC_UNLOCK(p);
2371 		mtx_lock(&fdesc_mtx);
2372 		if ((fdp = p->p_fd) == NULL) {
2373 			mtx_unlock(&fdesc_mtx);
2374 			continue;
2375 		}
2376 		FILEDESC_LOCK(fdp);
2377 		for (n = 0; n < fdp->fd_nfiles; ++n) {
2378 			if ((fp = fdp->fd_ofiles[n]) == NULL)
2379 				continue;
2380 			xf.xf_fd = n;
2381 			xf.xf_file = fp;
2382 			xf.xf_data = fp->f_data;
2383 			xf.xf_vnode = fp->f_vnode;
2384 			xf.xf_type = fp->f_type;
2385 			xf.xf_count = fp->f_count;
2386 			xf.xf_msgcount = fp->f_msgcount;
2387 			xf.xf_offset = fp->f_offset;
2388 			xf.xf_flag = fp->f_flag;
2389 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
2390 			if (error)
2391 				break;
2392 		}
2393 		FILEDESC_UNLOCK(fdp);
2394 		mtx_unlock(&fdesc_mtx);
2395 		if (error)
2396 			break;
2397 	}
2398 	sx_sunlock(&allproc_lock);
2399 	return (error);
2400 }
2401 
2402 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2403     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2404 
2405 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2406     &maxfilesperproc, 0, "Maximum files allowed open per process");
2407 
2408 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2409     &maxfiles, 0, "Maximum number of files");
2410 
2411 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2412     &nfiles, 0, "System-wide number of open files");
2413 
2414 static void
2415 fildesc_drvinit(void *unused)
2416 {
2417 	struct cdev *dev;
2418 
2419 	dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2420 	make_dev_alias(dev, "stdin");
2421 	dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2422 	make_dev_alias(dev, "stdout");
2423 	dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2424 	make_dev_alias(dev, "stderr");
2425 }
2426 
2427 static fo_rdwr_t	badfo_readwrite;
2428 static fo_ioctl_t	badfo_ioctl;
2429 static fo_poll_t	badfo_poll;
2430 static fo_kqfilter_t	badfo_kqfilter;
2431 static fo_stat_t	badfo_stat;
2432 static fo_close_t	badfo_close;
2433 
2434 struct fileops badfileops = {
2435 	.fo_read = badfo_readwrite,
2436 	.fo_write = badfo_readwrite,
2437 	.fo_ioctl = badfo_ioctl,
2438 	.fo_poll = badfo_poll,
2439 	.fo_kqfilter = badfo_kqfilter,
2440 	.fo_stat = badfo_stat,
2441 	.fo_close = badfo_close,
2442 };
2443 
2444 static int
2445 badfo_readwrite(fp, uio, active_cred, flags, td)
2446 	struct file *fp;
2447 	struct uio *uio;
2448 	struct ucred *active_cred;
2449 	struct thread *td;
2450 	int flags;
2451 {
2452 
2453 	return (EBADF);
2454 }
2455 
2456 static int
2457 badfo_ioctl(fp, com, data, active_cred, td)
2458 	struct file *fp;
2459 	u_long com;
2460 	void *data;
2461 	struct ucred *active_cred;
2462 	struct thread *td;
2463 {
2464 
2465 	return (EBADF);
2466 }
2467 
2468 static int
2469 badfo_poll(fp, events, active_cred, td)
2470 	struct file *fp;
2471 	int events;
2472 	struct ucred *active_cred;
2473 	struct thread *td;
2474 {
2475 
2476 	return (0);
2477 }
2478 
2479 static int
2480 badfo_kqfilter(fp, kn)
2481 	struct file *fp;
2482 	struct knote *kn;
2483 {
2484 
2485 	return (0);
2486 }
2487 
2488 static int
2489 badfo_stat(fp, sb, active_cred, td)
2490 	struct file *fp;
2491 	struct stat *sb;
2492 	struct ucred *active_cred;
2493 	struct thread *td;
2494 {
2495 
2496 	return (EBADF);
2497 }
2498 
2499 static int
2500 badfo_close(fp, td)
2501 	struct file *fp;
2502 	struct thread *td;
2503 {
2504 
2505 	return (EBADF);
2506 }
2507 
2508 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2509 					fildesc_drvinit,NULL)
2510 
2511 static void filelistinit(void *);
2512 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2513 
2514 /* ARGSUSED*/
2515 static void
2516 filelistinit(dummy)
2517 	void *dummy;
2518 {
2519 
2520 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2521 	    NULL, NULL, UMA_ALIGN_PTR, 0);
2522 	sx_init(&filelist_lock, "filelist lock");
2523 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2524 }
2525