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