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