Merge from vendor branch GCC:
[dragonfly.git] / sys / kern / vfs_subr.c
1 /*
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)vfs_subr.c  8.31 (Berkeley) 5/26/95
39  * $FreeBSD: src/sys/kern/vfs_subr.c,v 1.249.2.30 2003/04/04 20:35:57 tegge Exp $
40  * $DragonFly: src/sys/kern/vfs_subr.c,v 1.52 2005/02/12 18:56:46 dillon Exp $
41  */
42
43 /*
44  * External virtual filesystem routines
45  */
46 #include "opt_ddb.h"
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/buf.h>
51 #include <sys/conf.h>
52 #include <sys/dirent.h>
53 #include <sys/domain.h>
54 #include <sys/eventhandler.h>
55 #include <sys/fcntl.h>
56 #include <sys/kernel.h>
57 #include <sys/kthread.h>
58 #include <sys/malloc.h>
59 #include <sys/mbuf.h>
60 #include <sys/mount.h>
61 #include <sys/proc.h>
62 #include <sys/reboot.h>
63 #include <sys/socket.h>
64 #include <sys/stat.h>
65 #include <sys/sysctl.h>
66 #include <sys/syslog.h>
67 #include <sys/vmmeter.h>
68 #include <sys/vnode.h>
69
70 #include <machine/limits.h>
71
72 #include <vm/vm.h>
73 #include <vm/vm_object.h>
74 #include <vm/vm_extern.h>
75 #include <vm/vm_kern.h>
76 #include <vm/pmap.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_page.h>
79 #include <vm/vm_pager.h>
80 #include <vm/vnode_pager.h>
81 #include <vm/vm_zone.h>
82
83 #include <sys/buf2.h>
84 #include <sys/thread2.h>
85
86 static MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
87
88 int numvnodes;
89 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
90 int vfs_fastdev = 1;
91 SYSCTL_INT(_vfs, OID_AUTO, fastdev, CTLFLAG_RW, &vfs_fastdev, 0, "");
92
93 enum vtype iftovt_tab[16] = {
94         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
95         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
96 };
97 int vttoif_tab[9] = {
98         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
99         S_IFSOCK, S_IFIFO, S_IFMT,
100 };
101
102 static int reassignbufcalls;
103 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW,
104                 &reassignbufcalls, 0, "");
105 static int reassignbufloops;
106 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW,
107                 &reassignbufloops, 0, "");
108 static int reassignbufsortgood;
109 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW,
110                 &reassignbufsortgood, 0, "");
111 static int reassignbufsortbad;
112 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW,
113                 &reassignbufsortbad, 0, "");
114 static int reassignbufmethod = 1;
115 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW,
116                 &reassignbufmethod, 0, "");
117
118 int     nfs_mount_type = -1;
119 static struct lwkt_token spechash_token;
120 struct nfs_public nfs_pub;      /* publicly exported FS */
121
122 int desiredvnodes;
123 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW, 
124                 &desiredvnodes, 0, "Maximum number of vnodes");
125
126 static void     vfs_free_addrlist (struct netexport *nep);
127 static int      vfs_free_netcred (struct radix_node *rn, void *w);
128 static int      vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
129                                        struct export_args *argp);
130
131 extern int dev_ref_debug;
132 extern struct vnodeopv_entry_desc spec_vnodeop_entries[];
133
134 /*
135  * Return 0 if the vnode is already on the free list or cannot be placed
136  * on the free list.  Return 1 if the vnode can be placed on the free list.
137  */
138 static __inline int
139 vshouldfree(struct vnode *vp, int usecount)
140 {
141         if (vp->v_flag & VFREE)
142                 return (0);             /* already free */
143         if (vp->v_holdcnt != 0 || vp->v_usecount != usecount)
144                 return (0);             /* other holderse */
145         if (vp->v_object &&
146             (vp->v_object->ref_count || vp->v_object->resident_page_count)) {
147                 return (0);
148         }
149         return (1);
150 }
151
152 /*
153  * Initialize the vnode management data structures. 
154  *
155  * Called from vfsinit()
156  */
157 void
158 vfs_subr_init(void)
159 {
160         /*
161          * Desired vnodes is a result of the physical page count
162          * and the size of kernel's heap.  It scales in proportion
163          * to the amount of available physical memory.  This can
164          * cause trouble on 64-bit and large memory platforms.
165          */
166         /* desiredvnodes = maxproc + vmstats.v_page_count / 4; */
167         desiredvnodes =
168                 min(maxproc + vmstats.v_page_count /4,
169                     2 * (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) /
170                     (5 * (sizeof(struct vm_object) + sizeof(struct vnode))));
171
172         lwkt_token_init(&spechash_token);
173 }
174
175 /*
176  * Knob to control the precision of file timestamps:
177  *
178  *   0 = seconds only; nanoseconds zeroed.
179  *   1 = seconds and nanoseconds, accurate within 1/HZ.
180  *   2 = seconds and nanoseconds, truncated to microseconds.
181  * >=3 = seconds and nanoseconds, maximum precision.
182  */
183 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
184
185 static int timestamp_precision = TSP_SEC;
186 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
187                 &timestamp_precision, 0, "");
188
189 /*
190  * Get a current timestamp.
191  */
192 void
193 vfs_timestamp(struct timespec *tsp)
194 {
195         struct timeval tv;
196
197         switch (timestamp_precision) {
198         case TSP_SEC:
199                 tsp->tv_sec = time_second;
200                 tsp->tv_nsec = 0;
201                 break;
202         case TSP_HZ:
203                 getnanotime(tsp);
204                 break;
205         case TSP_USEC:
206                 microtime(&tv);
207                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
208                 break;
209         case TSP_NSEC:
210         default:
211                 nanotime(tsp);
212                 break;
213         }
214 }
215
216 /*
217  * Set vnode attributes to VNOVAL
218  */
219 void
220 vattr_null(struct vattr *vap)
221 {
222         vap->va_type = VNON;
223         vap->va_size = VNOVAL;
224         vap->va_bytes = VNOVAL;
225         vap->va_mode = VNOVAL;
226         vap->va_nlink = VNOVAL;
227         vap->va_uid = VNOVAL;
228         vap->va_gid = VNOVAL;
229         vap->va_fsid = VNOVAL;
230         vap->va_fileid = VNOVAL;
231         vap->va_blocksize = VNOVAL;
232         vap->va_rdev = VNOVAL;
233         vap->va_atime.tv_sec = VNOVAL;
234         vap->va_atime.tv_nsec = VNOVAL;
235         vap->va_mtime.tv_sec = VNOVAL;
236         vap->va_mtime.tv_nsec = VNOVAL;
237         vap->va_ctime.tv_sec = VNOVAL;
238         vap->va_ctime.tv_nsec = VNOVAL;
239         vap->va_flags = VNOVAL;
240         vap->va_gen = VNOVAL;
241         vap->va_vaflags = 0;
242 }
243
244 /*
245  * Update outstanding I/O count and do wakeup if requested.
246  */
247 void
248 vwakeup(struct buf *bp)
249 {
250         struct vnode *vp;
251
252         bp->b_flags &= ~B_WRITEINPROG;
253         if ((vp = bp->b_vp)) {
254                 vp->v_numoutput--;
255                 if (vp->v_numoutput < 0)
256                         panic("vwakeup: neg numoutput");
257                 if ((vp->v_numoutput == 0) && (vp->v_flag & VBWAIT)) {
258                         vp->v_flag &= ~VBWAIT;
259                         wakeup((caddr_t) &vp->v_numoutput);
260                 }
261         }
262 }
263
264 /*
265  * Flush out and invalidate all buffers associated with a vnode.
266  *
267  * vp must be locked.
268  */
269 int
270 vinvalbuf(struct vnode *vp, int flags, struct thread *td,
271         int slpflag, int slptimeo)
272 {
273         struct buf *bp;
274         struct buf *nbp, *blist;
275         int s, error;
276         vm_object_t object;
277
278         if (flags & V_SAVE) {
279                 s = splbio();
280                 while (vp->v_numoutput) {
281                         vp->v_flag |= VBWAIT;
282                         error = tsleep((caddr_t)&vp->v_numoutput,
283                             slpflag, "vinvlbuf", slptimeo);
284                         if (error) {
285                                 splx(s);
286                                 return (error);
287                         }
288                 }
289                 if (!TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
290                         splx(s);
291                         if ((error = VOP_FSYNC(vp, MNT_WAIT, td)) != 0)
292                                 return (error);
293                         s = splbio();
294                         if (vp->v_numoutput > 0 ||
295                             !TAILQ_EMPTY(&vp->v_dirtyblkhd))
296                                 panic("vinvalbuf: dirty bufs");
297                 }
298                 splx(s);
299         }
300         s = splbio();
301         for (;;) {
302                 blist = TAILQ_FIRST(&vp->v_cleanblkhd);
303                 if (!blist)
304                         blist = TAILQ_FIRST(&vp->v_dirtyblkhd);
305                 if (!blist)
306                         break;
307
308                 for (bp = blist; bp; bp = nbp) {
309                         nbp = TAILQ_NEXT(bp, b_vnbufs);
310                         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
311                                 error = BUF_TIMELOCK(bp,
312                                     LK_EXCLUSIVE | LK_SLEEPFAIL,
313                                     "vinvalbuf", slpflag, slptimeo);
314                                 if (error == ENOLCK)
315                                         break;
316                                 splx(s);
317                                 return (error);
318                         }
319                         /*
320                          * XXX Since there are no node locks for NFS, I
321                          * believe there is a slight chance that a delayed
322                          * write will occur while sleeping just above, so
323                          * check for it.  Note that vfs_bio_awrite expects
324                          * buffers to reside on a queue, while VOP_BWRITE and
325                          * brelse do not.
326                          */
327                         if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
328                                 (flags & V_SAVE)) {
329
330                                 if (bp->b_vp == vp) {
331                                         if (bp->b_flags & B_CLUSTEROK) {
332                                                 BUF_UNLOCK(bp);
333                                                 vfs_bio_awrite(bp);
334                                         } else {
335                                                 bremfree(bp);
336                                                 bp->b_flags |= B_ASYNC;
337                                                 VOP_BWRITE(bp->b_vp, bp);
338                                         }
339                                 } else {
340                                         bremfree(bp);
341                                         (void) VOP_BWRITE(bp->b_vp, bp);
342                                 }
343                                 break;
344                         }
345                         bremfree(bp);
346                         bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
347                         bp->b_flags &= ~B_ASYNC;
348                         brelse(bp);
349                 }
350         }
351
352         /*
353          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
354          * have write I/O in-progress but if there is a VM object then the
355          * VM object can also have read-I/O in-progress.
356          */
357         do {
358                 while (vp->v_numoutput > 0) {
359                         vp->v_flag |= VBWAIT;
360                         tsleep(&vp->v_numoutput, 0, "vnvlbv", 0);
361                 }
362                 if (VOP_GETVOBJECT(vp, &object) == 0) {
363                         while (object->paging_in_progress)
364                                 vm_object_pip_sleep(object, "vnvlbx");
365                 }
366         } while (vp->v_numoutput > 0);
367
368         splx(s);
369
370         /*
371          * Destroy the copy in the VM cache, too.
372          */
373         if (VOP_GETVOBJECT(vp, &object) == 0) {
374                 vm_object_page_remove(object, 0, 0,
375                         (flags & V_SAVE) ? TRUE : FALSE);
376         }
377
378         if (!TAILQ_EMPTY(&vp->v_dirtyblkhd) || !TAILQ_EMPTY(&vp->v_cleanblkhd))
379                 panic("vinvalbuf: flush failed");
380         return (0);
381 }
382
383 /*
384  * Truncate a file's buffer and pages to a specified length.  This
385  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
386  * sync activity.
387  *
388  * The vnode must be locked.
389  */
390 int
391 vtruncbuf(struct vnode *vp, struct thread *td, off_t length, int blksize)
392 {
393         struct buf *bp;
394         struct buf *nbp;
395         int s, anyfreed;
396         int trunclbn;
397
398         /*
399          * Round up to the *next* lbn.
400          */
401         trunclbn = (length + blksize - 1) / blksize;
402
403         s = splbio();
404 restart:
405         anyfreed = 1;
406         for (;anyfreed;) {
407                 anyfreed = 0;
408                 for (bp = TAILQ_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
409                         nbp = TAILQ_NEXT(bp, b_vnbufs);
410                         if (bp->b_lblkno >= trunclbn) {
411                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
412                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
413                                         goto restart;
414                                 } else {
415                                         bremfree(bp);
416                                         bp->b_flags |= (B_INVAL | B_RELBUF);
417                                         bp->b_flags &= ~B_ASYNC;
418                                         brelse(bp);
419                                         anyfreed = 1;
420                                 }
421                                 if (nbp &&
422                                     (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
423                                     (nbp->b_vp != vp) ||
424                                     (nbp->b_flags & B_DELWRI))) {
425                                         goto restart;
426                                 }
427                         }
428                 }
429
430                 for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
431                         nbp = TAILQ_NEXT(bp, b_vnbufs);
432                         if (bp->b_lblkno >= trunclbn) {
433                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
434                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
435                                         goto restart;
436                                 } else {
437                                         bremfree(bp);
438                                         bp->b_flags |= (B_INVAL | B_RELBUF);
439                                         bp->b_flags &= ~B_ASYNC;
440                                         brelse(bp);
441                                         anyfreed = 1;
442                                 }
443                                 if (nbp &&
444                                     (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
445                                     (nbp->b_vp != vp) ||
446                                     (nbp->b_flags & B_DELWRI) == 0)) {
447                                         goto restart;
448                                 }
449                         }
450                 }
451         }
452
453         if (length > 0) {
454 restartsync:
455                 for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
456                         nbp = TAILQ_NEXT(bp, b_vnbufs);
457                         if ((bp->b_flags & B_DELWRI) && (bp->b_lblkno < 0)) {
458                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
459                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
460                                         goto restart;
461                                 } else {
462                                         bremfree(bp);
463                                         if (bp->b_vp == vp) {
464                                                 bp->b_flags |= B_ASYNC;
465                                         } else {
466                                                 bp->b_flags &= ~B_ASYNC;
467                                         }
468                                         VOP_BWRITE(bp->b_vp, bp);
469                                 }
470                                 goto restartsync;
471                         }
472
473                 }
474         }
475
476         while (vp->v_numoutput > 0) {
477                 vp->v_flag |= VBWAIT;
478                 tsleep(&vp->v_numoutput, 0, "vbtrunc", 0);
479         }
480
481         splx(s);
482
483         vnode_pager_setsize(vp, length);
484
485         return (0);
486 }
487
488 /*
489  * Associate a buffer with a vnode.
490  */
491 void
492 bgetvp(struct vnode *vp, struct buf *bp)
493 {
494         KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
495
496         vhold(vp);
497         bp->b_vp = vp;
498         bp->b_dev = vn_todev(vp);
499         /*
500          * Insert onto list for new vnode.
501          */
502         crit_enter();
503         bp->b_xflags |= BX_VNCLEAN;
504         bp->b_xflags &= ~BX_VNDIRTY;
505         TAILQ_INSERT_TAIL(&vp->v_cleanblkhd, bp, b_vnbufs);
506         crit_exit();
507 }
508
509 /*
510  * Disassociate a buffer from a vnode.
511  */
512 void
513 brelvp(struct buf *bp)
514 {
515         struct vnode *vp;
516         struct buflists *listheadp;
517
518         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
519
520         /*
521          * Delete from old vnode list, if on one.
522          */
523         vp = bp->b_vp;
524         crit_enter();
525         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
526                 if (bp->b_xflags & BX_VNDIRTY)
527                         listheadp = &vp->v_dirtyblkhd;
528                 else 
529                         listheadp = &vp->v_cleanblkhd;
530                 TAILQ_REMOVE(listheadp, bp, b_vnbufs);
531                 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
532         }
533         if ((vp->v_flag & VONWORKLST) && TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
534                 vp->v_flag &= ~VONWORKLST;
535                 LIST_REMOVE(vp, v_synclist);
536         }
537         crit_exit();
538         bp->b_vp = NULL;
539         vdrop(vp);
540 }
541
542 /*
543  * Associate a p-buffer with a vnode.
544  *
545  * Also sets B_PAGING flag to indicate that vnode is not fully associated
546  * with the buffer.  i.e. the bp has not been linked into the vnode or
547  * ref-counted.
548  */
549 void
550 pbgetvp(struct vnode *vp, struct buf *bp)
551 {
552         KASSERT(bp->b_vp == NULL, ("pbgetvp: not free"));
553
554         bp->b_vp = vp;
555         bp->b_flags |= B_PAGING;
556         bp->b_dev = vn_todev(vp);
557 }
558
559 /*
560  * Disassociate a p-buffer from a vnode.
561  */
562 void
563 pbrelvp(struct buf *bp)
564 {
565         KASSERT(bp->b_vp != NULL, ("pbrelvp: NULL"));
566
567         /* XXX REMOVE ME */
568         if (TAILQ_NEXT(bp, b_vnbufs) != NULL) {
569                 panic(
570                     "relpbuf(): b_vp was probably reassignbuf()d %p %x", 
571                     bp,
572                     (int)bp->b_flags
573                 );
574         }
575         bp->b_vp = (struct vnode *) 0;
576         bp->b_flags &= ~B_PAGING;
577 }
578
579 void
580 pbreassignbuf(struct buf *bp, struct vnode *newvp)
581 {
582         if ((bp->b_flags & B_PAGING) == 0) {
583                 panic(
584                     "pbreassignbuf() on non phys bp %p", 
585                     bp
586                 );
587         }
588         bp->b_vp = newvp;
589 }
590
591 /*
592  * Reassign a buffer from one vnode to another.
593  * Used to assign file specific control information
594  * (indirect blocks) to the vnode to which they belong.
595  */
596 void
597 reassignbuf(struct buf *bp, struct vnode *newvp)
598 {
599         struct buflists *listheadp;
600         int delay;
601
602         if (newvp == NULL) {
603                 printf("reassignbuf: NULL");
604                 return;
605         }
606         ++reassignbufcalls;
607
608         /*
609          * B_PAGING flagged buffers cannot be reassigned because their vp
610          * is not fully linked in.
611          */
612         if (bp->b_flags & B_PAGING)
613                 panic("cannot reassign paging buffer");
614
615         crit_enter();
616         /*
617          * Delete from old vnode list, if on one.
618          */
619         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
620                 if (bp->b_xflags & BX_VNDIRTY)
621                         listheadp = &bp->b_vp->v_dirtyblkhd;
622                 else 
623                         listheadp = &bp->b_vp->v_cleanblkhd;
624                 TAILQ_REMOVE(listheadp, bp, b_vnbufs);
625                 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
626                 if (bp->b_vp != newvp) {
627                         vdrop(bp->b_vp);
628                         bp->b_vp = NULL;        /* for clarification */
629                 }
630         }
631         /*
632          * If dirty, put on list of dirty buffers; otherwise insert onto list
633          * of clean buffers.
634          */
635         if (bp->b_flags & B_DELWRI) {
636                 struct buf *tbp;
637
638                 listheadp = &newvp->v_dirtyblkhd;
639                 if ((newvp->v_flag & VONWORKLST) == 0) {
640                         switch (newvp->v_type) {
641                         case VDIR:
642                                 delay = dirdelay;
643                                 break;
644                         case VCHR:
645                         case VBLK:
646                                 if (newvp->v_rdev && 
647                                     newvp->v_rdev->si_mountpoint != NULL) {
648                                         delay = metadelay;
649                                         break;
650                                 }
651                                 /* fall through */
652                         default:
653                                 delay = filedelay;
654                         }
655                         vn_syncer_add_to_worklist(newvp, delay);
656                 }
657                 bp->b_xflags |= BX_VNDIRTY;
658                 tbp = TAILQ_FIRST(listheadp);
659                 if (tbp == NULL ||
660                     bp->b_lblkno == 0 ||
661                     (bp->b_lblkno > 0 && tbp->b_lblkno < 0) ||
662                     (bp->b_lblkno > 0 && bp->b_lblkno < tbp->b_lblkno)) {
663                         TAILQ_INSERT_HEAD(listheadp, bp, b_vnbufs);
664                         ++reassignbufsortgood;
665                 } else if (bp->b_lblkno < 0) {
666                         TAILQ_INSERT_TAIL(listheadp, bp, b_vnbufs);
667                         ++reassignbufsortgood;
668                 } else if (reassignbufmethod == 1) {
669                         /*
670                          * New sorting algorithm, only handle sequential case,
671                          * otherwise append to end (but before metadata)
672                          */
673                         if ((tbp = gbincore(newvp, bp->b_lblkno - 1)) != NULL &&
674                             (tbp->b_xflags & BX_VNDIRTY)) {
675                                 /*
676                                  * Found the best place to insert the buffer
677                                  */
678                                 TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
679                                 ++reassignbufsortgood;
680                         } else {
681                                 /*
682                                  * Missed, append to end, but before meta-data.
683                                  * We know that the head buffer in the list is
684                                  * not meta-data due to prior conditionals.
685                                  *
686                                  * Indirect effects:  NFS second stage write
687                                  * tends to wind up here, giving maximum 
688                                  * distance between the unstable write and the
689                                  * commit rpc.
690                                  */
691                                 tbp = TAILQ_LAST(listheadp, buflists);
692                                 while (tbp && tbp->b_lblkno < 0)
693                                         tbp = TAILQ_PREV(tbp, buflists, b_vnbufs);
694                                 TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
695                                 ++reassignbufsortbad;
696                         }
697                 } else {
698                         /*
699                          * Old sorting algorithm, scan queue and insert
700                          */
701                         struct buf *ttbp;
702                         while ((ttbp = TAILQ_NEXT(tbp, b_vnbufs)) &&
703                             (ttbp->b_lblkno < bp->b_lblkno)) {
704                                 ++reassignbufloops;
705                                 tbp = ttbp;
706                         }
707                         TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
708                 }
709         } else {
710                 bp->b_xflags |= BX_VNCLEAN;
711                 TAILQ_INSERT_TAIL(&newvp->v_cleanblkhd, bp, b_vnbufs);
712                 if ((newvp->v_flag & VONWORKLST) &&
713                     TAILQ_EMPTY(&newvp->v_dirtyblkhd)) {
714                         newvp->v_flag &= ~VONWORKLST;
715                         LIST_REMOVE(newvp, v_synclist);
716                 }
717         }
718         if (bp->b_vp != newvp) {
719                 bp->b_vp = newvp;
720                 vhold(bp->b_vp);
721         }
722         crit_exit();
723 }
724
725 /*
726  * Create a vnode for a block device.
727  * Used for mounting the root file system.
728  */
729 int
730 bdevvp(dev_t dev, struct vnode **vpp)
731 {
732         struct vnode *vp;
733         struct vnode *nvp;
734         int error;
735
736         if (dev == NODEV) {
737                 *vpp = NULLVP;
738                 return (ENXIO);
739         }
740         error = getspecialvnode(VT_NON, NULL, &spec_vnode_vops, &nvp, 0, 0);
741         if (error) {
742                 *vpp = NULLVP;
743                 return (error);
744         }
745         vp = nvp;
746         vp->v_type = VCHR;
747         vp->v_udev = dev->si_udev;
748         vx_unlock(vp);
749         *vpp = vp;
750         return (0);
751 }
752
753 int
754 v_associate_rdev(struct vnode *vp, dev_t dev)
755 {
756         lwkt_tokref ilock;
757
758         if (dev == NULL || dev == NODEV)
759                 return(ENXIO);
760         if (dev_is_good(dev) == 0)
761                 return(ENXIO);
762         KKASSERT(vp->v_rdev == NULL);
763         if (dev_ref_debug)
764                 printf("Z1");
765         vp->v_rdev = reference_dev(dev);
766         lwkt_gettoken(&ilock, &spechash_token);
767         SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_specnext);
768         lwkt_reltoken(&ilock);
769         return(0);
770 }
771
772 void
773 v_release_rdev(struct vnode *vp)
774 {
775         lwkt_tokref ilock;
776         dev_t dev;
777
778         if ((dev = vp->v_rdev) != NULL) {
779                 lwkt_gettoken(&ilock, &spechash_token);
780                 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_specnext);
781                 if (dev_ref_debug && vp->v_opencount != 0) {
782                         printf("releasing rdev with non-0 "
783                                 "v_opencount(%d) (revoked?)\n",
784                                 vp->v_opencount);
785                 }
786                 vp->v_rdev = NULL;
787                 vp->v_opencount = 0;
788                 release_dev(dev);
789                 lwkt_reltoken(&ilock);
790         }
791 }
792
793 /*
794  * Add a vnode to the alias list hung off the dev_t.  We only associate
795  * the device number with the vnode.  The actual device is not associated
796  * until the vnode is opened (usually in spec_open()), and will be 
797  * disassociated on last close.
798  */
799 void
800 addaliasu(struct vnode *nvp, udev_t nvp_udev)
801 {
802         if (nvp->v_type != VBLK && nvp->v_type != VCHR)
803                 panic("addaliasu on non-special vnode");
804         nvp->v_udev = nvp_udev;
805 }
806
807 /*
808  * Disassociate a vnode from its underlying filesystem. 
809  *
810  * The vnode must be VX locked and refd
811  *
812  * If there are v_usecount references to the vnode other then ours we have
813  * to VOP_CLOSE the vnode before we can deactivate and reclaim it.
814  */
815 void
816 vclean(struct vnode *vp, int flags, struct thread *td)
817 {
818         int active;
819
820         /*
821          * If the vnode has already been reclaimed we have nothing to do.
822          */
823         if (vp->v_flag & VRECLAIMED)
824                 return;
825         vp->v_flag |= VRECLAIMED;
826
827         /*
828          * Scrap the vfs cache
829          */
830         while (cache_inval_vp(vp, 0) != 0) {
831                 printf("Warning: vnode %p clean/cache_resolution race detected\n", vp);
832                 tsleep(vp, 0, "vclninv", 2);
833         }
834
835         /*
836          * Check to see if the vnode is in use. If so we have to reference it
837          * before we clean it out so that its count cannot fall to zero and
838          * generate a race against ourselves to recycle it.
839          */
840         active = (vp->v_usecount > 1);
841
842         /*
843          * Clean out any buffers associated with the vnode and destroy its
844          * object, if it has one.
845          */
846         vinvalbuf(vp, V_SAVE, td, 0, 0);
847         VOP_DESTROYVOBJECT(vp);
848
849         /*
850          * If purging an active vnode, it must be closed and
851          * deactivated before being reclaimed.   XXX
852          *
853          * Note that neither of these routines unlocks the vnode.
854          */
855         if (active) {
856                 if (flags & DOCLOSE)
857                         VOP_CLOSE(vp, FNONBLOCK, td);
858         }
859
860         /*
861          * If the vnode has not be deactivated, deactivated it.
862          */
863         if ((vp->v_flag & VINACTIVE) == 0) {
864                 vp->v_flag |= VINACTIVE;
865                 VOP_INACTIVE(vp, td);
866         }
867
868         /*
869          * Reclaim the vnode.
870          */
871         if (VOP_RECLAIM(vp, td))
872                 panic("vclean: cannot reclaim");
873
874         /*
875          * Done with purge, notify sleepers of the grim news.
876          */
877         vp->v_ops = &dead_vnode_vops;
878         vn_pollgone(vp);
879         vp->v_tag = VT_NON;
880 }
881
882 /*
883  * Eliminate all activity associated with the requested vnode
884  * and with all vnodes aliased to the requested vnode.
885  *
886  * The vnode must be referenced and vx_lock()'d
887  *
888  * revoke { struct vnode *a_vp, int a_flags }
889  */
890 int
891 vop_stdrevoke(struct vop_revoke_args *ap)
892 {
893         struct vnode *vp, *vq;
894         lwkt_tokref ilock;
895         dev_t dev;
896
897         KASSERT((ap->a_flags & REVOKEALL) != 0, ("vop_revoke"));
898
899         vp = ap->a_vp;
900
901         /*
902          * If the vnode is already dead don't try to revoke it
903          */
904         if (vp->v_flag & VRECLAIMED)
905                 return (0);
906
907         /*
908          * If the vnode has a device association, scrap all vnodes associated
909          * with the device.  Don't let the device disappear on us while we
910          * are scrapping the vnodes.
911          *
912          * The passed vp will probably show up in the list, do not VX lock
913          * it twice!
914          */
915         if (vp->v_type != VCHR && vp->v_type != VBLK)
916                 return(0);
917         if ((dev = vp->v_rdev) == NULL) {
918                 if ((dev = udev2dev(vp->v_udev, vp->v_type == VBLK)) == NODEV)
919                         return(0);
920         }
921         reference_dev(dev);
922         lwkt_gettoken(&ilock, &spechash_token);
923         while ((vq = SLIST_FIRST(&dev->si_hlist)) != NULL) {
924                 if (vp == vq || vx_get(vq) == 0) {
925                         if (vq == SLIST_FIRST(&dev->si_hlist))
926                                 vgone(vq);
927                         if (vp != vq)
928                                 vx_put(vq);
929                 }
930         }
931         lwkt_reltoken(&ilock);
932         release_dev(dev);
933         return (0);
934 }
935
936 /*
937  * Recycle an unused vnode to the front of the free list.
938  *
939  * Returns 1 if we were successfully able to recycle the vnode, 
940  * 0 otherwise.
941  */
942 int
943 vrecycle(struct vnode *vp, struct thread *td)
944 {
945         if (vp->v_usecount == 1) {
946                 vgone(vp);
947                 return (1);
948         }
949         return (0);
950 }
951
952 /*
953  * Eliminate all activity associated with a vnode in preparation for reuse.
954  *
955  * The vnode must be VX locked and refd and will remain VX locked and refd
956  * on return.  This routine may be called with the vnode in any state, as
957  * long as it is VX locked.  The vnode will be cleaned out and marked
958  * VRECLAIMED but will not actually be reused until all existing refs and
959  * holds go away.
960  *
961  * NOTE: This routine may be called on a vnode which has not yet been
962  * already been deactivated (VOP_INACTIVE), or on a vnode which has
963  * already been reclaimed.
964  *
965  * This routine is not responsible for placing us back on the freelist. 
966  * Instead, it happens automatically when the caller releases the VX lock
967  * (assuming there aren't any other references).
968  */
969 void
970 vgone(struct vnode *vp)
971 {
972         /*
973          * assert that the VX lock is held.  This is an absolute requirement
974          * now for vgone() to be called.
975          */
976         KKASSERT(vp->v_lock.lk_exclusivecount == 1);
977
978         /*
979          * Clean out the filesystem specific data and set the VRECLAIMED
980          * bit.  Also deactivate the vnode if necessary.
981          */
982         vclean(vp, DOCLOSE, curthread);
983
984         /*
985          * Delete from old mount point vnode list, if on one.
986          */
987         if (vp->v_mount != NULL)
988                 insmntque(vp, NULL);
989
990         /*
991          * If special device, remove it from special device alias list
992          * if it is on one.  This should normally only occur if a vnode is
993          * being revoked as the device should otherwise have been released
994          * naturally.
995          */
996         if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
997                 v_release_rdev(vp);
998         }
999
1000         /*
1001          * Set us to VBAD
1002          */
1003         vp->v_type = VBAD;
1004 }
1005
1006 /*
1007  * Lookup a vnode by device number.
1008  */
1009 int
1010 vfinddev(dev_t dev, enum vtype type, struct vnode **vpp)
1011 {
1012         lwkt_tokref ilock;
1013         struct vnode *vp;
1014
1015         lwkt_gettoken(&ilock, &spechash_token);
1016         SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
1017                 if (type == vp->v_type) {
1018                         *vpp = vp;
1019                         lwkt_reltoken(&ilock);
1020                         return (1);
1021                 }
1022         }
1023         lwkt_reltoken(&ilock);
1024         return (0);
1025 }
1026
1027 /*
1028  * Calculate the total number of references to a special device.  This
1029  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1030  * an overloaded field.  Since udev2dev can now return NODEV, we have
1031  * to check for a NULL v_rdev.
1032  */
1033 int
1034 count_dev(dev_t dev)
1035 {
1036         lwkt_tokref ilock;
1037         struct vnode *vp;
1038         int count = 0;
1039
1040         if (SLIST_FIRST(&dev->si_hlist)) {
1041                 lwkt_gettoken(&ilock, &spechash_token);
1042                 SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
1043                         count += vp->v_usecount;
1044                 }
1045                 lwkt_reltoken(&ilock);
1046         }
1047         return(count);
1048 }
1049
1050 int
1051 count_udev(udev_t udev)
1052 {
1053         dev_t dev;
1054
1055         if ((dev = udev2dev(udev, 0)) == NODEV)
1056                 return(0);
1057         return(count_dev(dev));
1058 }
1059
1060 int
1061 vcount(struct vnode *vp)
1062 {
1063         if (vp->v_rdev == NULL)
1064                 return(0);
1065         return(count_dev(vp->v_rdev));
1066 }
1067
1068 /*
1069  * Print out a description of a vnode.
1070  */
1071 static char *typename[] =
1072 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1073
1074 void
1075 vprint(char *label, struct vnode *vp)
1076 {
1077         char buf[96];
1078
1079         if (label != NULL)
1080                 printf("%s: %p: ", label, (void *)vp);
1081         else
1082                 printf("%p: ", (void *)vp);
1083         printf("type %s, usecount %d, writecount %d, refcount %d,",
1084             typename[vp->v_type], vp->v_usecount, vp->v_writecount,
1085             vp->v_holdcnt);
1086         buf[0] = '\0';
1087         if (vp->v_flag & VROOT)
1088                 strcat(buf, "|VROOT");
1089         if (vp->v_flag & VTEXT)
1090                 strcat(buf, "|VTEXT");
1091         if (vp->v_flag & VSYSTEM)
1092                 strcat(buf, "|VSYSTEM");
1093         if (vp->v_flag & VBWAIT)
1094                 strcat(buf, "|VBWAIT");
1095         if (vp->v_flag & VFREE)
1096                 strcat(buf, "|VFREE");
1097         if (vp->v_flag & VOBJBUF)
1098                 strcat(buf, "|VOBJBUF");
1099         if (buf[0] != '\0')
1100                 printf(" flags (%s)", &buf[1]);
1101         if (vp->v_data == NULL) {
1102                 printf("\n");
1103         } else {
1104                 printf("\n\t");
1105                 VOP_PRINT(vp);
1106         }
1107 }
1108
1109 #ifdef DDB
1110 #include <ddb/ddb.h>
1111 /*
1112  * List all of the locked vnodes in the system.
1113  * Called when debugging the kernel.
1114  */
1115 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1116 {
1117         struct thread *td = curthread;  /* XXX */
1118         lwkt_tokref ilock;
1119         struct mount *mp, *nmp;
1120         struct vnode *vp;
1121
1122         printf("Locked vnodes\n");
1123         lwkt_gettoken(&ilock, &mountlist_token);
1124         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1125                 if (vfs_busy(mp, LK_NOWAIT, &ilock, td)) {
1126                         nmp = TAILQ_NEXT(mp, mnt_list);
1127                         continue;
1128                 }
1129                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1130                         if (VOP_ISLOCKED(vp, NULL))
1131                                 vprint((char *)0, vp);
1132                 }
1133                 lwkt_gettokref(&ilock);
1134                 nmp = TAILQ_NEXT(mp, mnt_list);
1135                 vfs_unbusy(mp, td);
1136         }
1137         lwkt_reltoken(&ilock);
1138 }
1139 #endif
1140
1141 /*
1142  * Top level filesystem related information gathering.
1143  */
1144 static int      sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1145
1146 static int
1147 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1148 {
1149         int *name = (int *)arg1 - 1;    /* XXX */
1150         u_int namelen = arg2 + 1;       /* XXX */
1151         struct vfsconf *vfsp;
1152
1153 #if 1 || defined(COMPAT_PRELITE2)
1154         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1155         if (namelen == 1)
1156                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1157 #endif
1158
1159 #ifdef notyet
1160         /* all sysctl names at this level are at least name and field */
1161         if (namelen < 2)
1162                 return (ENOTDIR);               /* overloaded */
1163         if (name[0] != VFS_GENERIC) {
1164                 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
1165                         if (vfsp->vfc_typenum == name[0])
1166                                 break;
1167                 if (vfsp == NULL)
1168                         return (EOPNOTSUPP);
1169                 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1170                     oldp, oldlenp, newp, newlen, p));
1171         }
1172 #endif
1173         switch (name[1]) {
1174         case VFS_MAXTYPENUM:
1175                 if (namelen != 2)
1176                         return (ENOTDIR);
1177                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
1178         case VFS_CONF:
1179                 if (namelen != 3)
1180                         return (ENOTDIR);       /* overloaded */
1181                 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
1182                         if (vfsp->vfc_typenum == name[2])
1183                                 break;
1184                 if (vfsp == NULL)
1185                         return (EOPNOTSUPP);
1186                 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1187         }
1188         return (EOPNOTSUPP);
1189 }
1190
1191 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1192         "Generic filesystem");
1193
1194 #if 1 || defined(COMPAT_PRELITE2)
1195
1196 static int
1197 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1198 {
1199         int error;
1200         struct vfsconf *vfsp;
1201         struct ovfsconf ovfs;
1202
1203         for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
1204                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
1205                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
1206                 ovfs.vfc_index = vfsp->vfc_typenum;
1207                 ovfs.vfc_refcount = vfsp->vfc_refcount;
1208                 ovfs.vfc_flags = vfsp->vfc_flags;
1209                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1210                 if (error)
1211                         return error;
1212         }
1213         return 0;
1214 }
1215
1216 #endif /* 1 || COMPAT_PRELITE2 */
1217
1218 #if 0
1219 #define KINFO_VNODESLOP 10
1220 /*
1221  * Dump vnode list (via sysctl).
1222  * Copyout address of vnode followed by vnode.
1223  */
1224 /* ARGSUSED */
1225 static int
1226 sysctl_vnode(SYSCTL_HANDLER_ARGS)
1227 {
1228         struct proc *p = curproc;       /* XXX */
1229         struct mount *mp, *nmp;
1230         struct vnode *nvp, *vp;
1231         lwkt_tokref ilock;
1232         lwkt_tokref jlock;
1233         int error;
1234
1235 #define VPTRSZ  sizeof (struct vnode *)
1236 #define VNODESZ sizeof (struct vnode)
1237
1238         req->lock = 0;
1239         if (!req->oldptr) /* Make an estimate */
1240                 return (SYSCTL_OUT(req, 0,
1241                         (numvnodes + KINFO_VNODESLOP) * (VPTRSZ + VNODESZ)));
1242
1243         lwkt_gettoken(&ilock, &mountlist_token);
1244         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1245                 if (vfs_busy(mp, LK_NOWAIT, &ilock, p)) {
1246                         nmp = TAILQ_NEXT(mp, mnt_list);
1247                         continue;
1248                 }
1249                 lwkt_gettoken(&jlock, &mntvnode_token);
1250 again:
1251                 for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
1252                      vp != NULL;
1253                      vp = nvp) {
1254                         /*
1255                          * Check that the vp is still associated with
1256                          * this filesystem.  RACE: could have been
1257                          * recycled onto the same filesystem.
1258                          */
1259                         if (vp->v_mount != mp)
1260                                 goto again;
1261                         nvp = TAILQ_NEXT(vp, v_nmntvnodes);
1262                         if ((error = SYSCTL_OUT(req, &vp, VPTRSZ)) ||
1263                             (error = SYSCTL_OUT(req, vp, VNODESZ))) {
1264                                 lwkt_reltoken(&jlock);
1265                                 return (error);
1266                         }
1267                 }
1268                 lwkt_reltoken(&jlock);
1269                 lwkt_gettokref(&ilock);
1270                 nmp = TAILQ_NEXT(mp, mnt_list); /* ZZZ */
1271                 vfs_unbusy(mp, p);
1272         }
1273         lwkt_reltoken(&ilock);
1274
1275         return (0);
1276 }
1277 #endif
1278
1279 /*
1280  * XXX
1281  * Exporting the vnode list on large systems causes them to crash.
1282  * Exporting the vnode list on medium systems causes sysctl to coredump.
1283  */
1284 #if 0
1285 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
1286         0, 0, sysctl_vnode, "S,vnode", "");
1287 #endif
1288
1289 /*
1290  * Check to see if a filesystem is mounted on a block device.
1291  */
1292 int
1293 vfs_mountedon(struct vnode *vp)
1294 {
1295         dev_t dev;
1296
1297         if ((dev = vp->v_rdev) == NULL)
1298                 dev = udev2dev(vp->v_udev, (vp->v_type == VBLK));
1299         if (dev != NODEV && dev->si_mountpoint)
1300                 return (EBUSY);
1301         return (0);
1302 }
1303
1304 /*
1305  * Unmount all filesystems. The list is traversed in reverse order
1306  * of mounting to avoid dependencies.
1307  */
1308 void
1309 vfs_unmountall(void)
1310 {
1311         struct mount *mp;
1312         struct thread *td = curthread;
1313         int error;
1314
1315         if (td->td_proc == NULL)
1316                 td = initproc->p_thread;        /* XXX XXX use proc0 instead? */
1317
1318         /*
1319          * Since this only runs when rebooting, it is not interlocked.
1320          */
1321         while(!TAILQ_EMPTY(&mountlist)) {
1322                 mp = TAILQ_LAST(&mountlist, mntlist);
1323                 error = dounmount(mp, MNT_FORCE, td);
1324                 if (error) {
1325                         TAILQ_REMOVE(&mountlist, mp, mnt_list);
1326                         printf("unmount of filesystem mounted from %s failed (", mp->mnt_stat.f_mntfromname);
1327                         if (error == EBUSY)
1328                                 printf("BUSY)\n");
1329                         else
1330                                 printf("%d)\n", error);
1331                 } else {
1332                         /* The unmount has removed mp from the mountlist */
1333                 }
1334         }
1335 }
1336
1337 /*
1338  * Build hash lists of net addresses and hang them off the mount point.
1339  * Called by ufs_mount() to set up the lists of export addresses.
1340  */
1341 static int
1342 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
1343                 struct export_args *argp)
1344 {
1345         struct netcred *np;
1346         struct radix_node_head *rnh;
1347         int i;
1348         struct radix_node *rn;
1349         struct sockaddr *saddr, *smask = 0;
1350         struct domain *dom;
1351         int error;
1352
1353         if (argp->ex_addrlen == 0) {
1354                 if (mp->mnt_flag & MNT_DEFEXPORTED)
1355                         return (EPERM);
1356                 np = &nep->ne_defexported;
1357                 np->netc_exflags = argp->ex_flags;
1358                 np->netc_anon = argp->ex_anon;
1359                 np->netc_anon.cr_ref = 1;
1360                 mp->mnt_flag |= MNT_DEFEXPORTED;
1361                 return (0);
1362         }
1363
1364         if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
1365                 return (EINVAL);
1366         if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
1367                 return (EINVAL);
1368
1369         i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
1370         np = (struct netcred *) malloc(i, M_NETADDR, M_WAITOK);
1371         bzero((caddr_t) np, i);
1372         saddr = (struct sockaddr *) (np + 1);
1373         if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
1374                 goto out;
1375         if (saddr->sa_len > argp->ex_addrlen)
1376                 saddr->sa_len = argp->ex_addrlen;
1377         if (argp->ex_masklen) {
1378                 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
1379                 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
1380                 if (error)
1381                         goto out;
1382                 if (smask->sa_len > argp->ex_masklen)
1383                         smask->sa_len = argp->ex_masklen;
1384         }
1385         i = saddr->sa_family;
1386         if ((rnh = nep->ne_rtable[i]) == 0) {
1387                 /*
1388                  * Seems silly to initialize every AF when most are not used,
1389                  * do so on demand here
1390                  */
1391                 for (dom = domains; dom; dom = dom->dom_next)
1392                         if (dom->dom_family == i && dom->dom_rtattach) {
1393                                 dom->dom_rtattach((void **) &nep->ne_rtable[i],
1394                                     dom->dom_rtoffset);
1395                                 break;
1396                         }
1397                 if ((rnh = nep->ne_rtable[i]) == 0) {
1398                         error = ENOBUFS;
1399                         goto out;
1400                 }
1401         }
1402         rn = (*rnh->rnh_addaddr) ((char *) saddr, (char *) smask, rnh,
1403             np->netc_rnodes);
1404         if (rn == 0 || np != (struct netcred *) rn) {   /* already exists */
1405                 error = EPERM;
1406                 goto out;
1407         }
1408         np->netc_exflags = argp->ex_flags;
1409         np->netc_anon = argp->ex_anon;
1410         np->netc_anon.cr_ref = 1;
1411         return (0);
1412 out:
1413         free(np, M_NETADDR);
1414         return (error);
1415 }
1416
1417 /* ARGSUSED */
1418 static int
1419 vfs_free_netcred(struct radix_node *rn, void *w)
1420 {
1421         struct radix_node_head *rnh = (struct radix_node_head *) w;
1422
1423         (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
1424         free((caddr_t) rn, M_NETADDR);
1425         return (0);
1426 }
1427
1428 /*
1429  * Free the net address hash lists that are hanging off the mount points.
1430  */
1431 static void
1432 vfs_free_addrlist(struct netexport *nep)
1433 {
1434         int i;
1435         struct radix_node_head *rnh;
1436
1437         for (i = 0; i <= AF_MAX; i++)
1438                 if ((rnh = nep->ne_rtable[i])) {
1439                         (*rnh->rnh_walktree) (rnh, vfs_free_netcred,
1440                             (caddr_t) rnh);
1441                         free((caddr_t) rnh, M_RTABLE);
1442                         nep->ne_rtable[i] = 0;
1443                 }
1444 }
1445
1446 int
1447 vfs_export(struct mount *mp, struct netexport *nep, struct export_args *argp)
1448 {
1449         int error;
1450
1451         if (argp->ex_flags & MNT_DELEXPORT) {
1452                 if (mp->mnt_flag & MNT_EXPUBLIC) {
1453                         vfs_setpublicfs(NULL, NULL, NULL);
1454                         mp->mnt_flag &= ~MNT_EXPUBLIC;
1455                 }
1456                 vfs_free_addrlist(nep);
1457                 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
1458         }
1459         if (argp->ex_flags & MNT_EXPORTED) {
1460                 if (argp->ex_flags & MNT_EXPUBLIC) {
1461                         if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
1462                                 return (error);
1463                         mp->mnt_flag |= MNT_EXPUBLIC;
1464                 }
1465                 if ((error = vfs_hang_addrlist(mp, nep, argp)))
1466                         return (error);
1467                 mp->mnt_flag |= MNT_EXPORTED;
1468         }
1469         return (0);
1470 }
1471
1472
1473 /*
1474  * Set the publicly exported filesystem (WebNFS). Currently, only
1475  * one public filesystem is possible in the spec (RFC 2054 and 2055)
1476  */
1477 int
1478 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
1479                 struct export_args *argp)
1480 {
1481         int error;
1482         struct vnode *rvp;
1483         char *cp;
1484
1485         /*
1486          * mp == NULL -> invalidate the current info, the FS is
1487          * no longer exported. May be called from either vfs_export
1488          * or unmount, so check if it hasn't already been done.
1489          */
1490         if (mp == NULL) {
1491                 if (nfs_pub.np_valid) {
1492                         nfs_pub.np_valid = 0;
1493                         if (nfs_pub.np_index != NULL) {
1494                                 FREE(nfs_pub.np_index, M_TEMP);
1495                                 nfs_pub.np_index = NULL;
1496                         }
1497                 }
1498                 return (0);
1499         }
1500
1501         /*
1502          * Only one allowed at a time.
1503          */
1504         if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
1505                 return (EBUSY);
1506
1507         /*
1508          * Get real filehandle for root of exported FS.
1509          */
1510         bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
1511         nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
1512
1513         if ((error = VFS_ROOT(mp, &rvp)))
1514                 return (error);
1515
1516         if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
1517                 return (error);
1518
1519         vput(rvp);
1520
1521         /*
1522          * If an indexfile was specified, pull it in.
1523          */
1524         if (argp->ex_indexfile != NULL) {
1525                 MALLOC(nfs_pub.np_index, char *, MAXNAMLEN + 1, M_TEMP,
1526                     M_WAITOK);
1527                 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
1528                     MAXNAMLEN, (size_t *)0);
1529                 if (!error) {
1530                         /*
1531                          * Check for illegal filenames.
1532                          */
1533                         for (cp = nfs_pub.np_index; *cp; cp++) {
1534                                 if (*cp == '/') {
1535                                         error = EINVAL;
1536                                         break;
1537                                 }
1538                         }
1539                 }
1540                 if (error) {
1541                         FREE(nfs_pub.np_index, M_TEMP);
1542                         return (error);
1543                 }
1544         }
1545
1546         nfs_pub.np_mount = mp;
1547         nfs_pub.np_valid = 1;
1548         return (0);
1549 }
1550
1551 struct netcred *
1552 vfs_export_lookup(struct mount *mp, struct netexport *nep,
1553                 struct sockaddr *nam)
1554 {
1555         struct netcred *np;
1556         struct radix_node_head *rnh;
1557         struct sockaddr *saddr;
1558
1559         np = NULL;
1560         if (mp->mnt_flag & MNT_EXPORTED) {
1561                 /*
1562                  * Lookup in the export list first.
1563                  */
1564                 if (nam != NULL) {
1565                         saddr = nam;
1566                         rnh = nep->ne_rtable[saddr->sa_family];
1567                         if (rnh != NULL) {
1568                                 np = (struct netcred *)
1569                                         (*rnh->rnh_matchaddr)((char *)saddr,
1570                                                               rnh);
1571                                 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
1572                                         np = NULL;
1573                         }
1574                 }
1575                 /*
1576                  * If no address match, use the default if it exists.
1577                  */
1578                 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
1579                         np = &nep->ne_defexported;
1580         }
1581         return (np);
1582 }
1583
1584 /*
1585  * perform msync on all vnodes under a mount point.  The mount point must
1586  * be locked.  This code is also responsible for lazy-freeing unreferenced
1587  * vnodes whos VM objects no longer contain pages.
1588  *
1589  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
1590  */
1591 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
1592 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
1593
1594 void
1595 vfs_msync(struct mount *mp, int flags) 
1596 {
1597         vmntvnodescan(mp, VMSC_REFVP, vfs_msync_scan1, vfs_msync_scan2,
1598                         (void *)flags);
1599 }
1600
1601 /*
1602  * scan1 is a fast pre-check.  There could be hundreds of thousands of
1603  * vnodes, we cannot afford to do anything heavy weight until we have a
1604  * fairly good indication that there is work to do.
1605  */
1606 static
1607 int
1608 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
1609 {
1610         int flags = (int)data;
1611
1612         if ((vp->v_flag & VRECLAIMED) == 0) {
1613                 if (vshouldfree(vp, 0))
1614                         return(0);      /* call scan2 */
1615                 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
1616                     (vp->v_flag & VOBJDIRTY) &&
1617                     (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
1618                         return(0);      /* call scan2 */
1619                 }
1620         }
1621
1622         /*
1623          * do not call scan2, continue the loop
1624          */
1625         return(-1);
1626 }
1627
1628 static
1629 int
1630 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
1631 {
1632         vm_object_t obj;
1633         int flags = (int)data;
1634
1635         if (vp->v_flag & VRECLAIMED)
1636                 return(0);
1637
1638         if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
1639             (vp->v_flag & VOBJDIRTY) &&
1640             (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
1641                 if (VOP_GETVOBJECT(vp, &obj) == 0) {
1642                         vm_object_page_clean(obj, 0, 0, 
1643                          flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
1644                 }
1645         }
1646         return(0);
1647 }
1648
1649 /*
1650  * Create the VM object needed for VMIO and mmap support.  This
1651  * is done for all VREG files in the system.  Some filesystems might
1652  * afford the additional metadata buffering capability of the
1653  * VMIO code by making the device node be VMIO mode also.
1654  *
1655  * vp must be locked when vfs_object_create is called.
1656  */
1657 int
1658 vfs_object_create(struct vnode *vp, struct thread *td)
1659 {
1660         return (VOP_CREATEVOBJECT(vp, td));
1661 }
1662
1663 /*
1664  * Record a process's interest in events which might happen to
1665  * a vnode.  Because poll uses the historic select-style interface
1666  * internally, this routine serves as both the ``check for any
1667  * pending events'' and the ``record my interest in future events''
1668  * functions.  (These are done together, while the lock is held,
1669  * to avoid race conditions.)
1670  */
1671 int
1672 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
1673 {
1674         lwkt_tokref ilock;
1675
1676         lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
1677         if (vp->v_pollinfo.vpi_revents & events) {
1678                 /*
1679                  * This leaves events we are not interested
1680                  * in available for the other process which
1681                  * which presumably had requested them
1682                  * (otherwise they would never have been
1683                  * recorded).
1684                  */
1685                 events &= vp->v_pollinfo.vpi_revents;
1686                 vp->v_pollinfo.vpi_revents &= ~events;
1687
1688                 lwkt_reltoken(&ilock);
1689                 return events;
1690         }
1691         vp->v_pollinfo.vpi_events |= events;
1692         selrecord(td, &vp->v_pollinfo.vpi_selinfo);
1693         lwkt_reltoken(&ilock);
1694         return 0;
1695 }
1696
1697 /*
1698  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
1699  * it is possible for us to miss an event due to race conditions, but
1700  * that condition is expected to be rare, so for the moment it is the
1701  * preferred interface.
1702  */
1703 void
1704 vn_pollevent(struct vnode *vp, int events)
1705 {
1706         lwkt_tokref ilock;
1707
1708         lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
1709         if (vp->v_pollinfo.vpi_events & events) {
1710                 /*
1711                  * We clear vpi_events so that we don't
1712                  * call selwakeup() twice if two events are
1713                  * posted before the polling process(es) is
1714                  * awakened.  This also ensures that we take at
1715                  * most one selwakeup() if the polling process
1716                  * is no longer interested.  However, it does
1717                  * mean that only one event can be noticed at
1718                  * a time.  (Perhaps we should only clear those
1719                  * event bits which we note?) XXX
1720                  */
1721                 vp->v_pollinfo.vpi_events = 0;  /* &= ~events ??? */
1722                 vp->v_pollinfo.vpi_revents |= events;
1723                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
1724         }
1725         lwkt_reltoken(&ilock);
1726 }
1727
1728 /*
1729  * Wake up anyone polling on vp because it is being revoked.
1730  * This depends on dead_poll() returning POLLHUP for correct
1731  * behavior.
1732  */
1733 void
1734 vn_pollgone(struct vnode *vp)
1735 {
1736         lwkt_tokref ilock;
1737
1738         lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
1739         if (vp->v_pollinfo.vpi_events) {
1740                 vp->v_pollinfo.vpi_events = 0;
1741                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
1742         }
1743         lwkt_reltoken(&ilock);
1744 }
1745
1746 /*
1747  * extract the dev_t from a VBLK or VCHR.  The vnode must have been opened
1748  * (or v_rdev might be NULL).
1749  */
1750 dev_t
1751 vn_todev(struct vnode *vp)
1752 {
1753         if (vp->v_type != VBLK && vp->v_type != VCHR)
1754                 return (NODEV);
1755         KKASSERT(vp->v_rdev != NULL);
1756         return (vp->v_rdev);
1757 }
1758
1759 /*
1760  * Check if vnode represents a disk device.  The vnode does not need to be
1761  * opened.
1762  */
1763 int
1764 vn_isdisk(struct vnode *vp, int *errp)
1765 {
1766         dev_t dev;
1767
1768         if (vp->v_type != VBLK && vp->v_type != VCHR) {
1769                 if (errp != NULL)
1770                         *errp = ENOTBLK;
1771                 return (0);
1772         }
1773
1774         if ((dev = vp->v_rdev) == NULL)
1775                 dev = udev2dev(vp->v_udev, (vp->v_type == VBLK));
1776         if (dev == NULL || dev == NODEV) {
1777                 if (errp != NULL)
1778                         *errp = ENXIO;
1779                 return (0);
1780         }
1781         if (dev_is_good(dev) == 0) {
1782                 if (errp != NULL)
1783                         *errp = ENXIO;
1784                 return (0);
1785         }
1786         if ((dev_dflags(dev) & D_DISK) == 0) {
1787                 if (errp != NULL)
1788                         *errp = ENOTBLK;
1789                 return (0);
1790         }
1791         if (errp != NULL)
1792                 *errp = 0;
1793         return (1);
1794 }
1795
1796 #ifdef DEBUG_VFS_LOCKS
1797
1798 void
1799 assert_vop_locked(struct vnode *vp, const char *str)
1800 {
1801         if (vp && IS_LOCKING_VFS(vp) && !VOP_ISLOCKED(vp, NULL)) {
1802                 panic("%s: %p is not locked shared but should be", str, vp);
1803         }
1804 }
1805
1806 void
1807 assert_vop_unlocked(struct vnode *vp, const char *str)
1808 {
1809         if (vp && IS_LOCKING_VFS(vp)) {
1810                 if (VOP_ISLOCKED(vp, curthread) == LK_EXCLUSIVE) {
1811                         panic("%s: %p is locked but should not be", str, vp);
1812                 }
1813         }
1814 }
1815
1816 #endif