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