xref: /dragonfly/sys/kern/kern_descrip.c (revision 26efd328)
1 /*
2  * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Jeffrey Hsu.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *
35  * Copyright (c) 1982, 1986, 1989, 1991, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  * (c) UNIX System Laboratories, Inc.
38  * All or some portions of this file are derived from material licensed
39  * to the University of California by American Telephone and Telegraph
40  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
41  * the permission of UNIX System Laboratories, Inc.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. Neither the name of the University nor the names of its contributors
52  *    may be used to endorse or promote products derived from this software
53  *    without specific prior written permission.
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65  * SUCH DAMAGE.
66  *
67  *	@(#)kern_descrip.c	8.6 (Berkeley) 4/19/94
68  * $FreeBSD: src/sys/kern/kern_descrip.c,v 1.81.2.19 2004/02/28 00:43:31 tegge Exp $
69  */
70 
71 #include "opt_compat.h"
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/malloc.h>
75 #include <sys/sysproto.h>
76 #include <sys/conf.h>
77 #include <sys/device.h>
78 #include <sys/file.h>
79 #include <sys/filedesc.h>
80 #include <sys/kernel.h>
81 #include <sys/sysctl.h>
82 #include <sys/vnode.h>
83 #include <sys/proc.h>
84 #include <sys/nlookup.h>
85 #include <sys/stat.h>
86 #include <sys/filio.h>
87 #include <sys/fcntl.h>
88 #include <sys/unistd.h>
89 #include <sys/resourcevar.h>
90 #include <sys/event.h>
91 #include <sys/kern_syscall.h>
92 #include <sys/kcore.h>
93 #include <sys/kinfo.h>
94 #include <sys/un.h>
95 
96 #include <vm/vm.h>
97 #include <vm/vm_extern.h>
98 
99 #include <sys/thread2.h>
100 #include <sys/file2.h>
101 #include <sys/spinlock2.h>
102 
103 static void fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd);
104 static void fdreserve_locked (struct filedesc *fdp, int fd0, int incr);
105 static struct file *funsetfd_locked (struct filedesc *fdp, int fd);
106 static void ffree(struct file *fp);
107 
108 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
109 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
110 		     "file desc to leader structures");
111 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
112 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
113 
114 static struct krate krate_uidinfo = { .freq = 1 };
115 
116 static	 d_open_t  fdopen;
117 #define NUMFDESC 64
118 
119 #define CDEV_MAJOR 22
120 static struct dev_ops fildesc_ops = {
121 	{ "FD", 0, 0 },
122 	.d_open =	fdopen,
123 };
124 
125 /*
126  * Descriptor management.
127  */
128 static struct filelist filehead = LIST_HEAD_INITIALIZER(&filehead);
129 static struct spinlock filehead_spin = SPINLOCK_INITIALIZER(&filehead_spin, "filehead_spin");
130 static int nfiles;		/* actual number of open files */
131 extern int cmask;
132 
133 struct lwkt_token revoke_token = LWKT_TOKEN_INITIALIZER(revoke_token);
134 
135 /*
136  * Fixup fd_freefile and fd_lastfile after a descriptor has been cleared.
137  *
138  * must be called with fdp->fd_spin exclusively held
139  */
140 static __inline
141 void
142 fdfixup_locked(struct filedesc *fdp, int fd)
143 {
144 	if (fd < fdp->fd_freefile) {
145 	       fdp->fd_freefile = fd;
146 	}
147 	while (fdp->fd_lastfile >= 0 &&
148 	       fdp->fd_files[fdp->fd_lastfile].fp == NULL &&
149 	       fdp->fd_files[fdp->fd_lastfile].reserved == 0
150 	) {
151 		--fdp->fd_lastfile;
152 	}
153 }
154 
155 /*
156  * System calls on descriptors.
157  */
158 int
159 sys_getdtablesize(struct getdtablesize_args *uap)
160 {
161 	struct proc *p = curproc;
162 	struct plimit *limit = p->p_limit;
163 	int dtsize;
164 
165 	spin_lock(&limit->p_spin);
166 	if (limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur > INT_MAX)
167 		dtsize = INT_MAX;
168 	else
169 		dtsize = (int)limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur;
170 	spin_unlock(&limit->p_spin);
171 
172 	if (dtsize > maxfilesperproc)
173 		dtsize = maxfilesperproc;
174 	if (dtsize < minfilesperproc)
175 		dtsize = minfilesperproc;
176 	if (p->p_ucred->cr_uid && dtsize > maxfilesperuser)
177 		dtsize = maxfilesperuser;
178 	uap->sysmsg_result = dtsize;
179 	return (0);
180 }
181 
182 /*
183  * Duplicate a file descriptor to a particular value.
184  *
185  * note: keep in mind that a potential race condition exists when closing
186  * descriptors from a shared descriptor table (via rfork).
187  */
188 int
189 sys_dup2(struct dup2_args *uap)
190 {
191 	int error;
192 	int fd = 0;
193 
194 	error = kern_dup(DUP_FIXED, uap->from, uap->to, &fd);
195 	uap->sysmsg_fds[0] = fd;
196 
197 	return (error);
198 }
199 
200 /*
201  * Duplicate a file descriptor.
202  */
203 int
204 sys_dup(struct dup_args *uap)
205 {
206 	int error;
207 	int fd = 0;
208 
209 	error = kern_dup(DUP_VARIABLE, uap->fd, 0, &fd);
210 	uap->sysmsg_fds[0] = fd;
211 
212 	return (error);
213 }
214 
215 /*
216  * MPALMOSTSAFE - acquires mplock for fp operations
217  */
218 int
219 kern_fcntl(int fd, int cmd, union fcntl_dat *dat, struct ucred *cred)
220 {
221 	struct thread *td = curthread;
222 	struct proc *p = td->td_proc;
223 	struct file *fp;
224 	struct vnode *vp;
225 	u_int newmin;
226 	u_int oflags;
227 	u_int nflags;
228 	int tmp, error, flg = F_POSIX;
229 
230 	KKASSERT(p);
231 
232 	/*
233 	 * Operations on file descriptors that do not require a file pointer.
234 	 */
235 	switch (cmd) {
236 	case F_GETFD:
237 		error = fgetfdflags(p->p_fd, fd, &tmp);
238 		if (error == 0)
239 			dat->fc_cloexec = (tmp & UF_EXCLOSE) ? FD_CLOEXEC : 0;
240 		return (error);
241 
242 	case F_SETFD:
243 		if (dat->fc_cloexec & FD_CLOEXEC)
244 			error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
245 		else
246 			error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
247 		return (error);
248 	case F_DUPFD:
249 		newmin = dat->fc_fd;
250 		error = kern_dup(DUP_VARIABLE | DUP_FCNTL, fd, newmin,
251 		    &dat->fc_fd);
252 		return (error);
253 	case F_DUPFD_CLOEXEC:
254 		newmin = dat->fc_fd;
255 		error = kern_dup(DUP_VARIABLE | DUP_CLOEXEC | DUP_FCNTL,
256 		    fd, newmin, &dat->fc_fd);
257 		return (error);
258 	case F_DUP2FD:
259 		newmin = dat->fc_fd;
260 		error = kern_dup(DUP_FIXED, fd, newmin, &dat->fc_fd);
261 		return (error);
262 	case F_DUP2FD_CLOEXEC:
263 		newmin = dat->fc_fd;
264 		error = kern_dup(DUP_FIXED | DUP_CLOEXEC, fd, newmin,
265 				 &dat->fc_fd);
266 		return (error);
267 	default:
268 		break;
269 	}
270 
271 	/*
272 	 * Operations on file pointers
273 	 */
274 	if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
275 		return (EBADF);
276 
277 	switch (cmd) {
278 	case F_GETFL:
279 		dat->fc_flags = OFLAGS(fp->f_flag);
280 		error = 0;
281 		break;
282 
283 	case F_SETFL:
284 		oflags = fp->f_flag;
285 		nflags = FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
286 		nflags |= oflags & ~FCNTLFLAGS;
287 
288 		error = 0;
289 		if (((nflags ^ oflags) & O_APPEND) && (oflags & FAPPENDONLY))
290 			error = EINVAL;
291 		if (error == 0 && ((nflags ^ oflags) & FASYNC)) {
292 			tmp = nflags & FASYNC;
293 			error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp,
294 					 cred, NULL);
295 		}
296 
297 		/*
298 		 * If no error, must be atomically set.
299 		 */
300 		while (error == 0) {
301 			oflags = fp->f_flag;
302 			cpu_ccfence();
303 			nflags = (oflags & ~FCNTLFLAGS) | (nflags & FCNTLFLAGS);
304 			if (atomic_cmpset_int(&fp->f_flag, oflags, nflags))
305 				break;
306 			cpu_pause();
307 		}
308 		break;
309 
310 	case F_GETOWN:
311 		error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner,
312 				 cred, NULL);
313 		break;
314 
315 	case F_SETOWN:
316 		error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner,
317 				 cred, NULL);
318 		break;
319 
320 	case F_SETLKW:
321 		flg |= F_WAIT;
322 		/* Fall into F_SETLK */
323 
324 	case F_SETLK:
325 		if (fp->f_type != DTYPE_VNODE) {
326 			error = EBADF;
327 			break;
328 		}
329 		vp = (struct vnode *)fp->f_data;
330 
331 		/*
332 		 * copyin/lockop may block
333 		 */
334 		if (dat->fc_flock.l_whence == SEEK_CUR)
335 			dat->fc_flock.l_start += fp->f_offset;
336 
337 		switch (dat->fc_flock.l_type) {
338 		case F_RDLCK:
339 			if ((fp->f_flag & FREAD) == 0) {
340 				error = EBADF;
341 				break;
342 			}
343 			if ((p->p_leader->p_flags & P_ADVLOCK) == 0) {
344 				lwkt_gettoken(&p->p_leader->p_token);
345 				p->p_leader->p_flags |= P_ADVLOCK;
346 				lwkt_reltoken(&p->p_leader->p_token);
347 			}
348 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
349 			    &dat->fc_flock, flg);
350 			break;
351 		case F_WRLCK:
352 			if ((fp->f_flag & FWRITE) == 0) {
353 				error = EBADF;
354 				break;
355 			}
356 			if ((p->p_leader->p_flags & P_ADVLOCK) == 0) {
357 				lwkt_gettoken(&p->p_leader->p_token);
358 				p->p_leader->p_flags |= P_ADVLOCK;
359 				lwkt_reltoken(&p->p_leader->p_token);
360 			}
361 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
362 			    &dat->fc_flock, flg);
363 			break;
364 		case F_UNLCK:
365 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
366 				&dat->fc_flock, F_POSIX);
367 			break;
368 		default:
369 			error = EINVAL;
370 			break;
371 		}
372 
373 		/*
374 		 * It is possible to race a close() on the descriptor while
375 		 * we were blocked getting the lock.  If this occurs the
376 		 * close might not have caught the lock.
377 		 */
378 		if (checkfdclosed(p->p_fd, fd, fp)) {
379 			dat->fc_flock.l_whence = SEEK_SET;
380 			dat->fc_flock.l_start = 0;
381 			dat->fc_flock.l_len = 0;
382 			dat->fc_flock.l_type = F_UNLCK;
383 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
384 					   F_UNLCK, &dat->fc_flock, F_POSIX);
385 		}
386 		break;
387 
388 	case F_GETLK:
389 		if (fp->f_type != DTYPE_VNODE) {
390 			error = EBADF;
391 			break;
392 		}
393 		vp = (struct vnode *)fp->f_data;
394 		/*
395 		 * copyin/lockop may block
396 		 */
397 		if (dat->fc_flock.l_type != F_RDLCK &&
398 		    dat->fc_flock.l_type != F_WRLCK &&
399 		    dat->fc_flock.l_type != F_UNLCK) {
400 			error = EINVAL;
401 			break;
402 		}
403 		if (dat->fc_flock.l_whence == SEEK_CUR)
404 			dat->fc_flock.l_start += fp->f_offset;
405 		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
406 			    &dat->fc_flock, F_POSIX);
407 		break;
408 	default:
409 		error = EINVAL;
410 		break;
411 	}
412 
413 	fdrop(fp);
414 	return (error);
415 }
416 
417 /*
418  * The file control system call.
419  */
420 int
421 sys_fcntl(struct fcntl_args *uap)
422 {
423 	union fcntl_dat dat;
424 	int error;
425 
426 	switch (uap->cmd) {
427 	case F_DUPFD:
428 	case F_DUP2FD:
429 	case F_DUPFD_CLOEXEC:
430 	case F_DUP2FD_CLOEXEC:
431 		dat.fc_fd = uap->arg;
432 		break;
433 	case F_SETFD:
434 		dat.fc_cloexec = uap->arg;
435 		break;
436 	case F_SETFL:
437 		dat.fc_flags = uap->arg;
438 		break;
439 	case F_SETOWN:
440 		dat.fc_owner = uap->arg;
441 		break;
442 	case F_SETLKW:
443 	case F_SETLK:
444 	case F_GETLK:
445 		error = copyin((caddr_t)uap->arg, &dat.fc_flock,
446 			       sizeof(struct flock));
447 		if (error)
448 			return (error);
449 		break;
450 	}
451 
452 	error = kern_fcntl(uap->fd, uap->cmd, &dat, curthread->td_ucred);
453 
454 	if (error == 0) {
455 		switch (uap->cmd) {
456 		case F_DUPFD:
457 		case F_DUP2FD:
458 		case F_DUPFD_CLOEXEC:
459 		case F_DUP2FD_CLOEXEC:
460 			uap->sysmsg_result = dat.fc_fd;
461 			break;
462 		case F_GETFD:
463 			uap->sysmsg_result = dat.fc_cloexec;
464 			break;
465 		case F_GETFL:
466 			uap->sysmsg_result = dat.fc_flags;
467 			break;
468 		case F_GETOWN:
469 			uap->sysmsg_result = dat.fc_owner;
470 			break;
471 		case F_GETLK:
472 			error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
473 			    sizeof(struct flock));
474 			break;
475 		}
476 	}
477 
478 	return (error);
479 }
480 
481 /*
482  * Common code for dup, dup2, and fcntl(F_DUPFD).
483  *
484  * There are four type flags: DUP_FCNTL, DUP_FIXED, DUP_VARIABLE, and
485  * DUP_CLOEXEC.
486  *
487  * DUP_FCNTL is for handling EINVAL vs. EBADF differences between
488  * fcntl()'s F_DUPFD and F_DUPFD_CLOEXEC and dup2() (per POSIX).
489  * The next two flags are mutually exclusive, and the fourth is optional.
490  * DUP_FIXED tells kern_dup() to destructively dup over an existing file
491  * descriptor if "new" is already open.  DUP_VARIABLE tells kern_dup()
492  * to find the lowest unused file descriptor that is greater than or
493  * equal to "new".  DUP_CLOEXEC, which works with either of the first
494  * two flags, sets the close-on-exec flag on the "new" file descriptor.
495  */
496 int
497 kern_dup(int flags, int old, int new, int *res)
498 {
499 	struct thread *td = curthread;
500 	struct proc *p = td->td_proc;
501 	struct filedesc *fdp = p->p_fd;
502 	struct file *fp;
503 	struct file *delfp;
504 	int oldflags;
505 	int holdleaders;
506 	int dtsize;
507 	int error, newfd;
508 
509 	/*
510 	 * Verify that we have a valid descriptor to dup from and
511 	 * possibly to dup to. When the new descriptor is out of
512 	 * bounds, fcntl()'s F_DUPFD and F_DUPFD_CLOEXEC must
513 	 * return EINVAL, while dup2() returns EBADF in
514 	 * this case.
515 	 *
516 	 * NOTE: maxfilesperuser is not applicable to dup()
517 	 */
518 retry:
519 	if (p->p_rlimit[RLIMIT_NOFILE].rlim_cur > INT_MAX)
520 		dtsize = INT_MAX;
521 	else
522 		dtsize = (int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur;
523 	if (dtsize > maxfilesperproc)
524 		dtsize = maxfilesperproc;
525 	if (dtsize < minfilesperproc)
526 		dtsize = minfilesperproc;
527 
528 	if (new < 0 || new > dtsize)
529 		return (flags & DUP_FCNTL ? EINVAL : EBADF);
530 
531 	spin_lock(&fdp->fd_spin);
532 	if ((unsigned)old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL) {
533 		spin_unlock(&fdp->fd_spin);
534 		return (EBADF);
535 	}
536 	if ((flags & DUP_FIXED) && old == new) {
537 		*res = new;
538 		if (flags & DUP_CLOEXEC)
539 			fdp->fd_files[new].fileflags |= UF_EXCLOSE;
540 		spin_unlock(&fdp->fd_spin);
541 		return (0);
542 	}
543 	fp = fdp->fd_files[old].fp;
544 	oldflags = fdp->fd_files[old].fileflags;
545 	fhold(fp);
546 
547 	/*
548 	 * Allocate a new descriptor if DUP_VARIABLE, or expand the table
549 	 * if the requested descriptor is beyond the current table size.
550 	 *
551 	 * This can block.  Retry if the source descriptor no longer matches
552 	 * or if our expectation in the expansion case races.
553 	 *
554 	 * If we are not expanding or allocating a new decriptor, then reset
555 	 * the target descriptor to a reserved state so we have a uniform
556 	 * setup for the next code block.
557 	 */
558 	if ((flags & DUP_VARIABLE) || new >= fdp->fd_nfiles) {
559 		spin_unlock(&fdp->fd_spin);
560 		error = fdalloc(p, new, &newfd);
561 		spin_lock(&fdp->fd_spin);
562 		if (error) {
563 			spin_unlock(&fdp->fd_spin);
564 			fdrop(fp);
565 			return (error);
566 		}
567 		/*
568 		 * Check for ripout
569 		 */
570 		if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp != fp) {
571 			fsetfd_locked(fdp, NULL, newfd);
572 			spin_unlock(&fdp->fd_spin);
573 			fdrop(fp);
574 			goto retry;
575 		}
576 		/*
577 		 * Check for expansion race
578 		 */
579 		if ((flags & DUP_VARIABLE) == 0 && new != newfd) {
580 			fsetfd_locked(fdp, NULL, newfd);
581 			spin_unlock(&fdp->fd_spin);
582 			fdrop(fp);
583 			goto retry;
584 		}
585 		/*
586 		 * Check for ripout, newfd reused old (this case probably
587 		 * can't occur).
588 		 */
589 		if (old == newfd) {
590 			fsetfd_locked(fdp, NULL, newfd);
591 			spin_unlock(&fdp->fd_spin);
592 			fdrop(fp);
593 			goto retry;
594 		}
595 		new = newfd;
596 		delfp = NULL;
597 	} else {
598 		if (fdp->fd_files[new].reserved) {
599 			spin_unlock(&fdp->fd_spin);
600 			fdrop(fp);
601 			kprintf("Warning: dup(): target descriptor %d is reserved, waiting for it to be resolved\n", new);
602 			tsleep(fdp, 0, "fdres", hz);
603 			goto retry;
604 		}
605 
606 		/*
607 		 * If the target descriptor was never allocated we have
608 		 * to allocate it.  If it was we have to clean out the
609 		 * old descriptor.  delfp inherits the ref from the
610 		 * descriptor table.
611 		 */
612 		delfp = fdp->fd_files[new].fp;
613 		fdp->fd_files[new].fp = NULL;
614 		fdp->fd_files[new].reserved = 1;
615 		if (delfp == NULL) {
616 			fdreserve_locked(fdp, new, 1);
617 			if (new > fdp->fd_lastfile)
618 				fdp->fd_lastfile = new;
619 		}
620 
621 	}
622 
623 	/*
624 	 * NOTE: still holding an exclusive spinlock
625 	 */
626 
627 	/*
628 	 * If a descriptor is being overwritten we may hve to tell
629 	 * fdfree() to sleep to ensure that all relevant process
630 	 * leaders can be traversed in closef().
631 	 */
632 	if (delfp != NULL && p->p_fdtol != NULL) {
633 		fdp->fd_holdleaderscount++;
634 		holdleaders = 1;
635 	} else {
636 		holdleaders = 0;
637 	}
638 	KASSERT(delfp == NULL || (flags & DUP_FIXED),
639 		("dup() picked an open file"));
640 
641 	/*
642 	 * Duplicate the source descriptor, update lastfile.  If the new
643 	 * descriptor was not allocated and we aren't replacing an existing
644 	 * descriptor we have to mark the descriptor as being in use.
645 	 *
646 	 * The fd_files[] array inherits fp's hold reference.
647 	 */
648 	fsetfd_locked(fdp, fp, new);
649 	if ((flags & DUP_CLOEXEC) != 0)
650 		fdp->fd_files[new].fileflags = oldflags | UF_EXCLOSE;
651 	else
652 		fdp->fd_files[new].fileflags = oldflags & ~UF_EXCLOSE;
653 	spin_unlock(&fdp->fd_spin);
654 	fdrop(fp);
655 	*res = new;
656 
657 	/*
658 	 * If we dup'd over a valid file, we now own the reference to it
659 	 * and must dispose of it using closef() semantics (as if a
660 	 * close() were performed on it).
661 	 */
662 	if (delfp) {
663 		if (SLIST_FIRST(&delfp->f_klist))
664 			knote_fdclose(delfp, fdp, new);
665 		closef(delfp, p);
666 		if (holdleaders) {
667 			spin_lock(&fdp->fd_spin);
668 			fdp->fd_holdleaderscount--;
669 			if (fdp->fd_holdleaderscount == 0 &&
670 			    fdp->fd_holdleaderswakeup != 0) {
671 				fdp->fd_holdleaderswakeup = 0;
672 				spin_unlock(&fdp->fd_spin);
673 				wakeup(&fdp->fd_holdleaderscount);
674 			} else {
675 				spin_unlock(&fdp->fd_spin);
676 			}
677 		}
678 	}
679 	return (0);
680 }
681 
682 /*
683  * If sigio is on the list associated with a process or process group,
684  * disable signalling from the device, remove sigio from the list and
685  * free sigio.
686  */
687 void
688 funsetown(struct sigio **sigiop)
689 {
690 	struct pgrp *pgrp;
691 	struct proc *p;
692 	struct sigio *sigio;
693 
694 	if ((sigio = *sigiop) != NULL) {
695 		lwkt_gettoken(&sigio_token);	/* protect sigio */
696 		KKASSERT(sigiop == sigio->sio_myref);
697 		sigio = *sigiop;
698 		*sigiop = NULL;
699 		lwkt_reltoken(&sigio_token);
700 	}
701 	if (sigio == NULL)
702 		return;
703 
704 	if (sigio->sio_pgid < 0) {
705 		pgrp = sigio->sio_pgrp;
706 		sigio->sio_pgrp = NULL;
707 		lwkt_gettoken(&pgrp->pg_token);
708 		SLIST_REMOVE(&pgrp->pg_sigiolst, sigio, sigio, sio_pgsigio);
709 		lwkt_reltoken(&pgrp->pg_token);
710 		pgrel(pgrp);
711 	} else /* if ((*sigiop)->sio_pgid > 0) */ {
712 		p = sigio->sio_proc;
713 		sigio->sio_proc = NULL;
714 		PHOLD(p);
715 		lwkt_gettoken(&p->p_token);
716 		SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, sio_pgsigio);
717 		lwkt_reltoken(&p->p_token);
718 		PRELE(p);
719 	}
720 	crfree(sigio->sio_ucred);
721 	sigio->sio_ucred = NULL;
722 	kfree(sigio, M_SIGIO);
723 }
724 
725 /*
726  * Free a list of sigio structures.  Caller is responsible for ensuring
727  * that the list is MPSAFE.
728  */
729 void
730 funsetownlst(struct sigiolst *sigiolst)
731 {
732 	struct sigio *sigio;
733 
734 	while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
735 		funsetown(sigio->sio_myref);
736 }
737 
738 /*
739  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
740  *
741  * After permission checking, add a sigio structure to the sigio list for
742  * the process or process group.
743  */
744 int
745 fsetown(pid_t pgid, struct sigio **sigiop)
746 {
747 	struct proc *proc = NULL;
748 	struct pgrp *pgrp = NULL;
749 	struct sigio *sigio;
750 	int error;
751 
752 	if (pgid == 0) {
753 		funsetown(sigiop);
754 		return (0);
755 	}
756 
757 	if (pgid > 0) {
758 		proc = pfind(pgid);
759 		if (proc == NULL) {
760 			error = ESRCH;
761 			goto done;
762 		}
763 
764 		/*
765 		 * Policy - Don't allow a process to FSETOWN a process
766 		 * in another session.
767 		 *
768 		 * Remove this test to allow maximum flexibility or
769 		 * restrict FSETOWN to the current process or process
770 		 * group for maximum safety.
771 		 */
772 		if (proc->p_session != curproc->p_session) {
773 			error = EPERM;
774 			goto done;
775 		}
776 	} else /* if (pgid < 0) */ {
777 		pgrp = pgfind(-pgid);
778 		if (pgrp == NULL) {
779 			error = ESRCH;
780 			goto done;
781 		}
782 
783 		/*
784 		 * Policy - Don't allow a process to FSETOWN a process
785 		 * in another session.
786 		 *
787 		 * Remove this test to allow maximum flexibility or
788 		 * restrict FSETOWN to the current process or process
789 		 * group for maximum safety.
790 		 */
791 		if (pgrp->pg_session != curproc->p_session) {
792 			error = EPERM;
793 			goto done;
794 		}
795 	}
796 	sigio = kmalloc(sizeof(struct sigio), M_SIGIO, M_WAITOK | M_ZERO);
797 	if (pgid > 0) {
798 		KKASSERT(pgrp == NULL);
799 		lwkt_gettoken(&proc->p_token);
800 		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
801 		sigio->sio_proc = proc;
802 		lwkt_reltoken(&proc->p_token);
803 	} else {
804 		KKASSERT(proc == NULL);
805 		lwkt_gettoken(&pgrp->pg_token);
806 		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
807 		sigio->sio_pgrp = pgrp;
808 		lwkt_reltoken(&pgrp->pg_token);
809 		pgrp = NULL;
810 	}
811 	sigio->sio_pgid = pgid;
812 	sigio->sio_ucred = crhold(curthread->td_ucred);
813 	/* It would be convenient if p_ruid was in ucred. */
814 	sigio->sio_ruid = sigio->sio_ucred->cr_ruid;
815 	sigio->sio_myref = sigiop;
816 
817 	lwkt_gettoken(&sigio_token);
818 	while (*sigiop)
819 		funsetown(sigiop);
820 	*sigiop = sigio;
821 	lwkt_reltoken(&sigio_token);
822 	error = 0;
823 done:
824 	if (pgrp)
825 		pgrel(pgrp);
826 	if (proc)
827 		PRELE(proc);
828 	return (error);
829 }
830 
831 /*
832  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
833  */
834 pid_t
835 fgetown(struct sigio **sigiop)
836 {
837 	struct sigio *sigio;
838 	pid_t own;
839 
840 	lwkt_gettoken_shared(&sigio_token);
841 	sigio = *sigiop;
842 	own = (sigio != NULL ? sigio->sio_pgid : 0);
843 	lwkt_reltoken(&sigio_token);
844 
845 	return (own);
846 }
847 
848 /*
849  * Close many file descriptors.
850  */
851 int
852 sys_closefrom(struct closefrom_args *uap)
853 {
854 	return(kern_closefrom(uap->fd));
855 }
856 
857 /*
858  * Close all file descriptors greater then or equal to fd
859  */
860 int
861 kern_closefrom(int fd)
862 {
863 	struct thread *td = curthread;
864 	struct proc *p = td->td_proc;
865 	struct filedesc *fdp;
866 
867 	KKASSERT(p);
868 	fdp = p->p_fd;
869 
870 	if (fd < 0)
871 		return (EINVAL);
872 
873 	/*
874 	 * NOTE: This function will skip unassociated descriptors and
875 	 * reserved descriptors that have not yet been assigned.
876 	 * fd_lastfile can change as a side effect of kern_close().
877 	 */
878 	spin_lock(&fdp->fd_spin);
879 	while (fd <= fdp->fd_lastfile) {
880 		if (fdp->fd_files[fd].fp != NULL) {
881 			spin_unlock(&fdp->fd_spin);
882 			/* ok if this races another close */
883 			if (kern_close(fd) == EINTR)
884 				return (EINTR);
885 			spin_lock(&fdp->fd_spin);
886 		}
887 		++fd;
888 	}
889 	spin_unlock(&fdp->fd_spin);
890 	return (0);
891 }
892 
893 /*
894  * Close a file descriptor.
895  */
896 int
897 sys_close(struct close_args *uap)
898 {
899 	return(kern_close(uap->fd));
900 }
901 
902 /*
903  * close() helper
904  */
905 int
906 kern_close(int fd)
907 {
908 	struct thread *td = curthread;
909 	struct proc *p = td->td_proc;
910 	struct filedesc *fdp;
911 	struct file *fp;
912 	int error;
913 	int holdleaders;
914 
915 	KKASSERT(p);
916 	fdp = p->p_fd;
917 
918 	spin_lock(&fdp->fd_spin);
919 	if ((fp = funsetfd_locked(fdp, fd)) == NULL) {
920 		spin_unlock(&fdp->fd_spin);
921 		return (EBADF);
922 	}
923 	holdleaders = 0;
924 	if (p->p_fdtol != NULL) {
925 		/*
926 		 * Ask fdfree() to sleep to ensure that all relevant
927 		 * process leaders can be traversed in closef().
928 		 */
929 		fdp->fd_holdleaderscount++;
930 		holdleaders = 1;
931 	}
932 
933 	/*
934 	 * we now hold the fp reference that used to be owned by the descriptor
935 	 * array.
936 	 */
937 	spin_unlock(&fdp->fd_spin);
938 	if (SLIST_FIRST(&fp->f_klist))
939 		knote_fdclose(fp, fdp, fd);
940 	error = closef(fp, p);
941 	if (holdleaders) {
942 		spin_lock(&fdp->fd_spin);
943 		fdp->fd_holdleaderscount--;
944 		if (fdp->fd_holdleaderscount == 0 &&
945 		    fdp->fd_holdleaderswakeup != 0) {
946 			fdp->fd_holdleaderswakeup = 0;
947 			spin_unlock(&fdp->fd_spin);
948 			wakeup(&fdp->fd_holdleaderscount);
949 		} else {
950 			spin_unlock(&fdp->fd_spin);
951 		}
952 	}
953 	return (error);
954 }
955 
956 /*
957  * shutdown_args(int fd, int how)
958  */
959 int
960 kern_shutdown(int fd, int how)
961 {
962 	struct thread *td = curthread;
963 	struct proc *p = td->td_proc;
964 	struct file *fp;
965 	int error;
966 
967 	KKASSERT(p);
968 
969 	if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
970 		return (EBADF);
971 	error = fo_shutdown(fp, how);
972 	fdrop(fp);
973 
974 	return (error);
975 }
976 
977 /*
978  * MPALMOSTSAFE
979  */
980 int
981 sys_shutdown(struct shutdown_args *uap)
982 {
983 	int error;
984 
985 	error = kern_shutdown(uap->s, uap->how);
986 
987 	return (error);
988 }
989 
990 /*
991  * fstat() helper
992  */
993 int
994 kern_fstat(int fd, struct stat *ub)
995 {
996 	struct thread *td = curthread;
997 	struct proc *p = td->td_proc;
998 	struct file *fp;
999 	int error;
1000 
1001 	KKASSERT(p);
1002 
1003 	if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
1004 		return (EBADF);
1005 	error = fo_stat(fp, ub, td->td_ucred);
1006 	fdrop(fp);
1007 
1008 	return (error);
1009 }
1010 
1011 /*
1012  * Return status information about a file descriptor.
1013  */
1014 int
1015 sys_fstat(struct fstat_args *uap)
1016 {
1017 	struct stat st;
1018 	int error;
1019 
1020 	error = kern_fstat(uap->fd, &st);
1021 
1022 	if (error == 0)
1023 		error = copyout(&st, uap->sb, sizeof(st));
1024 	return (error);
1025 }
1026 
1027 /*
1028  * Return pathconf information about a file descriptor.
1029  *
1030  * MPALMOSTSAFE
1031  */
1032 int
1033 sys_fpathconf(struct fpathconf_args *uap)
1034 {
1035 	struct thread *td = curthread;
1036 	struct proc *p = td->td_proc;
1037 	struct file *fp;
1038 	struct vnode *vp;
1039 	int error = 0;
1040 
1041 	if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
1042 		return (EBADF);
1043 
1044 	switch (fp->f_type) {
1045 	case DTYPE_PIPE:
1046 	case DTYPE_SOCKET:
1047 		if (uap->name != _PC_PIPE_BUF) {
1048 			error = EINVAL;
1049 		} else {
1050 			uap->sysmsg_result = PIPE_BUF;
1051 			error = 0;
1052 		}
1053 		break;
1054 	case DTYPE_FIFO:
1055 	case DTYPE_VNODE:
1056 		vp = (struct vnode *)fp->f_data;
1057 		error = VOP_PATHCONF(vp, uap->name, &uap->sysmsg_reg);
1058 		break;
1059 	default:
1060 		error = EOPNOTSUPP;
1061 		break;
1062 	}
1063 	fdrop(fp);
1064 	return(error);
1065 }
1066 
1067 static int fdexpand;
1068 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0,
1069     "Number of times a file table has been expanded");
1070 
1071 /*
1072  * Grow the file table so it can hold through descriptor (want).
1073  *
1074  * The fdp's spinlock must be held exclusively on entry and may be held
1075  * exclusively on return.  The spinlock may be cycled by the routine.
1076  */
1077 static void
1078 fdgrow_locked(struct filedesc *fdp, int want)
1079 {
1080 	struct fdnode *newfiles;
1081 	struct fdnode *oldfiles;
1082 	int nf, extra;
1083 
1084 	nf = fdp->fd_nfiles;
1085 	do {
1086 		/* nf has to be of the form 2^n - 1 */
1087 		nf = 2 * nf + 1;
1088 	} while (nf <= want);
1089 
1090 	spin_unlock(&fdp->fd_spin);
1091 	newfiles = kmalloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
1092 	spin_lock(&fdp->fd_spin);
1093 
1094 	/*
1095 	 * We could have raced another extend while we were not holding
1096 	 * the spinlock.
1097 	 */
1098 	if (fdp->fd_nfiles >= nf) {
1099 		spin_unlock(&fdp->fd_spin);
1100 		kfree(newfiles, M_FILEDESC);
1101 		spin_lock(&fdp->fd_spin);
1102 		return;
1103 	}
1104 	/*
1105 	 * Copy the existing ofile and ofileflags arrays
1106 	 * and zero the new portion of each array.
1107 	 */
1108 	extra = nf - fdp->fd_nfiles;
1109 	bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
1110 	bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
1111 
1112 	oldfiles = fdp->fd_files;
1113 	fdp->fd_files = newfiles;
1114 	fdp->fd_nfiles = nf;
1115 
1116 	if (oldfiles != fdp->fd_builtin_files) {
1117 		spin_unlock(&fdp->fd_spin);
1118 		kfree(oldfiles, M_FILEDESC);
1119 		spin_lock(&fdp->fd_spin);
1120 	}
1121 	fdexpand++;
1122 }
1123 
1124 /*
1125  * Number of nodes in right subtree, including the root.
1126  */
1127 static __inline int
1128 right_subtree_size(int n)
1129 {
1130 	return (n ^ (n | (n + 1)));
1131 }
1132 
1133 /*
1134  * Bigger ancestor.
1135  */
1136 static __inline int
1137 right_ancestor(int n)
1138 {
1139 	return (n | (n + 1));
1140 }
1141 
1142 /*
1143  * Smaller ancestor.
1144  */
1145 static __inline int
1146 left_ancestor(int n)
1147 {
1148 	return ((n & (n + 1)) - 1);
1149 }
1150 
1151 /*
1152  * Traverse the in-place binary tree buttom-up adjusting the allocation
1153  * count so scans can determine where free descriptors are located.
1154  *
1155  * caller must be holding an exclusive spinlock on fdp
1156  */
1157 static
1158 void
1159 fdreserve_locked(struct filedesc *fdp, int fd, int incr)
1160 {
1161 	while (fd >= 0) {
1162 		fdp->fd_files[fd].allocated += incr;
1163 		KKASSERT(fdp->fd_files[fd].allocated >= 0);
1164 		fd = left_ancestor(fd);
1165 	}
1166 }
1167 
1168 /*
1169  * Reserve a file descriptor for the process.  If no error occurs, the
1170  * caller MUST at some point call fsetfd() or assign a file pointer
1171  * or dispose of the reservation.
1172  */
1173 int
1174 fdalloc(struct proc *p, int want, int *result)
1175 {
1176 	struct filedesc *fdp = p->p_fd;
1177 	struct uidinfo *uip;
1178 	int fd, rsize, rsum, node, lim;
1179 
1180 	/*
1181 	 * Check dtable size limit
1182 	 */
1183 	spin_lock(&p->p_limit->p_spin);
1184 	if (p->p_rlimit[RLIMIT_NOFILE].rlim_cur > INT_MAX)
1185 		lim = INT_MAX;
1186 	else
1187 		lim = (int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur;
1188 	spin_unlock(&p->p_limit->p_spin);
1189 
1190 	if (lim > maxfilesperproc)
1191 		lim = maxfilesperproc;
1192 	if (lim < minfilesperproc)
1193 		lim = minfilesperproc;
1194 	if (want >= lim)
1195 		return (EMFILE);
1196 
1197 	/*
1198 	 * Check that the user has not run out of descriptors (non-root only).
1199 	 * As a safety measure the dtable is allowed to have at least
1200 	 * minfilesperproc open fds regardless of the maxfilesperuser limit.
1201 	 */
1202 	if (p->p_ucred->cr_uid && fdp->fd_nfiles >= minfilesperproc) {
1203 		uip = p->p_ucred->cr_uidinfo;
1204 		if (uip->ui_openfiles > maxfilesperuser) {
1205 			krateprintf(&krate_uidinfo,
1206 				    "Warning: user %d pid %d (%s) ran out of "
1207 				    "file descriptors (%d/%d)\n",
1208 				    p->p_ucred->cr_uid, (int)p->p_pid,
1209 				    p->p_comm,
1210 				    uip->ui_openfiles, maxfilesperuser);
1211 			return(ENFILE);
1212 		}
1213 	}
1214 
1215 	/*
1216 	 * Grow the dtable if necessary
1217 	 */
1218 	spin_lock(&fdp->fd_spin);
1219 	if (want >= fdp->fd_nfiles)
1220 		fdgrow_locked(fdp, want);
1221 
1222 	/*
1223 	 * Search for a free descriptor starting at the higher
1224 	 * of want or fd_freefile.  If that fails, consider
1225 	 * expanding the ofile array.
1226 	 *
1227 	 * NOTE! the 'allocated' field is a cumulative recursive allocation
1228 	 * count.  If we happen to see a value of 0 then we can shortcut
1229 	 * our search.  Otherwise we run through through the tree going
1230 	 * down branches we know have free descriptor(s) until we hit a
1231 	 * leaf node.  The leaf node will be free but will not necessarily
1232 	 * have an allocated field of 0.
1233 	 */
1234 retry:
1235 	/* move up the tree looking for a subtree with a free node */
1236 	for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
1237 	     fd = right_ancestor(fd)) {
1238 		if (fdp->fd_files[fd].allocated == 0)
1239 			goto found;
1240 
1241 		rsize = right_subtree_size(fd);
1242 		if (fdp->fd_files[fd].allocated == rsize)
1243 			continue;	/* right subtree full */
1244 
1245 		/*
1246 		 * Free fd is in the right subtree of the tree rooted at fd.
1247 		 * Call that subtree R.  Look for the smallest (leftmost)
1248 		 * subtree of R with an unallocated fd: continue moving
1249 		 * down the left branch until encountering a full left
1250 		 * subtree, then move to the right.
1251 		 */
1252 		for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
1253 			node = fd + rsize;
1254 			rsum += fdp->fd_files[node].allocated;
1255 			if (fdp->fd_files[fd].allocated == rsum + rsize) {
1256 				fd = node;	/* move to the right */
1257 				if (fdp->fd_files[node].allocated == 0)
1258 					goto found;
1259 				rsum = 0;
1260 			}
1261 		}
1262 		goto found;
1263 	}
1264 
1265 	/*
1266 	 * No space in current array.  Expand?
1267 	 */
1268 	if (fdp->fd_nfiles >= lim) {
1269 		spin_unlock(&fdp->fd_spin);
1270 		return (EMFILE);
1271 	}
1272 	fdgrow_locked(fdp, want);
1273 	goto retry;
1274 
1275 found:
1276 	KKASSERT(fd < fdp->fd_nfiles);
1277 	if (fd > fdp->fd_lastfile)
1278 		fdp->fd_lastfile = fd;
1279 	if (want <= fdp->fd_freefile)
1280 		fdp->fd_freefile = fd;
1281 	*result = fd;
1282 	KKASSERT(fdp->fd_files[fd].fp == NULL);
1283 	KKASSERT(fdp->fd_files[fd].reserved == 0);
1284 	fdp->fd_files[fd].fileflags = 0;
1285 	fdp->fd_files[fd].reserved = 1;
1286 	fdreserve_locked(fdp, fd, 1);
1287 	spin_unlock(&fdp->fd_spin);
1288 	return (0);
1289 }
1290 
1291 /*
1292  * Check to see whether n user file descriptors
1293  * are available to the process p.
1294  */
1295 int
1296 fdavail(struct proc *p, int n)
1297 {
1298 	struct filedesc *fdp = p->p_fd;
1299 	struct fdnode *fdnode;
1300 	int i, lim, last;
1301 
1302 	spin_lock(&p->p_limit->p_spin);
1303 	if (p->p_rlimit[RLIMIT_NOFILE].rlim_cur > INT_MAX)
1304 		lim = INT_MAX;
1305 	else
1306 		lim = (int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur;
1307 	spin_unlock(&p->p_limit->p_spin);
1308 
1309 	if (lim > maxfilesperproc)
1310 		lim = maxfilesperproc;
1311 	if (lim < minfilesperproc)
1312 		lim = minfilesperproc;
1313 
1314 	spin_lock(&fdp->fd_spin);
1315 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0) {
1316 		spin_unlock(&fdp->fd_spin);
1317 		return (1);
1318 	}
1319 	last = min(fdp->fd_nfiles, lim);
1320 	fdnode = &fdp->fd_files[fdp->fd_freefile];
1321 	for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1322 		if (fdnode->fp == NULL && --n <= 0) {
1323 			spin_unlock(&fdp->fd_spin);
1324 			return (1);
1325 		}
1326 	}
1327 	spin_unlock(&fdp->fd_spin);
1328 	return (0);
1329 }
1330 
1331 /*
1332  * Revoke open descriptors referencing (f_data, f_type)
1333  *
1334  * Any revoke executed within a prison is only able to
1335  * revoke descriptors for processes within that prison.
1336  *
1337  * Returns 0 on success or an error code.
1338  */
1339 struct fdrevoke_info {
1340 	void *data;
1341 	short type;
1342 	short unused;
1343 	int found;
1344 	struct ucred *cred;
1345 	struct file *nfp;
1346 };
1347 
1348 static int fdrevoke_check_callback(struct file *fp, void *vinfo);
1349 static int fdrevoke_proc_callback(struct proc *p, void *vinfo);
1350 
1351 int
1352 fdrevoke(void *f_data, short f_type, struct ucred *cred)
1353 {
1354 	struct fdrevoke_info info;
1355 	int error;
1356 
1357 	bzero(&info, sizeof(info));
1358 	info.data = f_data;
1359 	info.type = f_type;
1360 	info.cred = cred;
1361 	error = falloc(NULL, &info.nfp, NULL);
1362 	if (error)
1363 		return (error);
1364 
1365 	/*
1366 	 * Scan the file pointer table once.  dups do not dup file pointers,
1367 	 * only descriptors, so there is no leak.  Set FREVOKED on the fps
1368 	 * being revoked.
1369 	 *
1370 	 * Any fps sent over unix-domain sockets will be revoked by the
1371 	 * socket code checking for FREVOKED when the fps are externialized.
1372 	 * revoke_token is used to make sure that fps marked FREVOKED and
1373 	 * externalized will be picked up by the following allproc_scan().
1374 	 */
1375 	lwkt_gettoken(&revoke_token);
1376 	allfiles_scan_exclusive(fdrevoke_check_callback, &info);
1377 	lwkt_reltoken(&revoke_token);
1378 
1379 	/*
1380 	 * If any fps were marked track down the related descriptors
1381 	 * and close them.  Any dup()s at this point will notice
1382 	 * the FREVOKED already set in the fp and do the right thing.
1383 	 */
1384 	if (info.found)
1385 		allproc_scan(fdrevoke_proc_callback, &info);
1386 	fdrop(info.nfp);
1387 	return(0);
1388 }
1389 
1390 /*
1391  * Locate matching file pointers directly.
1392  *
1393  * WARNING: allfiles_scan_exclusive() holds a spinlock through these calls!
1394  */
1395 static int
1396 fdrevoke_check_callback(struct file *fp, void *vinfo)
1397 {
1398 	struct fdrevoke_info *info = vinfo;
1399 
1400 	/*
1401 	 * File pointers already flagged for revokation are skipped.
1402 	 */
1403 	if (fp->f_flag & FREVOKED)
1404 		return(0);
1405 
1406 	/*
1407 	 * If revoking from a prison file pointers created outside of
1408 	 * that prison, or file pointers without creds, cannot be revoked.
1409 	 */
1410 	if (info->cred->cr_prison &&
1411 	    (fp->f_cred == NULL ||
1412 	     info->cred->cr_prison != fp->f_cred->cr_prison)) {
1413 		return(0);
1414 	}
1415 
1416 	/*
1417 	 * If the file pointer matches then mark it for revocation.  The
1418 	 * flag is currently only used by unp_revoke_gc().
1419 	 *
1420 	 * info->found is a heuristic and can race in a SMP environment.
1421 	 */
1422 	if (info->data == fp->f_data && info->type == fp->f_type) {
1423 		atomic_set_int(&fp->f_flag, FREVOKED);
1424 		info->found = 1;
1425 	}
1426 	return(0);
1427 }
1428 
1429 /*
1430  * Locate matching file pointers via process descriptor tables.
1431  */
1432 static int
1433 fdrevoke_proc_callback(struct proc *p, void *vinfo)
1434 {
1435 	struct fdrevoke_info *info = vinfo;
1436 	struct filedesc *fdp;
1437 	struct file *fp;
1438 	int n;
1439 
1440 	if (p->p_stat == SIDL || p->p_stat == SZOMB)
1441 		return(0);
1442 	if (info->cred->cr_prison &&
1443 	    info->cred->cr_prison != p->p_ucred->cr_prison) {
1444 		return(0);
1445 	}
1446 
1447 	/*
1448 	 * If the controlling terminal of the process matches the
1449 	 * vnode being revoked we clear the controlling terminal.
1450 	 *
1451 	 * The normal spec_close() may not catch this because it
1452 	 * uses curproc instead of p.
1453 	 */
1454 	if (p->p_session && info->type == DTYPE_VNODE &&
1455 	    info->data == p->p_session->s_ttyvp) {
1456 		p->p_session->s_ttyvp = NULL;
1457 		vrele(info->data);
1458 	}
1459 
1460 	/*
1461 	 * Softref the fdp to prevent it from being destroyed
1462 	 */
1463 	spin_lock(&p->p_spin);
1464 	if ((fdp = p->p_fd) == NULL) {
1465 		spin_unlock(&p->p_spin);
1466 		return(0);
1467 	}
1468 	atomic_add_int(&fdp->fd_softrefs, 1);
1469 	spin_unlock(&p->p_spin);
1470 
1471 	/*
1472 	 * Locate and close any matching file descriptors.
1473 	 */
1474 	spin_lock(&fdp->fd_spin);
1475 	for (n = 0; n < fdp->fd_nfiles; ++n) {
1476 		if ((fp = fdp->fd_files[n].fp) == NULL)
1477 			continue;
1478 		if (fp->f_flag & FREVOKED) {
1479 			fhold(info->nfp);
1480 			fdp->fd_files[n].fp = info->nfp;
1481 			spin_unlock(&fdp->fd_spin);
1482 			knote_fdclose(fp, fdp, n);	/* XXX */
1483 			closef(fp, p);
1484 			spin_lock(&fdp->fd_spin);
1485 		}
1486 	}
1487 	spin_unlock(&fdp->fd_spin);
1488 	atomic_subtract_int(&fdp->fd_softrefs, 1);
1489 	return(0);
1490 }
1491 
1492 /*
1493  * falloc:
1494  *	Create a new open file structure and reserve a file decriptor
1495  *	for the process that refers to it.
1496  *
1497  *	Root creds are checked using lp, or assumed if lp is NULL.  If
1498  *	resultfd is non-NULL then lp must also be non-NULL.  No file
1499  *	descriptor is reserved (and no process context is needed) if
1500  *	resultfd is NULL.
1501  *
1502  *	A file pointer with a refcount of 1 is returned.  Note that the
1503  *	file pointer is NOT associated with the descriptor.  If falloc
1504  *	returns success, fsetfd() MUST be called to either associate the
1505  *	file pointer or clear the reservation.
1506  */
1507 int
1508 falloc(struct lwp *lp, struct file **resultfp, int *resultfd)
1509 {
1510 	static struct timeval lastfail;
1511 	static int curfail;
1512 	struct file *fp;
1513 	struct ucred *cred = lp ? lp->lwp_thread->td_ucred : proc0.p_ucred;
1514 	int error;
1515 
1516 	fp = NULL;
1517 
1518 	/*
1519 	 * Handle filetable full issues and root overfill.
1520 	 */
1521 	if (nfiles >= maxfiles - maxfilesrootres &&
1522 	    (cred->cr_ruid != 0 || nfiles >= maxfiles)) {
1523 		if (ppsratecheck(&lastfail, &curfail, 1)) {
1524 			kprintf("kern.maxfiles limit exceeded by uid %d, "
1525 				"please see tuning(7).\n",
1526 				cred->cr_ruid);
1527 		}
1528 		error = ENFILE;
1529 		goto done;
1530 	}
1531 
1532 	/*
1533 	 * Allocate a new file descriptor.
1534 	 */
1535 	fp = kmalloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1536 	spin_init(&fp->f_spin, "falloc");
1537 	SLIST_INIT(&fp->f_klist);
1538 	fp->f_count = 1;
1539 	fp->f_ops = &badfileops;
1540 	fp->f_seqcount = 1;
1541 	fsetcred(fp, cred);
1542 	spin_lock(&filehead_spin);
1543 	nfiles++;
1544 	LIST_INSERT_HEAD(&filehead, fp, f_list);
1545 	spin_unlock(&filehead_spin);
1546 	if (resultfd) {
1547 		if ((error = fdalloc(lp->lwp_proc, 0, resultfd)) != 0) {
1548 			fdrop(fp);
1549 			fp = NULL;
1550 		}
1551 	} else {
1552 		error = 0;
1553 	}
1554 done:
1555 	*resultfp = fp;
1556 	return (error);
1557 }
1558 
1559 /*
1560  * Check for races against a file descriptor by determining that the
1561  * file pointer is still associated with the specified file descriptor,
1562  * and a close is not currently in progress.
1563  */
1564 int
1565 checkfdclosed(struct filedesc *fdp, int fd, struct file *fp)
1566 {
1567 	int error;
1568 
1569 	spin_lock_shared(&fdp->fd_spin);
1570 	if ((unsigned)fd >= fdp->fd_nfiles || fp != fdp->fd_files[fd].fp)
1571 		error = EBADF;
1572 	else
1573 		error = 0;
1574 	spin_unlock_shared(&fdp->fd_spin);
1575 	return (error);
1576 }
1577 
1578 /*
1579  * Associate a file pointer with a previously reserved file descriptor.
1580  * This function always succeeds.
1581  *
1582  * If fp is NULL, the file descriptor is returned to the pool.
1583  */
1584 
1585 /*
1586  * (exclusive spinlock must be held on call)
1587  */
1588 static void
1589 fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd)
1590 {
1591 	KKASSERT((unsigned)fd < fdp->fd_nfiles);
1592 	KKASSERT(fdp->fd_files[fd].reserved != 0);
1593 	if (fp) {
1594 		fhold(fp);
1595 		fdp->fd_files[fd].fp = fp;
1596 		fdp->fd_files[fd].reserved = 0;
1597 	} else {
1598 		fdp->fd_files[fd].reserved = 0;
1599 		fdreserve_locked(fdp, fd, -1);
1600 		fdfixup_locked(fdp, fd);
1601 	}
1602 }
1603 
1604 void
1605 fsetfd(struct filedesc *fdp, struct file *fp, int fd)
1606 {
1607 	spin_lock(&fdp->fd_spin);
1608 	fsetfd_locked(fdp, fp, fd);
1609 	spin_unlock(&fdp->fd_spin);
1610 }
1611 
1612 /*
1613  * (exclusive spinlock must be held on call)
1614  */
1615 static
1616 struct file *
1617 funsetfd_locked(struct filedesc *fdp, int fd)
1618 {
1619 	struct file *fp;
1620 
1621 	if ((unsigned)fd >= fdp->fd_nfiles)
1622 		return (NULL);
1623 	if ((fp = fdp->fd_files[fd].fp) == NULL)
1624 		return (NULL);
1625 	fdp->fd_files[fd].fp = NULL;
1626 	fdp->fd_files[fd].fileflags = 0;
1627 
1628 	fdreserve_locked(fdp, fd, -1);
1629 	fdfixup_locked(fdp, fd);
1630 	return(fp);
1631 }
1632 
1633 /*
1634  * WARNING: May not be called before initial fsetfd().
1635  */
1636 int
1637 fgetfdflags(struct filedesc *fdp, int fd, int *flagsp)
1638 {
1639 	int error;
1640 
1641 	spin_lock(&fdp->fd_spin);
1642 	if (((u_int)fd) >= fdp->fd_nfiles) {
1643 		error = EBADF;
1644 	} else if (fdp->fd_files[fd].fp == NULL) {
1645 		error = EBADF;
1646 	} else {
1647 		*flagsp = fdp->fd_files[fd].fileflags;
1648 		error = 0;
1649 	}
1650 	spin_unlock(&fdp->fd_spin);
1651 	return (error);
1652 }
1653 
1654 /*
1655  * WARNING: May not be called before initial fsetfd().
1656  */
1657 int
1658 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
1659 {
1660 	int error;
1661 
1662 	spin_lock(&fdp->fd_spin);
1663 	if (((u_int)fd) >= fdp->fd_nfiles) {
1664 		error = EBADF;
1665 	} else if (fdp->fd_files[fd].fp == NULL) {
1666 		error = EBADF;
1667 	} else {
1668 		fdp->fd_files[fd].fileflags |= add_flags;
1669 		error = 0;
1670 	}
1671 	spin_unlock(&fdp->fd_spin);
1672 	return (error);
1673 }
1674 
1675 /*
1676  * WARNING: May not be called before initial fsetfd().
1677  */
1678 int
1679 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
1680 {
1681 	int error;
1682 
1683 	spin_lock(&fdp->fd_spin);
1684 	if (((u_int)fd) >= fdp->fd_nfiles) {
1685 		error = EBADF;
1686 	} else if (fdp->fd_files[fd].fp == NULL) {
1687 		error = EBADF;
1688 	} else {
1689 		fdp->fd_files[fd].fileflags &= ~rem_flags;
1690 		error = 0;
1691 	}
1692 	spin_unlock(&fdp->fd_spin);
1693 	return (error);
1694 }
1695 
1696 /*
1697  * Set/Change/Clear the creds for a fp and synchronize the uidinfo.
1698  */
1699 void
1700 fsetcred(struct file *fp, struct ucred *ncr)
1701 {
1702 	struct ucred *ocr;
1703 	struct uidinfo *uip;
1704 
1705 	ocr = fp->f_cred;
1706 	if (ocr == NULL || ncr == NULL || ocr->cr_uidinfo != ncr->cr_uidinfo) {
1707 		if (ocr) {
1708 			uip = ocr->cr_uidinfo;
1709 			atomic_add_int(&uip->ui_openfiles, -1);
1710 		}
1711 		if (ncr) {
1712 			uip = ncr->cr_uidinfo;
1713 			atomic_add_int(&uip->ui_openfiles, 1);
1714 		}
1715 	}
1716 	if (ncr)
1717 		crhold(ncr);
1718 	fp->f_cred = ncr;
1719 	if (ocr)
1720 		crfree(ocr);
1721 }
1722 
1723 /*
1724  * Free a file descriptor.
1725  */
1726 static
1727 void
1728 ffree(struct file *fp)
1729 {
1730 	KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1731 	fsetcred(fp, NULL);
1732 	if (fp->f_nchandle.ncp)
1733 	    cache_drop(&fp->f_nchandle);
1734 	kfree(fp, M_FILE);
1735 }
1736 
1737 /*
1738  * called from init_main, initialize filedesc0 for proc0.
1739  */
1740 void
1741 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
1742 {
1743 	p0->p_fd = fdp0;
1744 	p0->p_fdtol = NULL;
1745 	fdp0->fd_refcnt = 1;
1746 	fdp0->fd_cmask = cmask;
1747 	fdp0->fd_files = fdp0->fd_builtin_files;
1748 	fdp0->fd_nfiles = NDFILE;
1749 	fdp0->fd_lastfile = -1;
1750 	spin_init(&fdp0->fd_spin, "fdinitbootstrap");
1751 }
1752 
1753 /*
1754  * Build a new filedesc structure.
1755  */
1756 struct filedesc *
1757 fdinit(struct proc *p)
1758 {
1759 	struct filedesc *newfdp;
1760 	struct filedesc *fdp = p->p_fd;
1761 
1762 	newfdp = kmalloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1763 	spin_lock(&fdp->fd_spin);
1764 	if (fdp->fd_cdir) {
1765 		newfdp->fd_cdir = fdp->fd_cdir;
1766 		vref(newfdp->fd_cdir);
1767 		cache_copy(&fdp->fd_ncdir, &newfdp->fd_ncdir);
1768 	}
1769 
1770 	/*
1771 	 * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1772 	 * proc0, but should unconditionally exist in other processes.
1773 	 */
1774 	if (fdp->fd_rdir) {
1775 		newfdp->fd_rdir = fdp->fd_rdir;
1776 		vref(newfdp->fd_rdir);
1777 		cache_copy(&fdp->fd_nrdir, &newfdp->fd_nrdir);
1778 	}
1779 	if (fdp->fd_jdir) {
1780 		newfdp->fd_jdir = fdp->fd_jdir;
1781 		vref(newfdp->fd_jdir);
1782 		cache_copy(&fdp->fd_njdir, &newfdp->fd_njdir);
1783 	}
1784 	spin_unlock(&fdp->fd_spin);
1785 
1786 	/* Create the file descriptor table. */
1787 	newfdp->fd_refcnt = 1;
1788 	newfdp->fd_cmask = cmask;
1789 	newfdp->fd_files = newfdp->fd_builtin_files;
1790 	newfdp->fd_nfiles = NDFILE;
1791 	newfdp->fd_lastfile = -1;
1792 	spin_init(&newfdp->fd_spin, "fdinit");
1793 
1794 	return (newfdp);
1795 }
1796 
1797 /*
1798  * Share a filedesc structure.
1799  */
1800 struct filedesc *
1801 fdshare(struct proc *p)
1802 {
1803 	struct filedesc *fdp;
1804 
1805 	fdp = p->p_fd;
1806 	spin_lock(&fdp->fd_spin);
1807 	fdp->fd_refcnt++;
1808 	spin_unlock(&fdp->fd_spin);
1809 	return (fdp);
1810 }
1811 
1812 /*
1813  * Copy a filedesc structure.
1814  */
1815 int
1816 fdcopy(struct proc *p, struct filedesc **fpp)
1817 {
1818 	struct filedesc *fdp = p->p_fd;
1819 	struct filedesc *newfdp;
1820 	struct fdnode *fdnode;
1821 	int i;
1822 	int ni;
1823 
1824 	/*
1825 	 * Certain daemons might not have file descriptors.
1826 	 */
1827 	if (fdp == NULL)
1828 		return (0);
1829 
1830 	/*
1831 	 * Allocate the new filedesc and fd_files[] array.  This can race
1832 	 * with operations by other threads on the fdp so we have to be
1833 	 * careful.
1834 	 */
1835 	newfdp = kmalloc(sizeof(struct filedesc),
1836 			 M_FILEDESC, M_WAITOK | M_ZERO | M_NULLOK);
1837 	if (newfdp == NULL) {
1838 		*fpp = NULL;
1839 		return (-1);
1840 	}
1841 again:
1842 	spin_lock(&fdp->fd_spin);
1843 	if (fdp->fd_lastfile < NDFILE) {
1844 		newfdp->fd_files = newfdp->fd_builtin_files;
1845 		i = NDFILE;
1846 	} else {
1847 		/*
1848 		 * We have to allocate (N^2-1) entries for our in-place
1849 		 * binary tree.  Allow the table to shrink.
1850 		 */
1851 		i = fdp->fd_nfiles;
1852 		ni = (i - 1) / 2;
1853 		while (ni > fdp->fd_lastfile && ni > NDFILE) {
1854 			i = ni;
1855 			ni = (i - 1) / 2;
1856 		}
1857 		spin_unlock(&fdp->fd_spin);
1858 		newfdp->fd_files = kmalloc(i * sizeof(struct fdnode),
1859 					  M_FILEDESC, M_WAITOK | M_ZERO);
1860 
1861 		/*
1862 		 * Check for race, retry
1863 		 */
1864 		spin_lock(&fdp->fd_spin);
1865 		if (i <= fdp->fd_lastfile) {
1866 			spin_unlock(&fdp->fd_spin);
1867 			kfree(newfdp->fd_files, M_FILEDESC);
1868 			goto again;
1869 		}
1870 	}
1871 
1872 	/*
1873 	 * Dup the remaining fields. vref() and cache_hold() can be
1874 	 * safely called while holding the read spinlock on fdp.
1875 	 *
1876 	 * The read spinlock on fdp is still being held.
1877 	 *
1878 	 * NOTE: vref and cache_hold calls for the case where the vnode
1879 	 * or cache entry already has at least one ref may be called
1880 	 * while holding spin locks.
1881 	 */
1882 	if ((newfdp->fd_cdir = fdp->fd_cdir) != NULL) {
1883 		vref(newfdp->fd_cdir);
1884 		cache_copy(&fdp->fd_ncdir, &newfdp->fd_ncdir);
1885 	}
1886 	/*
1887 	 * We must check for fd_rdir here, at least for now because
1888 	 * the init process is created before we have access to the
1889 	 * rootvode to take a reference to it.
1890 	 */
1891 	if ((newfdp->fd_rdir = fdp->fd_rdir) != NULL) {
1892 		vref(newfdp->fd_rdir);
1893 		cache_copy(&fdp->fd_nrdir, &newfdp->fd_nrdir);
1894 	}
1895 	if ((newfdp->fd_jdir = fdp->fd_jdir) != NULL) {
1896 		vref(newfdp->fd_jdir);
1897 		cache_copy(&fdp->fd_njdir, &newfdp->fd_njdir);
1898 	}
1899 	newfdp->fd_refcnt = 1;
1900 	newfdp->fd_nfiles = i;
1901 	newfdp->fd_lastfile = fdp->fd_lastfile;
1902 	newfdp->fd_freefile = fdp->fd_freefile;
1903 	newfdp->fd_cmask = fdp->fd_cmask;
1904 	spin_init(&newfdp->fd_spin, "fdcopy");
1905 
1906 	/*
1907 	 * Copy the descriptor table through (i).  This also copies the
1908 	 * allocation state.   Then go through and ref the file pointers
1909 	 * and clean up any KQ descriptors.
1910 	 *
1911 	 * kq descriptors cannot be copied.  Since we haven't ref'd the
1912 	 * copied files yet we can ignore the return value from funsetfd().
1913 	 *
1914 	 * The read spinlock on fdp is still being held.
1915 	 */
1916 	bcopy(fdp->fd_files, newfdp->fd_files, i * sizeof(struct fdnode));
1917 	for (i = 0 ; i < newfdp->fd_nfiles; ++i) {
1918 		fdnode = &newfdp->fd_files[i];
1919 		if (fdnode->reserved) {
1920 			fdreserve_locked(newfdp, i, -1);
1921 			fdnode->reserved = 0;
1922 			fdfixup_locked(newfdp, i);
1923 		} else if (fdnode->fp) {
1924 			if (fdnode->fp->f_type == DTYPE_KQUEUE) {
1925 				(void)funsetfd_locked(newfdp, i);
1926 			} else {
1927 				fhold(fdnode->fp);
1928 			}
1929 		}
1930 	}
1931 	spin_unlock(&fdp->fd_spin);
1932 	*fpp = newfdp;
1933 	return (0);
1934 }
1935 
1936 /*
1937  * Release a filedesc structure.
1938  *
1939  * NOT MPSAFE (MPSAFE for refs > 1, but the final cleanup code is not MPSAFE)
1940  */
1941 void
1942 fdfree(struct proc *p, struct filedesc *repl)
1943 {
1944 	struct filedesc *fdp;
1945 	struct fdnode *fdnode;
1946 	int i;
1947 	struct filedesc_to_leader *fdtol;
1948 	struct file *fp;
1949 	struct vnode *vp;
1950 	struct flock lf;
1951 
1952 	/*
1953 	 * Certain daemons might not have file descriptors.
1954 	 */
1955 	fdp = p->p_fd;
1956 	if (fdp == NULL) {
1957 		p->p_fd = repl;
1958 		return;
1959 	}
1960 
1961 	/*
1962 	 * Severe messing around to follow.
1963 	 */
1964 	spin_lock(&fdp->fd_spin);
1965 
1966 	/* Check for special need to clear POSIX style locks */
1967 	fdtol = p->p_fdtol;
1968 	if (fdtol != NULL) {
1969 		KASSERT(fdtol->fdl_refcount > 0,
1970 			("filedesc_to_refcount botch: fdl_refcount=%d",
1971 			 fdtol->fdl_refcount));
1972 		if (fdtol->fdl_refcount == 1 &&
1973 		    (p->p_leader->p_flags & P_ADVLOCK) != 0) {
1974 			for (i = 0; i <= fdp->fd_lastfile; ++i) {
1975 				fdnode = &fdp->fd_files[i];
1976 				if (fdnode->fp == NULL ||
1977 				    fdnode->fp->f_type != DTYPE_VNODE) {
1978 					continue;
1979 				}
1980 				fp = fdnode->fp;
1981 				fhold(fp);
1982 				spin_unlock(&fdp->fd_spin);
1983 
1984 				lf.l_whence = SEEK_SET;
1985 				lf.l_start = 0;
1986 				lf.l_len = 0;
1987 				lf.l_type = F_UNLCK;
1988 				vp = (struct vnode *)fp->f_data;
1989 				(void) VOP_ADVLOCK(vp,
1990 						   (caddr_t)p->p_leader,
1991 						   F_UNLCK,
1992 						   &lf,
1993 						   F_POSIX);
1994 				fdrop(fp);
1995 				spin_lock(&fdp->fd_spin);
1996 			}
1997 		}
1998 	retry:
1999 		if (fdtol->fdl_refcount == 1) {
2000 			if (fdp->fd_holdleaderscount > 0 &&
2001 			    (p->p_leader->p_flags & P_ADVLOCK) != 0) {
2002 				/*
2003 				 * close() or do_dup() has cleared a reference
2004 				 * in a shared file descriptor table.
2005 				 */
2006 				fdp->fd_holdleaderswakeup = 1;
2007 				ssleep(&fdp->fd_holdleaderscount,
2008 				       &fdp->fd_spin, 0, "fdlhold", 0);
2009 				goto retry;
2010 			}
2011 			if (fdtol->fdl_holdcount > 0) {
2012 				/*
2013 				 * Ensure that fdtol->fdl_leader
2014 				 * remains valid in closef().
2015 				 */
2016 				fdtol->fdl_wakeup = 1;
2017 				ssleep(fdtol, &fdp->fd_spin, 0, "fdlhold", 0);
2018 				goto retry;
2019 			}
2020 		}
2021 		fdtol->fdl_refcount--;
2022 		if (fdtol->fdl_refcount == 0 &&
2023 		    fdtol->fdl_holdcount == 0) {
2024 			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2025 			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2026 		} else {
2027 			fdtol = NULL;
2028 		}
2029 		p->p_fdtol = NULL;
2030 		if (fdtol != NULL) {
2031 			spin_unlock(&fdp->fd_spin);
2032 			kfree(fdtol, M_FILEDESC_TO_LEADER);
2033 			spin_lock(&fdp->fd_spin);
2034 		}
2035 	}
2036 	if (--fdp->fd_refcnt > 0) {
2037 		spin_unlock(&fdp->fd_spin);
2038 		spin_lock(&p->p_spin);
2039 		p->p_fd = repl;
2040 		spin_unlock(&p->p_spin);
2041 		return;
2042 	}
2043 
2044 	/*
2045 	 * Even though we are the last reference to the structure allproc
2046 	 * scans may still reference the structure.  Maintain proper
2047 	 * locks until we can replace p->p_fd.
2048 	 *
2049 	 * Also note that kqueue's closef still needs to reference the
2050 	 * fdp via p->p_fd, so we have to close the descriptors before
2051 	 * we replace p->p_fd.
2052 	 */
2053 	for (i = 0; i <= fdp->fd_lastfile; ++i) {
2054 		if (fdp->fd_files[i].fp) {
2055 			fp = funsetfd_locked(fdp, i);
2056 			if (fp) {
2057 				spin_unlock(&fdp->fd_spin);
2058 				if (SLIST_FIRST(&fp->f_klist))
2059 					knote_fdclose(fp, fdp, i);
2060 				closef(fp, p);
2061 				spin_lock(&fdp->fd_spin);
2062 			}
2063 		}
2064 	}
2065 	spin_unlock(&fdp->fd_spin);
2066 
2067 	/*
2068 	 * Interlock against an allproc scan operations (typically frevoke).
2069 	 */
2070 	spin_lock(&p->p_spin);
2071 	p->p_fd = repl;
2072 	spin_unlock(&p->p_spin);
2073 
2074 	/*
2075 	 * Wait for any softrefs to go away.  This race rarely occurs so
2076 	 * we can use a non-critical-path style poll/sleep loop.  The
2077 	 * race only occurs against allproc scans.
2078 	 *
2079 	 * No new softrefs can occur with the fdp disconnected from the
2080 	 * process.
2081 	 */
2082 	if (fdp->fd_softrefs) {
2083 		kprintf("pid %d: Warning, fdp race avoided\n", p->p_pid);
2084 		while (fdp->fd_softrefs)
2085 			tsleep(&fdp->fd_softrefs, 0, "fdsoft", 1);
2086 	}
2087 
2088 	if (fdp->fd_files != fdp->fd_builtin_files)
2089 		kfree(fdp->fd_files, M_FILEDESC);
2090 	if (fdp->fd_cdir) {
2091 		cache_drop(&fdp->fd_ncdir);
2092 		vrele(fdp->fd_cdir);
2093 	}
2094 	if (fdp->fd_rdir) {
2095 		cache_drop(&fdp->fd_nrdir);
2096 		vrele(fdp->fd_rdir);
2097 	}
2098 	if (fdp->fd_jdir) {
2099 		cache_drop(&fdp->fd_njdir);
2100 		vrele(fdp->fd_jdir);
2101 	}
2102 	kfree(fdp, M_FILEDESC);
2103 }
2104 
2105 /*
2106  * Retrieve and reference the file pointer associated with a descriptor.
2107  */
2108 struct file *
2109 holdfp(struct filedesc *fdp, int fd, int flag)
2110 {
2111 	struct file* fp;
2112 
2113 	spin_lock_shared(&fdp->fd_spin);
2114 	if (((u_int)fd) >= fdp->fd_nfiles) {
2115 		fp = NULL;
2116 		goto done;
2117 	}
2118 	if ((fp = fdp->fd_files[fd].fp) == NULL)
2119 		goto done;
2120 	if ((fp->f_flag & flag) == 0 && flag != -1) {
2121 		fp = NULL;
2122 		goto done;
2123 	}
2124 	fhold(fp);
2125 done:
2126 	spin_unlock_shared(&fdp->fd_spin);
2127 	return (fp);
2128 }
2129 
2130 /*
2131  * holdsock() - load the struct file pointer associated
2132  * with a socket into *fpp.  If an error occurs, non-zero
2133  * will be returned and *fpp will be set to NULL.
2134  */
2135 int
2136 holdsock(struct filedesc *fdp, int fd, struct file **fpp)
2137 {
2138 	struct file *fp;
2139 	int error;
2140 
2141 	spin_lock_shared(&fdp->fd_spin);
2142 	if ((unsigned)fd >= fdp->fd_nfiles) {
2143 		error = EBADF;
2144 		fp = NULL;
2145 		goto done;
2146 	}
2147 	if ((fp = fdp->fd_files[fd].fp) == NULL) {
2148 		error = EBADF;
2149 		goto done;
2150 	}
2151 	if (fp->f_type != DTYPE_SOCKET) {
2152 		error = ENOTSOCK;
2153 		goto done;
2154 	}
2155 	fhold(fp);
2156 	error = 0;
2157 done:
2158 	spin_unlock_shared(&fdp->fd_spin);
2159 	*fpp = fp;
2160 	return (error);
2161 }
2162 
2163 /*
2164  * Convert a user file descriptor to a held file pointer.
2165  */
2166 int
2167 holdvnode(struct filedesc *fdp, int fd, struct file **fpp)
2168 {
2169 	struct file *fp;
2170 	int error;
2171 
2172 	spin_lock_shared(&fdp->fd_spin);
2173 	if ((unsigned)fd >= fdp->fd_nfiles) {
2174 		error = EBADF;
2175 		fp = NULL;
2176 		goto done;
2177 	}
2178 	if ((fp = fdp->fd_files[fd].fp) == NULL) {
2179 		error = EBADF;
2180 		goto done;
2181 	}
2182 	if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
2183 		fp = NULL;
2184 		error = EINVAL;
2185 		goto done;
2186 	}
2187 	fhold(fp);
2188 	error = 0;
2189 done:
2190 	spin_unlock_shared(&fdp->fd_spin);
2191 	*fpp = fp;
2192 	return (error);
2193 }
2194 
2195 /*
2196  * For setugid programs, we don't want to people to use that setugidness
2197  * to generate error messages which write to a file which otherwise would
2198  * otherwise be off-limits to the process.
2199  *
2200  * This is a gross hack to plug the hole.  A better solution would involve
2201  * a special vop or other form of generalized access control mechanism.  We
2202  * go ahead and just reject all procfs file systems accesses as dangerous.
2203  *
2204  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2205  * sufficient.  We also don't for check setugidness since we know we are.
2206  */
2207 static int
2208 is_unsafe(struct file *fp)
2209 {
2210 	if (fp->f_type == DTYPE_VNODE &&
2211 	    ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
2212 		return (1);
2213 	return (0);
2214 }
2215 
2216 /*
2217  * Make this setguid thing safe, if at all possible.
2218  *
2219  * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
2220  */
2221 void
2222 setugidsafety(struct proc *p)
2223 {
2224 	struct filedesc *fdp = p->p_fd;
2225 	int i;
2226 
2227 	/* Certain daemons might not have file descriptors. */
2228 	if (fdp == NULL)
2229 		return;
2230 
2231 	/*
2232 	 * note: fdp->fd_files may be reallocated out from under us while
2233 	 * we are blocked in a close.  Be careful!
2234 	 */
2235 	for (i = 0; i <= fdp->fd_lastfile; i++) {
2236 		if (i > 2)
2237 			break;
2238 		if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
2239 			struct file *fp;
2240 
2241 			/*
2242 			 * NULL-out descriptor prior to close to avoid
2243 			 * a race while close blocks.
2244 			 */
2245 			if ((fp = funsetfd_locked(fdp, i)) != NULL) {
2246 				knote_fdclose(fp, fdp, i);
2247 				closef(fp, p);
2248 			}
2249 		}
2250 	}
2251 }
2252 
2253 /*
2254  * Close any files on exec?
2255  *
2256  * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
2257  */
2258 void
2259 fdcloseexec(struct proc *p)
2260 {
2261 	struct filedesc *fdp = p->p_fd;
2262 	int i;
2263 
2264 	/* Certain daemons might not have file descriptors. */
2265 	if (fdp == NULL)
2266 		return;
2267 
2268 	/*
2269 	 * We cannot cache fd_files since operations may block and rip
2270 	 * them out from under us.
2271 	 */
2272 	for (i = 0; i <= fdp->fd_lastfile; i++) {
2273 		if (fdp->fd_files[i].fp != NULL &&
2274 		    (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
2275 			struct file *fp;
2276 
2277 			/*
2278 			 * NULL-out descriptor prior to close to avoid
2279 			 * a race while close blocks.
2280 			 */
2281 			if ((fp = funsetfd_locked(fdp, i)) != NULL) {
2282 				knote_fdclose(fp, fdp, i);
2283 				closef(fp, p);
2284 			}
2285 		}
2286 	}
2287 }
2288 
2289 /*
2290  * It is unsafe for set[ug]id processes to be started with file
2291  * descriptors 0..2 closed, as these descriptors are given implicit
2292  * significance in the Standard C library.  fdcheckstd() will create a
2293  * descriptor referencing /dev/null for each of stdin, stdout, and
2294  * stderr that is not already open.
2295  *
2296  * NOT MPSAFE - calls falloc, vn_open, etc
2297  */
2298 int
2299 fdcheckstd(struct lwp *lp)
2300 {
2301 	struct nlookupdata nd;
2302 	struct filedesc *fdp;
2303 	struct file *fp;
2304 	int retval;
2305 	int i, error, flags, devnull;
2306 
2307 	fdp = lp->lwp_proc->p_fd;
2308 	if (fdp == NULL)
2309 		return (0);
2310 	devnull = -1;
2311 	error = 0;
2312 	for (i = 0; i < 3; i++) {
2313 		if (fdp->fd_files[i].fp != NULL)
2314 			continue;
2315 		if (devnull < 0) {
2316 			if ((error = falloc(lp, &fp, &devnull)) != 0)
2317 				break;
2318 
2319 			error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
2320 						NLC_FOLLOW|NLC_LOCKVP);
2321 			flags = FREAD | FWRITE;
2322 			if (error == 0)
2323 				error = vn_open(&nd, fp, flags, 0);
2324 			if (error == 0)
2325 				fsetfd(fdp, fp, devnull);
2326 			else
2327 				fsetfd(fdp, NULL, devnull);
2328 			fdrop(fp);
2329 			nlookup_done(&nd);
2330 			if (error)
2331 				break;
2332 			KKASSERT(i == devnull);
2333 		} else {
2334 			error = kern_dup(DUP_FIXED, devnull, i, &retval);
2335 			if (error != 0)
2336 				break;
2337 		}
2338 	}
2339 	return (error);
2340 }
2341 
2342 /*
2343  * Internal form of close.
2344  * Decrement reference count on file structure.
2345  * Note: td and/or p may be NULL when closing a file
2346  * that was being passed in a message.
2347  *
2348  * MPALMOSTSAFE - acquires mplock for VOP operations
2349  */
2350 int
2351 closef(struct file *fp, struct proc *p)
2352 {
2353 	struct vnode *vp;
2354 	struct flock lf;
2355 	struct filedesc_to_leader *fdtol;
2356 
2357 	if (fp == NULL)
2358 		return (0);
2359 
2360 	/*
2361 	 * POSIX record locking dictates that any close releases ALL
2362 	 * locks owned by this process.  This is handled by setting
2363 	 * a flag in the unlock to free ONLY locks obeying POSIX
2364 	 * semantics, and not to free BSD-style file locks.
2365 	 * If the descriptor was in a message, POSIX-style locks
2366 	 * aren't passed with the descriptor.
2367 	 */
2368 	if (p != NULL && fp->f_type == DTYPE_VNODE &&
2369 	    (((struct vnode *)fp->f_data)->v_flag & VMAYHAVELOCKS)
2370 	) {
2371 		if ((p->p_leader->p_flags & P_ADVLOCK) != 0) {
2372 			lf.l_whence = SEEK_SET;
2373 			lf.l_start = 0;
2374 			lf.l_len = 0;
2375 			lf.l_type = F_UNLCK;
2376 			vp = (struct vnode *)fp->f_data;
2377 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
2378 					   &lf, F_POSIX);
2379 		}
2380 		fdtol = p->p_fdtol;
2381 		if (fdtol != NULL) {
2382 			lwkt_gettoken(&p->p_token);
2383 			/*
2384 			 * Handle special case where file descriptor table
2385 			 * is shared between multiple process leaders.
2386 			 */
2387 			for (fdtol = fdtol->fdl_next;
2388 			     fdtol != p->p_fdtol;
2389 			     fdtol = fdtol->fdl_next) {
2390 				if ((fdtol->fdl_leader->p_flags &
2391 				     P_ADVLOCK) == 0)
2392 					continue;
2393 				fdtol->fdl_holdcount++;
2394 				lf.l_whence = SEEK_SET;
2395 				lf.l_start = 0;
2396 				lf.l_len = 0;
2397 				lf.l_type = F_UNLCK;
2398 				vp = (struct vnode *)fp->f_data;
2399 				(void) VOP_ADVLOCK(vp,
2400 						   (caddr_t)fdtol->fdl_leader,
2401 						   F_UNLCK, &lf, F_POSIX);
2402 				fdtol->fdl_holdcount--;
2403 				if (fdtol->fdl_holdcount == 0 &&
2404 				    fdtol->fdl_wakeup != 0) {
2405 					fdtol->fdl_wakeup = 0;
2406 					wakeup(fdtol);
2407 				}
2408 			}
2409 			lwkt_reltoken(&p->p_token);
2410 		}
2411 	}
2412 	return (fdrop(fp));
2413 }
2414 
2415 /*
2416  * fhold() can only be called if f_count is already at least 1 (i.e. the
2417  * caller of fhold() already has a reference to the file pointer in some
2418  * manner or other).
2419  *
2420  * Atomic ops are used for incrementing and decrementing f_count before
2421  * the 1->0 transition.  f_count 1->0 transition is special, see the
2422  * comment in fdrop().
2423  */
2424 void
2425 fhold(struct file *fp)
2426 {
2427 	/* 0->1 transition will never work */
2428 	KASSERT(fp->f_count > 0, ("fhold: invalid f_count %d", fp->f_count));
2429 	atomic_add_int(&fp->f_count, 1);
2430 }
2431 
2432 /*
2433  * fdrop() - drop a reference to a descriptor
2434  */
2435 int
2436 fdrop(struct file *fp)
2437 {
2438 	struct flock lf;
2439 	struct vnode *vp;
2440 	int error, do_free = 0;
2441 
2442 	/*
2443 	 * NOTE:
2444 	 * Simple atomic_fetchadd_int(f_count, -1) here will cause use-
2445 	 * after-free or double free (due to f_count 0->1 transition), if
2446 	 * fhold() is called on the fps found through filehead iteration.
2447 	 */
2448 	for (;;) {
2449 		int count = fp->f_count;
2450 
2451 		cpu_ccfence();
2452 		KASSERT(count > 0, ("fdrop: invalid f_count %d", count));
2453 		if (count == 1) {
2454 			/*
2455 			 * About to drop the last reference, hold the
2456 			 * filehead spin lock and drop it, so that no
2457 			 * one could see this fp through filehead anymore,
2458 			 * let alone fhold() this fp.
2459 			 */
2460 			spin_lock(&filehead_spin);
2461 			if (atomic_cmpset_int(&fp->f_count, count, 0)) {
2462 				LIST_REMOVE(fp, f_list);
2463 				nfiles--;
2464 				spin_unlock(&filehead_spin);
2465 				do_free = 1; /* free this fp */
2466 				break;
2467 			}
2468 			spin_unlock(&filehead_spin);
2469 			/* retry */
2470 		} else if (atomic_cmpset_int(&fp->f_count, count, count - 1)) {
2471 			break;
2472 		}
2473 		/* retry */
2474 	}
2475 	if (!do_free)
2476 		return (0);
2477 
2478 	KKASSERT(SLIST_FIRST(&fp->f_klist) == NULL);
2479 
2480 	/*
2481 	 * The last reference has gone away, we own the fp structure free
2482 	 * and clear.
2483 	 */
2484 	if (fp->f_count < 0)
2485 		panic("fdrop: count < 0");
2486 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE &&
2487 	    (((struct vnode *)fp->f_data)->v_flag & VMAYHAVELOCKS)
2488 	) {
2489 		lf.l_whence = SEEK_SET;
2490 		lf.l_start = 0;
2491 		lf.l_len = 0;
2492 		lf.l_type = F_UNLCK;
2493 		vp = (struct vnode *)fp->f_data;
2494 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
2495 	}
2496 	if (fp->f_ops != &badfileops)
2497 		error = fo_close(fp);
2498 	else
2499 		error = 0;
2500 	ffree(fp);
2501 	return (error);
2502 }
2503 
2504 /*
2505  * Apply an advisory lock on a file descriptor.
2506  *
2507  * Just attempt to get a record lock of the requested type on
2508  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2509  *
2510  * MPALMOSTSAFE
2511  */
2512 int
2513 sys_flock(struct flock_args *uap)
2514 {
2515 	struct proc *p = curproc;
2516 	struct file *fp;
2517 	struct vnode *vp;
2518 	struct flock lf;
2519 	int error;
2520 
2521 	if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
2522 		return (EBADF);
2523 	if (fp->f_type != DTYPE_VNODE) {
2524 		error = EOPNOTSUPP;
2525 		goto done;
2526 	}
2527 	vp = (struct vnode *)fp->f_data;
2528 	lf.l_whence = SEEK_SET;
2529 	lf.l_start = 0;
2530 	lf.l_len = 0;
2531 	if (uap->how & LOCK_UN) {
2532 		lf.l_type = F_UNLCK;
2533 		atomic_clear_int(&fp->f_flag, FHASLOCK); /* race ok */
2534 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
2535 		goto done;
2536 	}
2537 	if (uap->how & LOCK_EX)
2538 		lf.l_type = F_WRLCK;
2539 	else if (uap->how & LOCK_SH)
2540 		lf.l_type = F_RDLCK;
2541 	else {
2542 		error = EBADF;
2543 		goto done;
2544 	}
2545 	if (uap->how & LOCK_NB)
2546 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 0);
2547 	else
2548 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_WAIT);
2549 	atomic_set_int(&fp->f_flag, FHASLOCK);	/* race ok */
2550 done:
2551 	fdrop(fp);
2552 	return (error);
2553 }
2554 
2555 /*
2556  * File Descriptor pseudo-device driver (/dev/fd/).
2557  *
2558  * Opening minor device N dup()s the file (if any) connected to file
2559  * descriptor N belonging to the calling process.  Note that this driver
2560  * consists of only the ``open()'' routine, because all subsequent
2561  * references to this file will be direct to the other driver.
2562  */
2563 static int
2564 fdopen(struct dev_open_args *ap)
2565 {
2566 	thread_t td = curthread;
2567 
2568 	KKASSERT(td->td_lwp != NULL);
2569 
2570 	/*
2571 	 * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
2572 	 * the file descriptor being sought for duplication. The error
2573 	 * return ensures that the vnode for this device will be released
2574 	 * by vn_open. Open will detect this special error and take the
2575 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2576 	 * will simply report the error.
2577 	 */
2578 	td->td_lwp->lwp_dupfd = minor(ap->a_head.a_dev);
2579 	return (ENODEV);
2580 }
2581 
2582 /*
2583  * The caller has reserved the file descriptor dfd for us.  On success we
2584  * must fsetfd() it.  On failure the caller will clean it up.
2585  */
2586 int
2587 dupfdopen(struct filedesc *fdp, int dfd, int sfd, int mode, int error)
2588 {
2589 	struct file *wfp;
2590 	struct file *xfp;
2591 	int werror;
2592 
2593 	if ((wfp = holdfp(fdp, sfd, -1)) == NULL)
2594 		return (EBADF);
2595 
2596 	/*
2597 	 * Close a revoke/dup race.  Duping a descriptor marked as revoked
2598 	 * will dup a dummy descriptor instead of the real one.
2599 	 */
2600 	if (wfp->f_flag & FREVOKED) {
2601 		kprintf("Warning: attempt to dup() a revoked descriptor\n");
2602 		fdrop(wfp);
2603 		wfp = NULL;
2604 		werror = falloc(NULL, &wfp, NULL);
2605 		if (werror)
2606 			return (werror);
2607 	}
2608 
2609 	/*
2610 	 * There are two cases of interest here.
2611 	 *
2612 	 * For ENODEV simply dup sfd to file descriptor dfd and return.
2613 	 *
2614 	 * For ENXIO steal away the file structure from sfd and store it
2615 	 * dfd.  sfd is effectively closed by this operation.
2616 	 *
2617 	 * Any other error code is just returned.
2618 	 */
2619 	switch (error) {
2620 	case ENODEV:
2621 		/*
2622 		 * Check that the mode the file is being opened for is a
2623 		 * subset of the mode of the existing descriptor.
2624 		 */
2625 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2626 			error = EACCES;
2627 			break;
2628 		}
2629 		spin_lock(&fdp->fd_spin);
2630 		fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2631 		fsetfd_locked(fdp, wfp, dfd);
2632 		spin_unlock(&fdp->fd_spin);
2633 		error = 0;
2634 		break;
2635 	case ENXIO:
2636 		/*
2637 		 * Steal away the file pointer from dfd, and stuff it into indx.
2638 		 */
2639 		spin_lock(&fdp->fd_spin);
2640 		fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2641 		fsetfd(fdp, wfp, dfd);
2642 		if ((xfp = funsetfd_locked(fdp, sfd)) != NULL) {
2643 			spin_unlock(&fdp->fd_spin);
2644 			fdrop(xfp);
2645 		} else {
2646 			spin_unlock(&fdp->fd_spin);
2647 		}
2648 		error = 0;
2649 		break;
2650 	default:
2651 		break;
2652 	}
2653 	fdrop(wfp);
2654 	return (error);
2655 }
2656 
2657 /*
2658  * NOT MPSAFE - I think these refer to a common file descriptor table
2659  * and we need to spinlock that to link fdtol in.
2660  */
2661 struct filedesc_to_leader *
2662 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2663 			 struct proc *leader)
2664 {
2665 	struct filedesc_to_leader *fdtol;
2666 
2667 	fdtol = kmalloc(sizeof(struct filedesc_to_leader),
2668 			M_FILEDESC_TO_LEADER, M_WAITOK | M_ZERO);
2669 	fdtol->fdl_refcount = 1;
2670 	fdtol->fdl_holdcount = 0;
2671 	fdtol->fdl_wakeup = 0;
2672 	fdtol->fdl_leader = leader;
2673 	if (old != NULL) {
2674 		fdtol->fdl_next = old->fdl_next;
2675 		fdtol->fdl_prev = old;
2676 		old->fdl_next = fdtol;
2677 		fdtol->fdl_next->fdl_prev = fdtol;
2678 	} else {
2679 		fdtol->fdl_next = fdtol;
2680 		fdtol->fdl_prev = fdtol;
2681 	}
2682 	return fdtol;
2683 }
2684 
2685 /*
2686  * Scan all file pointers in the system.  The callback is made with
2687  * the master list spinlock held exclusively.
2688  */
2689 void
2690 allfiles_scan_exclusive(int (*callback)(struct file *, void *), void *data)
2691 {
2692 	struct file *fp;
2693 	int res;
2694 
2695 	spin_lock(&filehead_spin);
2696 	LIST_FOREACH(fp, &filehead, f_list) {
2697 		res = callback(fp, data);
2698 		if (res < 0)
2699 			break;
2700 	}
2701 	spin_unlock(&filehead_spin);
2702 }
2703 
2704 /*
2705  * Get file structures.
2706  *
2707  * NOT MPSAFE - process list scan, SYSCTL_OUT (probably not mpsafe)
2708  */
2709 
2710 struct sysctl_kern_file_info {
2711 	int count;
2712 	int error;
2713 	struct sysctl_req *req;
2714 };
2715 
2716 static int sysctl_kern_file_callback(struct proc *p, void *data);
2717 
2718 static int
2719 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2720 {
2721 	struct sysctl_kern_file_info info;
2722 
2723 	/*
2724 	 * Note: because the number of file descriptors is calculated
2725 	 * in different ways for sizing vs returning the data,
2726 	 * there is information leakage from the first loop.  However,
2727 	 * it is of a similar order of magnitude to the leakage from
2728 	 * global system statistics such as kern.openfiles.
2729 	 *
2730 	 * When just doing a count, note that we cannot just count
2731 	 * the elements and add f_count via the filehead list because
2732 	 * threaded processes share their descriptor table and f_count might
2733 	 * still be '1' in that case.
2734 	 *
2735 	 * Since the SYSCTL op can block, we must hold the process to
2736 	 * prevent it being ripped out from under us either in the
2737 	 * file descriptor loop or in the greater LIST_FOREACH.  The
2738 	 * process may be in varying states of disrepair.  If the process
2739 	 * is in SZOMB we may have caught it just as it is being removed
2740 	 * from the allproc list, we must skip it in that case to maintain
2741 	 * an unbroken chain through the allproc list.
2742 	 */
2743 	info.count = 0;
2744 	info.error = 0;
2745 	info.req = req;
2746 	allproc_scan(sysctl_kern_file_callback, &info);
2747 
2748 	/*
2749 	 * When just calculating the size, overestimate a bit to try to
2750 	 * prevent system activity from causing the buffer-fill call
2751 	 * to fail later on.
2752 	 */
2753 	if (req->oldptr == NULL) {
2754 		info.count = (info.count + 16) + (info.count / 10);
2755 		info.error = SYSCTL_OUT(req, NULL,
2756 					info.count * sizeof(struct kinfo_file));
2757 	}
2758 	return (info.error);
2759 }
2760 
2761 static int
2762 sysctl_kern_file_callback(struct proc *p, void *data)
2763 {
2764 	struct sysctl_kern_file_info *info = data;
2765 	struct kinfo_file kf;
2766 	struct filedesc *fdp;
2767 	struct file *fp;
2768 	uid_t uid;
2769 	int n;
2770 
2771 	if (p->p_stat == SIDL || p->p_stat == SZOMB)
2772 		return(0);
2773 	if (!(PRISON_CHECK(info->req->td->td_ucred, p->p_ucred) != 0))
2774 		return(0);
2775 
2776 	/*
2777 	 * Softref the fdp to prevent it from being destroyed
2778 	 */
2779 	spin_lock(&p->p_spin);
2780 	if ((fdp = p->p_fd) == NULL) {
2781 		spin_unlock(&p->p_spin);
2782 		return(0);
2783 	}
2784 	atomic_add_int(&fdp->fd_softrefs, 1);
2785 	spin_unlock(&p->p_spin);
2786 
2787 	/*
2788 	 * The fdp's own spinlock prevents the contents from being
2789 	 * modified.
2790 	 */
2791 	spin_lock_shared(&fdp->fd_spin);
2792 	for (n = 0; n < fdp->fd_nfiles; ++n) {
2793 		if ((fp = fdp->fd_files[n].fp) == NULL)
2794 			continue;
2795 		if (info->req->oldptr == NULL) {
2796 			++info->count;
2797 		} else {
2798 			uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
2799 			kcore_make_file(&kf, fp, p->p_pid, uid, n);
2800 			spin_unlock_shared(&fdp->fd_spin);
2801 			info->error = SYSCTL_OUT(info->req, &kf, sizeof(kf));
2802 			spin_lock_shared(&fdp->fd_spin);
2803 			if (info->error)
2804 				break;
2805 		}
2806 	}
2807 	spin_unlock_shared(&fdp->fd_spin);
2808 	atomic_subtract_int(&fdp->fd_softrefs, 1);
2809 	if (info->error)
2810 		return(-1);
2811 	return(0);
2812 }
2813 
2814 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2815     0, 0, sysctl_kern_file, "S,file", "Entire file table");
2816 
2817 SYSCTL_INT(_kern, OID_AUTO, minfilesperproc, CTLFLAG_RW,
2818     &minfilesperproc, 0, "Minimum files allowed open per process");
2819 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2820     &maxfilesperproc, 0, "Maximum files allowed open per process");
2821 SYSCTL_INT(_kern, OID_AUTO, maxfilesperuser, CTLFLAG_RW,
2822     &maxfilesperuser, 0, "Maximum files allowed open per user");
2823 
2824 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2825     &maxfiles, 0, "Maximum number of files");
2826 
2827 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
2828     &maxfilesrootres, 0, "Descriptors reserved for root use");
2829 
2830 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2831 	&nfiles, 0, "System-wide number of open files");
2832 
2833 static void
2834 fildesc_drvinit(void *unused)
2835 {
2836 	int fd;
2837 
2838 	for (fd = 0; fd < NUMFDESC; fd++) {
2839 		make_dev(&fildesc_ops, fd,
2840 			 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
2841 	}
2842 
2843 	make_dev(&fildesc_ops, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
2844 	make_dev(&fildesc_ops, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
2845 	make_dev(&fildesc_ops, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
2846 }
2847 
2848 struct fileops badfileops = {
2849 	.fo_read = badfo_readwrite,
2850 	.fo_write = badfo_readwrite,
2851 	.fo_ioctl = badfo_ioctl,
2852 	.fo_kqfilter = badfo_kqfilter,
2853 	.fo_stat = badfo_stat,
2854 	.fo_close = badfo_close,
2855 	.fo_shutdown = badfo_shutdown
2856 };
2857 
2858 int
2859 badfo_readwrite(
2860 	struct file *fp,
2861 	struct uio *uio,
2862 	struct ucred *cred,
2863 	int flags
2864 ) {
2865 	return (EBADF);
2866 }
2867 
2868 int
2869 badfo_ioctl(struct file *fp, u_long com, caddr_t data,
2870 	    struct ucred *cred, struct sysmsg *msgv)
2871 {
2872 	return (EBADF);
2873 }
2874 
2875 /*
2876  * Must return an error to prevent registration, typically
2877  * due to a revoked descriptor (file_filtops assigned).
2878  */
2879 int
2880 badfo_kqfilter(struct file *fp, struct knote *kn)
2881 {
2882 	return (EOPNOTSUPP);
2883 }
2884 
2885 int
2886 badfo_stat(struct file *fp, struct stat *sb, struct ucred *cred)
2887 {
2888 	return (EBADF);
2889 }
2890 
2891 int
2892 badfo_close(struct file *fp)
2893 {
2894 	return (EBADF);
2895 }
2896 
2897 int
2898 badfo_shutdown(struct file *fp, int how)
2899 {
2900 	return (EBADF);
2901 }
2902 
2903 int
2904 nofo_shutdown(struct file *fp, int how)
2905 {
2906 	return (EOPNOTSUPP);
2907 }
2908 
2909 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE + CDEV_MAJOR,
2910     fildesc_drvinit,NULL);
2911