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