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