xref: /freebsd/sys/kern/kern_descrip.c (revision 8e537d168674d6b65869f73c20813001af875738)
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  * $Id: kern_descrip.c,v 1.31 1996/08/15 16:33:32 smpatel Exp $
40  */
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/sysproto.h>
45 #include <sys/conf.h>
46 #include <sys/filedesc.h>
47 #include <sys/kernel.h>
48 #include <sys/sysctl.h>
49 #include <sys/vnode.h>
50 #include <sys/proc.h>
51 #include <sys/file.h>
52 #include <sys/socketvar.h>
53 #include <sys/stat.h>
54 #include <sys/filio.h>
55 #include <sys/ttycom.h>
56 #include <sys/fcntl.h>
57 #include <sys/malloc.h>
58 #include <sys/unistd.h>
59 #include <sys/resourcevar.h>
60 #include <sys/pipe.h>
61 
62 #include <vm/vm.h>
63 #include <vm/vm_extern.h>
64 
65 #ifdef DEVFS
66 #include <sys/devfsext.h>
67 #endif /*DEVFS*/
68 
69 static	 d_open_t  fdopen;
70 #define NUMFDESC 64
71 
72 #define CDEV_MAJOR 22
73 static struct cdevsw fildesc_cdevsw =
74 	{ fdopen,	noclose,	noread,		nowrite,	/*22*/
75 	  noioc,	nostop,		nullreset,	nodevtotty,/*fd(!=Fd)*/
76 	  noselect,	nommap,		nostrat };
77 
78 static int finishdup(struct filedesc *fdp, int old, int new, int *retval);
79 /*
80  * Descriptor management.
81  */
82 struct filelist filehead;	/* head of list of open files */
83 int nfiles;			/* actual number of open files */
84 extern int cmask;
85 
86 /*
87  * System calls on descriptors.
88  */
89 #ifndef _SYS_SYSPROTO_H_
90 struct getdtablesize_args {
91 	int	dummy;
92 };
93 #endif
94 /* ARGSUSED */
95 int
96 getdtablesize(p, uap, retval)
97 	struct proc *p;
98 	struct getdtablesize_args *uap;
99 	int *retval;
100 {
101 
102 	*retval = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
103 	return (0);
104 }
105 
106 /*
107  * Duplicate a file descriptor to a particular value.
108  */
109 #ifndef _SYS_SYSPROTO_H_
110 struct dup2_args {
111 	u_int	from;
112 	u_int	to;
113 };
114 #endif
115 /* ARGSUSED */
116 int
117 dup2(p, uap, retval)
118 	struct proc *p;
119 	struct dup2_args *uap;
120 	int *retval;
121 {
122 	register struct filedesc *fdp = p->p_fd;
123 	register u_int old = uap->from, new = uap->to;
124 	int i, error;
125 
126 	if (old >= fdp->fd_nfiles ||
127 	    fdp->fd_ofiles[old] == NULL ||
128 	    new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
129 	    new >= maxfilesperproc)
130 		return (EBADF);
131 	if (old == new) {
132 		*retval = new;
133 		return (0);
134 	}
135 	if (new >= fdp->fd_nfiles) {
136 		if ((error = fdalloc(p, new, &i)))
137 			return (error);
138 		if (new != i)
139 			panic("dup2: fdalloc");
140 	} else if (fdp->fd_ofiles[new]) {
141 		if (fdp->fd_ofileflags[new] & UF_MAPPED)
142 			(void) munmapfd(p, new);
143 		/*
144 		 * dup2() must succeed even if the close has an error.
145 		 */
146 		(void) closef(fdp->fd_ofiles[new], p);
147 	}
148 	return (finishdup(fdp, (int)old, (int)new, retval));
149 }
150 
151 /*
152  * Duplicate a file descriptor.
153  */
154 #ifndef _SYS_SYSPROTO_H_
155 struct dup_args {
156 	u_int	fd;
157 };
158 #endif
159 /* ARGSUSED */
160 int
161 dup(p, uap, retval)
162 	struct proc *p;
163 	struct dup_args *uap;
164 	int *retval;
165 {
166 	register struct filedesc *fdp;
167 	u_int old;
168 	int new, error;
169 
170 	old = uap->fd;
171 
172 #if 0
173 	/*
174 	 * XXX Compatibility
175 	 */
176 	if (old &~ 077) { uap->fd &= 077; return (dup2(p, uap, retval)); }
177 #endif
178 
179 	fdp = p->p_fd;
180 	if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL)
181 		return (EBADF);
182 	if ((error = fdalloc(p, 0, &new)))
183 		return (error);
184 	return (finishdup(fdp, (int)old, new, retval));
185 }
186 
187 /*
188  * The file control system call.
189  */
190 #ifndef _SYS_SYSPROTO_H_
191 struct fcntl_args {
192 	int	fd;
193 	int	cmd;
194 	int	arg;
195 };
196 #endif
197 /* ARGSUSED */
198 int
199 fcntl(p, uap, retval)
200 	struct proc *p;
201 	register struct fcntl_args *uap;
202 	int *retval;
203 {
204 	register struct filedesc *fdp = p->p_fd;
205 	register struct file *fp;
206 	register char *pop;
207 	struct vnode *vp;
208 	int i, tmp, error, flg = F_POSIX;
209 	struct flock fl;
210 	u_int newmin;
211 
212 	if ((unsigned)uap->fd >= fdp->fd_nfiles ||
213 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
214 		return (EBADF);
215 	pop = &fdp->fd_ofileflags[uap->fd];
216 	switch (uap->cmd) {
217 
218 	case F_DUPFD:
219 		newmin = uap->arg;
220 		if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
221 		    newmin >= maxfilesperproc)
222 			return (EINVAL);
223 		if ((error = fdalloc(p, newmin, &i)))
224 			return (error);
225 		return (finishdup(fdp, uap->fd, i, retval));
226 
227 	case F_GETFD:
228 		*retval = *pop & 1;
229 		return (0);
230 
231 	case F_SETFD:
232 		*pop = (*pop &~ 1) | (uap->arg & 1);
233 		return (0);
234 
235 	case F_GETFL:
236 		*retval = OFLAGS(fp->f_flag);
237 		return (0);
238 
239 	case F_SETFL:
240 		fp->f_flag &= ~FCNTLFLAGS;
241 		fp->f_flag |= FFLAGS(uap->arg) & FCNTLFLAGS;
242 		tmp = fp->f_flag & FNONBLOCK;
243 		error = (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
244 		if (error)
245 			return (error);
246 		tmp = fp->f_flag & FASYNC;
247 		error = (*fp->f_ops->fo_ioctl)(fp, FIOASYNC, (caddr_t)&tmp, p);
248 		if (!error)
249 			return (0);
250 		fp->f_flag &= ~FNONBLOCK;
251 		tmp = 0;
252 		(void) (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
253 		return (error);
254 
255 	case F_GETOWN:
256 		if (fp->f_type == DTYPE_SOCKET) {
257 			*retval = ((struct socket *)fp->f_data)->so_pgid;
258 			return (0);
259 		}
260 		error = (*fp->f_ops->fo_ioctl)
261 			(fp, TIOCGPGRP, (caddr_t)retval, p);
262 		*retval = -*retval;
263 		return (error);
264 
265 	case F_SETOWN:
266 		if (fp->f_type == DTYPE_SOCKET) {
267 			((struct socket *)fp->f_data)->so_pgid = uap->arg;
268 			return (0);
269 		}
270 		if (uap->arg <= 0) {
271 			uap->arg = -uap->arg;
272 		} else {
273 			struct proc *p1 = pfind(uap->arg);
274 			if (p1 == 0)
275 				return (ESRCH);
276 			uap->arg = p1->p_pgrp->pg_id;
277 		}
278 		return ((*fp->f_ops->fo_ioctl)
279 			(fp, TIOCSPGRP, (caddr_t)&uap->arg, p));
280 
281 	case F_SETLKW:
282 		flg |= F_WAIT;
283 		/* Fall into F_SETLK */
284 
285 	case F_SETLK:
286 		if (fp->f_type != DTYPE_VNODE)
287 			return (EBADF);
288 		vp = (struct vnode *)fp->f_data;
289 		/* Copy in the lock structure */
290 		error = copyin((caddr_t)uap->arg, (caddr_t)&fl, sizeof (fl));
291 		if (error)
292 			return (error);
293 		if (fl.l_whence == SEEK_CUR)
294 			fl.l_start += fp->f_offset;
295 		switch (fl.l_type) {
296 
297 		case F_RDLCK:
298 			if ((fp->f_flag & FREAD) == 0)
299 				return (EBADF);
300 			p->p_flag |= P_ADVLOCK;
301 			return (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg));
302 
303 		case F_WRLCK:
304 			if ((fp->f_flag & FWRITE) == 0)
305 				return (EBADF);
306 			p->p_flag |= P_ADVLOCK;
307 			return (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg));
308 
309 		case F_UNLCK:
310 			return (VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &fl,
311 				F_POSIX));
312 
313 		default:
314 			return (EINVAL);
315 		}
316 
317 	case F_GETLK:
318 		if (fp->f_type != DTYPE_VNODE)
319 			return (EBADF);
320 		vp = (struct vnode *)fp->f_data;
321 		/* Copy in the lock structure */
322 		error = copyin((caddr_t)uap->arg, (caddr_t)&fl, sizeof (fl));
323 		if (error)
324 			return (error);
325 		if (fl.l_whence == SEEK_CUR)
326 			fl.l_start += fp->f_offset;
327 		if ((error = VOP_ADVLOCK(vp,(caddr_t)p,F_GETLK,&fl,F_POSIX)))
328 			return (error);
329 		return (copyout((caddr_t)&fl, (caddr_t)uap->arg, sizeof (fl)));
330 
331 	default:
332 		return (EINVAL);
333 	}
334 	/* NOTREACHED */
335 }
336 
337 /*
338  * Common code for dup, dup2, and fcntl(F_DUPFD).
339  */
340 static int
341 finishdup(fdp, old, new, retval)
342 	register struct filedesc *fdp;
343 	register int old, new, *retval;
344 {
345 	register struct file *fp;
346 
347 	fp = fdp->fd_ofiles[old];
348 	fdp->fd_ofiles[new] = fp;
349 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
350 	fp->f_count++;
351 	if (new > fdp->fd_lastfile)
352 		fdp->fd_lastfile = new;
353 	*retval = new;
354 	return (0);
355 }
356 
357 /*
358  * Close a file descriptor.
359  */
360 #ifndef _SYS_SYSPROTO_H_
361 struct close_args {
362         int     fd;
363 };
364 #endif
365 /* ARGSUSED */
366 int
367 close(p, uap, retval)
368 	struct proc *p;
369 	struct close_args *uap;
370 	int *retval;
371 {
372 	register struct filedesc *fdp = p->p_fd;
373 	register struct file *fp;
374 	register int fd = uap->fd;
375 	register u_char *pf;
376 
377 	if ((unsigned)fd >= fdp->fd_nfiles ||
378 	    (fp = fdp->fd_ofiles[fd]) == NULL)
379 		return (EBADF);
380 	pf = (u_char *)&fdp->fd_ofileflags[fd];
381 	if (*pf & UF_MAPPED)
382 		(void) munmapfd(p, fd);
383 	fdp->fd_ofiles[fd] = NULL;
384 	while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
385 		fdp->fd_lastfile--;
386 	if (fd < fdp->fd_freefile)
387 		fdp->fd_freefile = fd;
388 	*pf = 0;
389 	return (closef(fp, p));
390 }
391 
392 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
393 /*
394  * Return status information about a file descriptor.
395  */
396 #ifndef _SYS_SYSPROTO_H_
397 struct ofstat_args {
398 	int	fd;
399 	struct	ostat *sb;
400 };
401 #endif
402 /* ARGSUSED */
403 int
404 ofstat(p, uap, retval)
405 	struct proc *p;
406 	register struct ofstat_args *uap;
407 	int *retval;
408 {
409 	register struct filedesc *fdp = p->p_fd;
410 	register struct file *fp;
411 	struct stat ub;
412 	struct ostat oub;
413 	int error;
414 
415 	if ((unsigned)uap->fd >= fdp->fd_nfiles ||
416 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
417 		return (EBADF);
418 	switch (fp->f_type) {
419 
420 	case DTYPE_VNODE:
421 		error = vn_stat((struct vnode *)fp->f_data, &ub, p);
422 		break;
423 
424 	case DTYPE_SOCKET:
425 		error = soo_stat((struct socket *)fp->f_data, &ub);
426 		break;
427 
428 #ifndef OLD_PIPE
429 	case DTYPE_PIPE:
430 		error = pipe_stat((struct pipe *)fp->f_data, &ub);
431 		break;
432 #endif
433 
434 	default:
435 		panic("ofstat");
436 		/*NOTREACHED*/
437 	}
438 	cvtstat(&ub, &oub);
439 	if (error == 0)
440 		error = copyout((caddr_t)&oub, (caddr_t)uap->sb, sizeof (oub));
441 	return (error);
442 }
443 #endif /* COMPAT_43 || COMPAT_SUNOS */
444 
445 /*
446  * Return status information about a file descriptor.
447  */
448 #ifndef _SYS_SYSPROTO_H_
449 struct fstat_args {
450 	int	fd;
451 	struct	stat *sb;
452 };
453 #endif
454 /* ARGSUSED */
455 int
456 fstat(p, uap, retval)
457 	struct proc *p;
458 	register struct fstat_args *uap;
459 	int *retval;
460 {
461 	register struct filedesc *fdp = p->p_fd;
462 	register struct file *fp;
463 	struct stat ub;
464 	int error;
465 
466 	if ((unsigned)uap->fd >= fdp->fd_nfiles ||
467 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
468 		return (EBADF);
469 	switch (fp->f_type) {
470 
471 	case DTYPE_VNODE:
472 		error = vn_stat((struct vnode *)fp->f_data, &ub, p);
473 		break;
474 
475 	case DTYPE_SOCKET:
476 		error = soo_stat((struct socket *)fp->f_data, &ub);
477 		break;
478 
479 #ifndef OLD_PIPE
480 	case DTYPE_PIPE:
481 		error = pipe_stat((struct pipe *)fp->f_data, &ub);
482 		break;
483 #endif
484 
485 	default:
486 		panic("fstat");
487 		/*NOTREACHED*/
488 	}
489 	if (error == 0)
490 		error = copyout((caddr_t)&ub, (caddr_t)uap->sb, sizeof (ub));
491 	return (error);
492 }
493 
494 /*
495  * Return pathconf information about a file descriptor.
496  */
497 #ifndef _SYS_SYSPROTO_H_
498 struct fpathconf_args {
499 	int	fd;
500 	int	name;
501 };
502 #endif
503 /* ARGSUSED */
504 int
505 fpathconf(p, uap, retval)
506 	struct proc *p;
507 	register struct fpathconf_args *uap;
508 	int *retval;
509 {
510 	struct filedesc *fdp = p->p_fd;
511 	struct file *fp;
512 	struct vnode *vp;
513 
514 	if ((unsigned)uap->fd >= fdp->fd_nfiles ||
515 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
516 		return (EBADF);
517 	switch (fp->f_type) {
518 
519 #ifndef OLD_PIPE
520 	case DTYPE_PIPE:
521 #endif
522 	case DTYPE_SOCKET:
523 		if (uap->name != _PC_PIPE_BUF)
524 			return (EINVAL);
525 		*retval = PIPE_BUF;
526 		return (0);
527 
528 	case DTYPE_VNODE:
529 		vp = (struct vnode *)fp->f_data;
530 		return (VOP_PATHCONF(vp, uap->name, retval));
531 
532 	default:
533 		panic("fpathconf");
534 	}
535 	/*NOTREACHED*/
536 }
537 
538 /*
539  * Allocate a file descriptor for the process.
540  */
541 static int fdexpand;
542 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
543 
544 int
545 fdalloc(p, want, result)
546 	struct proc *p;
547 	int want;
548 	int *result;
549 {
550 	register struct filedesc *fdp = p->p_fd;
551 	register int i;
552 	int lim, last, nfiles;
553 	struct file **newofile;
554 	char *newofileflags;
555 
556 	/*
557 	 * Search for a free descriptor starting at the higher
558 	 * of want or fd_freefile.  If that fails, consider
559 	 * expanding the ofile array.
560 	 */
561 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
562 	for (;;) {
563 		last = min(fdp->fd_nfiles, lim);
564 		if ((i = want) < fdp->fd_freefile)
565 			i = fdp->fd_freefile;
566 		for (; i < last; i++) {
567 			if (fdp->fd_ofiles[i] == NULL) {
568 				fdp->fd_ofileflags[i] = 0;
569 				if (i > fdp->fd_lastfile)
570 					fdp->fd_lastfile = i;
571 				if (want <= fdp->fd_freefile)
572 					fdp->fd_freefile = i;
573 				*result = i;
574 				return (0);
575 			}
576 		}
577 
578 		/*
579 		 * No space in current array.  Expand?
580 		 */
581 		if (fdp->fd_nfiles >= lim)
582 			return (EMFILE);
583 		if (fdp->fd_nfiles < NDEXTENT)
584 			nfiles = NDEXTENT;
585 		else
586 			nfiles = 2 * fdp->fd_nfiles;
587 		MALLOC(newofile, struct file **, nfiles * OFILESIZE,
588 		    M_FILEDESC, M_WAITOK);
589 		newofileflags = (char *) &newofile[nfiles];
590 		/*
591 		 * Copy the existing ofile and ofileflags arrays
592 		 * and zero the new portion of each array.
593 		 */
594 		bcopy(fdp->fd_ofiles, newofile,
595 			(i = sizeof(struct file *) * fdp->fd_nfiles));
596 		bzero((char *)newofile + i, nfiles * sizeof(struct file *) - i);
597 		bcopy(fdp->fd_ofileflags, newofileflags,
598 			(i = sizeof(char) * fdp->fd_nfiles));
599 		bzero(newofileflags + i, nfiles * sizeof(char) - i);
600 		if (fdp->fd_nfiles > NDFILE)
601 			FREE(fdp->fd_ofiles, M_FILEDESC);
602 		fdp->fd_ofiles = newofile;
603 		fdp->fd_ofileflags = newofileflags;
604 		fdp->fd_nfiles = nfiles;
605 		fdexpand++;
606 	}
607 	return (0);
608 }
609 
610 /*
611  * Check to see whether n user file descriptors
612  * are available to the process p.
613  */
614 int
615 fdavail(p, n)
616 	struct proc *p;
617 	register int n;
618 {
619 	register struct filedesc *fdp = p->p_fd;
620 	register struct file **fpp;
621 	register int i, lim, last;
622 
623 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
624 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
625 		return (1);
626 
627 	last = min(fdp->fd_nfiles, lim);
628 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
629 	for (i = last - fdp->fd_freefile; --i >= 0; fpp++)
630 		if (*fpp == NULL && --n <= 0)
631 			return (1);
632 	return (0);
633 }
634 
635 /*
636  * Create a new open file structure and allocate
637  * a file decriptor for the process that refers to it.
638  */
639 int
640 falloc(p, resultfp, resultfd)
641 	register struct proc *p;
642 	struct file **resultfp;
643 	int *resultfd;
644 {
645 	register struct file *fp, *fq;
646 	int error, i;
647 
648 	if ((error = fdalloc(p, 0, &i)))
649 		return (error);
650 	if (nfiles >= maxfiles) {
651 		tablefull("file");
652 		return (ENFILE);
653 	}
654 	/*
655 	 * Allocate a new file descriptor.
656 	 * If the process has file descriptor zero open, add to the list
657 	 * of open files at that point, otherwise put it at the front of
658 	 * the list of open files.
659 	 */
660 	nfiles++;
661 	MALLOC(fp, struct file *, sizeof(struct file), M_FILE, M_WAITOK);
662 	bzero(fp, sizeof(struct file));
663 	if ((fq = p->p_fd->fd_ofiles[0])) {
664 		LIST_INSERT_AFTER(fq, fp, f_list);
665 	} else {
666 		LIST_INSERT_HEAD(&filehead, fp, f_list);
667 	}
668 	p->p_fd->fd_ofiles[i] = fp;
669 	fp->f_count = 1;
670 	fp->f_cred = p->p_ucred;
671 	crhold(fp->f_cred);
672 	if (resultfp)
673 		*resultfp = fp;
674 	if (resultfd)
675 		*resultfd = i;
676 	return (0);
677 }
678 
679 /*
680  * Free a file descriptor.
681  */
682 void
683 ffree(fp)
684 	register struct file *fp;
685 {
686 	LIST_REMOVE(fp, f_list);
687 	crfree(fp->f_cred);
688 #ifdef DIAGNOSTIC
689 	fp->f_count = 0;
690 #endif
691 	nfiles--;
692 	FREE(fp, M_FILE);
693 }
694 
695 /*
696  * Build a new filedesc structure.
697  */
698 struct filedesc *
699 fdinit(p)
700 	struct proc *p;
701 {
702 	register struct filedesc0 *newfdp;
703 	register struct filedesc *fdp = p->p_fd;
704 
705 	MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
706 	    M_FILEDESC, M_WAITOK);
707 	bzero(newfdp, sizeof(struct filedesc0));
708 	newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
709 	VREF(newfdp->fd_fd.fd_cdir);
710 	newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
711 	if (newfdp->fd_fd.fd_rdir)
712 		VREF(newfdp->fd_fd.fd_rdir);
713 
714 	/* Create the file descriptor table. */
715 	newfdp->fd_fd.fd_refcnt = 1;
716 	newfdp->fd_fd.fd_cmask = cmask;
717 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
718 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
719 	newfdp->fd_fd.fd_nfiles = NDFILE;
720 
721 	newfdp->fd_fd.fd_freefile = 0;
722 	newfdp->fd_fd.fd_lastfile = 0;
723 
724 	return (&newfdp->fd_fd);
725 }
726 
727 /*
728  * Share a filedesc structure.
729  */
730 struct filedesc *
731 fdshare(p)
732 	struct proc *p;
733 {
734 	p->p_fd->fd_refcnt++;
735 	return (p->p_fd);
736 }
737 
738 /*
739  * Copy a filedesc structure.
740  */
741 struct filedesc *
742 fdcopy(p)
743 	struct proc *p;
744 {
745 	register struct filedesc *newfdp, *fdp = p->p_fd;
746 	register struct file **fpp;
747 	register int i;
748 
749 	MALLOC(newfdp, struct filedesc *, sizeof(struct filedesc0),
750 	    M_FILEDESC, M_WAITOK);
751 	bcopy(fdp, newfdp, sizeof(struct filedesc));
752 	VREF(newfdp->fd_cdir);
753 	if (newfdp->fd_rdir)
754 		VREF(newfdp->fd_rdir);
755 	newfdp->fd_refcnt = 1;
756 
757 	/*
758 	 * If the number of open files fits in the internal arrays
759 	 * of the open file structure, use them, otherwise allocate
760 	 * additional memory for the number of descriptors currently
761 	 * in use.
762 	 */
763 	if (newfdp->fd_lastfile < NDFILE) {
764 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
765 		newfdp->fd_ofileflags =
766 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
767 		i = NDFILE;
768 	} else {
769 		/*
770 		 * Compute the smallest multiple of NDEXTENT needed
771 		 * for the file descriptors currently in use,
772 		 * allowing the table to shrink.
773 		 */
774 		i = newfdp->fd_nfiles;
775 		while (i > 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
776 			i /= 2;
777 		MALLOC(newfdp->fd_ofiles, struct file **, i * OFILESIZE,
778 		    M_FILEDESC, M_WAITOK);
779 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
780 	}
781 	newfdp->fd_nfiles = i;
782 	bcopy(fdp->fd_ofiles, newfdp->fd_ofiles, i * sizeof(struct file **));
783 	bcopy(fdp->fd_ofileflags, newfdp->fd_ofileflags, i * sizeof(char));
784 	fpp = newfdp->fd_ofiles;
785 	for (i = newfdp->fd_lastfile; i-- >= 0; fpp++)
786 		if (*fpp != NULL)
787 			(*fpp)->f_count++;
788 	return (newfdp);
789 }
790 
791 /*
792  * Release a filedesc structure.
793  */
794 void
795 fdfree(p)
796 	struct proc *p;
797 {
798 	register struct filedesc *fdp = p->p_fd;
799 	struct file **fpp;
800 	register int i;
801 
802 	if (--fdp->fd_refcnt > 0)
803 		return;
804 	fpp = fdp->fd_ofiles;
805 	for (i = fdp->fd_lastfile; i-- >= 0; fpp++)
806 		if (*fpp)
807 			(void) closef(*fpp, p);
808 	if (fdp->fd_nfiles > NDFILE)
809 		FREE(fdp->fd_ofiles, M_FILEDESC);
810 	vrele(fdp->fd_cdir);
811 	if (fdp->fd_rdir)
812 		vrele(fdp->fd_rdir);
813 	FREE(fdp, M_FILEDESC);
814 }
815 
816 /*
817  * Close any files on exec?
818  */
819 void
820 fdcloseexec(p)
821 	struct proc *p;
822 {
823 	struct filedesc *fdp = p->p_fd;
824 	struct file **fpp;
825 	char *fdfp;
826 	register int i;
827 
828 	fpp = fdp->fd_ofiles;
829 	fdfp = fdp->fd_ofileflags;
830 	for (i = 0; i <= fdp->fd_lastfile; i++, fpp++, fdfp++)
831 		if (*fpp != NULL && (*fdfp & UF_EXCLOSE)) {
832 			if (*fdfp & UF_MAPPED)
833 				(void) munmapfd(p, i);
834 			(void) closef(*fpp, p);
835 			*fpp = NULL;
836 			*fdfp = 0;
837 			if (i < fdp->fd_freefile)
838 				fdp->fd_freefile = i;
839 		}
840 	while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
841 		fdp->fd_lastfile--;
842 }
843 
844 /*
845  * Internal form of close.
846  * Decrement reference count on file structure.
847  * Note: p may be NULL when closing a file
848  * that was being passed in a message.
849  */
850 int
851 closef(fp, p)
852 	register struct file *fp;
853 	register struct proc *p;
854 {
855 	struct vnode *vp;
856 	struct flock lf;
857 	int error;
858 
859 	if (fp == NULL)
860 		return (0);
861 	/*
862 	 * POSIX record locking dictates that any close releases ALL
863 	 * locks owned by this process.  This is handled by setting
864 	 * a flag in the unlock to free ONLY locks obeying POSIX
865 	 * semantics, and not to free BSD-style file locks.
866 	 * If the descriptor was in a message, POSIX-style locks
867 	 * aren't passed with the descriptor.
868 	 */
869 	if (p && (p->p_flag & P_ADVLOCK) && fp->f_type == DTYPE_VNODE) {
870 		lf.l_whence = SEEK_SET;
871 		lf.l_start = 0;
872 		lf.l_len = 0;
873 		lf.l_type = F_UNLCK;
874 		vp = (struct vnode *)fp->f_data;
875 		(void) VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_POSIX);
876 	}
877 	if (--fp->f_count > 0)
878 		return (0);
879 	if (fp->f_count < 0)
880 		panic("closef: count < 0");
881 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
882 		lf.l_whence = SEEK_SET;
883 		lf.l_start = 0;
884 		lf.l_len = 0;
885 		lf.l_type = F_UNLCK;
886 		vp = (struct vnode *)fp->f_data;
887 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
888 	}
889 	if (fp->f_ops)
890 		error = (*fp->f_ops->fo_close)(fp, p);
891 	else
892 		error = 0;
893 	ffree(fp);
894 	return (error);
895 }
896 
897 /*
898  * Apply an advisory lock on a file descriptor.
899  *
900  * Just attempt to get a record lock of the requested type on
901  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
902  */
903 #ifndef _SYS_SYSPROTO_H_
904 struct flock_args {
905 	int	fd;
906 	int	how;
907 };
908 #endif
909 /* ARGSUSED */
910 int
911 flock(p, uap, retval)
912 	struct proc *p;
913 	register struct flock_args *uap;
914 	int *retval;
915 {
916 	register struct filedesc *fdp = p->p_fd;
917 	register struct file *fp;
918 	struct vnode *vp;
919 	struct flock lf;
920 
921 	if ((unsigned)uap->fd >= fdp->fd_nfiles ||
922 	    (fp = fdp->fd_ofiles[uap->fd]) == NULL)
923 		return (EBADF);
924 	if (fp->f_type != DTYPE_VNODE)
925 		return (EOPNOTSUPP);
926 	vp = (struct vnode *)fp->f_data;
927 	lf.l_whence = SEEK_SET;
928 	lf.l_start = 0;
929 	lf.l_len = 0;
930 	if (uap->how & LOCK_UN) {
931 		lf.l_type = F_UNLCK;
932 		fp->f_flag &= ~FHASLOCK;
933 		return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK));
934 	}
935 	if (uap->how & LOCK_EX)
936 		lf.l_type = F_WRLCK;
937 	else if (uap->how & LOCK_SH)
938 		lf.l_type = F_RDLCK;
939 	else
940 		return (EBADF);
941 	fp->f_flag |= FHASLOCK;
942 	if (uap->how & LOCK_NB)
943 		return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK));
944 	return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT));
945 }
946 
947 /*
948  * File Descriptor pseudo-device driver (/dev/fd/).
949  *
950  * Opening minor device N dup()s the file (if any) connected to file
951  * descriptor N belonging to the calling process.  Note that this driver
952  * consists of only the ``open()'' routine, because all subsequent
953  * references to this file will be direct to the other driver.
954  */
955 /* ARGSUSED */
956 static int
957 fdopen(dev, mode, type, p)
958 	dev_t dev;
959 	int mode, type;
960 	struct proc *p;
961 {
962 
963 	/*
964 	 * XXX Kludge: set curproc->p_dupfd to contain the value of the
965 	 * the file descriptor being sought for duplication. The error
966 	 * return ensures that the vnode for this device will be released
967 	 * by vn_open. Open will detect this special error and take the
968 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
969 	 * will simply report the error.
970 	 */
971 	p->p_dupfd = minor(dev);
972 	return (ENODEV);
973 }
974 
975 /*
976  * Duplicate the specified descriptor to a free descriptor.
977  */
978 int
979 dupfdopen(fdp, indx, dfd, mode, error)
980 	register struct filedesc *fdp;
981 	register int indx, dfd;
982 	int mode;
983 	int error;
984 {
985 	register struct file *wfp;
986 	struct file *fp;
987 
988 	/*
989 	 * If the to-be-dup'd fd number is greater than the allowed number
990 	 * of file descriptors, or the fd to be dup'd has already been
991 	 * closed, reject.  Note, check for new == old is necessary as
992 	 * falloc could allocate an already closed to-be-dup'd descriptor
993 	 * as the new descriptor.
994 	 */
995 	fp = fdp->fd_ofiles[indx];
996 	if ((u_int)dfd >= fdp->fd_nfiles ||
997 	    (wfp = fdp->fd_ofiles[dfd]) == NULL || fp == wfp)
998 		return (EBADF);
999 
1000 	/*
1001 	 * There are two cases of interest here.
1002 	 *
1003 	 * For ENODEV simply dup (dfd) to file descriptor
1004 	 * (indx) and return.
1005 	 *
1006 	 * For ENXIO steal away the file structure from (dfd) and
1007 	 * store it in (indx).  (dfd) is effectively closed by
1008 	 * this operation.
1009 	 *
1010 	 * Any other error code is just returned.
1011 	 */
1012 	switch (error) {
1013 	case ENODEV:
1014 		/*
1015 		 * Check that the mode the file is being opened for is a
1016 		 * subset of the mode of the existing descriptor.
1017 		 */
1018 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1019 			return (EACCES);
1020 		fdp->fd_ofiles[indx] = wfp;
1021 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1022 		wfp->f_count++;
1023 		if (indx > fdp->fd_lastfile)
1024 			fdp->fd_lastfile = indx;
1025 		return (0);
1026 
1027 	case ENXIO:
1028 		/*
1029 		 * Steal away the file pointer from dfd, and stuff it into indx.
1030 		 */
1031 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
1032 		fdp->fd_ofiles[dfd] = NULL;
1033 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1034 		fdp->fd_ofileflags[dfd] = 0;
1035 		/*
1036 		 * Complete the clean up of the filedesc structure by
1037 		 * recomputing the various hints.
1038 		 */
1039 		if (indx > fdp->fd_lastfile)
1040 			fdp->fd_lastfile = indx;
1041 		else
1042 			while (fdp->fd_lastfile > 0 &&
1043 			       fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1044 				fdp->fd_lastfile--;
1045 			if (dfd < fdp->fd_freefile)
1046 				fdp->fd_freefile = dfd;
1047 		return (0);
1048 
1049 	default:
1050 		return (error);
1051 	}
1052 	/* NOTREACHED */
1053 }
1054 
1055 /*
1056  * Get file structures.
1057  */
1058 static int
1059 sysctl_kern_file SYSCTL_HANDLER_ARGS
1060 {
1061 	int error;
1062 	struct file *fp;
1063 
1064 	if (!req->oldptr) {
1065 		/*
1066 		 * overestimate by 10 files
1067 		 */
1068 		return (SYSCTL_OUT(req, 0, sizeof(filehead) +
1069 				(nfiles + 10) * sizeof(struct file)));
1070 	}
1071 
1072 	error = SYSCTL_OUT(req, (caddr_t)&filehead, sizeof(filehead));
1073 	if (error)
1074 		return (error);
1075 
1076 	/*
1077 	 * followed by an array of file structures
1078 	 */
1079 	for (fp = filehead.lh_first; fp != NULL; fp = fp->f_list.le_next) {
1080 		error = SYSCTL_OUT(req, (caddr_t)fp, sizeof (struct file));
1081 		if (error)
1082 			return (error);
1083 	}
1084 	return (0);
1085 }
1086 
1087 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
1088 	0, 0, sysctl_kern_file, "S,file", "");
1089 
1090 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc,
1091 	CTLFLAG_RW, &maxfilesperproc, 0, "");
1092 
1093 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW, &maxfiles, 0, "");
1094 
1095 static fildesc_devsw_installed = 0;
1096 #ifdef DEVFS
1097 static	void *devfs_token_stdin;
1098 static	void *devfs_token_stdout;
1099 static	void *devfs_token_stderr;
1100 static	void *devfs_token_fildesc[NUMFDESC];
1101 #endif
1102 
1103 static void 	fildesc_drvinit(void *unused)
1104 {
1105 	dev_t dev;
1106 #ifdef DEVFS
1107 	int fd;
1108 #endif
1109 
1110 	if( ! fildesc_devsw_installed ) {
1111 		dev = makedev(CDEV_MAJOR,0);
1112 		cdevsw_add(&dev,&fildesc_cdevsw,NULL);
1113 		fildesc_devsw_installed = 1;
1114 #ifdef DEVFS
1115 		for (fd = 0; fd < NUMFDESC; fd++)
1116 			devfs_token_fildesc[fd] =
1117 				devfs_add_devswf(&fildesc_cdevsw, fd, DV_CHR,
1118 						 UID_BIN, GID_BIN, 0666,
1119 						 "fd/%d", fd);
1120 		devfs_token_stdin =
1121 			devfs_add_devswf(&fildesc_cdevsw, 0, DV_CHR,
1122 					 UID_ROOT, GID_WHEEL, 0666,
1123 					 "stdin", fd);
1124 		devfs_token_stdout =
1125 			devfs_add_devswf(&fildesc_cdevsw, 1, DV_CHR,
1126 					 UID_ROOT, GID_WHEEL, 0666,
1127 					 "stdout", fd);
1128 		devfs_token_stderr =
1129 			devfs_add_devswf(&fildesc_cdevsw, 2, DV_CHR,
1130 					 UID_ROOT, GID_WHEEL, 0666,
1131 					 "stderr", fd);
1132 #endif
1133     	}
1134 }
1135 
1136 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
1137 					fildesc_drvinit,NULL)
1138 
1139 
1140