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