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