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