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