Convert most manual accesses to filedesc->fd_files[] into the appropriate
[dragonfly.git] / sys / kern / kern_descrip.c
1 /*
2  * Copyright (c) 2005 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Jeffrey Hsu.
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *
35  * Copyright (c) 1982, 1986, 1989, 1991, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  * (c) UNIX System Laboratories, Inc.
38  * All or some portions of this file are derived from material licensed
39  * to the University of California by American Telephone and Telegraph
40  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
41  * the permission of UNIX System Laboratories, Inc.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *      This product includes software developed by the University of
54  *      California, Berkeley and its contributors.
55  * 4. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  *
71  *      @(#)kern_descrip.c      8.6 (Berkeley) 4/19/94
72  * $FreeBSD: src/sys/kern/kern_descrip.c,v 1.81.2.19 2004/02/28 00:43:31 tegge Exp $
73  * $DragonFly: src/sys/kern/kern_descrip.c,v 1.58 2006/05/19 07:33:45 dillon Exp $
74  */
75
76 #include "opt_compat.h"
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/malloc.h>
80 #include <sys/sysproto.h>
81 #include <sys/conf.h>
82 #include <sys/filedesc.h>
83 #include <sys/kernel.h>
84 #include <sys/sysctl.h>
85 #include <sys/vnode.h>
86 #include <sys/proc.h>
87 #include <sys/nlookup.h>
88 #include <sys/file.h>
89 #include <sys/stat.h>
90 #include <sys/filio.h>
91 #include <sys/fcntl.h>
92 #include <sys/unistd.h>
93 #include <sys/resourcevar.h>
94 #include <sys/event.h>
95 #include <sys/kern_syscall.h>
96 #include <sys/kcore.h>
97 #include <sys/kinfo.h>
98
99 #include <vm/vm.h>
100 #include <vm/vm_extern.h>
101
102 #include <sys/thread2.h>
103 #include <sys/file2.h>
104
105 static void fdreserve (struct filedesc *fdp, int fd0, int incr);
106 static void funsetfd (struct filedesc *fdp, int fd);
107
108 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
109 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
110                      "file desc to leader structures");
111 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
112 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
113
114 static   d_open_t  fdopen;
115 #define NUMFDESC 64
116
117 #define CDEV_MAJOR 22
118 static struct cdevsw fildesc_cdevsw = {
119         /* name */      "FD",
120         /* maj */       CDEV_MAJOR,
121         /* flags */     0,
122         /* port */      NULL,
123         /* clone */     NULL,
124
125         /* open */      fdopen,
126         /* close */     noclose,
127         /* read */      noread,
128         /* write */     nowrite,
129         /* ioctl */     noioctl,
130         /* poll */      nopoll,
131         /* mmap */      nommap,
132         /* strategy */  nostrategy,
133         /* dump */      nodump,
134         /* psize */     nopsize
135 };
136
137 static int badfo_readwrite (struct file *fp, struct uio *uio,
138     struct ucred *cred, int flags);
139 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
140     struct ucred *cred);
141 static int badfo_poll (struct file *fp, int events, struct ucred *cred);
142 static int badfo_kqfilter (struct file *fp, struct knote *kn);
143 static int badfo_stat (struct file *fp, struct stat *sb, struct ucred *cred);
144 static int badfo_close (struct file *fp);
145 static int badfo_shutdown (struct file *fp, int how);
146
147 /*
148  * Descriptor management.
149  */
150 struct filelist filehead;       /* head of list of open files */
151 int nfiles;                     /* actual number of open files */
152 extern int cmask;       
153
154 /*
155  * System calls on descriptors.
156  */
157 /* ARGSUSED */
158 int
159 getdtablesize(struct getdtablesize_args *uap) 
160 {
161         struct proc *p = curproc;
162
163         uap->sysmsg_result = 
164             min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
165         return (0);
166 }
167
168 /*
169  * Duplicate a file descriptor to a particular value.
170  *
171  * note: keep in mind that a potential race condition exists when closing
172  * descriptors from a shared descriptor table (via rfork).
173  */
174 /* ARGSUSED */
175 int
176 dup2(struct dup2_args *uap)
177 {
178         int error;
179
180         error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
181
182         return (error);
183 }
184
185 /*
186  * Duplicate a file descriptor.
187  */
188 /* ARGSUSED */
189 int
190 dup(struct dup_args *uap)
191 {
192         int error;
193
194         error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
195
196         return (error);
197 }
198
199 int
200 kern_fcntl(int fd, int cmd, union fcntl_dat *dat, struct ucred *cred)
201 {
202         struct thread *td = curthread;
203         struct proc *p = td->td_proc;
204         struct filedesc *fdp = p->p_fd;
205         struct file *fp;
206         char *pop;
207         struct vnode *vp;
208         u_int newmin;
209         int tmp, error, flg = F_POSIX;
210
211         KKASSERT(p);
212
213         if ((unsigned)fd >= fdp->fd_nfiles ||
214             (fp = fdp->fd_files[fd].fp) == NULL)
215                 return (EBADF);
216         pop = &fdp->fd_files[fd].fileflags;
217
218         switch (cmd) {
219         case F_DUPFD:
220                 newmin = dat->fc_fd;
221                 if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
222                     newmin > maxfilesperproc)
223                         return (EINVAL);
224                 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
225                 return (error);
226
227         case F_GETFD:
228                 dat->fc_cloexec = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
229                 return (0);
230
231         case F_SETFD:
232                 *pop = (*pop &~ UF_EXCLOSE) |
233                     (dat->fc_cloexec & FD_CLOEXEC ? UF_EXCLOSE : 0);
234                 return (0);
235
236         case F_GETFL:
237                 dat->fc_flags = OFLAGS(fp->f_flag);
238                 return (0);
239
240         case F_SETFL:
241                 fhold(fp);
242                 fp->f_flag &= ~FCNTLFLAGS;
243                 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
244                 tmp = fp->f_flag & FNONBLOCK;
245                 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
246                 if (error) {
247                         fdrop(fp);
248                         return (error);
249                 }
250                 tmp = fp->f_flag & FASYNC;
251                 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred);
252                 if (!error) {
253                         fdrop(fp);
254                         return (0);
255                 }
256                 fp->f_flag &= ~FNONBLOCK;
257                 tmp = 0;
258                 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
259                 fdrop(fp);
260                 return (error);
261
262         case F_GETOWN:
263                 fhold(fp);
264                 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, cred);
265                 fdrop(fp);
266                 return(error);
267
268         case F_SETOWN:
269                 fhold(fp);
270                 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, cred);
271                 fdrop(fp);
272                 return(error);
273
274         case F_SETLKW:
275                 flg |= F_WAIT;
276                 /* Fall into F_SETLK */
277
278         case F_SETLK:
279                 if (fp->f_type != DTYPE_VNODE)
280                         return (EBADF);
281                 vp = (struct vnode *)fp->f_data;
282
283                 /*
284                  * copyin/lockop may block
285                  */
286                 fhold(fp);
287                 if (dat->fc_flock.l_whence == SEEK_CUR)
288                         dat->fc_flock.l_start += fp->f_offset;
289
290                 switch (dat->fc_flock.l_type) {
291                 case F_RDLCK:
292                         if ((fp->f_flag & FREAD) == 0) {
293                                 error = EBADF;
294                                 break;
295                         }
296                         p->p_leader->p_flag |= P_ADVLOCK;
297                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
298                             &dat->fc_flock, flg);
299                         break;
300                 case F_WRLCK:
301                         if ((fp->f_flag & FWRITE) == 0) {
302                                 error = EBADF;
303                                 break;
304                         }
305                         p->p_leader->p_flag |= P_ADVLOCK;
306                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
307                             &dat->fc_flock, flg);
308                         break;
309                 case F_UNLCK:
310                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
311                                 &dat->fc_flock, F_POSIX);
312                         break;
313                 default:
314                         error = EINVAL;
315                         break;
316                 }
317                 /* Check for race with close */
318                 if ((unsigned) fd >= fdp->fd_nfiles ||
319                     fp != fdp->fd_files[fd].fp) {
320                         dat->fc_flock.l_whence = SEEK_SET;
321                         dat->fc_flock.l_start = 0;
322                         dat->fc_flock.l_len = 0;
323                         dat->fc_flock.l_type = F_UNLCK;
324                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
325                                            F_UNLCK, &dat->fc_flock, F_POSIX);
326                 }
327                 fdrop(fp);
328                 return(error);
329
330         case F_GETLK:
331                 if (fp->f_type != DTYPE_VNODE)
332                         return (EBADF);
333                 vp = (struct vnode *)fp->f_data;
334                 /*
335                  * copyin/lockop may block
336                  */
337                 fhold(fp);
338                 if (dat->fc_flock.l_type != F_RDLCK &&
339                     dat->fc_flock.l_type != F_WRLCK &&
340                     dat->fc_flock.l_type != F_UNLCK) {
341                         fdrop(fp);
342                         return (EINVAL);
343                 }
344                 if (dat->fc_flock.l_whence == SEEK_CUR)
345                         dat->fc_flock.l_start += fp->f_offset;
346                 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
347                             &dat->fc_flock, F_POSIX);
348                 fdrop(fp);
349                 return(error);
350         default:
351                 return (EINVAL);
352         }
353         /* NOTREACHED */
354 }
355
356 /*
357  * The file control system call.
358  */
359 int
360 fcntl(struct fcntl_args *uap)
361 {
362         union fcntl_dat dat;
363         int error;
364
365         switch (uap->cmd) {
366         case F_DUPFD:
367                 dat.fc_fd = uap->arg;
368                 break;
369         case F_SETFD:
370                 dat.fc_cloexec = uap->arg;
371                 break;
372         case F_SETFL:
373                 dat.fc_flags = uap->arg;
374                 break;
375         case F_SETOWN:
376                 dat.fc_owner = uap->arg;
377                 break;
378         case F_SETLKW:
379         case F_SETLK:
380         case F_GETLK:
381                 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
382                     sizeof(struct flock));
383                 if (error)
384                         return (error);
385                 break;
386         }
387
388         error = kern_fcntl(uap->fd, uap->cmd, &dat, curproc->p_ucred);
389
390         if (error == 0) {
391                 switch (uap->cmd) {
392                 case F_DUPFD:
393                         uap->sysmsg_result = dat.fc_fd;
394                         break;
395                 case F_GETFD:
396                         uap->sysmsg_result = dat.fc_cloexec;
397                         break;
398                 case F_GETFL:
399                         uap->sysmsg_result = dat.fc_flags;
400                         break;
401                 case F_GETOWN:
402                         uap->sysmsg_result = dat.fc_owner;
403                 case F_GETLK:
404                         error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
405                             sizeof(struct flock));
406                         break;
407                 }
408         }
409
410         return (error);
411 }
412
413 /*
414  * Common code for dup, dup2, and fcntl(F_DUPFD).
415  *
416  * The type flag can be either DUP_FIXED or DUP_VARIABLE.  DUP_FIXED tells
417  * kern_dup() to destructively dup over an existing file descriptor if new
418  * is already open.  DUP_VARIABLE tells kern_dup() to find the lowest
419  * unused file descriptor that is greater than or equal to new.
420  */
421 int
422 kern_dup(enum dup_type type, int old, int new, int *res)
423 {
424         struct thread *td = curthread;
425         struct proc *p = td->td_proc;
426         struct filedesc *fdp = p->p_fd;
427         struct file *fp;
428         struct file *delfp;
429         int holdleaders;
430         boolean_t fdalloced = FALSE;
431         int error, newfd;
432
433         /*
434          * Verify that we have a valid descriptor to dup from and
435          * possibly to dup to.
436          */
437         if (old < 0 || new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
438             new >= maxfilesperproc)
439                 return (EBADF);
440         if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL)
441                 return (EBADF);
442         if (type == DUP_FIXED && old == new) {
443                 *res = new;
444                 return (0);
445         }
446         fp = fdp->fd_files[old].fp;
447         fhold(fp);
448
449         /*
450          * Expand the table for the new descriptor if needed.  This may
451          * block and drop and reacquire the fidedesc lock.
452          */
453         if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
454                 error = fdalloc(p, new, &newfd);
455                 if (error) {
456                         fdrop(fp);
457                         return (error);
458                 }
459                 fdalloced = TRUE;
460         }
461         if (type == DUP_VARIABLE)
462                 new = newfd;
463
464         /*
465          * If the old file changed out from under us then treat it as a
466          * bad file descriptor.  Userland should do its own locking to
467          * avoid this case.
468          */
469         if (fdp->fd_files[old].fp != fp) {
470                 if (fdp->fd_files[new].fp == NULL) {
471                         if (fdalloced)
472                                 fdreserve(fdp, newfd, -1);
473                         if (new < fdp->fd_freefile)
474                                 fdp->fd_freefile = new;
475                         while (fdp->fd_lastfile > 0 &&
476                             fdp->fd_files[fdp->fd_lastfile].fp == NULL)
477                                 fdp->fd_lastfile--;
478                 }
479                 fdrop(fp);
480                 return (EBADF);
481         }
482         KASSERT(old != new, ("new fd is same as old"));
483
484         /*
485          * Save info on the descriptor being overwritten.  We have
486          * to do the unmap now, but we cannot close it without
487          * introducing an ownership race for the slot.
488          */
489         delfp = fdp->fd_files[new].fp;
490         if (delfp != NULL && p->p_fdtol != NULL) {
491                 /*
492                  * Ask fdfree() to sleep to ensure that all relevant
493                  * process leaders can be traversed in closef().
494                  */
495                 fdp->fd_holdleaderscount++;
496                 holdleaders = 1;
497         } else
498                 holdleaders = 0;
499         KASSERT(delfp == NULL || type == DUP_FIXED,
500             ("dup() picked an open file"));
501
502         /*
503          * Duplicate the source descriptor, update lastfile
504          */
505         if (new > fdp->fd_lastfile)
506                 fdp->fd_lastfile = new;
507         if (!fdalloced && fdp->fd_files[new].fp == NULL)
508                 fdreserve(fdp, new, 1);
509         fdp->fd_files[new].fp = fp;
510         fdp->fd_files[new].fileflags = 
511                         fdp->fd_files[old].fileflags & ~UF_EXCLOSE;
512         *res = new;
513
514         /*
515          * If we dup'd over a valid file, we now own the reference to it
516          * and must dispose of it using closef() semantics (as if a
517          * close() were performed on it).
518          */
519         if (delfp) {
520                 (void) closef(delfp, td);
521                 if (holdleaders) {
522                         fdp->fd_holdleaderscount--;
523                         if (fdp->fd_holdleaderscount == 0 &&
524                             fdp->fd_holdleaderswakeup != 0) {
525                                 fdp->fd_holdleaderswakeup = 0;
526                                 wakeup(&fdp->fd_holdleaderscount);
527                         }
528                 }
529         }
530         return (0);
531 }
532
533 /*
534  * If sigio is on the list associated with a process or process group,
535  * disable signalling from the device, remove sigio from the list and
536  * free sigio.
537  */
538 void
539 funsetown(struct sigio *sigio)
540 {
541         if (sigio == NULL)
542                 return;
543         crit_enter();
544         *(sigio->sio_myref) = NULL;
545         crit_exit();
546         if (sigio->sio_pgid < 0) {
547                 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
548                              sigio, sio_pgsigio);
549         } else /* if ((*sigiop)->sio_pgid > 0) */ {
550                 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
551                              sigio, sio_pgsigio);
552         }
553         crfree(sigio->sio_ucred);
554         free(sigio, M_SIGIO);
555 }
556
557 /* Free a list of sigio structures. */
558 void
559 funsetownlst(struct sigiolst *sigiolst)
560 {
561         struct sigio *sigio;
562
563         while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
564                 funsetown(sigio);
565 }
566
567 /*
568  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
569  *
570  * After permission checking, add a sigio structure to the sigio list for
571  * the process or process group.
572  */
573 int
574 fsetown(pid_t pgid, struct sigio **sigiop)
575 {
576         struct proc *proc;
577         struct pgrp *pgrp;
578         struct sigio *sigio;
579
580         if (pgid == 0) {
581                 funsetown(*sigiop);
582                 return (0);
583         }
584         if (pgid > 0) {
585                 proc = pfind(pgid);
586                 if (proc == NULL)
587                         return (ESRCH);
588
589                 /*
590                  * Policy - Don't allow a process to FSETOWN a process
591                  * in another session.
592                  *
593                  * Remove this test to allow maximum flexibility or
594                  * restrict FSETOWN to the current process or process
595                  * group for maximum safety.
596                  */
597                 if (proc->p_session != curproc->p_session)
598                         return (EPERM);
599
600                 pgrp = NULL;
601         } else /* if (pgid < 0) */ {
602                 pgrp = pgfind(-pgid);
603                 if (pgrp == NULL)
604                         return (ESRCH);
605
606                 /*
607                  * Policy - Don't allow a process to FSETOWN a process
608                  * in another session.
609                  *
610                  * Remove this test to allow maximum flexibility or
611                  * restrict FSETOWN to the current process or process
612                  * group for maximum safety.
613                  */
614                 if (pgrp->pg_session != curproc->p_session)
615                         return (EPERM);
616
617                 proc = NULL;
618         }
619         funsetown(*sigiop);
620         sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
621         if (pgid > 0) {
622                 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
623                 sigio->sio_proc = proc;
624         } else {
625                 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
626                 sigio->sio_pgrp = pgrp;
627         }
628         sigio->sio_pgid = pgid;
629         sigio->sio_ucred = crhold(curproc->p_ucred);
630         /* It would be convenient if p_ruid was in ucred. */
631         sigio->sio_ruid = curproc->p_ucred->cr_ruid;
632         sigio->sio_myref = sigiop;
633         crit_enter();
634         *sigiop = sigio;
635         crit_exit();
636         return (0);
637 }
638
639 /*
640  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
641  */
642 pid_t
643 fgetown(struct sigio *sigio)
644 {
645         return (sigio != NULL ? sigio->sio_pgid : 0);
646 }
647
648 /*
649  * Close many file descriptors.
650  */
651 /* ARGSUSED */
652
653 int
654 closefrom(struct closefrom_args *uap)
655 {
656         return(kern_closefrom(uap->fd));
657 }
658
659 int
660 kern_closefrom(int fd)
661 {
662         struct thread *td = curthread;
663         struct proc *p = td->td_proc;
664         struct filedesc *fdp;
665
666         KKASSERT(p);
667         fdp = p->p_fd;
668
669         if (fd < 0 || fd > fdp->fd_lastfile)
670                 return (0);
671
672         do {
673                 if (kern_close(fdp->fd_lastfile) == EINTR)
674                         return (EINTR);
675         } while (fdp->fd_lastfile > fd);
676
677         return (0);
678 }
679
680 /*
681  * Close a file descriptor.
682  */
683 /* ARGSUSED */
684
685 int
686 close(struct close_args *uap)
687 {
688         return(kern_close(uap->fd));
689 }
690
691 int
692 kern_close(int fd)
693 {
694         struct thread *td = curthread;
695         struct proc *p = td->td_proc;
696         struct filedesc *fdp;
697         struct file *fp;
698         int error;
699         int holdleaders;
700
701         KKASSERT(p);
702         fdp = p->p_fd;
703
704         if ((unsigned)fd >= fdp->fd_nfiles ||
705             (fp = fdp->fd_files[fd].fp) == NULL)
706                 return (EBADF);
707         funsetfd(fdp, fd);
708         holdleaders = 0;
709         if (p->p_fdtol != NULL) {
710                 /*
711                  * Ask fdfree() to sleep to ensure that all relevant
712                  * process leaders can be traversed in closef().
713                  */
714                 fdp->fd_holdleaderscount++;
715                 holdleaders = 1;
716         }
717
718         /*
719          * we now hold the fp reference that used to be owned by the descriptor
720          * array.
721          */
722         while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
723                 fdp->fd_lastfile--;
724         if (fd < fdp->fd_knlistsize)
725                 knote_fdclose(p, fd);
726         error = closef(fp, td);
727         if (holdleaders) {
728                 fdp->fd_holdleaderscount--;
729                 if (fdp->fd_holdleaderscount == 0 &&
730                     fdp->fd_holdleaderswakeup != 0) {
731                         fdp->fd_holdleaderswakeup = 0;
732                         wakeup(&fdp->fd_holdleaderscount);
733                 }
734         }
735         return (error);
736 }
737
738 /*
739  * shutdown_args(int fd, int how)
740  */
741 int
742 kern_shutdown(int fd, int how)
743 {
744         struct thread *td = curthread;
745         struct proc *p = td->td_proc;
746         struct filedesc *fdp;
747         struct file *fp;
748         int error;
749
750         KKASSERT(p);
751
752         fdp = p->p_fd;
753         if ((unsigned)fd >= fdp->fd_nfiles ||
754             (fp = fdp->fd_files[fd].fp) == NULL)
755                 return (EBADF);
756         fhold(fp);
757         error = fo_shutdown(fp, how);
758         fdrop(fp);
759
760         return (error);
761 }
762
763 int
764 shutdown(struct shutdown_args *uap)
765 {
766         int error;
767
768         error = kern_shutdown(uap->s, uap->how);
769
770         return (error);
771 }
772
773 int
774 kern_fstat(int fd, struct stat *ub)
775 {
776         struct thread *td = curthread;
777         struct proc *p = td->td_proc;
778         struct filedesc *fdp;
779         struct file *fp;
780         int error;
781
782         KKASSERT(p);
783
784         fdp = p->p_fd;
785         if ((unsigned)fd >= fdp->fd_nfiles ||
786             (fp = fdp->fd_files[fd].fp) == NULL)
787                 return (EBADF);
788         fhold(fp);
789         error = fo_stat(fp, ub, p->p_ucred);
790         fdrop(fp);
791
792         return (error);
793 }
794
795 /*
796  * Return status information about a file descriptor.
797  */
798 int
799 fstat(struct fstat_args *uap)
800 {
801         struct stat st;
802         int error;
803
804         error = kern_fstat(uap->fd, &st);
805
806         if (error == 0)
807                 error = copyout(&st, uap->sb, sizeof(st));
808         return (error);
809 }
810
811 /*
812  * Return pathconf information about a file descriptor.
813  */
814 /* ARGSUSED */
815 int
816 fpathconf(struct fpathconf_args *uap)
817 {
818         struct thread *td = curthread;
819         struct proc *p = td->td_proc;
820         struct filedesc *fdp;
821         struct file *fp;
822         struct vnode *vp;
823         int error = 0;
824
825         KKASSERT(p);
826         fdp = p->p_fd;
827         if ((unsigned)uap->fd >= fdp->fd_nfiles ||
828             (fp = fdp->fd_files[uap->fd].fp) == NULL)
829                 return (EBADF);
830
831         fhold(fp);
832
833         switch (fp->f_type) {
834         case DTYPE_PIPE:
835         case DTYPE_SOCKET:
836                 if (uap->name != _PC_PIPE_BUF) {
837                         error = EINVAL;
838                 } else {
839                         uap->sysmsg_result = PIPE_BUF;
840                         error = 0;
841                 }
842                 break;
843         case DTYPE_FIFO:
844         case DTYPE_VNODE:
845                 vp = (struct vnode *)fp->f_data;
846                 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
847                 break;
848         default:
849                 error = EOPNOTSUPP;
850                 break;
851         }
852         fdrop(fp);
853         return(error);
854 }
855
856 static int fdexpand;
857 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
858
859 static void
860 fdgrow(struct filedesc *fdp, int want)
861 {
862         struct fdnode *newfiles;
863         struct fdnode *oldfiles;
864         int nf, extra;
865
866         nf = fdp->fd_nfiles;
867         do {
868                 /* nf has to be of the form 2^n - 1 */
869                 nf = 2 * nf + 1;
870         } while (nf <= want);
871
872         newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
873
874         /*
875          * deal with file-table extend race that might have occured
876          * when malloc was blocked.
877          */
878         if (fdp->fd_nfiles >= nf) {
879                 free(newfiles, M_FILEDESC);
880                 return;
881         }
882         /*
883          * Copy the existing ofile and ofileflags arrays
884          * and zero the new portion of each array.
885          */
886         extra = nf - fdp->fd_nfiles;
887         bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
888         bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
889
890         oldfiles = fdp->fd_files;
891         fdp->fd_files = newfiles;
892         fdp->fd_nfiles = nf;
893
894         if (oldfiles != fdp->fd_builtin_files)
895                 free(oldfiles, M_FILEDESC);
896         fdexpand++;
897 }
898
899 /*
900  * Number of nodes in right subtree, including the root.
901  */
902 static __inline int
903 right_subtree_size(int n)
904 {
905         return (n ^ (n | (n + 1)));
906 }
907
908 /*
909  * Bigger ancestor.
910  */
911 static __inline int
912 right_ancestor(int n)
913 {
914         return (n | (n + 1));
915 }
916
917 /*
918  * Smaller ancestor.
919  */
920 static __inline int
921 left_ancestor(int n)
922 {
923         return ((n & (n + 1)) - 1);
924 }
925
926 static
927 void
928 fdreserve(struct filedesc *fdp, int fd, int incr)
929 {
930         while (fd >= 0) {
931                 fdp->fd_files[fd].allocated += incr;
932                 KKASSERT(fdp->fd_files[fd].allocated >= 0);
933                 fd = left_ancestor(fd);
934         }
935 }
936
937 /*
938  * Allocate a file descriptor for the process.
939  */
940 int
941 fdalloc(struct proc *p, int want, int *result)
942 {
943         struct filedesc *fdp = p->p_fd;
944         int fd, rsize, rsum, node, lim;
945
946         lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
947         if (want >= lim)
948                 return (EMFILE);
949         if (want >= fdp->fd_nfiles)
950                 fdgrow(fdp, want);
951
952         /*
953          * Search for a free descriptor starting at the higher
954          * of want or fd_freefile.  If that fails, consider
955          * expanding the ofile array.
956          */
957 retry:
958         /* move up the tree looking for a subtree with a free node */
959         for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
960              fd = right_ancestor(fd)) {
961                 if (fdp->fd_files[fd].allocated == 0)
962                         goto found;
963
964                 rsize = right_subtree_size(fd);
965                 if (fdp->fd_files[fd].allocated == rsize)
966                         continue;       /* right subtree full */
967
968                 /*
969                  * Free fd is in the right subtree of the tree rooted at fd.
970                  * Call that subtree R.  Look for the smallest (leftmost)
971                  * subtree of R with an unallocated fd: continue moving
972                  * down the left branch until encountering a full left
973                  * subtree, then move to the right.
974                  */
975                 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
976                         node = fd + rsize;
977                         rsum += fdp->fd_files[node].allocated;
978                         if (fdp->fd_files[fd].allocated == rsum + rsize) {
979                                 fd = node;      /* move to the right */
980                                 if (fdp->fd_files[node].allocated == 0)
981                                         goto found;
982                                 rsum = 0;
983                         }
984                 }
985                 goto found;
986         }
987
988         /*
989          * No space in current array.  Expand?
990          */
991         if (fdp->fd_nfiles >= lim)
992                 return (EMFILE);
993         fdgrow(fdp, want);
994         goto retry;
995
996 found:
997         KKASSERT(fd < fdp->fd_nfiles);
998         fdp->fd_files[fd].fileflags = 0;
999         if (fd > fdp->fd_lastfile)
1000                 fdp->fd_lastfile = fd;
1001         if (want <= fdp->fd_freefile)
1002                 fdp->fd_freefile = fd;
1003         *result = fd;
1004         KKASSERT(fdp->fd_files[fd].fp == NULL);
1005         fdreserve(fdp, fd, 1);
1006         return (0);
1007 }
1008
1009 /*
1010  * Check to see whether n user file descriptors
1011  * are available to the process p.
1012  */
1013 int
1014 fdavail(struct proc *p, int n)
1015 {
1016         struct filedesc *fdp = p->p_fd;
1017         struct fdnode *fdnode;
1018         int i, lim, last;
1019
1020         lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1021         if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1022                 return (1);
1023
1024         last = min(fdp->fd_nfiles, lim);
1025         fdnode = &fdp->fd_files[fdp->fd_freefile];
1026         for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1027                 if (fdnode->fp == NULL && --n <= 0)
1028                         return (1);
1029         }
1030         return (0);
1031 }
1032
1033 /*
1034  * falloc:
1035  *      Create a new open file structure and allocate a file decriptor
1036  *      for the process that refers to it.  If p is NULL, no descriptor
1037  *      is allocated and the file pointer is returned unassociated with
1038  *      any process.  resultfd is only used if p is not NULL and may
1039  *      separately be NULL indicating that you don't need the returned fd.
1040  *
1041  *      A held file pointer is returned.  If a descriptor has been allocated
1042  *      an additional hold on the fp will be made due to the fd_files[]
1043  *      reference.
1044  */
1045 int
1046 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1047 {
1048         static struct timeval lastfail;
1049         static int curfail;
1050         struct file *fp;
1051         int error;
1052
1053         fp = NULL;
1054
1055         /*
1056          * Handle filetable full issues and root overfill.
1057          */
1058         if (nfiles >= maxfiles - maxfilesrootres &&
1059             ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1060                 if (ppsratecheck(&lastfail, &curfail, 1)) {
1061                         printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1062                                 (p ? p->p_ucred->cr_ruid : -1));
1063                 }
1064                 error = ENFILE;
1065                 goto done;
1066         }
1067
1068         /*
1069          * Allocate a new file descriptor.
1070          */
1071         nfiles++;
1072         fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1073         fp->f_count = 1;
1074         fp->f_ops = &badfileops;
1075         fp->f_seqcount = 1;
1076         if (p)
1077                 fp->f_cred = crhold(p->p_ucred);
1078         else
1079                 fp->f_cred = crhold(proc0.p_ucred);
1080         LIST_INSERT_HEAD(&filehead, fp, f_list);
1081         if (resultfd) {
1082                 if ((error = fsetfd(p, fp, resultfd)) != 0) {
1083                         fdrop(fp);
1084                         fp = NULL;
1085                 }
1086         } else {
1087                 error = 0;
1088         }
1089 done:
1090         *resultfp = fp;
1091         return (error);
1092 }
1093
1094 /*
1095  * fdealloc - deallocate a descriptor allocated with falloc.  The deallocation
1096  * only occurs if the passed file pointer matches the descriptor.
1097  */
1098 int
1099 fdealloc(struct proc *p, struct file *fp, int fd)
1100 {
1101         struct filedesc *fdp = p->p_fd;
1102
1103         if (((u_int)fd) >= fdp->fd_nfiles || fdp->fd_files[fd].fp != fp)
1104                 return(FALSE);
1105         fdp->fd_files[fd].fp = NULL;
1106         fdp->fd_files[fd].fileflags = 0;
1107         fdreserve(fdp, fd, -1);
1108         if (fd < fdp->fd_freefile)
1109                fdp->fd_freefile = fd;
1110         fdrop(fp);
1111         return (TRUE);
1112 }
1113
1114 /*
1115  * Associate a file pointer with a file descriptor.  On success the fp
1116  * will have an additional ref representing the fd_files[] association.
1117  */
1118 int
1119 fsetfd(struct proc *p, struct file *fp, int *resultfd)
1120 {
1121         int fd, error;
1122
1123         fd = -1;
1124         if ((error = fdalloc(p, 0, &fd)) == 0) {
1125                 fhold(fp);
1126                 p->p_fd->fd_files[fd].fp = fp;
1127         }
1128         *resultfd = fd;
1129         return (error);
1130 }
1131
1132 static 
1133 void
1134 funsetfd(struct filedesc *fdp, int fd)
1135 {
1136         fdp->fd_files[fd].fp = NULL;
1137         fdp->fd_files[fd].fileflags = 0;
1138         fdreserve(fdp, fd, -1);
1139         if (fd < fdp->fd_freefile)
1140                 fdp->fd_freefile = fd;
1141 }
1142
1143 int
1144 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
1145 {
1146         if (((u_int)fd) >= fdp->fd_nfiles)
1147                 return (EBADF);
1148         if (fdp->fd_files[fd].fp == NULL)
1149                 return (EBADF);
1150         fdp->fd_files[fd].fileflags |= add_flags;
1151         return (0);
1152 }
1153
1154 int
1155 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
1156 {
1157         if (((u_int)fd) >= fdp->fd_nfiles)
1158                 return (EBADF);
1159         if (fdp->fd_files[fd].fp == NULL)
1160                 return (EBADF);
1161         fdp->fd_files[fd].fileflags &= ~rem_flags;
1162         return (0);
1163 }
1164
1165 void
1166 fsetcred(struct file *fp, struct ucred *cr)
1167 {
1168         crhold(cr);
1169         crfree(fp->f_cred);
1170         fp->f_cred = cr;
1171 }
1172
1173 /*
1174  * Free a file descriptor.
1175  */
1176 void
1177 ffree(struct file *fp)
1178 {
1179         KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1180         LIST_REMOVE(fp, f_list);
1181         crfree(fp->f_cred);
1182         if (fp->f_ncp) {
1183             cache_drop(fp->f_ncp);
1184             fp->f_ncp = NULL;
1185         }
1186         nfiles--;
1187         free(fp, M_FILE);
1188 }
1189
1190 /*
1191  * called from init_main, initialize filedesc0 for proc0.
1192  */
1193 void
1194 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
1195 {
1196         p0->p_fd = fdp0;
1197         p0->p_fdtol = NULL;
1198         fdp0->fd_refcnt = 1;
1199         fdp0->fd_cmask = cmask;
1200         fdp0->fd_files = fdp0->fd_builtin_files;
1201         fdp0->fd_nfiles = NDFILE;
1202 }
1203
1204 /*
1205  * Build a new filedesc structure.
1206  */
1207 struct filedesc *
1208 fdinit(struct proc *p)
1209 {
1210         struct filedesc *newfdp;
1211         struct filedesc *fdp = p->p_fd;
1212
1213         newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1214         if (fdp->fd_cdir) {
1215                 newfdp->fd_cdir = fdp->fd_cdir;
1216                 vref(newfdp->fd_cdir);
1217                 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1218         }
1219
1220         /*
1221          * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1222          * proc0, but should unconditionally exist in other processes.
1223          */
1224         if (fdp->fd_rdir) {
1225                 newfdp->fd_rdir = fdp->fd_rdir;
1226                 vref(newfdp->fd_rdir);
1227                 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1228         }
1229         if (fdp->fd_jdir) {
1230                 newfdp->fd_jdir = fdp->fd_jdir;
1231                 vref(newfdp->fd_jdir);
1232                 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1233         }
1234
1235         /* Create the file descriptor table. */
1236         newfdp->fd_refcnt = 1;
1237         newfdp->fd_cmask = cmask;
1238         newfdp->fd_files = newfdp->fd_builtin_files;
1239         newfdp->fd_nfiles = NDFILE;
1240         newfdp->fd_knlistsize = -1;
1241
1242         return (newfdp);
1243 }
1244
1245 /*
1246  * Share a filedesc structure.
1247  */
1248 struct filedesc *
1249 fdshare(struct proc *p)
1250 {
1251         p->p_fd->fd_refcnt++;
1252         return (p->p_fd);
1253 }
1254
1255 /*
1256  * Copy a filedesc structure.
1257  */
1258 struct filedesc *
1259 fdcopy(struct proc *p)
1260 {
1261         struct filedesc *newfdp, *fdp = p->p_fd;
1262         struct fdnode *fdnode;
1263         int i;
1264
1265         /* Certain daemons might not have file descriptors. */
1266         if (fdp == NULL)
1267                 return (NULL);
1268
1269         newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK);
1270         *newfdp = *fdp;
1271         if (newfdp->fd_cdir) {
1272                 vref(newfdp->fd_cdir);
1273                 newfdp->fd_ncdir = cache_hold(newfdp->fd_ncdir);
1274         }
1275         /*
1276          * We must check for fd_rdir here, at least for now because
1277          * the init process is created before we have access to the
1278          * rootvode to take a reference to it.
1279          */
1280         if (newfdp->fd_rdir) {
1281                 vref(newfdp->fd_rdir);
1282                 newfdp->fd_nrdir = cache_hold(newfdp->fd_nrdir);
1283         }
1284         if (newfdp->fd_jdir) {
1285                 vref(newfdp->fd_jdir);
1286                 newfdp->fd_njdir = cache_hold(newfdp->fd_njdir);
1287         }
1288         newfdp->fd_refcnt = 1;
1289
1290         /*
1291          * If the number of open files fits in the internal arrays
1292          * of the open file structure, use them, otherwise allocate
1293          * additional memory for the number of descriptors currently
1294          * in use.
1295          */
1296         if (newfdp->fd_lastfile < NDFILE) {
1297                 newfdp->fd_files = newfdp->fd_builtin_files;
1298                 i = NDFILE;
1299         } else {
1300                 /*
1301                  * Compute the smallest file table size
1302                  * for the file descriptors currently in use,
1303                  * allowing the table to shrink.
1304                  */
1305                 i = newfdp->fd_nfiles;
1306                 while ((i-1)/2 > newfdp->fd_lastfile && (i-1)/2 > NDFILE)
1307                         i = (i-1)/2;
1308                 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1309                                           M_FILEDESC, M_WAITOK);
1310         }
1311         newfdp->fd_nfiles = i;
1312
1313         if (fdp->fd_files != fdp->fd_builtin_files ||
1314             newfdp->fd_files != newfdp->fd_builtin_files
1315         ) {
1316                 bcopy(fdp->fd_files, newfdp->fd_files, 
1317                       i * sizeof(struct fdnode));
1318         }
1319
1320         /*
1321          * kq descriptors cannot be copied.
1322          */
1323         if (newfdp->fd_knlistsize != -1) {
1324                 fdnode = &newfdp->fd_files[newfdp->fd_lastfile];
1325                 for (i = newfdp->fd_lastfile; i >= 0; i--, fdnode--) {
1326                         if (fdnode->fp != NULL && fdnode->fp->f_type == DTYPE_KQUEUE)
1327                                 funsetfd(newfdp, i);    /* nulls out *fpp */
1328                         if (fdnode->fp == NULL && i == newfdp->fd_lastfile && i > 0)
1329                                 newfdp->fd_lastfile--;
1330                 }
1331                 newfdp->fd_knlist = NULL;
1332                 newfdp->fd_knlistsize = -1;
1333                 newfdp->fd_knhash = NULL;
1334                 newfdp->fd_knhashmask = 0;
1335         }
1336
1337         fdnode = newfdp->fd_files;
1338         for (i = newfdp->fd_lastfile; i-- >= 0; fdnode++) {
1339                 if (fdnode->fp != NULL)
1340                         fhold(fdnode->fp);
1341         }
1342         return (newfdp);
1343 }
1344
1345 /*
1346  * Release a filedesc structure.
1347  */
1348 void
1349 fdfree(struct proc *p)
1350 {
1351         struct thread *td = p->p_thread;
1352         struct filedesc *fdp = p->p_fd;
1353         struct fdnode *fdnode;
1354         int i;
1355         struct filedesc_to_leader *fdtol;
1356         struct file *fp;
1357         struct vnode *vp;
1358         struct flock lf;
1359
1360         /* Certain daemons might not have file descriptors. */
1361         if (fdp == NULL)
1362                 return;
1363
1364         /* Check for special need to clear POSIX style locks */
1365         fdtol = p->p_fdtol;
1366         if (fdtol != NULL) {
1367                 KASSERT(fdtol->fdl_refcount > 0,
1368                         ("filedesc_to_refcount botch: fdl_refcount=%d",
1369                          fdtol->fdl_refcount));
1370                 if (fdtol->fdl_refcount == 1 &&
1371                     (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1372                         i = 0;
1373                         fdnode = fdp->fd_files;
1374                         for (i = 0; i <= fdp->fd_lastfile; i++, fdnode++) {
1375                                 if (fdnode->fp == NULL ||
1376                                     fdnode->fp->f_type != DTYPE_VNODE)
1377                                         continue;
1378                                 fp = fdnode->fp;
1379                                 fhold(fp);
1380                                 lf.l_whence = SEEK_SET;
1381                                 lf.l_start = 0;
1382                                 lf.l_len = 0;
1383                                 lf.l_type = F_UNLCK;
1384                                 vp = (struct vnode *)fp->f_data;
1385                                 (void) VOP_ADVLOCK(vp,
1386                                                    (caddr_t)p->p_leader,
1387                                                    F_UNLCK,
1388                                                    &lf,
1389                                                    F_POSIX);
1390                                 fdrop(fp);
1391                                 /* reload due to possible reallocation */
1392                                 fdnode = &fdp->fd_files[i];
1393                         }
1394                 }
1395         retry:
1396                 if (fdtol->fdl_refcount == 1) {
1397                         if (fdp->fd_holdleaderscount > 0 &&
1398                             (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1399                                 /*
1400                                  * close() or do_dup() has cleared a reference
1401                                  * in a shared file descriptor table.
1402                                  */
1403                                 fdp->fd_holdleaderswakeup = 1;
1404                                 tsleep(&fdp->fd_holdleaderscount,
1405                                        0, "fdlhold", 0);
1406                                 goto retry;
1407                         }
1408                         if (fdtol->fdl_holdcount > 0) {
1409                                 /* 
1410                                  * Ensure that fdtol->fdl_leader
1411                                  * remains valid in closef().
1412                                  */
1413                                 fdtol->fdl_wakeup = 1;
1414                                 tsleep(fdtol, 0, "fdlhold", 0);
1415                                 goto retry;
1416                         }
1417                 }
1418                 fdtol->fdl_refcount--;
1419                 if (fdtol->fdl_refcount == 0 &&
1420                     fdtol->fdl_holdcount == 0) {
1421                         fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1422                         fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1423                 } else
1424                         fdtol = NULL;
1425                 p->p_fdtol = NULL;
1426                 if (fdtol != NULL)
1427                         free(fdtol, M_FILEDESC_TO_LEADER);
1428         }
1429         if (--fdp->fd_refcnt > 0)
1430                 return;
1431         /*
1432          * we are the last reference to the structure, we can
1433          * safely assume it will not change out from under us.
1434          */
1435         for (i = 0; i <= fdp->fd_lastfile; ++i) {
1436                 if (fdp->fd_files[i].fp)
1437                         closef(fdp->fd_files[i].fp, td);
1438         }
1439         if (fdp->fd_files != fdp->fd_builtin_files)
1440                 free(fdp->fd_files, M_FILEDESC);
1441         if (fdp->fd_cdir) {
1442                 cache_drop(fdp->fd_ncdir);
1443                 vrele(fdp->fd_cdir);
1444         }
1445         if (fdp->fd_rdir) {
1446                 cache_drop(fdp->fd_nrdir);
1447                 vrele(fdp->fd_rdir);
1448         }
1449         if (fdp->fd_jdir) {
1450                 cache_drop(fdp->fd_njdir);
1451                 vrele(fdp->fd_jdir);
1452         }
1453         if (fdp->fd_knlist)
1454                 free(fdp->fd_knlist, M_KQUEUE);
1455         if (fdp->fd_knhash)
1456                 free(fdp->fd_knhash, M_KQUEUE);
1457         free(fdp, M_FILEDESC);
1458 }
1459
1460 /*
1461  * Retrieve and reference the file pointer associated with a descriptor.
1462  */
1463 struct file *
1464 holdfp(struct filedesc *fdp, int fd, int flag)
1465 {
1466         struct file* fp;
1467
1468         if (((u_int)fd) >= fdp->fd_nfiles)
1469                 return (NULL);
1470         if ((fp = fdp->fd_files[fd].fp) == NULL)
1471                 return (NULL);
1472         if ((fp->f_flag & flag) == 0 && flag != -1)
1473                 return (NULL);
1474         fhold(fp);
1475         return (fp);
1476 }
1477
1478 /*
1479  * holdsock() - load the struct file pointer associated
1480  * with a socket into *fpp.  If an error occurs, non-zero
1481  * will be returned and *fpp will be set to NULL.
1482  */
1483 int
1484 holdsock(struct filedesc *fdp, int fdes, struct file **fpp)
1485 {
1486         struct file *fp;
1487         int error = 0;
1488
1489         *fpp = NULL;
1490         if ((unsigned)fdes >= fdp->fd_nfiles)
1491                 return EBADF;
1492         if ((fp = fdp->fd_files[fdes].fp) == NULL)
1493                 return EBADF;
1494         if (fp->f_type != DTYPE_SOCKET)
1495                 return ENOTSOCK;
1496         fhold(fp);
1497         *fpp = fp;
1498         return (error);
1499 }
1500
1501 /*
1502  * Convert a user file descriptor to a kernel file entry.
1503  */
1504 int
1505 getvnode(struct filedesc *fdp, int fd, struct file **fpp)
1506 {
1507         struct file *fp;
1508                   
1509         if ((u_int)fd >= fdp->fd_nfiles ||
1510             (fp = fdp->fd_files[fd].fp) == NULL)
1511                 return (EBADF);
1512         if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO)
1513                 return (EINVAL);
1514         *fpp = fp;
1515         return (0);
1516 }
1517
1518 /*
1519  * For setugid programs, we don't want to people to use that setugidness
1520  * to generate error messages which write to a file which otherwise would
1521  * otherwise be off-limits to the process.
1522  *
1523  * This is a gross hack to plug the hole.  A better solution would involve
1524  * a special vop or other form of generalized access control mechanism.  We
1525  * go ahead and just reject all procfs file systems accesses as dangerous.
1526  *
1527  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1528  * sufficient.  We also don't for check setugidness since we know we are.
1529  */
1530 static int
1531 is_unsafe(struct file *fp)
1532 {
1533         if (fp->f_type == DTYPE_VNODE && 
1534             ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1535                 return (1);
1536         return (0);
1537 }
1538
1539 /*
1540  * Make this setguid thing safe, if at all possible.
1541  */
1542 void
1543 setugidsafety(struct proc *p)
1544 {
1545         struct thread *td = p->p_thread;
1546         struct filedesc *fdp = p->p_fd;
1547         int i;
1548
1549         /* Certain daemons might not have file descriptors. */
1550         if (fdp == NULL)
1551                 return;
1552
1553         /*
1554          * note: fdp->fd_files may be reallocated out from under us while
1555          * we are blocked in a close.  Be careful!
1556          */
1557         for (i = 0; i <= fdp->fd_lastfile; i++) {
1558                 if (i > 2)
1559                         break;
1560                 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1561                         struct file *fp;
1562
1563                         if (i < fdp->fd_knlistsize)
1564                                 knote_fdclose(p, i);
1565                         /*
1566                          * NULL-out descriptor prior to close to avoid
1567                          * a race while close blocks.
1568                          */
1569                         fp = fdp->fd_files[i].fp;
1570                         funsetfd(fdp, i);
1571                         closef(fp, td);
1572                 }
1573         }
1574         while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
1575                 fdp->fd_lastfile--;
1576 }
1577
1578 /*
1579  * Close any files on exec?
1580  */
1581 void
1582 fdcloseexec(struct proc *p)
1583 {
1584         struct thread *td = p->p_thread;
1585         struct filedesc *fdp = p->p_fd;
1586         int i;
1587
1588         /* Certain daemons might not have file descriptors. */
1589         if (fdp == NULL)
1590                 return;
1591
1592         /*
1593          * We cannot cache fd_files since operations may block and rip
1594          * them out from under us.
1595          */
1596         for (i = 0; i <= fdp->fd_lastfile; i++) {
1597                 if (fdp->fd_files[i].fp != NULL &&
1598                     (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1599                         struct file *fp;
1600
1601                         if (i < fdp->fd_knlistsize)
1602                                 knote_fdclose(p, i);
1603                         /*
1604                          * NULL-out descriptor prior to close to avoid
1605                          * a race while close blocks.
1606                          */
1607                         fp = fdp->fd_files[i].fp;
1608                         funsetfd(fdp, i);
1609                         closef(fp, td);
1610                 }
1611         }
1612         while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
1613                 fdp->fd_lastfile--;
1614 }
1615
1616 /*
1617  * It is unsafe for set[ug]id processes to be started with file
1618  * descriptors 0..2 closed, as these descriptors are given implicit
1619  * significance in the Standard C library.  fdcheckstd() will create a
1620  * descriptor referencing /dev/null for each of stdin, stdout, and
1621  * stderr that is not already open.
1622  */
1623 int
1624 fdcheckstd(struct proc *p)
1625 {
1626         struct nlookupdata nd;
1627         struct filedesc *fdp;
1628         struct file *fp;
1629         register_t retval;
1630         int fd, i, error, flags, devnull;
1631
1632        fdp = p->p_fd;
1633        if (fdp == NULL)
1634                return (0);
1635        devnull = -1;
1636        error = 0;
1637        for (i = 0; i < 3; i++) {
1638                 if (fdp->fd_files[i].fp != NULL)
1639                         continue;
1640                 if (devnull < 0) {
1641                         if ((error = falloc(p, &fp, NULL)) != 0)
1642                                 break;
1643
1644                         error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1645                                                 NLC_FOLLOW|NLC_LOCKVP);
1646                         flags = FREAD | FWRITE;
1647                         if (error == 0)
1648                                 error = vn_open(&nd, fp, flags, 0);
1649                         if (error == 0)
1650                                 error = fsetfd(p, fp, &fd);
1651                         fdrop(fp);
1652                         nlookup_done(&nd);
1653                         if (error)
1654                                 break;
1655                         KKASSERT(i == fd);
1656                         devnull = fd;
1657                 } else {
1658                         error = kern_dup(DUP_FIXED, devnull, i, &retval);
1659                         if (error != 0)
1660                                 break;
1661                 }
1662        }
1663        return (error);
1664 }
1665
1666 /*
1667  * Internal form of close.
1668  * Decrement reference count on file structure.
1669  * Note: td and/or p may be NULL when closing a file
1670  * that was being passed in a message.
1671  */
1672 int
1673 closef(struct file *fp, struct thread *td)
1674 {
1675         struct vnode *vp;
1676         struct flock lf;
1677         struct filedesc_to_leader *fdtol;
1678         struct proc *p;
1679
1680         if (fp == NULL)
1681                 return (0);
1682         if (td == NULL) {
1683                 td = curthread;
1684                 p = NULL;               /* allow no proc association */
1685         } else {
1686                 p = td->td_proc;        /* can also be NULL */
1687         }
1688         /*
1689          * POSIX record locking dictates that any close releases ALL
1690          * locks owned by this process.  This is handled by setting
1691          * a flag in the unlock to free ONLY locks obeying POSIX
1692          * semantics, and not to free BSD-style file locks.
1693          * If the descriptor was in a message, POSIX-style locks
1694          * aren't passed with the descriptor.
1695          */
1696         if (p != NULL && 
1697             fp->f_type == DTYPE_VNODE) {
1698                 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1699                         lf.l_whence = SEEK_SET;
1700                         lf.l_start = 0;
1701                         lf.l_len = 0;
1702                         lf.l_type = F_UNLCK;
1703                         vp = (struct vnode *)fp->f_data;
1704                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1705                                            &lf, F_POSIX);
1706                 }
1707                 fdtol = p->p_fdtol;
1708                 if (fdtol != NULL) {
1709                         /*
1710                          * Handle special case where file descriptor table
1711                          * is shared between multiple process leaders.
1712                          */
1713                         for (fdtol = fdtol->fdl_next;
1714                              fdtol != p->p_fdtol;
1715                              fdtol = fdtol->fdl_next) {
1716                                 if ((fdtol->fdl_leader->p_flag &
1717                                      P_ADVLOCK) == 0)
1718                                         continue;
1719                                 fdtol->fdl_holdcount++;
1720                                 lf.l_whence = SEEK_SET;
1721                                 lf.l_start = 0;
1722                                 lf.l_len = 0;
1723                                 lf.l_type = F_UNLCK;
1724                                 vp = (struct vnode *)fp->f_data;
1725                                 (void) VOP_ADVLOCK(vp,
1726                                                    (caddr_t)fdtol->fdl_leader,
1727                                                    F_UNLCK, &lf, F_POSIX);
1728                                 fdtol->fdl_holdcount--;
1729                                 if (fdtol->fdl_holdcount == 0 &&
1730                                     fdtol->fdl_wakeup != 0) {
1731                                         fdtol->fdl_wakeup = 0;
1732                                         wakeup(fdtol);
1733                                 }
1734                         }
1735                 }
1736         }
1737         return (fdrop(fp));
1738 }
1739
1740 int
1741 fdrop(struct file *fp)
1742 {
1743         struct flock lf;
1744         struct vnode *vp;
1745         int error;
1746
1747         if (--fp->f_count > 0)
1748                 return (0);
1749         if (fp->f_count < 0)
1750                 panic("fdrop: count < 0");
1751         if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1752                 lf.l_whence = SEEK_SET;
1753                 lf.l_start = 0;
1754                 lf.l_len = 0;
1755                 lf.l_type = F_UNLCK;
1756                 vp = (struct vnode *)fp->f_data;
1757                 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
1758         }
1759         if (fp->f_ops != &badfileops)
1760                 error = fo_close(fp);
1761         else
1762                 error = 0;
1763         ffree(fp);
1764         return (error);
1765 }
1766
1767 /*
1768  * Apply an advisory lock on a file descriptor.
1769  *
1770  * Just attempt to get a record lock of the requested type on
1771  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1772  */
1773 /* ARGSUSED */
1774 int
1775 flock(struct flock_args *uap)
1776 {
1777         struct proc *p = curproc;
1778         struct filedesc *fdp = p->p_fd;
1779         struct file *fp;
1780         struct vnode *vp;
1781         struct flock lf;
1782
1783         if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1784             (fp = fdp->fd_files[uap->fd].fp) == NULL)
1785                 return (EBADF);
1786         if (fp->f_type != DTYPE_VNODE)
1787                 return (EOPNOTSUPP);
1788         vp = (struct vnode *)fp->f_data;
1789         lf.l_whence = SEEK_SET;
1790         lf.l_start = 0;
1791         lf.l_len = 0;
1792         if (uap->how & LOCK_UN) {
1793                 lf.l_type = F_UNLCK;
1794                 fp->f_flag &= ~FHASLOCK;
1795                 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0));
1796         }
1797         if (uap->how & LOCK_EX)
1798                 lf.l_type = F_WRLCK;
1799         else if (uap->how & LOCK_SH)
1800                 lf.l_type = F_RDLCK;
1801         else
1802                 return (EBADF);
1803         fp->f_flag |= FHASLOCK;
1804         if (uap->how & LOCK_NB)
1805                 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 0));
1806         return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_WAIT));
1807 }
1808
1809 /*
1810  * File Descriptor pseudo-device driver (/dev/fd/).
1811  *
1812  * Opening minor device N dup()s the file (if any) connected to file
1813  * descriptor N belonging to the calling process.  Note that this driver
1814  * consists of only the ``open()'' routine, because all subsequent
1815  * references to this file will be direct to the other driver.
1816  */
1817 /* ARGSUSED */
1818 static int
1819 fdopen(dev_t dev, int mode, int type, struct thread *td)
1820 {
1821         KKASSERT(td->td_lwp != NULL);
1822
1823         /*
1824          * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
1825          * the file descriptor being sought for duplication. The error
1826          * return ensures that the vnode for this device will be released
1827          * by vn_open. Open will detect this special error and take the
1828          * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1829          * will simply report the error.
1830          */
1831         td->td_lwp->lwp_dupfd = minor(dev);
1832         return (ENODEV);
1833 }
1834
1835 /*
1836  * Duplicate the specified descriptor to a free descriptor.
1837  */
1838 int
1839 dupfdopen(struct filedesc *fdp, int indx, int dfd, int mode, int error)
1840 {
1841         struct file *wfp;
1842         struct file *fp;
1843
1844         /*
1845          * If the to-be-dup'd fd number is greater than the allowed number
1846          * of file descriptors, or the fd to be dup'd has already been
1847          * closed, then reject.
1848          */
1849         if ((u_int)dfd >= fdp->fd_nfiles ||
1850             (wfp = fdp->fd_files[dfd].fp) == NULL) {
1851                 return (EBADF);
1852         }
1853
1854         /*
1855          * There are two cases of interest here.
1856          *
1857          * For ENODEV simply dup (dfd) to file descriptor
1858          * (indx) and return.
1859          *
1860          * For ENXIO steal away the file structure from (dfd) and
1861          * store it in (indx).  (dfd) is effectively closed by
1862          * this operation.
1863          *
1864          * Any other error code is just returned.
1865          */
1866         switch (error) {
1867         case ENODEV:
1868                 /*
1869                  * Check that the mode the file is being opened for is a
1870                  * subset of the mode of the existing descriptor.
1871                  */
1872                 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1873                         return (EACCES);
1874                 fp = fdp->fd_files[indx].fp;
1875                 fdp->fd_files[indx].fp = wfp;
1876                 fdp->fd_files[indx].fileflags = fdp->fd_files[dfd].fileflags;
1877                 fhold(wfp);
1878                 if (indx > fdp->fd_lastfile)
1879                         fdp->fd_lastfile = indx;
1880                 /*
1881                  * we now own the reference to fp that the ofiles[] array
1882                  * used to own.  Release it.
1883                  */
1884                 if (fp)
1885                         fdrop(fp);
1886                 return (0);
1887
1888         case ENXIO:
1889                 /*
1890                  * Steal away the file pointer from dfd, and stuff it into indx.
1891                  */
1892                 fp = fdp->fd_files[indx].fp;
1893                 fdp->fd_files[indx].fp = fdp->fd_files[dfd].fp;
1894                 fdp->fd_files[indx].fileflags = fdp->fd_files[dfd].fileflags;
1895                 funsetfd(fdp, dfd);
1896
1897                 /*
1898                  * we now own the reference to fp that the files[] array
1899                  * used to own.  Release it.
1900                  */
1901                 if (fp)
1902                         fdrop(fp);
1903                 /*
1904                  * Complete the clean up of the filedesc structure by
1905                  * recomputing the various hints.
1906                  */
1907                 if (indx > fdp->fd_lastfile) {
1908                         fdp->fd_lastfile = indx;
1909                 } else {
1910                         while (fdp->fd_lastfile > 0 &&
1911                            fdp->fd_files[fdp->fd_lastfile].fp == NULL) {
1912                                 fdp->fd_lastfile--;
1913                         }
1914                 }
1915                 return (0);
1916
1917         default:
1918                 return (error);
1919         }
1920         /* NOTREACHED */
1921 }
1922
1923
1924 struct filedesc_to_leader *
1925 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
1926                          struct proc *leader)
1927 {
1928         struct filedesc_to_leader *fdtol;
1929         
1930         fdtol = malloc(sizeof(struct filedesc_to_leader), 
1931                         M_FILEDESC_TO_LEADER, M_WAITOK);
1932         fdtol->fdl_refcount = 1;
1933         fdtol->fdl_holdcount = 0;
1934         fdtol->fdl_wakeup = 0;
1935         fdtol->fdl_leader = leader;
1936         if (old != NULL) {
1937                 fdtol->fdl_next = old->fdl_next;
1938                 fdtol->fdl_prev = old;
1939                 old->fdl_next = fdtol;
1940                 fdtol->fdl_next->fdl_prev = fdtol;
1941         } else {
1942                 fdtol->fdl_next = fdtol;
1943                 fdtol->fdl_prev = fdtol;
1944         }
1945         return fdtol;
1946 }
1947
1948 /*
1949  * Get file structures.
1950  */
1951 static int
1952 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
1953 {
1954         struct kinfo_file kf;
1955         struct filedesc *fdp;
1956         struct file *fp;
1957         struct proc *p;
1958         uid_t uid;
1959         int count;
1960         int error;
1961         int n;
1962
1963         /*
1964          * Note: because the number of file descriptors is calculated
1965          * in different ways for sizing vs returning the data,
1966          * there is information leakage from the first loop.  However,
1967          * it is of a similar order of magnitude to the leakage from
1968          * global system statistics such as kern.openfiles.
1969          *
1970          * When just doing a count, note that we cannot just count
1971          * the elements and add f_count via the filehead list because 
1972          * threaded processes share their descriptor table and f_count might
1973          * still be '1' in that case.
1974          *
1975          * Since the SYSCTL op can block, we must hold the process to
1976          * prevent it being ripped out from under us either in the 
1977          * file descriptor loop or in the greater LIST_FOREACH.  The
1978          * process may be in varying states of disrepair.  If the process
1979          * is in SZOMB we may have caught it just as it is being removed
1980          * from the allproc list, we must skip it in that case to maintain
1981          * an unbroken chain through the allproc list.
1982          */
1983         count = 0;
1984         error = 0;
1985         LIST_FOREACH(p, &allproc, p_list) {
1986                 if (p->p_stat == SIDL || (p->p_flag & P_ZOMBIE))
1987                         continue;
1988                 if (!PRISON_CHECK(req->td->td_proc->p_ucred, p->p_ucred) != 0)
1989                         continue;
1990                 if ((fdp = p->p_fd) == NULL)
1991                         continue;
1992                 PHOLD(p);
1993                 for (n = 0; n < fdp->fd_nfiles; ++n) {
1994                         if ((fp = fdp->fd_files[n].fp) == NULL)
1995                                 continue;
1996                         if (req->oldptr == NULL) {
1997                                 ++count;
1998                         } else {
1999                                 uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
2000                                 kcore_make_file(&kf, fp, p->p_pid, uid, n);
2001                                 error = SYSCTL_OUT(req, &kf, sizeof(kf));
2002                                 if (error)
2003                                         break;
2004                         }
2005                 }
2006                 PRELE(p);
2007                 if (error)
2008                         break;
2009         }
2010
2011         /*
2012          * When just calculating the size, overestimate a bit to try to
2013          * prevent system activity from causing the buffer-fill call 
2014          * to fail later on.
2015          */
2016         if (req->oldptr == NULL) {
2017                 count = (count + 16) + (count / 10);
2018                 error = SYSCTL_OUT(req, NULL, count * sizeof(kf));
2019         }
2020         return (error);
2021 }
2022
2023 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2024     0, 0, sysctl_kern_file, "S,file", "Entire file table");
2025
2026 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW, 
2027     &maxfilesperproc, 0, "Maximum files allowed open per process");
2028
2029 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW, 
2030     &maxfiles, 0, "Maximum number of files");
2031
2032 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW, 
2033     &maxfilesrootres, 0, "Descriptors reserved for root use");
2034
2035 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD, 
2036         &nfiles, 0, "System-wide number of open files");
2037
2038 static void
2039 fildesc_drvinit(void *unused)
2040 {
2041         int fd;
2042
2043         cdevsw_add(&fildesc_cdevsw, 0, 0);
2044         for (fd = 0; fd < NUMFDESC; fd++) {
2045                 make_dev(&fildesc_cdevsw, fd,
2046                     UID_BIN, GID_BIN, 0666, "fd/%d", fd);
2047         }
2048         make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
2049         make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
2050         make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
2051 }
2052
2053 struct fileops badfileops = {
2054         NULL,   /* port */
2055         NULL,   /* clone */
2056         badfo_readwrite,
2057         badfo_readwrite,
2058         badfo_ioctl,
2059         badfo_poll,
2060         badfo_kqfilter,
2061         badfo_stat,
2062         badfo_close,
2063         badfo_shutdown
2064 };
2065
2066 static int
2067 badfo_readwrite(
2068         struct file *fp,
2069         struct uio *uio,
2070         struct ucred *cred,
2071         int flags
2072 ) {
2073         return (EBADF);
2074 }
2075
2076 static int
2077 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct ucred *cred)
2078 {
2079         return (EBADF);
2080 }
2081
2082 static int
2083 badfo_poll(struct file *fp, int events, struct ucred *cred)
2084 {
2085         return (0);
2086 }
2087
2088 static int
2089 badfo_kqfilter(struct file *fp, struct knote *kn)
2090 {
2091         return (0);
2092 }
2093
2094 static int
2095 badfo_stat(struct file *fp, struct stat *sb, struct ucred *cred)
2096 {
2097         return (EBADF);
2098 }
2099
2100 static int
2101 badfo_close(struct file *fp)
2102 {
2103         return (EBADF);
2104 }
2105
2106 static int
2107 badfo_shutdown(struct file *fp, int how)
2108 {
2109         return (EBADF);
2110 }
2111
2112 int
2113 nofo_shutdown(struct file *fp, int how)
2114 {
2115         return (EOPNOTSUPP);
2116 }
2117
2118 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2119                                         fildesc_drvinit,NULL)