Greatly reduce the MP locking that occurs in closef(), and remove
[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.66 2006/05/27 01:57:41 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                 if (fd < fdp->fd_knlistsize)
845                         knote_fdclose(p, fd);
846                 rel_mplock();
847         }
848         error = closef(fp, td);
849         if (holdleaders) {
850                 spin_lock_wr(&fdp->fd_spin);
851                 fdp->fd_holdleaderscount--;
852                 if (fdp->fd_holdleaderscount == 0 &&
853                     fdp->fd_holdleaderswakeup != 0) {
854                         fdp->fd_holdleaderswakeup = 0;
855                         spin_unlock_wr(&fdp->fd_spin);
856                         wakeup(&fdp->fd_holdleaderscount);
857                 } else {
858                         spin_unlock_wr(&fdp->fd_spin);
859                 }
860         }
861         return (error);
862 }
863
864 /*
865  * shutdown_args(int fd, int how)
866  */
867 int
868 kern_shutdown(int fd, int how)
869 {
870         struct thread *td = curthread;
871         struct proc *p = td->td_proc;
872         struct file *fp;
873         int error;
874
875         KKASSERT(p);
876
877         if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
878                 return (EBADF);
879         error = fo_shutdown(fp, how);
880         fdrop(fp);
881
882         return (error);
883 }
884
885 int
886 shutdown(struct shutdown_args *uap)
887 {
888         int error;
889
890         error = kern_shutdown(uap->s, uap->how);
891
892         return (error);
893 }
894
895 int
896 kern_fstat(int fd, struct stat *ub)
897 {
898         struct thread *td = curthread;
899         struct proc *p = td->td_proc;
900         struct file *fp;
901         int error;
902
903         KKASSERT(p);
904
905         if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
906                 return (EBADF);
907         error = fo_stat(fp, ub, p->p_ucred);
908         fdrop(fp);
909
910         return (error);
911 }
912
913 /*
914  * Return status information about a file descriptor.
915  */
916 int
917 fstat(struct fstat_args *uap)
918 {
919         struct stat st;
920         int error;
921
922         error = kern_fstat(uap->fd, &st);
923
924         if (error == 0)
925                 error = copyout(&st, uap->sb, sizeof(st));
926         return (error);
927 }
928
929 /*
930  * Return pathconf information about a file descriptor.
931  */
932 /* ARGSUSED */
933 int
934 fpathconf(struct fpathconf_args *uap)
935 {
936         struct thread *td = curthread;
937         struct proc *p = td->td_proc;
938         struct file *fp;
939         struct vnode *vp;
940         int error = 0;
941
942         KKASSERT(p);
943
944         if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
945                 return (EBADF);
946
947         switch (fp->f_type) {
948         case DTYPE_PIPE:
949         case DTYPE_SOCKET:
950                 if (uap->name != _PC_PIPE_BUF) {
951                         error = EINVAL;
952                 } else {
953                         uap->sysmsg_result = PIPE_BUF;
954                         error = 0;
955                 }
956                 break;
957         case DTYPE_FIFO:
958         case DTYPE_VNODE:
959                 vp = (struct vnode *)fp->f_data;
960                 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
961                 break;
962         default:
963                 error = EOPNOTSUPP;
964                 break;
965         }
966         fdrop(fp);
967         return(error);
968 }
969
970 static int fdexpand;
971 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
972
973 /*
974  * Grow the file table so it can hold through descriptor (want).
975  *
976  * The fdp's spinlock must be held exclusively on entry and may be held
977  * exclusively on return.  The spinlock may be cycled by the routine.
978  *
979  * MPSAFE
980  */
981 static void
982 fdgrow_locked(struct filedesc *fdp, int want)
983 {
984         struct fdnode *newfiles;
985         struct fdnode *oldfiles;
986         int nf, extra;
987
988         nf = fdp->fd_nfiles;
989         do {
990                 /* nf has to be of the form 2^n - 1 */
991                 nf = 2 * nf + 1;
992         } while (nf <= want);
993
994         spin_unlock_wr(&fdp->fd_spin);
995         newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
996         spin_lock_wr(&fdp->fd_spin);
997
998         /*
999          * We could have raced another extend while we were not holding
1000          * the spinlock.
1001          */
1002         if (fdp->fd_nfiles >= nf) {
1003                 spin_unlock_wr(&fdp->fd_spin);
1004                 free(newfiles, M_FILEDESC);
1005                 spin_lock_wr(&fdp->fd_spin);
1006                 return;
1007         }
1008         /*
1009          * Copy the existing ofile and ofileflags arrays
1010          * and zero the new portion of each array.
1011          */
1012         extra = nf - fdp->fd_nfiles;
1013         bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
1014         bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
1015
1016         oldfiles = fdp->fd_files;
1017         fdp->fd_files = newfiles;
1018         fdp->fd_nfiles = nf;
1019
1020         if (oldfiles != fdp->fd_builtin_files) {
1021                 spin_unlock_wr(&fdp->fd_spin);
1022                 free(oldfiles, M_FILEDESC);
1023                 spin_lock_wr(&fdp->fd_spin);
1024         }
1025         fdexpand++;
1026 }
1027
1028 /*
1029  * Number of nodes in right subtree, including the root.
1030  */
1031 static __inline int
1032 right_subtree_size(int n)
1033 {
1034         return (n ^ (n | (n + 1)));
1035 }
1036
1037 /*
1038  * Bigger ancestor.
1039  */
1040 static __inline int
1041 right_ancestor(int n)
1042 {
1043         return (n | (n + 1));
1044 }
1045
1046 /*
1047  * Smaller ancestor.
1048  */
1049 static __inline int
1050 left_ancestor(int n)
1051 {
1052         return ((n & (n + 1)) - 1);
1053 }
1054
1055 /*
1056  * Traverse the in-place binary tree buttom-up adjusting the allocation
1057  * count so scans can determine where free descriptors are located.
1058  *
1059  * MPSAFE - caller must be holding an exclusive spinlock on fdp
1060  */
1061 static
1062 void
1063 fdreserve_locked(struct filedesc *fdp, int fd, int incr)
1064 {
1065         while (fd >= 0) {
1066                 fdp->fd_files[fd].allocated += incr;
1067                 KKASSERT(fdp->fd_files[fd].allocated >= 0);
1068                 fd = left_ancestor(fd);
1069         }
1070 }
1071
1072 /*
1073  * Reserve a file descriptor for the process.  If no error occurs, the
1074  * caller MUST at some point call fsetfd() or assign a file pointer
1075  * or dispose of the reservation.
1076  *
1077  * MPSAFE
1078  */
1079 int
1080 fdalloc(struct proc *p, int want, int *result)
1081 {
1082         struct filedesc *fdp = p->p_fd;
1083         int fd, rsize, rsum, node, lim;
1084
1085         spin_lock_rd(&p->p_limit->p_spin);
1086         lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1087         spin_unlock_rd(&p->p_limit->p_spin);
1088         if (want >= lim)
1089                 return (EMFILE);
1090         spin_lock_wr(&fdp->fd_spin);
1091         if (want >= fdp->fd_nfiles)
1092                 fdgrow_locked(fdp, want);
1093
1094         /*
1095          * Search for a free descriptor starting at the higher
1096          * of want or fd_freefile.  If that fails, consider
1097          * expanding the ofile array.
1098          *
1099          * NOTE! the 'allocated' field is a cumulative recursive allocation
1100          * count.  If we happen to see a value of 0 then we can shortcut
1101          * our search.  Otherwise we run through through the tree going
1102          * down branches we know have free descriptor(s) until we hit a
1103          * leaf node.  The leaf node will be free but will not necessarily
1104          * have an allocated field of 0.
1105          */
1106 retry:
1107         /* move up the tree looking for a subtree with a free node */
1108         for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
1109              fd = right_ancestor(fd)) {
1110                 if (fdp->fd_files[fd].allocated == 0)
1111                         goto found;
1112
1113                 rsize = right_subtree_size(fd);
1114                 if (fdp->fd_files[fd].allocated == rsize)
1115                         continue;       /* right subtree full */
1116
1117                 /*
1118                  * Free fd is in the right subtree of the tree rooted at fd.
1119                  * Call that subtree R.  Look for the smallest (leftmost)
1120                  * subtree of R with an unallocated fd: continue moving
1121                  * down the left branch until encountering a full left
1122                  * subtree, then move to the right.
1123                  */
1124                 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
1125                         node = fd + rsize;
1126                         rsum += fdp->fd_files[node].allocated;
1127                         if (fdp->fd_files[fd].allocated == rsum + rsize) {
1128                                 fd = node;      /* move to the right */
1129                                 if (fdp->fd_files[node].allocated == 0)
1130                                         goto found;
1131                                 rsum = 0;
1132                         }
1133                 }
1134                 goto found;
1135         }
1136
1137         /*
1138          * No space in current array.  Expand?
1139          */
1140         if (fdp->fd_nfiles >= lim) {
1141                 spin_unlock_wr(&fdp->fd_spin);
1142                 return (EMFILE);
1143         }
1144         fdgrow_locked(fdp, want);
1145         goto retry;
1146
1147 found:
1148         KKASSERT(fd < fdp->fd_nfiles);
1149         if (fd > fdp->fd_lastfile)
1150                 fdp->fd_lastfile = fd;
1151         if (want <= fdp->fd_freefile)
1152                 fdp->fd_freefile = fd;
1153         *result = fd;
1154         KKASSERT(fdp->fd_files[fd].fp == NULL);
1155         KKASSERT(fdp->fd_files[fd].reserved == 0);
1156         fdp->fd_files[fd].fileflags = 0;
1157         fdp->fd_files[fd].reserved = 1;
1158         fdreserve_locked(fdp, fd, 1);
1159         spin_unlock_wr(&fdp->fd_spin);
1160         return (0);
1161 }
1162
1163 /*
1164  * Check to see whether n user file descriptors
1165  * are available to the process p.
1166  *
1167  * MPSAFE
1168  */
1169 int
1170 fdavail(struct proc *p, int n)
1171 {
1172         struct filedesc *fdp = p->p_fd;
1173         struct fdnode *fdnode;
1174         int i, lim, last;
1175
1176         spin_lock_rd(&p->p_limit->p_spin);
1177         lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1178         spin_unlock_rd(&p->p_limit->p_spin);
1179
1180         spin_lock_rd(&fdp->fd_spin);
1181         if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0) {
1182                 spin_unlock_rd(&fdp->fd_spin);
1183                 return (1);
1184         }
1185         last = min(fdp->fd_nfiles, lim);
1186         fdnode = &fdp->fd_files[fdp->fd_freefile];
1187         for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1188                 if (fdnode->fp == NULL && --n <= 0) {
1189                         spin_unlock_rd(&fdp->fd_spin);
1190                         return (1);
1191                 }
1192         }
1193         spin_unlock_rd(&fdp->fd_spin);
1194         return (0);
1195 }
1196
1197 /*
1198  * falloc:
1199  *      Create a new open file structure and reserve a file decriptor
1200  *      for the process that refers to it.
1201  *
1202  *      Root creds are checked using p, or assumed if p is NULL.  If
1203  *      resultfd is non-NULL then p must also be non-NULL.  No file
1204  *      descriptor is reserved if resultfd is NULL.
1205  *
1206  *      A file pointer with a refcount of 1 is returned.  Note that the
1207  *      file pointer is NOT associated with the descriptor.  If falloc
1208  *      returns success, fsetfd() MUST be called to either associate the
1209  *      file pointer or clear the reservation.
1210  *
1211  * MPSAFE
1212  */
1213 int
1214 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1215 {
1216         static struct timeval lastfail;
1217         static int curfail;
1218         struct file *fp;
1219         int error;
1220
1221         fp = NULL;
1222
1223         /*
1224          * Handle filetable full issues and root overfill.
1225          */
1226         if (nfiles >= maxfiles - maxfilesrootres &&
1227             ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1228                 if (ppsratecheck(&lastfail, &curfail, 1)) {
1229                         printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1230                                 (p ? p->p_ucred->cr_ruid : -1));
1231                 }
1232                 error = ENFILE;
1233                 goto done;
1234         }
1235
1236         /*
1237          * Allocate a new file descriptor.
1238          */
1239         fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1240         spin_init(&fp->f_spin);
1241         fp->f_count = 1;
1242         fp->f_ops = &badfileops;
1243         fp->f_seqcount = 1;
1244         if (p)
1245                 fp->f_cred = crhold(p->p_ucred);
1246         else
1247                 fp->f_cred = crhold(proc0.p_ucred);
1248         spin_lock_wr(&filehead_spin);
1249         nfiles++;
1250         LIST_INSERT_HEAD(&filehead, fp, f_list);
1251         spin_unlock_wr(&filehead_spin);
1252         if (resultfd) {
1253                 if ((error = fdalloc(p, 0, resultfd)) != 0) {
1254                         fdrop(fp);
1255                         fp = NULL;
1256                 }
1257         } else {
1258                 error = 0;
1259         }
1260 done:
1261         *resultfp = fp;
1262         return (error);
1263 }
1264
1265 /*
1266  * MPSAFE
1267  */
1268 static
1269 int
1270 checkfpclosed(struct filedesc *fdp, int fd, struct file *fp)
1271 {
1272         int error;
1273
1274         spin_lock_rd(&fdp->fd_spin);
1275         if ((unsigned) fd >= fdp->fd_nfiles || fp != fdp->fd_files[fd].fp)
1276                 error = EBADF;
1277         else
1278                 error = 0;
1279         spin_unlock_rd(&fdp->fd_spin);
1280         return (error);
1281 }
1282
1283 /*
1284  * Associate a file pointer with a previously reserved file descriptor.
1285  * This function always succeeds.
1286  *
1287  * If fp is NULL, the file descriptor is returned to the pool.
1288  */
1289
1290 /*
1291  * MPSAFE (exclusive spinlock must be held on call)
1292  */
1293 static void
1294 fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd)
1295 {
1296         KKASSERT((unsigned)fd < fdp->fd_nfiles);
1297         KKASSERT(fdp->fd_files[fd].reserved != 0);
1298         if (fp) {
1299                 fhold(fp);
1300                 fdp->fd_files[fd].fp = fp;
1301                 fdp->fd_files[fd].reserved = 0;
1302                 if (fp->f_type == DTYPE_KQUEUE) {
1303                         if (fdp->fd_knlistsize < 0)
1304                                 fdp->fd_knlistsize = 0;
1305                 }
1306         } else {
1307                 fdp->fd_files[fd].reserved = 0;
1308                 fdreserve_locked(fdp, fd, -1);
1309                 fdfixup_locked(fdp, fd);
1310         }
1311 }
1312
1313 /*
1314  * MPSAFE
1315  */
1316 void
1317 fsetfd(struct proc *p, struct file *fp, int fd)
1318 {
1319         struct filedesc *fdp = p->p_fd;
1320
1321         spin_lock_wr(&fdp->fd_spin);
1322         fsetfd_locked(fdp, fp, fd);
1323         spin_unlock_wr(&fdp->fd_spin);
1324 }
1325
1326 /*
1327  * MPSAFE (exclusive spinlock must be held on call)
1328  */
1329 static 
1330 struct file *
1331 funsetfd_locked(struct filedesc *fdp, int fd)
1332 {
1333         struct file *fp;
1334
1335         if ((unsigned)fd >= fdp->fd_nfiles)
1336                 return (NULL);
1337         if ((fp = fdp->fd_files[fd].fp) == NULL)
1338                 return (NULL);
1339         fdp->fd_files[fd].fp = NULL;
1340         fdp->fd_files[fd].fileflags = 0;
1341
1342         fdreserve_locked(fdp, fd, -1);
1343         fdfixup_locked(fdp, fd);
1344         return(fp);
1345 }
1346
1347 /*
1348  * MPSAFE
1349  */
1350 int
1351 fgetfdflags(struct filedesc *fdp, int fd, int *flagsp)
1352 {
1353         int error;
1354
1355         spin_lock_rd(&fdp->fd_spin);
1356         if (((u_int)fd) >= fdp->fd_nfiles) {
1357                 error = EBADF;
1358         } else if (fdp->fd_files[fd].fp == NULL) {
1359                 error = EBADF;
1360         } else {
1361                 *flagsp = fdp->fd_files[fd].fileflags;
1362                 error = 0;
1363         }
1364         spin_unlock_rd(&fdp->fd_spin);
1365         return (error);
1366 }
1367
1368 /*
1369  * MPSAFE
1370  */
1371 int
1372 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
1373 {
1374         int error;
1375
1376         spin_lock_wr(&fdp->fd_spin);
1377         if (((u_int)fd) >= fdp->fd_nfiles) {
1378                 error = EBADF;
1379         } else if (fdp->fd_files[fd].fp == NULL) {
1380                 error = EBADF;
1381         } else {
1382                 fdp->fd_files[fd].fileflags |= add_flags;
1383                 error = 0;
1384         }
1385         spin_unlock_wr(&fdp->fd_spin);
1386         return (error);
1387 }
1388
1389 /*
1390  * MPSAFE
1391  */
1392 int
1393 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
1394 {
1395         int error;
1396
1397         spin_lock_wr(&fdp->fd_spin);
1398         if (((u_int)fd) >= fdp->fd_nfiles) {
1399                 error = EBADF;
1400         } else if (fdp->fd_files[fd].fp == NULL) {
1401                 error = EBADF;
1402         } else {
1403                 fdp->fd_files[fd].fileflags &= ~rem_flags;
1404                 error = 0;
1405         }
1406         spin_unlock_wr(&fdp->fd_spin);
1407         return (error);
1408 }
1409
1410 void
1411 fsetcred(struct file *fp, struct ucred *cr)
1412 {
1413         crhold(cr);
1414         crfree(fp->f_cred);
1415         fp->f_cred = cr;
1416 }
1417
1418 /*
1419  * Free a file descriptor.
1420  */
1421 static
1422 void
1423 ffree(struct file *fp)
1424 {
1425         KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1426         spin_lock_wr(&filehead_spin);
1427         LIST_REMOVE(fp, f_list);
1428         nfiles--;
1429         spin_unlock_wr(&filehead_spin);
1430         crfree(fp->f_cred);
1431         if (fp->f_ncp) {
1432             cache_drop(fp->f_ncp);
1433             fp->f_ncp = NULL;
1434         }
1435         free(fp, M_FILE);
1436 }
1437
1438 /*
1439  * called from init_main, initialize filedesc0 for proc0.
1440  */
1441 void
1442 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
1443 {
1444         p0->p_fd = fdp0;
1445         p0->p_fdtol = NULL;
1446         fdp0->fd_refcnt = 1;
1447         fdp0->fd_cmask = cmask;
1448         fdp0->fd_files = fdp0->fd_builtin_files;
1449         fdp0->fd_nfiles = NDFILE;
1450         fdp0->fd_lastfile = -1;
1451         spin_init(&fdp0->fd_spin);
1452 }
1453
1454 /*
1455  * Build a new filedesc structure.
1456  *
1457  * NOT MPSAFE (vref)
1458  */
1459 struct filedesc *
1460 fdinit(struct proc *p)
1461 {
1462         struct filedesc *newfdp;
1463         struct filedesc *fdp = p->p_fd;
1464
1465         newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1466         spin_lock_rd(&fdp->fd_spin);
1467         if (fdp->fd_cdir) {
1468                 newfdp->fd_cdir = fdp->fd_cdir;
1469                 vref(newfdp->fd_cdir);
1470                 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1471         }
1472
1473         /*
1474          * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1475          * proc0, but should unconditionally exist in other processes.
1476          */
1477         if (fdp->fd_rdir) {
1478                 newfdp->fd_rdir = fdp->fd_rdir;
1479                 vref(newfdp->fd_rdir);
1480                 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1481         }
1482         if (fdp->fd_jdir) {
1483                 newfdp->fd_jdir = fdp->fd_jdir;
1484                 vref(newfdp->fd_jdir);
1485                 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1486         }
1487         spin_unlock_rd(&fdp->fd_spin);
1488
1489         /* Create the file descriptor table. */
1490         newfdp->fd_refcnt = 1;
1491         newfdp->fd_cmask = cmask;
1492         newfdp->fd_files = newfdp->fd_builtin_files;
1493         newfdp->fd_nfiles = NDFILE;
1494         newfdp->fd_knlistsize = -1;
1495         newfdp->fd_lastfile = -1;
1496         spin_init(&newfdp->fd_spin);
1497
1498         return (newfdp);
1499 }
1500
1501 /*
1502  * Share a filedesc structure.
1503  *
1504  * MPSAFE
1505  */
1506 struct filedesc *
1507 fdshare(struct proc *p)
1508 {
1509         struct filedesc *fdp;
1510
1511         fdp = p->p_fd;
1512         spin_lock_wr(&fdp->fd_spin);
1513         fdp->fd_refcnt++;
1514         spin_unlock_wr(&fdp->fd_spin);
1515         return (fdp);
1516 }
1517
1518 /*
1519  * Copy a filedesc structure.
1520  *
1521  * MPSAFE
1522  */
1523 struct filedesc *
1524 fdcopy(struct proc *p)
1525 {
1526         struct filedesc *fdp = p->p_fd;
1527         struct filedesc *newfdp;
1528         struct fdnode *fdnode;
1529         int i;
1530         int ni;
1531
1532         /*
1533          * Certain daemons might not have file descriptors. 
1534          */
1535         if (fdp == NULL)
1536                 return (NULL);
1537
1538         /*
1539          * Allocate the new filedesc and fd_files[] array.  This can race
1540          * with operations by other threads on the fdp so we have to be
1541          * careful.
1542          */
1543         newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK | M_ZERO);
1544 again:
1545         spin_lock_rd(&fdp->fd_spin);
1546         if (fdp->fd_lastfile < NDFILE) {
1547                 newfdp->fd_files = newfdp->fd_builtin_files;
1548                 i = NDFILE;
1549         } else {
1550                 /*
1551                  * We have to allocate (N^2-1) entries for our in-place
1552                  * binary tree.  Allow the table to shrink.
1553                  */
1554                 i = fdp->fd_nfiles;
1555                 ni = (i - 1) / 2;
1556                 while (ni > fdp->fd_lastfile && ni > NDFILE) {
1557                         i = ni;
1558                         ni = (i - 1) / 2;
1559                 }
1560                 spin_unlock_rd(&fdp->fd_spin);
1561                 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1562                                           M_FILEDESC, M_WAITOK | M_ZERO);
1563
1564                 /*
1565                  * Check for race, retry
1566                  */
1567                 spin_lock_rd(&fdp->fd_spin);
1568                 if (i <= fdp->fd_lastfile) {
1569                         spin_unlock_rd(&fdp->fd_spin);
1570                         free(newfdp->fd_files, M_FILEDESC);
1571                         goto again;
1572                 }
1573         }
1574
1575         /*
1576          * Dup the remaining fields. vref() and cache_hold() can be
1577          * safely called while holding the read spinlock on fdp.
1578          *
1579          * The read spinlock on fdp is still being held.
1580          *
1581          * NOTE: vref and cache_hold calls for the case where the vnode
1582          * or cache entry already has at least one ref may be called
1583          * while holding spin locks.
1584          */
1585         if ((newfdp->fd_cdir = fdp->fd_cdir) != NULL) {
1586                 vref(newfdp->fd_cdir);
1587                 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1588         }
1589         /*
1590          * We must check for fd_rdir here, at least for now because
1591          * the init process is created before we have access to the
1592          * rootvode to take a reference to it.
1593          */
1594         if ((newfdp->fd_rdir = fdp->fd_rdir) != NULL) {
1595                 vref(newfdp->fd_rdir);
1596                 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1597         }
1598         if ((newfdp->fd_jdir = fdp->fd_jdir) != NULL) {
1599                 vref(newfdp->fd_jdir);
1600                 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1601         }
1602         newfdp->fd_refcnt = 1;
1603         newfdp->fd_nfiles = i;
1604         newfdp->fd_lastfile = fdp->fd_lastfile;
1605         newfdp->fd_freefile = fdp->fd_freefile;
1606         newfdp->fd_cmask = fdp->fd_cmask;
1607         newfdp->fd_knlist = NULL;
1608         newfdp->fd_knlistsize = -1;
1609         newfdp->fd_knhash = NULL;
1610         newfdp->fd_knhashmask = 0;
1611         spin_init(&newfdp->fd_spin);
1612
1613         /*
1614          * Copy the descriptor table through (i).  This also copies the
1615          * allocation state.   Then go through and ref the file pointers
1616          * and clean up any KQ descriptors.
1617          *
1618          * kq descriptors cannot be copied.  Since we haven't ref'd the
1619          * copied files yet we can ignore the return value from funsetfd().
1620          *
1621          * The read spinlock on fdp is still being held.
1622          */
1623         bcopy(fdp->fd_files, newfdp->fd_files, i * sizeof(struct fdnode));
1624         for (i = 0 ; i < newfdp->fd_nfiles; ++i) {
1625                 fdnode = &newfdp->fd_files[i];
1626                 if (fdnode->reserved) {
1627                         fdreserve_locked(newfdp, i, -1);
1628                         fdnode->reserved = 0;
1629                         fdfixup_locked(newfdp, i);
1630                 } else if (fdnode->fp) {
1631                         if (fdnode->fp->f_type == DTYPE_KQUEUE) {
1632                                 (void)funsetfd_locked(newfdp, i);
1633                         } else {
1634                                 fhold(fdnode->fp);
1635                         }
1636                 }
1637         }
1638         spin_unlock_rd(&fdp->fd_spin);
1639         return (newfdp);
1640 }
1641
1642 /*
1643  * Release a filedesc structure.
1644  *
1645  * NOT MPSAFE (MPSAFE for refs > 1, but the final cleanup code is not MPSAFE)
1646  */
1647 void
1648 fdfree(struct proc *p)
1649 {
1650         struct thread *td = p->p_thread;
1651         struct filedesc *fdp = p->p_fd;
1652         struct fdnode *fdnode;
1653         int i;
1654         struct filedesc_to_leader *fdtol;
1655         struct file *fp;
1656         struct vnode *vp;
1657         struct flock lf;
1658
1659         /* Certain daemons might not have file descriptors. */
1660         if (fdp == NULL)
1661                 return;
1662
1663         /*
1664          * Severe messing around to follow
1665          */
1666         spin_lock_wr(&fdp->fd_spin);
1667
1668         /* Check for special need to clear POSIX style locks */
1669         fdtol = p->p_fdtol;
1670         if (fdtol != NULL) {
1671                 KASSERT(fdtol->fdl_refcount > 0,
1672                         ("filedesc_to_refcount botch: fdl_refcount=%d",
1673                          fdtol->fdl_refcount));
1674                 if (fdtol->fdl_refcount == 1 &&
1675                     (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1676                         for (i = 0; i <= fdp->fd_lastfile; ++i) {
1677                                 fdnode = &fdp->fd_files[i];
1678                                 if (fdnode->fp == NULL ||
1679                                     fdnode->fp->f_type != DTYPE_VNODE) {
1680                                         continue;
1681                                 }
1682                                 fp = fdnode->fp;
1683                                 fhold(fp);
1684                                 spin_unlock_wr(&fdp->fd_spin);
1685
1686                                 lf.l_whence = SEEK_SET;
1687                                 lf.l_start = 0;
1688                                 lf.l_len = 0;
1689                                 lf.l_type = F_UNLCK;
1690                                 vp = (struct vnode *)fp->f_data;
1691                                 (void) VOP_ADVLOCK(vp,
1692                                                    (caddr_t)p->p_leader,
1693                                                    F_UNLCK,
1694                                                    &lf,
1695                                                    F_POSIX);
1696                                 fdrop(fp);
1697                                 spin_lock_wr(&fdp->fd_spin);
1698                         }
1699                 }
1700         retry:
1701                 if (fdtol->fdl_refcount == 1) {
1702                         if (fdp->fd_holdleaderscount > 0 &&
1703                             (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1704                                 /*
1705                                  * close() or do_dup() has cleared a reference
1706                                  * in a shared file descriptor table.
1707                                  */
1708                                 fdp->fd_holdleaderswakeup = 1;
1709                                 msleep(&fdp->fd_holdleaderscount, 
1710                                        &fdp->fd_spin, 0, "fdlhold", 0);
1711                                 goto retry;
1712                         }
1713                         if (fdtol->fdl_holdcount > 0) {
1714                                 /* 
1715                                  * Ensure that fdtol->fdl_leader
1716                                  * remains valid in closef().
1717                                  */
1718                                 fdtol->fdl_wakeup = 1;
1719                                 msleep(fdtol, &fdp->fd_spin, 0, "fdlhold", 0);
1720                                 goto retry;
1721                         }
1722                 }
1723                 fdtol->fdl_refcount--;
1724                 if (fdtol->fdl_refcount == 0 &&
1725                     fdtol->fdl_holdcount == 0) {
1726                         fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1727                         fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1728                 } else {
1729                         fdtol = NULL;
1730                 }
1731                 p->p_fdtol = NULL;
1732                 if (fdtol != NULL) {
1733                         spin_unlock_wr(&fdp->fd_spin);
1734                         free(fdtol, M_FILEDESC_TO_LEADER);
1735                         spin_lock_wr(&fdp->fd_spin);
1736                 }
1737         }
1738         if (--fdp->fd_refcnt > 0) {
1739                 spin_unlock_wr(&fdp->fd_spin);
1740                 return;
1741         }
1742         spin_unlock_wr(&fdp->fd_spin);
1743
1744         /*
1745          * we are the last reference to the structure, we can
1746          * safely assume it will not change out from under us.
1747          */
1748         for (i = 0; i <= fdp->fd_lastfile; ++i) {
1749                 if (fdp->fd_files[i].fp)
1750                         closef(fdp->fd_files[i].fp, td);
1751         }
1752         if (fdp->fd_files != fdp->fd_builtin_files)
1753                 free(fdp->fd_files, M_FILEDESC);
1754         if (fdp->fd_cdir) {
1755                 cache_drop(fdp->fd_ncdir);
1756                 vrele(fdp->fd_cdir);
1757         }
1758         if (fdp->fd_rdir) {
1759                 cache_drop(fdp->fd_nrdir);
1760                 vrele(fdp->fd_rdir);
1761         }
1762         if (fdp->fd_jdir) {
1763                 cache_drop(fdp->fd_njdir);
1764                 vrele(fdp->fd_jdir);
1765         }
1766         if (fdp->fd_knlist)
1767                 free(fdp->fd_knlist, M_KQUEUE);
1768         if (fdp->fd_knhash)
1769                 free(fdp->fd_knhash, M_KQUEUE);
1770         free(fdp, M_FILEDESC);
1771 }
1772
1773 /*
1774  * Retrieve and reference the file pointer associated with a descriptor.
1775  *
1776  * MPSAFE
1777  */
1778 struct file *
1779 holdfp(struct filedesc *fdp, int fd, int flag)
1780 {
1781         struct file* fp;
1782
1783         spin_lock_rd(&fdp->fd_spin);
1784         if (((u_int)fd) >= fdp->fd_nfiles) {
1785                 fp = NULL;
1786                 goto done;
1787         }
1788         if ((fp = fdp->fd_files[fd].fp) == NULL)
1789                 goto done;
1790         if ((fp->f_flag & flag) == 0 && flag != -1) {
1791                 fp = NULL;
1792                 goto done;
1793         }
1794         fhold(fp);
1795 done:
1796         spin_unlock_rd(&fdp->fd_spin);
1797         return (fp);
1798 }
1799
1800 /*
1801  * holdsock() - load the struct file pointer associated
1802  * with a socket into *fpp.  If an error occurs, non-zero
1803  * will be returned and *fpp will be set to NULL.
1804  *
1805  * MPSAFE
1806  */
1807 int
1808 holdsock(struct filedesc *fdp, int fd, struct file **fpp)
1809 {
1810         struct file *fp;
1811         int error;
1812
1813         spin_lock_rd(&fdp->fd_spin);
1814         if ((unsigned)fd >= fdp->fd_nfiles) {
1815                 error = EBADF;
1816                 fp = NULL;
1817                 goto done;
1818         }
1819         if ((fp = fdp->fd_files[fd].fp) == NULL) {
1820                 error = EBADF;
1821                 goto done;
1822         }
1823         if (fp->f_type != DTYPE_SOCKET) {
1824                 error = ENOTSOCK;
1825                 goto done;
1826         }
1827         fhold(fp);
1828         error = 0;
1829 done:
1830         spin_unlock_rd(&fdp->fd_spin);
1831         *fpp = fp;
1832         return (error);
1833 }
1834
1835 /*
1836  * Convert a user file descriptor to a held file pointer.
1837  *
1838  * MPSAFE
1839  */
1840 int
1841 holdvnode(struct filedesc *fdp, int fd, struct file **fpp)
1842 {
1843         struct file *fp;
1844         int error;
1845
1846         spin_lock_rd(&fdp->fd_spin);
1847         if ((unsigned)fd >= fdp->fd_nfiles) {
1848                 error = EBADF;
1849                 fp = NULL;
1850                 goto done;
1851         }
1852         if ((fp = fdp->fd_files[fd].fp) == NULL) {
1853                 error = EBADF;
1854                 goto done;
1855         }
1856         if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
1857                 error = EINVAL;
1858                 goto done;
1859         }
1860         fhold(fp);
1861         error = 0;
1862 done:
1863         spin_unlock_rd(&fdp->fd_spin);
1864         *fpp = fp;
1865         return (error);
1866 }
1867
1868 /*
1869  * For setugid programs, we don't want to people to use that setugidness
1870  * to generate error messages which write to a file which otherwise would
1871  * otherwise be off-limits to the process.
1872  *
1873  * This is a gross hack to plug the hole.  A better solution would involve
1874  * a special vop or other form of generalized access control mechanism.  We
1875  * go ahead and just reject all procfs file systems accesses as dangerous.
1876  *
1877  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1878  * sufficient.  We also don't for check setugidness since we know we are.
1879  */
1880 static int
1881 is_unsafe(struct file *fp)
1882 {
1883         if (fp->f_type == DTYPE_VNODE && 
1884             ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1885                 return (1);
1886         return (0);
1887 }
1888
1889 /*
1890  * Make this setguid thing safe, if at all possible.
1891  *
1892  * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
1893  */
1894 void
1895 setugidsafety(struct proc *p)
1896 {
1897         struct thread *td = p->p_thread;
1898         struct filedesc *fdp = p->p_fd;
1899         int i;
1900
1901         /* Certain daemons might not have file descriptors. */
1902         if (fdp == NULL)
1903                 return;
1904
1905         /*
1906          * note: fdp->fd_files may be reallocated out from under us while
1907          * we are blocked in a close.  Be careful!
1908          */
1909         for (i = 0; i <= fdp->fd_lastfile; i++) {
1910                 if (i > 2)
1911                         break;
1912                 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1913                         struct file *fp;
1914
1915                         if (i < fdp->fd_knlistsize)
1916                                 knote_fdclose(p, i);
1917                         /*
1918                          * NULL-out descriptor prior to close to avoid
1919                          * a race while close blocks.
1920                          */
1921                         if ((fp = funsetfd_locked(fdp, i)) != NULL)
1922                                 closef(fp, td);
1923                 }
1924         }
1925 }
1926
1927 /*
1928  * Close any files on exec?
1929  *
1930  * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
1931  */
1932 void
1933 fdcloseexec(struct proc *p)
1934 {
1935         struct thread *td = p->p_thread;
1936         struct filedesc *fdp = p->p_fd;
1937         int i;
1938
1939         /* Certain daemons might not have file descriptors. */
1940         if (fdp == NULL)
1941                 return;
1942
1943         /*
1944          * We cannot cache fd_files since operations may block and rip
1945          * them out from under us.
1946          */
1947         for (i = 0; i <= fdp->fd_lastfile; i++) {
1948                 if (fdp->fd_files[i].fp != NULL &&
1949                     (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1950                         struct file *fp;
1951
1952                         if (i < fdp->fd_knlistsize)
1953                                 knote_fdclose(p, i);
1954                         /*
1955                          * NULL-out descriptor prior to close to avoid
1956                          * a race while close blocks.
1957                          */
1958                         if ((fp = funsetfd_locked(fdp, i)) != NULL)
1959                                 closef(fp, td);
1960                 }
1961         }
1962 }
1963
1964 /*
1965  * It is unsafe for set[ug]id processes to be started with file
1966  * descriptors 0..2 closed, as these descriptors are given implicit
1967  * significance in the Standard C library.  fdcheckstd() will create a
1968  * descriptor referencing /dev/null for each of stdin, stdout, and
1969  * stderr that is not already open.
1970  *
1971  * NOT MPSAFE - calls falloc, vn_open, etc
1972  */
1973 int
1974 fdcheckstd(struct proc *p)
1975 {
1976         struct nlookupdata nd;
1977         struct filedesc *fdp;
1978         struct file *fp;
1979         register_t retval;
1980         int i, error, flags, devnull;
1981
1982        fdp = p->p_fd;
1983        if (fdp == NULL)
1984                return (0);
1985        devnull = -1;
1986        error = 0;
1987        for (i = 0; i < 3; i++) {
1988                 if (fdp->fd_files[i].fp != NULL)
1989                         continue;
1990                 if (devnull < 0) {
1991                         if ((error = falloc(p, &fp, &devnull)) != 0)
1992                                 break;
1993
1994                         error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1995                                                 NLC_FOLLOW|NLC_LOCKVP);
1996                         flags = FREAD | FWRITE;
1997                         if (error == 0)
1998                                 error = vn_open(&nd, fp, flags, 0);
1999                         if (error == 0)
2000                                 fsetfd(p, fp, devnull);
2001                         else
2002                                 fsetfd(p, NULL, devnull);
2003                         fdrop(fp);
2004                         nlookup_done(&nd);
2005                         if (error)
2006                                 break;
2007                         KKASSERT(i == devnull);
2008                 } else {
2009                         error = kern_dup(DUP_FIXED, devnull, i, &retval);
2010                         if (error != 0)
2011                                 break;
2012                 }
2013        }
2014        return (error);
2015 }
2016
2017 /*
2018  * Internal form of close.
2019  * Decrement reference count on file structure.
2020  * Note: td and/or p may be NULL when closing a file
2021  * that was being passed in a message.
2022  *
2023  * MPALMOSTSAFE - acquires mplock for VOP operations
2024  */
2025 int
2026 closef(struct file *fp, struct thread *td)
2027 {
2028         struct vnode *vp;
2029         struct flock lf;
2030         struct filedesc_to_leader *fdtol;
2031         struct proc *p;
2032
2033         if (fp == NULL)
2034                 return (0);
2035         if (td == NULL) {
2036                 td = curthread;
2037                 p = NULL;               /* allow no proc association */
2038         } else {
2039                 p = td->td_proc;        /* can also be NULL */
2040         }
2041         /*
2042          * POSIX record locking dictates that any close releases ALL
2043          * locks owned by this process.  This is handled by setting
2044          * a flag in the unlock to free ONLY locks obeying POSIX
2045          * semantics, and not to free BSD-style file locks.
2046          * If the descriptor was in a message, POSIX-style locks
2047          * aren't passed with the descriptor.
2048          */
2049         if (p != NULL && fp->f_type == DTYPE_VNODE &&
2050             (((struct vnode *)fp->f_data)->v_flag & VMAYHAVELOCKS)
2051         ) {
2052                 get_mplock();
2053                 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
2054                         lf.l_whence = SEEK_SET;
2055                         lf.l_start = 0;
2056                         lf.l_len = 0;
2057                         lf.l_type = F_UNLCK;
2058                         vp = (struct vnode *)fp->f_data;
2059                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
2060                                            &lf, F_POSIX);
2061                 }
2062                 fdtol = p->p_fdtol;
2063                 if (fdtol != NULL) {
2064                         /*
2065                          * Handle special case where file descriptor table
2066                          * is shared between multiple process leaders.
2067                          */
2068                         for (fdtol = fdtol->fdl_next;
2069                              fdtol != p->p_fdtol;
2070                              fdtol = fdtol->fdl_next) {
2071                                 if ((fdtol->fdl_leader->p_flag &
2072                                      P_ADVLOCK) == 0)
2073                                         continue;
2074                                 fdtol->fdl_holdcount++;
2075                                 lf.l_whence = SEEK_SET;
2076                                 lf.l_start = 0;
2077                                 lf.l_len = 0;
2078                                 lf.l_type = F_UNLCK;
2079                                 vp = (struct vnode *)fp->f_data;
2080                                 (void) VOP_ADVLOCK(vp,
2081                                                    (caddr_t)fdtol->fdl_leader,
2082                                                    F_UNLCK, &lf, F_POSIX);
2083                                 fdtol->fdl_holdcount--;
2084                                 if (fdtol->fdl_holdcount == 0 &&
2085                                     fdtol->fdl_wakeup != 0) {
2086                                         fdtol->fdl_wakeup = 0;
2087                                         wakeup(fdtol);
2088                                 }
2089                         }
2090                 }
2091                 rel_mplock();
2092         }
2093         return (fdrop(fp));
2094 }
2095
2096 /*
2097  * MPSAFE
2098  *
2099  * fhold() can only be called if f_count is already at least 1 (i.e. the
2100  * caller of fhold() already has a reference to the file pointer in some
2101  * manner or other). 
2102  *
2103  * This is a rare case where callers are allowed to hold spinlocks, so
2104  * we can't ourselves.  Since we are not obtaining the fp spinlock,
2105  * we have to use an atomic lock to interlock against fdrop().
2106  */
2107 void
2108 fhold(struct file *fp)
2109 {
2110         atomic_add_int(&fp->f_count, 1);
2111 }
2112
2113 /*
2114  * A spinlock is required to handle 1->0 transitions on f_count.  We have
2115  * to use atomic_sub_int so as not to race the atomic_add_int in fhold().
2116  *
2117  * MPALMOSTSAFE - acquires mplock for final close sequence
2118  */
2119 int
2120 fdrop(struct file *fp)
2121 {
2122         struct flock lf;
2123         struct vnode *vp;
2124         int error;
2125
2126         spin_lock_wr(&fp->f_spin);
2127         atomic_subtract_int(&fp->f_count, 1);
2128         if (fp->f_count > 0) {
2129                 spin_unlock_wr(&fp->f_spin);
2130                 return (0);
2131         }
2132         spin_unlock_wr(&fp->f_spin);
2133
2134         get_mplock();
2135
2136         /*
2137          * The last reference has gone away, we own the fp structure free
2138          * and clear.
2139          */
2140         if (fp->f_count < 0)
2141                 panic("fdrop: count < 0");
2142         if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE &&
2143             (((struct vnode *)fp->f_data)->v_flag & VMAYHAVELOCKS)
2144         ) {
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)