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