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