Merge from vendor branch OPENSSH:
[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.45 2005/06/22 19:58:44 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, struct thread *td);
136 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
137     struct thread *td);
138 static int badfo_poll (struct file *fp, int events,
139     struct ucred *cred, struct thread *td);
140 static int badfo_kqfilter (struct file *fp, struct knote *kn);
141 static int badfo_stat (struct file *fp, struct stat *sb, struct thread *td);
142 static int badfo_close (struct file *fp, struct thread *td);
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)
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, td);
243                 if (error) {
244                         fdrop(fp, td);
245                         return (error);
246                 }
247                 tmp = fp->f_flag & FASYNC;
248                 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, td);
249                 if (!error) {
250                         fdrop(fp, td);
251                         return (0);
252                 }
253                 fp->f_flag &= ~FNONBLOCK;
254                 tmp = 0;
255                 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
256                 fdrop(fp, td);
257                 return (error);
258
259         case F_GETOWN:
260                 fhold(fp);
261                 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, td);
262                 fdrop(fp, td);
263                 return(error);
264
265         case F_SETOWN:
266                 fhold(fp);
267                 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, td);
268                 fdrop(fp, td);
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, td);
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, td);
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, td);
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);
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, td);
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, td);
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 #if 0
499         if (delfp && (fdp->fd_files[new].fileflags & UF_MAPPED))
500                 (void) munmapfd(p, new);
501 #endif
502
503         /*
504          * Duplicate the source descriptor, update lastfile
505          */
506         if (new > fdp->fd_lastfile)
507                 fdp->fd_lastfile = new;
508         if (!fdalloced && fdp->fd_files[new].fp == NULL)
509                 fdreserve(fdp, new, 1);
510         fdp->fd_files[new].fp = fp;
511         fdp->fd_files[new].fileflags = 
512                         fdp->fd_files[old].fileflags & ~UF_EXCLOSE;
513         *res = new;
514
515         /*
516          * If we dup'd over a valid file, we now own the reference to it
517          * and must dispose of it using closef() semantics (as if a
518          * close() were performed on it).
519          */
520         if (delfp) {
521                 (void) closef(delfp, td);
522                 if (holdleaders) {
523                         fdp->fd_holdleaderscount--;
524                         if (fdp->fd_holdleaderscount == 0 &&
525                             fdp->fd_holdleaderswakeup != 0) {
526                                 fdp->fd_holdleaderswakeup = 0;
527                                 wakeup(&fdp->fd_holdleaderscount);
528                         }
529                 }
530         }
531         return (0);
532 }
533
534 /*
535  * If sigio is on the list associated with a process or process group,
536  * disable signalling from the device, remove sigio from the list and
537  * free sigio.
538  */
539 void
540 funsetown(struct sigio *sigio)
541 {
542         if (sigio == NULL)
543                 return;
544         crit_enter();
545         *(sigio->sio_myref) = NULL;
546         crit_exit();
547         if (sigio->sio_pgid < 0) {
548                 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
549                              sigio, sio_pgsigio);
550         } else /* if ((*sigiop)->sio_pgid > 0) */ {
551                 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
552                              sigio, sio_pgsigio);
553         }
554         crfree(sigio->sio_ucred);
555         free(sigio, M_SIGIO);
556 }
557
558 /* Free a list of sigio structures. */
559 void
560 funsetownlst(struct sigiolst *sigiolst)
561 {
562         struct sigio *sigio;
563
564         while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
565                 funsetown(sigio);
566 }
567
568 /*
569  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
570  *
571  * After permission checking, add a sigio structure to the sigio list for
572  * the process or process group.
573  */
574 int
575 fsetown(pid_t pgid, struct sigio **sigiop)
576 {
577         struct proc *proc;
578         struct pgrp *pgrp;
579         struct sigio *sigio;
580
581         if (pgid == 0) {
582                 funsetown(*sigiop);
583                 return (0);
584         }
585         if (pgid > 0) {
586                 proc = pfind(pgid);
587                 if (proc == NULL)
588                         return (ESRCH);
589
590                 /*
591                  * Policy - Don't allow a process to FSETOWN a process
592                  * in another session.
593                  *
594                  * Remove this test to allow maximum flexibility or
595                  * restrict FSETOWN to the current process or process
596                  * group for maximum safety.
597                  */
598                 if (proc->p_session != curproc->p_session)
599                         return (EPERM);
600
601                 pgrp = NULL;
602         } else /* if (pgid < 0) */ {
603                 pgrp = pgfind(-pgid);
604                 if (pgrp == NULL)
605                         return (ESRCH);
606
607                 /*
608                  * Policy - Don't allow a process to FSETOWN a process
609                  * in another session.
610                  *
611                  * Remove this test to allow maximum flexibility or
612                  * restrict FSETOWN to the current process or process
613                  * group for maximum safety.
614                  */
615                 if (pgrp->pg_session != curproc->p_session)
616                         return (EPERM);
617
618                 proc = NULL;
619         }
620         funsetown(*sigiop);
621         sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
622         if (pgid > 0) {
623                 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
624                 sigio->sio_proc = proc;
625         } else {
626                 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
627                 sigio->sio_pgrp = pgrp;
628         }
629         sigio->sio_pgid = pgid;
630         sigio->sio_ucred = crhold(curproc->p_ucred);
631         /* It would be convenient if p_ruid was in ucred. */
632         sigio->sio_ruid = curproc->p_ucred->cr_ruid;
633         sigio->sio_myref = sigiop;
634         crit_enter();
635         *sigiop = sigio;
636         crit_exit();
637         return (0);
638 }
639
640 /*
641  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
642  */
643 pid_t
644 fgetown(struct sigio *sigio)
645 {
646         return (sigio != NULL ? sigio->sio_pgid : 0);
647 }
648
649 /*
650  * Close many file descriptors.
651  */
652 /* ARGSUSED */
653
654 int
655 closefrom(struct closefrom_args *uap)
656 {
657         return(kern_closefrom(uap->fd));
658 }
659
660 int
661 kern_closefrom(int fd)
662 {
663         struct thread *td = curthread;
664         struct proc *p = td->td_proc;
665         struct filedesc *fdp;
666
667         KKASSERT(p);
668         fdp = p->p_fd;
669
670         if (fd < 0 || fd > fdp->fd_lastfile)
671                 return (0);
672
673         do {
674                 if (kern_close(fdp->fd_lastfile) == EINTR)
675                         return (EINTR);
676         } while (fdp->fd_lastfile > fd);
677
678         return (0);
679 }
680
681 /*
682  * Close a file descriptor.
683  */
684 /* ARGSUSED */
685
686 int
687 close(struct close_args *uap)
688 {
689         return(kern_close(uap->fd));
690 }
691
692 int
693 kern_close(int fd)
694 {
695         struct thread *td = curthread;
696         struct proc *p = td->td_proc;
697         struct filedesc *fdp;
698         struct file *fp;
699         int error;
700         int holdleaders;
701
702         KKASSERT(p);
703         fdp = p->p_fd;
704
705         if ((unsigned)fd >= fdp->fd_nfiles ||
706             (fp = fdp->fd_files[fd].fp) == NULL)
707                 return (EBADF);
708 #if 0
709         if (fdp->fd_files[fd].fileflags & UF_MAPPED)
710                 (void) munmapfd(p, fd);
711 #endif
712         funsetfd(fdp, fd);
713         holdleaders = 0;
714         if (p->p_fdtol != NULL) {
715                 /*
716                  * Ask fdfree() to sleep to ensure that all relevant
717                  * process leaders can be traversed in closef().
718                  */
719                 fdp->fd_holdleaderscount++;
720                 holdleaders = 1;
721         }
722
723         /*
724          * we now hold the fp reference that used to be owned by the descriptor
725          * array.
726          */
727         while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
728                 fdp->fd_lastfile--;
729         if (fd < fdp->fd_knlistsize)
730                 knote_fdclose(p, fd);
731         error = closef(fp, td);
732         if (holdleaders) {
733                 fdp->fd_holdleaderscount--;
734                 if (fdp->fd_holdleaderscount == 0 &&
735                     fdp->fd_holdleaderswakeup != 0) {
736                         fdp->fd_holdleaderswakeup = 0;
737                         wakeup(&fdp->fd_holdleaderscount);
738                 }
739         }
740         return (error);
741 }
742
743 int
744 kern_fstat(int fd, struct stat *ub)
745 {
746         struct thread *td = curthread;
747         struct proc *p = td->td_proc;
748         struct filedesc *fdp;
749         struct file *fp;
750         int error;
751
752         KKASSERT(p);
753
754         fdp = p->p_fd;
755         if ((unsigned)fd >= fdp->fd_nfiles ||
756             (fp = fdp->fd_files[fd].fp) == NULL)
757                 return (EBADF);
758         fhold(fp);
759         error = fo_stat(fp, ub, td);
760         fdrop(fp, td);
761
762         return (error);
763 }
764
765 /*
766  * Return status information about a file descriptor.
767  */
768 int
769 fstat(struct fstat_args *uap)
770 {
771         struct stat st;
772         int error;
773
774         error = kern_fstat(uap->fd, &st);
775
776         if (error == 0)
777                 error = copyout(&st, uap->sb, sizeof(st));
778         return (error);
779 }
780
781 /*
782  * XXX: This is for source compatibility with NetBSD.  Probably doesn't
783  * belong here.
784  */
785 int
786 nfstat(struct nfstat_args *uap)
787 {
788         struct stat st;
789         struct nstat nst;
790         int error;
791
792         error = kern_fstat(uap->fd, &st);
793
794         if (error == 0) {
795                 cvtnstat(&st, &nst);
796                 error = copyout(&nst, uap->sb, sizeof (nst));
797         }
798         return (error);
799 }
800
801 /*
802  * Return pathconf information about a file descriptor.
803  */
804 /* ARGSUSED */
805 int
806 fpathconf(struct fpathconf_args *uap)
807 {
808         struct thread *td = curthread;
809         struct proc *p = td->td_proc;
810         struct filedesc *fdp;
811         struct file *fp;
812         struct vnode *vp;
813         int error = 0;
814
815         KKASSERT(p);
816         fdp = p->p_fd;
817         if ((unsigned)uap->fd >= fdp->fd_nfiles ||
818             (fp = fdp->fd_files[uap->fd].fp) == NULL)
819                 return (EBADF);
820
821         fhold(fp);
822
823         switch (fp->f_type) {
824         case DTYPE_PIPE:
825         case DTYPE_SOCKET:
826                 if (uap->name != _PC_PIPE_BUF) {
827                         error = EINVAL;
828                 } else {
829                         uap->sysmsg_result = PIPE_BUF;
830                         error = 0;
831                 }
832                 break;
833         case DTYPE_FIFO:
834         case DTYPE_VNODE:
835                 vp = (struct vnode *)fp->f_data;
836                 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
837                 break;
838         default:
839                 error = EOPNOTSUPP;
840                 break;
841         }
842         fdrop(fp, td);
843         return(error);
844 }
845
846 static int fdexpand;
847 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
848
849 static void
850 fdgrow(struct filedesc *fdp, int want)
851 {
852         struct fdnode *newfiles;
853         struct fdnode *oldfiles;
854         int nf, extra;
855
856         nf = fdp->fd_nfiles;
857         do {
858                 /* nf has to be of the form 2^n - 1 */
859                 nf = 2 * nf + 1;
860         } while (nf <= want);
861
862         newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
863
864         /*
865          * deal with file-table extend race that might have occured
866          * when malloc was blocked.
867          */
868         if (fdp->fd_nfiles >= nf) {
869                 free(newfiles, M_FILEDESC);
870                 return;
871         }
872         /*
873          * Copy the existing ofile and ofileflags arrays
874          * and zero the new portion of each array.
875          */
876         extra = nf - fdp->fd_nfiles;
877         bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
878         bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
879
880         oldfiles = fdp->fd_files;
881         fdp->fd_files = newfiles;
882         fdp->fd_nfiles = nf;
883
884         if (oldfiles != fdp->fd_builtin_files)
885                 free(oldfiles, M_FILEDESC);
886         fdexpand++;
887 }
888
889 /*
890  * Number of nodes in right subtree, including the root.
891  */
892 static __inline int
893 right_subtree_size(int n)
894 {
895         return (n ^ (n | (n + 1)));
896 }
897
898 /*
899  * Bigger ancestor.
900  */
901 static __inline int
902 right_ancestor(int n)
903 {
904         return (n | (n + 1));
905 }
906
907 /*
908  * Smaller ancestor.
909  */
910 static __inline int
911 left_ancestor(int n)
912 {
913         return ((n & (n + 1)) - 1);
914 }
915
916 void
917 fdreserve(struct filedesc *fdp, int fd, int incr)
918 {
919         while (fd >= 0) {
920                 fdp->fd_files[fd].allocated += incr;
921                 KKASSERT(fdp->fd_files[fd].allocated >= 0);
922                 fd = left_ancestor(fd);
923         }
924 }
925
926 /*
927  * Allocate a file descriptor for the process.
928  */
929 int
930 fdalloc(struct proc *p, int want, int *result)
931 {
932         struct filedesc *fdp = p->p_fd;
933         int fd, rsize, rsum, node, lim;
934
935         lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
936         if (want >= lim)
937                 return (EMFILE);
938         if (want >= fdp->fd_nfiles)
939                 fdgrow(fdp, want);
940
941         /*
942          * Search for a free descriptor starting at the higher
943          * of want or fd_freefile.  If that fails, consider
944          * expanding the ofile array.
945          */
946 retry:
947         /* move up the tree looking for a subtree with a free node */
948         for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
949              fd = right_ancestor(fd)) {
950                 if (fdp->fd_files[fd].allocated == 0)
951                         goto found;
952
953                 rsize = right_subtree_size(fd);
954                 if (fdp->fd_files[fd].allocated == rsize)
955                         continue;       /* right subtree full */
956
957                 /*
958                  * Free fd is in the right subtree of the tree rooted at fd.
959                  * Call that subtree R.  Look for the smallest (leftmost)
960                  * subtree of R with an unallocated fd: continue moving
961                  * down the left branch until encountering a full left
962                  * subtree, then move to the right.
963                  */
964                 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
965                         node = fd + rsize;
966                         rsum += fdp->fd_files[node].allocated;
967                         if (fdp->fd_files[fd].allocated == rsum + rsize) {
968                                 fd = node;      /* move to the right */
969                                 if (fdp->fd_files[node].allocated == 0)
970                                         goto found;
971                                 rsum = 0;
972                         }
973                 }
974                 goto found;
975         }
976
977         /*
978          * No space in current array.  Expand?
979          */
980         if (fdp->fd_nfiles >= lim)
981                 return (EMFILE);
982         fdgrow(fdp, want);
983         goto retry;
984
985 found:
986         KKASSERT(fd < fdp->fd_nfiles);
987         fdp->fd_files[fd].fileflags = 0;
988         if (fd > fdp->fd_lastfile)
989                 fdp->fd_lastfile = fd;
990         if (want <= fdp->fd_freefile)
991                 fdp->fd_freefile = fd;
992         *result = fd;
993         KKASSERT(fdp->fd_files[fd].fp == NULL);
994         fdreserve(fdp, fd, 1);
995         return (0);
996 }
997
998 /*
999  * Check to see whether n user file descriptors
1000  * are available to the process p.
1001  */
1002 int
1003 fdavail(struct proc *p, int n)
1004 {
1005         struct filedesc *fdp = p->p_fd;
1006         struct fdnode *fdnode;
1007         int i, lim, last;
1008
1009         lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1010         if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1011                 return (1);
1012
1013         last = min(fdp->fd_nfiles, lim);
1014         fdnode = &fdp->fd_files[fdp->fd_freefile];
1015         for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1016                 if (fdnode->fp == NULL && --n <= 0)
1017                         return (1);
1018         }
1019         return (0);
1020 }
1021
1022 /*
1023  * falloc:
1024  *      Create a new open file structure and allocate a file decriptor
1025  *      for the process that refers to it.  If p is NULL, no descriptor
1026  *      is allocated and the file pointer is returned unassociated with
1027  *      any process.  resultfd is only used if p is not NULL and may
1028  *      separately be NULL indicating that you don't need the returned fd.
1029  *
1030  *      A held file pointer is returned.  If a descriptor has been allocated
1031  *      an additional hold on the fp will be made due to the fd_files[]
1032  *      reference.
1033  */
1034 int
1035 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1036 {
1037         static struct timeval lastfail;
1038         static int curfail;
1039         struct file *fp;
1040         int error;
1041
1042         fp = NULL;
1043
1044         /*
1045          * Handle filetable full issues and root overfill.
1046          */
1047         if (nfiles >= maxfiles - maxfilesrootres &&
1048             ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1049                 if (ppsratecheck(&lastfail, &curfail, 1)) {
1050                         printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1051                                 (p ? p->p_ucred->cr_ruid : -1));
1052                 }
1053                 error = ENFILE;
1054                 goto done;
1055         }
1056
1057         /*
1058          * Allocate a new file descriptor.
1059          */
1060         nfiles++;
1061         fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1062         fp->f_count = 1;
1063         fp->f_ops = &badfileops;
1064         fp->f_seqcount = 1;
1065         if (p)
1066                 fp->f_cred = crhold(p->p_ucred);
1067         else
1068                 fp->f_cred = crhold(proc0.p_ucred);
1069         LIST_INSERT_HEAD(&filehead, fp, f_list);
1070         if (resultfd) {
1071                 if ((error = fsetfd(p, fp, resultfd)) != 0) {
1072                         fdrop(fp, p->p_thread);
1073                         fp = NULL;
1074                 }
1075         } else {
1076                 error = 0;
1077         }
1078 done:
1079         *resultfp = fp;
1080         return (error);
1081 }
1082
1083 /*
1084  * Associate a file pointer with a file descriptor.  On success the fp
1085  * will have an additional ref representing the fd_files[] association.
1086  */
1087 int
1088 fsetfd(struct proc *p, struct file *fp, int *resultfd)
1089 {
1090         int fd, error;
1091
1092         fd = -1;
1093         if ((error = fdalloc(p, 0, &fd)) == 0) {
1094                 fhold(fp);
1095                 p->p_fd->fd_files[fd].fp = fp;
1096         }
1097         *resultfd = fd;
1098         return (0);
1099 }
1100
1101 void
1102 funsetfd(struct filedesc *fdp, int fd)
1103 {
1104         fdp->fd_files[fd].fp = NULL;
1105         fdp->fd_files[fd].fileflags = 0;
1106         fdreserve(fdp, fd, -1);
1107         if (fd < fdp->fd_freefile)
1108                 fdp->fd_freefile = fd;
1109 }
1110
1111 void
1112 fsetcred(struct file *fp, struct ucred *cr)
1113 {
1114         crhold(cr);
1115         crfree(fp->f_cred);
1116         fp->f_cred = cr;
1117 }
1118
1119 /*
1120  * Free a file descriptor.
1121  */
1122 void
1123 ffree(struct file *fp)
1124 {
1125         KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1126         LIST_REMOVE(fp, f_list);
1127         crfree(fp->f_cred);
1128         if (fp->f_ncp) {
1129             cache_drop(fp->f_ncp);
1130             fp->f_ncp = NULL;
1131         }
1132         nfiles--;
1133         free(fp, M_FILE);
1134 }
1135
1136 /*
1137  * Build a new filedesc structure.
1138  */
1139 struct filedesc *
1140 fdinit(struct proc *p)
1141 {
1142         struct filedesc *newfdp;
1143         struct filedesc *fdp = p->p_fd;
1144
1145         newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1146         if (fdp->fd_cdir) {
1147                 newfdp->fd_cdir = fdp->fd_cdir;
1148                 vref(newfdp->fd_cdir);
1149                 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1150         }
1151
1152         /*
1153          * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1154          * proc0, but should unconditionally exist in other processes.
1155          */
1156         if (fdp->fd_rdir) {
1157                 newfdp->fd_rdir = fdp->fd_rdir;
1158                 vref(newfdp->fd_rdir);
1159                 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1160         }
1161         if (fdp->fd_jdir) {
1162                 newfdp->fd_jdir = fdp->fd_jdir;
1163                 vref(newfdp->fd_jdir);
1164                 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1165         }
1166
1167         /* Create the file descriptor table. */
1168         newfdp->fd_refcnt = 1;
1169         newfdp->fd_cmask = cmask;
1170         newfdp->fd_files = newfdp->fd_builtin_files;
1171         newfdp->fd_nfiles = NDFILE;
1172         newfdp->fd_knlistsize = -1;
1173
1174         return (newfdp);
1175 }
1176
1177 /*
1178  * Share a filedesc structure.
1179  */
1180 struct filedesc *
1181 fdshare(struct proc *p)
1182 {
1183         p->p_fd->fd_refcnt++;
1184         return (p->p_fd);
1185 }
1186
1187 /*
1188  * Copy a filedesc structure.
1189  */
1190 struct filedesc *
1191 fdcopy(struct proc *p)
1192 {
1193         struct filedesc *newfdp, *fdp = p->p_fd;
1194         struct fdnode *fdnode;
1195         int i;
1196
1197         /* Certain daemons might not have file descriptors. */
1198         if (fdp == NULL)
1199                 return (NULL);
1200
1201         newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK);
1202         *newfdp = *fdp;
1203         if (newfdp->fd_cdir) {
1204                 vref(newfdp->fd_cdir);
1205                 newfdp->fd_ncdir = cache_hold(newfdp->fd_ncdir);
1206         }
1207         /*
1208          * We must check for fd_rdir here, at least for now because
1209          * the init process is created before we have access to the
1210          * rootvode to take a reference to it.
1211          */
1212         if (newfdp->fd_rdir) {
1213                 vref(newfdp->fd_rdir);
1214                 newfdp->fd_nrdir = cache_hold(newfdp->fd_nrdir);
1215         }
1216         if (newfdp->fd_jdir) {
1217                 vref(newfdp->fd_jdir);
1218                 newfdp->fd_njdir = cache_hold(newfdp->fd_njdir);
1219         }
1220         newfdp->fd_refcnt = 1;
1221
1222         /*
1223          * If the number of open files fits in the internal arrays
1224          * of the open file structure, use them, otherwise allocate
1225          * additional memory for the number of descriptors currently
1226          * in use.
1227          */
1228         if (newfdp->fd_lastfile < NDFILE) {
1229                 newfdp->fd_files = newfdp->fd_builtin_files;
1230                 i = NDFILE;
1231         } else {
1232                 /*
1233                  * Compute the smallest file table size
1234                  * for the file descriptors currently in use,
1235                  * allowing the table to shrink.
1236                  */
1237                 i = newfdp->fd_nfiles;
1238                 while ((i-1)/2 > newfdp->fd_lastfile && (i-1)/2 > NDFILE)
1239                         i = (i-1)/2;
1240                 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1241                                           M_FILEDESC, M_WAITOK);
1242         }
1243         newfdp->fd_nfiles = i;
1244
1245         if (fdp->fd_files != fdp->fd_builtin_files ||
1246             newfdp->fd_files != newfdp->fd_builtin_files
1247         ) {
1248                 bcopy(fdp->fd_files, newfdp->fd_files, 
1249                       i * sizeof(struct fdnode));
1250         }
1251
1252         /*
1253          * kq descriptors cannot be copied.
1254          */
1255         if (newfdp->fd_knlistsize != -1) {
1256                 fdnode = &newfdp->fd_files[newfdp->fd_lastfile];
1257                 for (i = newfdp->fd_lastfile; i >= 0; i--, fdnode--) {
1258                         if (fdnode->fp != NULL && fdnode->fp->f_type == DTYPE_KQUEUE)
1259                                 funsetfd(newfdp, i);    /* nulls out *fpp */
1260                         if (fdnode->fp == NULL && i == newfdp->fd_lastfile && i > 0)
1261                                 newfdp->fd_lastfile--;
1262                 }
1263                 newfdp->fd_knlist = NULL;
1264                 newfdp->fd_knlistsize = -1;
1265                 newfdp->fd_knhash = NULL;
1266                 newfdp->fd_knhashmask = 0;
1267         }
1268
1269         fdnode = newfdp->fd_files;
1270         for (i = newfdp->fd_lastfile; i-- >= 0; fdnode++) {
1271                 if (fdnode->fp != NULL)
1272                         fhold(fdnode->fp);
1273         }
1274         return (newfdp);
1275 }
1276
1277 /*
1278  * Release a filedesc structure.
1279  */
1280 void
1281 fdfree(struct proc *p)
1282 {
1283         struct thread *td = p->p_thread;
1284         struct filedesc *fdp = p->p_fd;
1285         struct fdnode *fdnode;
1286         int i;
1287         struct filedesc_to_leader *fdtol;
1288         struct file *fp;
1289         struct vnode *vp;
1290         struct flock lf;
1291
1292         /* Certain daemons might not have file descriptors. */
1293         if (fdp == NULL)
1294                 return;
1295
1296         /* Check for special need to clear POSIX style locks */
1297         fdtol = p->p_fdtol;
1298         if (fdtol != NULL) {
1299                 KASSERT(fdtol->fdl_refcount > 0,
1300                         ("filedesc_to_refcount botch: fdl_refcount=%d",
1301                          fdtol->fdl_refcount));
1302                 if (fdtol->fdl_refcount == 1 &&
1303                     (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1304                         i = 0;
1305                         fdnode = fdp->fd_files;
1306                         for (i = 0; i <= fdp->fd_lastfile; i++, fdnode++) {
1307                                 if (fdnode->fp == NULL ||
1308                                     fdnode->fp->f_type != DTYPE_VNODE)
1309                                         continue;
1310                                 fp = fdnode->fp;
1311                                 fhold(fp);
1312                                 lf.l_whence = SEEK_SET;
1313                                 lf.l_start = 0;
1314                                 lf.l_len = 0;
1315                                 lf.l_type = F_UNLCK;
1316                                 vp = (struct vnode *)fp->f_data;
1317                                 (void) VOP_ADVLOCK(vp,
1318                                                    (caddr_t)p->p_leader,
1319                                                    F_UNLCK,
1320                                                    &lf,
1321                                                    F_POSIX);
1322                                 fdrop(fp, p->p_thread);
1323                                 /* reload due to possible reallocation */
1324                                 fdnode = &fdp->fd_files[i];
1325                         }
1326                 }
1327         retry:
1328                 if (fdtol->fdl_refcount == 1) {
1329                         if (fdp->fd_holdleaderscount > 0 &&
1330                             (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1331                                 /*
1332                                  * close() or do_dup() has cleared a reference
1333                                  * in a shared file descriptor table.
1334                                  */
1335                                 fdp->fd_holdleaderswakeup = 1;
1336                                 tsleep(&fdp->fd_holdleaderscount,
1337                                        0, "fdlhold", 0);
1338                                 goto retry;
1339                         }
1340                         if (fdtol->fdl_holdcount > 0) {
1341                                 /* 
1342                                  * Ensure that fdtol->fdl_leader
1343                                  * remains valid in closef().
1344                                  */
1345                                 fdtol->fdl_wakeup = 1;
1346                                 tsleep(fdtol, 0, "fdlhold", 0);
1347                                 goto retry;
1348                         }
1349                 }
1350                 fdtol->fdl_refcount--;
1351                 if (fdtol->fdl_refcount == 0 &&
1352                     fdtol->fdl_holdcount == 0) {
1353                         fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1354                         fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1355                 } else
1356                         fdtol = NULL;
1357                 p->p_fdtol = NULL;
1358                 if (fdtol != NULL)
1359                         free(fdtol, M_FILEDESC_TO_LEADER);
1360         }
1361         if (--fdp->fd_refcnt > 0)
1362                 return;
1363         /*
1364          * we are the last reference to the structure, we can
1365          * safely assume it will not change out from under us.
1366          */
1367         for (i = 0; i <= fdp->fd_lastfile; ++i) {
1368                 if (fdp->fd_files[i].fp)
1369                         closef(fdp->fd_files[i].fp, td);
1370         }
1371         if (fdp->fd_files != fdp->fd_builtin_files)
1372                 free(fdp->fd_files, M_FILEDESC);
1373         if (fdp->fd_cdir) {
1374                 cache_drop(fdp->fd_ncdir);
1375                 vrele(fdp->fd_cdir);
1376         }
1377         if (fdp->fd_rdir) {
1378                 cache_drop(fdp->fd_nrdir);
1379                 vrele(fdp->fd_rdir);
1380         }
1381         if (fdp->fd_jdir) {
1382                 cache_drop(fdp->fd_njdir);
1383                 vrele(fdp->fd_jdir);
1384         }
1385         if (fdp->fd_knlist)
1386                 free(fdp->fd_knlist, M_KQUEUE);
1387         if (fdp->fd_knhash)
1388                 free(fdp->fd_knhash, M_KQUEUE);
1389         free(fdp, M_FILEDESC);
1390 }
1391
1392 /*
1393  * For setugid programs, we don't want to people to use that setugidness
1394  * to generate error messages which write to a file which otherwise would
1395  * otherwise be off-limits to the process.
1396  *
1397  * This is a gross hack to plug the hole.  A better solution would involve
1398  * a special vop or other form of generalized access control mechanism.  We
1399  * go ahead and just reject all procfs file systems accesses as dangerous.
1400  *
1401  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1402  * sufficient.  We also don't for check setugidness since we know we are.
1403  */
1404 static int
1405 is_unsafe(struct file *fp)
1406 {
1407         if (fp->f_type == DTYPE_VNODE && 
1408             ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1409                 return (1);
1410         return (0);
1411 }
1412
1413 /*
1414  * Make this setguid thing safe, if at all possible.
1415  */
1416 void
1417 setugidsafety(struct proc *p)
1418 {
1419         struct thread *td = p->p_thread;
1420         struct filedesc *fdp = p->p_fd;
1421         int i;
1422
1423         /* Certain daemons might not have file descriptors. */
1424         if (fdp == NULL)
1425                 return;
1426
1427         /*
1428          * note: fdp->fd_files may be reallocated out from under us while
1429          * we are blocked in a close.  Be careful!
1430          */
1431         for (i = 0; i <= fdp->fd_lastfile; i++) {
1432                 if (i > 2)
1433                         break;
1434                 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1435                         struct file *fp;
1436
1437 #if 0
1438                         if ((fdp->fd_files[i].fileflags & UF_MAPPED) != 0)
1439                                 (void) munmapfd(p, i);
1440 #endif
1441                         if (i < fdp->fd_knlistsize)
1442                                 knote_fdclose(p, i);
1443                         /*
1444                          * NULL-out descriptor prior to close to avoid
1445                          * a race while close blocks.
1446                          */
1447                         fp = fdp->fd_files[i].fp;
1448                         funsetfd(fdp, i);
1449                         closef(fp, td);
1450                 }
1451         }
1452         while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
1453                 fdp->fd_lastfile--;
1454 }
1455
1456 /*
1457  * Close any files on exec?
1458  */
1459 void
1460 fdcloseexec(struct proc *p)
1461 {
1462         struct thread *td = p->p_thread;
1463         struct filedesc *fdp = p->p_fd;
1464         int i;
1465
1466         /* Certain daemons might not have file descriptors. */
1467         if (fdp == NULL)
1468                 return;
1469
1470         /*
1471          * We cannot cache fd_files since operations may block and rip
1472          * them out from under us.
1473          */
1474         for (i = 0; i <= fdp->fd_lastfile; i++) {
1475                 if (fdp->fd_files[i].fp != NULL &&
1476                     (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1477                         struct file *fp;
1478
1479 #if 0
1480                         if (fdp->fd_files[i].fileflags & UF_MAPPED)
1481                                 (void) munmapfd(p, i);
1482 #endif
1483                         if (i < fdp->fd_knlistsize)
1484                                 knote_fdclose(p, i);
1485                         /*
1486                          * NULL-out descriptor prior to close to avoid
1487                          * a race while close blocks.
1488                          */
1489                         fp = fdp->fd_files[i].fp;
1490                         funsetfd(fdp, i);
1491                         closef(fp, td);
1492                 }
1493         }
1494         while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
1495                 fdp->fd_lastfile--;
1496 }
1497
1498 /*
1499  * It is unsafe for set[ug]id processes to be started with file
1500  * descriptors 0..2 closed, as these descriptors are given implicit
1501  * significance in the Standard C library.  fdcheckstd() will create a
1502  * descriptor referencing /dev/null for each of stdin, stdout, and
1503  * stderr that is not already open.
1504  */
1505 int
1506 fdcheckstd(struct proc *p)
1507 {
1508         struct thread *td = p->p_thread;
1509         struct nlookupdata nd;
1510         struct filedesc *fdp;
1511         struct file *fp;
1512         register_t retval;
1513         int fd, i, error, flags, devnull;
1514
1515        fdp = p->p_fd;
1516        if (fdp == NULL)
1517                return (0);
1518        devnull = -1;
1519        error = 0;
1520        for (i = 0; i < 3; i++) {
1521                 if (fdp->fd_files[i].fp != NULL)
1522                         continue;
1523                 if (devnull < 0) {
1524                         if ((error = falloc(p, &fp, NULL)) != 0)
1525                                 break;
1526
1527                         error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1528                                                 NLC_FOLLOW|NLC_LOCKVP);
1529                         flags = FREAD | FWRITE;
1530                         if (error == 0)
1531                                 error = vn_open(&nd, fp, flags, 0);
1532                         if (error == 0)
1533                                 error = fsetfd(p, fp, &fd);
1534                         fdrop(fp, td);
1535                         nlookup_done(&nd);
1536                         if (error)
1537                                 break;
1538                         KKASSERT(i == fd);
1539                         devnull = fd;
1540                 } else {
1541                         error = kern_dup(DUP_FIXED, devnull, i, &retval);
1542                         if (error != 0)
1543                                 break;
1544                 }
1545        }
1546        return (error);
1547 }
1548
1549 /*
1550  * Internal form of close.
1551  * Decrement reference count on file structure.
1552  * Note: td and/or p may be NULL when closing a file
1553  * that was being passed in a message.
1554  */
1555 int
1556 closef(struct file *fp, struct thread *td)
1557 {
1558         struct vnode *vp;
1559         struct flock lf;
1560         struct filedesc_to_leader *fdtol;
1561         struct proc *p;
1562
1563         if (fp == NULL)
1564                 return (0);
1565         if (td == NULL) {
1566                 td = curthread;
1567                 p = NULL;               /* allow no proc association */
1568         } else {
1569                 p = td->td_proc;        /* can also be NULL */
1570         }
1571         /*
1572          * POSIX record locking dictates that any close releases ALL
1573          * locks owned by this process.  This is handled by setting
1574          * a flag in the unlock to free ONLY locks obeying POSIX
1575          * semantics, and not to free BSD-style file locks.
1576          * If the descriptor was in a message, POSIX-style locks
1577          * aren't passed with the descriptor.
1578          */
1579         if (p != NULL && 
1580             fp->f_type == DTYPE_VNODE) {
1581                 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1582                         lf.l_whence = SEEK_SET;
1583                         lf.l_start = 0;
1584                         lf.l_len = 0;
1585                         lf.l_type = F_UNLCK;
1586                         vp = (struct vnode *)fp->f_data;
1587                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1588                                            &lf, F_POSIX);
1589                 }
1590                 fdtol = p->p_fdtol;
1591                 if (fdtol != NULL) {
1592                         /*
1593                          * Handle special case where file descriptor table
1594                          * is shared between multiple process leaders.
1595                          */
1596                         for (fdtol = fdtol->fdl_next;
1597                              fdtol != p->p_fdtol;
1598                              fdtol = fdtol->fdl_next) {
1599                                 if ((fdtol->fdl_leader->p_flag &
1600                                      P_ADVLOCK) == 0)
1601                                         continue;
1602                                 fdtol->fdl_holdcount++;
1603                                 lf.l_whence = SEEK_SET;
1604                                 lf.l_start = 0;
1605                                 lf.l_len = 0;
1606                                 lf.l_type = F_UNLCK;
1607                                 vp = (struct vnode *)fp->f_data;
1608                                 (void) VOP_ADVLOCK(vp,
1609                                                    (caddr_t)p->p_leader,
1610                                                    F_UNLCK, &lf, F_POSIX);
1611                                 fdtol->fdl_holdcount--;
1612                                 if (fdtol->fdl_holdcount == 0 &&
1613                                     fdtol->fdl_wakeup != 0) {
1614                                         fdtol->fdl_wakeup = 0;
1615                                         wakeup(fdtol);
1616                                 }
1617                         }
1618                 }
1619         }
1620         return (fdrop(fp, td));
1621 }
1622
1623 int
1624 fdrop(struct file *fp, struct thread *td)
1625 {
1626         struct flock lf;
1627         struct vnode *vp;
1628         int error;
1629
1630         if (--fp->f_count > 0)
1631                 return (0);
1632         if (fp->f_count < 0)
1633                 panic("fdrop: count < 0");
1634         if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1635                 lf.l_whence = SEEK_SET;
1636                 lf.l_start = 0;
1637                 lf.l_len = 0;
1638                 lf.l_type = F_UNLCK;
1639                 vp = (struct vnode *)fp->f_data;
1640                 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
1641         }
1642         if (fp->f_ops != &badfileops)
1643                 error = fo_close(fp, td);
1644         else
1645                 error = 0;
1646         ffree(fp);
1647         return (error);
1648 }
1649
1650 /*
1651  * Apply an advisory lock on a file descriptor.
1652  *
1653  * Just attempt to get a record lock of the requested type on
1654  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1655  */
1656 /* ARGSUSED */
1657 int
1658 flock(struct flock_args *uap)
1659 {
1660         struct proc *p = curproc;
1661         struct filedesc *fdp = p->p_fd;
1662         struct file *fp;
1663         struct vnode *vp;
1664         struct flock lf;
1665
1666         if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1667             (fp = fdp->fd_files[uap->fd].fp) == NULL)
1668                 return (EBADF);
1669         if (fp->f_type != DTYPE_VNODE)
1670                 return (EOPNOTSUPP);
1671         vp = (struct vnode *)fp->f_data;
1672         lf.l_whence = SEEK_SET;
1673         lf.l_start = 0;
1674         lf.l_len = 0;
1675         if (uap->how & LOCK_UN) {
1676                 lf.l_type = F_UNLCK;
1677                 fp->f_flag &= ~FHASLOCK;
1678                 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK));
1679         }
1680         if (uap->how & LOCK_EX)
1681                 lf.l_type = F_WRLCK;
1682         else if (uap->how & LOCK_SH)
1683                 lf.l_type = F_RDLCK;
1684         else
1685                 return (EBADF);
1686         fp->f_flag |= FHASLOCK;
1687         if (uap->how & LOCK_NB)
1688                 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK));
1689         return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT));
1690 }
1691
1692 /*
1693  * File Descriptor pseudo-device driver (/dev/fd/).
1694  *
1695  * Opening minor device N dup()s the file (if any) connected to file
1696  * descriptor N belonging to the calling process.  Note that this driver
1697  * consists of only the ``open()'' routine, because all subsequent
1698  * references to this file will be direct to the other driver.
1699  */
1700 /* ARGSUSED */
1701 static int
1702 fdopen(dev_t dev, int mode, int type, struct thread *td)
1703 {
1704         KKASSERT(td->td_proc != NULL);
1705
1706         /*
1707          * XXX Kludge: set curproc->p_dupfd to contain the value of the
1708          * the file descriptor being sought for duplication. The error
1709          * return ensures that the vnode for this device will be released
1710          * by vn_open. Open will detect this special error and take the
1711          * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1712          * will simply report the error.
1713          */
1714         td->td_proc->p_dupfd = minor(dev);
1715         return (ENODEV);
1716 }
1717
1718 /*
1719  * Duplicate the specified descriptor to a free descriptor.
1720  */
1721 int
1722 dupfdopen(struct filedesc *fdp, int indx, int dfd, int mode, int error)
1723 {
1724         struct file *wfp;
1725         struct file *fp;
1726
1727         /*
1728          * If the to-be-dup'd fd number is greater than the allowed number
1729          * of file descriptors, or the fd to be dup'd has already been
1730          * closed, then reject.
1731          */
1732         if ((u_int)dfd >= fdp->fd_nfiles ||
1733             (wfp = fdp->fd_files[dfd].fp) == NULL) {
1734                 return (EBADF);
1735         }
1736
1737         /*
1738          * There are two cases of interest here.
1739          *
1740          * For ENODEV simply dup (dfd) to file descriptor
1741          * (indx) and return.
1742          *
1743          * For ENXIO steal away the file structure from (dfd) and
1744          * store it in (indx).  (dfd) is effectively closed by
1745          * this operation.
1746          *
1747          * Any other error code is just returned.
1748          */
1749         switch (error) {
1750         case ENODEV:
1751                 /*
1752                  * Check that the mode the file is being opened for is a
1753                  * subset of the mode of the existing descriptor.
1754                  */
1755                 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1756                         return (EACCES);
1757                 fp = fdp->fd_files[indx].fp;
1758 #if 0
1759                 if (fp && fdp->fd_files[indx].fileflags & UF_MAPPED)
1760                         (void) munmapfd(p, indx);
1761 #endif
1762                 fdp->fd_files[indx].fp = wfp;
1763                 fdp->fd_files[indx].fileflags = fdp->fd_files[dfd].fileflags;
1764                 fhold(wfp);
1765                 if (indx > fdp->fd_lastfile)
1766                         fdp->fd_lastfile = indx;
1767                 /*
1768                  * we now own the reference to fp that the ofiles[] array
1769                  * used to own.  Release it.
1770                  */
1771                 if (fp)
1772                         fdrop(fp, curthread);
1773                 return (0);
1774
1775         case ENXIO:
1776                 /*
1777                  * Steal away the file pointer from dfd, and stuff it into indx.
1778                  */
1779                 fp = fdp->fd_files[indx].fp;
1780 #if 0
1781                 if (fp && fdp->fd_files[indx].fileflags & UF_MAPPED)
1782                         (void) munmapfd(p, indx);
1783 #endif
1784                 fdp->fd_files[indx].fp = fdp->fd_files[dfd].fp;
1785                 fdp->fd_files[indx].fileflags = fdp->fd_files[dfd].fileflags;
1786                 funsetfd(fdp, dfd);
1787
1788                 /*
1789                  * we now own the reference to fp that the files[] array
1790                  * used to own.  Release it.
1791                  */
1792                 if (fp)
1793                         fdrop(fp, curthread);
1794                 /*
1795                  * Complete the clean up of the filedesc structure by
1796                  * recomputing the various hints.
1797                  */
1798                 if (indx > fdp->fd_lastfile) {
1799                         fdp->fd_lastfile = indx;
1800                 } else {
1801                         while (fdp->fd_lastfile > 0 &&
1802                            fdp->fd_files[fdp->fd_lastfile].fp == NULL) {
1803                                 fdp->fd_lastfile--;
1804                         }
1805                 }
1806                 return (0);
1807
1808         default:
1809                 return (error);
1810         }
1811         /* NOTREACHED */
1812 }
1813
1814
1815 struct filedesc_to_leader *
1816 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
1817                          struct proc *leader)
1818 {
1819         struct filedesc_to_leader *fdtol;
1820         
1821         fdtol = malloc(sizeof(struct filedesc_to_leader), 
1822                         M_FILEDESC_TO_LEADER, M_WAITOK);
1823         fdtol->fdl_refcount = 1;
1824         fdtol->fdl_holdcount = 0;
1825         fdtol->fdl_wakeup = 0;
1826         fdtol->fdl_leader = leader;
1827         if (old != NULL) {
1828                 fdtol->fdl_next = old->fdl_next;
1829                 fdtol->fdl_prev = old;
1830                 old->fdl_next = fdtol;
1831                 fdtol->fdl_next->fdl_prev = fdtol;
1832         } else {
1833                 fdtol->fdl_next = fdtol;
1834                 fdtol->fdl_prev = fdtol;
1835         }
1836         return fdtol;
1837 }
1838
1839 /*
1840  * Get file structures.
1841  */
1842 static int
1843 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
1844 {
1845         struct kinfo_file kf;
1846         struct filedesc *fdp;
1847         struct file *fp;
1848         struct proc *p;
1849         int count;
1850         int error;
1851         int n;
1852
1853         /*
1854          * Note: because the number of file descriptors is calculated
1855          * in different ways for sizing vs returning the data,
1856          * there is information leakage from the first loop.  However,
1857          * it is of a similar order of magnitude to the leakage from
1858          * global system statistics such as kern.openfiles.
1859          *
1860          * When just doing a count, note that we cannot just count
1861          * the elements and add f_count via the filehead list because 
1862          * threaded processes share their descriptor table and f_count might
1863          * still be '1' in that case.
1864          */
1865         count = 0;
1866         error = 0;
1867         LIST_FOREACH(p, &allproc, p_list) {
1868                 if (p->p_stat == SIDL)
1869                         continue;
1870                 if (!PRISON_CHECK(req->td->td_proc->p_ucred, p->p_ucred) != 0)
1871                         continue;
1872                 if ((fdp = p->p_fd) == NULL)
1873                         continue;
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                                 kcore_make_file(&kf, fp, p->p_pid,
1881                                                 p->p_ucred->cr_uid, n);
1882                                 error = SYSCTL_OUT(req, &kf, sizeof(kf));
1883                                 if (error)
1884                                         break;
1885                         }
1886                 }
1887                 if (error)
1888                         break;
1889         }
1890
1891         /*
1892          * When just calculating the size, overestimate a bit to try to
1893          * prevent system activity from causing the buffer-fill call 
1894          * to fail later on.
1895          */
1896         if (req->oldptr == NULL) {
1897                 count = (count + 16) + (count / 10);
1898                 error = SYSCTL_OUT(req, NULL, count * sizeof(kf));
1899         }
1900         return (error);
1901 }
1902
1903 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
1904     0, 0, sysctl_kern_file, "S,file", "Entire file table");
1905
1906 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW, 
1907     &maxfilesperproc, 0, "Maximum files allowed open per process");
1908
1909 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW, 
1910     &maxfiles, 0, "Maximum number of files");
1911
1912 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW, 
1913     &maxfilesrootres, 0, "Descriptors reserved for root use");
1914
1915 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD, 
1916         &nfiles, 0, "System-wide number of open files");
1917
1918 static void
1919 fildesc_drvinit(void *unused)
1920 {
1921         int fd;
1922
1923         cdevsw_add(&fildesc_cdevsw, 0, 0);
1924         for (fd = 0; fd < NUMFDESC; fd++) {
1925                 make_dev(&fildesc_cdevsw, fd,
1926                     UID_BIN, GID_BIN, 0666, "fd/%d", fd);
1927         }
1928         make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
1929         make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
1930         make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
1931 }
1932
1933 struct fileops badfileops = {
1934         NULL,   /* port */
1935         NULL,   /* clone */
1936         badfo_readwrite,
1937         badfo_readwrite,
1938         badfo_ioctl,
1939         badfo_poll,
1940         badfo_kqfilter,
1941         badfo_stat,
1942         badfo_close
1943 };
1944
1945 static int
1946 badfo_readwrite(
1947         struct file *fp,
1948         struct uio *uio,
1949         struct ucred *cred,
1950         int flags,
1951         struct thread *td
1952 ) {
1953         return (EBADF);
1954 }
1955
1956 static int
1957 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct thread *td)
1958 {
1959         return (EBADF);
1960 }
1961
1962 static int
1963 badfo_poll(struct file *fp, int events, struct ucred *cred, struct thread *td)
1964 {
1965         return (0);
1966 }
1967
1968 static int
1969 badfo_kqfilter(struct file *fp, struct knote *kn)
1970 {
1971         return (0);
1972 }
1973
1974 static int
1975 badfo_stat(struct file *fp, struct stat *sb, struct thread *td)
1976 {
1977         return (EBADF);
1978 }
1979
1980 static int
1981 badfo_close(struct file *fp, struct thread *td)
1982 {
1983         return (EBADF);
1984 }
1985
1986 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
1987                                         fildesc_drvinit,NULL)