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