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