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