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