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