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