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