kern_descrip.c revision 280258
1298823Sbapt/*-
2298823Sbapt * Copyright (c) 1982, 1986, 1989, 1991, 1993
3298823Sbapt *	The Regents of the University of California.  All rights reserved.
4298823Sbapt * (c) UNIX System Laboratories, Inc.
5298823Sbapt * All or some portions of this file are derived from material licensed
6298823Sbapt * to the University of California by American Telephone and Telegraph
7298823Sbapt * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8298823Sbapt * the permission of UNIX System Laboratories, Inc.
9298823Sbapt *
10298823Sbapt * Redistribution and use in source and binary forms, with or without
11298823Sbapt * modification, are permitted provided that the following conditions
12298823Sbapt * are met:
13298823Sbapt * 1. Redistributions of source code must retain the above copyright
14298823Sbapt *    notice, this list of conditions and the following disclaimer.
15298823Sbapt * 2. Redistributions in binary form must reproduce the above copyright
16298823Sbapt *    notice, this list of conditions and the following disclaimer in the
17298823Sbapt *    documentation and/or other materials provided with the distribution.
18298823Sbapt * 4. Neither the name of the University nor the names of its contributors
19298823Sbapt *    may be used to endorse or promote products derived from this software
20298823Sbapt *    without specific prior written permission.
21298823Sbapt *
22298823Sbapt * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23298823Sbapt * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24298823Sbapt * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25298823Sbapt * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26298823Sbapt * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27298823Sbapt * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28298823Sbapt * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29298823Sbapt * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30298823Sbapt * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31298823Sbapt * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32298823Sbapt * SUCH DAMAGE.
33298823Sbapt *
34298823Sbapt *	@(#)kern_descrip.c	8.6 (Berkeley) 4/19/94
35298823Sbapt */
36298823Sbapt
37298823Sbapt#include <sys/cdefs.h>
38298823Sbapt__FBSDID("$FreeBSD: stable/10/sys/kern/kern_descrip.c 280258 2015-03-19 13:37:36Z rwatson $");
39298823Sbapt
40298823Sbapt#include "opt_capsicum.h"
41298823Sbapt#include "opt_compat.h"
42298823Sbapt#include "opt_ddb.h"
43298823Sbapt#include "opt_ktrace.h"
44298823Sbapt#include "opt_procdesc.h"
45298823Sbapt
46298823Sbapt#include <sys/param.h>
47298823Sbapt#include <sys/systm.h>
48298823Sbapt
49298823Sbapt#include <sys/capsicum.h>
50298823Sbapt#include <sys/conf.h>
51298823Sbapt#include <sys/domain.h>
52298823Sbapt#include <sys/fcntl.h>
53298823Sbapt#include <sys/file.h>
54298823Sbapt#include <sys/filedesc.h>
55298823Sbapt#include <sys/filio.h>
56298823Sbapt#include <sys/jail.h>
57298823Sbapt#include <sys/kernel.h>
58298823Sbapt#include <sys/ksem.h>
59298823Sbapt#include <sys/limits.h>
60298823Sbapt#include <sys/lock.h>
61298823Sbapt#include <sys/malloc.h>
62298823Sbapt#include <sys/mman.h>
63298823Sbapt#include <sys/mount.h>
64298823Sbapt#include <sys/mqueue.h>
65298823Sbapt#include <sys/mutex.h>
66298823Sbapt#include <sys/namei.h>
67298823Sbapt#include <sys/selinfo.h>
68298823Sbapt#include <sys/pipe.h>
69298823Sbapt#include <sys/priv.h>
70298823Sbapt#include <sys/proc.h>
71298823Sbapt#include <sys/procdesc.h>
72298823Sbapt#include <sys/protosw.h>
73298823Sbapt#include <sys/racct.h>
74298823Sbapt#include <sys/resourcevar.h>
75298823Sbapt#include <sys/sbuf.h>
76298823Sbapt#include <sys/signalvar.h>
77298823Sbapt#include <sys/socketvar.h>
78298823Sbapt#include <sys/stat.h>
79298823Sbapt#include <sys/sx.h>
80298823Sbapt#include <sys/syscallsubr.h>
81298823Sbapt#include <sys/sysctl.h>
82298823Sbapt#include <sys/sysproto.h>
83298823Sbapt#include <sys/tty.h>
84298823Sbapt#include <sys/unistd.h>
85298823Sbapt#include <sys/un.h>
86298823Sbapt#include <sys/unpcb.h>
87298823Sbapt#include <sys/user.h>
88298823Sbapt#include <sys/vnode.h>
89298823Sbapt#ifdef KTRACE
90298823Sbapt#include <sys/ktrace.h>
91298823Sbapt#endif
92298823Sbapt
93298823Sbapt#include <net/vnet.h>
94298823Sbapt
95298823Sbapt#include <netinet/in.h>
96298823Sbapt#include <netinet/in_pcb.h>
97298823Sbapt
98298823Sbapt#include <security/audit/audit.h>
99298823Sbapt
100298823Sbapt#include <vm/uma.h>
101298823Sbapt#include <vm/vm.h>
102298823Sbapt
103298823Sbapt#include <ddb/ddb.h>
104298823Sbapt
105298823Sbaptstatic MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
106298823Sbaptstatic MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
107298823Sbapt    "file desc to leader structures");
108298823Sbaptstatic MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
109298823SbaptMALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
110298823Sbapt
111298823SbaptMALLOC_DECLARE(M_FADVISE);
112298823Sbapt
113298823Sbaptstatic uma_zone_t file_zone;
114298823Sbapt
115298823Sbaptvoid	(*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
116298823Sbapt
117298823Sbaptstatic int	closefp(struct filedesc *fdp, int fd, struct file *fp,
118298823Sbapt		    struct thread *td, int holdleaders);
119298823Sbaptstatic int	fd_first_free(struct filedesc *fdp, int low, int size);
120298823Sbaptstatic int	fd_last_used(struct filedesc *fdp, int size);
121298823Sbaptstatic void	fdgrowtable(struct filedesc *fdp, int nfd);
122298823Sbaptstatic void	fdgrowtable_exp(struct filedesc *fdp, int nfd);
123298823Sbaptstatic void	fdunused(struct filedesc *fdp, int fd);
124298823Sbaptstatic void	fdused(struct filedesc *fdp, int fd);
125298823Sbaptstatic int	fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
126298823Sbaptstatic int	fill_procdesc_info(struct procdesc *pdp,
127298823Sbapt		    struct kinfo_file *kif);
128298823Sbaptstatic int	fill_pts_info(struct tty *tp, struct kinfo_file *kif);
129298823Sbaptstatic int	fill_sem_info(struct file *fp, struct kinfo_file *kif);
130298823Sbaptstatic int	fill_shm_info(struct file *fp, struct kinfo_file *kif);
131298823Sbaptstatic int	fill_socket_info(struct socket *so, struct kinfo_file *kif);
132298823Sbaptstatic int	fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
133298823Sbaptstatic int	getmaxfd(struct proc *p);
134298823Sbapt
135298823Sbapt/*
136298823Sbapt * Each process has:
137298823Sbapt *
138298823Sbapt * - An array of open file descriptors (fd_ofiles)
139298823Sbapt * - An array of file flags (fd_ofileflags)
140298823Sbapt * - A bitmap recording which descriptors are in use (fd_map)
141298823Sbapt *
142298823Sbapt * A process starts out with NDFILE descriptors.  The value of NDFILE has
143298823Sbapt * been selected based the historical limit of 20 open files, and an
144298823Sbapt * assumption that the majority of processes, especially short-lived
145298823Sbapt * processes like shells, will never need more.
146298823Sbapt *
147298823Sbapt * If this initial allocation is exhausted, a larger descriptor table and
148298823Sbapt * map are allocated dynamically, and the pointers in the process's struct
149298823Sbapt * filedesc are updated to point to those.  This is repeated every time
150298823Sbapt * the process runs out of file descriptors (provided it hasn't hit its
151298823Sbapt * resource limit).
152298823Sbapt *
153298823Sbapt * Since threads may hold references to individual descriptor table
154298823Sbapt * entries, the tables are never freed.  Instead, they are placed on a
155298823Sbapt * linked list and freed only when the struct filedesc is released.
156298823Sbapt */
157298823Sbapt#define NDFILE		20
158298823Sbapt#define NDSLOTSIZE	sizeof(NDSLOTTYPE)
159298823Sbapt#define	NDENTRIES	(NDSLOTSIZE * __CHAR_BIT)
160298823Sbapt#define NDSLOT(x)	((x) / NDENTRIES)
161298823Sbapt#define NDBIT(x)	((NDSLOTTYPE)1 << ((x) % NDENTRIES))
162298823Sbapt#define	NDSLOTS(x)	(((x) + NDENTRIES - 1) / NDENTRIES)
163298823Sbapt
164298823Sbapt/*
165298823Sbapt * SLIST entry used to keep track of ofiles which must be reclaimed when
166298823Sbapt * the process exits.
167298823Sbapt */
168298823Sbaptstruct freetable {
169298823Sbapt	struct filedescent *ft_table;
170298823Sbapt	SLIST_ENTRY(freetable) ft_next;
171298823Sbapt};
172298823Sbapt
173298823Sbapt/*
174298823Sbapt * Initial allocation: a filedesc structure + the head of SLIST used to
175298823Sbapt * keep track of old ofiles + enough space for NDFILE descriptors.
176298823Sbapt */
177298823Sbaptstruct filedesc0 {
178298823Sbapt	struct filedesc fd_fd;
179298823Sbapt	SLIST_HEAD(, freetable) fd_free;
180298823Sbapt	struct	filedescent fd_dfiles[NDFILE];
181298823Sbapt	NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
182298823Sbapt};
183298823Sbapt
184298823Sbapt/*
185298823Sbapt * Descriptor management.
186298823Sbapt */
187298823Sbaptvolatile int openfiles;			/* actual number of open files */
188298823Sbaptstruct mtx sigio_lock;		/* mtx to protect pointers to sigio */
189298823Sbaptvoid (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
190298823Sbapt
191298823Sbapt/* A mutex to protect the association between a proc and filedesc. */
192298823Sbaptstatic struct mtx fdesc_mtx;
193298823Sbapt
194298823Sbapt/*
195298823Sbapt * If low >= size, just return low. Otherwise find the first zero bit in the
196298823Sbapt * given bitmap, starting at low and not exceeding size - 1. Return size if
197298823Sbapt * not found.
198298823Sbapt */
199298823Sbaptstatic int
200298823Sbaptfd_first_free(struct filedesc *fdp, int low, int size)
201298823Sbapt{
202298823Sbapt	NDSLOTTYPE *map = fdp->fd_map;
203298823Sbapt	NDSLOTTYPE mask;
204298823Sbapt	int off, maxoff;
205298823Sbapt
206298823Sbapt	if (low >= size)
207298823Sbapt		return (low);
208
209	off = NDSLOT(low);
210	if (low % NDENTRIES) {
211		mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
212		if ((mask &= ~map[off]) != 0UL)
213			return (off * NDENTRIES + ffsl(mask) - 1);
214		++off;
215	}
216	for (maxoff = NDSLOTS(size); off < maxoff; ++off)
217		if (map[off] != ~0UL)
218			return (off * NDENTRIES + ffsl(~map[off]) - 1);
219	return (size);
220}
221
222/*
223 * Find the highest non-zero bit in the given bitmap, starting at 0 and
224 * not exceeding size - 1. Return -1 if not found.
225 */
226static int
227fd_last_used(struct filedesc *fdp, int size)
228{
229	NDSLOTTYPE *map = fdp->fd_map;
230	NDSLOTTYPE mask;
231	int off, minoff;
232
233	off = NDSLOT(size);
234	if (size % NDENTRIES) {
235		mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
236		if ((mask &= map[off]) != 0)
237			return (off * NDENTRIES + flsl(mask) - 1);
238		--off;
239	}
240	for (minoff = NDSLOT(0); off >= minoff; --off)
241		if (map[off] != 0)
242			return (off * NDENTRIES + flsl(map[off]) - 1);
243	return (-1);
244}
245
246static int
247fdisused(struct filedesc *fdp, int fd)
248{
249
250	FILEDESC_LOCK_ASSERT(fdp);
251
252	KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
253	    ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
254
255	return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
256}
257
258/*
259 * Mark a file descriptor as used.
260 */
261static void
262fdused(struct filedesc *fdp, int fd)
263{
264
265	FILEDESC_XLOCK_ASSERT(fdp);
266
267	KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
268
269	fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
270	if (fd > fdp->fd_lastfile)
271		fdp->fd_lastfile = fd;
272	if (fd == fdp->fd_freefile)
273		fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
274}
275
276/*
277 * Mark a file descriptor as unused.
278 */
279static void
280fdunused(struct filedesc *fdp, int fd)
281{
282
283	FILEDESC_XLOCK_ASSERT(fdp);
284
285	KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
286	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
287	    ("fd=%d is still in use", fd));
288
289	fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
290	if (fd < fdp->fd_freefile)
291		fdp->fd_freefile = fd;
292	if (fd == fdp->fd_lastfile)
293		fdp->fd_lastfile = fd_last_used(fdp, fd);
294}
295
296/*
297 * Free a file descriptor.
298 *
299 * Avoid some work if fdp is about to be destroyed.
300 */
301static inline void
302_fdfree(struct filedesc *fdp, int fd, int last)
303{
304	struct filedescent *fde;
305
306	fde = &fdp->fd_ofiles[fd];
307#ifdef CAPABILITIES
308	if (!last)
309		seq_write_begin(&fde->fde_seq);
310#endif
311	filecaps_free(&fde->fde_caps);
312	if (last)
313		return;
314	bzero(fde, fde_change_size);
315	fdunused(fdp, fd);
316#ifdef CAPABILITIES
317	seq_write_end(&fde->fde_seq);
318#endif
319}
320
321static inline void
322fdfree(struct filedesc *fdp, int fd)
323{
324
325	_fdfree(fdp, fd, 0);
326}
327
328static inline void
329fdfree_last(struct filedesc *fdp, int fd)
330{
331
332	_fdfree(fdp, fd, 1);
333}
334
335/*
336 * System calls on descriptors.
337 */
338#ifndef _SYS_SYSPROTO_H_
339struct getdtablesize_args {
340	int	dummy;
341};
342#endif
343/* ARGSUSED */
344int
345sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
346{
347	struct proc *p = td->td_proc;
348	uint64_t lim;
349
350	PROC_LOCK(p);
351	td->td_retval[0] =
352	    min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
353	lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
354	PROC_UNLOCK(p);
355	if (lim < td->td_retval[0])
356		td->td_retval[0] = lim;
357	return (0);
358}
359
360/*
361 * Duplicate a file descriptor to a particular value.
362 *
363 * Note: keep in mind that a potential race condition exists when closing
364 * descriptors from a shared descriptor table (via rfork).
365 */
366#ifndef _SYS_SYSPROTO_H_
367struct dup2_args {
368	u_int	from;
369	u_int	to;
370};
371#endif
372/* ARGSUSED */
373int
374sys_dup2(struct thread *td, struct dup2_args *uap)
375{
376
377	return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
378		    td->td_retval));
379}
380
381/*
382 * Duplicate a file descriptor.
383 */
384#ifndef _SYS_SYSPROTO_H_
385struct dup_args {
386	u_int	fd;
387};
388#endif
389/* ARGSUSED */
390int
391sys_dup(struct thread *td, struct dup_args *uap)
392{
393
394	return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
395}
396
397/*
398 * The file control system call.
399 */
400#ifndef _SYS_SYSPROTO_H_
401struct fcntl_args {
402	int	fd;
403	int	cmd;
404	long	arg;
405};
406#endif
407/* ARGSUSED */
408int
409sys_fcntl(struct thread *td, struct fcntl_args *uap)
410{
411
412	return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
413}
414
415int
416kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
417{
418	struct flock fl;
419	struct __oflock ofl;
420	intptr_t arg1;
421	int error;
422
423	error = 0;
424	switch (cmd) {
425	case F_OGETLK:
426	case F_OSETLK:
427	case F_OSETLKW:
428		/*
429		 * Convert old flock structure to new.
430		 */
431		error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
432		fl.l_start = ofl.l_start;
433		fl.l_len = ofl.l_len;
434		fl.l_pid = ofl.l_pid;
435		fl.l_type = ofl.l_type;
436		fl.l_whence = ofl.l_whence;
437		fl.l_sysid = 0;
438
439		switch (cmd) {
440		case F_OGETLK:
441		    cmd = F_GETLK;
442		    break;
443		case F_OSETLK:
444		    cmd = F_SETLK;
445		    break;
446		case F_OSETLKW:
447		    cmd = F_SETLKW;
448		    break;
449		}
450		arg1 = (intptr_t)&fl;
451		break;
452        case F_GETLK:
453        case F_SETLK:
454        case F_SETLKW:
455	case F_SETLK_REMOTE:
456                error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
457                arg1 = (intptr_t)&fl;
458                break;
459	default:
460		arg1 = arg;
461		break;
462	}
463	if (error)
464		return (error);
465	error = kern_fcntl(td, fd, cmd, arg1);
466	if (error)
467		return (error);
468	if (cmd == F_OGETLK) {
469		ofl.l_start = fl.l_start;
470		ofl.l_len = fl.l_len;
471		ofl.l_pid = fl.l_pid;
472		ofl.l_type = fl.l_type;
473		ofl.l_whence = fl.l_whence;
474		error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
475	} else if (cmd == F_GETLK) {
476		error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
477	}
478	return (error);
479}
480
481int
482kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
483{
484	struct filedesc *fdp;
485	struct flock *flp;
486	struct file *fp, *fp2;
487	struct filedescent *fde;
488	struct proc *p;
489	struct vnode *vp;
490	cap_rights_t rights;
491	int error, flg, tmp;
492	uint64_t bsize;
493	off_t foffset;
494
495	error = 0;
496	flg = F_POSIX;
497	p = td->td_proc;
498	fdp = p->p_fd;
499
500	switch (cmd) {
501	case F_DUPFD:
502		tmp = arg;
503		error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
504		break;
505
506	case F_DUPFD_CLOEXEC:
507		tmp = arg;
508		error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
509		    td->td_retval);
510		break;
511
512	case F_DUP2FD:
513		tmp = arg;
514		error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
515		break;
516
517	case F_DUP2FD_CLOEXEC:
518		tmp = arg;
519		error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
520		    td->td_retval);
521		break;
522
523	case F_GETFD:
524		FILEDESC_SLOCK(fdp);
525		if ((fp = fget_locked(fdp, fd)) == NULL) {
526			FILEDESC_SUNLOCK(fdp);
527			error = EBADF;
528			break;
529		}
530		fde = &fdp->fd_ofiles[fd];
531		td->td_retval[0] =
532		    (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
533		FILEDESC_SUNLOCK(fdp);
534		break;
535
536	case F_SETFD:
537		FILEDESC_XLOCK(fdp);
538		if ((fp = fget_locked(fdp, fd)) == NULL) {
539			FILEDESC_XUNLOCK(fdp);
540			error = EBADF;
541			break;
542		}
543		fde = &fdp->fd_ofiles[fd];
544		fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
545		    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
546		FILEDESC_XUNLOCK(fdp);
547		break;
548
549	case F_GETFL:
550		error = fget_unlocked(fdp, fd,
551		    cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
552		if (error != 0)
553			break;
554		td->td_retval[0] = OFLAGS(fp->f_flag);
555		fdrop(fp, td);
556		break;
557
558	case F_SETFL:
559		error = fget_unlocked(fdp, fd,
560		    cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
561		if (error != 0)
562			break;
563		do {
564			tmp = flg = fp->f_flag;
565			tmp &= ~FCNTLFLAGS;
566			tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
567		} while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
568		tmp = fp->f_flag & FNONBLOCK;
569		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
570		if (error != 0) {
571			fdrop(fp, td);
572			break;
573		}
574		tmp = fp->f_flag & FASYNC;
575		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
576		if (error == 0) {
577			fdrop(fp, td);
578			break;
579		}
580		atomic_clear_int(&fp->f_flag, FNONBLOCK);
581		tmp = 0;
582		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
583		fdrop(fp, td);
584		break;
585
586	case F_GETOWN:
587		error = fget_unlocked(fdp, fd,
588		    cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
589		if (error != 0)
590			break;
591		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
592		if (error == 0)
593			td->td_retval[0] = tmp;
594		fdrop(fp, td);
595		break;
596
597	case F_SETOWN:
598		error = fget_unlocked(fdp, fd,
599		    cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
600		if (error != 0)
601			break;
602		tmp = arg;
603		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
604		fdrop(fp, td);
605		break;
606
607	case F_SETLK_REMOTE:
608		error = priv_check(td, PRIV_NFS_LOCKD);
609		if (error)
610			return (error);
611		flg = F_REMOTE;
612		goto do_setlk;
613
614	case F_SETLKW:
615		flg |= F_WAIT;
616		/* FALLTHROUGH F_SETLK */
617
618	case F_SETLK:
619	do_setlk:
620		cap_rights_init(&rights, CAP_FLOCK);
621		error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
622		if (error != 0)
623			break;
624		if (fp->f_type != DTYPE_VNODE) {
625			error = EBADF;
626			fdrop(fp, td);
627			break;
628		}
629
630		flp = (struct flock *)arg;
631		if (flp->l_whence == SEEK_CUR) {
632			foffset = foffset_get(fp);
633			if (foffset < 0 ||
634			    (flp->l_start > 0 &&
635			     foffset > OFF_MAX - flp->l_start)) {
636				FILEDESC_SUNLOCK(fdp);
637				error = EOVERFLOW;
638				fdrop(fp, td);
639				break;
640			}
641			flp->l_start += foffset;
642		}
643
644		vp = fp->f_vnode;
645		switch (flp->l_type) {
646		case F_RDLCK:
647			if ((fp->f_flag & FREAD) == 0) {
648				error = EBADF;
649				break;
650			}
651			PROC_LOCK(p->p_leader);
652			p->p_leader->p_flag |= P_ADVLOCK;
653			PROC_UNLOCK(p->p_leader);
654			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
655			    flp, flg);
656			break;
657		case F_WRLCK:
658			if ((fp->f_flag & FWRITE) == 0) {
659				error = EBADF;
660				break;
661			}
662			PROC_LOCK(p->p_leader);
663			p->p_leader->p_flag |= P_ADVLOCK;
664			PROC_UNLOCK(p->p_leader);
665			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
666			    flp, flg);
667			break;
668		case F_UNLCK:
669			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
670			    flp, flg);
671			break;
672		case F_UNLCKSYS:
673			/*
674			 * Temporary api for testing remote lock
675			 * infrastructure.
676			 */
677			if (flg != F_REMOTE) {
678				error = EINVAL;
679				break;
680			}
681			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
682			    F_UNLCKSYS, flp, flg);
683			break;
684		default:
685			error = EINVAL;
686			break;
687		}
688		if (error != 0 || flp->l_type == F_UNLCK ||
689		    flp->l_type == F_UNLCKSYS) {
690			fdrop(fp, td);
691			break;
692		}
693
694		/*
695		 * Check for a race with close.
696		 *
697		 * The vnode is now advisory locked (or unlocked, but this case
698		 * is not really important) as the caller requested.
699		 * We had to drop the filedesc lock, so we need to recheck if
700		 * the descriptor is still valid, because if it was closed
701		 * in the meantime we need to remove advisory lock from the
702		 * vnode - close on any descriptor leading to an advisory
703		 * locked vnode, removes that lock.
704		 * We will return 0 on purpose in that case, as the result of
705		 * successful advisory lock might have been externally visible
706		 * already. This is fine - effectively we pretend to the caller
707		 * that the closing thread was a bit slower and that the
708		 * advisory lock succeeded before the close.
709		 */
710		error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
711		if (error != 0) {
712			fdrop(fp, td);
713			break;
714		}
715		if (fp != fp2) {
716			flp->l_whence = SEEK_SET;
717			flp->l_start = 0;
718			flp->l_len = 0;
719			flp->l_type = F_UNLCK;
720			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
721			    F_UNLCK, flp, F_POSIX);
722		}
723		fdrop(fp, td);
724		fdrop(fp2, td);
725		break;
726
727	case F_GETLK:
728		error = fget_unlocked(fdp, fd,
729		    cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
730		if (error != 0)
731			break;
732		if (fp->f_type != DTYPE_VNODE) {
733			error = EBADF;
734			fdrop(fp, td);
735			break;
736		}
737		flp = (struct flock *)arg;
738		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
739		    flp->l_type != F_UNLCK) {
740			error = EINVAL;
741			fdrop(fp, td);
742			break;
743		}
744		if (flp->l_whence == SEEK_CUR) {
745			foffset = foffset_get(fp);
746			if ((flp->l_start > 0 &&
747			    foffset > OFF_MAX - flp->l_start) ||
748			    (flp->l_start < 0 &&
749			     foffset < OFF_MIN - flp->l_start)) {
750				FILEDESC_SUNLOCK(fdp);
751				error = EOVERFLOW;
752				fdrop(fp, td);
753				break;
754			}
755			flp->l_start += foffset;
756		}
757		vp = fp->f_vnode;
758		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
759		    F_POSIX);
760		fdrop(fp, td);
761		break;
762
763	case F_RDAHEAD:
764		arg = arg ? 128 * 1024: 0;
765		/* FALLTHROUGH */
766	case F_READAHEAD:
767		error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
768		if (error != 0)
769			break;
770		if (fp->f_type != DTYPE_VNODE) {
771			fdrop(fp, td);
772			error = EBADF;
773			break;
774		}
775		vp = fp->f_vnode;
776		/*
777		 * Exclusive lock synchronizes against f_seqcount reads and
778		 * writes in sequential_heuristic().
779		 */
780		error = vn_lock(vp, LK_EXCLUSIVE);
781		if (error != 0) {
782			fdrop(fp, td);
783			break;
784		}
785		if (arg >= 0) {
786			bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
787			fp->f_seqcount = (arg + bsize - 1) / bsize;
788			atomic_set_int(&fp->f_flag, FRDAHEAD);
789		} else {
790			atomic_clear_int(&fp->f_flag, FRDAHEAD);
791		}
792		VOP_UNLOCK(vp, 0);
793		fdrop(fp, td);
794		break;
795
796	default:
797		error = EINVAL;
798		break;
799	}
800	return (error);
801}
802
803static int
804getmaxfd(struct proc *p)
805{
806	int maxfd;
807
808	PROC_LOCK(p);
809	maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
810	PROC_UNLOCK(p);
811
812	return (maxfd);
813}
814
815/*
816 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
817 */
818int
819do_dup(struct thread *td, int flags, int old, int new,
820    register_t *retval)
821{
822	struct filedesc *fdp;
823	struct filedescent *oldfde, *newfde;
824	struct proc *p;
825	struct file *fp;
826	struct file *delfp;
827	int error, maxfd;
828
829	p = td->td_proc;
830	fdp = p->p_fd;
831
832	/*
833	 * Verify we have a valid descriptor to dup from and possibly to
834	 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
835	 * return EINVAL when the new descriptor is out of bounds.
836	 */
837	if (old < 0)
838		return (EBADF);
839	if (new < 0)
840		return (flags & DUP_FCNTL ? EINVAL : EBADF);
841	maxfd = getmaxfd(p);
842	if (new >= maxfd)
843		return (flags & DUP_FCNTL ? EINVAL : EBADF);
844
845	FILEDESC_XLOCK(fdp);
846	if (fget_locked(fdp, old) == NULL) {
847		FILEDESC_XUNLOCK(fdp);
848		return (EBADF);
849	}
850	oldfde = &fdp->fd_ofiles[old];
851	if (flags & DUP_FIXED && old == new) {
852		*retval = new;
853		if (flags & DUP_CLOEXEC)
854			fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
855		FILEDESC_XUNLOCK(fdp);
856		return (0);
857	}
858	fp = oldfde->fde_file;
859	fhold(fp);
860
861	/*
862	 * If the caller specified a file descriptor, make sure the file
863	 * table is large enough to hold it, and grab it.  Otherwise, just
864	 * allocate a new descriptor the usual way.
865	 */
866	if (flags & DUP_FIXED) {
867		if (new >= fdp->fd_nfiles) {
868			/*
869			 * The resource limits are here instead of e.g.
870			 * fdalloc(), because the file descriptor table may be
871			 * shared between processes, so we can't really use
872			 * racct_add()/racct_sub().  Instead of counting the
873			 * number of actually allocated descriptors, just put
874			 * the limit on the size of the file descriptor table.
875			 */
876#ifdef RACCT
877			PROC_LOCK(p);
878			error = racct_set(p, RACCT_NOFILE, new + 1);
879			PROC_UNLOCK(p);
880			if (error != 0) {
881				FILEDESC_XUNLOCK(fdp);
882				fdrop(fp, td);
883				return (EMFILE);
884			}
885#endif
886			fdgrowtable_exp(fdp, new + 1);
887			oldfde = &fdp->fd_ofiles[old];
888		}
889		newfde = &fdp->fd_ofiles[new];
890		if (newfde->fde_file == NULL)
891			fdused(fdp, new);
892	} else {
893		if ((error = fdalloc(td, new, &new)) != 0) {
894			FILEDESC_XUNLOCK(fdp);
895			fdrop(fp, td);
896			return (error);
897		}
898		newfde = &fdp->fd_ofiles[new];
899	}
900
901	KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
902	KASSERT(old != new, ("new fd is same as old"));
903
904	delfp = newfde->fde_file;
905
906	/*
907	 * Duplicate the source descriptor.
908	 */
909#ifdef CAPABILITIES
910	seq_write_begin(&newfde->fde_seq);
911#endif
912	filecaps_free(&newfde->fde_caps);
913	memcpy(newfde, oldfde, fde_change_size);
914	filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
915	if ((flags & DUP_CLOEXEC) != 0)
916		newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
917	else
918		newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
919#ifdef CAPABILITIES
920	seq_write_end(&newfde->fde_seq);
921#endif
922	*retval = new;
923
924	if (delfp != NULL) {
925		(void) closefp(fdp, new, delfp, td, 1);
926		/* closefp() drops the FILEDESC lock for us. */
927	} else {
928		FILEDESC_XUNLOCK(fdp);
929	}
930
931	return (0);
932}
933
934/*
935 * If sigio is on the list associated with a process or process group,
936 * disable signalling from the device, remove sigio from the list and
937 * free sigio.
938 */
939void
940funsetown(struct sigio **sigiop)
941{
942	struct sigio *sigio;
943
944	SIGIO_LOCK();
945	sigio = *sigiop;
946	if (sigio == NULL) {
947		SIGIO_UNLOCK();
948		return;
949	}
950	*(sigio->sio_myref) = NULL;
951	if ((sigio)->sio_pgid < 0) {
952		struct pgrp *pg = (sigio)->sio_pgrp;
953		PGRP_LOCK(pg);
954		SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
955			     sigio, sio_pgsigio);
956		PGRP_UNLOCK(pg);
957	} else {
958		struct proc *p = (sigio)->sio_proc;
959		PROC_LOCK(p);
960		SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
961			     sigio, sio_pgsigio);
962		PROC_UNLOCK(p);
963	}
964	SIGIO_UNLOCK();
965	crfree(sigio->sio_ucred);
966	free(sigio, M_SIGIO);
967}
968
969/*
970 * Free a list of sigio structures.
971 * We only need to lock the SIGIO_LOCK because we have made ourselves
972 * inaccessible to callers of fsetown and therefore do not need to lock
973 * the proc or pgrp struct for the list manipulation.
974 */
975void
976funsetownlst(struct sigiolst *sigiolst)
977{
978	struct proc *p;
979	struct pgrp *pg;
980	struct sigio *sigio;
981
982	sigio = SLIST_FIRST(sigiolst);
983	if (sigio == NULL)
984		return;
985	p = NULL;
986	pg = NULL;
987
988	/*
989	 * Every entry of the list should belong
990	 * to a single proc or pgrp.
991	 */
992	if (sigio->sio_pgid < 0) {
993		pg = sigio->sio_pgrp;
994		PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
995	} else /* if (sigio->sio_pgid > 0) */ {
996		p = sigio->sio_proc;
997		PROC_LOCK_ASSERT(p, MA_NOTOWNED);
998	}
999
1000	SIGIO_LOCK();
1001	while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1002		*(sigio->sio_myref) = NULL;
1003		if (pg != NULL) {
1004			KASSERT(sigio->sio_pgid < 0,
1005			    ("Proc sigio in pgrp sigio list"));
1006			KASSERT(sigio->sio_pgrp == pg,
1007			    ("Bogus pgrp in sigio list"));
1008			PGRP_LOCK(pg);
1009			SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1010			    sio_pgsigio);
1011			PGRP_UNLOCK(pg);
1012		} else /* if (p != NULL) */ {
1013			KASSERT(sigio->sio_pgid > 0,
1014			    ("Pgrp sigio in proc sigio list"));
1015			KASSERT(sigio->sio_proc == p,
1016			    ("Bogus proc in sigio list"));
1017			PROC_LOCK(p);
1018			SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1019			    sio_pgsigio);
1020			PROC_UNLOCK(p);
1021		}
1022		SIGIO_UNLOCK();
1023		crfree(sigio->sio_ucred);
1024		free(sigio, M_SIGIO);
1025		SIGIO_LOCK();
1026	}
1027	SIGIO_UNLOCK();
1028}
1029
1030/*
1031 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1032 *
1033 * After permission checking, add a sigio structure to the sigio list for
1034 * the process or process group.
1035 */
1036int
1037fsetown(pid_t pgid, struct sigio **sigiop)
1038{
1039	struct proc *proc;
1040	struct pgrp *pgrp;
1041	struct sigio *sigio;
1042	int ret;
1043
1044	if (pgid == 0) {
1045		funsetown(sigiop);
1046		return (0);
1047	}
1048
1049	ret = 0;
1050
1051	/* Allocate and fill in the new sigio out of locks. */
1052	sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1053	sigio->sio_pgid = pgid;
1054	sigio->sio_ucred = crhold(curthread->td_ucred);
1055	sigio->sio_myref = sigiop;
1056
1057	sx_slock(&proctree_lock);
1058	if (pgid > 0) {
1059		proc = pfind(pgid);
1060		if (proc == NULL) {
1061			ret = ESRCH;
1062			goto fail;
1063		}
1064
1065		/*
1066		 * Policy - Don't allow a process to FSETOWN a process
1067		 * in another session.
1068		 *
1069		 * Remove this test to allow maximum flexibility or
1070		 * restrict FSETOWN to the current process or process
1071		 * group for maximum safety.
1072		 */
1073		PROC_UNLOCK(proc);
1074		if (proc->p_session != curthread->td_proc->p_session) {
1075			ret = EPERM;
1076			goto fail;
1077		}
1078
1079		pgrp = NULL;
1080	} else /* if (pgid < 0) */ {
1081		pgrp = pgfind(-pgid);
1082		if (pgrp == NULL) {
1083			ret = ESRCH;
1084			goto fail;
1085		}
1086		PGRP_UNLOCK(pgrp);
1087
1088		/*
1089		 * Policy - Don't allow a process to FSETOWN a process
1090		 * in another session.
1091		 *
1092		 * Remove this test to allow maximum flexibility or
1093		 * restrict FSETOWN to the current process or process
1094		 * group for maximum safety.
1095		 */
1096		if (pgrp->pg_session != curthread->td_proc->p_session) {
1097			ret = EPERM;
1098			goto fail;
1099		}
1100
1101		proc = NULL;
1102	}
1103	funsetown(sigiop);
1104	if (pgid > 0) {
1105		PROC_LOCK(proc);
1106		/*
1107		 * Since funsetownlst() is called without the proctree
1108		 * locked, we need to check for P_WEXIT.
1109		 * XXX: is ESRCH correct?
1110		 */
1111		if ((proc->p_flag & P_WEXIT) != 0) {
1112			PROC_UNLOCK(proc);
1113			ret = ESRCH;
1114			goto fail;
1115		}
1116		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1117		sigio->sio_proc = proc;
1118		PROC_UNLOCK(proc);
1119	} else {
1120		PGRP_LOCK(pgrp);
1121		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1122		sigio->sio_pgrp = pgrp;
1123		PGRP_UNLOCK(pgrp);
1124	}
1125	sx_sunlock(&proctree_lock);
1126	SIGIO_LOCK();
1127	*sigiop = sigio;
1128	SIGIO_UNLOCK();
1129	return (0);
1130
1131fail:
1132	sx_sunlock(&proctree_lock);
1133	crfree(sigio->sio_ucred);
1134	free(sigio, M_SIGIO);
1135	return (ret);
1136}
1137
1138/*
1139 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1140 */
1141pid_t
1142fgetown(sigiop)
1143	struct sigio **sigiop;
1144{
1145	pid_t pgid;
1146
1147	SIGIO_LOCK();
1148	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1149	SIGIO_UNLOCK();
1150	return (pgid);
1151}
1152
1153/*
1154 * Function drops the filedesc lock on return.
1155 */
1156static int
1157closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1158    int holdleaders)
1159{
1160	int error;
1161
1162	FILEDESC_XLOCK_ASSERT(fdp);
1163
1164	if (holdleaders) {
1165		if (td->td_proc->p_fdtol != NULL) {
1166			/*
1167			 * Ask fdfree() to sleep to ensure that all relevant
1168			 * process leaders can be traversed in closef().
1169			 */
1170			fdp->fd_holdleaderscount++;
1171		} else {
1172			holdleaders = 0;
1173		}
1174	}
1175
1176	/*
1177	 * We now hold the fp reference that used to be owned by the
1178	 * descriptor array.  We have to unlock the FILEDESC *AFTER*
1179	 * knote_fdclose to prevent a race of the fd getting opened, a knote
1180	 * added, and deleteing a knote for the new fd.
1181	 */
1182	knote_fdclose(td, fd);
1183
1184	/*
1185	 * We need to notify mqueue if the object is of type mqueue.
1186	 */
1187	if (fp->f_type == DTYPE_MQUEUE)
1188		mq_fdclose(td, fd, fp);
1189	FILEDESC_XUNLOCK(fdp);
1190
1191	error = closef(fp, td);
1192	if (holdleaders) {
1193		FILEDESC_XLOCK(fdp);
1194		fdp->fd_holdleaderscount--;
1195		if (fdp->fd_holdleaderscount == 0 &&
1196		    fdp->fd_holdleaderswakeup != 0) {
1197			fdp->fd_holdleaderswakeup = 0;
1198			wakeup(&fdp->fd_holdleaderscount);
1199		}
1200		FILEDESC_XUNLOCK(fdp);
1201	}
1202	return (error);
1203}
1204
1205/*
1206 * Close a file descriptor.
1207 */
1208#ifndef _SYS_SYSPROTO_H_
1209struct close_args {
1210	int     fd;
1211};
1212#endif
1213/* ARGSUSED */
1214int
1215sys_close(td, uap)
1216	struct thread *td;
1217	struct close_args *uap;
1218{
1219
1220	return (kern_close(td, uap->fd));
1221}
1222
1223int
1224kern_close(td, fd)
1225	struct thread *td;
1226	int fd;
1227{
1228	struct filedesc *fdp;
1229	struct file *fp;
1230
1231	fdp = td->td_proc->p_fd;
1232
1233	AUDIT_SYSCLOSE(td, fd);
1234
1235	FILEDESC_XLOCK(fdp);
1236	if ((fp = fget_locked(fdp, fd)) == NULL) {
1237		FILEDESC_XUNLOCK(fdp);
1238		return (EBADF);
1239	}
1240	fdfree(fdp, fd);
1241
1242	/* closefp() drops the FILEDESC lock for us. */
1243	return (closefp(fdp, fd, fp, td, 1));
1244}
1245
1246/*
1247 * Close open file descriptors.
1248 */
1249#ifndef _SYS_SYSPROTO_H_
1250struct closefrom_args {
1251	int	lowfd;
1252};
1253#endif
1254/* ARGSUSED */
1255int
1256sys_closefrom(struct thread *td, struct closefrom_args *uap)
1257{
1258	struct filedesc *fdp;
1259	int fd;
1260
1261	fdp = td->td_proc->p_fd;
1262	AUDIT_ARG_FD(uap->lowfd);
1263
1264	/*
1265	 * Treat negative starting file descriptor values identical to
1266	 * closefrom(0) which closes all files.
1267	 */
1268	if (uap->lowfd < 0)
1269		uap->lowfd = 0;
1270	FILEDESC_SLOCK(fdp);
1271	for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1272		if (fdp->fd_ofiles[fd].fde_file != NULL) {
1273			FILEDESC_SUNLOCK(fdp);
1274			(void)kern_close(td, fd);
1275			FILEDESC_SLOCK(fdp);
1276		}
1277	}
1278	FILEDESC_SUNLOCK(fdp);
1279	return (0);
1280}
1281
1282#if defined(COMPAT_43)
1283/*
1284 * Return status information about a file descriptor.
1285 */
1286#ifndef _SYS_SYSPROTO_H_
1287struct ofstat_args {
1288	int	fd;
1289	struct	ostat *sb;
1290};
1291#endif
1292/* ARGSUSED */
1293int
1294ofstat(struct thread *td, struct ofstat_args *uap)
1295{
1296	struct ostat oub;
1297	struct stat ub;
1298	int error;
1299
1300	error = kern_fstat(td, uap->fd, &ub);
1301	if (error == 0) {
1302		cvtstat(&ub, &oub);
1303		error = copyout(&oub, uap->sb, sizeof(oub));
1304	}
1305	return (error);
1306}
1307#endif /* COMPAT_43 */
1308
1309/*
1310 * Return status information about a file descriptor.
1311 */
1312#ifndef _SYS_SYSPROTO_H_
1313struct fstat_args {
1314	int	fd;
1315	struct	stat *sb;
1316};
1317#endif
1318/* ARGSUSED */
1319int
1320sys_fstat(struct thread *td, struct fstat_args *uap)
1321{
1322	struct stat ub;
1323	int error;
1324
1325	error = kern_fstat(td, uap->fd, &ub);
1326	if (error == 0)
1327		error = copyout(&ub, uap->sb, sizeof(ub));
1328	return (error);
1329}
1330
1331int
1332kern_fstat(struct thread *td, int fd, struct stat *sbp)
1333{
1334	struct file *fp;
1335	cap_rights_t rights;
1336	int error;
1337
1338	AUDIT_ARG_FD(fd);
1339
1340	error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1341	if (error != 0)
1342		return (error);
1343
1344	AUDIT_ARG_FILE(td->td_proc, fp);
1345
1346	error = fo_stat(fp, sbp, td->td_ucred, td);
1347	fdrop(fp, td);
1348#ifdef KTRACE
1349	if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1350		ktrstat(sbp);
1351#endif
1352	return (error);
1353}
1354
1355/*
1356 * Return status information about a file descriptor.
1357 */
1358#ifndef _SYS_SYSPROTO_H_
1359struct nfstat_args {
1360	int	fd;
1361	struct	nstat *sb;
1362};
1363#endif
1364/* ARGSUSED */
1365int
1366sys_nfstat(struct thread *td, struct nfstat_args *uap)
1367{
1368	struct nstat nub;
1369	struct stat ub;
1370	int error;
1371
1372	error = kern_fstat(td, uap->fd, &ub);
1373	if (error == 0) {
1374		cvtnstat(&ub, &nub);
1375		error = copyout(&nub, uap->sb, sizeof(nub));
1376	}
1377	return (error);
1378}
1379
1380/*
1381 * Return pathconf information about a file descriptor.
1382 */
1383#ifndef _SYS_SYSPROTO_H_
1384struct fpathconf_args {
1385	int	fd;
1386	int	name;
1387};
1388#endif
1389/* ARGSUSED */
1390int
1391sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1392{
1393	struct file *fp;
1394	struct vnode *vp;
1395	cap_rights_t rights;
1396	int error;
1397
1398	error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1399	if (error != 0)
1400		return (error);
1401
1402	/* If asynchronous I/O is available, it works for all descriptors. */
1403	if (uap->name == _PC_ASYNC_IO) {
1404		td->td_retval[0] = async_io_version;
1405		goto out;
1406	}
1407	vp = fp->f_vnode;
1408	if (vp != NULL) {
1409		vn_lock(vp, LK_SHARED | LK_RETRY);
1410		error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1411		VOP_UNLOCK(vp, 0);
1412	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1413		if (uap->name != _PC_PIPE_BUF) {
1414			error = EINVAL;
1415		} else {
1416			td->td_retval[0] = PIPE_BUF;
1417			error = 0;
1418		}
1419	} else {
1420		error = EOPNOTSUPP;
1421	}
1422out:
1423	fdrop(fp, td);
1424	return (error);
1425}
1426
1427/*
1428 * Initialize filecaps structure.
1429 */
1430void
1431filecaps_init(struct filecaps *fcaps)
1432{
1433
1434	bzero(fcaps, sizeof(*fcaps));
1435	fcaps->fc_nioctls = -1;
1436}
1437
1438/*
1439 * Copy filecaps structure allocating memory for ioctls array if needed.
1440 */
1441void
1442filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1443{
1444	size_t size;
1445
1446	*dst = *src;
1447	if (src->fc_ioctls != NULL) {
1448		KASSERT(src->fc_nioctls > 0,
1449		    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1450
1451		size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1452		dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1453		bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1454	}
1455}
1456
1457/*
1458 * Move filecaps structure to the new place and clear the old place.
1459 */
1460void
1461filecaps_move(struct filecaps *src, struct filecaps *dst)
1462{
1463
1464	*dst = *src;
1465	bzero(src, sizeof(*src));
1466}
1467
1468/*
1469 * Fill the given filecaps structure with full rights.
1470 */
1471static void
1472filecaps_fill(struct filecaps *fcaps)
1473{
1474
1475	CAP_ALL(&fcaps->fc_rights);
1476	fcaps->fc_ioctls = NULL;
1477	fcaps->fc_nioctls = -1;
1478	fcaps->fc_fcntls = CAP_FCNTL_ALL;
1479}
1480
1481/*
1482 * Free memory allocated within filecaps structure.
1483 */
1484void
1485filecaps_free(struct filecaps *fcaps)
1486{
1487
1488	free(fcaps->fc_ioctls, M_FILECAPS);
1489	bzero(fcaps, sizeof(*fcaps));
1490}
1491
1492/*
1493 * Validate the given filecaps structure.
1494 */
1495static void
1496filecaps_validate(const struct filecaps *fcaps, const char *func)
1497{
1498
1499	KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1500	    ("%s: invalid rights", func));
1501	KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1502	    ("%s: invalid fcntls", func));
1503	KASSERT(fcaps->fc_fcntls == 0 ||
1504	    cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1505	    ("%s: fcntls without CAP_FCNTL", func));
1506	KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1507	    (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1508	    ("%s: invalid ioctls", func));
1509	KASSERT(fcaps->fc_nioctls == 0 ||
1510	    cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1511	    ("%s: ioctls without CAP_IOCTL", func));
1512}
1513
1514static void
1515fdgrowtable_exp(struct filedesc *fdp, int nfd)
1516{
1517	int nfd1;
1518
1519	FILEDESC_XLOCK_ASSERT(fdp);
1520
1521	nfd1 = fdp->fd_nfiles * 2;
1522	if (nfd1 < nfd)
1523		nfd1 = nfd;
1524	fdgrowtable(fdp, nfd1);
1525}
1526
1527/*
1528 * Grow the file table to accomodate (at least) nfd descriptors.
1529 */
1530static void
1531fdgrowtable(struct filedesc *fdp, int nfd)
1532{
1533	struct filedesc0 *fdp0;
1534	struct freetable *ft;
1535	struct filedescent *ntable;
1536	struct filedescent *otable;
1537	int nnfiles, onfiles;
1538	NDSLOTTYPE *nmap, *omap;
1539
1540	FILEDESC_XLOCK_ASSERT(fdp);
1541
1542	KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1543
1544	/* save old values */
1545	onfiles = fdp->fd_nfiles;
1546	otable = fdp->fd_ofiles;
1547	omap = fdp->fd_map;
1548
1549	/* compute the size of the new table */
1550	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1551	if (nnfiles <= onfiles)
1552		/* the table is already large enough */
1553		return;
1554
1555	/*
1556	 * Allocate a new table.  We need enough space for the
1557	 * file entries themselves and the struct freetable we will use
1558	 * when we decommission the table and place it on the freelist.
1559	 * We place the struct freetable in the middle so we don't have
1560	 * to worry about padding.
1561	 */
1562	ntable = malloc(nnfiles * sizeof(ntable[0]) + sizeof(struct freetable),
1563	    M_FILEDESC, M_ZERO | M_WAITOK);
1564	/* copy the old data over and point at the new tables */
1565	memcpy(ntable, otable, onfiles * sizeof(*otable));
1566	fdp->fd_ofiles = ntable;
1567
1568	/*
1569	 * Allocate a new map only if the old is not large enough.  It will
1570	 * grow at a slower rate than the table as it can map more
1571	 * entries than the table can hold.
1572	 */
1573	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1574		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1575		    M_ZERO | M_WAITOK);
1576		/* copy over the old data and update the pointer */
1577		memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1578		fdp->fd_map = nmap;
1579	}
1580
1581	/*
1582	 * In order to have a valid pattern for fget_unlocked()
1583	 * fdp->fd_nfiles must be the last member to be updated, otherwise
1584	 * fget_unlocked() consumers may reference a new, higher value for
1585	 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1586	 * resulting in OOB accesses.
1587	 */
1588	atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1589
1590	/*
1591	 * Do not free the old file table, as some threads may still
1592	 * reference entries within it.  Instead, place it on a freelist
1593	 * which will be processed when the struct filedesc is released.
1594	 *
1595	 * Note that if onfiles == NDFILE, we're dealing with the original
1596	 * static allocation contained within (struct filedesc0 *)fdp,
1597	 * which must not be freed.
1598	 */
1599	if (onfiles > NDFILE) {
1600		ft = (struct freetable *)&otable[onfiles];
1601		fdp0 = (struct filedesc0 *)fdp;
1602		ft->ft_table = otable;
1603		SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1604	}
1605	/*
1606	 * The map does not have the same possibility of threads still
1607	 * holding references to it.  So always free it as long as it
1608	 * does not reference the original static allocation.
1609	 */
1610	if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1611		free(omap, M_FILEDESC);
1612}
1613
1614/*
1615 * Allocate a file descriptor for the process.
1616 */
1617int
1618fdalloc(struct thread *td, int minfd, int *result)
1619{
1620	struct proc *p = td->td_proc;
1621	struct filedesc *fdp = p->p_fd;
1622	int fd = -1, maxfd, allocfd;
1623#ifdef RACCT
1624	int error;
1625#endif
1626
1627	FILEDESC_XLOCK_ASSERT(fdp);
1628
1629	if (fdp->fd_freefile > minfd)
1630		minfd = fdp->fd_freefile;
1631
1632	maxfd = getmaxfd(p);
1633
1634	/*
1635	 * Search the bitmap for a free descriptor starting at minfd.
1636	 * If none is found, grow the file table.
1637	 */
1638	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1639	if (fd >= maxfd)
1640		return (EMFILE);
1641	if (fd >= fdp->fd_nfiles) {
1642		allocfd = min(fd * 2, maxfd);
1643#ifdef RACCT
1644		PROC_LOCK(p);
1645		error = racct_set(p, RACCT_NOFILE, allocfd);
1646		PROC_UNLOCK(p);
1647		if (error != 0)
1648			return (EMFILE);
1649#endif
1650		/*
1651		 * fd is already equal to first free descriptor >= minfd, so
1652		 * we only need to grow the table and we are done.
1653		 */
1654		fdgrowtable_exp(fdp, allocfd);
1655	}
1656
1657	/*
1658	 * Perform some sanity checks, then mark the file descriptor as
1659	 * used and return it to the caller.
1660	 */
1661	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1662	    ("invalid descriptor %d", fd));
1663	KASSERT(!fdisused(fdp, fd),
1664	    ("fd_first_free() returned non-free descriptor"));
1665	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1666	    ("file descriptor isn't free"));
1667	KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1668	fdused(fdp, fd);
1669	*result = fd;
1670	return (0);
1671}
1672
1673/*
1674 * Allocate n file descriptors for the process.
1675 */
1676int
1677fdallocn(struct thread *td, int minfd, int *fds, int n)
1678{
1679	struct proc *p = td->td_proc;
1680	struct filedesc *fdp = p->p_fd;
1681	int i;
1682
1683	FILEDESC_XLOCK_ASSERT(fdp);
1684
1685	if (!fdavail(td, n))
1686		return (EMFILE);
1687
1688	for (i = 0; i < n; i++)
1689		if (fdalloc(td, 0, &fds[i]) != 0)
1690			break;
1691
1692	if (i < n) {
1693		for (i--; i >= 0; i--)
1694			fdunused(fdp, fds[i]);
1695		return (EMFILE);
1696	}
1697
1698	return (0);
1699}
1700
1701/*
1702 * Check to see whether n user file descriptors are available to the process
1703 * p.
1704 */
1705int
1706fdavail(struct thread *td, int n)
1707{
1708	struct proc *p = td->td_proc;
1709	struct filedesc *fdp = td->td_proc->p_fd;
1710	int i, lim, last;
1711
1712	FILEDESC_LOCK_ASSERT(fdp);
1713
1714	/*
1715	 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1716	 *      call racct_add() from there instead of dealing with containers
1717	 *      here.
1718	 */
1719	lim = getmaxfd(p);
1720	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1721		return (1);
1722	last = min(fdp->fd_nfiles, lim);
1723	for (i = fdp->fd_freefile; i < last; i++) {
1724		if (fdp->fd_ofiles[i].fde_file == NULL && --n <= 0)
1725			return (1);
1726	}
1727	return (0);
1728}
1729
1730/*
1731 * Create a new open file structure and allocate a file decriptor for the
1732 * process that refers to it.  We add one reference to the file for the
1733 * descriptor table and one reference for resultfp. This is to prevent us
1734 * being preempted and the entry in the descriptor table closed after we
1735 * release the FILEDESC lock.
1736 */
1737int
1738falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1739{
1740	struct file *fp;
1741	int error, fd;
1742
1743	error = falloc_noinstall(td, &fp);
1744	if (error)
1745		return (error);		/* no reference held on error */
1746
1747	error = finstall(td, fp, &fd, flags, NULL);
1748	if (error) {
1749		fdrop(fp, td);		/* one reference (fp only) */
1750		return (error);
1751	}
1752
1753	if (resultfp != NULL)
1754		*resultfp = fp;		/* copy out result */
1755	else
1756		fdrop(fp, td);		/* release local reference */
1757
1758	if (resultfd != NULL)
1759		*resultfd = fd;
1760
1761	return (0);
1762}
1763
1764/*
1765 * Create a new open file structure without allocating a file descriptor.
1766 */
1767int
1768falloc_noinstall(struct thread *td, struct file **resultfp)
1769{
1770	struct file *fp;
1771	int maxuserfiles = maxfiles - (maxfiles / 20);
1772	static struct timeval lastfail;
1773	static int curfail;
1774
1775	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1776
1777	if ((openfiles >= maxuserfiles &&
1778	    priv_check(td, PRIV_MAXFILES) != 0) ||
1779	    openfiles >= maxfiles) {
1780		if (ppsratecheck(&lastfail, &curfail, 1)) {
1781			printf("kern.maxfiles limit exceeded by uid %i, "
1782			    "please see tuning(7).\n", td->td_ucred->cr_ruid);
1783		}
1784		return (ENFILE);
1785	}
1786	atomic_add_int(&openfiles, 1);
1787	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1788	refcount_init(&fp->f_count, 1);
1789	fp->f_cred = crhold(td->td_ucred);
1790	fp->f_ops = &badfileops;
1791	fp->f_data = NULL;
1792	fp->f_vnode = NULL;
1793	*resultfp = fp;
1794	return (0);
1795}
1796
1797/*
1798 * Install a file in a file descriptor table.
1799 */
1800int
1801finstall(struct thread *td, struct file *fp, int *fd, int flags,
1802    struct filecaps *fcaps)
1803{
1804	struct filedesc *fdp = td->td_proc->p_fd;
1805	struct filedescent *fde;
1806	int error;
1807
1808	KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1809	KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1810	if (fcaps != NULL)
1811		filecaps_validate(fcaps, __func__);
1812
1813	FILEDESC_XLOCK(fdp);
1814	if ((error = fdalloc(td, 0, fd))) {
1815		FILEDESC_XUNLOCK(fdp);
1816		return (error);
1817	}
1818	fhold(fp);
1819	fde = &fdp->fd_ofiles[*fd];
1820#ifdef CAPABILITIES
1821	seq_write_begin(&fde->fde_seq);
1822#endif
1823	fde->fde_file = fp;
1824	if ((flags & O_CLOEXEC) != 0)
1825		fde->fde_flags |= UF_EXCLOSE;
1826	if (fcaps != NULL)
1827		filecaps_move(fcaps, &fde->fde_caps);
1828	else
1829		filecaps_fill(&fde->fde_caps);
1830#ifdef CAPABILITIES
1831	seq_write_end(&fde->fde_seq);
1832#endif
1833	FILEDESC_XUNLOCK(fdp);
1834	return (0);
1835}
1836
1837/*
1838 * Build a new filedesc structure from another.
1839 * Copy the current, root, and jail root vnode references.
1840 */
1841struct filedesc *
1842fdinit(struct filedesc *fdp)
1843{
1844	struct filedesc0 *newfdp;
1845
1846	newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1847	FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1848	if (fdp != NULL) {
1849		FILEDESC_SLOCK(fdp);
1850		newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1851		if (newfdp->fd_fd.fd_cdir)
1852			VREF(newfdp->fd_fd.fd_cdir);
1853		newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1854		if (newfdp->fd_fd.fd_rdir)
1855			VREF(newfdp->fd_fd.fd_rdir);
1856		newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1857		if (newfdp->fd_fd.fd_jdir)
1858			VREF(newfdp->fd_fd.fd_jdir);
1859		FILEDESC_SUNLOCK(fdp);
1860	}
1861
1862	/* Create the file descriptor table. */
1863	newfdp->fd_fd.fd_refcnt = 1;
1864	newfdp->fd_fd.fd_holdcnt = 1;
1865	newfdp->fd_fd.fd_cmask = CMASK;
1866	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1867	newfdp->fd_fd.fd_nfiles = NDFILE;
1868	newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1869	newfdp->fd_fd.fd_lastfile = -1;
1870	return (&newfdp->fd_fd);
1871}
1872
1873static struct filedesc *
1874fdhold(struct proc *p)
1875{
1876	struct filedesc *fdp;
1877
1878	mtx_lock(&fdesc_mtx);
1879	fdp = p->p_fd;
1880	if (fdp != NULL)
1881		fdp->fd_holdcnt++;
1882	mtx_unlock(&fdesc_mtx);
1883	return (fdp);
1884}
1885
1886static void
1887fddrop(struct filedesc *fdp)
1888{
1889	struct filedesc0 *fdp0;
1890	struct freetable *ft;
1891	int i;
1892
1893	mtx_lock(&fdesc_mtx);
1894	i = --fdp->fd_holdcnt;
1895	mtx_unlock(&fdesc_mtx);
1896	if (i > 0)
1897		return;
1898
1899	FILEDESC_LOCK_DESTROY(fdp);
1900	fdp0 = (struct filedesc0 *)fdp;
1901	while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1902		SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1903		free(ft->ft_table, M_FILEDESC);
1904	}
1905	free(fdp, M_FILEDESC);
1906}
1907
1908/*
1909 * Share a filedesc structure.
1910 */
1911struct filedesc *
1912fdshare(struct filedesc *fdp)
1913{
1914
1915	FILEDESC_XLOCK(fdp);
1916	fdp->fd_refcnt++;
1917	FILEDESC_XUNLOCK(fdp);
1918	return (fdp);
1919}
1920
1921/*
1922 * Unshare a filedesc structure, if necessary by making a copy
1923 */
1924void
1925fdunshare(struct thread *td)
1926{
1927	struct filedesc *tmp;
1928	struct proc *p = td->td_proc;
1929
1930	if (p->p_fd->fd_refcnt == 1)
1931		return;
1932
1933	tmp = fdcopy(p->p_fd);
1934	fdescfree(td);
1935	p->p_fd = tmp;
1936}
1937
1938/*
1939 * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
1940 * this is to ease callers, not catch errors.
1941 */
1942struct filedesc *
1943fdcopy(struct filedesc *fdp)
1944{
1945	struct filedesc *newfdp;
1946	struct filedescent *nfde, *ofde;
1947	int i;
1948
1949	/* Certain daemons might not have file descriptors. */
1950	if (fdp == NULL)
1951		return (NULL);
1952
1953	newfdp = fdinit(fdp);
1954	FILEDESC_SLOCK(fdp);
1955	while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1956		FILEDESC_SUNLOCK(fdp);
1957		FILEDESC_XLOCK(newfdp);
1958		fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1959		FILEDESC_XUNLOCK(newfdp);
1960		FILEDESC_SLOCK(fdp);
1961	}
1962	/* copy all passable descriptors (i.e. not kqueue) */
1963	newfdp->fd_freefile = -1;
1964	for (i = 0; i <= fdp->fd_lastfile; ++i) {
1965		ofde = &fdp->fd_ofiles[i];
1966		if (fdisused(fdp, i) &&
1967		    (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1968		    ofde->fde_file->f_ops != &badfileops) {
1969			nfde = &newfdp->fd_ofiles[i];
1970			*nfde = *ofde;
1971			filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1972			fhold(nfde->fde_file);
1973			newfdp->fd_lastfile = i;
1974		} else {
1975			if (newfdp->fd_freefile == -1)
1976				newfdp->fd_freefile = i;
1977		}
1978	}
1979	newfdp->fd_cmask = fdp->fd_cmask;
1980	FILEDESC_SUNLOCK(fdp);
1981	FILEDESC_XLOCK(newfdp);
1982	for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1983		if (newfdp->fd_ofiles[i].fde_file != NULL)
1984			fdused(newfdp, i);
1985	}
1986	if (newfdp->fd_freefile == -1)
1987		newfdp->fd_freefile = i;
1988	FILEDESC_XUNLOCK(newfdp);
1989	return (newfdp);
1990}
1991
1992/*
1993 * Release a filedesc structure.
1994 */
1995void
1996fdescfree(struct thread *td)
1997{
1998	struct filedesc *fdp;
1999	int i;
2000	struct filedesc_to_leader *fdtol;
2001	struct file *fp;
2002	struct vnode *cdir, *jdir, *rdir, *vp;
2003	struct flock lf;
2004
2005	/* Certain daemons might not have file descriptors. */
2006	fdp = td->td_proc->p_fd;
2007	if (fdp == NULL)
2008		return;
2009
2010#ifdef RACCT
2011	PROC_LOCK(td->td_proc);
2012	racct_set(td->td_proc, RACCT_NOFILE, 0);
2013	PROC_UNLOCK(td->td_proc);
2014#endif
2015
2016	/* Check for special need to clear POSIX style locks */
2017	fdtol = td->td_proc->p_fdtol;
2018	if (fdtol != NULL) {
2019		FILEDESC_XLOCK(fdp);
2020		KASSERT(fdtol->fdl_refcount > 0,
2021		    ("filedesc_to_refcount botch: fdl_refcount=%d",
2022		    fdtol->fdl_refcount));
2023		if (fdtol->fdl_refcount == 1 &&
2024		    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2025			for (i = 0; i <= fdp->fd_lastfile; i++) {
2026				fp = fdp->fd_ofiles[i].fde_file;
2027				if (fp == NULL || fp->f_type != DTYPE_VNODE)
2028					continue;
2029				fhold(fp);
2030				FILEDESC_XUNLOCK(fdp);
2031				lf.l_whence = SEEK_SET;
2032				lf.l_start = 0;
2033				lf.l_len = 0;
2034				lf.l_type = F_UNLCK;
2035				vp = fp->f_vnode;
2036				(void) VOP_ADVLOCK(vp,
2037				    (caddr_t)td->td_proc->p_leader, F_UNLCK,
2038				    &lf, F_POSIX);
2039				FILEDESC_XLOCK(fdp);
2040				fdrop(fp, td);
2041			}
2042		}
2043	retry:
2044		if (fdtol->fdl_refcount == 1) {
2045			if (fdp->fd_holdleaderscount > 0 &&
2046			    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2047				/*
2048				 * close() or do_dup() has cleared a reference
2049				 * in a shared file descriptor table.
2050				 */
2051				fdp->fd_holdleaderswakeup = 1;
2052				sx_sleep(&fdp->fd_holdleaderscount,
2053				    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2054				goto retry;
2055			}
2056			if (fdtol->fdl_holdcount > 0) {
2057				/*
2058				 * Ensure that fdtol->fdl_leader remains
2059				 * valid in closef().
2060				 */
2061				fdtol->fdl_wakeup = 1;
2062				sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2063				    "fdlhold", 0);
2064				goto retry;
2065			}
2066		}
2067		fdtol->fdl_refcount--;
2068		if (fdtol->fdl_refcount == 0 &&
2069		    fdtol->fdl_holdcount == 0) {
2070			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2071			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2072		} else
2073			fdtol = NULL;
2074		td->td_proc->p_fdtol = NULL;
2075		FILEDESC_XUNLOCK(fdp);
2076		if (fdtol != NULL)
2077			free(fdtol, M_FILEDESC_TO_LEADER);
2078	}
2079
2080	mtx_lock(&fdesc_mtx);
2081	td->td_proc->p_fd = NULL;
2082	mtx_unlock(&fdesc_mtx);
2083
2084	FILEDESC_XLOCK(fdp);
2085	i = --fdp->fd_refcnt;
2086	if (i > 0) {
2087		FILEDESC_XUNLOCK(fdp);
2088		return;
2089	}
2090
2091	cdir = fdp->fd_cdir;
2092	fdp->fd_cdir = NULL;
2093	rdir = fdp->fd_rdir;
2094	fdp->fd_rdir = NULL;
2095	jdir = fdp->fd_jdir;
2096	fdp->fd_jdir = NULL;
2097	FILEDESC_XUNLOCK(fdp);
2098
2099	for (i = 0; i <= fdp->fd_lastfile; i++) {
2100		fp = fdp->fd_ofiles[i].fde_file;
2101		if (fp != NULL) {
2102			fdfree_last(fdp, i);
2103			(void) closef(fp, td);
2104		}
2105	}
2106
2107	if (fdp->fd_nfiles > NDFILE)
2108		free(fdp->fd_ofiles, M_FILEDESC);
2109	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2110		free(fdp->fd_map, M_FILEDESC);
2111
2112	if (cdir != NULL)
2113		vrele(cdir);
2114	if (rdir != NULL)
2115		vrele(rdir);
2116	if (jdir != NULL)
2117		vrele(jdir);
2118
2119	fddrop(fdp);
2120}
2121
2122/*
2123 * For setugid programs, we don't want to people to use that setugidness
2124 * to generate error messages which write to a file which otherwise would
2125 * otherwise be off-limits to the process.  We check for filesystems where
2126 * the vnode can change out from under us after execve (like [lin]procfs).
2127 *
2128 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2129 * sufficient.  We also don't check for setugidness since we know we are.
2130 */
2131static int
2132is_unsafe(struct file *fp)
2133{
2134	if (fp->f_type == DTYPE_VNODE) {
2135		struct vnode *vp = fp->f_vnode;
2136
2137		if ((vp->v_vflag & VV_PROCDEP) != 0)
2138			return (1);
2139	}
2140	return (0);
2141}
2142
2143/*
2144 * Make this setguid thing safe, if at all possible.
2145 */
2146void
2147setugidsafety(struct thread *td)
2148{
2149	struct filedesc *fdp;
2150	struct file *fp;
2151	int i;
2152
2153	fdp = td->td_proc->p_fd;
2154	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2155	FILEDESC_XLOCK(fdp);
2156	for (i = 0; i <= fdp->fd_lastfile; i++) {
2157		if (i > 2)
2158			break;
2159		fp = fdp->fd_ofiles[i].fde_file;
2160		if (fp != NULL && is_unsafe(fp)) {
2161			knote_fdclose(td, i);
2162			/*
2163			 * NULL-out descriptor prior to close to avoid
2164			 * a race while close blocks.
2165			 */
2166			fdfree(fdp, i);
2167			FILEDESC_XUNLOCK(fdp);
2168			(void) closef(fp, td);
2169			FILEDESC_XLOCK(fdp);
2170		}
2171	}
2172	FILEDESC_XUNLOCK(fdp);
2173}
2174
2175/*
2176 * If a specific file object occupies a specific file descriptor, close the
2177 * file descriptor entry and drop a reference on the file object.  This is a
2178 * convenience function to handle a subsequent error in a function that calls
2179 * falloc() that handles the race that another thread might have closed the
2180 * file descriptor out from under the thread creating the file object.
2181 */
2182void
2183fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2184{
2185
2186	FILEDESC_XLOCK(fdp);
2187	if (fdp->fd_ofiles[idx].fde_file == fp) {
2188		fdfree(fdp, idx);
2189		FILEDESC_XUNLOCK(fdp);
2190		fdrop(fp, td);
2191	} else
2192		FILEDESC_XUNLOCK(fdp);
2193}
2194
2195/*
2196 * Close any files on exec?
2197 */
2198void
2199fdcloseexec(struct thread *td)
2200{
2201	struct filedesc *fdp;
2202	struct filedescent *fde;
2203	struct file *fp;
2204	int i;
2205
2206	fdp = td->td_proc->p_fd;
2207	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2208	FILEDESC_XLOCK(fdp);
2209	for (i = 0; i <= fdp->fd_lastfile; i++) {
2210		fde = &fdp->fd_ofiles[i];
2211		fp = fde->fde_file;
2212		if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2213		    (fde->fde_flags & UF_EXCLOSE))) {
2214			fdfree(fdp, i);
2215			(void) closefp(fdp, i, fp, td, 0);
2216			/* closefp() drops the FILEDESC lock. */
2217			FILEDESC_XLOCK(fdp);
2218		}
2219	}
2220	FILEDESC_XUNLOCK(fdp);
2221}
2222
2223/*
2224 * It is unsafe for set[ug]id processes to be started with file
2225 * descriptors 0..2 closed, as these descriptors are given implicit
2226 * significance in the Standard C library.  fdcheckstd() will create a
2227 * descriptor referencing /dev/null for each of stdin, stdout, and
2228 * stderr that is not already open.
2229 */
2230int
2231fdcheckstd(struct thread *td)
2232{
2233	struct filedesc *fdp;
2234	register_t retval, save;
2235	int i, error, devnull;
2236
2237	fdp = td->td_proc->p_fd;
2238	KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2239	devnull = -1;
2240	error = 0;
2241	for (i = 0; i < 3; i++) {
2242		if (fdp->fd_ofiles[i].fde_file != NULL)
2243			continue;
2244		if (devnull < 0) {
2245			save = td->td_retval[0];
2246			error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2247			    O_RDWR, 0);
2248			devnull = td->td_retval[0];
2249			td->td_retval[0] = save;
2250			if (error)
2251				break;
2252			KASSERT(devnull == i, ("oof, we didn't get our fd"));
2253		} else {
2254			error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2255			if (error != 0)
2256				break;
2257		}
2258	}
2259	return (error);
2260}
2261
2262/*
2263 * Internal form of close.  Decrement reference count on file structure.
2264 * Note: td may be NULL when closing a file that was being passed in a
2265 * message.
2266 *
2267 * XXXRW: Giant is not required for the caller, but often will be held; this
2268 * makes it moderately likely the Giant will be recursed in the VFS case.
2269 */
2270int
2271closef(struct file *fp, struct thread *td)
2272{
2273	struct vnode *vp;
2274	struct flock lf;
2275	struct filedesc_to_leader *fdtol;
2276	struct filedesc *fdp;
2277
2278	/*
2279	 * POSIX record locking dictates that any close releases ALL
2280	 * locks owned by this process.  This is handled by setting
2281	 * a flag in the unlock to free ONLY locks obeying POSIX
2282	 * semantics, and not to free BSD-style file locks.
2283	 * If the descriptor was in a message, POSIX-style locks
2284	 * aren't passed with the descriptor, and the thread pointer
2285	 * will be NULL.  Callers should be careful only to pass a
2286	 * NULL thread pointer when there really is no owning
2287	 * context that might have locks, or the locks will be
2288	 * leaked.
2289	 */
2290	if (fp->f_type == DTYPE_VNODE && td != NULL) {
2291		vp = fp->f_vnode;
2292		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2293			lf.l_whence = SEEK_SET;
2294			lf.l_start = 0;
2295			lf.l_len = 0;
2296			lf.l_type = F_UNLCK;
2297			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2298			    F_UNLCK, &lf, F_POSIX);
2299		}
2300		fdtol = td->td_proc->p_fdtol;
2301		if (fdtol != NULL) {
2302			/*
2303			 * Handle special case where file descriptor table is
2304			 * shared between multiple process leaders.
2305			 */
2306			fdp = td->td_proc->p_fd;
2307			FILEDESC_XLOCK(fdp);
2308			for (fdtol = fdtol->fdl_next;
2309			     fdtol != td->td_proc->p_fdtol;
2310			     fdtol = fdtol->fdl_next) {
2311				if ((fdtol->fdl_leader->p_flag &
2312				     P_ADVLOCK) == 0)
2313					continue;
2314				fdtol->fdl_holdcount++;
2315				FILEDESC_XUNLOCK(fdp);
2316				lf.l_whence = SEEK_SET;
2317				lf.l_start = 0;
2318				lf.l_len = 0;
2319				lf.l_type = F_UNLCK;
2320				vp = fp->f_vnode;
2321				(void) VOP_ADVLOCK(vp,
2322				    (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2323				    F_POSIX);
2324				FILEDESC_XLOCK(fdp);
2325				fdtol->fdl_holdcount--;
2326				if (fdtol->fdl_holdcount == 0 &&
2327				    fdtol->fdl_wakeup != 0) {
2328					fdtol->fdl_wakeup = 0;
2329					wakeup(fdtol);
2330				}
2331			}
2332			FILEDESC_XUNLOCK(fdp);
2333		}
2334	}
2335	return (fdrop(fp, td));
2336}
2337
2338/*
2339 * Initialize the file pointer with the specified properties.
2340 *
2341 * The ops are set with release semantics to be certain that the flags, type,
2342 * and data are visible when ops is.  This is to prevent ops methods from being
2343 * called with bad data.
2344 */
2345void
2346finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2347{
2348	fp->f_data = data;
2349	fp->f_flag = flag;
2350	fp->f_type = type;
2351	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2352}
2353
2354int
2355fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2356    int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2357{
2358#ifdef CAPABILITIES
2359	struct filedescent fde;
2360#endif
2361	struct file *fp;
2362	u_int count;
2363#ifdef CAPABILITIES
2364	seq_t seq;
2365	cap_rights_t haverights;
2366	int error;
2367#endif
2368
2369	/*
2370	 * Avoid reads reordering and then a first access to the
2371	 * fdp->fd_ofiles table which could result in OOB operation.
2372	 */
2373	if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2374		return (EBADF);
2375	/*
2376	 * Fetch the descriptor locklessly.  We avoid fdrop() races by
2377	 * never raising a refcount above 0.  To accomplish this we have
2378	 * to use a cmpset loop rather than an atomic_add.  The descriptor
2379	 * must be re-verified once we acquire a reference to be certain
2380	 * that the identity is still correct and we did not lose a race
2381	 * due to preemption.
2382	 */
2383	for (;;) {
2384#ifdef CAPABILITIES
2385		seq = seq_read(fd_seq(fdp, fd));
2386		fde = fdp->fd_ofiles[fd];
2387		if (!seq_consistent(fd_seq(fdp, fd), seq)) {
2388			cpu_spinwait();
2389			continue;
2390		}
2391		fp = fde.fde_file;
2392#else
2393		fp = fdp->fd_ofiles[fd].fde_file;
2394#endif
2395		if (fp == NULL)
2396			return (EBADF);
2397#ifdef CAPABILITIES
2398		haverights = *cap_rights_fde(&fde);
2399		if (needrightsp != NULL) {
2400			error = cap_check(&haverights, needrightsp);
2401			if (error != 0)
2402				return (error);
2403			if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2404				error = cap_fcntl_check_fde(&fde, needfcntl);
2405				if (error != 0)
2406					return (error);
2407			}
2408		}
2409#endif
2410		count = fp->f_count;
2411		if (count == 0)
2412			continue;
2413		/*
2414		 * Use an acquire barrier to prevent caching of fd_ofiles
2415		 * so it is refreshed for verification.
2416		 */
2417		if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2418			continue;
2419#ifdef	CAPABILITIES
2420		if (seq_consistent_nomb(fd_seq(fdp, fd), seq))
2421#else
2422		if (fp == fdp->fd_ofiles[fd].fde_file)
2423#endif
2424			break;
2425		fdrop(fp, curthread);
2426	}
2427	*fpp = fp;
2428	if (haverightsp != NULL) {
2429#ifdef CAPABILITIES
2430		*haverightsp = haverights;
2431#else
2432		CAP_ALL(haverightsp);
2433#endif
2434	}
2435	return (0);
2436}
2437
2438/*
2439 * Extract the file pointer associated with the specified descriptor for the
2440 * current user process.
2441 *
2442 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2443 * returned.
2444 *
2445 * File's rights will be checked against the capability rights mask.
2446 *
2447 * If an error occured the non-zero error is returned and *fpp is set to
2448 * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
2449 * responsible for fdrop().
2450 */
2451static __inline int
2452_fget(struct thread *td, int fd, struct file **fpp, int flags,
2453    cap_rights_t *needrightsp, u_char *maxprotp)
2454{
2455	struct filedesc *fdp;
2456	struct file *fp;
2457	cap_rights_t haverights, needrights;
2458	int error;
2459
2460	*fpp = NULL;
2461	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2462		return (EBADF);
2463	if (needrightsp != NULL)
2464		needrights = *needrightsp;
2465	else
2466		cap_rights_init(&needrights);
2467	if (maxprotp != NULL)
2468		cap_rights_set(&needrights, CAP_MMAP);
2469	error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2470	if (error != 0)
2471		return (error);
2472	if (fp->f_ops == &badfileops) {
2473		fdrop(fp, td);
2474		return (EBADF);
2475	}
2476
2477#ifdef CAPABILITIES
2478	/*
2479	 * If requested, convert capability rights to access flags.
2480	 */
2481	if (maxprotp != NULL)
2482		*maxprotp = cap_rights_to_vmprot(&haverights);
2483#else /* !CAPABILITIES */
2484	if (maxprotp != NULL)
2485		*maxprotp = VM_PROT_ALL;
2486#endif /* CAPABILITIES */
2487
2488	/*
2489	 * FREAD and FWRITE failure return EBADF as per POSIX.
2490	 */
2491	error = 0;
2492	switch (flags) {
2493	case FREAD:
2494	case FWRITE:
2495		if ((fp->f_flag & flags) == 0)
2496			error = EBADF;
2497		break;
2498	case FEXEC:
2499	    	if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2500		    ((fp->f_flag & FWRITE) != 0))
2501			error = EBADF;
2502		break;
2503	case 0:
2504		break;
2505	default:
2506		KASSERT(0, ("wrong flags"));
2507	}
2508
2509	if (error != 0) {
2510		fdrop(fp, td);
2511		return (error);
2512	}
2513
2514	*fpp = fp;
2515	return (0);
2516}
2517
2518int
2519fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2520{
2521
2522	return(_fget(td, fd, fpp, 0, rightsp, NULL));
2523}
2524
2525int
2526fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2527    struct file **fpp)
2528{
2529
2530	return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2531}
2532
2533int
2534fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2535{
2536
2537	return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2538}
2539
2540int
2541fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2542{
2543
2544	return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2545}
2546
2547/*
2548 * Like fget() but loads the underlying vnode, or returns an error if the
2549 * descriptor does not represent a vnode.  Note that pipes use vnodes but
2550 * never have VM objects.  The returned vnode will be vref()'d.
2551 *
2552 * XXX: what about the unused flags ?
2553 */
2554static __inline int
2555_fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2556    struct vnode **vpp)
2557{
2558	struct file *fp;
2559	int error;
2560
2561	*vpp = NULL;
2562	error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2563	if (error != 0)
2564		return (error);
2565	if (fp->f_vnode == NULL) {
2566		error = EINVAL;
2567	} else {
2568		*vpp = fp->f_vnode;
2569		vref(*vpp);
2570	}
2571	fdrop(fp, td);
2572
2573	return (error);
2574}
2575
2576int
2577fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2578{
2579
2580	return (_fgetvp(td, fd, 0, rightsp, vpp));
2581}
2582
2583int
2584fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2585    struct filecaps *havecaps, struct vnode **vpp)
2586{
2587	struct filedesc *fdp;
2588	struct file *fp;
2589#ifdef CAPABILITIES
2590	int error;
2591#endif
2592
2593	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2594		return (EBADF);
2595
2596	fp = fget_locked(fdp, fd);
2597	if (fp == NULL || fp->f_ops == &badfileops)
2598		return (EBADF);
2599
2600#ifdef CAPABILITIES
2601	if (needrightsp != NULL) {
2602		error = cap_check(cap_rights(fdp, fd), needrightsp);
2603		if (error != 0)
2604			return (error);
2605	}
2606#endif
2607
2608	if (fp->f_vnode == NULL)
2609		return (EINVAL);
2610
2611	*vpp = fp->f_vnode;
2612	vref(*vpp);
2613	filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2614
2615	return (0);
2616}
2617
2618int
2619fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2620{
2621
2622	return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2623}
2624
2625int
2626fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2627{
2628
2629	return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2630}
2631
2632#ifdef notyet
2633int
2634fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2635    struct vnode **vpp)
2636{
2637
2638	return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2639}
2640#endif
2641
2642/*
2643 * Like fget() but loads the underlying socket, or returns an error if the
2644 * descriptor does not represent a socket.
2645 *
2646 * We bump the ref count on the returned socket.  XXX Also obtain the SX lock
2647 * in the future.
2648 *
2649 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2650 * on their file descriptor reference to prevent the socket from being free'd
2651 * during use.
2652 */
2653int
2654fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2655    u_int *fflagp)
2656{
2657	struct file *fp;
2658	int error;
2659
2660	*spp = NULL;
2661	if (fflagp != NULL)
2662		*fflagp = 0;
2663	if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2664		return (error);
2665	if (fp->f_type != DTYPE_SOCKET) {
2666		error = ENOTSOCK;
2667	} else {
2668		*spp = fp->f_data;
2669		if (fflagp)
2670			*fflagp = fp->f_flag;
2671		SOCK_LOCK(*spp);
2672		soref(*spp);
2673		SOCK_UNLOCK(*spp);
2674	}
2675	fdrop(fp, td);
2676
2677	return (error);
2678}
2679
2680/*
2681 * Drop the reference count on the socket and XXX release the SX lock in the
2682 * future.  The last reference closes the socket.
2683 *
2684 * Note: fputsock() is deprecated, see comment for fgetsock().
2685 */
2686void
2687fputsock(struct socket *so)
2688{
2689
2690	ACCEPT_LOCK();
2691	SOCK_LOCK(so);
2692	CURVNET_SET(so->so_vnet);
2693	sorele(so);
2694	CURVNET_RESTORE();
2695}
2696
2697/*
2698 * Handle the last reference to a file being closed.
2699 */
2700int
2701_fdrop(struct file *fp, struct thread *td)
2702{
2703	int error;
2704
2705	error = 0;
2706	if (fp->f_count != 0)
2707		panic("fdrop: count %d", fp->f_count);
2708	if (fp->f_ops != &badfileops)
2709		error = fo_close(fp, td);
2710	atomic_subtract_int(&openfiles, 1);
2711	crfree(fp->f_cred);
2712	free(fp->f_advice, M_FADVISE);
2713	uma_zfree(file_zone, fp);
2714
2715	return (error);
2716}
2717
2718/*
2719 * Apply an advisory lock on a file descriptor.
2720 *
2721 * Just attempt to get a record lock of the requested type on the entire file
2722 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2723 */
2724#ifndef _SYS_SYSPROTO_H_
2725struct flock_args {
2726	int	fd;
2727	int	how;
2728};
2729#endif
2730/* ARGSUSED */
2731int
2732sys_flock(struct thread *td, struct flock_args *uap)
2733{
2734	struct file *fp;
2735	struct vnode *vp;
2736	struct flock lf;
2737	cap_rights_t rights;
2738	int error;
2739
2740	error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2741	if (error != 0)
2742		return (error);
2743	if (fp->f_type != DTYPE_VNODE) {
2744		fdrop(fp, td);
2745		return (EOPNOTSUPP);
2746	}
2747
2748	vp = fp->f_vnode;
2749	lf.l_whence = SEEK_SET;
2750	lf.l_start = 0;
2751	lf.l_len = 0;
2752	if (uap->how & LOCK_UN) {
2753		lf.l_type = F_UNLCK;
2754		atomic_clear_int(&fp->f_flag, FHASLOCK);
2755		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2756		goto done2;
2757	}
2758	if (uap->how & LOCK_EX)
2759		lf.l_type = F_WRLCK;
2760	else if (uap->how & LOCK_SH)
2761		lf.l_type = F_RDLCK;
2762	else {
2763		error = EBADF;
2764		goto done2;
2765	}
2766	atomic_set_int(&fp->f_flag, FHASLOCK);
2767	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2768	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2769done2:
2770	fdrop(fp, td);
2771	return (error);
2772}
2773/*
2774 * Duplicate the specified descriptor to a free descriptor.
2775 */
2776int
2777dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2778    int openerror, int *indxp)
2779{
2780	struct filedescent *newfde, *oldfde;
2781	struct file *fp;
2782	int error, indx;
2783
2784	KASSERT(openerror == ENODEV || openerror == ENXIO,
2785	    ("unexpected error %d in %s", openerror, __func__));
2786
2787	/*
2788	 * If the to-be-dup'd fd number is greater than the allowed number
2789	 * of file descriptors, or the fd to be dup'd has already been
2790	 * closed, then reject.
2791	 */
2792	FILEDESC_XLOCK(fdp);
2793	if ((fp = fget_locked(fdp, dfd)) == NULL) {
2794		FILEDESC_XUNLOCK(fdp);
2795		return (EBADF);
2796	}
2797
2798	error = fdalloc(td, 0, &indx);
2799	if (error != 0) {
2800		FILEDESC_XUNLOCK(fdp);
2801		return (error);
2802	}
2803
2804	/*
2805	 * There are two cases of interest here.
2806	 *
2807	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2808	 *
2809	 * For ENXIO steal away the file structure from (dfd) and store it in
2810	 * (indx).  (dfd) is effectively closed by this operation.
2811	 */
2812	switch (openerror) {
2813	case ENODEV:
2814		/*
2815		 * Check that the mode the file is being opened for is a
2816		 * subset of the mode of the existing descriptor.
2817		 */
2818		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2819			fdunused(fdp, indx);
2820			FILEDESC_XUNLOCK(fdp);
2821			return (EACCES);
2822		}
2823		fhold(fp);
2824		newfde = &fdp->fd_ofiles[indx];
2825		oldfde = &fdp->fd_ofiles[dfd];
2826#ifdef CAPABILITIES
2827		seq_write_begin(&newfde->fde_seq);
2828#endif
2829		memcpy(newfde, oldfde, fde_change_size);
2830		filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
2831#ifdef CAPABILITIES
2832		seq_write_end(&newfde->fde_seq);
2833#endif
2834		break;
2835	case ENXIO:
2836		/*
2837		 * Steal away the file pointer from dfd and stuff it into indx.
2838		 */
2839		newfde = &fdp->fd_ofiles[indx];
2840		oldfde = &fdp->fd_ofiles[dfd];
2841#ifdef CAPABILITIES
2842		seq_write_begin(&newfde->fde_seq);
2843#endif
2844		memcpy(newfde, oldfde, fde_change_size);
2845		bzero(oldfde, fde_change_size);
2846		fdunused(fdp, dfd);
2847#ifdef CAPABILITIES
2848		seq_write_end(&newfde->fde_seq);
2849#endif
2850		break;
2851	}
2852	FILEDESC_XUNLOCK(fdp);
2853	*indxp = indx;
2854	return (0);
2855}
2856
2857/*
2858 * Scan all active processes and prisons to see if any of them have a current
2859 * or root directory of `olddp'. If so, replace them with the new mount point.
2860 */
2861void
2862mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2863{
2864	struct filedesc *fdp;
2865	struct prison *pr;
2866	struct proc *p;
2867	int nrele;
2868
2869	if (vrefcnt(olddp) == 1)
2870		return;
2871	nrele = 0;
2872	sx_slock(&allproc_lock);
2873	FOREACH_PROC_IN_SYSTEM(p) {
2874		fdp = fdhold(p);
2875		if (fdp == NULL)
2876			continue;
2877		FILEDESC_XLOCK(fdp);
2878		if (fdp->fd_cdir == olddp) {
2879			vref(newdp);
2880			fdp->fd_cdir = newdp;
2881			nrele++;
2882		}
2883		if (fdp->fd_rdir == olddp) {
2884			vref(newdp);
2885			fdp->fd_rdir = newdp;
2886			nrele++;
2887		}
2888		if (fdp->fd_jdir == olddp) {
2889			vref(newdp);
2890			fdp->fd_jdir = newdp;
2891			nrele++;
2892		}
2893		FILEDESC_XUNLOCK(fdp);
2894		fddrop(fdp);
2895	}
2896	sx_sunlock(&allproc_lock);
2897	if (rootvnode == olddp) {
2898		vref(newdp);
2899		rootvnode = newdp;
2900		nrele++;
2901	}
2902	mtx_lock(&prison0.pr_mtx);
2903	if (prison0.pr_root == olddp) {
2904		vref(newdp);
2905		prison0.pr_root = newdp;
2906		nrele++;
2907	}
2908	mtx_unlock(&prison0.pr_mtx);
2909	sx_slock(&allprison_lock);
2910	TAILQ_FOREACH(pr, &allprison, pr_list) {
2911		mtx_lock(&pr->pr_mtx);
2912		if (pr->pr_root == olddp) {
2913			vref(newdp);
2914			pr->pr_root = newdp;
2915			nrele++;
2916		}
2917		mtx_unlock(&pr->pr_mtx);
2918	}
2919	sx_sunlock(&allprison_lock);
2920	while (nrele--)
2921		vrele(olddp);
2922}
2923
2924struct filedesc_to_leader *
2925filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2926{
2927	struct filedesc_to_leader *fdtol;
2928
2929	fdtol = malloc(sizeof(struct filedesc_to_leader),
2930	       M_FILEDESC_TO_LEADER,
2931	       M_WAITOK);
2932	fdtol->fdl_refcount = 1;
2933	fdtol->fdl_holdcount = 0;
2934	fdtol->fdl_wakeup = 0;
2935	fdtol->fdl_leader = leader;
2936	if (old != NULL) {
2937		FILEDESC_XLOCK(fdp);
2938		fdtol->fdl_next = old->fdl_next;
2939		fdtol->fdl_prev = old;
2940		old->fdl_next = fdtol;
2941		fdtol->fdl_next->fdl_prev = fdtol;
2942		FILEDESC_XUNLOCK(fdp);
2943	} else {
2944		fdtol->fdl_next = fdtol;
2945		fdtol->fdl_prev = fdtol;
2946	}
2947	return (fdtol);
2948}
2949
2950/*
2951 * Get file structures globally.
2952 */
2953static int
2954sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2955{
2956	struct xfile xf;
2957	struct filedesc *fdp;
2958	struct file *fp;
2959	struct proc *p;
2960	int error, n;
2961
2962	error = sysctl_wire_old_buffer(req, 0);
2963	if (error != 0)
2964		return (error);
2965	if (req->oldptr == NULL) {
2966		n = 0;
2967		sx_slock(&allproc_lock);
2968		FOREACH_PROC_IN_SYSTEM(p) {
2969			if (p->p_state == PRS_NEW)
2970				continue;
2971			fdp = fdhold(p);
2972			if (fdp == NULL)
2973				continue;
2974			/* overestimates sparse tables. */
2975			if (fdp->fd_lastfile > 0)
2976				n += fdp->fd_lastfile;
2977			fddrop(fdp);
2978		}
2979		sx_sunlock(&allproc_lock);
2980		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2981	}
2982	error = 0;
2983	bzero(&xf, sizeof(xf));
2984	xf.xf_size = sizeof(xf);
2985	sx_slock(&allproc_lock);
2986	FOREACH_PROC_IN_SYSTEM(p) {
2987		PROC_LOCK(p);
2988		if (p->p_state == PRS_NEW) {
2989			PROC_UNLOCK(p);
2990			continue;
2991		}
2992		if (p_cansee(req->td, p) != 0) {
2993			PROC_UNLOCK(p);
2994			continue;
2995		}
2996		xf.xf_pid = p->p_pid;
2997		xf.xf_uid = p->p_ucred->cr_uid;
2998		PROC_UNLOCK(p);
2999		fdp = fdhold(p);
3000		if (fdp == NULL)
3001			continue;
3002		FILEDESC_SLOCK(fdp);
3003		for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3004			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3005				continue;
3006			xf.xf_fd = n;
3007			xf.xf_file = fp;
3008			xf.xf_data = fp->f_data;
3009			xf.xf_vnode = fp->f_vnode;
3010			xf.xf_type = fp->f_type;
3011			xf.xf_count = fp->f_count;
3012			xf.xf_msgcount = 0;
3013			xf.xf_offset = foffset_get(fp);
3014			xf.xf_flag = fp->f_flag;
3015			error = SYSCTL_OUT(req, &xf, sizeof(xf));
3016			if (error)
3017				break;
3018		}
3019		FILEDESC_SUNLOCK(fdp);
3020		fddrop(fdp);
3021		if (error)
3022			break;
3023	}
3024	sx_sunlock(&allproc_lock);
3025	return (error);
3026}
3027
3028SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3029    0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3030
3031#ifdef KINFO_OFILE_SIZE
3032CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3033#endif
3034
3035#ifdef COMPAT_FREEBSD7
3036static int
3037export_vnode_for_osysctl(struct vnode *vp, int type,
3038    struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
3039{
3040	int error;
3041	char *fullpath, *freepath;
3042
3043	bzero(kif, sizeof(*kif));
3044	kif->kf_structsize = sizeof(*kif);
3045
3046	vref(vp);
3047	kif->kf_fd = type;
3048	kif->kf_type = KF_TYPE_VNODE;
3049	/* This function only handles directories. */
3050	if (vp->v_type != VDIR) {
3051		vrele(vp);
3052		return (ENOTDIR);
3053	}
3054	kif->kf_vnode_type = KF_VTYPE_VDIR;
3055
3056	/*
3057	 * This is not a true file descriptor, so we set a bogus refcount
3058	 * and offset to indicate these fields should be ignored.
3059	 */
3060	kif->kf_ref_count = -1;
3061	kif->kf_offset = -1;
3062
3063	freepath = NULL;
3064	fullpath = "-";
3065	FILEDESC_SUNLOCK(fdp);
3066	vn_fullpath(curthread, vp, &fullpath, &freepath);
3067	vrele(vp);
3068	strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3069	if (freepath != NULL)
3070		free(freepath, M_TEMP);
3071	error = SYSCTL_OUT(req, kif, sizeof(*kif));
3072	FILEDESC_SLOCK(fdp);
3073	return (error);
3074}
3075
3076/*
3077 * Get per-process file descriptors for use by procstat(1), et al.
3078 */
3079static int
3080sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3081{
3082	char *fullpath, *freepath;
3083	struct kinfo_ofile *kif;
3084	struct filedesc *fdp;
3085	int error, i, *name;
3086	struct shmfd *shmfd;
3087	struct socket *so;
3088	struct vnode *vp;
3089	struct ksem *ks;
3090	struct file *fp;
3091	struct proc *p;
3092	struct tty *tp;
3093
3094	name = (int *)arg1;
3095	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3096	if (error != 0)
3097		return (error);
3098	fdp = fdhold(p);
3099	PROC_UNLOCK(p);
3100	if (fdp == NULL)
3101		return (ENOENT);
3102	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3103	FILEDESC_SLOCK(fdp);
3104	if (fdp->fd_cdir != NULL)
3105		export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3106				fdp, req);
3107	if (fdp->fd_rdir != NULL)
3108		export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3109				fdp, req);
3110	if (fdp->fd_jdir != NULL)
3111		export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3112				fdp, req);
3113	for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3114		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3115			continue;
3116		bzero(kif, sizeof(*kif));
3117		kif->kf_structsize = sizeof(*kif);
3118		ks = NULL;
3119		vp = NULL;
3120		so = NULL;
3121		tp = NULL;
3122		shmfd = NULL;
3123		kif->kf_fd = i;
3124
3125		switch (fp->f_type) {
3126		case DTYPE_VNODE:
3127			kif->kf_type = KF_TYPE_VNODE;
3128			vp = fp->f_vnode;
3129			break;
3130
3131		case DTYPE_SOCKET:
3132			kif->kf_type = KF_TYPE_SOCKET;
3133			so = fp->f_data;
3134			break;
3135
3136		case DTYPE_PIPE:
3137			kif->kf_type = KF_TYPE_PIPE;
3138			break;
3139
3140		case DTYPE_FIFO:
3141			kif->kf_type = KF_TYPE_FIFO;
3142			vp = fp->f_vnode;
3143			break;
3144
3145		case DTYPE_KQUEUE:
3146			kif->kf_type = KF_TYPE_KQUEUE;
3147			break;
3148
3149		case DTYPE_CRYPTO:
3150			kif->kf_type = KF_TYPE_CRYPTO;
3151			break;
3152
3153		case DTYPE_MQUEUE:
3154			kif->kf_type = KF_TYPE_MQUEUE;
3155			break;
3156
3157		case DTYPE_SHM:
3158			kif->kf_type = KF_TYPE_SHM;
3159			shmfd = fp->f_data;
3160			break;
3161
3162		case DTYPE_SEM:
3163			kif->kf_type = KF_TYPE_SEM;
3164			ks = fp->f_data;
3165			break;
3166
3167		case DTYPE_PTS:
3168			kif->kf_type = KF_TYPE_PTS;
3169			tp = fp->f_data;
3170			break;
3171
3172#ifdef PROCDESC
3173		case DTYPE_PROCDESC:
3174			kif->kf_type = KF_TYPE_PROCDESC;
3175			break;
3176#endif
3177
3178		default:
3179			kif->kf_type = KF_TYPE_UNKNOWN;
3180			break;
3181		}
3182		kif->kf_ref_count = fp->f_count;
3183		if (fp->f_flag & FREAD)
3184			kif->kf_flags |= KF_FLAG_READ;
3185		if (fp->f_flag & FWRITE)
3186			kif->kf_flags |= KF_FLAG_WRITE;
3187		if (fp->f_flag & FAPPEND)
3188			kif->kf_flags |= KF_FLAG_APPEND;
3189		if (fp->f_flag & FASYNC)
3190			kif->kf_flags |= KF_FLAG_ASYNC;
3191		if (fp->f_flag & FFSYNC)
3192			kif->kf_flags |= KF_FLAG_FSYNC;
3193		if (fp->f_flag & FNONBLOCK)
3194			kif->kf_flags |= KF_FLAG_NONBLOCK;
3195		if (fp->f_flag & O_DIRECT)
3196			kif->kf_flags |= KF_FLAG_DIRECT;
3197		if (fp->f_flag & FHASLOCK)
3198			kif->kf_flags |= KF_FLAG_HASLOCK;
3199		kif->kf_offset = foffset_get(fp);
3200		if (vp != NULL) {
3201			vref(vp);
3202			switch (vp->v_type) {
3203			case VNON:
3204				kif->kf_vnode_type = KF_VTYPE_VNON;
3205				break;
3206			case VREG:
3207				kif->kf_vnode_type = KF_VTYPE_VREG;
3208				break;
3209			case VDIR:
3210				kif->kf_vnode_type = KF_VTYPE_VDIR;
3211				break;
3212			case VBLK:
3213				kif->kf_vnode_type = KF_VTYPE_VBLK;
3214				break;
3215			case VCHR:
3216				kif->kf_vnode_type = KF_VTYPE_VCHR;
3217				break;
3218			case VLNK:
3219				kif->kf_vnode_type = KF_VTYPE_VLNK;
3220				break;
3221			case VSOCK:
3222				kif->kf_vnode_type = KF_VTYPE_VSOCK;
3223				break;
3224			case VFIFO:
3225				kif->kf_vnode_type = KF_VTYPE_VFIFO;
3226				break;
3227			case VBAD:
3228				kif->kf_vnode_type = KF_VTYPE_VBAD;
3229				break;
3230			default:
3231				kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3232				break;
3233			}
3234			/*
3235			 * It is OK to drop the filedesc lock here as we will
3236			 * re-validate and re-evaluate its properties when
3237			 * the loop continues.
3238			 */
3239			freepath = NULL;
3240			fullpath = "-";
3241			FILEDESC_SUNLOCK(fdp);
3242			vn_fullpath(curthread, vp, &fullpath, &freepath);
3243			vrele(vp);
3244			strlcpy(kif->kf_path, fullpath,
3245			    sizeof(kif->kf_path));
3246			if (freepath != NULL)
3247				free(freepath, M_TEMP);
3248			FILEDESC_SLOCK(fdp);
3249		}
3250		if (so != NULL) {
3251			struct sockaddr *sa;
3252
3253			if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3254			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3255				bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3256				free(sa, M_SONAME);
3257			}
3258			if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3259			    == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3260				bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3261				free(sa, M_SONAME);
3262			}
3263			kif->kf_sock_domain =
3264			    so->so_proto->pr_domain->dom_family;
3265			kif->kf_sock_type = so->so_type;
3266			kif->kf_sock_protocol = so->so_proto->pr_protocol;
3267		}
3268		if (tp != NULL) {
3269			strlcpy(kif->kf_path, tty_devname(tp),
3270			    sizeof(kif->kf_path));
3271		}
3272		if (shmfd != NULL)
3273			shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3274		if (ks != NULL && ksem_info != NULL)
3275			ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3276		error = SYSCTL_OUT(req, kif, sizeof(*kif));
3277		if (error)
3278			break;
3279	}
3280	FILEDESC_SUNLOCK(fdp);
3281	fddrop(fdp);
3282	free(kif, M_TEMP);
3283	return (0);
3284}
3285
3286static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3287    CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3288    "Process ofiledesc entries");
3289#endif	/* COMPAT_FREEBSD7 */
3290
3291#ifdef KINFO_FILE_SIZE
3292CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3293#endif
3294
3295struct export_fd_buf {
3296	struct filedesc		*fdp;
3297	struct sbuf 		*sb;
3298	ssize_t			remainder;
3299	struct kinfo_file	kif;
3300};
3301
3302static int
3303export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3304    int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3305{
3306	struct {
3307		int	fflag;
3308		int	kf_fflag;
3309	} fflags_table[] = {
3310		{ FAPPEND, KF_FLAG_APPEND },
3311		{ FASYNC, KF_FLAG_ASYNC },
3312		{ FFSYNC, KF_FLAG_FSYNC },
3313		{ FHASLOCK, KF_FLAG_HASLOCK },
3314		{ FNONBLOCK, KF_FLAG_NONBLOCK },
3315		{ FREAD, KF_FLAG_READ },
3316		{ FWRITE, KF_FLAG_WRITE },
3317		{ O_CREAT, KF_FLAG_CREAT },
3318		{ O_DIRECT, KF_FLAG_DIRECT },
3319		{ O_EXCL, KF_FLAG_EXCL },
3320		{ O_EXEC, KF_FLAG_EXEC },
3321		{ O_EXLOCK, KF_FLAG_EXLOCK },
3322		{ O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3323		{ O_SHLOCK, KF_FLAG_SHLOCK },
3324		{ O_TRUNC, KF_FLAG_TRUNC }
3325	};
3326#define	NFFLAGS	(sizeof(fflags_table) / sizeof(*fflags_table))
3327	struct kinfo_file *kif;
3328	struct vnode *vp;
3329	int error, locked;
3330	unsigned int i;
3331
3332	if (efbuf->remainder == 0)
3333		return (0);
3334	kif = &efbuf->kif;
3335	bzero(kif, sizeof(*kif));
3336	locked = efbuf->fdp != NULL;
3337	switch (type) {
3338	case KF_TYPE_FIFO:
3339	case KF_TYPE_VNODE:
3340		if (locked) {
3341			FILEDESC_SUNLOCK(efbuf->fdp);
3342			locked = 0;
3343		}
3344		vp = (struct vnode *)data;
3345		error = fill_vnode_info(vp, kif);
3346		vrele(vp);
3347		break;
3348	case KF_TYPE_SOCKET:
3349		error = fill_socket_info((struct socket *)data, kif);
3350		break;
3351	case KF_TYPE_PIPE:
3352		error = fill_pipe_info((struct pipe *)data, kif);
3353		break;
3354	case KF_TYPE_PTS:
3355		error = fill_pts_info((struct tty *)data, kif);
3356		break;
3357	case KF_TYPE_PROCDESC:
3358		error = fill_procdesc_info((struct procdesc *)data, kif);
3359		break;
3360	case KF_TYPE_SEM:
3361		error = fill_sem_info((struct file *)data, kif);
3362		break;
3363	case KF_TYPE_SHM:
3364		error = fill_shm_info((struct file *)data, kif);
3365		break;
3366	default:
3367		error = 0;
3368	}
3369	if (error == 0)
3370		kif->kf_status |= KF_ATTR_VALID;
3371
3372	/*
3373	 * Translate file access flags.
3374	 */
3375	for (i = 0; i < NFFLAGS; i++)
3376		if (fflags & fflags_table[i].fflag)
3377			kif->kf_flags |=  fflags_table[i].kf_fflag;
3378	if (rightsp != NULL)
3379		kif->kf_cap_rights = *rightsp;
3380	else
3381		cap_rights_init(&kif->kf_cap_rights);
3382	kif->kf_fd = fd;
3383	kif->kf_type = type;
3384	kif->kf_ref_count = refcnt;
3385	kif->kf_offset = offset;
3386	/* Pack record size down */
3387	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3388	    strlen(kif->kf_path) + 1;
3389	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3390	if (efbuf->remainder != -1) {
3391		if (efbuf->remainder < kif->kf_structsize) {
3392			/* Terminate export. */
3393			efbuf->remainder = 0;
3394			if (efbuf->fdp != NULL && !locked)
3395				FILEDESC_SLOCK(efbuf->fdp);
3396			return (0);
3397		}
3398		efbuf->remainder -= kif->kf_structsize;
3399	}
3400	if (locked)
3401		FILEDESC_SUNLOCK(efbuf->fdp);
3402	error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM;
3403	if (efbuf->fdp != NULL)
3404		FILEDESC_SLOCK(efbuf->fdp);
3405	return (error);
3406}
3407
3408/*
3409 * Store a process file descriptor information to sbuf.
3410 *
3411 * Takes a locked proc as argument, and returns with the proc unlocked.
3412 */
3413int
3414kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
3415{
3416	struct file *fp;
3417	struct filedesc *fdp;
3418	struct export_fd_buf *efbuf;
3419	struct vnode *cttyvp, *textvp, *tracevp;
3420	int64_t offset;
3421	void *data;
3422	int error, i;
3423	int type, refcnt, fflags;
3424	cap_rights_t rights;
3425
3426	PROC_LOCK_ASSERT(p, MA_OWNED);
3427
3428	/* ktrace vnode */
3429	tracevp = p->p_tracevp;
3430	if (tracevp != NULL)
3431		vref(tracevp);
3432	/* text vnode */
3433	textvp = p->p_textvp;
3434	if (textvp != NULL)
3435		vref(textvp);
3436	/* Controlling tty. */
3437	cttyvp = NULL;
3438	if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3439		cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3440		if (cttyvp != NULL)
3441			vref(cttyvp);
3442	}
3443	fdp = fdhold(p);
3444	PROC_UNLOCK(p);
3445	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3446	efbuf->fdp = NULL;
3447	efbuf->sb = sb;
3448	efbuf->remainder = maxlen;
3449	if (tracevp != NULL)
3450		export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3451		    FREAD | FWRITE, -1, -1, NULL, efbuf);
3452	if (textvp != NULL)
3453		export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3454		    FREAD, -1, -1, NULL, efbuf);
3455	if (cttyvp != NULL)
3456		export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3457		    FREAD | FWRITE, -1, -1, NULL, efbuf);
3458	error = 0;
3459	if (fdp == NULL)
3460		goto fail;
3461	efbuf->fdp = fdp;
3462	FILEDESC_SLOCK(fdp);
3463	/* working directory */
3464	if (fdp->fd_cdir != NULL) {
3465		vref(fdp->fd_cdir);
3466		data = fdp->fd_cdir;
3467		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3468		    FREAD, -1, -1, NULL, efbuf);
3469	}
3470	/* root directory */
3471	if (fdp->fd_rdir != NULL) {
3472		vref(fdp->fd_rdir);
3473		data = fdp->fd_rdir;
3474		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3475		    FREAD, -1, -1, NULL, efbuf);
3476	}
3477	/* jail directory */
3478	if (fdp->fd_jdir != NULL) {
3479		vref(fdp->fd_jdir);
3480		data = fdp->fd_jdir;
3481		export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3482		    FREAD, -1, -1, NULL, efbuf);
3483	}
3484	for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3485		if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3486			continue;
3487		data = NULL;
3488#ifdef CAPABILITIES
3489		rights = *cap_rights(fdp, i);
3490#else /* !CAPABILITIES */
3491		cap_rights_init(&rights);
3492#endif
3493		switch (fp->f_type) {
3494		case DTYPE_VNODE:
3495			type = KF_TYPE_VNODE;
3496			vref(fp->f_vnode);
3497			data = fp->f_vnode;
3498			break;
3499
3500		case DTYPE_SOCKET:
3501			type = KF_TYPE_SOCKET;
3502			data = fp->f_data;
3503			break;
3504
3505		case DTYPE_PIPE:
3506			type = KF_TYPE_PIPE;
3507			data = fp->f_data;
3508			break;
3509
3510		case DTYPE_FIFO:
3511			type = KF_TYPE_FIFO;
3512			vref(fp->f_vnode);
3513			data = fp->f_vnode;
3514			break;
3515
3516		case DTYPE_KQUEUE:
3517			type = KF_TYPE_KQUEUE;
3518			break;
3519
3520		case DTYPE_CRYPTO:
3521			type = KF_TYPE_CRYPTO;
3522			break;
3523
3524		case DTYPE_MQUEUE:
3525			type = KF_TYPE_MQUEUE;
3526			break;
3527
3528		case DTYPE_SHM:
3529			type = KF_TYPE_SHM;
3530			data = fp;
3531			break;
3532
3533		case DTYPE_SEM:
3534			type = KF_TYPE_SEM;
3535			data = fp;
3536			break;
3537
3538		case DTYPE_PTS:
3539			type = KF_TYPE_PTS;
3540			data = fp->f_data;
3541			break;
3542
3543#ifdef PROCDESC
3544		case DTYPE_PROCDESC:
3545			type = KF_TYPE_PROCDESC;
3546			data = fp->f_data;
3547			break;
3548#endif
3549
3550		default:
3551			type = KF_TYPE_UNKNOWN;
3552			break;
3553		}
3554		refcnt = fp->f_count;
3555		fflags = fp->f_flag;
3556		offset = foffset_get(fp);
3557
3558		/*
3559		 * Create sysctl entry.
3560		 * It is OK to drop the filedesc lock here as we will
3561		 * re-validate and re-evaluate its properties when
3562		 * the loop continues.
3563		 */
3564		error = export_fd_to_sb(data, type, i, fflags, refcnt,
3565		    offset, &rights, efbuf);
3566		if (error != 0)
3567			break;
3568	}
3569	FILEDESC_SUNLOCK(fdp);
3570	fddrop(fdp);
3571fail:
3572	free(efbuf, M_TEMP);
3573	return (error);
3574}
3575
3576#define FILEDESC_SBUF_SIZE	(sizeof(struct kinfo_file) * 5)
3577
3578/*
3579 * Get per-process file descriptors for use by procstat(1), et al.
3580 */
3581static int
3582sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3583{
3584	struct sbuf sb;
3585	struct proc *p;
3586	ssize_t maxlen;
3587	int error, error2, *name;
3588
3589	name = (int *)arg1;
3590
3591	sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3592	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3593	if (error != 0) {
3594		sbuf_delete(&sb);
3595		return (error);
3596	}
3597	maxlen = req->oldptr != NULL ? req->oldlen : -1;
3598	error = kern_proc_filedesc_out(p, &sb, maxlen);
3599	error2 = sbuf_finish(&sb);
3600	sbuf_delete(&sb);
3601	return (error != 0 ? error : error2);
3602}
3603
3604int
3605vntype_to_kinfo(int vtype)
3606{
3607	struct {
3608		int	vtype;
3609		int	kf_vtype;
3610	} vtypes_table[] = {
3611		{ VBAD, KF_VTYPE_VBAD },
3612		{ VBLK, KF_VTYPE_VBLK },
3613		{ VCHR, KF_VTYPE_VCHR },
3614		{ VDIR, KF_VTYPE_VDIR },
3615		{ VFIFO, KF_VTYPE_VFIFO },
3616		{ VLNK, KF_VTYPE_VLNK },
3617		{ VNON, KF_VTYPE_VNON },
3618		{ VREG, KF_VTYPE_VREG },
3619		{ VSOCK, KF_VTYPE_VSOCK }
3620	};
3621#define	NVTYPES	(sizeof(vtypes_table) / sizeof(*vtypes_table))
3622	unsigned int i;
3623
3624	/*
3625	 * Perform vtype translation.
3626	 */
3627	for (i = 0; i < NVTYPES; i++)
3628		if (vtypes_table[i].vtype == vtype)
3629			break;
3630	if (i < NVTYPES)
3631		return (vtypes_table[i].kf_vtype);
3632
3633	return (KF_VTYPE_UNKNOWN);
3634}
3635
3636static int
3637fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3638{
3639	struct vattr va;
3640	char *fullpath, *freepath;
3641	int error;
3642
3643	if (vp == NULL)
3644		return (1);
3645	kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3646	freepath = NULL;
3647	fullpath = "-";
3648	error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3649	if (error == 0) {
3650		strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3651	}
3652	if (freepath != NULL)
3653		free(freepath, M_TEMP);
3654
3655	/*
3656	 * Retrieve vnode attributes.
3657	 */
3658	va.va_fsid = VNOVAL;
3659	va.va_rdev = NODEV;
3660	vn_lock(vp, LK_SHARED | LK_RETRY);
3661	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3662	VOP_UNLOCK(vp, 0);
3663	if (error != 0)
3664		return (error);
3665	if (va.va_fsid != VNOVAL)
3666		kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3667	else
3668		kif->kf_un.kf_file.kf_file_fsid =
3669		    vp->v_mount->mnt_stat.f_fsid.val[0];
3670	kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3671	kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3672	kif->kf_un.kf_file.kf_file_size = va.va_size;
3673	kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3674	return (0);
3675}
3676
3677static int
3678fill_socket_info(struct socket *so, struct kinfo_file *kif)
3679{
3680	struct sockaddr *sa;
3681	struct inpcb *inpcb;
3682	struct unpcb *unpcb;
3683	int error;
3684
3685	if (so == NULL)
3686		return (1);
3687	kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3688	kif->kf_sock_type = so->so_type;
3689	kif->kf_sock_protocol = so->so_proto->pr_protocol;
3690	kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3691	switch(kif->kf_sock_domain) {
3692	case AF_INET:
3693	case AF_INET6:
3694		if (kif->kf_sock_protocol == IPPROTO_TCP) {
3695			if (so->so_pcb != NULL) {
3696				inpcb = (struct inpcb *)(so->so_pcb);
3697				kif->kf_un.kf_sock.kf_sock_inpcb =
3698				    (uintptr_t)inpcb->inp_ppcb;
3699			}
3700		}
3701		break;
3702	case AF_UNIX:
3703		if (so->so_pcb != NULL) {
3704			unpcb = (struct unpcb *)(so->so_pcb);
3705			if (unpcb->unp_conn) {
3706				kif->kf_un.kf_sock.kf_sock_unpconn =
3707				    (uintptr_t)unpcb->unp_conn;
3708				kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3709				    so->so_rcv.sb_state;
3710				kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3711				    so->so_snd.sb_state;
3712			}
3713		}
3714		break;
3715	}
3716	error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3717	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3718		bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3719		free(sa, M_SONAME);
3720	}
3721	error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3722	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3723		bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3724		free(sa, M_SONAME);
3725	}
3726	strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3727	    sizeof(kif->kf_path));
3728	return (0);
3729}
3730
3731static int
3732fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3733{
3734
3735	if (tp == NULL)
3736		return (1);
3737	kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3738	strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3739	return (0);
3740}
3741
3742static int
3743fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3744{
3745
3746	if (pi == NULL)
3747		return (1);
3748	kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3749	kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3750	kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3751	return (0);
3752}
3753
3754static int
3755fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3756{
3757
3758	if (pdp == NULL)
3759		return (1);
3760	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3761	return (0);
3762}
3763
3764static int
3765fill_sem_info(struct file *fp, struct kinfo_file *kif)
3766{
3767	struct thread *td;
3768	struct stat sb;
3769
3770	td = curthread;
3771	if (fp->f_data == NULL)
3772		return (1);
3773	if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3774		return (1);
3775	if (ksem_info == NULL)
3776		return (1);
3777	ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3778	    &kif->kf_un.kf_sem.kf_sem_value);
3779	kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3780	return (0);
3781}
3782
3783static int
3784fill_shm_info(struct file *fp, struct kinfo_file *kif)
3785{
3786	struct thread *td;
3787	struct stat sb;
3788
3789	td = curthread;
3790	if (fp->f_data == NULL)
3791		return (1);
3792	if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3793		return (1);
3794	shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3795	kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3796	kif->kf_un.kf_file.kf_file_size = sb.st_size;
3797	return (0);
3798}
3799
3800static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3801    CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3802    "Process filedesc entries");
3803
3804#ifdef DDB
3805/*
3806 * For the purposes of debugging, generate a human-readable string for the
3807 * file type.
3808 */
3809static const char *
3810file_type_to_name(short type)
3811{
3812
3813	switch (type) {
3814	case 0:
3815		return ("zero");
3816	case DTYPE_VNODE:
3817		return ("vnod");
3818	case DTYPE_SOCKET:
3819		return ("sock");
3820	case DTYPE_PIPE:
3821		return ("pipe");
3822	case DTYPE_FIFO:
3823		return ("fifo");
3824	case DTYPE_KQUEUE:
3825		return ("kque");
3826	case DTYPE_CRYPTO:
3827		return ("crpt");
3828	case DTYPE_MQUEUE:
3829		return ("mque");
3830	case DTYPE_SHM:
3831		return ("shm");
3832	case DTYPE_SEM:
3833		return ("ksem");
3834	default:
3835		return ("unkn");
3836	}
3837}
3838
3839/*
3840 * For the purposes of debugging, identify a process (if any, perhaps one of
3841 * many) that references the passed file in its file descriptor array. Return
3842 * NULL if none.
3843 */
3844static struct proc *
3845file_to_first_proc(struct file *fp)
3846{
3847	struct filedesc *fdp;
3848	struct proc *p;
3849	int n;
3850
3851	FOREACH_PROC_IN_SYSTEM(p) {
3852		if (p->p_state == PRS_NEW)
3853			continue;
3854		fdp = p->p_fd;
3855		if (fdp == NULL)
3856			continue;
3857		for (n = 0; n <= fdp->fd_lastfile; n++) {
3858			if (fp == fdp->fd_ofiles[n].fde_file)
3859				return (p);
3860		}
3861	}
3862	return (NULL);
3863}
3864
3865static void
3866db_print_file(struct file *fp, int header)
3867{
3868	struct proc *p;
3869
3870	if (header)
3871		db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3872		    "File", "Type", "Data", "Flag", "GCFl", "Count",
3873		    "MCount", "Vnode", "FPID", "FCmd");
3874	p = file_to_first_proc(fp);
3875	db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3876	    file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3877	    0, fp->f_count, 0, fp->f_vnode,
3878	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3879}
3880
3881DB_SHOW_COMMAND(file, db_show_file)
3882{
3883	struct file *fp;
3884
3885	if (!have_addr) {
3886		db_printf("usage: show file <addr>\n");
3887		return;
3888	}
3889	fp = (struct file *)addr;
3890	db_print_file(fp, 1);
3891}
3892
3893DB_SHOW_COMMAND(files, db_show_files)
3894{
3895	struct filedesc *fdp;
3896	struct file *fp;
3897	struct proc *p;
3898	int header;
3899	int n;
3900
3901	header = 1;
3902	FOREACH_PROC_IN_SYSTEM(p) {
3903		if (p->p_state == PRS_NEW)
3904			continue;
3905		if ((fdp = p->p_fd) == NULL)
3906			continue;
3907		for (n = 0; n <= fdp->fd_lastfile; ++n) {
3908			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3909				continue;
3910			db_print_file(fp, header);
3911			header = 0;
3912		}
3913	}
3914}
3915#endif
3916
3917SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3918    &maxfilesperproc, 0, "Maximum files allowed open per process");
3919
3920SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3921    &maxfiles, 0, "Maximum number of files");
3922
3923SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3924    __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3925
3926/* ARGSUSED*/
3927static void
3928filelistinit(void *dummy)
3929{
3930
3931	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3932	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3933	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3934	mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3935}
3936SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3937
3938/*-------------------------------------------------------------------*/
3939
3940static int
3941badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3942    int flags, struct thread *td)
3943{
3944
3945	return (EBADF);
3946}
3947
3948static int
3949badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3950    struct thread *td)
3951{
3952
3953	return (EINVAL);
3954}
3955
3956static int
3957badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3958    struct thread *td)
3959{
3960
3961	return (EBADF);
3962}
3963
3964static int
3965badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3966    struct thread *td)
3967{
3968
3969	return (0);
3970}
3971
3972static int
3973badfo_kqfilter(struct file *fp, struct knote *kn)
3974{
3975
3976	return (EBADF);
3977}
3978
3979static int
3980badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3981    struct thread *td)
3982{
3983
3984	return (EBADF);
3985}
3986
3987static int
3988badfo_close(struct file *fp, struct thread *td)
3989{
3990
3991	return (EBADF);
3992}
3993
3994static int
3995badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3996    struct thread *td)
3997{
3998
3999	return (EBADF);
4000}
4001
4002static int
4003badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4004    struct thread *td)
4005{
4006
4007	return (EBADF);
4008}
4009
4010static int
4011badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4012    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4013    int kflags, struct thread *td)
4014{
4015
4016	return (EBADF);
4017}
4018
4019struct fileops badfileops = {
4020	.fo_read = badfo_readwrite,
4021	.fo_write = badfo_readwrite,
4022	.fo_truncate = badfo_truncate,
4023	.fo_ioctl = badfo_ioctl,
4024	.fo_poll = badfo_poll,
4025	.fo_kqfilter = badfo_kqfilter,
4026	.fo_stat = badfo_stat,
4027	.fo_close = badfo_close,
4028	.fo_chmod = badfo_chmod,
4029	.fo_chown = badfo_chown,
4030	.fo_sendfile = badfo_sendfile,
4031};
4032
4033int
4034invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4035    struct thread *td)
4036{
4037
4038	return (EINVAL);
4039}
4040
4041int
4042invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4043    struct thread *td)
4044{
4045
4046	return (EINVAL);
4047}
4048
4049int
4050invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4051    struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4052    int kflags, struct thread *td)
4053{
4054
4055	return (EINVAL);
4056}
4057
4058/*-------------------------------------------------------------------*/
4059
4060/*
4061 * File Descriptor pseudo-device driver (/dev/fd/).
4062 *
4063 * Opening minor device N dup()s the file (if any) connected to file
4064 * descriptor N belonging to the calling process.  Note that this driver
4065 * consists of only the ``open()'' routine, because all subsequent
4066 * references to this file will be direct to the other driver.
4067 *
4068 * XXX: we could give this one a cloning event handler if necessary.
4069 */
4070
4071/* ARGSUSED */
4072static int
4073fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4074{
4075
4076	/*
4077	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4078	 * the file descriptor being sought for duplication. The error
4079	 * return ensures that the vnode for this device will be released
4080	 * by vn_open. Open will detect this special error and take the
4081	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4082	 * will simply report the error.
4083	 */
4084	td->td_dupfd = dev2unit(dev);
4085	return (ENODEV);
4086}
4087
4088static struct cdevsw fildesc_cdevsw = {
4089	.d_version =	D_VERSION,
4090	.d_open =	fdopen,
4091	.d_name =	"FD",
4092};
4093
4094static void
4095fildesc_drvinit(void *unused)
4096{
4097	struct cdev *dev;
4098
4099	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4100	    UID_ROOT, GID_WHEEL, 0666, "fd/0");
4101	make_dev_alias(dev, "stdin");
4102	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4103	    UID_ROOT, GID_WHEEL, 0666, "fd/1");
4104	make_dev_alias(dev, "stdout");
4105	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4106	    UID_ROOT, GID_WHEEL, 0666, "fd/2");
4107	make_dev_alias(dev, "stderr");
4108}
4109
4110SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
4111