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