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