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