Add #include <sys/lock.h> where needed to support get_mplock().
[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.65 2006/05/26 02:26:01 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 #include <sys/spinlock2.h>
105
106 static void fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd);
107 static void fdreserve_locked (struct filedesc *fdp, int fd0, int incr);
108 static struct file *funsetfd_locked (struct filedesc *fdp, int fd);
109 static int checkfpclosed(struct filedesc *fdp, int fd, struct file *fp);
110 static void ffree(struct file *fp);
111
112 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
113 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
114                      "file desc to leader structures");
115 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
116 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
117
118 static   d_open_t  fdopen;
119 #define NUMFDESC 64
120
121 #define CDEV_MAJOR 22
122 static struct cdevsw fildesc_cdevsw = {
123         /* name */      "FD",
124         /* maj */       CDEV_MAJOR,
125         /* flags */     0,
126         /* port */      NULL,
127         /* clone */     NULL,
128
129         /* open */      fdopen,
130         /* close */     noclose,
131         /* read */      noread,
132         /* write */     nowrite,
133         /* ioctl */     noioctl,
134         /* poll */      nopoll,
135         /* mmap */      nommap,
136         /* strategy */  nostrategy,
137         /* dump */      nodump,
138         /* psize */     nopsize
139 };
140
141 static int badfo_readwrite (struct file *fp, struct uio *uio,
142     struct ucred *cred, int flags);
143 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
144     struct ucred *cred);
145 static int badfo_poll (struct file *fp, int events, struct ucred *cred);
146 static int badfo_kqfilter (struct file *fp, struct knote *kn);
147 static int badfo_stat (struct file *fp, struct stat *sb, struct ucred *cred);
148 static int badfo_close (struct file *fp);
149 static int badfo_shutdown (struct file *fp, int how);
150
151 /*
152  * Descriptor management.
153  */
154 static struct filelist filehead = LIST_HEAD_INITIALIZER(&filehead);
155 static struct spinlock filehead_spin = SPINLOCK_INITIALIZER(&filehead_spin);
156 static int nfiles;              /* actual number of open files */
157 extern int cmask;       
158
159 /*
160  * Fixup fd_freefile and fd_lastfile after a descriptor has been cleared.
161  *
162  * MPSAFE - must be called with fdp->fd_spin exclusively held
163  */
164 static __inline
165 void
166 fdfixup_locked(struct filedesc *fdp, int fd)
167 {
168         if (fd < fdp->fd_freefile) {
169                fdp->fd_freefile = fd;
170         }
171         while (fdp->fd_lastfile >= 0 &&
172                fdp->fd_files[fdp->fd_lastfile].fp == NULL &&
173                fdp->fd_files[fdp->fd_lastfile].reserved == 0
174         ) {
175                 --fdp->fd_lastfile;
176         }
177 }
178
179 /*
180  * System calls on descriptors.
181  *
182  * MPSAFE
183  */
184 int
185 getdtablesize(struct getdtablesize_args *uap) 
186 {
187         struct proc *p = curproc;
188         struct plimit *limit = p->p_limit;
189
190         spin_lock_rd(&limit->p_spin);
191         uap->sysmsg_result = 
192             min((int)limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
193         spin_unlock_rd(&limit->p_spin);
194         return (0);
195 }
196
197 /*
198  * Duplicate a file descriptor to a particular value.
199  *
200  * note: keep in mind that a potential race condition exists when closing
201  * descriptors from a shared descriptor table (via rfork).
202  *
203  * MPSAFE
204  */
205 int
206 dup2(struct dup2_args *uap)
207 {
208         int error;
209
210         error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
211
212         return (error);
213 }
214
215 /*
216  * Duplicate a file descriptor.
217  *
218  * MPSAFE
219  */
220 int
221 dup(struct dup_args *uap)
222 {
223         int error;
224
225         error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
226
227         return (error);
228 }
229
230 /*
231  * MPALMOSTSAFE - acquires mplock for fp operations
232  */
233 int
234 kern_fcntl(int fd, int cmd, union fcntl_dat *dat, struct ucred *cred)
235 {
236         struct thread *td = curthread;
237         struct proc *p = td->td_proc;
238         struct file *fp;
239         struct vnode *vp;
240         u_int newmin;
241         int tmp, error, flg = F_POSIX;
242
243         KKASSERT(p);
244
245         /*
246          * Operations on file descriptors that do not require a file pointer.
247          */
248         switch (cmd) {
249         case F_GETFD:
250                 error = fgetfdflags(p->p_fd, fd, &tmp);
251                 if (error == 0)
252                         dat->fc_cloexec = (tmp & UF_EXCLOSE) ? FD_CLOEXEC : 0;
253                 return (error);
254
255         case F_SETFD:
256                 if (dat->fc_cloexec & FD_CLOEXEC)
257                         error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
258                 else
259                         error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
260                 return (error);
261         case F_DUPFD:
262                 newmin = dat->fc_fd;
263                 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
264                 return (error);
265         default:
266                 break;
267         }
268
269         /*
270          * Operations on file pointers
271          */
272         if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
273                 return (EBADF);
274
275         get_mplock();
276         switch (cmd) {
277         case F_GETFL:
278                 dat->fc_flags = OFLAGS(fp->f_flag);
279                 error = 0;
280                 break;
281
282         case F_SETFL:
283                 fp->f_flag &= ~FCNTLFLAGS;
284                 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
285                 tmp = fp->f_flag & FNONBLOCK;
286                 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
287                 if (error)
288                         break;
289                 tmp = fp->f_flag & FASYNC;
290                 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred);
291                 if (error == 0)
292                         break;
293                 fp->f_flag &= ~FNONBLOCK;
294                 tmp = 0;
295                 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
296                 break;
297
298         case F_GETOWN:
299                 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, cred);
300                 break;
301
302         case F_SETOWN:
303                 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, cred);
304                 break;
305
306         case F_SETLKW:
307                 flg |= F_WAIT;
308                 /* Fall into F_SETLK */
309
310         case F_SETLK:
311                 if (fp->f_type != DTYPE_VNODE) {
312                         error = EBADF;
313                         break;
314                 }
315                 vp = (struct vnode *)fp->f_data;
316
317                 /*
318                  * copyin/lockop may block
319                  */
320                 if (dat->fc_flock.l_whence == SEEK_CUR)
321                         dat->fc_flock.l_start += fp->f_offset;
322
323                 switch (dat->fc_flock.l_type) {
324                 case F_RDLCK:
325                         if ((fp->f_flag & FREAD) == 0) {
326                                 error = EBADF;
327                                 break;
328                         }
329                         p->p_leader->p_flag |= P_ADVLOCK;
330                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
331                             &dat->fc_flock, flg);
332                         break;
333                 case F_WRLCK:
334                         if ((fp->f_flag & FWRITE) == 0) {
335                                 error = EBADF;
336                                 break;
337                         }
338                         p->p_leader->p_flag |= P_ADVLOCK;
339                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
340                             &dat->fc_flock, flg);
341                         break;
342                 case F_UNLCK:
343                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
344                                 &dat->fc_flock, F_POSIX);
345                         break;
346                 default:
347                         error = EINVAL;
348                         break;
349                 }
350
351                 /*
352                  * It is possible to race a close() on the descriptor while
353                  * we were blocked getting the lock.  If this occurs the
354                  * close might not have caught the lock.
355                  */
356                 if (checkfpclosed(p->p_fd, fd, fp)) {
357                         dat->fc_flock.l_whence = SEEK_SET;
358                         dat->fc_flock.l_start = 0;
359                         dat->fc_flock.l_len = 0;
360                         dat->fc_flock.l_type = F_UNLCK;
361                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
362                                            F_UNLCK, &dat->fc_flock, F_POSIX);
363                 }
364                 break;
365
366         case F_GETLK:
367                 if (fp->f_type != DTYPE_VNODE) {
368                         error = EBADF;
369                         break;
370                 }
371                 vp = (struct vnode *)fp->f_data;
372                 /*
373                  * copyin/lockop may block
374                  */
375                 if (dat->fc_flock.l_type != F_RDLCK &&
376                     dat->fc_flock.l_type != F_WRLCK &&
377                     dat->fc_flock.l_type != F_UNLCK) {
378                         error = EINVAL;
379                         break;
380                 }
381                 if (dat->fc_flock.l_whence == SEEK_CUR)
382                         dat->fc_flock.l_start += fp->f_offset;
383                 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
384                             &dat->fc_flock, F_POSIX);
385                 break;
386         default:
387                 error = EINVAL;
388                 break;
389         }
390         rel_mplock();
391
392         fdrop(fp);
393         return (error);
394 }
395
396 /*
397  * The file control system call.
398  *
399  * MPSAFE
400  */
401 int
402 fcntl(struct fcntl_args *uap)
403 {
404         union fcntl_dat dat;
405         int error;
406
407         switch (uap->cmd) {
408         case F_DUPFD:
409                 dat.fc_fd = uap->arg;
410                 break;
411         case F_SETFD:
412                 dat.fc_cloexec = uap->arg;
413                 break;
414         case F_SETFL:
415                 dat.fc_flags = uap->arg;
416                 break;
417         case F_SETOWN:
418                 dat.fc_owner = uap->arg;
419                 break;
420         case F_SETLKW:
421         case F_SETLK:
422         case F_GETLK:
423                 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
424                                sizeof(struct flock));
425                 if (error)
426                         return (error);
427                 break;
428         }
429
430         error = kern_fcntl(uap->fd, uap->cmd, &dat, curproc->p_ucred);
431
432         if (error == 0) {
433                 switch (uap->cmd) {
434                 case F_DUPFD:
435                         uap->sysmsg_result = dat.fc_fd;
436                         break;
437                 case F_GETFD:
438                         uap->sysmsg_result = dat.fc_cloexec;
439                         break;
440                 case F_GETFL:
441                         uap->sysmsg_result = dat.fc_flags;
442                         break;
443                 case F_GETOWN:
444                         uap->sysmsg_result = dat.fc_owner;
445                 case F_GETLK:
446                         error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
447                             sizeof(struct flock));
448                         break;
449                 }
450         }
451
452         return (error);
453 }
454
455 /*
456  * Common code for dup, dup2, and fcntl(F_DUPFD).
457  *
458  * The type flag can be either DUP_FIXED or DUP_VARIABLE.  DUP_FIXED tells
459  * kern_dup() to destructively dup over an existing file descriptor if new
460  * is already open.  DUP_VARIABLE tells kern_dup() to find the lowest
461  * unused file descriptor that is greater than or equal to new.
462  *
463  * MPSAFE
464  */
465 int
466 kern_dup(enum dup_type type, int old, int new, int *res)
467 {
468         struct thread *td = curthread;
469         struct proc *p = td->td_proc;
470         struct filedesc *fdp = p->p_fd;
471         struct file *fp;
472         struct file *delfp;
473         int oldflags;
474         int holdleaders;
475         int error, newfd;
476
477         /*
478          * Verify that we have a valid descriptor to dup from and
479          * possibly to dup to.
480          */
481 retry:
482         spin_lock_wr(&fdp->fd_spin);
483         if (new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
484             new >= maxfilesperproc) {
485                 spin_unlock_wr(&fdp->fd_spin);
486                 return (EINVAL);
487         }
488         if ((unsigned)old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL) {
489                 spin_unlock_wr(&fdp->fd_spin);
490                 return (EBADF);
491         }
492         if (type == DUP_FIXED && old == new) {
493                 *res = new;
494                 spin_unlock_wr(&fdp->fd_spin);
495                 return (0);
496         }
497         fp = fdp->fd_files[old].fp;
498         oldflags = fdp->fd_files[old].fileflags;
499         fhold(fp);      /* MPSAFE - can be called with a spinlock held */
500
501         /*
502          * Allocate a new descriptor if DUP_VARIABLE, or expand the table
503          * if the requested descriptor is beyond the current table size.
504          *
505          * This can block.  Retry if the source descriptor no longer matches
506          * or if our expectation in the expansion case races.
507          *
508          * If we are not expanding or allocating a new decriptor, then reset
509          * the target descriptor to a reserved state so we have a uniform
510          * setup for the next code block.
511          */
512         if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
513                 spin_unlock_wr(&fdp->fd_spin);
514                 error = fdalloc(p, new, &newfd);
515                 spin_lock_wr(&fdp->fd_spin);
516                 if (error) {
517                         spin_unlock_wr(&fdp->fd_spin);
518                         fdrop(fp);
519                         return (error);
520                 }
521                 /*
522                  * Check for ripout
523                  */
524                 if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp != fp) {
525                         fsetfd_locked(fdp, NULL, newfd);
526                         spin_unlock_wr(&fdp->fd_spin);
527                         fdrop(fp);
528                         goto retry;
529                 }
530                 /*
531                  * Check for expansion race
532                  */
533                 if (type != DUP_VARIABLE && new != newfd) {
534                         fsetfd_locked(fdp, NULL, newfd);
535                         spin_unlock_wr(&fdp->fd_spin);
536                         fdrop(fp);
537                         goto retry;
538                 }
539                 /*
540                  * Check for ripout, newfd reused old (this case probably
541                  * can't occur).
542                  */
543                 if (old == newfd) {
544                         fsetfd_locked(fdp, NULL, newfd);
545                         spin_unlock_wr(&fdp->fd_spin);
546                         fdrop(fp);
547                         goto retry;
548                 }
549                 new = newfd;
550                 delfp = NULL;
551         } else {
552                 if (fdp->fd_files[new].reserved) {
553                         spin_unlock_wr(&fdp->fd_spin);
554                         fdrop(fp);
555                         printf("Warning: dup(): target descriptor %d is reserved, waiting for it to be resolved\n", new);
556                         tsleep(fdp, 0, "fdres", hz);
557                         goto retry;
558                 }
559
560                 /*
561                  * If the target descriptor was never allocated we have
562                  * to allocate it.  If it was we have to clean out the
563                  * old descriptor.  delfp inherits the ref from the 
564                  * descriptor table.
565                  */
566                 delfp = fdp->fd_files[new].fp;
567                 fdp->fd_files[new].fp = NULL;
568                 fdp->fd_files[new].reserved = 1;
569                 if (delfp == NULL) {
570                         fdreserve_locked(fdp, new, 1);
571                         if (new > fdp->fd_lastfile)
572                                 fdp->fd_lastfile = new;
573                 }
574
575         }
576
577         /*
578          * NOTE: still holding an exclusive spinlock
579          */
580
581         /*
582          * If a descriptor is being overwritten we may hve to tell 
583          * fdfree() to sleep to ensure that all relevant process
584          * leaders can be traversed in closef().
585          */
586         if (delfp != NULL && p->p_fdtol != NULL) {
587                 fdp->fd_holdleaderscount++;
588                 holdleaders = 1;
589         } else {
590                 holdleaders = 0;
591         }
592         KASSERT(delfp == NULL || type == DUP_FIXED,
593                 ("dup() picked an open file"));
594
595         /*
596          * Duplicate the source descriptor, update lastfile.  If the new
597          * descriptor was not allocated and we aren't replacing an existing
598          * descriptor we have to mark the descriptor as being in use.
599          *
600          * The fd_files[] array inherits fp's hold reference.
601          */
602         fsetfd_locked(fdp, fp, new);
603         fdp->fd_files[new].fileflags = oldflags & ~UF_EXCLOSE;
604         spin_unlock_wr(&fdp->fd_spin);
605         fdrop(fp);
606         *res = new;
607
608         /*
609          * If we dup'd over a valid file, we now own the reference to it
610          * and must dispose of it using closef() semantics (as if a
611          * close() were performed on it).
612          */
613         if (delfp) {
614                 (void)closef(delfp, td);
615                 if (holdleaders) {
616                         spin_lock_wr(&fdp->fd_spin);
617                         fdp->fd_holdleaderscount--;
618                         if (fdp->fd_holdleaderscount == 0 &&
619                             fdp->fd_holdleaderswakeup != 0) {
620                                 fdp->fd_holdleaderswakeup = 0;
621                                 spin_unlock_wr(&fdp->fd_spin);
622                                 wakeup(&fdp->fd_holdleaderscount);
623                         } else {
624                                 spin_unlock_wr(&fdp->fd_spin);
625                         }
626                 }
627         }
628         return (0);
629 }
630
631 /*
632  * If sigio is on the list associated with a process or process group,
633  * disable signalling from the device, remove sigio from the list and
634  * free sigio.
635  */
636 void
637 funsetown(struct sigio *sigio)
638 {
639         if (sigio == NULL)
640                 return;
641         crit_enter();
642         *(sigio->sio_myref) = NULL;
643         crit_exit();
644         if (sigio->sio_pgid < 0) {
645                 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
646                              sigio, sio_pgsigio);
647         } else /* if ((*sigiop)->sio_pgid > 0) */ {
648                 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
649                              sigio, sio_pgsigio);
650         }
651         crfree(sigio->sio_ucred);
652         free(sigio, M_SIGIO);
653 }
654
655 /* Free a list of sigio structures. */
656 void
657 funsetownlst(struct sigiolst *sigiolst)
658 {
659         struct sigio *sigio;
660
661         while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
662                 funsetown(sigio);
663 }
664
665 /*
666  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
667  *
668  * After permission checking, add a sigio structure to the sigio list for
669  * the process or process group.
670  */
671 int
672 fsetown(pid_t pgid, struct sigio **sigiop)
673 {
674         struct proc *proc;
675         struct pgrp *pgrp;
676         struct sigio *sigio;
677
678         if (pgid == 0) {
679                 funsetown(*sigiop);
680                 return (0);
681         }
682         if (pgid > 0) {
683                 proc = pfind(pgid);
684                 if (proc == NULL)
685                         return (ESRCH);
686
687                 /*
688                  * Policy - Don't allow a process to FSETOWN a process
689                  * in another session.
690                  *
691                  * Remove this test to allow maximum flexibility or
692                  * restrict FSETOWN to the current process or process
693                  * group for maximum safety.
694                  */
695                 if (proc->p_session != curproc->p_session)
696                         return (EPERM);
697
698                 pgrp = NULL;
699         } else /* if (pgid < 0) */ {
700                 pgrp = pgfind(-pgid);
701                 if (pgrp == NULL)
702                         return (ESRCH);
703
704                 /*
705                  * Policy - Don't allow a process to FSETOWN a process
706                  * in another session.
707                  *
708                  * Remove this test to allow maximum flexibility or
709                  * restrict FSETOWN to the current process or process
710                  * group for maximum safety.
711                  */
712                 if (pgrp->pg_session != curproc->p_session)
713                         return (EPERM);
714
715                 proc = NULL;
716         }
717         funsetown(*sigiop);
718         sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
719         if (pgid > 0) {
720                 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
721                 sigio->sio_proc = proc;
722         } else {
723                 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
724                 sigio->sio_pgrp = pgrp;
725         }
726         sigio->sio_pgid = pgid;
727         sigio->sio_ucred = crhold(curproc->p_ucred);
728         /* It would be convenient if p_ruid was in ucred. */
729         sigio->sio_ruid = curproc->p_ucred->cr_ruid;
730         sigio->sio_myref = sigiop;
731         crit_enter();
732         *sigiop = sigio;
733         crit_exit();
734         return (0);
735 }
736
737 /*
738  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
739  */
740 pid_t
741 fgetown(struct sigio *sigio)
742 {
743         return (sigio != NULL ? sigio->sio_pgid : 0);
744 }
745
746 /*
747  * Close many file descriptors.
748  *
749  * MPSAFE
750  */
751 int
752 closefrom(struct closefrom_args *uap)
753 {
754         return(kern_closefrom(uap->fd));
755 }
756
757 /*
758  * Close all file descriptors greater then or equal to fd
759  *
760  * MPSAFE
761  */
762 int
763 kern_closefrom(int fd)
764 {
765         struct thread *td = curthread;
766         struct proc *p = td->td_proc;
767         struct filedesc *fdp;
768
769         KKASSERT(p);
770         fdp = p->p_fd;
771
772         if (fd < 0)
773                 return (EINVAL);
774
775         /*
776          * NOTE: This function will skip unassociated descriptors and
777          * reserved descriptors that have not yet been assigned.  
778          * fd_lastfile can change as a side effect of kern_close().
779          */
780         spin_lock_wr(&fdp->fd_spin);
781         while (fd <= fdp->fd_lastfile) {
782                 if (fdp->fd_files[fd].fp != NULL) {
783                         spin_unlock_wr(&fdp->fd_spin);
784                         /* ok if this races another close */
785                         if (kern_close(fd) == EINTR)
786                                 return (EINTR);
787                         spin_lock_wr(&fdp->fd_spin);
788                 }
789                 ++fd;
790         }
791         spin_unlock_wr(&fdp->fd_spin);
792         return (0);
793 }
794
795 /*
796  * Close a file descriptor.
797  *
798  * MPSAFE
799  */
800 int
801 close(struct close_args *uap)
802 {
803         return(kern_close(uap->fd));
804 }
805
806 /*
807  * MPALMOSTSAFE - acquires mplock around knote_fdclose() calls
808  */
809 int
810 kern_close(int fd)
811 {
812         struct thread *td = curthread;
813         struct proc *p = td->td_proc;
814         struct filedesc *fdp;
815         struct file *fp;
816         int error;
817         int holdleaders;
818
819         KKASSERT(p);
820         fdp = p->p_fd;
821
822         spin_lock_wr(&fdp->fd_spin);
823         if ((fp = funsetfd_locked(fdp, fd)) == NULL) {
824                 spin_unlock_wr(&fdp->fd_spin);
825                 return (EBADF);
826         }
827         holdleaders = 0;
828         if (p->p_fdtol != NULL) {
829                 /*
830                  * Ask fdfree() to sleep to ensure that all relevant
831                  * process leaders can be traversed in closef().
832                  */
833                 fdp->fd_holdleaderscount++;
834                 holdleaders = 1;
835         }
836
837         /*
838          * we now hold the fp reference that used to be owned by the descriptor
839          * array.
840          */
841         spin_unlock_wr(&fdp->fd_spin);
842         if (fd < fdp->fd_knlistsize) {
843                 get_mplock();
844                 knote_fdclose(p, fd);
845                 rel_mplock();
846         }
847         error = closef(fp, td);
848         if (holdleaders) {
849                 spin_lock_wr(&fdp->fd_spin);
850                 fdp->fd_holdleaderscount--;
851                 if (fdp->fd_holdleaderscount == 0 &&
852                     fdp->fd_holdleaderswakeup != 0) {
853                         fdp->fd_holdleaderswakeup = 0;
854                         spin_unlock_wr(&fdp->fd_spin);
855                         wakeup(&fdp->fd_holdleaderscount);
856                 } else {
857                         spin_unlock_wr(&fdp->fd_spin);
858                 }
859         }
860         return (error);
861 }
862
863 /*
864  * shutdown_args(int fd, int how)
865  */
866 int
867 kern_shutdown(int fd, int how)
868 {
869         struct thread *td = curthread;
870         struct proc *p = td->td_proc;
871         struct file *fp;
872         int error;
873
874         KKASSERT(p);
875
876         if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
877                 return (EBADF);
878         error = fo_shutdown(fp, how);
879         fdrop(fp);
880
881         return (error);
882 }
883
884 int
885 shutdown(struct shutdown_args *uap)
886 {
887         int error;
888
889         error = kern_shutdown(uap->s, uap->how);
890
891         return (error);
892 }
893
894 int
895 kern_fstat(int fd, struct stat *ub)
896 {
897         struct thread *td = curthread;
898         struct proc *p = td->td_proc;
899         struct file *fp;
900         int error;
901
902         KKASSERT(p);
903
904         if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
905                 return (EBADF);
906         error = fo_stat(fp, ub, p->p_ucred);
907         fdrop(fp);
908
909         return (error);
910 }
911
912 /*
913  * Return status information about a file descriptor.
914  */
915 int
916 fstat(struct fstat_args *uap)
917 {
918         struct stat st;
919         int error;
920
921         error = kern_fstat(uap->fd, &st);
922
923         if (error == 0)
924                 error = copyout(&st, uap->sb, sizeof(st));
925         return (error);
926 }
927
928 /*
929  * Return pathconf information about a file descriptor.
930  */
931 /* ARGSUSED */
932 int
933 fpathconf(struct fpathconf_args *uap)
934 {
935         struct thread *td = curthread;
936         struct proc *p = td->td_proc;
937         struct file *fp;
938         struct vnode *vp;
939         int error = 0;
940
941         KKASSERT(p);
942
943         if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
944                 return (EBADF);
945
946         switch (fp->f_type) {
947         case DTYPE_PIPE:
948         case DTYPE_SOCKET:
949                 if (uap->name != _PC_PIPE_BUF) {
950                         error = EINVAL;
951                 } else {
952                         uap->sysmsg_result = PIPE_BUF;
953                         error = 0;
954                 }
955                 break;
956         case DTYPE_FIFO:
957         case DTYPE_VNODE:
958                 vp = (struct vnode *)fp->f_data;
959                 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
960                 break;
961         default:
962                 error = EOPNOTSUPP;
963                 break;
964         }
965         fdrop(fp);
966         return(error);
967 }
968
969 static int fdexpand;
970 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
971
972 /*
973  * Grow the file table so it can hold through descriptor (want).
974  *
975  * The fdp's spinlock must be held exclusively on entry and may be held
976  * exclusively on return.  The spinlock may be cycled by the routine.
977  *
978  * MPSAFE
979  */
980 static void
981 fdgrow_locked(struct filedesc *fdp, int want)
982 {
983         struct fdnode *newfiles;
984         struct fdnode *oldfiles;
985         int nf, extra;
986
987         nf = fdp->fd_nfiles;
988         do {
989                 /* nf has to be of the form 2^n - 1 */
990                 nf = 2 * nf + 1;
991         } while (nf <= want);
992
993         spin_unlock_wr(&fdp->fd_spin);
994         newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
995         spin_lock_wr(&fdp->fd_spin);
996
997         /*
998          * We could have raced another extend while we were not holding
999          * the spinlock.
1000          */
1001         if (fdp->fd_nfiles >= nf) {
1002                 spin_unlock_wr(&fdp->fd_spin);
1003                 free(newfiles, M_FILEDESC);
1004                 spin_lock_wr(&fdp->fd_spin);
1005                 return;
1006         }
1007         /*
1008          * Copy the existing ofile and ofileflags arrays
1009          * and zero the new portion of each array.
1010          */
1011         extra = nf - fdp->fd_nfiles;
1012         bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
1013         bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
1014
1015         oldfiles = fdp->fd_files;
1016         fdp->fd_files = newfiles;
1017         fdp->fd_nfiles = nf;
1018
1019         if (oldfiles != fdp->fd_builtin_files) {
1020                 spin_unlock_wr(&fdp->fd_spin);
1021                 free(oldfiles, M_FILEDESC);
1022                 spin_lock_wr(&fdp->fd_spin);
1023         }
1024         fdexpand++;
1025 }
1026
1027 /*
1028  * Number of nodes in right subtree, including the root.
1029  */
1030 static __inline int
1031 right_subtree_size(int n)
1032 {
1033         return (n ^ (n | (n + 1)));
1034 }
1035
1036 /*
1037  * Bigger ancestor.
1038  */
1039 static __inline int
1040 right_ancestor(int n)
1041 {
1042         return (n | (n + 1));
1043 }
1044
1045 /*
1046  * Smaller ancestor.
1047  */
1048 static __inline int
1049 left_ancestor(int n)
1050 {
1051         return ((n & (n + 1)) - 1);
1052 }
1053
1054 /*
1055  * Traverse the in-place binary tree buttom-up adjusting the allocation
1056  * count so scans can determine where free descriptors are located.
1057  *
1058  * MPSAFE - caller must be holding an exclusive spinlock on fdp
1059  */
1060 static
1061 void
1062 fdreserve_locked(struct filedesc *fdp, int fd, int incr)
1063 {
1064         while (fd >= 0) {
1065                 fdp->fd_files[fd].allocated += incr;
1066                 KKASSERT(fdp->fd_files[fd].allocated >= 0);
1067                 fd = left_ancestor(fd);
1068         }
1069 }
1070
1071 /*
1072  * Reserve a file descriptor for the process.  If no error occurs, the
1073  * caller MUST at some point call fsetfd() or assign a file pointer
1074  * or dispose of the reservation.
1075  *
1076  * MPSAFE
1077  */
1078 int
1079 fdalloc(struct proc *p, int want, int *result)
1080 {
1081         struct filedesc *fdp = p->p_fd;
1082         int fd, rsize, rsum, node, lim;
1083
1084         spin_lock_rd(&p->p_limit->p_spin);
1085         lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1086         spin_unlock_rd(&p->p_limit->p_spin);
1087         if (want >= lim)
1088                 return (EMFILE);
1089         spin_lock_wr(&fdp->fd_spin);
1090         if (want >= fdp->fd_nfiles)
1091                 fdgrow_locked(fdp, want);
1092
1093         /*
1094          * Search for a free descriptor starting at the higher
1095          * of want or fd_freefile.  If that fails, consider
1096          * expanding the ofile array.
1097          *
1098          * NOTE! the 'allocated' field is a cumulative recursive allocation
1099          * count.  If we happen to see a value of 0 then we can shortcut
1100          * our search.  Otherwise we run through through the tree going
1101          * down branches we know have free descriptor(s) until we hit a
1102          * leaf node.  The leaf node will be free but will not necessarily
1103          * have an allocated field of 0.
1104          */
1105 retry:
1106         /* move up the tree looking for a subtree with a free node */
1107         for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
1108              fd = right_ancestor(fd)) {
1109                 if (fdp->fd_files[fd].allocated == 0)
1110                         goto found;
1111
1112                 rsize = right_subtree_size(fd);
1113                 if (fdp->fd_files[fd].allocated == rsize)
1114                         continue;       /* right subtree full */
1115
1116                 /*
1117                  * Free fd is in the right subtree of the tree rooted at fd.
1118                  * Call that subtree R.  Look for the smallest (leftmost)
1119                  * subtree of R with an unallocated fd: continue moving
1120                  * down the left branch until encountering a full left
1121                  * subtree, then move to the right.
1122                  */
1123                 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
1124                         node = fd + rsize;
1125                         rsum += fdp->fd_files[node].allocated;
1126                         if (fdp->fd_files[fd].allocated == rsum + rsize) {
1127                                 fd = node;      /* move to the right */
1128                                 if (fdp->fd_files[node].allocated == 0)
1129                                         goto found;
1130                                 rsum = 0;
1131                         }
1132                 }
1133                 goto found;
1134         }
1135
1136         /*
1137          * No space in current array.  Expand?
1138          */
1139         if (fdp->fd_nfiles >= lim) {
1140                 spin_unlock_wr(&fdp->fd_spin);
1141                 return (EMFILE);
1142         }
1143         fdgrow_locked(fdp, want);
1144         goto retry;
1145
1146 found:
1147         KKASSERT(fd < fdp->fd_nfiles);
1148         if (fd > fdp->fd_lastfile)
1149                 fdp->fd_lastfile = fd;
1150         if (want <= fdp->fd_freefile)
1151                 fdp->fd_freefile = fd;
1152         *result = fd;
1153         KKASSERT(fdp->fd_files[fd].fp == NULL);
1154         KKASSERT(fdp->fd_files[fd].reserved == 0);
1155         fdp->fd_files[fd].fileflags = 0;
1156         fdp->fd_files[fd].reserved = 1;
1157         fdreserve_locked(fdp, fd, 1);
1158         spin_unlock_wr(&fdp->fd_spin);
1159         return (0);
1160 }
1161
1162 /*
1163  * Check to see whether n user file descriptors
1164  * are available to the process p.
1165  *
1166  * MPSAFE
1167  */
1168 int
1169 fdavail(struct proc *p, int n)
1170 {
1171         struct filedesc *fdp = p->p_fd;
1172         struct fdnode *fdnode;
1173         int i, lim, last;
1174
1175         spin_lock_rd(&p->p_limit->p_spin);
1176         lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1177         spin_unlock_rd(&p->p_limit->p_spin);
1178
1179         spin_lock_rd(&fdp->fd_spin);
1180         if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0) {
1181                 spin_unlock_rd(&fdp->fd_spin);
1182                 return (1);
1183         }
1184         last = min(fdp->fd_nfiles, lim);
1185         fdnode = &fdp->fd_files[fdp->fd_freefile];
1186         for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1187                 if (fdnode->fp == NULL && --n <= 0) {
1188                         spin_unlock_rd(&fdp->fd_spin);
1189                         return (1);
1190                 }
1191         }
1192         spin_unlock_rd(&fdp->fd_spin);
1193         return (0);
1194 }
1195
1196 /*
1197  * falloc:
1198  *      Create a new open file structure and reserve a file decriptor
1199  *      for the process that refers to it.
1200  *
1201  *      Root creds are checked using p, or assumed if p is NULL.  If
1202  *      resultfd is non-NULL then p must also be non-NULL.  No file
1203  *      descriptor is reserved if resultfd is NULL.
1204  *
1205  *      A file pointer with a refcount of 1 is returned.  Note that the
1206  *      file pointer is NOT associated with the descriptor.  If falloc
1207  *      returns success, fsetfd() MUST be called to either associate the
1208  *      file pointer or clear the reservation.
1209  *
1210  * MPSAFE
1211  */
1212 int
1213 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1214 {
1215         static struct timeval lastfail;
1216         static int curfail;
1217         struct file *fp;
1218         int error;
1219
1220         fp = NULL;
1221
1222         /*
1223          * Handle filetable full issues and root overfill.
1224          */
1225         if (nfiles >= maxfiles - maxfilesrootres &&
1226             ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1227                 if (ppsratecheck(&lastfail, &curfail, 1)) {
1228                         printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1229                                 (p ? p->p_ucred->cr_ruid : -1));
1230                 }
1231                 error = ENFILE;
1232                 goto done;
1233         }
1234
1235         /*
1236          * Allocate a new file descriptor.
1237          */
1238         fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1239         spin_init(&fp->f_spin);
1240         fp->f_count = 1;
1241         fp->f_ops = &badfileops;
1242         fp->f_seqcount = 1;
1243         if (p)
1244                 fp->f_cred = crhold(p->p_ucred);
1245         else
1246                 fp->f_cred = crhold(proc0.p_ucred);
1247         spin_lock_wr(&filehead_spin);
1248         nfiles++;
1249         LIST_INSERT_HEAD(&filehead, fp, f_list);
1250         spin_unlock_wr(&filehead_spin);
1251         if (resultfd) {
1252                 if ((error = fdalloc(p, 0, resultfd)) != 0) {
1253                         fdrop(fp);
1254                         fp = NULL;
1255                 }
1256         } else {
1257                 error = 0;
1258         }
1259 done:
1260         *resultfp = fp;
1261         return (error);
1262 }
1263
1264 /*
1265  * MPSAFE
1266  */
1267 static
1268 int
1269 checkfpclosed(struct filedesc *fdp, int fd, struct file *fp)
1270 {
1271         int error;
1272
1273         spin_lock_rd(&fdp->fd_spin);
1274         if ((unsigned) fd >= fdp->fd_nfiles || fp != fdp->fd_files[fd].fp)
1275                 error = EBADF;
1276         else
1277                 error = 0;
1278         spin_unlock_rd(&fdp->fd_spin);
1279         return (error);
1280 }
1281
1282 /*
1283  * Associate a file pointer with a previously reserved file descriptor.
1284  * This function always succeeds.
1285  *
1286  * If fp is NULL, the file descriptor is returned to the pool.
1287  */
1288
1289 /*
1290  * MPSAFE (exclusive spinlock must be held on call)
1291  */
1292 static void
1293 fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd)
1294 {
1295         KKASSERT((unsigned)fd < fdp->fd_nfiles);
1296         KKASSERT(fdp->fd_files[fd].reserved != 0);
1297         if (fp) {
1298                 fhold(fp);
1299                 fdp->fd_files[fd].fp = fp;
1300                 fdp->fd_files[fd].reserved = 0;
1301                 if (fp->f_type == DTYPE_KQUEUE) {
1302                         if (fdp->fd_knlistsize < 0)
1303                                 fdp->fd_knlistsize = 0;
1304                 }
1305         } else {
1306                 fdp->fd_files[fd].reserved = 0;
1307                 fdreserve_locked(fdp, fd, -1);
1308                 fdfixup_locked(fdp, fd);
1309         }
1310 }
1311
1312 /*
1313  * MPSAFE
1314  */
1315 void
1316 fsetfd(struct proc *p, struct file *fp, int fd)
1317 {
1318         struct filedesc *fdp = p->p_fd;
1319
1320         spin_lock_wr(&fdp->fd_spin);
1321         fsetfd_locked(fdp, fp, fd);
1322         spin_unlock_wr(&fdp->fd_spin);
1323 }
1324
1325 /*
1326  * MPSAFE (exclusive spinlock must be held on call)
1327  */
1328 static 
1329 struct file *
1330 funsetfd_locked(struct filedesc *fdp, int fd)
1331 {
1332         struct file *fp;
1333
1334         if ((unsigned)fd >= fdp->fd_nfiles)
1335                 return (NULL);
1336         if ((fp = fdp->fd_files[fd].fp) == NULL)
1337                 return (NULL);
1338         fdp->fd_files[fd].fp = NULL;
1339         fdp->fd_files[fd].fileflags = 0;
1340
1341         fdreserve_locked(fdp, fd, -1);
1342         fdfixup_locked(fdp, fd);
1343         return(fp);
1344 }
1345
1346 /*
1347  * MPSAFE
1348  */
1349 int
1350 fgetfdflags(struct filedesc *fdp, int fd, int *flagsp)
1351 {
1352         int error;
1353
1354         spin_lock_rd(&fdp->fd_spin);
1355         if (((u_int)fd) >= fdp->fd_nfiles) {
1356                 error = EBADF;
1357         } else if (fdp->fd_files[fd].fp == NULL) {
1358                 error = EBADF;
1359         } else {
1360                 *flagsp = fdp->fd_files[fd].fileflags;
1361                 error = 0;
1362         }
1363         spin_unlock_rd(&fdp->fd_spin);
1364         return (error);
1365 }
1366
1367 /*
1368  * MPSAFE
1369  */
1370 int
1371 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
1372 {
1373         int error;
1374
1375         spin_lock_wr(&fdp->fd_spin);
1376         if (((u_int)fd) >= fdp->fd_nfiles) {
1377                 error = EBADF;
1378         } else if (fdp->fd_files[fd].fp == NULL) {
1379                 error = EBADF;
1380         } else {
1381                 fdp->fd_files[fd].fileflags |= add_flags;
1382                 error = 0;
1383         }
1384         spin_unlock_wr(&fdp->fd_spin);
1385         return (error);
1386 }
1387
1388 /*
1389  * MPSAFE
1390  */
1391 int
1392 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
1393 {
1394         int error;
1395
1396         spin_lock_wr(&fdp->fd_spin);
1397         if (((u_int)fd) >= fdp->fd_nfiles) {
1398                 error = EBADF;
1399         } else if (fdp->fd_files[fd].fp == NULL) {
1400                 error = EBADF;
1401         } else {
1402                 fdp->fd_files[fd].fileflags &= ~rem_flags;
1403                 error = 0;
1404         }
1405         spin_unlock_wr(&fdp->fd_spin);
1406         return (error);
1407 }
1408
1409 void
1410 fsetcred(struct file *fp, struct ucred *cr)
1411 {
1412         crhold(cr);
1413         crfree(fp->f_cred);
1414         fp->f_cred = cr;
1415 }
1416
1417 /*
1418  * Free a file descriptor.
1419  */
1420 static
1421 void
1422 ffree(struct file *fp)
1423 {
1424         KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1425         spin_lock_wr(&filehead_spin);
1426         LIST_REMOVE(fp, f_list);
1427         nfiles--;
1428         spin_unlock_wr(&filehead_spin);
1429         crfree(fp->f_cred);
1430         if (fp->f_ncp) {
1431             cache_drop(fp->f_ncp);
1432             fp->f_ncp = NULL;
1433         }
1434         free(fp, M_FILE);
1435 }
1436
1437 /*
1438  * called from init_main, initialize filedesc0 for proc0.
1439  */
1440 void
1441 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
1442 {
1443         p0->p_fd = fdp0;
1444         p0->p_fdtol = NULL;
1445         fdp0->fd_refcnt = 1;
1446         fdp0->fd_cmask = cmask;
1447         fdp0->fd_files = fdp0->fd_builtin_files;
1448         fdp0->fd_nfiles = NDFILE;
1449         fdp0->fd_lastfile = -1;
1450         spin_init(&fdp0->fd_spin);
1451 }
1452
1453 /*
1454  * Build a new filedesc structure.
1455  *
1456  * NOT MPSAFE (vref)
1457  */
1458 struct filedesc *
1459 fdinit(struct proc *p)
1460 {
1461         struct filedesc *newfdp;
1462         struct filedesc *fdp = p->p_fd;
1463
1464         newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1465         spin_lock_rd(&fdp->fd_spin);
1466         if (fdp->fd_cdir) {
1467                 newfdp->fd_cdir = fdp->fd_cdir;
1468                 vref(newfdp->fd_cdir);
1469                 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1470         }
1471
1472         /*
1473          * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1474          * proc0, but should unconditionally exist in other processes.
1475          */
1476         if (fdp->fd_rdir) {
1477                 newfdp->fd_rdir = fdp->fd_rdir;
1478                 vref(newfdp->fd_rdir);
1479                 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1480         }
1481         if (fdp->fd_jdir) {
1482                 newfdp->fd_jdir = fdp->fd_jdir;
1483                 vref(newfdp->fd_jdir);
1484                 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1485         }
1486         spin_unlock_rd(&fdp->fd_spin);
1487
1488         /* Create the file descriptor table. */
1489         newfdp->fd_refcnt = 1;
1490         newfdp->fd_cmask = cmask;
1491         newfdp->fd_files = newfdp->fd_builtin_files;
1492         newfdp->fd_nfiles = NDFILE;
1493         newfdp->fd_knlistsize = -1;
1494         newfdp->fd_lastfile = -1;
1495         spin_init(&newfdp->fd_spin);
1496
1497         return (newfdp);
1498 }
1499
1500 /*
1501  * Share a filedesc structure.
1502  *
1503  * MPSAFE
1504  */
1505 struct filedesc *
1506 fdshare(struct proc *p)
1507 {
1508         struct filedesc *fdp;
1509
1510         fdp = p->p_fd;
1511         spin_lock_wr(&fdp->fd_spin);
1512         fdp->fd_refcnt++;
1513         spin_unlock_wr(&fdp->fd_spin);
1514         return (fdp);
1515 }
1516
1517 /*
1518  * Copy a filedesc structure.
1519  *
1520  * MPSAFE
1521  */
1522 struct filedesc *
1523 fdcopy(struct proc *p)
1524 {
1525         struct filedesc *fdp = p->p_fd;
1526         struct filedesc *newfdp;
1527         struct fdnode *fdnode;
1528         int i;
1529         int ni;
1530
1531         /*
1532          * Certain daemons might not have file descriptors. 
1533          */
1534         if (fdp == NULL)
1535                 return (NULL);
1536
1537         /*
1538          * Allocate the new filedesc and fd_files[] array.  This can race
1539          * with operations by other threads on the fdp so we have to be
1540          * careful.
1541          */
1542         newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK | M_ZERO);
1543 again:
1544         spin_lock_rd(&fdp->fd_spin);
1545         if (fdp->fd_lastfile < NDFILE) {
1546                 newfdp->fd_files = newfdp->fd_builtin_files;
1547                 i = NDFILE;
1548         } else {
1549                 /*
1550                  * We have to allocate (N^2-1) entries for our in-place
1551                  * binary tree.  Allow the table to shrink.
1552                  */
1553                 i = fdp->fd_nfiles;
1554                 ni = (i - 1) / 2;
1555                 while (ni > fdp->fd_lastfile && ni > NDFILE) {
1556                         i = ni;
1557                         ni = (i - 1) / 2;
1558                 }
1559                 spin_unlock_rd(&fdp->fd_spin);
1560                 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1561                                           M_FILEDESC, M_WAITOK | M_ZERO);
1562
1563                 /*
1564                  * Check for race, retry
1565                  */
1566                 spin_lock_rd(&fdp->fd_spin);
1567                 if (i <= fdp->fd_lastfile) {
1568                         spin_unlock_rd(&fdp->fd_spin);
1569                         free(newfdp->fd_files, M_FILEDESC);
1570                         goto again;
1571                 }
1572         }
1573
1574         /*
1575          * Dup the remaining fields. vref() and cache_hold() can be
1576          * safely called while holding the read spinlock on fdp.
1577          *
1578          * The read spinlock on fdp is still being held.
1579          *
1580          * NOTE: vref and cache_hold calls for the case where the vnode
1581          * or cache entry already has at least one ref may be called
1582          * while holding spin locks.
1583          */
1584         if ((newfdp->fd_cdir = fdp->fd_cdir) != NULL) {
1585                 vref(newfdp->fd_cdir);
1586                 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1587         }
1588         /*
1589          * We must check for fd_rdir here, at least for now because
1590          * the init process is created before we have access to the
1591          * rootvode to take a reference to it.
1592          */
1593         if ((newfdp->fd_rdir = fdp->fd_rdir) != NULL) {
1594                 vref(newfdp->fd_rdir);
1595                 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1596         }
1597         if ((newfdp->fd_jdir = fdp->fd_jdir) != NULL) {
1598                 vref(newfdp->fd_jdir);
1599                 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1600         }
1601         newfdp->fd_refcnt = 1;
1602         newfdp->fd_nfiles = i;
1603         newfdp->fd_lastfile = fdp->fd_lastfile;
1604         newfdp->fd_freefile = fdp->fd_freefile;
1605         newfdp->fd_cmask = fdp->fd_cmask;
1606         newfdp->fd_knlist = NULL;
1607         newfdp->fd_knlistsize = -1;
1608         newfdp->fd_knhash = NULL;
1609         newfdp->fd_knhashmask = 0;
1610         spin_init(&newfdp->fd_spin);
1611
1612         /*
1613          * Copy the descriptor table through (i).  This also copies the
1614          * allocation state.   Then go through and ref the file pointers
1615          * and clean up any KQ descriptors.
1616          *
1617          * kq descriptors cannot be copied.  Since we haven't ref'd the
1618          * copied files yet we can ignore the return value from funsetfd().
1619          *
1620          * The read spinlock on fdp is still being held.
1621          */
1622         bcopy(fdp->fd_files, newfdp->fd_files, i * sizeof(struct fdnode));
1623         for (i = 0 ; i < newfdp->fd_nfiles; ++i) {
1624                 fdnode = &newfdp->fd_files[i];
1625                 if (fdnode->reserved) {
1626                         fdreserve_locked(newfdp, i, -1);
1627                         fdnode->reserved = 0;
1628                         fdfixup_locked(newfdp, i);
1629                 } else if (fdnode->fp) {
1630                         if (fdnode->fp->f_type == DTYPE_KQUEUE) {
1631                                 (void)funsetfd_locked(newfdp, i);
1632                         } else {
1633                                 fhold(fdnode->fp);
1634                         }
1635                 }
1636         }
1637         spin_unlock_rd(&fdp->fd_spin);
1638         return (newfdp);
1639 }
1640
1641 /*
1642  * Release a filedesc structure.
1643  *
1644  * NOT MPSAFE (MPSAFE for refs > 1, but the final cleanup code is not MPSAFE)
1645  */
1646 void
1647 fdfree(struct proc *p)
1648 {
1649         struct thread *td = p->p_thread;
1650         struct filedesc *fdp = p->p_fd;
1651         struct fdnode *fdnode;
1652         int i;
1653         struct filedesc_to_leader *fdtol;
1654         struct file *fp;
1655         struct vnode *vp;
1656         struct flock lf;
1657
1658         /* Certain daemons might not have file descriptors. */
1659         if (fdp == NULL)
1660                 return;
1661
1662         /*
1663          * Severe messing around to follow
1664          */
1665         spin_lock_wr(&fdp->fd_spin);
1666
1667         /* Check for special need to clear POSIX style locks */
1668         fdtol = p->p_fdtol;
1669         if (fdtol != NULL) {
1670                 KASSERT(fdtol->fdl_refcount > 0,
1671                         ("filedesc_to_refcount botch: fdl_refcount=%d",
1672                          fdtol->fdl_refcount));
1673                 if (fdtol->fdl_refcount == 1 &&
1674                     (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1675                         for (i = 0; i <= fdp->fd_lastfile; ++i) {
1676                                 fdnode = &fdp->fd_files[i];
1677                                 if (fdnode->fp == NULL ||
1678                                     fdnode->fp->f_type != DTYPE_VNODE) {
1679                                         continue;
1680                                 }
1681                                 fp = fdnode->fp;
1682                                 fhold(fp);
1683                                 spin_unlock_wr(&fdp->fd_spin);
1684
1685                                 lf.l_whence = SEEK_SET;
1686                                 lf.l_start = 0;
1687                                 lf.l_len = 0;
1688                                 lf.l_type = F_UNLCK;
1689                                 vp = (struct vnode *)fp->f_data;
1690                                 (void) VOP_ADVLOCK(vp,
1691                                                    (caddr_t)p->p_leader,
1692                                                    F_UNLCK,
1693                                                    &lf,
1694                                                    F_POSIX);
1695                                 fdrop(fp);
1696                                 spin_lock_wr(&fdp->fd_spin);
1697                         }
1698                 }
1699         retry:
1700                 if (fdtol->fdl_refcount == 1) {
1701                         if (fdp->fd_holdleaderscount > 0 &&
1702                             (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1703                                 /*
1704                                  * close() or do_dup() has cleared a reference
1705                                  * in a shared file descriptor table.
1706                                  */
1707                                 fdp->fd_holdleaderswakeup = 1;
1708                                 spin_unlock_wr(&fdp->fd_spin);
1709                                 tsleep(&fdp->fd_holdleaderscount,
1710                                        0, "fdlhold", 0);
1711                                 spin_lock_wr(&fdp->fd_spin);
1712                                 goto retry;
1713                         }
1714                         if (fdtol->fdl_holdcount > 0) {
1715                                 /* 
1716                                  * Ensure that fdtol->fdl_leader
1717                                  * remains valid in closef().
1718                                  */
1719                                 fdtol->fdl_wakeup = 1;
1720                                 spin_unlock_wr(&fdp->fd_spin);
1721                                 tsleep(fdtol, 0, "fdlhold", 0);
1722                                 spin_lock_wr(&fdp->fd_spin);
1723                                 goto retry;
1724                         }
1725                 }
1726                 fdtol->fdl_refcount--;
1727                 if (fdtol->fdl_refcount == 0 &&
1728                     fdtol->fdl_holdcount == 0) {
1729                         fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1730                         fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1731                 } else {
1732                         fdtol = NULL;
1733                 }
1734                 p->p_fdtol = NULL;
1735                 if (fdtol != NULL) {
1736                         spin_unlock_wr(&fdp->fd_spin);
1737                         free(fdtol, M_FILEDESC_TO_LEADER);
1738                         spin_lock_wr(&fdp->fd_spin);
1739                 }
1740         }
1741         if (--fdp->fd_refcnt > 0) {
1742                 spin_unlock_wr(&fdp->fd_spin);
1743                 return;
1744         }
1745         spin_unlock_wr(&fdp->fd_spin);
1746
1747         /*
1748          * we are the last reference to the structure, we can
1749          * safely assume it will not change out from under us.
1750          */
1751         for (i = 0; i <= fdp->fd_lastfile; ++i) {
1752                 if (fdp->fd_files[i].fp)
1753                         closef(fdp->fd_files[i].fp, td);
1754         }
1755         if (fdp->fd_files != fdp->fd_builtin_files)
1756                 free(fdp->fd_files, M_FILEDESC);
1757         if (fdp->fd_cdir) {
1758                 cache_drop(fdp->fd_ncdir);
1759                 vrele(fdp->fd_cdir);
1760         }
1761         if (fdp->fd_rdir) {
1762                 cache_drop(fdp->fd_nrdir);
1763                 vrele(fdp->fd_rdir);
1764         }
1765         if (fdp->fd_jdir) {
1766                 cache_drop(fdp->fd_njdir);
1767                 vrele(fdp->fd_jdir);
1768         }
1769         if (fdp->fd_knlist)
1770                 free(fdp->fd_knlist, M_KQUEUE);
1771         if (fdp->fd_knhash)
1772                 free(fdp->fd_knhash, M_KQUEUE);
1773         free(fdp, M_FILEDESC);
1774 }
1775
1776 /*
1777  * Retrieve and reference the file pointer associated with a descriptor.
1778  *
1779  * MPSAFE
1780  */
1781 struct file *
1782 holdfp(struct filedesc *fdp, int fd, int flag)
1783 {
1784         struct file* fp;
1785
1786         spin_lock_rd(&fdp->fd_spin);
1787         if (((u_int)fd) >= fdp->fd_nfiles) {
1788                 fp = NULL;
1789                 goto done;
1790         }
1791         if ((fp = fdp->fd_files[fd].fp) == NULL)
1792                 goto done;
1793         if ((fp->f_flag & flag) == 0 && flag != -1) {
1794                 fp = NULL;
1795                 goto done;
1796         }
1797         fhold(fp);
1798 done:
1799         spin_unlock_rd(&fdp->fd_spin);
1800         return (fp);
1801 }
1802
1803 /*
1804  * holdsock() - load the struct file pointer associated
1805  * with a socket into *fpp.  If an error occurs, non-zero
1806  * will be returned and *fpp will be set to NULL.
1807  *
1808  * MPSAFE
1809  */
1810 int
1811 holdsock(struct filedesc *fdp, int fd, struct file **fpp)
1812 {
1813         struct file *fp;
1814         int error;
1815
1816         spin_lock_rd(&fdp->fd_spin);
1817         if ((unsigned)fd >= fdp->fd_nfiles) {
1818                 error = EBADF;
1819                 fp = NULL;
1820                 goto done;
1821         }
1822         if ((fp = fdp->fd_files[fd].fp) == NULL) {
1823                 error = EBADF;
1824                 goto done;
1825         }
1826         if (fp->f_type != DTYPE_SOCKET) {
1827                 error = ENOTSOCK;
1828                 goto done;
1829         }
1830         fhold(fp);
1831         error = 0;
1832 done:
1833         spin_unlock_rd(&fdp->fd_spin);
1834         *fpp = fp;
1835         return (error);
1836 }
1837
1838 /*
1839  * Convert a user file descriptor to a held file pointer.
1840  *
1841  * MPSAFE
1842  */
1843 int
1844 holdvnode(struct filedesc *fdp, int fd, struct file **fpp)
1845 {
1846         struct file *fp;
1847         int error;
1848
1849         spin_lock_rd(&fdp->fd_spin);
1850         if ((unsigned)fd >= fdp->fd_nfiles) {
1851                 error = EBADF;
1852                 fp = NULL;
1853                 goto done;
1854         }
1855         if ((fp = fdp->fd_files[fd].fp) == NULL) {
1856                 error = EBADF;
1857                 goto done;
1858         }
1859         if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
1860                 error = EINVAL;
1861                 goto done;
1862         }
1863         fhold(fp);
1864         error = 0;
1865 done:
1866         spin_unlock_rd(&fdp->fd_spin);
1867         *fpp = fp;
1868         return (error);
1869 }
1870
1871 /*
1872  * For setugid programs, we don't want to people to use that setugidness
1873  * to generate error messages which write to a file which otherwise would
1874  * otherwise be off-limits to the process.
1875  *
1876  * This is a gross hack to plug the hole.  A better solution would involve
1877  * a special vop or other form of generalized access control mechanism.  We
1878  * go ahead and just reject all procfs file systems accesses as dangerous.
1879  *
1880  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1881  * sufficient.  We also don't for check setugidness since we know we are.
1882  */
1883 static int
1884 is_unsafe(struct file *fp)
1885 {
1886         if (fp->f_type == DTYPE_VNODE && 
1887             ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1888                 return (1);
1889         return (0);
1890 }
1891
1892 /*
1893  * Make this setguid thing safe, if at all possible.
1894  *
1895  * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
1896  */
1897 void
1898 setugidsafety(struct proc *p)
1899 {
1900         struct thread *td = p->p_thread;
1901         struct filedesc *fdp = p->p_fd;
1902         int i;
1903
1904         /* Certain daemons might not have file descriptors. */
1905         if (fdp == NULL)
1906                 return;
1907
1908         /*
1909          * note: fdp->fd_files may be reallocated out from under us while
1910          * we are blocked in a close.  Be careful!
1911          */
1912         for (i = 0; i <= fdp->fd_lastfile; i++) {
1913                 if (i > 2)
1914                         break;
1915                 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1916                         struct file *fp;
1917
1918                         if (i < fdp->fd_knlistsize)
1919                                 knote_fdclose(p, i);
1920                         /*
1921                          * NULL-out descriptor prior to close to avoid
1922                          * a race while close blocks.
1923                          */
1924                         if ((fp = funsetfd_locked(fdp, i)) != NULL)
1925                                 closef(fp, td);
1926                 }
1927         }
1928 }
1929
1930 /*
1931  * Close any files on exec?
1932  *
1933  * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
1934  */
1935 void
1936 fdcloseexec(struct proc *p)
1937 {
1938         struct thread *td = p->p_thread;
1939         struct filedesc *fdp = p->p_fd;
1940         int i;
1941
1942         /* Certain daemons might not have file descriptors. */
1943         if (fdp == NULL)
1944                 return;
1945
1946         /*
1947          * We cannot cache fd_files since operations may block and rip
1948          * them out from under us.
1949          */
1950         for (i = 0; i <= fdp->fd_lastfile; i++) {
1951                 if (fdp->fd_files[i].fp != NULL &&
1952                     (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1953                         struct file *fp;
1954
1955                         if (i < fdp->fd_knlistsize)
1956                                 knote_fdclose(p, i);
1957                         /*
1958                          * NULL-out descriptor prior to close to avoid
1959                          * a race while close blocks.
1960                          */
1961                         if ((fp = funsetfd_locked(fdp, i)) != NULL)
1962                                 closef(fp, td);
1963                 }
1964         }
1965 }
1966
1967 /*
1968  * It is unsafe for set[ug]id processes to be started with file
1969  * descriptors 0..2 closed, as these descriptors are given implicit
1970  * significance in the Standard C library.  fdcheckstd() will create a
1971  * descriptor referencing /dev/null for each of stdin, stdout, and
1972  * stderr that is not already open.
1973  *
1974  * NOT MPSAFE - calls falloc, vn_open, etc
1975  */
1976 int
1977 fdcheckstd(struct proc *p)
1978 {
1979         struct nlookupdata nd;
1980         struct filedesc *fdp;
1981         struct file *fp;
1982         register_t retval;
1983         int i, error, flags, devnull;
1984
1985        fdp = p->p_fd;
1986        if (fdp == NULL)
1987                return (0);
1988        devnull = -1;
1989        error = 0;
1990        for (i = 0; i < 3; i++) {
1991                 if (fdp->fd_files[i].fp != NULL)
1992                         continue;
1993                 if (devnull < 0) {
1994                         if ((error = falloc(p, &fp, &devnull)) != 0)
1995                                 break;
1996
1997                         error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1998                                                 NLC_FOLLOW|NLC_LOCKVP);
1999                         flags = FREAD | FWRITE;
2000                         if (error == 0)
2001                                 error = vn_open(&nd, fp, flags, 0);
2002                         if (error == 0)
2003                                 fsetfd(p, fp, devnull);
2004                         else
2005                                 fsetfd(p, NULL, devnull);
2006                         fdrop(fp);
2007                         nlookup_done(&nd);
2008                         if (error)
2009                                 break;
2010                         KKASSERT(i == devnull);
2011                 } else {
2012                         error = kern_dup(DUP_FIXED, devnull, i, &retval);
2013                         if (error != 0)
2014                                 break;
2015                 }
2016        }
2017        return (error);
2018 }
2019
2020 /*
2021  * Internal form of close.
2022  * Decrement reference count on file structure.
2023  * Note: td and/or p may be NULL when closing a file
2024  * that was being passed in a message.
2025  *
2026  * MPALMOSTSAFE - acquires mplock for VOP operations
2027  */
2028 int
2029 closef(struct file *fp, struct thread *td)
2030 {
2031         struct vnode *vp;
2032         struct flock lf;
2033         struct filedesc_to_leader *fdtol;
2034         struct proc *p;
2035
2036         if (fp == NULL)
2037                 return (0);
2038         if (td == NULL) {
2039                 td = curthread;
2040                 p = NULL;               /* allow no proc association */
2041         } else {
2042                 p = td->td_proc;        /* can also be NULL */
2043         }
2044         get_mplock();
2045         /*
2046          * POSIX record locking dictates that any close releases ALL
2047          * locks owned by this process.  This is handled by setting
2048          * a flag in the unlock to free ONLY locks obeying POSIX
2049          * semantics, and not to free BSD-style file locks.
2050          * If the descriptor was in a message, POSIX-style locks
2051          * aren't passed with the descriptor.
2052          */
2053         if (p != NULL && 
2054             fp->f_type == DTYPE_VNODE) {
2055                 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
2056                         lf.l_whence = SEEK_SET;
2057                         lf.l_start = 0;
2058                         lf.l_len = 0;
2059                         lf.l_type = F_UNLCK;
2060                         vp = (struct vnode *)fp->f_data;
2061                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
2062                                            &lf, F_POSIX);
2063                 }
2064                 fdtol = p->p_fdtol;
2065                 if (fdtol != NULL) {
2066                         /*
2067                          * Handle special case where file descriptor table
2068                          * is shared between multiple process leaders.
2069                          */
2070                         for (fdtol = fdtol->fdl_next;
2071                              fdtol != p->p_fdtol;
2072                              fdtol = fdtol->fdl_next) {
2073                                 if ((fdtol->fdl_leader->p_flag &
2074                                      P_ADVLOCK) == 0)
2075                                         continue;
2076                                 fdtol->fdl_holdcount++;
2077                                 lf.l_whence = SEEK_SET;
2078                                 lf.l_start = 0;
2079                                 lf.l_len = 0;
2080                                 lf.l_type = F_UNLCK;
2081                                 vp = (struct vnode *)fp->f_data;
2082                                 (void) VOP_ADVLOCK(vp,
2083                                                    (caddr_t)fdtol->fdl_leader,
2084                                                    F_UNLCK, &lf, F_POSIX);
2085                                 fdtol->fdl_holdcount--;
2086                                 if (fdtol->fdl_holdcount == 0 &&
2087                                     fdtol->fdl_wakeup != 0) {
2088                                         fdtol->fdl_wakeup = 0;
2089                                         wakeup(fdtol);
2090                                 }
2091                         }
2092                 }
2093         }
2094         rel_mplock();
2095         return (fdrop(fp));
2096 }
2097
2098 /*
2099  * MPSAFE
2100  *
2101  * fhold() can only be called if f_count is already at least 1 (i.e. the
2102  * caller of fhold() already has a reference to the file pointer in some
2103  * manner or other). 
2104  *
2105  * This is a rare case where callers are allowed to hold spinlocks, so
2106  * we can't ourselves.  Since we are not obtaining the fp spinlock,
2107  * we have to use an atomic lock to interlock against fdrop().
2108  */
2109 void
2110 fhold(struct file *fp)
2111 {
2112         atomic_add_int(&fp->f_count, 1);
2113 }
2114
2115 /*
2116  * A spinlock is required to handle 1->0 transitions on f_count.  We have
2117  * to use atomic_sub_int so as not to race the atomic_add_int in fhold().
2118  *
2119  * MPALMOSTSAFE - acquires mplock for final close sequence
2120  */
2121 int
2122 fdrop(struct file *fp)
2123 {
2124         struct flock lf;
2125         struct vnode *vp;
2126         int error;
2127
2128         spin_lock_wr(&fp->f_spin);
2129         atomic_subtract_int(&fp->f_count, 1);
2130         if (fp->f_count > 0) {
2131                 spin_unlock_wr(&fp->f_spin);
2132                 return (0);
2133         }
2134         spin_unlock_wr(&fp->f_spin);
2135
2136         get_mplock();
2137
2138         /*
2139          * The last reference has gone away, we own the fp structure free
2140          * and clear.
2141          */
2142         if (fp->f_count < 0)
2143                 panic("fdrop: count < 0");
2144         if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
2145                 lf.l_whence = SEEK_SET;
2146                 lf.l_start = 0;
2147                 lf.l_len = 0;
2148                 lf.l_type = F_UNLCK;
2149                 vp = (struct vnode *)fp->f_data;
2150                 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
2151         }
2152         if (fp->f_ops != &badfileops)
2153                 error = fo_close(fp);
2154         else
2155                 error = 0;
2156         ffree(fp);
2157         rel_mplock();
2158         return (error);
2159 }
2160
2161 /*
2162  * Apply an advisory lock on a file descriptor.
2163  *
2164  * Just attempt to get a record lock of the requested type on
2165  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2166  */
2167 int
2168 flock(struct flock_args *uap)
2169 {
2170         struct proc *p = curproc;
2171         struct file *fp;
2172         struct vnode *vp;
2173         struct flock lf;
2174         int error;
2175
2176         if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
2177                 return (EBADF);
2178         if (fp->f_type != DTYPE_VNODE) {
2179                 error = EOPNOTSUPP;
2180                 goto done;
2181         }
2182         vp = (struct vnode *)fp->f_data;
2183         lf.l_whence = SEEK_SET;
2184         lf.l_start = 0;
2185         lf.l_len = 0;
2186         if (uap->how & LOCK_UN) {
2187                 lf.l_type = F_UNLCK;
2188                 fp->f_flag &= ~FHASLOCK;
2189                 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
2190                 goto done;
2191         }
2192         if (uap->how & LOCK_EX)
2193                 lf.l_type = F_WRLCK;
2194         else if (uap->how & LOCK_SH)
2195                 lf.l_type = F_RDLCK;
2196         else {
2197                 error = EBADF;
2198                 goto done;
2199         }
2200         fp->f_flag |= FHASLOCK;
2201         if (uap->how & LOCK_NB)
2202                 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 0);
2203         else
2204                 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_WAIT);
2205 done:
2206         fdrop(fp);
2207         return (error);
2208 }
2209
2210 /*
2211  * File Descriptor pseudo-device driver (/dev/fd/).
2212  *
2213  * Opening minor device N dup()s the file (if any) connected to file
2214  * descriptor N belonging to the calling process.  Note that this driver
2215  * consists of only the ``open()'' routine, because all subsequent
2216  * references to this file will be direct to the other driver.
2217  */
2218 /* ARGSUSED */
2219 static int
2220 fdopen(dev_t dev, int mode, int type, struct thread *td)
2221 {
2222         KKASSERT(td->td_lwp != NULL);
2223
2224         /*
2225          * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
2226          * the file descriptor being sought for duplication. The error
2227          * return ensures that the vnode for this device will be released
2228          * by vn_open. Open will detect this special error and take the
2229          * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2230          * will simply report the error.
2231          */
2232         td->td_lwp->lwp_dupfd = minor(dev);
2233         return (ENODEV);
2234 }
2235
2236 /*
2237  * The caller has reserved the file descriptor dfd for us.  On success we
2238  * must fsetfd() it.  On failure the caller will clean it up.
2239  *
2240  * NOT MPSAFE - isn't getting spinlocks, possibly other things
2241  */
2242 int
2243 dupfdopen(struct proc *p, int dfd, int sfd, int mode, int error)
2244 {
2245         struct filedesc *fdp = p->p_fd;
2246         struct file *wfp;
2247         struct file *xfp;
2248
2249         if ((wfp = holdfp(fdp, sfd, -1)) == NULL)
2250                 return (EBADF);
2251
2252         /*
2253          * There are two cases of interest here.
2254          *
2255          * For ENODEV simply dup sfd to file descriptor dfd and return.
2256          *
2257          * For ENXIO steal away the file structure from sfd and store it
2258          * dfd.  sfd is effectively closed by this operation.
2259          *
2260          * Any other error code is just returned.
2261          */
2262         switch (error) {
2263         case ENODEV:
2264                 /*
2265                  * Check that the mode the file is being opened for is a
2266                  * subset of the mode of the existing descriptor.
2267                  */
2268                 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
2269                         return (EACCES);
2270                 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2271                 fsetfd(p, wfp, dfd);
2272                 error = 0;
2273                 break;
2274         case ENXIO:
2275                 /*
2276                  * Steal away the file pointer from dfd, and stuff it into indx.
2277                  */
2278                 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2279                 fsetfd(p, wfp, dfd);
2280                 if ((xfp = funsetfd_locked(fdp, sfd)) != NULL)
2281                         fdrop(xfp);
2282                 KKASSERT(xfp == wfp);   /* XXX MP RACE */
2283                 error = 0;
2284                 break;
2285         default:
2286                 break;
2287         }
2288         fdrop(wfp);
2289         return (error);
2290 }
2291
2292 /*
2293  * NOT MPSAFE - I think these refer to a common file descriptor table
2294  * and we need to spinlock that to link fdtol in.
2295  */
2296 struct filedesc_to_leader *
2297 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2298                          struct proc *leader)
2299 {
2300         struct filedesc_to_leader *fdtol;
2301         
2302         fdtol = malloc(sizeof(struct filedesc_to_leader), 
2303                         M_FILEDESC_TO_LEADER, M_WAITOK);
2304         fdtol->fdl_refcount = 1;
2305         fdtol->fdl_holdcount = 0;
2306         fdtol->fdl_wakeup = 0;
2307         fdtol->fdl_leader = leader;
2308         if (old != NULL) {
2309                 fdtol->fdl_next = old->fdl_next;
2310                 fdtol->fdl_prev = old;
2311                 old->fdl_next = fdtol;
2312                 fdtol->fdl_next->fdl_prev = fdtol;
2313         } else {
2314                 fdtol->fdl_next = fdtol;
2315                 fdtol->fdl_prev = fdtol;
2316         }
2317         return fdtol;
2318 }
2319
2320 /*
2321  * Scan all file pointers in the system.  The callback is made with
2322  * both the master list spinlock held and the fp spinlock held,
2323  * both exclusively.
2324  *
2325  * MPSAFE
2326  *
2327  * WARNING: both the filehead spinlock and the file pointer spinlock are
2328  * held exclusively when the callback is made.  The file pointer is not
2329  * referenced.
2330  */
2331 void
2332 allfiles_scan_exclusive(int (*callback)(struct file *, void *), void *data)
2333 {
2334         struct file *fp;
2335         int res;
2336
2337         spin_lock_wr(&filehead_spin);
2338         LIST_FOREACH(fp, &filehead, f_list) {
2339                 spin_lock_wr(&fp->f_spin);
2340                 res = callback(fp, data);
2341                 spin_unlock_wr(&fp->f_spin);
2342                 if (res < 0)
2343                         break;
2344         }
2345         spin_unlock_wr(&filehead_spin);
2346 }
2347
2348 /*
2349  * Get file structures.
2350  *
2351  * NOT MPSAFE - process list scan, SYSCTL_OUT (probably not mpsafe)
2352  */
2353
2354 struct sysctl_kern_file_info {
2355         int count;
2356         int error;
2357         struct sysctl_req *req;
2358 };
2359
2360 static int sysctl_kern_file_callback(struct proc *p, void *data);
2361
2362 static int
2363 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2364 {
2365         struct sysctl_kern_file_info info;
2366
2367         /*
2368          * Note: because the number of file descriptors is calculated
2369          * in different ways for sizing vs returning the data,
2370          * there is information leakage from the first loop.  However,
2371          * it is of a similar order of magnitude to the leakage from
2372          * global system statistics such as kern.openfiles.
2373          *
2374          * When just doing a count, note that we cannot just count
2375          * the elements and add f_count via the filehead list because 
2376          * threaded processes share their descriptor table and f_count might
2377          * still be '1' in that case.
2378          *
2379          * Since the SYSCTL op can block, we must hold the process to
2380          * prevent it being ripped out from under us either in the 
2381          * file descriptor loop or in the greater LIST_FOREACH.  The
2382          * process may be in varying states of disrepair.  If the process
2383          * is in SZOMB we may have caught it just as it is being removed
2384          * from the allproc list, we must skip it in that case to maintain
2385          * an unbroken chain through the allproc list.
2386          */
2387         info.count = 0;
2388         info.error = 0;
2389         info.req = req;
2390         allproc_scan(sysctl_kern_file_callback, &info);
2391
2392         /*
2393          * When just calculating the size, overestimate a bit to try to
2394          * prevent system activity from causing the buffer-fill call 
2395          * to fail later on.
2396          */
2397         if (req->oldptr == NULL) {
2398                 info.count = (info.count + 16) + (info.count / 10);
2399                 info.error = SYSCTL_OUT(req, NULL,
2400                                         info.count * sizeof(struct kinfo_file));
2401         }
2402         return (info.error);
2403 }
2404
2405 static int
2406 sysctl_kern_file_callback(struct proc *p, void *data)
2407 {
2408         struct sysctl_kern_file_info *info = data;
2409         struct kinfo_file kf;
2410         struct filedesc *fdp;
2411         struct file *fp;
2412         uid_t uid;
2413         int n;
2414
2415         if (p->p_stat == SIDL || (p->p_flag & P_ZOMBIE))
2416                 return(0);
2417         if (!PRISON_CHECK(info->req->td->td_proc->p_ucred, p->p_ucred) != 0)
2418                 return(0);
2419         if ((fdp = p->p_fd) == NULL)
2420                 return(0);
2421         spin_lock_rd(&fdp->fd_spin);
2422         for (n = 0; n < fdp->fd_nfiles; ++n) {
2423                 if ((fp = fdp->fd_files[n].fp) == NULL)
2424                         continue;
2425                 if (info->req->oldptr == NULL) {
2426                         ++info->count;
2427                 } else {
2428                         uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
2429                         kcore_make_file(&kf, fp, p->p_pid, uid, n);
2430                         spin_unlock_rd(&fdp->fd_spin);
2431                         info->error = SYSCTL_OUT(info->req, &kf, sizeof(kf));
2432                         spin_lock_rd(&fdp->fd_spin);
2433                         if (info->error)
2434                                 break;
2435                 }
2436         }
2437         spin_unlock_rd(&fdp->fd_spin);
2438         if (info->error)
2439                 return(-1);
2440         return(0);
2441 }
2442
2443 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2444     0, 0, sysctl_kern_file, "S,file", "Entire file table");
2445
2446 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW, 
2447     &maxfilesperproc, 0, "Maximum files allowed open per process");
2448
2449 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW, 
2450     &maxfiles, 0, "Maximum number of files");
2451
2452 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW, 
2453     &maxfilesrootres, 0, "Descriptors reserved for root use");
2454
2455 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD, 
2456         &nfiles, 0, "System-wide number of open files");
2457
2458 static void
2459 fildesc_drvinit(void *unused)
2460 {
2461         int fd;
2462
2463         cdevsw_add(&fildesc_cdevsw, 0, 0);
2464         for (fd = 0; fd < NUMFDESC; fd++) {
2465                 make_dev(&fildesc_cdevsw, fd,
2466                     UID_BIN, GID_BIN, 0666, "fd/%d", fd);
2467         }
2468         make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
2469         make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
2470         make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
2471 }
2472
2473 /*
2474  * MPSAFE
2475  */
2476 struct fileops badfileops = {
2477         NULL,   /* port */
2478         NULL,   /* clone */
2479         badfo_readwrite,
2480         badfo_readwrite,
2481         badfo_ioctl,
2482         badfo_poll,
2483         badfo_kqfilter,
2484         badfo_stat,
2485         badfo_close,
2486         badfo_shutdown
2487 };
2488
2489 /*
2490  * MPSAFE
2491  */
2492 static int
2493 badfo_readwrite(
2494         struct file *fp,
2495         struct uio *uio,
2496         struct ucred *cred,
2497         int flags
2498 ) {
2499         return (EBADF);
2500 }
2501
2502 /*
2503  * MPSAFE
2504  */
2505 static int
2506 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct ucred *cred)
2507 {
2508         return (EBADF);
2509 }
2510
2511 /*
2512  * MPSAFE
2513  */
2514 static int
2515 badfo_poll(struct file *fp, int events, struct ucred *cred)
2516 {
2517         return (0);
2518 }
2519
2520 /*
2521  * MPSAFE
2522  */
2523 static int
2524 badfo_kqfilter(struct file *fp, struct knote *kn)
2525 {
2526         return (0);
2527 }
2528
2529 static int
2530 badfo_stat(struct file *fp, struct stat *sb, struct ucred *cred)
2531 {
2532         return (EBADF);
2533 }
2534
2535 /*
2536  * MPSAFE
2537  */
2538 static int
2539 badfo_close(struct file *fp)
2540 {
2541         return (EBADF);
2542 }
2543
2544 /*
2545  * MPSAFE
2546  */
2547 static int
2548 badfo_shutdown(struct file *fp, int how)
2549 {
2550         return (EBADF);
2551 }
2552
2553 /*
2554  * MPSAFE
2555  */
2556 int
2557 nofo_shutdown(struct file *fp, int how)
2558 {
2559         return (EOPNOTSUPP);
2560 }
2561
2562 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2563                                         fildesc_drvinit,NULL)