xref: /dragonfly/sys/kern/kern_descrip.c (revision aa8d5dcb)
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: src/sys/kern/kern_descrip.c,v 1.81.2.17 2003/06/06 20:21:32 tegge Exp $
40  * $DragonFly: src/sys/kern/kern_descrip.c,v 1.19 2004/03/01 06:33:17 dillon Exp $
41  */
42 
43 #include "opt_compat.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/malloc.h>
47 #include <sys/sysproto.h>
48 #include <sys/conf.h>
49 #include <sys/filedesc.h>
50 #include <sys/kernel.h>
51 #include <sys/sysctl.h>
52 #include <sys/vnode.h>
53 #include <sys/proc.h>
54 #include <sys/namei.h>
55 #include <sys/file.h>
56 #include <sys/stat.h>
57 #include <sys/filio.h>
58 #include <sys/fcntl.h>
59 #include <sys/unistd.h>
60 #include <sys/resourcevar.h>
61 #include <sys/event.h>
62 #include <sys/kern_syscall.h>
63 
64 #include <vm/vm.h>
65 #include <vm/vm_extern.h>
66 
67 #include <sys/file2.h>
68 
69 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
70 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
71 		     "file desc to leader structures");
72 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
73 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
74 
75 static	 d_open_t  fdopen;
76 #define NUMFDESC 64
77 
78 #define CDEV_MAJOR 22
79 static struct cdevsw fildesc_cdevsw = {
80 	/* name */	"FD",
81 	/* maj */	CDEV_MAJOR,
82 	/* flags */	0,
83 	/* port */      NULL,
84 	/* autoq */	0,
85 
86 	/* open */	fdopen,
87 	/* close */	noclose,
88 	/* read */	noread,
89 	/* write */	nowrite,
90 	/* ioctl */	noioctl,
91 	/* poll */	nopoll,
92 	/* mmap */	nommap,
93 	/* strategy */	nostrategy,
94 	/* dump */	nodump,
95 	/* psize */	nopsize
96 };
97 
98 static int badfo_readwrite (struct file *fp, struct uio *uio,
99     struct ucred *cred, int flags, struct thread *td);
100 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
101     struct thread *td);
102 static int badfo_poll (struct file *fp, int events,
103     struct ucred *cred, struct thread *td);
104 static int badfo_kqfilter (struct file *fp, struct knote *kn);
105 static int badfo_stat (struct file *fp, struct stat *sb, struct thread *td);
106 static int badfo_close (struct file *fp, struct thread *td);
107 
108 /*
109  * Descriptor management.
110  */
111 struct filelist filehead;	/* head of list of open files */
112 int nfiles;			/* actual number of open files */
113 extern int cmask;
114 
115 /*
116  * System calls on descriptors.
117  */
118 /* ARGSUSED */
119 int
120 getdtablesize(struct getdtablesize_args *uap)
121 {
122 	struct proc *p = curproc;
123 
124 	uap->sysmsg_result =
125 	    min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
126 	return (0);
127 }
128 
129 /*
130  * Duplicate a file descriptor to a particular value.
131  *
132  * note: keep in mind that a potential race condition exists when closing
133  * descriptors from a shared descriptor table (via rfork).
134  */
135 /* ARGSUSED */
136 int
137 dup2(struct dup2_args *uap)
138 {
139 	int error;
140 
141 	error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
142 
143 	return (error);
144 }
145 
146 /*
147  * Duplicate a file descriptor.
148  */
149 /* ARGSUSED */
150 int
151 dup(struct dup_args *uap)
152 {
153 	int error;
154 
155 	error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
156 
157 	return (error);
158 }
159 
160 int
161 kern_fcntl(int fd, int cmd, union fcntl_dat *dat)
162 {
163 	struct thread *td = curthread;
164 	struct proc *p = td->td_proc;
165 	struct filedesc *fdp = p->p_fd;
166 	struct file *fp;
167 	char *pop;
168 	struct vnode *vp;
169 	u_int newmin;
170 	int tmp, error, flg = F_POSIX;
171 
172 	KKASSERT(p);
173 
174 	if ((unsigned)fd >= fdp->fd_nfiles ||
175 	    (fp = fdp->fd_ofiles[fd]) == NULL)
176 		return (EBADF);
177 	pop = &fdp->fd_ofileflags[fd];
178 
179 	switch (cmd) {
180 	case F_DUPFD:
181 		newmin = dat->fc_fd;
182 		if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
183 		    newmin > maxfilesperproc)
184 			return (EINVAL);
185 		error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
186 		return (error);
187 
188 	case F_GETFD:
189 		dat->fc_cloexec = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
190 		return (0);
191 
192 	case F_SETFD:
193 		*pop = (*pop &~ UF_EXCLOSE) |
194 		    (dat->fc_cloexec & FD_CLOEXEC ? UF_EXCLOSE : 0);
195 		return (0);
196 
197 	case F_GETFL:
198 		dat->fc_flags = OFLAGS(fp->f_flag);
199 		return (0);
200 
201 	case F_SETFL:
202 		fhold(fp);
203 		fp->f_flag &= ~FCNTLFLAGS;
204 		fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
205 		tmp = fp->f_flag & FNONBLOCK;
206 		error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
207 		if (error) {
208 			fdrop(fp, td);
209 			return (error);
210 		}
211 		tmp = fp->f_flag & FASYNC;
212 		error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, td);
213 		if (!error) {
214 			fdrop(fp, td);
215 			return (0);
216 		}
217 		fp->f_flag &= ~FNONBLOCK;
218 		tmp = 0;
219 		fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
220 		fdrop(fp, td);
221 		return (error);
222 
223 	case F_GETOWN:
224 		fhold(fp);
225 		error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, td);
226 		fdrop(fp, td);
227 		return(error);
228 
229 	case F_SETOWN:
230 		fhold(fp);
231 		error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, td);
232 		fdrop(fp, td);
233 		return(error);
234 
235 	case F_SETLKW:
236 		flg |= F_WAIT;
237 		/* Fall into F_SETLK */
238 
239 	case F_SETLK:
240 		if (fp->f_type != DTYPE_VNODE)
241 			return (EBADF);
242 		vp = (struct vnode *)fp->f_data;
243 
244 		/*
245 		 * copyin/lockop may block
246 		 */
247 		fhold(fp);
248 		if (dat->fc_flock.l_whence == SEEK_CUR)
249 			dat->fc_flock.l_start += fp->f_offset;
250 
251 		switch (dat->fc_flock.l_type) {
252 		case F_RDLCK:
253 			if ((fp->f_flag & FREAD) == 0) {
254 				error = EBADF;
255 				break;
256 			}
257 			p->p_leader->p_flag |= P_ADVLOCK;
258 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
259 			    &dat->fc_flock, flg);
260 			break;
261 		case F_WRLCK:
262 			if ((fp->f_flag & FWRITE) == 0) {
263 				error = EBADF;
264 				break;
265 			}
266 			p->p_leader->p_flag |= P_ADVLOCK;
267 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
268 			    &dat->fc_flock, flg);
269 			break;
270 		case F_UNLCK:
271 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
272 				&dat->fc_flock, F_POSIX);
273 			break;
274 		default:
275 			error = EINVAL;
276 			break;
277 		}
278 		/* Check for race with close */
279 		if ((unsigned) fd >= fdp->fd_nfiles ||
280 		    fp != fdp->fd_ofiles[fd]) {
281 			dat->fc_flock.l_whence = SEEK_SET;
282 			dat->fc_flock.l_start = 0;
283 			dat->fc_flock.l_len = 0;
284 			dat->fc_flock.l_type = F_UNLCK;
285 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
286 					   F_UNLCK, &dat->fc_flock, F_POSIX);
287 		}
288 		fdrop(fp, td);
289 		return(error);
290 
291 	case F_GETLK:
292 		if (fp->f_type != DTYPE_VNODE)
293 			return (EBADF);
294 		vp = (struct vnode *)fp->f_data;
295 		/*
296 		 * copyin/lockop may block
297 		 */
298 		fhold(fp);
299 		if (dat->fc_flock.l_type != F_RDLCK &&
300 		    dat->fc_flock.l_type != F_WRLCK &&
301 		    dat->fc_flock.l_type != F_UNLCK) {
302 			fdrop(fp, td);
303 			return (EINVAL);
304 		}
305 		if (dat->fc_flock.l_whence == SEEK_CUR)
306 			dat->fc_flock.l_start += fp->f_offset;
307 		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
308 			    &dat->fc_flock, F_POSIX);
309 		fdrop(fp, td);
310 		return(error);
311 	default:
312 		return (EINVAL);
313 	}
314 	/* NOTREACHED */
315 }
316 
317 /*
318  * The file control system call.
319  */
320 int
321 fcntl(struct fcntl_args *uap)
322 {
323 	union fcntl_dat dat;
324 	int error;
325 
326 	switch (uap->cmd) {
327 	case F_DUPFD:
328 		dat.fc_fd = uap->arg;
329 		break;
330 	case F_SETFD:
331 		dat.fc_cloexec = uap->arg;
332 		break;
333 	case F_SETFL:
334 		dat.fc_flags = uap->arg;
335 		break;
336 	case F_SETOWN:
337 		dat.fc_owner = uap->arg;
338 		break;
339 	case F_SETLKW:
340 	case F_SETLK:
341 	case F_GETLK:
342 		error = copyin((caddr_t)uap->arg, &dat.fc_flock,
343 		    sizeof(struct flock));
344 		if (error)
345 			return (error);
346 		break;
347 	}
348 
349 	error = kern_fcntl(uap->fd, uap->cmd, &dat);
350 
351 	if (error == 0) {
352 		switch (uap->cmd) {
353 		case F_DUPFD:
354 			uap->sysmsg_result = dat.fc_fd;
355 			break;
356 		case F_GETFD:
357 			uap->sysmsg_result = dat.fc_cloexec;
358 			break;
359 		case F_GETFL:
360 			uap->sysmsg_result = dat.fc_flags;
361 			break;
362 		case F_GETOWN:
363 			uap->sysmsg_result = dat.fc_owner;
364 		case F_GETLK:
365 			error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
366 			    sizeof(struct flock));
367 			break;
368 		}
369 	}
370 
371 	return (error);
372 }
373 
374 /*
375  * Common code for dup, dup2, and fcntl(F_DUPFD).
376  *
377  * The type flag can be either DUP_FIXED or DUP_VARIABLE.  DUP_FIXED tells
378  * kern_dup() to destructively dup over an existing file descriptor if new
379  * is already open.  DUP_VARIABLE tells kern_dup() to find the lowest
380  * unused file descriptor that is greater than or equal to new.
381  */
382 int
383 kern_dup(enum dup_type type, int old, int new, int *res)
384 {
385 	struct thread *td = curthread;
386 	struct proc *p = td->td_proc;
387 	struct filedesc *fdp = p->p_fd;
388 	struct file *fp;
389 	struct file *delfp;
390 	int holdleaders;
391 	int error, newfd;
392 
393 	/*
394 	 * Verify that we have a valid descriptor to dup from and
395 	 * possibly to dup to.
396 	 */
397 	if (old < 0 || new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
398 	    new >= maxfilesperproc)
399 		return (EBADF);
400 	if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL)
401 		return (EBADF);
402 	if (type == DUP_FIXED && old == new) {
403 		*res = new;
404 		return (0);
405 	}
406 	fp = fdp->fd_ofiles[old];
407 	fhold(fp);
408 
409 	/*
410 	 * Expand the table for the new descriptor if needed.  This may
411 	 * block and drop and reacquire the fidedesc lock.
412 	 */
413 	if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
414 		error = fdalloc(p, new, &newfd);
415 		if (error) {
416 			fdrop(fp, td);
417 			return (error);
418 		}
419 	}
420 	if (type == DUP_VARIABLE)
421 		new = newfd;
422 
423 	/*
424 	 * If the old file changed out from under us then treat it as a
425 	 * bad file descriptor.  Userland should do its own locking to
426 	 * avoid this case.
427 	 */
428 	if (fdp->fd_ofiles[old] != fp) {
429 		if (fdp->fd_ofiles[new] == NULL) {
430 			if (new < fdp->fd_freefile)
431 				fdp->fd_freefile = new;
432 			while (fdp->fd_lastfile > 0 &&
433 			    fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
434 				fdp->fd_lastfile--;
435 		}
436 		fdrop(fp, td);
437 		return (EBADF);
438 	}
439 	KASSERT(old != new, ("new fd is same as old"));
440 
441 	/*
442 	 * Save info on the descriptor being overwritten.  We have
443 	 * to do the unmap now, but we cannot close it without
444 	 * introducing an ownership race for the slot.
445 	 */
446 	delfp = fdp->fd_ofiles[new];
447 	if (delfp != NULL && p->p_fdtol != NULL) {
448 		/*
449 		 * Ask fdfree() to sleep to ensure that all relevant
450 		 * process leaders can be traversed in closef().
451 		 */
452 		fdp->fd_holdleaderscount++;
453 		holdleaders = 1;
454 	} else
455 		holdleaders = 0;
456 	KASSERT(delfp == NULL || type == DUP_FIXED,
457 	    ("dup() picked an open file"));
458 #if 0
459 	if (delfp && (fdp->fd_ofileflags[new] & UF_MAPPED))
460 		(void) munmapfd(p, new);
461 #endif
462 
463 	/*
464 	 * Duplicate the source descriptor, update lastfile
465 	 */
466 	fdp->fd_ofiles[new] = fp;
467 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
468 	if (new > fdp->fd_lastfile)
469 		fdp->fd_lastfile = new;
470 	*res = new;
471 
472 	/*
473 	 * If we dup'd over a valid file, we now own the reference to it
474 	 * and must dispose of it using closef() semantics (as if a
475 	 * close() were performed on it).
476 	 */
477 	if (delfp) {
478 		(void) closef(delfp, td);
479 		if (holdleaders) {
480 			fdp->fd_holdleaderscount--;
481 			if (fdp->fd_holdleaderscount == 0 &&
482 			    fdp->fd_holdleaderswakeup != 0) {
483 				fdp->fd_holdleaderswakeup = 0;
484 				wakeup(&fdp->fd_holdleaderscount);
485 			}
486 		}
487 	}
488 	return (0);
489 }
490 
491 /*
492  * If sigio is on the list associated with a process or process group,
493  * disable signalling from the device, remove sigio from the list and
494  * free sigio.
495  */
496 void
497 funsetown(sigio)
498 	struct sigio *sigio;
499 {
500 	int s;
501 
502 	if (sigio == NULL)
503 		return;
504 	s = splhigh();
505 	*(sigio->sio_myref) = NULL;
506 	splx(s);
507 	if (sigio->sio_pgid < 0) {
508 		SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
509 			     sigio, sio_pgsigio);
510 	} else /* if ((*sigiop)->sio_pgid > 0) */ {
511 		SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
512 			     sigio, sio_pgsigio);
513 	}
514 	crfree(sigio->sio_ucred);
515 	FREE(sigio, M_SIGIO);
516 }
517 
518 /* Free a list of sigio structures. */
519 void
520 funsetownlst(sigiolst)
521 	struct sigiolst *sigiolst;
522 {
523 	struct sigio *sigio;
524 
525 	while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
526 		funsetown(sigio);
527 }
528 
529 /*
530  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
531  *
532  * After permission checking, add a sigio structure to the sigio list for
533  * the process or process group.
534  */
535 int
536 fsetown(pgid, sigiop)
537 	pid_t pgid;
538 	struct sigio **sigiop;
539 {
540 	struct proc *proc;
541 	struct pgrp *pgrp;
542 	struct sigio *sigio;
543 	int s;
544 
545 	if (pgid == 0) {
546 		funsetown(*sigiop);
547 		return (0);
548 	}
549 	if (pgid > 0) {
550 		proc = pfind(pgid);
551 		if (proc == NULL)
552 			return (ESRCH);
553 
554 		/*
555 		 * Policy - Don't allow a process to FSETOWN a process
556 		 * in another session.
557 		 *
558 		 * Remove this test to allow maximum flexibility or
559 		 * restrict FSETOWN to the current process or process
560 		 * group for maximum safety.
561 		 */
562 		if (proc->p_session != curproc->p_session)
563 			return (EPERM);
564 
565 		pgrp = NULL;
566 	} else /* if (pgid < 0) */ {
567 		pgrp = pgfind(-pgid);
568 		if (pgrp == NULL)
569 			return (ESRCH);
570 
571 		/*
572 		 * Policy - Don't allow a process to FSETOWN a process
573 		 * in another session.
574 		 *
575 		 * Remove this test to allow maximum flexibility or
576 		 * restrict FSETOWN to the current process or process
577 		 * group for maximum safety.
578 		 */
579 		if (pgrp->pg_session != curproc->p_session)
580 			return (EPERM);
581 
582 		proc = NULL;
583 	}
584 	funsetown(*sigiop);
585 	MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
586 	if (pgid > 0) {
587 		SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
588 		sigio->sio_proc = proc;
589 	} else {
590 		SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
591 		sigio->sio_pgrp = pgrp;
592 	}
593 	sigio->sio_pgid = pgid;
594 	sigio->sio_ucred = crhold(curproc->p_ucred);
595 	/* It would be convenient if p_ruid was in ucred. */
596 	sigio->sio_ruid = curproc->p_ucred->cr_ruid;
597 	sigio->sio_myref = sigiop;
598 	s = splhigh();
599 	*sigiop = sigio;
600 	splx(s);
601 	return (0);
602 }
603 
604 /*
605  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
606  */
607 pid_t
608 fgetown(sigio)
609 	struct sigio *sigio;
610 {
611 	return (sigio != NULL ? sigio->sio_pgid : 0);
612 }
613 
614 /*
615  * Close a file descriptor.
616  */
617 /* ARGSUSED */
618 int
619 close(struct close_args *uap)
620 {
621 	struct thread *td = curthread;
622 	struct proc *p = td->td_proc;
623 	struct filedesc *fdp;
624 	struct file *fp;
625 	int fd = uap->fd;
626 	int error;
627 	int holdleaders;
628 
629 	KKASSERT(p);
630 	fdp = p->p_fd;
631 
632 	if ((unsigned)fd >= fdp->fd_nfiles ||
633 	    (fp = fdp->fd_ofiles[fd]) == NULL)
634 		return (EBADF);
635 #if 0
636 	if (fdp->fd_ofileflags[fd] & UF_MAPPED)
637 		(void) munmapfd(p, fd);
638 #endif
639 	fdp->fd_ofiles[fd] = NULL;
640 	fdp->fd_ofileflags[fd] = 0;
641 	holdleaders = 0;
642 	if (p->p_fdtol != NULL) {
643 		/*
644 		 * Ask fdfree() to sleep to ensure that all relevant
645 		 * process leaders can be traversed in closef().
646 		 */
647 		fdp->fd_holdleaderscount++;
648 		holdleaders = 1;
649 	}
650 
651 	/*
652 	 * we now hold the fp reference that used to be owned by the descriptor
653 	 * array.
654 	 */
655 	while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
656 		fdp->fd_lastfile--;
657 	if (fd < fdp->fd_freefile)
658 		fdp->fd_freefile = fd;
659 	if (fd < fdp->fd_knlistsize)
660 		knote_fdclose(p, fd);
661 	error = closef(fp, td);
662 	if (holdleaders) {
663 		fdp->fd_holdleaderscount--;
664 		if (fdp->fd_holdleaderscount == 0 &&
665 		    fdp->fd_holdleaderswakeup != 0) {
666 			fdp->fd_holdleaderswakeup = 0;
667 			wakeup(&fdp->fd_holdleaderscount);
668 		}
669 	}
670 	return (error);
671 }
672 
673 int
674 kern_fstat(int fd, struct stat *ub)
675 {
676 	struct thread *td = curthread;
677 	struct proc *p = td->td_proc;
678 	struct filedesc *fdp;
679 	struct file *fp;
680 	int error;
681 
682 	KKASSERT(p);
683 
684 	fdp = p->p_fd;
685 	if ((unsigned)fd >= fdp->fd_nfiles ||
686 	    (fp = fdp->fd_ofiles[fd]) == NULL)
687 		return (EBADF);
688 	fhold(fp);
689 	error = fo_stat(fp, ub, td);
690 	fdrop(fp, td);
691 
692 	return (error);
693 }
694 
695 /*
696  * Return status information about a file descriptor.
697  */
698 int
699 fstat(struct fstat_args *uap)
700 {
701 	struct stat st;
702 	int error;
703 
704 	error = kern_fstat(uap->fd, &st);
705 
706 	if (error == 0)
707 		error = copyout(&st, uap->sb, sizeof(st));
708 	return (error);
709 }
710 
711 /*
712  * XXX: This is for source compatibility with NetBSD.  Probably doesn't
713  * belong here.
714  */
715 int
716 nfstat(struct nfstat_args *uap)
717 {
718 	struct stat st;
719 	struct nstat nst;
720 	int error;
721 
722 	error = kern_fstat(uap->fd, &st);
723 
724 	if (error == 0) {
725 		cvtnstat(&st, &nst);
726 		error = copyout(&nst, uap->sb, sizeof (nst));
727 	}
728 	return (error);
729 }
730 
731 /*
732  * Return pathconf information about a file descriptor.
733  */
734 /* ARGSUSED */
735 int
736 fpathconf(struct fpathconf_args *uap)
737 {
738 	struct thread *td = curthread;
739 	struct proc *p = td->td_proc;
740 	struct filedesc *fdp;
741 	struct file *fp;
742 	struct vnode *vp;
743 	int error = 0;
744 
745 	KKASSERT(p);
746 	fdp = p->p_fd;
747 	if ((unsigned)uap->fd >= fdp->fd_nfiles ||
748 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
749 		return (EBADF);
750 
751 	fhold(fp);
752 
753 	switch (fp->f_type) {
754 	case DTYPE_PIPE:
755 	case DTYPE_SOCKET:
756 		if (uap->name != _PC_PIPE_BUF) {
757 			error = EINVAL;
758 		} else {
759 			uap->sysmsg_result = PIPE_BUF;
760 			error = 0;
761 		}
762 		break;
763 	case DTYPE_FIFO:
764 	case DTYPE_VNODE:
765 		vp = (struct vnode *)fp->f_data;
766 		error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
767 		break;
768 	default:
769 		error = EOPNOTSUPP;
770 		break;
771 	}
772 	fdrop(fp, td);
773 	return(error);
774 }
775 
776 /*
777  * Allocate a file descriptor for the process.
778  */
779 static int fdexpand;
780 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
781 
782 int
783 fdalloc(struct proc *p, int want, int *result)
784 {
785 	struct filedesc *fdp = p->p_fd;
786 	int i;
787 	int lim, last, nfiles;
788 	struct file **newofile;
789 	char *newofileflags;
790 
791 	/*
792 	 * Search for a free descriptor starting at the higher
793 	 * of want or fd_freefile.  If that fails, consider
794 	 * expanding the ofile array.
795 	 */
796 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
797 	for (;;) {
798 		last = min(fdp->fd_nfiles, lim);
799 		if ((i = want) < fdp->fd_freefile)
800 			i = fdp->fd_freefile;
801 		for (; i < last; i++) {
802 			if (fdp->fd_ofiles[i] == NULL) {
803 				fdp->fd_ofileflags[i] = 0;
804 				if (i > fdp->fd_lastfile)
805 					fdp->fd_lastfile = i;
806 				if (want <= fdp->fd_freefile)
807 					fdp->fd_freefile = i;
808 				*result = i;
809 				return (0);
810 			}
811 		}
812 
813 		/*
814 		 * No space in current array.  Expand?
815 		 */
816 		if (fdp->fd_nfiles >= lim)
817 			return (EMFILE);
818 		if (fdp->fd_nfiles < NDEXTENT)
819 			nfiles = NDEXTENT;
820 		else
821 			nfiles = 2 * fdp->fd_nfiles;
822 		MALLOC(newofile, struct file **, nfiles * OFILESIZE,
823 		    M_FILEDESC, M_WAITOK);
824 
825 		/*
826 		 * deal with file-table extend race that might have occured
827 		 * when malloc was blocked.
828 		 */
829 		if (fdp->fd_nfiles >= nfiles) {
830 			FREE(newofile, M_FILEDESC);
831 			continue;
832 		}
833 		newofileflags = (char *) &newofile[nfiles];
834 		/*
835 		 * Copy the existing ofile and ofileflags arrays
836 		 * and zero the new portion of each array.
837 		 */
838 		bcopy(fdp->fd_ofiles, newofile,
839 			(i = sizeof(struct file *) * fdp->fd_nfiles));
840 		bzero((char *)newofile + i, nfiles * sizeof(struct file *) - i);
841 		bcopy(fdp->fd_ofileflags, newofileflags,
842 			(i = sizeof(char) * fdp->fd_nfiles));
843 		bzero(newofileflags + i, nfiles * sizeof(char) - i);
844 		if (fdp->fd_nfiles > NDFILE)
845 			FREE(fdp->fd_ofiles, M_FILEDESC);
846 		fdp->fd_ofiles = newofile;
847 		fdp->fd_ofileflags = newofileflags;
848 		fdp->fd_nfiles = nfiles;
849 		fdexpand++;
850 	}
851 	return (0);
852 }
853 
854 /*
855  * Check to see whether n user file descriptors
856  * are available to the process p.
857  */
858 int
859 fdavail(p, n)
860 	struct proc *p;
861 	int n;
862 {
863 	struct filedesc *fdp = p->p_fd;
864 	struct file **fpp;
865 	int i, lim, last;
866 
867 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
868 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
869 		return (1);
870 
871 	last = min(fdp->fd_nfiles, lim);
872 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
873 	for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
874 		if (*fpp == NULL && --n <= 0)
875 			return (1);
876 	}
877 	return (0);
878 }
879 
880 /*
881  * falloc:
882  *	Create a new open file structure and allocate a file decriptor
883  *	for the process that refers to it.  If p is NULL, no descriptor
884  *	is allocated and the file pointer is returned unassociated with
885  *	any process.  resultfd is only used if p is not NULL and may
886  *	separately be NULL indicating that you don't need the returned fd.
887  */
888 int
889 falloc(struct proc *p, struct file **resultfp, int *resultfd)
890 {
891 	struct file *fp, *fq;
892 	int error, i;
893 
894 	if (nfiles >= maxfiles) {
895 		tablefull("file");
896 		return (ENFILE);
897 	}
898 	/*
899 	 * Allocate a new file descriptor.
900 	 * If the process has file descriptor zero open, add to the list
901 	 * of open files at that point, otherwise put it at the front of
902 	 * the list of open files.
903 	 */
904 	nfiles++;
905 	MALLOC(fp, struct file *, sizeof(struct file), M_FILE, M_WAITOK);
906 	bzero(fp, sizeof(struct file));
907 
908 	/*
909 	 * wait until after malloc (which may have blocked) returns before
910 	 * allocating the slot, else a race might have shrunk it if we had
911 	 * allocated it before the malloc.
912 	 */
913 	i = -1;
914 	if (p && (error = fdalloc(p, 0, &i))) {
915 		nfiles--;
916 		FREE(fp, M_FILE);
917 		return (error);
918 	}
919 	fp->f_count = 1;
920 	fp->f_ops = &badfileops;
921 	fp->f_seqcount = 1;
922 	if (p) {
923 		fp->f_cred = crhold(p->p_ucred);
924 		if ((fq = p->p_fd->fd_ofiles[0]) != NULL) {
925 			LIST_INSERT_AFTER(fq, fp, f_list);
926 		} else {
927 			LIST_INSERT_HEAD(&filehead, fp, f_list);
928 		}
929 		p->p_fd->fd_ofiles[i] = fp;
930 	} else {
931 		fp->f_cred = crhold(proc0.p_ucred);
932 		LIST_INSERT_HEAD(&filehead, fp, f_list);
933 	}
934 	if (resultfp)
935 		*resultfp = fp;
936 	if (resultfd)
937 		*resultfd = i;
938 	return (0);
939 }
940 
941 void
942 fsetcred(struct file *fp, struct ucred *cr)
943 {
944 	crhold(cr);
945 	crfree(fp->f_cred);
946 	fp->f_cred = cr;
947 }
948 
949 /*
950  * Free a file descriptor.
951  */
952 void
953 ffree(fp)
954 	struct file *fp;
955 {
956 	KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
957 	LIST_REMOVE(fp, f_list);
958 	crfree(fp->f_cred);
959 	nfiles--;
960 	FREE(fp, M_FILE);
961 }
962 
963 /*
964  * Build a new filedesc structure.
965  */
966 struct filedesc *
967 fdinit(p)
968 	struct proc *p;
969 {
970 	struct filedesc0 *newfdp;
971 	struct filedesc *fdp = p->p_fd;
972 
973 	MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
974 	    M_FILEDESC, M_WAITOK);
975 	bzero(newfdp, sizeof(struct filedesc0));
976 	newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
977 	if (newfdp->fd_fd.fd_cdir)
978 		VREF(newfdp->fd_fd.fd_cdir);
979 	newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
980 	if (newfdp->fd_fd.fd_rdir)
981 		VREF(newfdp->fd_fd.fd_rdir);
982 	newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
983 	if (newfdp->fd_fd.fd_jdir)
984 		VREF(newfdp->fd_fd.fd_jdir);
985 
986 	/* Create the file descriptor table. */
987 	newfdp->fd_fd.fd_refcnt = 1;
988 	newfdp->fd_fd.fd_cmask = cmask;
989 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
990 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
991 	newfdp->fd_fd.fd_nfiles = NDFILE;
992 	newfdp->fd_fd.fd_knlistsize = -1;
993 
994 	return (&newfdp->fd_fd);
995 }
996 
997 /*
998  * Share a filedesc structure.
999  */
1000 struct filedesc *
1001 fdshare(p)
1002 	struct proc *p;
1003 {
1004 	p->p_fd->fd_refcnt++;
1005 	return (p->p_fd);
1006 }
1007 
1008 /*
1009  * Copy a filedesc structure.
1010  */
1011 struct filedesc *
1012 fdcopy(p)
1013 	struct proc *p;
1014 {
1015 	struct filedesc *newfdp, *fdp = p->p_fd;
1016 	struct file **fpp;
1017 	int i;
1018 
1019 	/* Certain daemons might not have file descriptors. */
1020 	if (fdp == NULL)
1021 		return (NULL);
1022 
1023 	MALLOC(newfdp, struct filedesc *, sizeof(struct filedesc0),
1024 	    M_FILEDESC, M_WAITOK);
1025 	bcopy(fdp, newfdp, sizeof(struct filedesc));
1026 	if (newfdp->fd_cdir)
1027 		VREF(newfdp->fd_cdir);
1028 	if (newfdp->fd_rdir)
1029 		VREF(newfdp->fd_rdir);
1030 	if (newfdp->fd_jdir)
1031 		VREF(newfdp->fd_jdir);
1032 	newfdp->fd_refcnt = 1;
1033 
1034 	/*
1035 	 * If the number of open files fits in the internal arrays
1036 	 * of the open file structure, use them, otherwise allocate
1037 	 * additional memory for the number of descriptors currently
1038 	 * in use.
1039 	 */
1040 	if (newfdp->fd_lastfile < NDFILE) {
1041 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
1042 		newfdp->fd_ofileflags =
1043 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
1044 		i = NDFILE;
1045 	} else {
1046 		/*
1047 		 * Compute the smallest multiple of NDEXTENT needed
1048 		 * for the file descriptors currently in use,
1049 		 * allowing the table to shrink.
1050 		 */
1051 		i = newfdp->fd_nfiles;
1052 		while (i > 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
1053 			i /= 2;
1054 		MALLOC(newfdp->fd_ofiles, struct file **, i * OFILESIZE,
1055 		    M_FILEDESC, M_WAITOK);
1056 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
1057 	}
1058 	newfdp->fd_nfiles = i;
1059 	bcopy(fdp->fd_ofiles, newfdp->fd_ofiles, i * sizeof(struct file **));
1060 	bcopy(fdp->fd_ofileflags, newfdp->fd_ofileflags, i * sizeof(char));
1061 
1062 	/*
1063 	 * kq descriptors cannot be copied.
1064 	 */
1065 	if (newfdp->fd_knlistsize != -1) {
1066 		fpp = &newfdp->fd_ofiles[newfdp->fd_lastfile];
1067 		for (i = newfdp->fd_lastfile; i >= 0; i--, fpp--) {
1068 			if (*fpp != NULL && (*fpp)->f_type == DTYPE_KQUEUE) {
1069 				*fpp = NULL;
1070 				if (i < newfdp->fd_freefile)
1071 					newfdp->fd_freefile = i;
1072 			}
1073 			if (*fpp == NULL && i == newfdp->fd_lastfile && i > 0)
1074 				newfdp->fd_lastfile--;
1075 		}
1076 		newfdp->fd_knlist = NULL;
1077 		newfdp->fd_knlistsize = -1;
1078 		newfdp->fd_knhash = NULL;
1079 		newfdp->fd_knhashmask = 0;
1080 	}
1081 
1082 	fpp = newfdp->fd_ofiles;
1083 	for (i = newfdp->fd_lastfile; i-- >= 0; fpp++) {
1084 		if (*fpp != NULL)
1085 			fhold(*fpp);
1086 	}
1087 	return (newfdp);
1088 }
1089 
1090 /*
1091  * Release a filedesc structure.
1092  */
1093 void
1094 fdfree(struct proc *p)
1095 {
1096 	struct thread *td = p->p_thread;
1097 	struct filedesc *fdp = p->p_fd;
1098 	struct file **fpp;
1099 	int i;
1100 	struct filedesc_to_leader *fdtol;
1101 	struct file *fp;
1102 	struct vnode *vp;
1103 	struct flock lf;
1104 
1105 	/* Certain daemons might not have file descriptors. */
1106 	if (fdp == NULL)
1107 		return;
1108 
1109 	/* Check for special need to clear POSIX style locks */
1110 	fdtol = p->p_fdtol;
1111 	if (fdtol != NULL) {
1112 		KASSERT(fdtol->fdl_refcount > 0,
1113 			("filedesc_to_refcount botch: fdl_refcount=%d",
1114 			 fdtol->fdl_refcount));
1115 		if (fdtol->fdl_refcount == 1 &&
1116 		    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1117 			i = 0;
1118 			fpp = fdp->fd_ofiles;
1119 			for (i = 0, fpp = fdp->fd_ofiles;
1120 			     i <= fdp->fd_lastfile;
1121 			     i++, fpp++) {
1122 				if (*fpp == NULL ||
1123 				    (*fpp)->f_type != DTYPE_VNODE)
1124 					continue;
1125 				fp = *fpp;
1126 				fhold(fp);
1127 				lf.l_whence = SEEK_SET;
1128 				lf.l_start = 0;
1129 				lf.l_len = 0;
1130 				lf.l_type = F_UNLCK;
1131 				vp = (struct vnode *)fp->f_data;
1132 				(void) VOP_ADVLOCK(vp,
1133 						   (caddr_t)p->p_leader,
1134 						   F_UNLCK,
1135 						   &lf,
1136 						   F_POSIX);
1137 				fdrop(fp, p->p_thread);
1138 				fpp = fdp->fd_ofiles + i;
1139 			}
1140 		}
1141 	retry:
1142 		if (fdtol->fdl_refcount == 1) {
1143 			if (fdp->fd_holdleaderscount > 0 &&
1144 			    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1145 				/*
1146 				 * close() or do_dup() has cleared a reference
1147 				 * in a shared file descriptor table.
1148 				 */
1149 				fdp->fd_holdleaderswakeup = 1;
1150 				tsleep(&fdp->fd_holdleaderscount,
1151 				       0, "fdlhold", 0);
1152 				goto retry;
1153 			}
1154 			if (fdtol->fdl_holdcount > 0) {
1155 				/*
1156 				 * Ensure that fdtol->fdl_leader
1157 				 * remains valid in closef().
1158 				 */
1159 				fdtol->fdl_wakeup = 1;
1160 				tsleep(fdtol, 0, "fdlhold", 0);
1161 				goto retry;
1162 			}
1163 		}
1164 		fdtol->fdl_refcount--;
1165 		if (fdtol->fdl_refcount == 0 &&
1166 		    fdtol->fdl_holdcount == 0) {
1167 			fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1168 			fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1169 		} else
1170 			fdtol = NULL;
1171 		p->p_fdtol = NULL;
1172 		if (fdtol != NULL)
1173 			FREE(fdtol, M_FILEDESC_TO_LEADER);
1174 	}
1175 	if (--fdp->fd_refcnt > 0)
1176 		return;
1177 	/*
1178 	 * we are the last reference to the structure, we can
1179 	 * safely assume it will not change out from under us.
1180 	 */
1181 	fpp = fdp->fd_ofiles;
1182 	for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1183 		if (*fpp)
1184 			(void) closef(*fpp, td);
1185 	}
1186 	if (fdp->fd_nfiles > NDFILE)
1187 		FREE(fdp->fd_ofiles, M_FILEDESC);
1188 	if (fdp->fd_cdir)
1189 		vrele(fdp->fd_cdir);
1190 	if (fdp->fd_rdir)
1191 		vrele(fdp->fd_rdir);
1192 	if (fdp->fd_jdir)
1193 		vrele(fdp->fd_jdir);
1194 	if (fdp->fd_knlist)
1195 		FREE(fdp->fd_knlist, M_KQUEUE);
1196 	if (fdp->fd_knhash)
1197 		FREE(fdp->fd_knhash, M_KQUEUE);
1198 	FREE(fdp, M_FILEDESC);
1199 }
1200 
1201 /*
1202  * For setugid programs, we don't want to people to use that setugidness
1203  * to generate error messages which write to a file which otherwise would
1204  * otherwise be off-limits to the process.
1205  *
1206  * This is a gross hack to plug the hole.  A better solution would involve
1207  * a special vop or other form of generalized access control mechanism.  We
1208  * go ahead and just reject all procfs file systems accesses as dangerous.
1209  *
1210  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1211  * sufficient.  We also don't for check setugidness since we know we are.
1212  */
1213 static int
1214 is_unsafe(struct file *fp)
1215 {
1216 	if (fp->f_type == DTYPE_VNODE &&
1217 	    ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1218 		return (1);
1219 	return (0);
1220 }
1221 
1222 /*
1223  * Make this setguid thing safe, if at all possible.
1224  */
1225 void
1226 setugidsafety(struct proc *p)
1227 {
1228 	struct thread *td = p->p_thread;
1229 	struct filedesc *fdp = p->p_fd;
1230 	int i;
1231 
1232 	/* Certain daemons might not have file descriptors. */
1233 	if (fdp == NULL)
1234 		return;
1235 
1236 	/*
1237 	 * note: fdp->fd_ofiles may be reallocated out from under us while
1238 	 * we are blocked in a close.  Be careful!
1239 	 */
1240 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1241 		if (i > 2)
1242 			break;
1243 		if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1244 			struct file *fp;
1245 
1246 #if 0
1247 			if ((fdp->fd_ofileflags[i] & UF_MAPPED) != 0)
1248 				(void) munmapfd(p, i);
1249 #endif
1250 			if (i < fdp->fd_knlistsize)
1251 				knote_fdclose(p, i);
1252 			/*
1253 			 * NULL-out descriptor prior to close to avoid
1254 			 * a race while close blocks.
1255 			 */
1256 			fp = fdp->fd_ofiles[i];
1257 			fdp->fd_ofiles[i] = NULL;
1258 			fdp->fd_ofileflags[i] = 0;
1259 			if (i < fdp->fd_freefile)
1260 				fdp->fd_freefile = i;
1261 			(void) closef(fp, td);
1262 		}
1263 	}
1264 	while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1265 		fdp->fd_lastfile--;
1266 }
1267 
1268 /*
1269  * Close any files on exec?
1270  */
1271 void
1272 fdcloseexec(struct proc *p)
1273 {
1274 	struct thread *td = p->p_thread;
1275 	struct filedesc *fdp = p->p_fd;
1276 	int i;
1277 
1278 	/* Certain daemons might not have file descriptors. */
1279 	if (fdp == NULL)
1280 		return;
1281 
1282 	/*
1283 	 * We cannot cache fd_ofiles or fd_ofileflags since operations
1284 	 * may block and rip them out from under us.
1285 	 */
1286 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1287 		if (fdp->fd_ofiles[i] != NULL &&
1288 		    (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1289 			struct file *fp;
1290 
1291 #if 0
1292 			if (fdp->fd_ofileflags[i] & UF_MAPPED)
1293 				(void) munmapfd(p, i);
1294 #endif
1295 			if (i < fdp->fd_knlistsize)
1296 				knote_fdclose(p, i);
1297 			/*
1298 			 * NULL-out descriptor prior to close to avoid
1299 			 * a race while close blocks.
1300 			 */
1301 			fp = fdp->fd_ofiles[i];
1302 			fdp->fd_ofiles[i] = NULL;
1303 			fdp->fd_ofileflags[i] = 0;
1304 			if (i < fdp->fd_freefile)
1305 				fdp->fd_freefile = i;
1306 			(void) closef(fp, td);
1307 		}
1308 	}
1309 	while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1310 		fdp->fd_lastfile--;
1311 }
1312 
1313 /*
1314  * It is unsafe for set[ug]id processes to be started with file
1315  * descriptors 0..2 closed, as these descriptors are given implicit
1316  * significance in the Standard C library.  fdcheckstd() will create a
1317  * descriptor referencing /dev/null for each of stdin, stdout, and
1318  * stderr that is not already open.
1319  */
1320 int
1321 fdcheckstd(struct proc *p)
1322 {
1323 	struct thread *td = p->p_thread;
1324 	struct nameidata nd;
1325 	struct filedesc *fdp;
1326 	struct file *fp;
1327 	register_t retval;
1328 	int fd, i, error, flags, devnull;
1329 
1330        fdp = p->p_fd;
1331        if (fdp == NULL)
1332                return (0);
1333        devnull = -1;
1334        error = 0;
1335        for (i = 0; i < 3; i++) {
1336                if (fdp->fd_ofiles[i] != NULL)
1337                        continue;
1338                if (devnull < 0) {
1339                        error = falloc(p, &fp, &fd);
1340                        if (error != 0)
1341                                break;
1342                        NDINIT(&nd, NAMEI_LOOKUP, CNP_FOLLOW, UIO_SYSSPACE,
1343 			   "/dev/null", td);
1344                        flags = FREAD | FWRITE;
1345                        error = vn_open(&nd, flags, 0);
1346                        if (error != 0) {
1347                                fdp->fd_ofiles[i] = NULL;
1348                                fdrop(fp, td);
1349                                break;
1350                        }
1351                        NDFREE(&nd, NDF_ONLY_PNBUF);
1352                        fp->f_data = (caddr_t)nd.ni_vp;
1353                        fp->f_flag = flags;
1354                        fp->f_ops = &vnops;
1355                        fp->f_type = DTYPE_VNODE;
1356                        VOP_UNLOCK(nd.ni_vp, NULL, 0, td);
1357                        devnull = fd;
1358                } else {
1359                        error = kern_dup(DUP_FIXED, devnull, i, &retval);
1360                        if (error != 0)
1361                                break;
1362                }
1363        }
1364        return (error);
1365 }
1366 
1367 /*
1368  * Internal form of close.
1369  * Decrement reference count on file structure.
1370  * Note: td and/or p may be NULL when closing a file
1371  * that was being passed in a message.
1372  */
1373 int
1374 closef(struct file *fp, struct thread *td)
1375 {
1376 	struct vnode *vp;
1377 	struct flock lf;
1378 	struct filedesc_to_leader *fdtol;
1379 	struct proc *p;
1380 
1381 	if (fp == NULL)
1382 		return (0);
1383 	if (td == NULL) {
1384 		td = curthread;
1385 		p = NULL;		/* allow no proc association */
1386 	} else {
1387 		p = td->td_proc;	/* can also be NULL */
1388 	}
1389 	/*
1390 	 * POSIX record locking dictates that any close releases ALL
1391 	 * locks owned by this process.  This is handled by setting
1392 	 * a flag in the unlock to free ONLY locks obeying POSIX
1393 	 * semantics, and not to free BSD-style file locks.
1394 	 * If the descriptor was in a message, POSIX-style locks
1395 	 * aren't passed with the descriptor.
1396 	 */
1397 	if (p != NULL &&
1398 	    fp->f_type == DTYPE_VNODE) {
1399 		if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1400 			lf.l_whence = SEEK_SET;
1401 			lf.l_start = 0;
1402 			lf.l_len = 0;
1403 			lf.l_type = F_UNLCK;
1404 			vp = (struct vnode *)fp->f_data;
1405 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1406 					   &lf, F_POSIX);
1407 		}
1408 		fdtol = p->p_fdtol;
1409 		if (fdtol != NULL) {
1410 			/*
1411 			 * Handle special case where file descriptor table
1412 			 * is shared between multiple process leaders.
1413 			 */
1414 			for (fdtol = fdtol->fdl_next;
1415 			     fdtol != p->p_fdtol;
1416 			     fdtol = fdtol->fdl_next) {
1417 				if ((fdtol->fdl_leader->p_flag &
1418 				     P_ADVLOCK) == 0)
1419 					continue;
1420 				fdtol->fdl_holdcount++;
1421 				lf.l_whence = SEEK_SET;
1422 				lf.l_start = 0;
1423 				lf.l_len = 0;
1424 				lf.l_type = F_UNLCK;
1425 				vp = (struct vnode *)fp->f_data;
1426 				(void) VOP_ADVLOCK(vp,
1427 						   (caddr_t)p->p_leader,
1428 						   F_UNLCK, &lf, F_POSIX);
1429 				fdtol->fdl_holdcount--;
1430 				if (fdtol->fdl_holdcount == 0 &&
1431 				    fdtol->fdl_wakeup != 0) {
1432 					fdtol->fdl_wakeup = 0;
1433 					wakeup(fdtol);
1434 				}
1435 			}
1436 		}
1437 	}
1438 	return (fdrop(fp, td));
1439 }
1440 
1441 int
1442 fdrop(struct file *fp, struct thread *td)
1443 {
1444 	struct flock lf;
1445 	struct vnode *vp;
1446 	int error;
1447 
1448 	if (--fp->f_count > 0)
1449 		return (0);
1450 	if (fp->f_count < 0)
1451 		panic("fdrop: count < 0");
1452 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1453 		lf.l_whence = SEEK_SET;
1454 		lf.l_start = 0;
1455 		lf.l_len = 0;
1456 		lf.l_type = F_UNLCK;
1457 		vp = (struct vnode *)fp->f_data;
1458 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
1459 	}
1460 	if (fp->f_ops != &badfileops)
1461 		error = fo_close(fp, td);
1462 	else
1463 		error = 0;
1464 	ffree(fp);
1465 	return (error);
1466 }
1467 
1468 /*
1469  * Apply an advisory lock on a file descriptor.
1470  *
1471  * Just attempt to get a record lock of the requested type on
1472  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1473  */
1474 /* ARGSUSED */
1475 int
1476 flock(struct flock_args *uap)
1477 {
1478 	struct proc *p = curproc;
1479 	struct filedesc *fdp = p->p_fd;
1480 	struct file *fp;
1481 	struct vnode *vp;
1482 	struct flock lf;
1483 
1484 	if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1485 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
1486 		return (EBADF);
1487 	if (fp->f_type != DTYPE_VNODE)
1488 		return (EOPNOTSUPP);
1489 	vp = (struct vnode *)fp->f_data;
1490 	lf.l_whence = SEEK_SET;
1491 	lf.l_start = 0;
1492 	lf.l_len = 0;
1493 	if (uap->how & LOCK_UN) {
1494 		lf.l_type = F_UNLCK;
1495 		fp->f_flag &= ~FHASLOCK;
1496 		return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK));
1497 	}
1498 	if (uap->how & LOCK_EX)
1499 		lf.l_type = F_WRLCK;
1500 	else if (uap->how & LOCK_SH)
1501 		lf.l_type = F_RDLCK;
1502 	else
1503 		return (EBADF);
1504 	fp->f_flag |= FHASLOCK;
1505 	if (uap->how & LOCK_NB)
1506 		return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK));
1507 	return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT));
1508 }
1509 
1510 /*
1511  * File Descriptor pseudo-device driver (/dev/fd/).
1512  *
1513  * Opening minor device N dup()s the file (if any) connected to file
1514  * descriptor N belonging to the calling process.  Note that this driver
1515  * consists of only the ``open()'' routine, because all subsequent
1516  * references to this file will be direct to the other driver.
1517  */
1518 /* ARGSUSED */
1519 static int
1520 fdopen(dev_t dev, int mode, int type, struct thread *td)
1521 {
1522 	KKASSERT(td->td_proc != NULL);
1523 
1524 	/*
1525 	 * XXX Kludge: set curproc->p_dupfd to contain the value of the
1526 	 * the file descriptor being sought for duplication. The error
1527 	 * return ensures that the vnode for this device will be released
1528 	 * by vn_open. Open will detect this special error and take the
1529 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1530 	 * will simply report the error.
1531 	 */
1532 	td->td_proc->p_dupfd = minor(dev);
1533 	return (ENODEV);
1534 }
1535 
1536 /*
1537  * Duplicate the specified descriptor to a free descriptor.
1538  */
1539 int
1540 dupfdopen(struct filedesc *fdp, int indx, int dfd, int mode, int error)
1541 {
1542 	struct file *wfp;
1543 	struct file *fp;
1544 
1545 	/*
1546 	 * If the to-be-dup'd fd number is greater than the allowed number
1547 	 * of file descriptors, or the fd to be dup'd has already been
1548 	 * closed, then reject.
1549 	 */
1550 	if ((u_int)dfd >= fdp->fd_nfiles ||
1551 	    (wfp = fdp->fd_ofiles[dfd]) == NULL) {
1552 		return (EBADF);
1553 	}
1554 
1555 	/*
1556 	 * There are two cases of interest here.
1557 	 *
1558 	 * For ENODEV simply dup (dfd) to file descriptor
1559 	 * (indx) and return.
1560 	 *
1561 	 * For ENXIO steal away the file structure from (dfd) and
1562 	 * store it in (indx).  (dfd) is effectively closed by
1563 	 * this operation.
1564 	 *
1565 	 * Any other error code is just returned.
1566 	 */
1567 	switch (error) {
1568 	case ENODEV:
1569 		/*
1570 		 * Check that the mode the file is being opened for is a
1571 		 * subset of the mode of the existing descriptor.
1572 		 */
1573 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1574 			return (EACCES);
1575 		fp = fdp->fd_ofiles[indx];
1576 #if 0
1577 		if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
1578 			(void) munmapfd(p, indx);
1579 #endif
1580 		fdp->fd_ofiles[indx] = wfp;
1581 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1582 		fhold(wfp);
1583 		if (indx > fdp->fd_lastfile)
1584 			fdp->fd_lastfile = indx;
1585 		/*
1586 		 * we now own the reference to fp that the ofiles[] array
1587 		 * used to own.  Release it.
1588 		 */
1589 		if (fp)
1590 			fdrop(fp, curthread);
1591 		return (0);
1592 
1593 	case ENXIO:
1594 		/*
1595 		 * Steal away the file pointer from dfd, and stuff it into indx.
1596 		 */
1597 		fp = fdp->fd_ofiles[indx];
1598 #if 0
1599 		if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
1600 			(void) munmapfd(p, indx);
1601 #endif
1602 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
1603 		fdp->fd_ofiles[dfd] = NULL;
1604 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1605 		fdp->fd_ofileflags[dfd] = 0;
1606 
1607 		/*
1608 		 * we now own the reference to fp that the ofiles[] array
1609 		 * used to own.  Release it.
1610 		 */
1611 		if (fp)
1612 			fdrop(fp, curthread);
1613 		/*
1614 		 * Complete the clean up of the filedesc structure by
1615 		 * recomputing the various hints.
1616 		 */
1617 		if (indx > fdp->fd_lastfile) {
1618 			fdp->fd_lastfile = indx;
1619 		} else {
1620 			while (fdp->fd_lastfile > 0 &&
1621 			   fdp->fd_ofiles[fdp->fd_lastfile] == NULL) {
1622 				fdp->fd_lastfile--;
1623 			}
1624 			if (dfd < fdp->fd_freefile)
1625 				fdp->fd_freefile = dfd;
1626 		}
1627 		return (0);
1628 
1629 	default:
1630 		return (error);
1631 	}
1632 	/* NOTREACHED */
1633 }
1634 
1635 
1636 struct filedesc_to_leader *
1637 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
1638 			 struct proc *leader)
1639 {
1640 	struct filedesc_to_leader *fdtol;
1641 
1642 	MALLOC(fdtol, struct filedesc_to_leader *,
1643 	       sizeof(struct filedesc_to_leader),
1644 	       M_FILEDESC_TO_LEADER,
1645 	       M_WAITOK);
1646 	fdtol->fdl_refcount = 1;
1647 	fdtol->fdl_holdcount = 0;
1648 	fdtol->fdl_wakeup = 0;
1649 	fdtol->fdl_leader = leader;
1650 	if (old != NULL) {
1651 		fdtol->fdl_next = old->fdl_next;
1652 		fdtol->fdl_prev = old;
1653 		old->fdl_next = fdtol;
1654 		fdtol->fdl_next->fdl_prev = fdtol;
1655 	} else {
1656 		fdtol->fdl_next = fdtol;
1657 		fdtol->fdl_prev = fdtol;
1658 	}
1659 	return fdtol;
1660 }
1661 
1662 /*
1663  * Get file structures.
1664  */
1665 static int
1666 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
1667 {
1668 	int error;
1669 	struct file *fp;
1670 
1671 	if (!req->oldptr) {
1672 		/*
1673 		 * overestimate by 10 files
1674 		 */
1675 		return (SYSCTL_OUT(req, 0, sizeof(filehead) +
1676 				(nfiles + 10) * sizeof(struct file)));
1677 	}
1678 
1679 	error = SYSCTL_OUT(req, (caddr_t)&filehead, sizeof(filehead));
1680 	if (error)
1681 		return (error);
1682 
1683 	/*
1684 	 * followed by an array of file structures
1685 	 */
1686 	LIST_FOREACH(fp, &filehead, f_list) {
1687 		error = SYSCTL_OUT(req, (caddr_t)fp, sizeof (struct file));
1688 		if (error)
1689 			return (error);
1690 	}
1691 	return (0);
1692 }
1693 
1694 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
1695     0, 0, sysctl_kern_file, "S,file", "Entire file table");
1696 
1697 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
1698     &maxfilesperproc, 0, "Maximum files allowed open per process");
1699 
1700 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
1701     &maxfiles, 0, "Maximum number of files");
1702 
1703 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
1704 	&nfiles, 0, "System-wide number of open files");
1705 
1706 static void
1707 fildesc_drvinit(void *unused)
1708 {
1709 	int fd;
1710 
1711 	for (fd = 0; fd < NUMFDESC; fd++)
1712 		make_dev(&fildesc_cdevsw, fd,
1713 		    UID_BIN, GID_BIN, 0666, "fd/%d", fd);
1714 	make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
1715 	make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
1716 	make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
1717 }
1718 
1719 struct fileops badfileops = {
1720 	NULL,	/* port */
1721 	0,	/* autoq */
1722 	badfo_readwrite,
1723 	badfo_readwrite,
1724 	badfo_ioctl,
1725 	badfo_poll,
1726 	badfo_kqfilter,
1727 	badfo_stat,
1728 	badfo_close
1729 };
1730 
1731 static int
1732 badfo_readwrite(
1733 	struct file *fp,
1734 	struct uio *uio,
1735 	struct ucred *cred,
1736 	int flags,
1737 	struct thread *td
1738 ) {
1739 	return (EBADF);
1740 }
1741 
1742 static int
1743 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct thread *td)
1744 {
1745 	return (EBADF);
1746 }
1747 
1748 static int
1749 badfo_poll(struct file *fp, int events, struct ucred *cred, struct thread *td)
1750 {
1751 	return (0);
1752 }
1753 
1754 static int
1755 badfo_kqfilter(struct file *fp, struct knote *kn)
1756 {
1757 	return (0);
1758 }
1759 
1760 static int
1761 badfo_stat(struct file *fp, struct stat *sb, struct thread *td)
1762 {
1763 	return (EBADF);
1764 }
1765 
1766 static int
1767 badfo_close(struct file *fp, struct thread *td)
1768 {
1769 	return (EBADF);
1770 }
1771 
1772 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
1773 					fildesc_drvinit,NULL)
1774