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