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