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