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