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