xref: /freebsd/sys/kern/kern_descrip.c (revision 390e8cc2974df1888369c06339ef8e0e92b312b6)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_descrip.c	8.6 (Berkeley) 4/19/94
39  * $FreeBSD$
40  */
41 
42 #include "opt_compat.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/syscallsubr.h>
47 #include <sys/sysproto.h>
48 #include <sys/conf.h>
49 #include <sys/filedesc.h>
50 #include <sys/lock.h>
51 #include <sys/kernel.h>
52 #include <sys/limits.h>
53 #include <sys/malloc.h>
54 #include <sys/mutex.h>
55 #include <sys/sysctl.h>
56 #include <sys/vnode.h>
57 #include <sys/mount.h>
58 #include <sys/proc.h>
59 #include <sys/namei.h>
60 #include <sys/file.h>
61 #include <sys/stat.h>
62 #include <sys/filio.h>
63 #include <sys/fcntl.h>
64 #include <sys/unistd.h>
65 #include <sys/resourcevar.h>
66 #include <sys/event.h>
67 #include <sys/sx.h>
68 #include <sys/socketvar.h>
69 #include <sys/signalvar.h>
70 
71 #include <vm/vm.h>
72 #include <vm/vm_extern.h>
73 #include <vm/uma.h>
74 
75 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
76 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
77 		     "file desc to leader structures");
78 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
79 
80 static uma_zone_t file_zone;
81 
82 static	 d_open_t  fdopen;
83 #define	NUMFDESC 64
84 
85 #define	CDEV_MAJOR 22
86 static struct cdevsw fildesc_cdevsw = {
87 	.d_open =	fdopen,
88 	.d_name =	"FD",
89 	.d_maj =	CDEV_MAJOR,
90 };
91 
92 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
93 enum dup_type { DUP_VARIABLE, DUP_FIXED };
94 
95 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
96     register_t *retval);
97 
98 /*
99  * Descriptor management.
100  */
101 struct filelist filehead;	/* head of list of open files */
102 int nfiles;			/* actual number of open files */
103 extern int cmask;
104 struct sx filelist_lock;	/* sx to protect filelist */
105 struct mtx sigio_lock;		/* mtx to protect pointers to sigio */
106 
107 /*
108  * System calls on descriptors.
109  */
110 #ifndef _SYS_SYSPROTO_H_
111 struct getdtablesize_args {
112 	int	dummy;
113 };
114 #endif
115 /*
116  * MPSAFE
117  */
118 /* ARGSUSED */
119 int
120 getdtablesize(td, uap)
121 	struct thread *td;
122 	struct getdtablesize_args *uap;
123 {
124 	struct proc *p = td->td_proc;
125 
126 	mtx_lock(&Giant);
127 	td->td_retval[0] =
128 	    min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
129 	mtx_unlock(&Giant);
130 	return (0);
131 }
132 
133 /*
134  * Duplicate a file descriptor to a particular value.
135  *
136  * note: keep in mind that a potential race condition exists when closing
137  * descriptors from a shared descriptor table (via rfork).
138  */
139 #ifndef _SYS_SYSPROTO_H_
140 struct dup2_args {
141 	u_int	from;
142 	u_int	to;
143 };
144 #endif
145 /*
146  * MPSAFE
147  */
148 /* ARGSUSED */
149 int
150 dup2(td, uap)
151 	struct thread *td;
152 	struct dup2_args *uap;
153 {
154 
155 	return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
156 		    td->td_retval));
157 }
158 
159 /*
160  * Duplicate a file descriptor.
161  */
162 #ifndef _SYS_SYSPROTO_H_
163 struct dup_args {
164 	u_int	fd;
165 };
166 #endif
167 /*
168  * MPSAFE
169  */
170 /* ARGSUSED */
171 int
172 dup(td, uap)
173 	struct thread *td;
174 	struct dup_args *uap;
175 {
176 
177 	return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
178 }
179 
180 /*
181  * The file control system call.
182  */
183 #ifndef _SYS_SYSPROTO_H_
184 struct fcntl_args {
185 	int	fd;
186 	int	cmd;
187 	long	arg;
188 };
189 #endif
190 /*
191  * MPSAFE
192  */
193 /* ARGSUSED */
194 int
195 fcntl(td, uap)
196 	struct thread *td;
197 	struct fcntl_args *uap;
198 {
199 	struct flock fl;
200 	intptr_t arg;
201 	int error;
202 
203 	error = 0;
204 	switch (uap->cmd) {
205 	case F_GETLK:
206 	case F_SETLK:
207 	case F_SETLKW:
208 		error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
209 		arg = (intptr_t)&fl;
210 		break;
211 	default:
212 		arg = uap->arg;
213 		break;
214 	}
215 	if (error)
216 		return (error);
217 	error = kern_fcntl(td, uap->fd, uap->cmd, arg);
218 	if (error)
219 		return (error);
220 	if (uap->cmd == F_GETLK)
221 		error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
222 	return (error);
223 }
224 
225 int
226 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
227 {
228 	struct filedesc *fdp;
229 	struct flock *flp;
230 	struct file *fp;
231 	struct proc *p;
232 	char *pop;
233 	struct vnode *vp;
234 	u_int newmin;
235 	int error, flg, tmp;
236 
237 	error = 0;
238 	flg = F_POSIX;
239 	p = td->td_proc;
240 	fdp = p->p_fd;
241 	mtx_lock(&Giant);
242 	FILEDESC_LOCK(fdp);
243 	if ((unsigned)fd >= fdp->fd_nfiles ||
244 	    (fp = fdp->fd_ofiles[fd]) == NULL) {
245 		FILEDESC_UNLOCK(fdp);
246 		error = EBADF;
247 		goto done2;
248 	}
249 	pop = &fdp->fd_ofileflags[fd];
250 
251 	switch (cmd) {
252 	case F_DUPFD:
253 		FILEDESC_UNLOCK(fdp);
254 		newmin = arg;
255 		if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
256 		    newmin >= maxfilesperproc) {
257 			error = EINVAL;
258 			break;
259 		}
260 		error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
261 		break;
262 
263 	case F_GETFD:
264 		td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
265 		FILEDESC_UNLOCK(fdp);
266 		break;
267 
268 	case F_SETFD:
269 		*pop = (*pop &~ UF_EXCLOSE) |
270 		    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
271 		FILEDESC_UNLOCK(fdp);
272 		break;
273 
274 	case F_GETFL:
275 		FILE_LOCK(fp);
276 		FILEDESC_UNLOCK(fdp);
277 		td->td_retval[0] = OFLAGS(fp->f_flag);
278 		FILE_UNLOCK(fp);
279 		break;
280 
281 	case F_SETFL:
282 		FILE_LOCK(fp);
283 		FILEDESC_UNLOCK(fdp);
284 		fhold_locked(fp);
285 		fp->f_flag &= ~FCNTLFLAGS;
286 		fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
287 		FILE_UNLOCK(fp);
288 		tmp = fp->f_flag & FNONBLOCK;
289 		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
290 		if (error) {
291 			fdrop(fp, td);
292 			break;
293 		}
294 		tmp = fp->f_flag & FASYNC;
295 		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
296 		if (error == 0) {
297 			fdrop(fp, td);
298 			break;
299 		}
300 		FILE_LOCK(fp);
301 		fp->f_flag &= ~FNONBLOCK;
302 		FILE_UNLOCK(fp);
303 		tmp = 0;
304 		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
305 		fdrop(fp, td);
306 		break;
307 
308 	case F_GETOWN:
309 		fhold(fp);
310 		FILEDESC_UNLOCK(fdp);
311 		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
312 		if (error == 0)
313 			td->td_retval[0] = tmp;
314 		fdrop(fp, td);
315 		break;
316 
317 	case F_SETOWN:
318 		fhold(fp);
319 		FILEDESC_UNLOCK(fdp);
320 		tmp = arg;
321 		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
322 		fdrop(fp, td);
323 		break;
324 
325 	case F_SETLKW:
326 		flg |= F_WAIT;
327 		/* FALLTHROUGH F_SETLK */
328 
329 	case F_SETLK:
330 		if (fp->f_type != DTYPE_VNODE) {
331 			FILEDESC_UNLOCK(fdp);
332 			error = EBADF;
333 			break;
334 		}
335 
336 		flp = (struct flock *)arg;
337 		if (flp->l_whence == SEEK_CUR) {
338 			if (fp->f_offset < 0 ||
339 			    (flp->l_start > 0 &&
340 			     fp->f_offset > OFF_MAX - flp->l_start)) {
341 				FILEDESC_UNLOCK(fdp);
342 				error = EOVERFLOW;
343 				break;
344 			}
345 			flp->l_start += fp->f_offset;
346 		}
347 
348 		/*
349 		 * VOP_ADVLOCK() may block.
350 		 */
351 		fhold(fp);
352 		FILEDESC_UNLOCK(fdp);
353 		vp = fp->f_data;
354 
355 		switch (flp->l_type) {
356 		case F_RDLCK:
357 			if ((fp->f_flag & FREAD) == 0) {
358 				error = EBADF;
359 				break;
360 			}
361 			PROC_LOCK(p->p_leader);
362 			p->p_leader->p_flag |= P_ADVLOCK;
363 			PROC_UNLOCK(p->p_leader);
364 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
365 			    flp, flg);
366 			break;
367 		case F_WRLCK:
368 			if ((fp->f_flag & FWRITE) == 0) {
369 				error = EBADF;
370 				break;
371 			}
372 			PROC_LOCK(p->p_leader);
373 			p->p_leader->p_flag |= P_ADVLOCK;
374 			PROC_UNLOCK(p->p_leader);
375 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
376 			    flp, flg);
377 			break;
378 		case F_UNLCK:
379 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
380 			    flp, F_POSIX);
381 			break;
382 		default:
383 			error = EINVAL;
384 			break;
385 		}
386 		/* Check for race with close */
387 		FILEDESC_LOCK(fdp);
388 		if ((unsigned) fd >= fdp->fd_nfiles ||
389 		    fp != fdp->fd_ofiles[fd]) {
390 			FILEDESC_UNLOCK(fdp);
391 			flp->l_whence = SEEK_SET;
392 			flp->l_start = 0;
393 			flp->l_len = 0;
394 			flp->l_type = F_UNLCK;
395 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
396 					   F_UNLCK, flp, F_POSIX);
397 		} else
398 			FILEDESC_UNLOCK(fdp);
399 		fdrop(fp, td);
400 		break;
401 
402 	case F_GETLK:
403 		if (fp->f_type != DTYPE_VNODE) {
404 			FILEDESC_UNLOCK(fdp);
405 			error = EBADF;
406 			break;
407 		}
408 		flp = (struct flock *)arg;
409 		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
410 		    flp->l_type != F_UNLCK) {
411 			FILEDESC_UNLOCK(fdp);
412 			error = EINVAL;
413 			break;
414 		}
415 		if (flp->l_whence == SEEK_CUR) {
416 			if ((flp->l_start > 0 &&
417 			    fp->f_offset > OFF_MAX - flp->l_start) ||
418 			    (flp->l_start < 0 &&
419 			     fp->f_offset < OFF_MIN - flp->l_start)) {
420 				FILEDESC_UNLOCK(fdp);
421 				error = EOVERFLOW;
422 				break;
423 			}
424 			flp->l_start += fp->f_offset;
425 		}
426 		/*
427 		 * VOP_ADVLOCK() may block.
428 		 */
429 		fhold(fp);
430 		FILEDESC_UNLOCK(fdp);
431 		vp = fp->f_data;
432 		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
433 		    F_POSIX);
434 		fdrop(fp, td);
435 		break;
436 	default:
437 		FILEDESC_UNLOCK(fdp);
438 		error = EINVAL;
439 		break;
440 	}
441 done2:
442 	mtx_unlock(&Giant);
443 	return (error);
444 }
445 
446 /*
447  * Common code for dup, dup2, and fcntl(F_DUPFD).
448  */
449 static int
450 do_dup(td, type, old, new, retval)
451 	enum dup_type type;
452 	int old, new;
453 	register_t *retval;
454 	struct thread *td;
455 {
456 	struct filedesc *fdp;
457 	struct proc *p;
458 	struct file *fp;
459 	struct file *delfp;
460 	int error, newfd;
461 	int holdleaders;
462 
463 	p = td->td_proc;
464 	fdp = p->p_fd;
465 
466 	/*
467 	 * Verify we have a valid descriptor to dup from and possibly to
468 	 * dup to.
469 	 */
470 	if (old < 0 || new < 0 || new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
471 	    new >= maxfilesperproc)
472 		return (EBADF);
473 	FILEDESC_LOCK(fdp);
474 	if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
475 		FILEDESC_UNLOCK(fdp);
476 		return (EBADF);
477 	}
478 	if (type == DUP_FIXED && old == new) {
479 		*retval = new;
480 		FILEDESC_UNLOCK(fdp);
481 		return (0);
482 	}
483 	fp = fdp->fd_ofiles[old];
484 	fhold(fp);
485 
486 	/*
487 	 * Expand the table for the new descriptor if needed.  This may
488 	 * block and drop and reacquire the filedesc lock.
489 	 */
490 	if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
491 		error = fdalloc(td, new, &newfd);
492 		if (error) {
493 			FILEDESC_UNLOCK(fdp);
494 			fdrop(fp, td);
495 			return (error);
496 		}
497 	}
498 	if (type == DUP_VARIABLE)
499 		new = newfd;
500 
501 	/*
502 	 * If the old file changed out from under us then treat it as a
503 	 * bad file descriptor.  Userland should do its own locking to
504 	 * avoid this case.
505 	 */
506 	if (fdp->fd_ofiles[old] != fp) {
507 		if (fdp->fd_ofiles[new] == NULL) {
508 			if (new < fdp->fd_freefile)
509 				fdp->fd_freefile = new;
510 			while (fdp->fd_lastfile > 0 &&
511 			    fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
512 				fdp->fd_lastfile--;
513 		}
514 		FILEDESC_UNLOCK(fdp);
515 		fdrop(fp, td);
516 		return (EBADF);
517 	}
518 	KASSERT(old != new, ("new fd is same as old"));
519 
520 	/*
521 	 * Save info on the descriptor being overwritten.  We have
522 	 * to do the unmap now, but we cannot close it without
523 	 * introducing an ownership race for the slot.
524 	 */
525 	delfp = fdp->fd_ofiles[new];
526 	if (delfp != NULL && p->p_fdtol != NULL) {
527 		/*
528 		 * Ask fdfree() to sleep to ensure that all relevant
529 		 * process leaders can be traversed in closef().
530 		 */
531 		fdp->fd_holdleaderscount++;
532 		holdleaders = 1;
533 	} else
534 		holdleaders = 0;
535 	KASSERT(delfp == NULL || type == DUP_FIXED,
536 	    ("dup() picked an open file"));
537 #if 0
538 	if (delfp && (fdp->fd_ofileflags[new] & UF_MAPPED))
539 		(void) munmapfd(td, new);
540 #endif
541 
542 	/*
543 	 * Duplicate the source descriptor, update lastfile
544 	 */
545 	fdp->fd_ofiles[new] = fp;
546  	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
547 	if (new > fdp->fd_lastfile)
548 		fdp->fd_lastfile = new;
549 	FILEDESC_UNLOCK(fdp);
550 	*retval = new;
551 
552 	/*
553 	 * If we dup'd over a valid file, we now own the reference to it
554 	 * and must dispose of it using closef() semantics (as if a
555 	 * close() were performed on it).
556 	 */
557 	if (delfp) {
558 		mtx_lock(&Giant);
559 		(void) closef(delfp, td);
560 		mtx_unlock(&Giant);
561 		if (holdleaders) {
562 			FILEDESC_LOCK(fdp);
563 			fdp->fd_holdleaderscount--;
564 			if (fdp->fd_holdleaderscount == 0 &&
565 			    fdp->fd_holdleaderswakeup != 0) {
566 				fdp->fd_holdleaderswakeup = 0;
567 				wakeup(&fdp->fd_holdleaderscount);
568 			}
569 			FILEDESC_UNLOCK(fdp);
570 		}
571 	}
572 	return (0);
573 }
574 
575 /*
576  * If sigio is on the list associated with a process or process group,
577  * disable signalling from the device, remove sigio from the list and
578  * free sigio.
579  */
580 void
581 funsetown(sigiop)
582 	struct sigio **sigiop;
583 {
584 	struct sigio *sigio;
585 
586 	SIGIO_LOCK();
587 	sigio = *sigiop;
588 	if (sigio == NULL) {
589 		SIGIO_UNLOCK();
590 		return;
591 	}
592 	*(sigio->sio_myref) = NULL;
593 	if ((sigio)->sio_pgid < 0) {
594 		struct pgrp *pg = (sigio)->sio_pgrp;
595 		PGRP_LOCK(pg);
596 		SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
597 			     sigio, sio_pgsigio);
598 		PGRP_UNLOCK(pg);
599 	} else {
600 		struct proc *p = (sigio)->sio_proc;
601 		PROC_LOCK(p);
602 		SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
603 			     sigio, sio_pgsigio);
604 		PROC_UNLOCK(p);
605 	}
606 	SIGIO_UNLOCK();
607 	crfree(sigio->sio_ucred);
608 	FREE(sigio, M_SIGIO);
609 }
610 
611 /*
612  * Free a list of sigio structures.
613  * We only need to lock the SIGIO_LOCK because we have made ourselves
614  * inaccessable to callers of fsetown and therefore do not need to lock
615  * the proc or pgrp struct for the list manipulation.
616  */
617 void
618 funsetownlst(sigiolst)
619 	struct sigiolst *sigiolst;
620 {
621 	struct proc *p;
622 	struct pgrp *pg;
623 	struct sigio *sigio;
624 
625 	sigio = SLIST_FIRST(sigiolst);
626 	if (sigio == NULL)
627 		return;
628 	p = NULL;
629 	pg = NULL;
630 
631 	/*
632 	 * Every entry of the list should belong
633 	 * to a single proc or pgrp.
634 	 */
635 	if (sigio->sio_pgid < 0) {
636 		pg = sigio->sio_pgrp;
637 		PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
638 	} else /* if (sigio->sio_pgid > 0) */ {
639 		p = sigio->sio_proc;
640 		PROC_LOCK_ASSERT(p, MA_NOTOWNED);
641 	}
642 
643 	SIGIO_LOCK();
644 	while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
645 		*(sigio->sio_myref) = NULL;
646 		if (pg != NULL) {
647 			KASSERT(sigio->sio_pgid < 0,
648 			    ("Proc sigio in pgrp sigio list"));
649 			KASSERT(sigio->sio_pgrp == pg,
650 			    ("Bogus pgrp in sigio list"));
651 			PGRP_LOCK(pg);
652 			SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
653 			    sio_pgsigio);
654 			PGRP_UNLOCK(pg);
655 		} else /* if (p != NULL) */ {
656 			KASSERT(sigio->sio_pgid > 0,
657 			    ("Pgrp sigio in proc sigio list"));
658 			KASSERT(sigio->sio_proc == p,
659 			    ("Bogus proc in sigio list"));
660 			PROC_LOCK(p);
661 			SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
662 			    sio_pgsigio);
663 			PROC_UNLOCK(p);
664 		}
665 		SIGIO_UNLOCK();
666 		crfree(sigio->sio_ucred);
667 		FREE(sigio, M_SIGIO);
668 		SIGIO_LOCK();
669 	}
670 	SIGIO_UNLOCK();
671 }
672 
673 /*
674  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
675  *
676  * After permission checking, add a sigio structure to the sigio list for
677  * the process or process group.
678  */
679 int
680 fsetown(pgid, sigiop)
681 	pid_t pgid;
682 	struct sigio **sigiop;
683 {
684 	struct proc *proc;
685 	struct pgrp *pgrp;
686 	struct sigio *sigio;
687 	int ret;
688 
689 	if (pgid == 0) {
690 		funsetown(sigiop);
691 		return (0);
692 	}
693 
694 	ret = 0;
695 
696 	/* Allocate and fill in the new sigio out of locks. */
697 	MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
698 	sigio->sio_pgid = pgid;
699 	sigio->sio_ucred = crhold(curthread->td_ucred);
700 	sigio->sio_myref = sigiop;
701 
702 	sx_slock(&proctree_lock);
703 	if (pgid > 0) {
704 		proc = pfind(pgid);
705 		if (proc == NULL) {
706 			ret = ESRCH;
707 			goto fail;
708 		}
709 
710 		/*
711 		 * Policy - Don't allow a process to FSETOWN a process
712 		 * in another session.
713 		 *
714 		 * Remove this test to allow maximum flexibility or
715 		 * restrict FSETOWN to the current process or process
716 		 * group for maximum safety.
717 		 */
718 		PROC_UNLOCK(proc);
719 		if (proc->p_session != curthread->td_proc->p_session) {
720 			ret = EPERM;
721 			goto fail;
722 		}
723 
724 		pgrp = NULL;
725 	} else /* if (pgid < 0) */ {
726 		pgrp = pgfind(-pgid);
727 		if (pgrp == NULL) {
728 			ret = ESRCH;
729 			goto fail;
730 		}
731 		PGRP_UNLOCK(pgrp);
732 
733 		/*
734 		 * Policy - Don't allow a process to FSETOWN a process
735 		 * in another session.
736 		 *
737 		 * Remove this test to allow maximum flexibility or
738 		 * restrict FSETOWN to the current process or process
739 		 * group for maximum safety.
740 		 */
741 		if (pgrp->pg_session != curthread->td_proc->p_session) {
742 			ret = EPERM;
743 			goto fail;
744 		}
745 
746 		proc = NULL;
747 	}
748 	funsetown(sigiop);
749 	if (pgid > 0) {
750 		PROC_LOCK(proc);
751 		/*
752 		 * Since funsetownlst() is called without the proctree
753 		 * locked, we need to check for P_WEXIT.
754 		 * XXX: is ESRCH correct?
755 		 */
756 		if ((proc->p_flag & P_WEXIT) != 0) {
757 			PROC_UNLOCK(proc);
758 			ret = ESRCH;
759 			goto fail;
760 		}
761 		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
762 		sigio->sio_proc = proc;
763 		PROC_UNLOCK(proc);
764 	} else {
765 		PGRP_LOCK(pgrp);
766 		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
767 		sigio->sio_pgrp = pgrp;
768 		PGRP_UNLOCK(pgrp);
769 	}
770 	sx_sunlock(&proctree_lock);
771 	SIGIO_LOCK();
772 	*sigiop = sigio;
773 	SIGIO_UNLOCK();
774 	return (0);
775 
776 fail:
777 	sx_sunlock(&proctree_lock);
778 	crfree(sigio->sio_ucred);
779 	FREE(sigio, M_SIGIO);
780 	return (ret);
781 }
782 
783 /*
784  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
785  */
786 pid_t
787 fgetown(sigiop)
788 	struct sigio **sigiop;
789 {
790 	pid_t pgid;
791 
792 	SIGIO_LOCK();
793 	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
794 	SIGIO_UNLOCK();
795 	return (pgid);
796 }
797 
798 /*
799  * Close a file descriptor.
800  */
801 #ifndef _SYS_SYSPROTO_H_
802 struct close_args {
803         int     fd;
804 };
805 #endif
806 /*
807  * MPSAFE
808  */
809 /* ARGSUSED */
810 int
811 close(td, uap)
812 	struct thread *td;
813 	struct close_args *uap;
814 {
815 	struct filedesc *fdp;
816 	struct file *fp;
817 	int fd, error;
818 	int holdleaders;
819 
820 	fd = uap->fd;
821 	error = 0;
822 	holdleaders = 0;
823 	fdp = td->td_proc->p_fd;
824 	mtx_lock(&Giant);
825 	FILEDESC_LOCK(fdp);
826 	if ((unsigned)fd >= fdp->fd_nfiles ||
827 	    (fp = fdp->fd_ofiles[fd]) == NULL) {
828 		FILEDESC_UNLOCK(fdp);
829 		error = EBADF;
830 		goto done2;
831 	}
832 #if 0
833 	if (fdp->fd_ofileflags[fd] & UF_MAPPED)
834 		(void) munmapfd(td, fd);
835 #endif
836 	fdp->fd_ofiles[fd] = NULL;
837 	fdp->fd_ofileflags[fd] = 0;
838 	if (td->td_proc->p_fdtol != NULL) {
839 		/*
840 		 * Ask fdfree() to sleep to ensure that all relevant
841 		 * process leaders can be traversed in closef().
842 		 */
843 		fdp->fd_holdleaderscount++;
844 		holdleaders = 1;
845 	}
846 
847 	/*
848 	 * we now hold the fp reference that used to be owned by the descriptor
849 	 * array.
850 	 */
851 	while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
852 		fdp->fd_lastfile--;
853 	if (fd < fdp->fd_freefile)
854 		fdp->fd_freefile = fd;
855 	if (fd < fdp->fd_knlistsize) {
856 		FILEDESC_UNLOCK(fdp);
857 		knote_fdclose(td, fd);
858 	} else
859 		FILEDESC_UNLOCK(fdp);
860 
861 	error = closef(fp, td);
862 done2:
863 	mtx_unlock(&Giant);
864 	if (holdleaders) {
865 		FILEDESC_LOCK(fdp);
866 		fdp->fd_holdleaderscount--;
867 		if (fdp->fd_holdleaderscount == 0 &&
868 		    fdp->fd_holdleaderswakeup != 0) {
869 			fdp->fd_holdleaderswakeup = 0;
870 			wakeup(&fdp->fd_holdleaderscount);
871 		}
872 		FILEDESC_UNLOCK(fdp);
873 	}
874 	return (error);
875 }
876 
877 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
878 /*
879  * Return status information about a file descriptor.
880  */
881 #ifndef _SYS_SYSPROTO_H_
882 struct ofstat_args {
883 	int	fd;
884 	struct	ostat *sb;
885 };
886 #endif
887 /*
888  * MPSAFE
889  */
890 /* ARGSUSED */
891 int
892 ofstat(td, uap)
893 	struct thread *td;
894 	struct ofstat_args *uap;
895 {
896 	struct file *fp;
897 	struct stat ub;
898 	struct ostat oub;
899 	int error;
900 
901 	mtx_lock(&Giant);
902 	if ((error = fget(td, uap->fd, &fp)) != 0)
903 		goto done2;
904 	error = fo_stat(fp, &ub, td->td_ucred, td);
905 	if (error == 0) {
906 		cvtstat(&ub, &oub);
907 		error = copyout(&oub, uap->sb, sizeof(oub));
908 	}
909 	fdrop(fp, td);
910 done2:
911 	mtx_unlock(&Giant);
912 	return (error);
913 }
914 #endif /* COMPAT_43 || COMPAT_SUNOS */
915 
916 /*
917  * Return status information about a file descriptor.
918  */
919 #ifndef _SYS_SYSPROTO_H_
920 struct fstat_args {
921 	int	fd;
922 	struct	stat *sb;
923 };
924 #endif
925 /*
926  * MPSAFE
927  */
928 /* ARGSUSED */
929 int
930 fstat(td, uap)
931 	struct thread *td;
932 	struct fstat_args *uap;
933 {
934 	struct file *fp;
935 	struct stat ub;
936 	int error;
937 
938 	mtx_lock(&Giant);
939 	if ((error = fget(td, uap->fd, &fp)) != 0)
940 		goto done2;
941 	error = fo_stat(fp, &ub, td->td_ucred, td);
942 	if (error == 0)
943 		error = copyout(&ub, uap->sb, sizeof(ub));
944 	fdrop(fp, td);
945 done2:
946 	mtx_unlock(&Giant);
947 	return (error);
948 }
949 
950 /*
951  * Return status information about a file descriptor.
952  */
953 #ifndef _SYS_SYSPROTO_H_
954 struct nfstat_args {
955 	int	fd;
956 	struct	nstat *sb;
957 };
958 #endif
959 /*
960  * MPSAFE
961  */
962 /* ARGSUSED */
963 int
964 nfstat(td, uap)
965 	struct thread *td;
966 	struct nfstat_args *uap;
967 {
968 	struct file *fp;
969 	struct stat ub;
970 	struct nstat nub;
971 	int error;
972 
973 	mtx_lock(&Giant);
974 	if ((error = fget(td, uap->fd, &fp)) != 0)
975 		goto done2;
976 	error = fo_stat(fp, &ub, td->td_ucred, td);
977 	if (error == 0) {
978 		cvtnstat(&ub, &nub);
979 		error = copyout(&nub, uap->sb, sizeof(nub));
980 	}
981 	fdrop(fp, td);
982 done2:
983 	mtx_unlock(&Giant);
984 	return (error);
985 }
986 
987 /*
988  * Return pathconf information about a file descriptor.
989  */
990 #ifndef _SYS_SYSPROTO_H_
991 struct fpathconf_args {
992 	int	fd;
993 	int	name;
994 };
995 #endif
996 /*
997  * MPSAFE
998  */
999 /* ARGSUSED */
1000 int
1001 fpathconf(td, uap)
1002 	struct thread *td;
1003 	struct fpathconf_args *uap;
1004 {
1005 	struct file *fp;
1006 	struct vnode *vp;
1007 	int error;
1008 
1009 	if ((error = fget(td, uap->fd, &fp)) != 0)
1010 		return (error);
1011 
1012 	/* If asynchronous I/O is available, it works for all descriptors. */
1013 	if (uap->name == _PC_ASYNC_IO) {
1014 		td->td_retval[0] = async_io_version;
1015 		goto out;
1016 	}
1017 	switch (fp->f_type) {
1018 	case DTYPE_PIPE:
1019 	case DTYPE_SOCKET:
1020 		if (uap->name != _PC_PIPE_BUF) {
1021 			error = EINVAL;
1022 		} else {
1023 			td->td_retval[0] = PIPE_BUF;
1024 			error = 0;
1025 		}
1026 		break;
1027 	case DTYPE_FIFO:
1028 	case DTYPE_VNODE:
1029 		vp = fp->f_data;
1030 		mtx_lock(&Giant);
1031 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1032 		error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1033 		VOP_UNLOCK(vp, 0, td);
1034 		mtx_unlock(&Giant);
1035 		break;
1036 	default:
1037 		error = EOPNOTSUPP;
1038 		break;
1039 	}
1040 out:
1041 	fdrop(fp, td);
1042 	return (error);
1043 }
1044 
1045 /*
1046  * Allocate a file descriptor for the process.
1047  */
1048 static int fdexpand;
1049 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
1050 
1051 int
1052 fdalloc(td, want, result)
1053 	struct thread *td;
1054 	int want;
1055 	int *result;
1056 {
1057 	struct proc *p = td->td_proc;
1058 	struct filedesc *fdp = td->td_proc->p_fd;
1059 	int i;
1060 	int lim, last, nfiles;
1061 	struct file **newofile, **oldofile;
1062 	char *newofileflags;
1063 
1064 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1065 
1066 	/*
1067 	 * Search for a free descriptor starting at the higher
1068 	 * of want or fd_freefile.  If that fails, consider
1069 	 * expanding the ofile array.
1070 	 */
1071 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1072 	for (;;) {
1073 		last = min(fdp->fd_nfiles, lim);
1074 		i = max(want, fdp->fd_freefile);
1075 		for (; i < last; i++) {
1076 			if (fdp->fd_ofiles[i] == NULL) {
1077 				fdp->fd_ofileflags[i] = 0;
1078 				if (i > fdp->fd_lastfile)
1079 					fdp->fd_lastfile = i;
1080 				if (want <= fdp->fd_freefile)
1081 					fdp->fd_freefile = i;
1082 				*result = i;
1083 				return (0);
1084 			}
1085 		}
1086 
1087 		/*
1088 		 * No space in current array.  Expand?
1089 		 */
1090 		if (i >= lim)
1091 			return (EMFILE);
1092 		if (fdp->fd_nfiles < NDEXTENT)
1093 			nfiles = NDEXTENT;
1094 		else
1095 			nfiles = 2 * fdp->fd_nfiles;
1096 		while (nfiles < want)
1097 			nfiles <<= 1;
1098 		FILEDESC_UNLOCK(fdp);
1099 		/*
1100 		 * XXX malloc() calls uma_large_malloc() for sizes larger
1101 		 * than KMEM_ZMAX bytes. uma_large_malloc() requires Giant.
1102 		 */
1103 		mtx_lock(&Giant);
1104 		newofile = malloc(nfiles * OFILESIZE, M_FILEDESC, M_WAITOK);
1105 		mtx_unlock(&Giant);
1106 
1107 		/*
1108 		 * Deal with file-table extend race that might have
1109 		 * occurred while filedesc was unlocked.
1110 		 */
1111 		FILEDESC_LOCK(fdp);
1112 		if (fdp->fd_nfiles >= nfiles) {
1113 			/* XXX uma_large_free() needs Giant. */
1114 			FILEDESC_UNLOCK(fdp);
1115 			mtx_lock(&Giant);
1116 			free(newofile, M_FILEDESC);
1117 			mtx_unlock(&Giant);
1118 			FILEDESC_LOCK(fdp);
1119 			continue;
1120 		}
1121 		newofileflags = (char *) &newofile[nfiles];
1122 		/*
1123 		 * Copy the existing ofile and ofileflags arrays
1124 		 * and zero the new portion of each array.
1125 		 */
1126 		i = fdp->fd_nfiles * sizeof(struct file *);
1127 		bcopy(fdp->fd_ofiles, newofile,	i);
1128 		bzero((char *)newofile + i,
1129 		    nfiles * sizeof(struct file *) - i);
1130 		i = fdp->fd_nfiles * sizeof(char);
1131 		bcopy(fdp->fd_ofileflags, newofileflags, i);
1132 		bzero(newofileflags + i, nfiles * sizeof(char) - i);
1133 		if (fdp->fd_nfiles > NDFILE)
1134 			oldofile = fdp->fd_ofiles;
1135 		else
1136 			oldofile = NULL;
1137 		fdp->fd_ofiles = newofile;
1138 		fdp->fd_ofileflags = newofileflags;
1139 		fdp->fd_nfiles = nfiles;
1140 		fdexpand++;
1141 		if (oldofile != NULL) {
1142 			/* XXX uma_large_free() needs Giant. */
1143 			FILEDESC_UNLOCK(fdp);
1144 			mtx_lock(&Giant);
1145 			free(oldofile, M_FILEDESC);
1146 			mtx_unlock(&Giant);
1147 			FILEDESC_LOCK(fdp);
1148 		}
1149 	}
1150 }
1151 
1152 /*
1153  * Check to see whether n user file descriptors
1154  * are available to the process p.
1155  */
1156 int
1157 fdavail(td, n)
1158 	struct thread *td;
1159 	int n;
1160 {
1161 	struct proc *p = td->td_proc;
1162 	struct filedesc *fdp = td->td_proc->p_fd;
1163 	struct file **fpp;
1164 	int i, lim, last;
1165 
1166 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1167 
1168 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1169 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1170 		return (1);
1171 	last = min(fdp->fd_nfiles, lim);
1172 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1173 	for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1174 		if (*fpp == NULL && --n <= 0)
1175 			return (1);
1176 	}
1177 	return (0);
1178 }
1179 
1180 /*
1181  * Create a new open file structure and allocate
1182  * a file decriptor for the process that refers to it.
1183  */
1184 int
1185 falloc(td, resultfp, resultfd)
1186 	struct thread *td;
1187 	struct file **resultfp;
1188 	int *resultfd;
1189 {
1190 	struct proc *p = td->td_proc;
1191 	struct file *fp, *fq;
1192 	int error, i;
1193 
1194 	fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1195 	sx_xlock(&filelist_lock);
1196 	if (nfiles >= maxfiles) {
1197 		sx_xunlock(&filelist_lock);
1198 		uma_zfree(file_zone, fp);
1199 		tablefull("file");
1200 		return (ENFILE);
1201 	}
1202 	nfiles++;
1203 
1204 	/*
1205 	 * If the process has file descriptor zero open, add the new file
1206 	 * descriptor to the list of open files at that point, otherwise
1207 	 * put it at the front of the list of open files.
1208 	 */
1209 	fp->f_mtxp = mtx_pool_alloc();
1210 	fp->f_gcflag = 0;
1211 	fp->f_count = 1;
1212 	fp->f_cred = crhold(td->td_ucred);
1213 	fp->f_ops = &badfileops;
1214 	fp->f_seqcount = 1;
1215 	FILEDESC_LOCK(p->p_fd);
1216 	if ((fq = p->p_fd->fd_ofiles[0])) {
1217 		LIST_INSERT_AFTER(fq, fp, f_list);
1218 	} else {
1219 		LIST_INSERT_HEAD(&filehead, fp, f_list);
1220 	}
1221 	sx_xunlock(&filelist_lock);
1222 	if ((error = fdalloc(td, 0, &i))) {
1223 		FILEDESC_UNLOCK(p->p_fd);
1224 		fdrop(fp, td);
1225 		return (error);
1226 	}
1227 	p->p_fd->fd_ofiles[i] = fp;
1228 	FILEDESC_UNLOCK(p->p_fd);
1229 	if (resultfp)
1230 		*resultfp = fp;
1231 	if (resultfd)
1232 		*resultfd = i;
1233 	return (0);
1234 }
1235 
1236 /*
1237  * Free a file descriptor.
1238  */
1239 void
1240 ffree(fp)
1241 	struct file *fp;
1242 {
1243 
1244 	KASSERT(fp->f_count == 0, ("ffree: fp_fcount not 0!"));
1245 	sx_xlock(&filelist_lock);
1246 	LIST_REMOVE(fp, f_list);
1247 	nfiles--;
1248 	sx_xunlock(&filelist_lock);
1249 	crfree(fp->f_cred);
1250 	uma_zfree(file_zone, fp);
1251 }
1252 
1253 /*
1254  * Build a new filedesc structure from another.
1255  * Copy the current, root, and jail root vnode references.
1256  */
1257 struct filedesc *
1258 fdinit(fdp)
1259 	struct filedesc *fdp;
1260 {
1261 	struct filedesc0 *newfdp;
1262 
1263 	MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
1264 	    M_FILEDESC, M_WAITOK | M_ZERO);
1265 	mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1266 	newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1267 	if (newfdp->fd_fd.fd_cdir)
1268 		VREF(newfdp->fd_fd.fd_cdir);
1269 	newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1270 	if (newfdp->fd_fd.fd_rdir)
1271 		VREF(newfdp->fd_fd.fd_rdir);
1272 	newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1273 	if (newfdp->fd_fd.fd_jdir)
1274 		VREF(newfdp->fd_fd.fd_jdir);
1275 
1276 	/* Create the file descriptor table. */
1277 	newfdp->fd_fd.fd_refcnt = 1;
1278 	newfdp->fd_fd.fd_cmask = cmask;
1279 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1280 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1281 	newfdp->fd_fd.fd_nfiles = NDFILE;
1282 	newfdp->fd_fd.fd_knlistsize = -1;
1283 	return (&newfdp->fd_fd);
1284 }
1285 
1286 /*
1287  * Share a filedesc structure.
1288  */
1289 struct filedesc *
1290 fdshare(fdp)
1291 	struct filedesc *fdp;
1292 {
1293 	FILEDESC_LOCK(fdp);
1294 	fdp->fd_refcnt++;
1295 	FILEDESC_UNLOCK(fdp);
1296 	return (fdp);
1297 }
1298 
1299 /*
1300  * Copy a filedesc structure.
1301  * A NULL pointer in returns a NULL reference, this is to ease callers,
1302  * not catch errors.
1303  */
1304 struct filedesc *
1305 fdcopy(fdp)
1306 	struct filedesc *fdp;
1307 {
1308 	struct filedesc *newfdp;
1309 	struct file **fpp;
1310 	int i, j;
1311 
1312 	/* Certain daemons might not have file descriptors. */
1313 	if (fdp == NULL)
1314 		return (NULL);
1315 
1316 	FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1317 
1318 	FILEDESC_UNLOCK(fdp);
1319 	MALLOC(newfdp, struct filedesc *, sizeof(struct filedesc0),
1320 	    M_FILEDESC, M_WAITOK);
1321 	FILEDESC_LOCK(fdp);
1322 	bcopy(fdp, newfdp, sizeof(struct filedesc));
1323 	FILEDESC_UNLOCK(fdp);
1324 	bzero(&newfdp->fd_mtx, sizeof(newfdp->fd_mtx));
1325 	mtx_init(&newfdp->fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1326 	if (newfdp->fd_cdir)
1327 		VREF(newfdp->fd_cdir);
1328 	if (newfdp->fd_rdir)
1329 		VREF(newfdp->fd_rdir);
1330 	if (newfdp->fd_jdir)
1331 		VREF(newfdp->fd_jdir);
1332 	newfdp->fd_refcnt = 1;
1333 
1334 	/*
1335 	 * If the number of open files fits in the internal arrays
1336 	 * of the open file structure, use them, otherwise allocate
1337 	 * additional memory for the number of descriptors currently
1338 	 * in use.
1339 	 */
1340 	FILEDESC_LOCK(fdp);
1341 	newfdp->fd_lastfile = fdp->fd_lastfile;
1342 	newfdp->fd_nfiles = fdp->fd_nfiles;
1343 	if (newfdp->fd_lastfile < NDFILE) {
1344 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
1345 		newfdp->fd_ofileflags =
1346 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
1347 		i = NDFILE;
1348 	} else {
1349 		/*
1350 		 * Compute the smallest multiple of NDEXTENT needed
1351 		 * for the file descriptors currently in use,
1352 		 * allowing the table to shrink.
1353 		 */
1354 retry:
1355 		i = newfdp->fd_nfiles;
1356 		while (i > 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
1357 			i /= 2;
1358 		FILEDESC_UNLOCK(fdp);
1359 		MALLOC(newfdp->fd_ofiles, struct file **, i * OFILESIZE,
1360 		    M_FILEDESC, M_WAITOK);
1361 		FILEDESC_LOCK(fdp);
1362 		newfdp->fd_lastfile = fdp->fd_lastfile;
1363 		newfdp->fd_nfiles = fdp->fd_nfiles;
1364 		j = newfdp->fd_nfiles;
1365 		while (j > 2 * NDEXTENT && j > newfdp->fd_lastfile * 2)
1366 			j /= 2;
1367 		if (i != j) {
1368 			/*
1369 			 * The size of the original table has changed.
1370 			 * Go over once again.
1371 			 */
1372 			FILEDESC_UNLOCK(fdp);
1373 			FREE(newfdp->fd_ofiles, M_FILEDESC);
1374 			FILEDESC_LOCK(fdp);
1375 			newfdp->fd_lastfile = fdp->fd_lastfile;
1376 			newfdp->fd_nfiles = fdp->fd_nfiles;
1377 			goto retry;
1378 		}
1379 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
1380 	}
1381 	newfdp->fd_nfiles = i;
1382 	bcopy(fdp->fd_ofiles, newfdp->fd_ofiles, i * sizeof(struct file **));
1383 	bcopy(fdp->fd_ofileflags, newfdp->fd_ofileflags, i * sizeof(char));
1384 
1385 	/*
1386 	 * kq descriptors cannot be copied.
1387 	 */
1388 	if (newfdp->fd_knlistsize != -1) {
1389 		fpp = &newfdp->fd_ofiles[newfdp->fd_lastfile];
1390 		for (i = newfdp->fd_lastfile; i >= 0; i--, fpp--) {
1391 			if (*fpp != NULL && (*fpp)->f_type == DTYPE_KQUEUE) {
1392 				*fpp = NULL;
1393 				if (i < newfdp->fd_freefile)
1394 					newfdp->fd_freefile = i;
1395 			}
1396 			if (*fpp == NULL && i == newfdp->fd_lastfile && i > 0)
1397 				newfdp->fd_lastfile--;
1398 		}
1399 		newfdp->fd_knlist = NULL;
1400 		newfdp->fd_knlistsize = -1;
1401 		newfdp->fd_knhash = NULL;
1402 		newfdp->fd_knhashmask = 0;
1403 	}
1404 
1405 	fpp = newfdp->fd_ofiles;
1406 	for (i = newfdp->fd_lastfile; i-- >= 0; fpp++) {
1407 		if (*fpp != NULL)
1408 			fhold(*fpp);
1409 	}
1410 	return (newfdp);
1411 }
1412 
1413 /* A mutex to protect the association between a proc and filedesc. */
1414 struct mtx	fdesc_mtx;
1415 MTX_SYSINIT(fdesc, &fdesc_mtx, "fdesc", MTX_DEF);
1416 
1417 /*
1418  * Release a filedesc structure.
1419  */
1420 void
1421 fdfree(td)
1422 	struct thread *td;
1423 {
1424 	struct filedesc *fdp;
1425 	struct file **fpp;
1426 	int i;
1427 	struct filedesc_to_leader *fdtol;
1428 	struct file *fp;
1429 	struct vnode *vp;
1430 	struct flock lf;
1431 
1432 	/* Certain daemons might not have file descriptors. */
1433 	fdp = td->td_proc->p_fd;
1434 	if (fdp == NULL)
1435 		return;
1436 
1437 	/* Check for special need to clear POSIX style locks */
1438 	fdtol = td->td_proc->p_fdtol;
1439 	if (fdtol != NULL) {
1440 		FILEDESC_LOCK(fdp);
1441 		KASSERT(fdtol->fdl_refcount > 0,
1442 			("filedesc_to_refcount botch: fdl_refcount=%d",
1443 			 fdtol->fdl_refcount));
1444 		if (fdtol->fdl_refcount == 1 &&
1445 		    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1446 			i = 0;
1447 			fpp = fdp->fd_ofiles;
1448 			for (i = 0, fpp = fdp->fd_ofiles;
1449 			     i < fdp->fd_lastfile;
1450 			     i++, fpp++) {
1451 				if (*fpp == NULL ||
1452 				    (*fpp)->f_type != DTYPE_VNODE)
1453 					continue;
1454 				fp = *fpp;
1455 				fhold(fp);
1456 				FILEDESC_UNLOCK(fdp);
1457 				lf.l_whence = SEEK_SET;
1458 				lf.l_start = 0;
1459 				lf.l_len = 0;
1460 				lf.l_type = F_UNLCK;
1461 				vp = fp->f_data;
1462 				(void) VOP_ADVLOCK(vp,
1463 						   (caddr_t)td->td_proc->
1464 						   p_leader,
1465 						   F_UNLCK,
1466 						   &lf,
1467 						   F_POSIX);
1468 				FILEDESC_LOCK(fdp);
1469 				fdrop(fp, td);
1470 				fpp = fdp->fd_ofiles + i;
1471 			}
1472 		}
1473 	retry:
1474 		if (fdtol->fdl_refcount == 1) {
1475 			if (fdp->fd_holdleaderscount > 0 &&
1476 			    (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1477 				/*
1478 				 * close() or do_dup() has cleared a reference
1479 				 * in a shared file descriptor table.
1480 				 */
1481 				fdp->fd_holdleaderswakeup = 1;
1482 				msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
1483 				       PLOCK, "fdlhold", 0);
1484 				goto retry;
1485 			}
1486 			if (fdtol->fdl_holdcount > 0) {
1487 				/*
1488 				 * Ensure that fdtol->fdl_leader
1489 				 * remains valid in closef().
1490 				 */
1491 				fdtol->fdl_wakeup = 1;
1492 				msleep(fdtol, &fdp->fd_mtx,
1493 				       PLOCK, "fdlhold", 0);
1494 				goto retry;
1495 			}
1496 		}
1497 		fdtol->fdl_refcount--;
1498 		if (fdtol->fdl_refcount == 0 &&
1499 		    fdtol->fdl_holdcount == 0) {
1500 			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1501 			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1502 		} else
1503 			fdtol = NULL;
1504 		td->td_proc->p_fdtol = NULL;
1505 		FILEDESC_UNLOCK(fdp);
1506 		if (fdtol != NULL)
1507 			FREE(fdtol, M_FILEDESC_TO_LEADER);
1508 	}
1509 	FILEDESC_LOCK(fdp);
1510 	if (--fdp->fd_refcnt > 0) {
1511 		FILEDESC_UNLOCK(fdp);
1512 		return;
1513 	}
1514 
1515 	/*
1516 	 * We are the last reference to the structure, so we can
1517 	 * safely assume it will not change out from under us.
1518 	 */
1519 	FILEDESC_UNLOCK(fdp);
1520 	fpp = fdp->fd_ofiles;
1521 	for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1522 		if (*fpp)
1523 			(void) closef(*fpp, td);
1524 	}
1525 
1526 	/* XXX This should happen earlier. */
1527 	mtx_lock(&fdesc_mtx);
1528 	td->td_proc->p_fd = NULL;
1529 	mtx_unlock(&fdesc_mtx);
1530 
1531 	if (fdp->fd_nfiles > NDFILE)
1532 		FREE(fdp->fd_ofiles, M_FILEDESC);
1533 	if (fdp->fd_cdir)
1534 		vrele(fdp->fd_cdir);
1535 	if (fdp->fd_rdir)
1536 		vrele(fdp->fd_rdir);
1537 	if (fdp->fd_jdir)
1538 		vrele(fdp->fd_jdir);
1539 	if (fdp->fd_knlist)
1540 		FREE(fdp->fd_knlist, M_KQUEUE);
1541 	if (fdp->fd_knhash)
1542 		FREE(fdp->fd_knhash, M_KQUEUE);
1543 	mtx_destroy(&fdp->fd_mtx);
1544 	FREE(fdp, M_FILEDESC);
1545 }
1546 
1547 /*
1548  * For setugid programs, we don't want to people to use that setugidness
1549  * to generate error messages which write to a file which otherwise would
1550  * otherwise be off-limits to the process.  We check for filesystems where
1551  * the vnode can change out from under us after execve (like [lin]procfs).
1552  *
1553  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1554  * sufficient.  We also don't for check setugidness since we know we are.
1555  */
1556 static int
1557 is_unsafe(struct file *fp)
1558 {
1559 	if (fp->f_type == DTYPE_VNODE) {
1560 		struct vnode *vp = fp->f_data;
1561 
1562 		if ((vp->v_vflag & VV_PROCDEP) != 0)
1563 			return (1);
1564 	}
1565 	return (0);
1566 }
1567 
1568 /*
1569  * Make this setguid thing safe, if at all possible.
1570  */
1571 void
1572 setugidsafety(td)
1573 	struct thread *td;
1574 {
1575 	struct filedesc *fdp;
1576 	int i;
1577 
1578 	/* Certain daemons might not have file descriptors. */
1579 	fdp = td->td_proc->p_fd;
1580 	if (fdp == NULL)
1581 		return;
1582 
1583 	/*
1584 	 * Note: fdp->fd_ofiles may be reallocated out from under us while
1585 	 * we are blocked in a close.  Be careful!
1586 	 */
1587 	FILEDESC_LOCK(fdp);
1588 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1589 		if (i > 2)
1590 			break;
1591 		if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1592 			struct file *fp;
1593 
1594 #if 0
1595 			if ((fdp->fd_ofileflags[i] & UF_MAPPED) != 0)
1596 				(void) munmapfd(td, i);
1597 #endif
1598 			if (i < fdp->fd_knlistsize) {
1599 				FILEDESC_UNLOCK(fdp);
1600 				knote_fdclose(td, i);
1601 				FILEDESC_LOCK(fdp);
1602 			}
1603 			/*
1604 			 * NULL-out descriptor prior to close to avoid
1605 			 * a race while close blocks.
1606 			 */
1607 			fp = fdp->fd_ofiles[i];
1608 			fdp->fd_ofiles[i] = NULL;
1609 			fdp->fd_ofileflags[i] = 0;
1610 			if (i < fdp->fd_freefile)
1611 				fdp->fd_freefile = i;
1612 			FILEDESC_UNLOCK(fdp);
1613 			(void) closef(fp, td);
1614 			FILEDESC_LOCK(fdp);
1615 		}
1616 	}
1617 	while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1618 		fdp->fd_lastfile--;
1619 	FILEDESC_UNLOCK(fdp);
1620 }
1621 
1622 /*
1623  * Close any files on exec?
1624  */
1625 void
1626 fdcloseexec(td)
1627 	struct thread *td;
1628 {
1629 	struct filedesc *fdp;
1630 	int i;
1631 
1632 	/* Certain daemons might not have file descriptors. */
1633 	fdp = td->td_proc->p_fd;
1634 	if (fdp == NULL)
1635 		return;
1636 
1637 	FILEDESC_LOCK(fdp);
1638 
1639 	/*
1640 	 * We cannot cache fd_ofiles or fd_ofileflags since operations
1641 	 * may block and rip them out from under us.
1642 	 */
1643 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1644 		if (fdp->fd_ofiles[i] != NULL &&
1645 		    (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1646 			struct file *fp;
1647 
1648 #if 0
1649 			if (fdp->fd_ofileflags[i] & UF_MAPPED)
1650 				(void) munmapfd(td, i);
1651 #endif
1652 			if (i < fdp->fd_knlistsize) {
1653 				FILEDESC_UNLOCK(fdp);
1654 				knote_fdclose(td, i);
1655 				FILEDESC_LOCK(fdp);
1656 			}
1657 			/*
1658 			 * NULL-out descriptor prior to close to avoid
1659 			 * a race while close blocks.
1660 			 */
1661 			fp = fdp->fd_ofiles[i];
1662 			fdp->fd_ofiles[i] = NULL;
1663 			fdp->fd_ofileflags[i] = 0;
1664 			if (i < fdp->fd_freefile)
1665 				fdp->fd_freefile = i;
1666 			FILEDESC_UNLOCK(fdp);
1667 			(void) closef(fp, td);
1668 			FILEDESC_LOCK(fdp);
1669 		}
1670 	}
1671 	while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1672 		fdp->fd_lastfile--;
1673 	FILEDESC_UNLOCK(fdp);
1674 }
1675 
1676 /*
1677  * It is unsafe for set[ug]id processes to be started with file
1678  * descriptors 0..2 closed, as these descriptors are given implicit
1679  * significance in the Standard C library.  fdcheckstd() will create a
1680  * descriptor referencing /dev/null for each of stdin, stdout, and
1681  * stderr that is not already open.
1682  */
1683 int
1684 fdcheckstd(td)
1685 	struct thread *td;
1686 {
1687 	struct nameidata nd;
1688 	struct filedesc *fdp;
1689 	struct file *fp;
1690 	register_t retval;
1691 	int fd, i, error, flags, devnull;
1692 
1693 	fdp = td->td_proc->p_fd;
1694 	if (fdp == NULL)
1695 		return (0);
1696 	devnull = -1;
1697 	error = 0;
1698 	for (i = 0; i < 3; i++) {
1699 		if (fdp->fd_ofiles[i] != NULL)
1700 			continue;
1701 		if (devnull < 0) {
1702 			error = falloc(td, &fp, &fd);
1703 			if (error != 0)
1704 				break;
1705 			KASSERT(fd == i, ("oof, we didn't get our fd"));
1706 			NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null",
1707 			    td);
1708 			flags = FREAD | FWRITE;
1709 			error = vn_open(&nd, &flags, 0);
1710 			if (error != 0) {
1711 				FILEDESC_LOCK(fdp);
1712 				fdp->fd_ofiles[fd] = NULL;
1713 				FILEDESC_UNLOCK(fdp);
1714 				fdrop(fp, td);
1715 				break;
1716 			}
1717 			NDFREE(&nd, NDF_ONLY_PNBUF);
1718 			fp->f_data = nd.ni_vp;
1719 			fp->f_flag = flags;
1720 			fp->f_ops = &vnops;
1721 			fp->f_type = DTYPE_VNODE;
1722 			VOP_UNLOCK(nd.ni_vp, 0, td);
1723 			devnull = fd;
1724 		} else {
1725 			error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1726 			if (error != 0)
1727 				break;
1728 		}
1729 	}
1730 	return (error);
1731 }
1732 
1733 /*
1734  * Internal form of close.
1735  * Decrement reference count on file structure.
1736  * Note: td may be NULL when closing a file
1737  * that was being passed in a message.
1738  */
1739 int
1740 closef(fp, td)
1741 	struct file *fp;
1742 	struct thread *td;
1743 {
1744 	struct vnode *vp;
1745 	struct flock lf;
1746 	struct filedesc_to_leader *fdtol;
1747 	struct filedesc *fdp;
1748 
1749 	if (fp == NULL)
1750 		return (0);
1751 	/*
1752 	 * POSIX record locking dictates that any close releases ALL
1753 	 * locks owned by this process.  This is handled by setting
1754 	 * a flag in the unlock to free ONLY locks obeying POSIX
1755 	 * semantics, and not to free BSD-style file locks.
1756 	 * If the descriptor was in a message, POSIX-style locks
1757 	 * aren't passed with the descriptor.
1758 	 */
1759 	if (td != NULL &&
1760 	    fp->f_type == DTYPE_VNODE) {
1761 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1762 			lf.l_whence = SEEK_SET;
1763 			lf.l_start = 0;
1764 			lf.l_len = 0;
1765 			lf.l_type = F_UNLCK;
1766 			vp = fp->f_data;
1767 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1768 					   F_UNLCK, &lf, F_POSIX);
1769 		}
1770 		fdtol = td->td_proc->p_fdtol;
1771 		if (fdtol != NULL) {
1772 			/*
1773 			 * Handle special case where file descriptor table
1774 			 * is shared between multiple process leaders.
1775 			 */
1776 			fdp = td->td_proc->p_fd;
1777 			FILEDESC_LOCK(fdp);
1778 			for (fdtol = fdtol->fdl_next;
1779 			     fdtol != td->td_proc->p_fdtol;
1780 			     fdtol = fdtol->fdl_next) {
1781 				if ((fdtol->fdl_leader->p_flag &
1782 				     P_ADVLOCK) == 0)
1783 					continue;
1784 				fdtol->fdl_holdcount++;
1785 				FILEDESC_UNLOCK(fdp);
1786 				lf.l_whence = SEEK_SET;
1787 				lf.l_start = 0;
1788 				lf.l_len = 0;
1789 				lf.l_type = F_UNLCK;
1790 				vp = fp->f_data;
1791 				(void) VOP_ADVLOCK(vp,
1792 						   (caddr_t)fdtol->fdl_leader,
1793 						   F_UNLCK, &lf, F_POSIX);
1794 				FILEDESC_LOCK(fdp);
1795 				fdtol->fdl_holdcount--;
1796 				if (fdtol->fdl_holdcount == 0 &&
1797 				    fdtol->fdl_wakeup != 0) {
1798 					fdtol->fdl_wakeup = 0;
1799 					wakeup(fdtol);
1800 				}
1801 			}
1802 			FILEDESC_UNLOCK(fdp);
1803 		}
1804 	}
1805 	return (fdrop(fp, td));
1806 }
1807 
1808 /*
1809  * Drop reference on struct file passed in, may call closef if the
1810  * reference hits zero.
1811  */
1812 int
1813 fdrop(fp, td)
1814 	struct file *fp;
1815 	struct thread *td;
1816 {
1817 
1818 	FILE_LOCK(fp);
1819 	return (fdrop_locked(fp, td));
1820 }
1821 
1822 /*
1823  * Extract the file pointer associated with the specified descriptor for
1824  * the current user process.
1825  *
1826  * If the descriptor doesn't exist, EBADF is returned.
1827  *
1828  * If the descriptor exists but doesn't match 'flags' then
1829  * return EBADF for read attempts and EINVAL for write attempts.
1830  *
1831  * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1832  * It should be droped with fdrop().
1833  * If it is not set, then the refcount will not be bumped however the
1834  * thread's filedesc struct will be returned locked (for fgetsock).
1835  *
1836  * If an error occured the non-zero error is returned and *fpp is set to NULL.
1837  * Otherwise *fpp is set and zero is returned.
1838  */
1839 static __inline int
1840 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1841 {
1842 	struct filedesc *fdp;
1843 	struct file *fp;
1844 
1845 	*fpp = NULL;
1846 	if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1847 		return (EBADF);
1848 	FILEDESC_LOCK(fdp);
1849 	if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1850 		FILEDESC_UNLOCK(fdp);
1851 		return (EBADF);
1852 	}
1853 
1854 	/*
1855 	 * Note: FREAD failures returns EBADF to maintain backwards
1856 	 * compatibility with what routines returned before.
1857 	 *
1858 	 * Only one flag, or 0, may be specified.
1859 	 */
1860 	if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1861 		FILEDESC_UNLOCK(fdp);
1862 		return (EBADF);
1863 	}
1864 	if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
1865 		FILEDESC_UNLOCK(fdp);
1866 		return (EINVAL);
1867 	}
1868 	if (hold) {
1869 		fhold(fp);
1870 		FILEDESC_UNLOCK(fdp);
1871 	}
1872 	*fpp = fp;
1873 	return (0);
1874 }
1875 
1876 int
1877 fget(struct thread *td, int fd, struct file **fpp)
1878 {
1879 
1880 	return(_fget(td, fd, fpp, 0, 1));
1881 }
1882 
1883 int
1884 fget_read(struct thread *td, int fd, struct file **fpp)
1885 {
1886 
1887 	return(_fget(td, fd, fpp, FREAD, 1));
1888 }
1889 
1890 int
1891 fget_write(struct thread *td, int fd, struct file **fpp)
1892 {
1893 
1894 	return(_fget(td, fd, fpp, FWRITE, 1));
1895 }
1896 
1897 /*
1898  * Like fget() but loads the underlying vnode, or returns an error if
1899  * the descriptor does not represent a vnode.  Note that pipes use vnodes
1900  * but never have VM objects (so VOP_GETVOBJECT() calls will return an
1901  * error).  The returned vnode will be vref()d.
1902  */
1903 static __inline int
1904 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
1905 {
1906 	struct file *fp;
1907 	int error;
1908 
1909 	*vpp = NULL;
1910 	if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
1911 		return (error);
1912 	if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
1913 		error = EINVAL;
1914 	} else {
1915 		*vpp = fp->f_data;
1916 		vref(*vpp);
1917 	}
1918 	FILEDESC_UNLOCK(td->td_proc->p_fd);
1919 	return (error);
1920 }
1921 
1922 int
1923 fgetvp(struct thread *td, int fd, struct vnode **vpp)
1924 {
1925 
1926 	return (_fgetvp(td, fd, vpp, 0));
1927 }
1928 
1929 int
1930 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
1931 {
1932 
1933 	return (_fgetvp(td, fd, vpp, FREAD));
1934 }
1935 
1936 int
1937 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
1938 {
1939 
1940 	return (_fgetvp(td, fd, vpp, FWRITE));
1941 }
1942 
1943 /*
1944  * Like fget() but loads the underlying socket, or returns an error if
1945  * the descriptor does not represent a socket.
1946  *
1947  * We bump the ref count on the returned socket.  XXX Also obtain the SX
1948  * lock in the future.
1949  */
1950 int
1951 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
1952 {
1953 	struct file *fp;
1954 	int error;
1955 
1956 	*spp = NULL;
1957 	if (fflagp != NULL)
1958 		*fflagp = 0;
1959 	if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
1960 		return (error);
1961 	if (fp->f_type != DTYPE_SOCKET) {
1962 		error = ENOTSOCK;
1963 	} else {
1964 		*spp = fp->f_data;
1965 		if (fflagp)
1966 			*fflagp = fp->f_flag;
1967 		soref(*spp);
1968 	}
1969 	FILEDESC_UNLOCK(td->td_proc->p_fd);
1970 	return (error);
1971 }
1972 
1973 /*
1974  * Drop the reference count on the the socket and XXX release the SX lock in
1975  * the future.  The last reference closes the socket.
1976  */
1977 void
1978 fputsock(struct socket *so)
1979 {
1980 
1981 	sorele(so);
1982 }
1983 
1984 /*
1985  * Drop reference on struct file passed in, may call closef if the
1986  * reference hits zero.
1987  * Expects struct file locked, and will unlock it.
1988  */
1989 int
1990 fdrop_locked(fp, td)
1991 	struct file *fp;
1992 	struct thread *td;
1993 {
1994 	struct flock lf;
1995 	struct vnode *vp;
1996 	int error;
1997 
1998 	FILE_LOCK_ASSERT(fp, MA_OWNED);
1999 
2000 	if (--fp->f_count > 0) {
2001 		FILE_UNLOCK(fp);
2002 		return (0);
2003 	}
2004 	mtx_lock(&Giant);
2005 	if (fp->f_count < 0)
2006 		panic("fdrop: count < 0");
2007 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
2008 		lf.l_whence = SEEK_SET;
2009 		lf.l_start = 0;
2010 		lf.l_len = 0;
2011 		lf.l_type = F_UNLCK;
2012 		vp = fp->f_data;
2013 		FILE_UNLOCK(fp);
2014 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2015 	} else
2016 		FILE_UNLOCK(fp);
2017 	if (fp->f_ops != &badfileops)
2018 		error = fo_close(fp, td);
2019 	else
2020 		error = 0;
2021 	ffree(fp);
2022 	mtx_unlock(&Giant);
2023 	return (error);
2024 }
2025 
2026 /*
2027  * Apply an advisory lock on a file descriptor.
2028  *
2029  * Just attempt to get a record lock of the requested type on
2030  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2031  */
2032 #ifndef _SYS_SYSPROTO_H_
2033 struct flock_args {
2034 	int	fd;
2035 	int	how;
2036 };
2037 #endif
2038 /*
2039  * MPSAFE
2040  */
2041 /* ARGSUSED */
2042 int
2043 flock(td, uap)
2044 	struct thread *td;
2045 	struct flock_args *uap;
2046 {
2047 	struct file *fp;
2048 	struct vnode *vp;
2049 	struct flock lf;
2050 	int error;
2051 
2052 	if ((error = fget(td, uap->fd, &fp)) != 0)
2053 		return (error);
2054 	if (fp->f_type != DTYPE_VNODE) {
2055 		fdrop(fp, td);
2056 		return (EOPNOTSUPP);
2057 	}
2058 
2059 	mtx_lock(&Giant);
2060 	vp = fp->f_data;
2061 	lf.l_whence = SEEK_SET;
2062 	lf.l_start = 0;
2063 	lf.l_len = 0;
2064 	if (uap->how & LOCK_UN) {
2065 		lf.l_type = F_UNLCK;
2066 		FILE_LOCK(fp);
2067 		fp->f_flag &= ~FHASLOCK;
2068 		FILE_UNLOCK(fp);
2069 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2070 		goto done2;
2071 	}
2072 	if (uap->how & LOCK_EX)
2073 		lf.l_type = F_WRLCK;
2074 	else if (uap->how & LOCK_SH)
2075 		lf.l_type = F_RDLCK;
2076 	else {
2077 		error = EBADF;
2078 		goto done2;
2079 	}
2080 	FILE_LOCK(fp);
2081 	fp->f_flag |= FHASLOCK;
2082 	FILE_UNLOCK(fp);
2083 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2084 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2085 done2:
2086 	fdrop(fp, td);
2087 	mtx_unlock(&Giant);
2088 	return (error);
2089 }
2090 
2091 /*
2092  * File Descriptor pseudo-device driver (/dev/fd/).
2093  *
2094  * Opening minor device N dup()s the file (if any) connected to file
2095  * descriptor N belonging to the calling process.  Note that this driver
2096  * consists of only the ``open()'' routine, because all subsequent
2097  * references to this file will be direct to the other driver.
2098  */
2099 /* ARGSUSED */
2100 static int
2101 fdopen(dev, mode, type, td)
2102 	dev_t dev;
2103 	int mode, type;
2104 	struct thread *td;
2105 {
2106 
2107 	/*
2108 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2109 	 * the file descriptor being sought for duplication. The error
2110 	 * return ensures that the vnode for this device will be released
2111 	 * by vn_open. Open will detect this special error and take the
2112 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2113 	 * will simply report the error.
2114 	 */
2115 	td->td_dupfd = dev2unit(dev);
2116 	return (ENODEV);
2117 }
2118 
2119 /*
2120  * Duplicate the specified descriptor to a free descriptor.
2121  */
2122 int
2123 dupfdopen(td, fdp, indx, dfd, mode, error)
2124 	struct thread *td;
2125 	struct filedesc *fdp;
2126 	int indx, dfd;
2127 	int mode;
2128 	int error;
2129 {
2130 	struct file *wfp;
2131 	struct file *fp;
2132 
2133 	/*
2134 	 * If the to-be-dup'd fd number is greater than the allowed number
2135 	 * of file descriptors, or the fd to be dup'd has already been
2136 	 * closed, then reject.
2137 	 */
2138 	FILEDESC_LOCK(fdp);
2139 	if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2140 	    (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2141 		FILEDESC_UNLOCK(fdp);
2142 		return (EBADF);
2143 	}
2144 
2145 	/*
2146 	 * There are two cases of interest here.
2147 	 *
2148 	 * For ENODEV simply dup (dfd) to file descriptor
2149 	 * (indx) and return.
2150 	 *
2151 	 * For ENXIO steal away the file structure from (dfd) and
2152 	 * store it in (indx).  (dfd) is effectively closed by
2153 	 * this operation.
2154 	 *
2155 	 * Any other error code is just returned.
2156 	 */
2157 	switch (error) {
2158 	case ENODEV:
2159 		/*
2160 		 * Check that the mode the file is being opened for is a
2161 		 * subset of the mode of the existing descriptor.
2162 		 */
2163 		FILE_LOCK(wfp);
2164 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2165 			FILE_UNLOCK(wfp);
2166 			FILEDESC_UNLOCK(fdp);
2167 			return (EACCES);
2168 		}
2169 		fp = fdp->fd_ofiles[indx];
2170 #if 0
2171 		if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
2172 			(void) munmapfd(td, indx);
2173 #endif
2174 		fdp->fd_ofiles[indx] = wfp;
2175 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2176 		fhold_locked(wfp);
2177 		FILE_UNLOCK(wfp);
2178 		if (indx > fdp->fd_lastfile)
2179 			fdp->fd_lastfile = indx;
2180 		if (fp != NULL)
2181 			FILE_LOCK(fp);
2182 		FILEDESC_UNLOCK(fdp);
2183 		/*
2184 		 * We now own the reference to fp that the ofiles[] array
2185 		 * used to own.  Release it.
2186 		 */
2187 		if (fp != NULL)
2188 			fdrop_locked(fp, td);
2189 		return (0);
2190 
2191 	case ENXIO:
2192 		/*
2193 		 * Steal away the file pointer from dfd and stuff it into indx.
2194 		 */
2195 		fp = fdp->fd_ofiles[indx];
2196 #if 0
2197 		if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
2198 			(void) munmapfd(td, indx);
2199 #endif
2200 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2201 		fdp->fd_ofiles[dfd] = NULL;
2202 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2203 		fdp->fd_ofileflags[dfd] = 0;
2204 
2205 		/*
2206 		 * Complete the clean up of the filedesc structure by
2207 		 * recomputing the various hints.
2208 		 */
2209 		if (indx > fdp->fd_lastfile) {
2210 			fdp->fd_lastfile = indx;
2211 		} else {
2212 			while (fdp->fd_lastfile > 0 &&
2213 			   fdp->fd_ofiles[fdp->fd_lastfile] == NULL) {
2214 				fdp->fd_lastfile--;
2215 			}
2216 			if (dfd < fdp->fd_freefile)
2217 				fdp->fd_freefile = dfd;
2218 		}
2219 		if (fp != NULL)
2220 			FILE_LOCK(fp);
2221 		FILEDESC_UNLOCK(fdp);
2222 
2223 		/*
2224 		 * we now own the reference to fp that the ofiles[] array
2225 		 * used to own.  Release it.
2226 		 */
2227 		if (fp != NULL)
2228 			fdrop_locked(fp, td);
2229 		return (0);
2230 
2231 	default:
2232 		FILEDESC_UNLOCK(fdp);
2233 		return (error);
2234 	}
2235 	/* NOTREACHED */
2236 }
2237 
2238 
2239 struct filedesc_to_leader *
2240 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2241 			 struct filedesc *fdp,
2242 			 struct proc *leader)
2243 {
2244 	struct filedesc_to_leader *fdtol;
2245 
2246 	MALLOC(fdtol, struct filedesc_to_leader *,
2247 	       sizeof(struct filedesc_to_leader),
2248 	       M_FILEDESC_TO_LEADER,
2249 	       M_WAITOK);
2250 	fdtol->fdl_refcount = 1;
2251 	fdtol->fdl_holdcount = 0;
2252 	fdtol->fdl_wakeup = 0;
2253 	fdtol->fdl_leader = leader;
2254 	if (old != NULL) {
2255 		FILEDESC_LOCK(fdp);
2256 		fdtol->fdl_next = old->fdl_next;
2257 		fdtol->fdl_prev = old;
2258 		old->fdl_next = fdtol;
2259 		fdtol->fdl_next->fdl_prev = fdtol;
2260 		FILEDESC_UNLOCK(fdp);
2261 	} else {
2262 		fdtol->fdl_next = fdtol;
2263 		fdtol->fdl_prev = fdtol;
2264 	}
2265 	return fdtol;
2266 }
2267 
2268 /*
2269  * Get file structures.
2270  */
2271 static int
2272 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2273 {
2274 	struct xfile xf;
2275 	struct filedesc *fdp;
2276 	struct file *fp;
2277 	struct proc *p;
2278 	int error, n;
2279 
2280 	sysctl_wire_old_buffer(req, 0);
2281 	if (req->oldptr == NULL) {
2282 		n = 16;		/* A slight overestimate. */
2283 		sx_slock(&filelist_lock);
2284 		LIST_FOREACH(fp, &filehead, f_list) {
2285 			/*
2286 			 * We should grab the lock, but this is an
2287 			 * estimate, so does it really matter?
2288 			 */
2289 			/* mtx_lock(fp->f_mtxp); */
2290 			n += fp->f_count;
2291 			/* mtx_unlock(f->f_mtxp); */
2292 		}
2293 		sx_sunlock(&filelist_lock);
2294 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2295 	}
2296 	error = 0;
2297 	bzero(&xf, sizeof(xf));
2298 	xf.xf_size = sizeof(xf);
2299 	sx_slock(&allproc_lock);
2300 	LIST_FOREACH(p, &allproc, p_list) {
2301 		PROC_LOCK(p);
2302 		xf.xf_pid = p->p_pid;
2303 		xf.xf_uid = p->p_ucred->cr_uid;
2304 		PROC_UNLOCK(p);
2305 		mtx_lock(&fdesc_mtx);
2306 		if ((fdp = p->p_fd) == NULL) {
2307 			mtx_unlock(&fdesc_mtx);
2308 			continue;
2309 		}
2310 		FILEDESC_LOCK(fdp);
2311 		for (n = 0; n < fdp->fd_nfiles; ++n) {
2312 			if ((fp = fdp->fd_ofiles[n]) == NULL)
2313 				continue;
2314 			xf.xf_fd = n;
2315 			xf.xf_file = fp;
2316 			xf.xf_data = fp->f_data;
2317 			xf.xf_type = fp->f_type;
2318 			xf.xf_count = fp->f_count;
2319 			xf.xf_msgcount = fp->f_msgcount;
2320 			xf.xf_offset = fp->f_offset;
2321 			xf.xf_flag = fp->f_flag;
2322 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
2323 			if (error)
2324 				break;
2325 		}
2326 		FILEDESC_UNLOCK(fdp);
2327 		mtx_unlock(&fdesc_mtx);
2328 		if (error)
2329 			break;
2330 	}
2331 	sx_sunlock(&allproc_lock);
2332 	return (error);
2333 }
2334 
2335 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2336     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2337 
2338 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2339     &maxfilesperproc, 0, "Maximum files allowed open per process");
2340 
2341 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2342     &maxfiles, 0, "Maximum number of files");
2343 
2344 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2345     &nfiles, 0, "System-wide number of open files");
2346 
2347 static void
2348 fildesc_drvinit(void *unused)
2349 {
2350 	dev_t dev;
2351 
2352 	dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2353 	make_dev_alias(dev, "stdin");
2354 	dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2355 	make_dev_alias(dev, "stdout");
2356 	dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2357 	make_dev_alias(dev, "stderr");
2358 }
2359 
2360 static fo_rdwr_t	badfo_readwrite;
2361 static fo_ioctl_t	badfo_ioctl;
2362 static fo_poll_t	badfo_poll;
2363 static fo_kqfilter_t	badfo_kqfilter;
2364 static fo_stat_t	badfo_stat;
2365 static fo_close_t	badfo_close;
2366 
2367 struct fileops badfileops = {
2368 	badfo_readwrite,
2369 	badfo_readwrite,
2370 	badfo_ioctl,
2371 	badfo_poll,
2372 	badfo_kqfilter,
2373 	badfo_stat,
2374 	badfo_close,
2375 	0
2376 };
2377 
2378 static int
2379 badfo_readwrite(fp, uio, active_cred, flags, td)
2380 	struct file *fp;
2381 	struct uio *uio;
2382 	struct ucred *active_cred;
2383 	struct thread *td;
2384 	int flags;
2385 {
2386 
2387 	return (EBADF);
2388 }
2389 
2390 static int
2391 badfo_ioctl(fp, com, data, active_cred, td)
2392 	struct file *fp;
2393 	u_long com;
2394 	void *data;
2395 	struct ucred *active_cred;
2396 	struct thread *td;
2397 {
2398 
2399 	return (EBADF);
2400 }
2401 
2402 static int
2403 badfo_poll(fp, events, active_cred, td)
2404 	struct file *fp;
2405 	int events;
2406 	struct ucred *active_cred;
2407 	struct thread *td;
2408 {
2409 
2410 	return (0);
2411 }
2412 
2413 static int
2414 badfo_kqfilter(fp, kn)
2415 	struct file *fp;
2416 	struct knote *kn;
2417 {
2418 
2419 	return (0);
2420 }
2421 
2422 static int
2423 badfo_stat(fp, sb, active_cred, td)
2424 	struct file *fp;
2425 	struct stat *sb;
2426 	struct ucred *active_cred;
2427 	struct thread *td;
2428 {
2429 
2430 	return (EBADF);
2431 }
2432 
2433 static int
2434 badfo_close(fp, td)
2435 	struct file *fp;
2436 	struct thread *td;
2437 {
2438 
2439 	return (EBADF);
2440 }
2441 
2442 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2443 					fildesc_drvinit,NULL)
2444 
2445 static void filelistinit(void *);
2446 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2447 
2448 /* ARGSUSED*/
2449 static void
2450 filelistinit(dummy)
2451 	void *dummy;
2452 {
2453 
2454 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2455 	    NULL, NULL, UMA_ALIGN_PTR, 0);
2456 	sx_init(&filelist_lock, "filelist lock");
2457 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2458 }
2459