When booting from CD, check cd1a and acd1a after cd0a and acd0a, allowing
[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.34 2004/07/04 05:16:30 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 static void     insmntque (struct vnode *vp, struct mount *mp);
90 static void     vclean (struct vnode *vp, lwkt_tokref_t vlock, 
91                         int flags, struct thread *td);
92
93 static unsigned long numvnodes;
94 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
95
96 enum vtype iftovt_tab[16] = {
97         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
98         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
99 };
100 int vttoif_tab[9] = {
101         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
102         S_IFSOCK, S_IFIFO, S_IFMT,
103 };
104
105 static TAILQ_HEAD(freelst, vnode) vnode_free_list;      /* vnode free list */
106
107 static u_long wantfreevnodes = 25;
108 SYSCTL_INT(_debug, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
109                 &wantfreevnodes, 0, "");
110 static u_long freevnodes = 0;
111 SYSCTL_INT(_debug, OID_AUTO, freevnodes, CTLFLAG_RD,
112                 &freevnodes, 0, "");
113
114 static int reassignbufcalls;
115 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW,
116                 &reassignbufcalls, 0, "");
117 static int reassignbufloops;
118 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW,
119                 &reassignbufloops, 0, "");
120 static int reassignbufsortgood;
121 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW,
122                 &reassignbufsortgood, 0, "");
123 static int reassignbufsortbad;
124 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW,
125                 &reassignbufsortbad, 0, "");
126 static int reassignbufmethod = 1;
127 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW,
128                 &reassignbufmethod, 0, "");
129
130 #ifdef ENABLE_VFS_IOOPT
131 int vfs_ioopt = 0;
132 SYSCTL_INT(_vfs, OID_AUTO, ioopt, CTLFLAG_RW, &vfs_ioopt, 0, "");
133 #endif
134
135 struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist); /* mounted fs */
136 struct lwkt_token mountlist_token;
137 struct lwkt_token mntvnode_token;
138 int     nfs_mount_type = -1;
139 static struct lwkt_token mntid_token;
140 static struct lwkt_token vnode_free_list_token;
141 static struct lwkt_token spechash_token;
142 struct nfs_public nfs_pub;      /* publicly exported FS */
143 static vm_zone_t vnode_zone;
144
145 /*
146  * The workitem queue.
147  */
148 #define SYNCER_MAXDELAY         32
149 static int syncer_maxdelay = SYNCER_MAXDELAY;   /* maximum delay time */
150 time_t syncdelay = 30;          /* max time to delay syncing data */
151 SYSCTL_INT(_kern, OID_AUTO, syncdelay, CTLFLAG_RW,
152                 &syncdelay, 0, "VFS data synchronization delay");
153 time_t filedelay = 30;          /* time to delay syncing files */
154 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW,
155                 &filedelay, 0, "File synchronization delay");
156 time_t dirdelay = 29;           /* time to delay syncing directories */
157 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW,
158                 &dirdelay, 0, "Directory synchronization delay");
159 time_t metadelay = 28;          /* time to delay syncing metadata */
160 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW,
161                 &metadelay, 0, "VFS metadata synchronization delay");
162 static int rushjob;                     /* number of slots to run ASAP */
163 static int stat_rush_requests;  /* number of times I/O speeded up */
164 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW,
165                 &stat_rush_requests, 0, "");
166
167 static int syncer_delayno = 0;
168 static long syncer_mask; 
169 LIST_HEAD(synclist, vnode);
170 static struct synclist *syncer_workitem_pending;
171
172 int desiredvnodes;
173 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW, 
174                 &desiredvnodes, 0, "Maximum number of vnodes");
175 static int minvnodes;
176 SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW, 
177                 &minvnodes, 0, "Minimum number of vnodes");
178 static int vnlru_nowhere = 0;
179 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
180                 &vnlru_nowhere, 0,
181                 "Number of times the vnlru process ran without success");
182
183 static void     vfs_free_addrlist (struct netexport *nep);
184 static int      vfs_free_netcred (struct radix_node *rn, void *w);
185 static int      vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
186                                        struct export_args *argp);
187
188 #define VSHOULDFREE(vp) \
189         (!((vp)->v_flag & (VFREE|VDOOMED)) && \
190          !(vp)->v_holdcnt && !(vp)->v_usecount && \
191          (!(vp)->v_object || \
192           !((vp)->v_object->ref_count || (vp)->v_object->resident_page_count)))
193  
194 #define VMIGHTFREE(vp) \
195         (((vp)->v_flag & (VFREE|VDOOMED|VXLOCK)) == 0 &&   \
196          cache_leaf_test(vp) == 0 && (vp)->v_usecount == 0)
197  
198 #define VSHOULDBUSY(vp) \
199         (((vp)->v_flag & VFREE) && \
200          ((vp)->v_holdcnt || (vp)->v_usecount))
201
202 static void vbusy(struct vnode *vp);
203 static void vfree(struct vnode *vp);
204 static void vmaybefree(struct vnode *vp);
205
206 extern int dev_ref_debug;
207
208 /*
209  * NOTE: the vnode interlock must be held on call.
210  */
211 static __inline void
212 vmaybefree(struct vnode *vp)
213 {
214         if (VSHOULDFREE(vp))
215                 vfree(vp);
216 }
217  
218 /*
219  * Initialize the vnode management data structures.
220  */
221 void
222 vntblinit(void)
223 {
224
225         /*
226          * Desired vnodes is a result of the physical page count
227          * and the size of kernel's heap.  It scales in proportion
228          * to the amount of available physical memory.  This can
229          * cause trouble on 64-bit and large memory platforms.
230          */
231         /* desiredvnodes = maxproc + vmstats.v_page_count / 4; */
232         desiredvnodes =
233                 min(maxproc + vmstats.v_page_count /4,
234                     2 * (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) /
235                     (5 * (sizeof(struct vm_object) + sizeof(struct vnode))));
236
237         minvnodes = desiredvnodes / 4;
238         lwkt_token_init(&mountlist_token);
239         lwkt_token_init(&mntvnode_token);
240         lwkt_token_init(&mntid_token);
241         lwkt_token_init(&spechash_token);
242         TAILQ_INIT(&vnode_free_list);
243         lwkt_token_init(&vnode_free_list_token);
244         vnode_zone = zinit("VNODE", sizeof (struct vnode), 0, 0, 5);
245         /*
246          * Initialize the filesystem syncer.
247          */     
248         syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE, 
249                 &syncer_mask);
250         syncer_maxdelay = syncer_mask + 1;
251 }
252
253 /*
254  * Mark a mount point as busy. Used to synchronize access and to delay
255  * unmounting. Interlock is not released on failure.
256  */
257 int
258 vfs_busy(struct mount *mp, int flags,
259         lwkt_tokref_t interlkp, struct thread *td)
260 {
261         int lkflags;
262
263         if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
264                 if (flags & LK_NOWAIT)
265                         return (ENOENT);
266                 mp->mnt_kern_flag |= MNTK_MWAIT;
267                 /*
268                  * Since all busy locks are shared except the exclusive
269                  * lock granted when unmounting, the only place that a
270                  * wakeup needs to be done is at the release of the
271                  * exclusive lock at the end of dounmount.
272                  *
273                  * note: interlkp is a serializer and thus can be safely
274                  * held through any sleep
275                  */
276                 tsleep((caddr_t)mp, 0, "vfs_busy", 0);
277                 return (ENOENT);
278         }
279         lkflags = LK_SHARED | LK_NOPAUSE;
280         if (interlkp)
281                 lkflags |= LK_INTERLOCK;
282         if (lockmgr(&mp->mnt_lock, lkflags, interlkp, td))
283                 panic("vfs_busy: unexpected lock failure");
284         return (0);
285 }
286
287 /*
288  * Free a busy filesystem.
289  */
290 void
291 vfs_unbusy(struct mount *mp, struct thread *td)
292 {
293         lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, td);
294 }
295
296 /*
297  * Lookup a filesystem type, and if found allocate and initialize
298  * a mount structure for it.
299  *
300  * Devname is usually updated by mount(8) after booting.
301  */
302 int
303 vfs_rootmountalloc(char *fstypename, char *devname, struct mount **mpp)
304 {
305         struct thread *td = curthread;  /* XXX */
306         struct vfsconf *vfsp;
307         struct mount *mp;
308
309         if (fstypename == NULL)
310                 return (ENODEV);
311         for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
312                 if (!strcmp(vfsp->vfc_name, fstypename))
313                         break;
314         }
315         if (vfsp == NULL)
316                 return (ENODEV);
317         mp = malloc((u_long)sizeof(struct mount), M_MOUNT, M_WAITOK);
318         bzero((char *)mp, (u_long)sizeof(struct mount));
319         lockinit(&mp->mnt_lock, 0, "vfslock", VLKTIMEOUT, LK_NOPAUSE);
320         vfs_busy(mp, LK_NOWAIT, NULL, td);
321         TAILQ_INIT(&mp->mnt_nvnodelist);
322         TAILQ_INIT(&mp->mnt_reservedvnlist);
323         mp->mnt_nvnodelistsize = 0;
324         mp->mnt_vfc = vfsp;
325         mp->mnt_op = vfsp->vfc_vfsops;
326         mp->mnt_flag = MNT_RDONLY;
327         mp->mnt_vnodecovered = NULLVP;
328         vfsp->vfc_refcount++;
329         mp->mnt_iosize_max = DFLTPHYS;
330         mp->mnt_stat.f_type = vfsp->vfc_typenum;
331         mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
332         strncpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
333         mp->mnt_stat.f_mntonname[0] = '/';
334         mp->mnt_stat.f_mntonname[1] = 0;
335         (void) copystr(devname, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, 0);
336         *mpp = mp;
337         return (0);
338 }
339
340 /*
341  * Lookup a mount point by filesystem identifier.
342  */
343 struct mount *
344 vfs_getvfs(fsid_t *fsid)
345 {
346         struct mount *mp;
347         lwkt_tokref ilock;
348
349         lwkt_gettoken(&ilock, &mountlist_token);
350         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
351                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
352                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
353                         break;
354             }
355         }
356         lwkt_reltoken(&ilock);
357         return (mp);
358 }
359
360 /*
361  * Get a new unique fsid.  Try to make its val[0] unique, since this value
362  * will be used to create fake device numbers for stat().  Also try (but
363  * not so hard) make its val[0] unique mod 2^16, since some emulators only
364  * support 16-bit device numbers.  We end up with unique val[0]'s for the
365  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
366  *
367  * Keep in mind that several mounts may be running in parallel.  Starting
368  * the search one past where the previous search terminated is both a
369  * micro-optimization and a defense against returning the same fsid to
370  * different mounts.
371  */
372 void
373 vfs_getnewfsid(struct mount *mp)
374 {
375         static u_int16_t mntid_base;
376         lwkt_tokref ilock;
377         fsid_t tfsid;
378         int mtype;
379
380         lwkt_gettoken(&ilock, &mntid_token);
381         mtype = mp->mnt_vfc->vfc_typenum;
382         tfsid.val[1] = mtype;
383         mtype = (mtype & 0xFF) << 24;
384         for (;;) {
385                 tfsid.val[0] = makeudev(255,
386                     mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
387                 mntid_base++;
388                 if (vfs_getvfs(&tfsid) == NULL)
389                         break;
390         }
391         mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
392         mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
393         lwkt_reltoken(&ilock);
394 }
395
396 /*
397  * Knob to control the precision of file timestamps:
398  *
399  *   0 = seconds only; nanoseconds zeroed.
400  *   1 = seconds and nanoseconds, accurate within 1/HZ.
401  *   2 = seconds and nanoseconds, truncated to microseconds.
402  * >=3 = seconds and nanoseconds, maximum precision.
403  */
404 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
405
406 static int timestamp_precision = TSP_SEC;
407 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
408                 &timestamp_precision, 0, "");
409
410 /*
411  * Get a current timestamp.
412  */
413 void
414 vfs_timestamp(struct timespec *tsp)
415 {
416         struct timeval tv;
417
418         switch (timestamp_precision) {
419         case TSP_SEC:
420                 tsp->tv_sec = time_second;
421                 tsp->tv_nsec = 0;
422                 break;
423         case TSP_HZ:
424                 getnanotime(tsp);
425                 break;
426         case TSP_USEC:
427                 microtime(&tv);
428                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
429                 break;
430         case TSP_NSEC:
431         default:
432                 nanotime(tsp);
433                 break;
434         }
435 }
436
437 /*
438  * Set vnode attributes to VNOVAL
439  */
440 void
441 vattr_null(struct vattr *vap)
442 {
443         vap->va_type = VNON;
444         vap->va_size = VNOVAL;
445         vap->va_bytes = VNOVAL;
446         vap->va_mode = VNOVAL;
447         vap->va_nlink = VNOVAL;
448         vap->va_uid = VNOVAL;
449         vap->va_gid = VNOVAL;
450         vap->va_fsid = VNOVAL;
451         vap->va_fileid = VNOVAL;
452         vap->va_blocksize = VNOVAL;
453         vap->va_rdev = VNOVAL;
454         vap->va_atime.tv_sec = VNOVAL;
455         vap->va_atime.tv_nsec = VNOVAL;
456         vap->va_mtime.tv_sec = VNOVAL;
457         vap->va_mtime.tv_nsec = VNOVAL;
458         vap->va_ctime.tv_sec = VNOVAL;
459         vap->va_ctime.tv_nsec = VNOVAL;
460         vap->va_flags = VNOVAL;
461         vap->va_gen = VNOVAL;
462         vap->va_vaflags = 0;
463 }
464
465 /*
466  * This routine is called when we have too many vnodes.  It attempts
467  * to free <count> vnodes and will potentially free vnodes that still
468  * have VM backing store (VM backing store is typically the cause
469  * of a vnode blowout so we want to do this).  Therefore, this operation
470  * is not considered cheap.
471  *
472  * A number of conditions may prevent a vnode from being reclaimed.
473  * the buffer cache may have references on the vnode, a directory
474  * vnode may still have references due to the namei cache representing
475  * underlying files, or the vnode may be in active use.   It is not
476  * desireable to reuse such vnodes.  These conditions may cause the
477  * number of vnodes to reach some minimum value regardless of what
478  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
479  */
480 static int
481 vlrureclaim(struct mount *mp)
482 {
483         struct vnode *vp;
484         lwkt_tokref ilock;
485         lwkt_tokref vlock;
486         int done;
487         int trigger;
488         int usevnodes;
489         int count;
490
491         /*
492          * Calculate the trigger point, don't allow user
493          * screwups to blow us up.   This prevents us from
494          * recycling vnodes with lots of resident pages.  We
495          * aren't trying to free memory, we are trying to
496          * free vnodes.
497          */
498         usevnodes = desiredvnodes;
499         if (usevnodes <= 0)
500                 usevnodes = 1;
501         trigger = vmstats.v_page_count * 2 / usevnodes;
502
503         done = 0;
504         lwkt_gettoken(&ilock, &mntvnode_token);
505         count = mp->mnt_nvnodelistsize / 10 + 1;
506         while (count && (vp = TAILQ_FIRST(&mp->mnt_nvnodelist)) != NULL) {
507                 /*
508                  * __VNODESCAN__
509                  *
510                  * The VP will stick around while we hold mntvnode_token,
511                  * at least until we block, so we can safely do an initial
512                  * check.  But we have to check again after obtaining
513                  * the vnode interlock.  vp->v_interlock points to stable
514                  * storage so it's ok if the vp gets ripped out from
515                  * under us while we are blocked.
516                  */
517                 if (vp->v_type == VNON ||
518                     vp->v_type == VBAD ||
519                     !VMIGHTFREE(vp) ||          /* critical path opt */
520                     (vp->v_object &&
521                      vp->v_object->resident_page_count >= trigger)
522                 ) {
523                         TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
524                         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist,vp, v_nmntvnodes);
525                         --count;
526                         continue;
527                 }
528
529                 /*
530                  * Get the interlock, delay moving the node to the tail so
531                  * we don't race against new additions to the mountlist.
532                  */
533                 lwkt_gettoken(&vlock, vp->v_interlock);
534                 if (TAILQ_FIRST(&mp->mnt_nvnodelist) != vp) {
535                         lwkt_reltoken(&vlock);
536                         continue;
537                 }
538                 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
539                 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist,vp, v_nmntvnodes);
540
541                 /*
542                  * Must check again
543                  */
544                 if (vp->v_type == VNON ||
545                     vp->v_type == VBAD ||
546                     !VMIGHTFREE(vp) ||          /* critical path opt */
547                     (vp->v_object &&
548                      vp->v_object->resident_page_count >= trigger)
549                 ) {
550                         lwkt_reltoken(&vlock);
551                         --count;
552                         continue;
553                 }
554                 vgonel(vp, &vlock, curthread);
555                 ++done;
556                 --count;
557         }
558         lwkt_reltoken(&ilock);
559         return done;
560 }
561
562 /*
563  * Attempt to recycle vnodes in a context that is always safe to block.
564  * Calling vlrurecycle() from the bowels of file system code has some
565  * interesting deadlock problems.
566  */
567 static struct thread *vnlruthread;
568 static int vnlruproc_sig;
569
570 static void 
571 vnlru_proc(void)
572 {
573         struct mount *mp, *nmp;
574         lwkt_tokref ilock;
575         int s;
576         int done;
577         struct thread *td = curthread;
578
579         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, td,
580             SHUTDOWN_PRI_FIRST);   
581
582         s = splbio();
583         for (;;) {
584                 kproc_suspend_loop();
585                 if (numvnodes - freevnodes <= desiredvnodes * 9 / 10) {
586                         vnlruproc_sig = 0;
587                         wakeup(&vnlruproc_sig);
588                         tsleep(td, 0, "vlruwt", hz);
589                         continue;
590                 }
591                 done = 0;
592                 lwkt_gettoken(&ilock, &mountlist_token);
593                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
594                         if (vfs_busy(mp, LK_NOWAIT, &ilock, td)) {
595                                 nmp = TAILQ_NEXT(mp, mnt_list);
596                                 continue;
597                         }
598                         done += vlrureclaim(mp);
599                         lwkt_gettokref(&ilock);
600                         nmp = TAILQ_NEXT(mp, mnt_list);
601                         vfs_unbusy(mp, td);
602                 }
603                 lwkt_reltoken(&ilock);
604                 if (done == 0) {
605                         vnlru_nowhere++;
606                         tsleep(td, 0, "vlrup", hz * 3);
607                 }
608         }
609         splx(s);
610 }
611
612 static struct kproc_desc vnlru_kp = {
613         "vnlru",
614         vnlru_proc,
615         &vnlruthread
616 };
617 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &vnlru_kp)
618
619 /*
620  * Routines having to do with the management of the vnode table.
621  */
622 extern vop_t **dead_vnodeop_p;
623
624 /*
625  * Return the next vnode from the free list.
626  */
627 int
628 getnewvnode(enum vtagtype tag, struct mount *mp, 
629             vop_t **vops, struct vnode **vpp)
630 {
631         int s;
632         struct thread *td = curthread;  /* XXX */
633         struct vnode *vp = NULL;
634         struct vnode *xvp;
635         vm_object_t object;
636         lwkt_tokref ilock;
637         lwkt_tokref vlock;
638
639         s = splbio();
640
641         /*
642          * Try to reuse vnodes if we hit the max.  This situation only
643          * occurs in certain large-memory (2G+) situations.  We cannot
644          * attempt to directly reclaim vnodes due to nasty recursion
645          * problems.
646          */
647         while (numvnodes - freevnodes > desiredvnodes) {
648                 if (vnlruproc_sig == 0) {
649                         vnlruproc_sig = 1;      /* avoid unnecessary wakeups */
650                         wakeup(vnlruthread);
651                 }
652                 tsleep(&vnlruproc_sig, 0, "vlruwk", hz);
653         }
654
655
656         /*
657          * Attempt to reuse a vnode already on the free list, allocating
658          * a new vnode if we can't find one or if we have not reached a
659          * good minimum for good LRU performance.
660          */
661         lwkt_gettoken(&ilock, &vnode_free_list_token);
662         if (freevnodes >= wantfreevnodes && numvnodes >= minvnodes) {
663                 int count;
664
665                 for (count = 0; count < freevnodes; count++) {
666                         /*
667                          * __VNODESCAN__
668                          *
669                          * Pull the next vnode off the free list and do some
670                          * sanity checks.  Note that regardless of how we
671                          * block, if freevnodes is non-zero there had better
672                          * be something on the list.
673                          */
674                         vp = TAILQ_FIRST(&vnode_free_list);
675                         if (vp == NULL)
676                                 panic("getnewvnode: free vnode isn't");
677
678                         /*
679                          * Move the vnode to the end of the list so other
680                          * processes do not double-block trying to recycle
681                          * the same vnode (as an optimization), then get
682                          * the interlock.
683                          */
684                         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
685                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
686
687                         /*
688                          * Skip vnodes that are in the process of being
689                          * held or referenced.  Since the act of adding or
690                          * removing a vnode on the freelist requires a token
691                          * and may block, the ref count may be adjusted
692                          * prior to its addition or removal.
693                          */
694                         if (VSHOULDBUSY(vp)) {
695                                 vp = NULL;
696                                 continue;
697                         }
698
699
700                         /*
701                          * Obtain the vnode interlock and check that the
702                          * vnode is still on the free list.
703                          *
704                          * This normally devolves into a degenerate case so
705                          * it is optimal.   Loop up if it isn't.  Note that
706                          * the vnode could be in the middle of being moved
707                          * off the free list (the VSHOULDBUSY() check) and
708                          * must be skipped if so.
709                          */
710                         lwkt_gettoken(&vlock, vp->v_interlock);
711                         TAILQ_FOREACH_REVERSE(xvp, &vnode_free_list, 
712                             freelst, v_freelist) {
713                                 if (vp == xvp)
714                                         break;
715                         }
716                         if (vp != xvp || VSHOULDBUSY(vp)) {
717                                 vp = NULL;
718                                 continue;
719                         }
720
721                         /*
722                          * We now safely own the vnode.  If the vnode has
723                          * an object do not recycle it if its VM object
724                          * has resident pages or references.
725                          */
726                         if ((VOP_GETVOBJECT(vp, &object) == 0 &&
727                             (object->resident_page_count || object->ref_count))
728                         ) {
729                                 lwkt_reltoken(&vlock);
730                                 vp = NULL;
731                                 continue;
732                         }
733
734                         /*
735                          * We can almost reuse this vnode.  But we don't want
736                          * to recycle it if the vnode has children in the
737                          * namecache because that breaks the namecache's
738                          * path element chain.  (YYY use nc_refs for the
739                          * check?)
740                          */
741                         KKASSERT(vp->v_flag & VFREE);
742                         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
743
744                         if (TAILQ_FIRST(&vp->v_namecache) == NULL ||
745                             cache_leaf_test(vp) >= 0) {
746                                 /* ok, we can reuse this vnode */
747                                 break;
748                         }
749                         lwkt_reltoken(&vlock);
750                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
751                         vp = NULL;
752                 }
753         }
754
755         /*
756          * If vp is non-NULL we hold it's interlock.
757          */
758         if (vp) {
759                 vp->v_flag |= VDOOMED;
760                 vp->v_flag &= ~VFREE;
761                 freevnodes--;
762                 lwkt_reltoken(&ilock);
763                 cache_purge(vp);        /* YYY may block */
764                 vp->v_lease = NULL;
765                 if (vp->v_type != VBAD) {
766                         vgonel(vp, &vlock, td);
767                 } else {
768                         lwkt_reltoken(&vlock);
769                 }
770
771 #ifdef INVARIANTS
772                 {
773                         int s;
774
775                         if (vp->v_data)
776                                 panic("cleaned vnode isn't");
777                         s = splbio();
778                         if (vp->v_numoutput)
779                                 panic("Clean vnode has pending I/O's");
780                         splx(s);
781                 }
782 #endif
783                 vp->v_flag = 0;
784                 vp->v_lastw = 0;
785                 vp->v_lasta = 0;
786                 vp->v_cstart = 0;
787                 vp->v_clen = 0;
788                 vp->v_socket = 0;
789                 vp->v_writecount = 0;   /* XXX */
790         } else {
791                 lwkt_reltoken(&ilock);
792                 vp = zalloc(vnode_zone);
793                 bzero(vp, sizeof(*vp));
794                 vp->v_interlock = lwkt_token_pool_get(vp);
795                 lwkt_token_init(&vp->v_pollinfo.vpi_token);
796                 cache_purge(vp);
797                 TAILQ_INIT(&vp->v_namecache);
798                 numvnodes++;
799         }
800
801         TAILQ_INIT(&vp->v_cleanblkhd);
802         TAILQ_INIT(&vp->v_dirtyblkhd);
803         vp->v_type = VNON;
804         vp->v_tag = tag;
805         vp->v_op = vops;
806         insmntque(vp, mp);
807         *vpp = vp;
808         vp->v_usecount = 1;
809         vp->v_data = 0;
810         splx(s);
811
812         vfs_object_create(vp, td);
813         return (0);
814 }
815
816 /*
817  * Move a vnode from one mount queue to another.
818  */
819 static void
820 insmntque(struct vnode *vp, struct mount *mp)
821 {
822         lwkt_tokref ilock;
823
824         lwkt_gettoken(&ilock, &mntvnode_token);
825         /*
826          * Delete from old mount point vnode list, if on one.
827          */
828         if (vp->v_mount != NULL) {
829                 KASSERT(vp->v_mount->mnt_nvnodelistsize > 0,
830                         ("bad mount point vnode list size"));
831                 TAILQ_REMOVE(&vp->v_mount->mnt_nvnodelist, vp, v_nmntvnodes);
832                 vp->v_mount->mnt_nvnodelistsize--;
833         }
834         /*
835          * Insert into list of vnodes for the new mount point, if available.
836          */
837         if ((vp->v_mount = mp) == NULL) {
838                 lwkt_reltoken(&ilock);
839                 return;
840         }
841         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
842         mp->mnt_nvnodelistsize++;
843         lwkt_reltoken(&ilock);
844 }
845
846 /*
847  * Update outstanding I/O count and do wakeup if requested.
848  */
849 void
850 vwakeup(struct buf *bp)
851 {
852         struct vnode *vp;
853
854         bp->b_flags &= ~B_WRITEINPROG;
855         if ((vp = bp->b_vp)) {
856                 vp->v_numoutput--;
857                 if (vp->v_numoutput < 0)
858                         panic("vwakeup: neg numoutput");
859                 if ((vp->v_numoutput == 0) && (vp->v_flag & VBWAIT)) {
860                         vp->v_flag &= ~VBWAIT;
861                         wakeup((caddr_t) &vp->v_numoutput);
862                 }
863         }
864 }
865
866 /*
867  * Flush out and invalidate all buffers associated with a vnode.
868  * Called with the underlying object locked.
869  */
870 int
871 vinvalbuf(struct vnode *vp, int flags, struct thread *td,
872         int slpflag, int slptimeo)
873 {
874         struct buf *bp;
875         struct buf *nbp, *blist;
876         int s, error;
877         vm_object_t object;
878         lwkt_tokref vlock;
879
880         if (flags & V_SAVE) {
881                 s = splbio();
882                 while (vp->v_numoutput) {
883                         vp->v_flag |= VBWAIT;
884                         error = tsleep((caddr_t)&vp->v_numoutput,
885                             slpflag, "vinvlbuf", slptimeo);
886                         if (error) {
887                                 splx(s);
888                                 return (error);
889                         }
890                 }
891                 if (!TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
892                         splx(s);
893                         if ((error = VOP_FSYNC(vp, MNT_WAIT, td)) != 0)
894                                 return (error);
895                         s = splbio();
896                         if (vp->v_numoutput > 0 ||
897                             !TAILQ_EMPTY(&vp->v_dirtyblkhd))
898                                 panic("vinvalbuf: dirty bufs");
899                 }
900                 splx(s);
901         }
902         s = splbio();
903         for (;;) {
904                 blist = TAILQ_FIRST(&vp->v_cleanblkhd);
905                 if (!blist)
906                         blist = TAILQ_FIRST(&vp->v_dirtyblkhd);
907                 if (!blist)
908                         break;
909
910                 for (bp = blist; bp; bp = nbp) {
911                         nbp = TAILQ_NEXT(bp, b_vnbufs);
912                         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
913                                 error = BUF_TIMELOCK(bp,
914                                     LK_EXCLUSIVE | LK_SLEEPFAIL,
915                                     "vinvalbuf", slpflag, slptimeo);
916                                 if (error == ENOLCK)
917                                         break;
918                                 splx(s);
919                                 return (error);
920                         }
921                         /*
922                          * XXX Since there are no node locks for NFS, I
923                          * believe there is a slight chance that a delayed
924                          * write will occur while sleeping just above, so
925                          * check for it.  Note that vfs_bio_awrite expects
926                          * buffers to reside on a queue, while VOP_BWRITE and
927                          * brelse do not.
928                          */
929                         if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
930                                 (flags & V_SAVE)) {
931
932                                 if (bp->b_vp == vp) {
933                                         if (bp->b_flags & B_CLUSTEROK) {
934                                                 BUF_UNLOCK(bp);
935                                                 vfs_bio_awrite(bp);
936                                         } else {
937                                                 bremfree(bp);
938                                                 bp->b_flags |= B_ASYNC;
939                                                 VOP_BWRITE(bp->b_vp, bp);
940                                         }
941                                 } else {
942                                         bremfree(bp);
943                                         (void) VOP_BWRITE(bp->b_vp, bp);
944                                 }
945                                 break;
946                         }
947                         bremfree(bp);
948                         bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
949                         bp->b_flags &= ~B_ASYNC;
950                         brelse(bp);
951                 }
952         }
953
954         /*
955          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
956          * have write I/O in-progress but if there is a VM object then the
957          * VM object can also have read-I/O in-progress.
958          */
959         do {
960                 while (vp->v_numoutput > 0) {
961                         vp->v_flag |= VBWAIT;
962                         tsleep(&vp->v_numoutput, 0, "vnvlbv", 0);
963                 }
964                 if (VOP_GETVOBJECT(vp, &object) == 0) {
965                         while (object->paging_in_progress)
966                                 vm_object_pip_sleep(object, "vnvlbx");
967                 }
968         } while (vp->v_numoutput > 0);
969
970         splx(s);
971
972         /*
973          * Destroy the copy in the VM cache, too.
974          */
975         lwkt_gettoken(&vlock, vp->v_interlock);
976         if (VOP_GETVOBJECT(vp, &object) == 0) {
977                 vm_object_page_remove(object, 0, 0,
978                         (flags & V_SAVE) ? TRUE : FALSE);
979         }
980         lwkt_reltoken(&vlock);
981
982         if (!TAILQ_EMPTY(&vp->v_dirtyblkhd) || !TAILQ_EMPTY(&vp->v_cleanblkhd))
983                 panic("vinvalbuf: flush failed");
984         return (0);
985 }
986
987 /*
988  * Truncate a file's buffer and pages to a specified length.  This
989  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
990  * sync activity.
991  */
992 int
993 vtruncbuf(struct vnode *vp, struct thread *td, off_t length, int blksize)
994 {
995         struct buf *bp;
996         struct buf *nbp;
997         int s, anyfreed;
998         int trunclbn;
999
1000         /*
1001          * Round up to the *next* lbn.
1002          */
1003         trunclbn = (length + blksize - 1) / blksize;
1004
1005         s = splbio();
1006 restart:
1007         anyfreed = 1;
1008         for (;anyfreed;) {
1009                 anyfreed = 0;
1010                 for (bp = TAILQ_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
1011                         nbp = TAILQ_NEXT(bp, b_vnbufs);
1012                         if (bp->b_lblkno >= trunclbn) {
1013                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
1014                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
1015                                         goto restart;
1016                                 } else {
1017                                         bremfree(bp);
1018                                         bp->b_flags |= (B_INVAL | B_RELBUF);
1019                                         bp->b_flags &= ~B_ASYNC;
1020                                         brelse(bp);
1021                                         anyfreed = 1;
1022                                 }
1023                                 if (nbp &&
1024                                     (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1025                                     (nbp->b_vp != vp) ||
1026                                     (nbp->b_flags & B_DELWRI))) {
1027                                         goto restart;
1028                                 }
1029                         }
1030                 }
1031
1032                 for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
1033                         nbp = TAILQ_NEXT(bp, b_vnbufs);
1034                         if (bp->b_lblkno >= trunclbn) {
1035                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
1036                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
1037                                         goto restart;
1038                                 } else {
1039                                         bremfree(bp);
1040                                         bp->b_flags |= (B_INVAL | B_RELBUF);
1041                                         bp->b_flags &= ~B_ASYNC;
1042                                         brelse(bp);
1043                                         anyfreed = 1;
1044                                 }
1045                                 if (nbp &&
1046                                     (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1047                                     (nbp->b_vp != vp) ||
1048                                     (nbp->b_flags & B_DELWRI) == 0)) {
1049                                         goto restart;
1050                                 }
1051                         }
1052                 }
1053         }
1054
1055         if (length > 0) {
1056 restartsync:
1057                 for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
1058                         nbp = TAILQ_NEXT(bp, b_vnbufs);
1059                         if ((bp->b_flags & B_DELWRI) && (bp->b_lblkno < 0)) {
1060                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
1061                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
1062                                         goto restart;
1063                                 } else {
1064                                         bremfree(bp);
1065                                         if (bp->b_vp == vp) {
1066                                                 bp->b_flags |= B_ASYNC;
1067                                         } else {
1068                                                 bp->b_flags &= ~B_ASYNC;
1069                                         }
1070                                         VOP_BWRITE(bp->b_vp, bp);
1071                                 }
1072                                 goto restartsync;
1073                         }
1074
1075                 }
1076         }
1077
1078         while (vp->v_numoutput > 0) {
1079                 vp->v_flag |= VBWAIT;
1080                 tsleep(&vp->v_numoutput, 0, "vbtrunc", 0);
1081         }
1082
1083         splx(s);
1084
1085         vnode_pager_setsize(vp, length);
1086
1087         return (0);
1088 }
1089
1090 /*
1091  * Associate a buffer with a vnode.
1092  */
1093 void
1094 bgetvp(struct vnode *vp, struct buf *bp)
1095 {
1096         int s;
1097
1098         KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
1099
1100         vhold(vp);
1101         bp->b_vp = vp;
1102         bp->b_dev = vn_todev(vp);
1103         /*
1104          * Insert onto list for new vnode.
1105          */
1106         s = splbio();
1107         bp->b_xflags |= BX_VNCLEAN;
1108         bp->b_xflags &= ~BX_VNDIRTY;
1109         TAILQ_INSERT_TAIL(&vp->v_cleanblkhd, bp, b_vnbufs);
1110         splx(s);
1111 }
1112
1113 /*
1114  * Disassociate a buffer from a vnode.
1115  */
1116 void
1117 brelvp(struct buf *bp)
1118 {
1119         struct vnode *vp;
1120         struct buflists *listheadp;
1121         int s;
1122
1123         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1124
1125         /*
1126          * Delete from old vnode list, if on one.
1127          */
1128         vp = bp->b_vp;
1129         s = splbio();
1130         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
1131                 if (bp->b_xflags & BX_VNDIRTY)
1132                         listheadp = &vp->v_dirtyblkhd;
1133                 else 
1134                         listheadp = &vp->v_cleanblkhd;
1135                 TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1136                 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1137         }
1138         if ((vp->v_flag & VONWORKLST) && TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
1139                 vp->v_flag &= ~VONWORKLST;
1140                 LIST_REMOVE(vp, v_synclist);
1141         }
1142         splx(s);
1143         bp->b_vp = (struct vnode *) 0;
1144         vdrop(vp);
1145 }
1146
1147 /*
1148  * The workitem queue.
1149  * 
1150  * It is useful to delay writes of file data and filesystem metadata
1151  * for tens of seconds so that quickly created and deleted files need
1152  * not waste disk bandwidth being created and removed. To realize this,
1153  * we append vnodes to a "workitem" queue. When running with a soft
1154  * updates implementation, most pending metadata dependencies should
1155  * not wait for more than a few seconds. Thus, mounted on block devices
1156  * are delayed only about a half the time that file data is delayed.
1157  * Similarly, directory updates are more critical, so are only delayed
1158  * about a third the time that file data is delayed. Thus, there are
1159  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
1160  * one each second (driven off the filesystem syncer process). The
1161  * syncer_delayno variable indicates the next queue that is to be processed.
1162  * Items that need to be processed soon are placed in this queue:
1163  *
1164  *      syncer_workitem_pending[syncer_delayno]
1165  *
1166  * A delay of fifteen seconds is done by placing the request fifteen
1167  * entries later in the queue:
1168  *
1169  *      syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
1170  *
1171  */
1172
1173 /*
1174  * Add an item to the syncer work queue.
1175  */
1176 static void
1177 vn_syncer_add_to_worklist(struct vnode *vp, int delay)
1178 {
1179         int s, slot;
1180
1181         s = splbio();
1182
1183         if (vp->v_flag & VONWORKLST) {
1184                 LIST_REMOVE(vp, v_synclist);
1185         }
1186
1187         if (delay > syncer_maxdelay - 2)
1188                 delay = syncer_maxdelay - 2;
1189         slot = (syncer_delayno + delay) & syncer_mask;
1190
1191         LIST_INSERT_HEAD(&syncer_workitem_pending[slot], vp, v_synclist);
1192         vp->v_flag |= VONWORKLST;
1193         splx(s);
1194 }
1195
1196 struct  thread *updatethread;
1197 static void sched_sync (void);
1198 static struct kproc_desc up_kp = {
1199         "syncer",
1200         sched_sync,
1201         &updatethread
1202 };
1203 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
1204
1205 /*
1206  * System filesystem synchronizer daemon.
1207  */
1208 void 
1209 sched_sync(void)
1210 {
1211         struct synclist *slp;
1212         struct vnode *vp;
1213         long starttime;
1214         int s;
1215         struct thread *td = curthread;
1216
1217         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, td,
1218             SHUTDOWN_PRI_LAST);   
1219
1220         for (;;) {
1221                 kproc_suspend_loop();
1222
1223                 starttime = time_second;
1224
1225                 /*
1226                  * Push files whose dirty time has expired.  Be careful
1227                  * of interrupt race on slp queue.
1228                  */
1229                 s = splbio();
1230                 slp = &syncer_workitem_pending[syncer_delayno];
1231                 syncer_delayno += 1;
1232                 if (syncer_delayno == syncer_maxdelay)
1233                         syncer_delayno = 0;
1234                 splx(s);
1235
1236                 while ((vp = LIST_FIRST(slp)) != NULL) {
1237                         if (VOP_ISLOCKED(vp, NULL) == 0) {
1238                                 vn_lock(vp, NULL, LK_EXCLUSIVE | LK_RETRY, td);
1239                                 (void) VOP_FSYNC(vp, MNT_LAZY, td);
1240                                 VOP_UNLOCK(vp, NULL, 0, td);
1241                         }
1242                         s = splbio();
1243                         if (LIST_FIRST(slp) == vp) {
1244                                 /*
1245                                  * Note: v_tag VT_VFS vps can remain on the
1246                                  * worklist too with no dirty blocks, but 
1247                                  * since sync_fsync() moves it to a different 
1248                                  * slot we are safe.
1249                                  */
1250                                 if (TAILQ_EMPTY(&vp->v_dirtyblkhd) &&
1251                                     !vn_isdisk(vp, NULL))
1252                                         panic("sched_sync: fsync failed vp %p tag %d", vp, vp->v_tag);
1253                                 /*
1254                                  * Put us back on the worklist.  The worklist
1255                                  * routine will remove us from our current
1256                                  * position and then add us back in at a later
1257                                  * position.
1258                                  */
1259                                 vn_syncer_add_to_worklist(vp, syncdelay);
1260                         }
1261                         splx(s);
1262                 }
1263
1264                 /*
1265                  * Do soft update processing.
1266                  */
1267                 if (bioops.io_sync)
1268                         (*bioops.io_sync)(NULL);
1269
1270                 /*
1271                  * The variable rushjob allows the kernel to speed up the
1272                  * processing of the filesystem syncer process. A rushjob
1273                  * value of N tells the filesystem syncer to process the next
1274                  * N seconds worth of work on its queue ASAP. Currently rushjob
1275                  * is used by the soft update code to speed up the filesystem
1276                  * syncer process when the incore state is getting so far
1277                  * ahead of the disk that the kernel memory pool is being
1278                  * threatened with exhaustion.
1279                  */
1280                 if (rushjob > 0) {
1281                         rushjob -= 1;
1282                         continue;
1283                 }
1284                 /*
1285                  * If it has taken us less than a second to process the
1286                  * current work, then wait. Otherwise start right over
1287                  * again. We can still lose time if any single round
1288                  * takes more than two seconds, but it does not really
1289                  * matter as we are just trying to generally pace the
1290                  * filesystem activity.
1291                  */
1292                 if (time_second == starttime)
1293                         tsleep(&lbolt, 0, "syncer", 0);
1294         }
1295 }
1296
1297 /*
1298  * Request the syncer daemon to speed up its work.
1299  * We never push it to speed up more than half of its
1300  * normal turn time, otherwise it could take over the cpu.
1301  *
1302  * YYY wchan field protected by the BGL.
1303  */
1304 int
1305 speedup_syncer(void)
1306 {
1307         crit_enter();
1308         if (updatethread->td_wchan == &lbolt) { /* YYY */
1309                 unsleep(updatethread);
1310                 lwkt_schedule(updatethread);
1311         }
1312         crit_exit();
1313         if (rushjob < syncdelay / 2) {
1314                 rushjob += 1;
1315                 stat_rush_requests += 1;
1316                 return (1);
1317         }
1318         return(0);
1319 }
1320
1321 /*
1322  * Associate a p-buffer with a vnode.
1323  *
1324  * Also sets B_PAGING flag to indicate that vnode is not fully associated
1325  * with the buffer.  i.e. the bp has not been linked into the vnode or
1326  * ref-counted.
1327  */
1328 void
1329 pbgetvp(struct vnode *vp, struct buf *bp)
1330 {
1331         KASSERT(bp->b_vp == NULL, ("pbgetvp: not free"));
1332
1333         bp->b_vp = vp;
1334         bp->b_flags |= B_PAGING;
1335         bp->b_dev = vn_todev(vp);
1336 }
1337
1338 /*
1339  * Disassociate a p-buffer from a vnode.
1340  */
1341 void
1342 pbrelvp(struct buf *bp)
1343 {
1344         KASSERT(bp->b_vp != NULL, ("pbrelvp: NULL"));
1345
1346         /* XXX REMOVE ME */
1347         if (TAILQ_NEXT(bp, b_vnbufs) != NULL) {
1348                 panic(
1349                     "relpbuf(): b_vp was probably reassignbuf()d %p %x", 
1350                     bp,
1351                     (int)bp->b_flags
1352                 );
1353         }
1354         bp->b_vp = (struct vnode *) 0;
1355         bp->b_flags &= ~B_PAGING;
1356 }
1357
1358 void
1359 pbreassignbuf(struct buf *bp, struct vnode *newvp)
1360 {
1361         if ((bp->b_flags & B_PAGING) == 0) {
1362                 panic(
1363                     "pbreassignbuf() on non phys bp %p", 
1364                     bp
1365                 );
1366         }
1367         bp->b_vp = newvp;
1368 }
1369
1370 /*
1371  * Reassign a buffer from one vnode to another.
1372  * Used to assign file specific control information
1373  * (indirect blocks) to the vnode to which they belong.
1374  */
1375 void
1376 reassignbuf(struct buf *bp, struct vnode *newvp)
1377 {
1378         struct buflists *listheadp;
1379         int delay;
1380         int s;
1381
1382         if (newvp == NULL) {
1383                 printf("reassignbuf: NULL");
1384                 return;
1385         }
1386         ++reassignbufcalls;
1387
1388         /*
1389          * B_PAGING flagged buffers cannot be reassigned because their vp
1390          * is not fully linked in.
1391          */
1392         if (bp->b_flags & B_PAGING)
1393                 panic("cannot reassign paging buffer");
1394
1395         s = splbio();
1396         /*
1397          * Delete from old vnode list, if on one.
1398          */
1399         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
1400                 if (bp->b_xflags & BX_VNDIRTY)
1401                         listheadp = &bp->b_vp->v_dirtyblkhd;
1402                 else 
1403                         listheadp = &bp->b_vp->v_cleanblkhd;
1404                 TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1405                 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1406                 if (bp->b_vp != newvp) {
1407                         vdrop(bp->b_vp);
1408                         bp->b_vp = NULL;        /* for clarification */
1409                 }
1410         }
1411         /*
1412          * If dirty, put on list of dirty buffers; otherwise insert onto list
1413          * of clean buffers.
1414          */
1415         if (bp->b_flags & B_DELWRI) {
1416                 struct buf *tbp;
1417
1418                 listheadp = &newvp->v_dirtyblkhd;
1419                 if ((newvp->v_flag & VONWORKLST) == 0) {
1420                         switch (newvp->v_type) {
1421                         case VDIR:
1422                                 delay = dirdelay;
1423                                 break;
1424                         case VCHR:
1425                         case VBLK:
1426                                 if (newvp->v_rdev && 
1427                                     newvp->v_rdev->si_mountpoint != NULL) {
1428                                         delay = metadelay;
1429                                         break;
1430                                 }
1431                                 /* fall through */
1432                         default:
1433                                 delay = filedelay;
1434                         }
1435                         vn_syncer_add_to_worklist(newvp, delay);
1436                 }
1437                 bp->b_xflags |= BX_VNDIRTY;
1438                 tbp = TAILQ_FIRST(listheadp);
1439                 if (tbp == NULL ||
1440                     bp->b_lblkno == 0 ||
1441                     (bp->b_lblkno > 0 && tbp->b_lblkno < 0) ||
1442                     (bp->b_lblkno > 0 && bp->b_lblkno < tbp->b_lblkno)) {
1443                         TAILQ_INSERT_HEAD(listheadp, bp, b_vnbufs);
1444                         ++reassignbufsortgood;
1445                 } else if (bp->b_lblkno < 0) {
1446                         TAILQ_INSERT_TAIL(listheadp, bp, b_vnbufs);
1447                         ++reassignbufsortgood;
1448                 } else if (reassignbufmethod == 1) {
1449                         /*
1450                          * New sorting algorithm, only handle sequential case,
1451                          * otherwise append to end (but before metadata)
1452                          */
1453                         if ((tbp = gbincore(newvp, bp->b_lblkno - 1)) != NULL &&
1454                             (tbp->b_xflags & BX_VNDIRTY)) {
1455                                 /*
1456                                  * Found the best place to insert the buffer
1457                                  */
1458                                 TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1459                                 ++reassignbufsortgood;
1460                         } else {
1461                                 /*
1462                                  * Missed, append to end, but before meta-data.
1463                                  * We know that the head buffer in the list is
1464                                  * not meta-data due to prior conditionals.
1465                                  *
1466                                  * Indirect effects:  NFS second stage write
1467                                  * tends to wind up here, giving maximum 
1468                                  * distance between the unstable write and the
1469                                  * commit rpc.
1470                                  */
1471                                 tbp = TAILQ_LAST(listheadp, buflists);
1472                                 while (tbp && tbp->b_lblkno < 0)
1473                                         tbp = TAILQ_PREV(tbp, buflists, b_vnbufs);
1474                                 TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1475                                 ++reassignbufsortbad;
1476                         }
1477                 } else {
1478                         /*
1479                          * Old sorting algorithm, scan queue and insert
1480                          */
1481                         struct buf *ttbp;
1482                         while ((ttbp = TAILQ_NEXT(tbp, b_vnbufs)) &&
1483                             (ttbp->b_lblkno < bp->b_lblkno)) {
1484                                 ++reassignbufloops;
1485                                 tbp = ttbp;
1486                         }
1487                         TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1488                 }
1489         } else {
1490                 bp->b_xflags |= BX_VNCLEAN;
1491                 TAILQ_INSERT_TAIL(&newvp->v_cleanblkhd, bp, b_vnbufs);
1492                 if ((newvp->v_flag & VONWORKLST) &&
1493                     TAILQ_EMPTY(&newvp->v_dirtyblkhd)) {
1494                         newvp->v_flag &= ~VONWORKLST;
1495                         LIST_REMOVE(newvp, v_synclist);
1496                 }
1497         }
1498         if (bp->b_vp != newvp) {
1499                 bp->b_vp = newvp;
1500                 vhold(bp->b_vp);
1501         }
1502         splx(s);
1503 }
1504
1505 /*
1506  * Create a vnode for a block device.
1507  * Used for mounting the root file system.
1508  */
1509 int
1510 bdevvp(dev_t dev, struct vnode **vpp)
1511 {
1512         struct vnode *vp;
1513         struct vnode *nvp;
1514         int error;
1515
1516         if (dev == NODEV) {
1517                 *vpp = NULLVP;
1518                 return (ENXIO);
1519         }
1520         error = getnewvnode(VT_NON, (struct mount *)0, spec_vnodeop_p, &nvp);
1521         if (error) {
1522                 *vpp = NULLVP;
1523                 return (error);
1524         }
1525         vp = nvp;
1526         vp->v_type = VCHR;
1527         vp->v_udev = dev->si_udev;
1528         *vpp = vp;
1529         return (0);
1530 }
1531
1532 int
1533 v_associate_rdev(struct vnode *vp, dev_t dev)
1534 {
1535         lwkt_tokref ilock;
1536
1537         if (dev == NULL || dev == NODEV)
1538                 return(ENXIO);
1539         if (dev_is_good(dev) == 0)
1540                 return(ENXIO);
1541         KKASSERT(vp->v_rdev == NULL);
1542         if (dev_ref_debug)
1543                 printf("Z1");
1544         vp->v_rdev = reference_dev(dev);
1545         lwkt_gettoken(&ilock, &spechash_token);
1546         SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_specnext);
1547         lwkt_reltoken(&ilock);
1548         return(0);
1549 }
1550
1551 void
1552 v_release_rdev(struct vnode *vp)
1553 {
1554         lwkt_tokref ilock;
1555         dev_t dev;
1556
1557         if ((dev = vp->v_rdev) != NULL) {
1558                 lwkt_gettoken(&ilock, &spechash_token);
1559                 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_specnext);
1560                 if (dev_ref_debug && vp->v_opencount != 0) {
1561                         printf("releasing rdev with non-0 "
1562                                 "v_opencount(%d) (revoked?)\n",
1563                                 vp->v_opencount);
1564                 }
1565                 vp->v_rdev = NULL;
1566                 vp->v_opencount = 0;
1567                 release_dev(dev);
1568                 lwkt_reltoken(&ilock);
1569         }
1570 }
1571
1572 /*
1573  * Add a vnode to the alias list hung off the dev_t.  We only associate
1574  * the device number with the vnode.  The actual device is not associated
1575  * until the vnode is opened (usually in spec_open()), and will be 
1576  * disassociated on last close.
1577  */
1578 void
1579 addaliasu(struct vnode *nvp, udev_t nvp_udev)
1580 {
1581         if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1582                 panic("addaliasu on non-special vnode");
1583         nvp->v_udev = nvp_udev;
1584 }
1585
1586 /*
1587  * Grab a particular vnode from the free list, increment its
1588  * reference count and lock it. The vnode lock bit is set if the
1589  * vnode is being eliminated in vgone. The process is awakened
1590  * when the transition is completed, and an error returned to
1591  * indicate that the vnode is no longer usable (possibly having
1592  * been changed to a new file system type).
1593  *
1594  * This code is very sensitive.  We are depending on the vnode interlock
1595  * to be maintained through to the vn_lock() call, which means that we
1596  * cannot block which means that we cannot call vbusy() until after vn_lock().
1597  * If the interlock is not maintained, the VXLOCK check will not properly
1598  * interlock against a vclean()'s LK_DRAIN operation on the lock.
1599  */
1600 int
1601 vget(struct vnode *vp, lwkt_tokref_t vlock, int flags, thread_t td)
1602 {
1603         int error;
1604         lwkt_tokref vvlock;
1605
1606         /*
1607          * We need the interlock to safely modify the v_ fields.  ZZZ it is
1608          * only legal to pass (1) the vnode's interlock and (2) only pass
1609          * NULL w/o LK_INTERLOCK if the vnode is *ALREADY* referenced or
1610          * held.
1611          */
1612         if ((flags & LK_INTERLOCK) == 0) {
1613                 lwkt_gettoken(&vvlock, vp->v_interlock);
1614                 vlock = &vvlock;
1615         }
1616
1617         /*
1618          * If the vnode is in the process of being cleaned out for
1619          * another use, we wait for the cleaning to finish and then
1620          * return failure. Cleaning is determined by checking that
1621          * the VXLOCK flag is set.  It is possible for the vnode to be
1622          * self-referenced during the cleaning operation.
1623          */
1624         if (vp->v_flag & VXLOCK) {
1625                 if (vp->v_vxthread == curthread) {
1626 #if 0
1627                         /* this can now occur in normal operation */
1628                         log(LOG_INFO, "VXLOCK interlock avoided\n");
1629 #endif
1630                 } else {
1631                         vp->v_flag |= VXWANT;
1632                         lwkt_reltoken(vlock);
1633                         tsleep((caddr_t)vp, 0, "vget", 0);
1634                         return (ENOENT);
1635                 }
1636         }
1637
1638         /*
1639          * Bump v_usecount to prevent the vnode from being recycled.  The
1640          * usecount needs to be bumped before we successfully get our lock.
1641          */
1642         vp->v_usecount++;
1643         if (flags & LK_TYPE_MASK) {
1644                 if ((error = vn_lock(vp, vlock, flags | LK_INTERLOCK, td)) != 0) {
1645                         /*
1646                          * must expand vrele here because we do not want
1647                          * to call VOP_INACTIVE if the reference count
1648                          * drops back to zero since it was never really
1649                          * active. We must remove it from the free list
1650                          * before sleeping so that multiple processes do
1651                          * not try to recycle it.
1652                          */
1653                         lwkt_gettokref(vlock);
1654                         vp->v_usecount--;
1655                         vmaybefree(vp);
1656                         lwkt_reltoken(vlock);
1657                 }
1658                 return (error);
1659         }
1660         if (VSHOULDBUSY(vp))
1661                 vbusy(vp);      /* interlock must be held on call */
1662         lwkt_reltoken(vlock);
1663         return (0);
1664 }
1665
1666 void
1667 vref(struct vnode *vp)
1668 {
1669         crit_enter();   /* YYY use crit section for moment / BGL protected */
1670         vp->v_usecount++;
1671         crit_exit();
1672 }
1673
1674 /*
1675  * Vnode put/release.
1676  * If count drops to zero, call inactive routine and return to freelist.
1677  */
1678 void
1679 vrele(struct vnode *vp)
1680 {
1681         struct thread *td = curthread;  /* XXX */
1682         lwkt_tokref vlock;
1683
1684         KASSERT(vp != NULL && vp->v_usecount >= 0,
1685             ("vrele: null vp or <=0 v_usecount"));
1686
1687         lwkt_gettoken(&vlock, vp->v_interlock);
1688
1689         if (vp->v_usecount > 1) {
1690                 vp->v_usecount--;
1691                 lwkt_reltoken(&vlock);
1692                 return;
1693         }
1694
1695         if (vp->v_usecount == 1) {
1696                 vp->v_usecount--;
1697                 /*
1698                  * We must call VOP_INACTIVE with the node locked and the
1699                  * usecount 0.  If we are doing a vpu, the node is already
1700                  * locked, but, in the case of vrele, we must explicitly lock
1701                  * the vnode before calling VOP_INACTIVE.
1702                  */
1703
1704                 if (vn_lock(vp, NULL, LK_EXCLUSIVE, td) == 0)
1705                         VOP_INACTIVE(vp, td);
1706                 vmaybefree(vp);
1707                 lwkt_reltoken(&vlock);
1708         } else {
1709 #ifdef DIAGNOSTIC
1710                 vprint("vrele: negative ref count", vp);
1711 #endif
1712                 lwkt_reltoken(&vlock);
1713                 panic("vrele: negative ref cnt");
1714         }
1715 }
1716
1717 void
1718 vput(struct vnode *vp)
1719 {
1720         struct thread *td = curthread;  /* XXX */
1721         lwkt_tokref vlock;
1722
1723         KASSERT(vp != NULL, ("vput: null vp"));
1724
1725         lwkt_gettoken(&vlock, vp->v_interlock);
1726
1727         if (vp->v_usecount > 1) {
1728                 vp->v_usecount--;
1729                 VOP_UNLOCK(vp, &vlock, LK_INTERLOCK, td);
1730                 return;
1731         }
1732
1733         if (vp->v_usecount == 1) {
1734                 vp->v_usecount--;
1735                 /*
1736                  * We must call VOP_INACTIVE with the node locked.
1737                  * If we are doing a vpu, the node is already locked,
1738                  * so we just need to release the vnode mutex.
1739                  */
1740                 VOP_INACTIVE(vp, td);
1741                 vmaybefree(vp);
1742                 lwkt_reltoken(&vlock);
1743         } else {
1744 #ifdef DIAGNOSTIC
1745                 vprint("vput: negative ref count", vp);
1746 #endif
1747                 lwkt_reltoken(&vlock);
1748                 panic("vput: negative ref cnt");
1749         }
1750 }
1751
1752 /*
1753  * Somebody doesn't want the vnode recycled. ZZZ vnode interlock should
1754  * be held but isn't.
1755  */
1756 void
1757 vhold(struct vnode *vp)
1758 {
1759         int s;
1760
1761         s = splbio();
1762         vp->v_holdcnt++;
1763         if (VSHOULDBUSY(vp))
1764                 vbusy(vp);      /* interlock must be held on call */
1765         splx(s);
1766 }
1767
1768 /*
1769  * One less who cares about this vnode.
1770  */
1771 void
1772 vdrop(struct vnode *vp)
1773 {
1774         lwkt_tokref vlock;
1775
1776         lwkt_gettoken(&vlock, vp->v_interlock);
1777         if (vp->v_holdcnt <= 0)
1778                 panic("vdrop: holdcnt");
1779         vp->v_holdcnt--;
1780         vmaybefree(vp);
1781         lwkt_reltoken(&vlock);
1782 }
1783
1784 int
1785 vmntvnodescan(
1786     struct mount *mp, 
1787     int (*fastfunc)(struct mount *mp, struct vnode *vp, void *data),
1788     int (*slowfunc)(struct mount *mp, struct vnode *vp, 
1789                     lwkt_tokref_t vlock, void *data),
1790     void *data
1791 ) {
1792         lwkt_tokref ilock;
1793         lwkt_tokref vlock;
1794         struct vnode *pvp;
1795         struct vnode *vp;
1796         int r = 0;
1797
1798         /*
1799          * Scan the vnodes on the mount's vnode list.  Use a placemarker
1800          */
1801         pvp = zalloc(vnode_zone);
1802         pvp->v_flag |= VPLACEMARKER;
1803
1804         lwkt_gettoken(&ilock, &mntvnode_token);
1805         TAILQ_INSERT_HEAD(&mp->mnt_nvnodelist, pvp, v_nmntvnodes);
1806
1807         while ((vp = TAILQ_NEXT(pvp, v_nmntvnodes)) != NULL) {
1808                 /*
1809                  * Move the placemarker and skip other placemarkers we
1810                  * encounter.  The nothing can get in our way so the
1811                  * mount point on the vp must be valid.
1812                  */
1813                 TAILQ_REMOVE(&mp->mnt_nvnodelist, pvp, v_nmntvnodes);
1814                 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, pvp, v_nmntvnodes);
1815                 if (vp->v_flag & VPLACEMARKER)
1816                         continue;
1817                 KKASSERT(vp->v_mount == mp);
1818
1819                 /*
1820                  * Quick test
1821                  */
1822                 if (fastfunc) {
1823                         if ((r = fastfunc(mp, vp, data)) < 0)
1824                                 continue;
1825                         if (r)
1826                                 break;
1827                 }
1828
1829                 /*
1830                  * Get the vnodes interlock and make sure it is still on the
1831                  * mount list.  Skip it if it has moved (we may encounter it
1832                  * later).  Then do the with-interlock test.  The callback
1833                  * is responsible for releasing the vnode interlock.
1834                  *
1835                  * The interlock is type-stable.
1836                  */
1837                 if (slowfunc) {
1838                         lwkt_gettoken(&vlock, vp->v_interlock);
1839                         if (vp != TAILQ_PREV(pvp, vnodelst, v_nmntvnodes)) {
1840                                 printf("vmntvnodescan (debug info only): f=%p vp=%p vnode ripped out from under us\n", slowfunc, vp);
1841                                 lwkt_reltoken(&vlock);
1842                                 continue;
1843                         }
1844                         if ((r = slowfunc(mp, vp, &vlock, data)) != 0) {
1845                                 KKASSERT(lwkt_havetokref(&vlock) == 0);
1846                                 break;
1847                         }
1848                         KKASSERT(lwkt_havetokref(&vlock) == 0);
1849                 }
1850         }
1851         TAILQ_REMOVE(&mp->mnt_nvnodelist, pvp, v_nmntvnodes);
1852         zfree(vnode_zone, pvp);
1853         lwkt_reltoken(&ilock);
1854         return(r);
1855 }
1856
1857 /*
1858  * Remove any vnodes in the vnode table belonging to mount point mp.
1859  *
1860  * If FORCECLOSE is not specified, there should not be any active ones,
1861  * return error if any are found (nb: this is a user error, not a
1862  * system error). If FORCECLOSE is specified, detach any active vnodes
1863  * that are found.
1864  *
1865  * If WRITECLOSE is set, only flush out regular file vnodes open for
1866  * writing.
1867  *
1868  * SKIPSYSTEM causes any vnodes marked VSYSTEM to be skipped.
1869  *
1870  * `rootrefs' specifies the base reference count for the root vnode
1871  * of this filesystem. The root vnode is considered busy if its
1872  * v_usecount exceeds this value. On a successful return, vflush()
1873  * will call vrele() on the root vnode exactly rootrefs times.
1874  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
1875  * be zero.
1876  */
1877 #ifdef DIAGNOSTIC
1878 static int busyprt = 0;         /* print out busy vnodes */
1879 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
1880 #endif
1881
1882 static int vflush_scan(struct mount *mp, struct vnode *vp,
1883                         lwkt_tokref_t vlock, void *data);
1884
1885 struct vflush_info {
1886         int flags;
1887         int busy;
1888         thread_t td;
1889 };
1890
1891 int
1892 vflush(struct mount *mp, int rootrefs, int flags)
1893 {
1894         struct thread *td = curthread;  /* XXX */
1895         struct vnode *rootvp = NULL;
1896         int error;
1897         lwkt_tokref vlock;
1898         struct vflush_info vflush_info;
1899
1900         if (rootrefs > 0) {
1901                 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
1902                     ("vflush: bad args"));
1903                 /*
1904                  * Get the filesystem root vnode. We can vput() it
1905                  * immediately, since with rootrefs > 0, it won't go away.
1906                  */
1907                 if ((error = VFS_ROOT(mp, &rootvp)) != 0)
1908                         return (error);
1909                 vput(rootvp);
1910         }
1911
1912         vflush_info.busy = 0;
1913         vflush_info.flags = flags;
1914         vflush_info.td = td;
1915         vmntvnodescan(mp, NULL, vflush_scan, &vflush_info);
1916
1917         if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
1918                 /*
1919                  * If just the root vnode is busy, and if its refcount
1920                  * is equal to `rootrefs', then go ahead and kill it.
1921                  */
1922                 lwkt_gettoken(&vlock, rootvp->v_interlock);
1923                 KASSERT(vflush_info.busy > 0, ("vflush: not busy"));
1924                 KASSERT(rootvp->v_usecount >= rootrefs, ("vflush: rootrefs"));
1925                 if (vflush_info.busy == 1 && rootvp->v_usecount == rootrefs) {
1926                         vgonel(rootvp, &vlock, td);
1927                         vflush_info.busy = 0;
1928                 } else {
1929                         lwkt_reltoken(&vlock);
1930                 }
1931         }
1932         if (vflush_info.busy)
1933                 return (EBUSY);
1934         for (; rootrefs > 0; rootrefs--)
1935                 vrele(rootvp);
1936         return (0);
1937 }
1938
1939 /*
1940  * The scan callback is made with an interlocked vnode.
1941  */
1942 static int
1943 vflush_scan(struct mount *mp, struct vnode *vp,
1944             lwkt_tokref_t vlock, void *data)
1945 {
1946         struct vflush_info *info = data;
1947         struct vattr vattr;
1948
1949         /*
1950          * Skip over a vnodes marked VSYSTEM.
1951          */
1952         if ((info->flags & SKIPSYSTEM) && (vp->v_flag & VSYSTEM)) {
1953                 lwkt_reltoken(vlock);
1954                 return(0);
1955         }
1956
1957         /*
1958          * If WRITECLOSE is set, flush out unlinked but still open
1959          * files (even if open only for reading) and regular file
1960          * vnodes open for writing. 
1961          */
1962         if ((info->flags & WRITECLOSE) &&
1963             (vp->v_type == VNON ||
1964             (VOP_GETATTR(vp, &vattr, info->td) == 0 &&
1965             vattr.va_nlink > 0)) &&
1966             (vp->v_writecount == 0 || vp->v_type != VREG)) {
1967                 lwkt_reltoken(vlock);
1968                 return(0);
1969         }
1970
1971         /*
1972          * With v_usecount == 0, all we need to do is clear out the
1973          * vnode data structures and we are done.
1974          */
1975         if (vp->v_usecount == 0) {
1976                 vgonel(vp, vlock, info->td);
1977                 return(0);
1978         }
1979
1980         /*
1981          * If FORCECLOSE is set, forcibly close the vnode. For block
1982          * or character devices, revert to an anonymous device. For
1983          * all other files, just kill them.
1984          */
1985         if (info->flags & FORCECLOSE) {
1986                 if (vp->v_type != VBLK && vp->v_type != VCHR) {
1987                         vgonel(vp, vlock, info->td);
1988                 } else {
1989                         vclean(vp, vlock, 0, info->td);
1990                         vp->v_op = spec_vnodeop_p;
1991                         insmntque(vp, (struct mount *) 0);
1992                 }
1993                 return(0);
1994         }
1995 #ifdef DIAGNOSTIC
1996         if (busyprt)
1997                 vprint("vflush: busy vnode", vp);
1998 #endif
1999         lwkt_reltoken(vlock);
2000         ++info->busy;
2001         return(0);
2002 }
2003
2004 /*
2005  * Disassociate the underlying file system from a vnode.
2006  */
2007 static void
2008 vclean(struct vnode *vp, lwkt_tokref_t vlock, int flags, struct thread *td)
2009 {
2010         int active;
2011
2012         /*
2013          * Check to see if the vnode is in use. If so we have to reference it
2014          * before we clean it out so that its count cannot fall to zero and
2015          * generate a race against ourselves to recycle it.
2016          */
2017         if ((active = vp->v_usecount))
2018                 vp->v_usecount++;
2019
2020         /*
2021          * Prevent the vnode from being recycled or brought into use while we
2022          * clean it out.
2023          */
2024         if (vp->v_flag & VXLOCK)
2025                 panic("vclean: deadlock");
2026         vp->v_flag |= VXLOCK;
2027         vp->v_vxthread = curthread;
2028
2029         /*
2030          * Even if the count is zero, the VOP_INACTIVE routine may still
2031          * have the object locked while it cleans it out. The VOP_LOCK
2032          * ensures that the VOP_INACTIVE routine is done with its work.
2033          * For active vnodes, it ensures that no other activity can
2034          * occur while the underlying object is being cleaned out.
2035          *
2036          * NOTE: we continue to hold the vnode interlock through to the
2037          * end of vclean().
2038          */
2039         VOP_LOCK(vp, NULL, LK_DRAIN, td);
2040
2041         /*
2042          * Clean out any buffers associated with the vnode.
2043          */
2044         vinvalbuf(vp, V_SAVE, td, 0, 0);
2045         VOP_DESTROYVOBJECT(vp);
2046
2047         /*
2048          * If purging an active vnode, it must be closed and
2049          * deactivated before being reclaimed. Note that the
2050          * VOP_INACTIVE will unlock the vnode.
2051          */
2052         if (active) {
2053                 if (flags & DOCLOSE)
2054                         VOP_CLOSE(vp, FNONBLOCK, td);
2055                 VOP_INACTIVE(vp, td);
2056         } else {
2057                 /*
2058                  * Any other processes trying to obtain this lock must first
2059                  * wait for VXLOCK to clear, then call the new lock operation.
2060                  */
2061                 VOP_UNLOCK(vp, NULL, 0, td);
2062         }
2063         /*
2064          * Reclaim the vnode.
2065          */
2066         if (VOP_RECLAIM(vp, td))
2067                 panic("vclean: cannot reclaim");
2068
2069         if (active) {
2070                 /*
2071                  * Inline copy of vrele() since VOP_INACTIVE
2072                  * has already been called.
2073                  */
2074                 if (--vp->v_usecount <= 0) {
2075 #ifdef DIAGNOSTIC
2076                         if (vp->v_usecount < 0 || vp->v_writecount != 0) {
2077                                 vprint("vclean: bad ref count", vp);
2078                                 panic("vclean: ref cnt");
2079                         }
2080 #endif
2081                         vfree(vp);
2082                 }
2083         }
2084
2085         cache_purge(vp);
2086         vp->v_vnlock = NULL;
2087         vmaybefree(vp);
2088         
2089         /*
2090          * Done with purge, notify sleepers of the grim news.
2091          */
2092         vp->v_op = dead_vnodeop_p;
2093         vn_pollgone(vp);
2094         vp->v_tag = VT_NON;
2095         vp->v_flag &= ~VXLOCK;
2096         vp->v_vxthread = NULL;
2097         if (vp->v_flag & VXWANT) {
2098                 vp->v_flag &= ~VXWANT;
2099                 wakeup((caddr_t) vp);
2100         }
2101         lwkt_reltoken(vlock);
2102 }
2103
2104 /*
2105  * Eliminate all activity associated with the requested vnode
2106  * and with all vnodes aliased to the requested vnode.
2107  *
2108  * revoke { struct vnode *a_vp, int a_flags }
2109  */
2110 int
2111 vop_revoke(struct vop_revoke_args *ap)
2112 {
2113         struct vnode *vp, *vq;
2114         lwkt_tokref ilock;
2115         dev_t dev;
2116
2117         KASSERT((ap->a_flags & REVOKEALL) != 0, ("vop_revoke"));
2118
2119         vp = ap->a_vp;
2120         /*
2121          * If a vgone (or vclean) is already in progress,
2122          * wait until it is done and return.
2123          */
2124         if (vp->v_flag & VXLOCK) {
2125                 vp->v_flag |= VXWANT;
2126                 /*lwkt_reltoken(vlock); ZZZ */
2127                 tsleep((caddr_t)vp, 0, "vop_revokeall", 0);
2128                 return (0);
2129         }
2130
2131         /*
2132          * If the vnode has a device association, scrap all vnodes associated
2133          * with the device.  Don't let the device disappear on us while we
2134          * are scrapping the vnodes.
2135          */
2136         if (vp->v_type != VCHR && vp->v_type != VBLK)
2137                 return(0);
2138         if ((dev = vp->v_rdev) == NULL) {
2139                 if ((dev = udev2dev(vp->v_udev, vp->v_type == VBLK)) == NODEV)
2140                         return(0);
2141         }
2142         reference_dev(dev);
2143         for (;;) {
2144                 lwkt_gettoken(&ilock, &spechash_token);
2145                 vq = SLIST_FIRST(&dev->si_hlist);
2146                 lwkt_reltoken(&ilock);
2147                 if (vq == NULL)
2148                         break;
2149                 vgone(vq);
2150         }
2151         release_dev(dev);
2152         return (0);
2153 }
2154
2155 /*
2156  * Recycle an unused vnode to the front of the free list.
2157  * Release the passed interlock if the vnode will be recycled.
2158  */
2159 int
2160 vrecycle(struct vnode *vp, lwkt_tokref_t inter_lkp, struct thread *td)
2161 {
2162         lwkt_tokref vlock;
2163
2164         lwkt_gettoken(&vlock, vp->v_interlock);
2165         if (vp->v_usecount == 0) {
2166                 if (inter_lkp)
2167                         lwkt_reltoken(inter_lkp);
2168                 vgonel(vp, &vlock, td);
2169                 return (1);
2170         }
2171         lwkt_reltoken(&vlock);
2172         return (0);
2173 }
2174
2175 /*
2176  * Eliminate all activity associated with a vnode
2177  * in preparation for reuse.
2178  */
2179 void
2180 vgone(struct vnode *vp)
2181 {
2182         struct thread *td = curthread;  /* XXX */
2183         lwkt_tokref vlock;
2184
2185         lwkt_gettoken(&vlock, vp->v_interlock);
2186         vgonel(vp, &vlock, td);
2187 }
2188
2189 /*
2190  * vgone, with the vp interlock held.
2191  */
2192 void
2193 vgonel(struct vnode *vp, lwkt_tokref_t vlock, struct thread *td)
2194 {
2195         lwkt_tokref ilock;
2196         int s;
2197
2198         /*
2199          * If a vgone (or vclean) is already in progress,
2200          * wait until it is done and return.
2201          */
2202         if (vp->v_flag & VXLOCK) {
2203                 vp->v_flag |= VXWANT;
2204                 lwkt_reltoken(vlock);
2205                 tsleep((caddr_t)vp, 0, "vgone", 0);
2206                 return;
2207         }
2208
2209         /*
2210          * Clean out the filesystem specific data.
2211          */
2212         vclean(vp, vlock, DOCLOSE, td);
2213         lwkt_gettokref(vlock);
2214
2215         /*
2216          * Delete from old mount point vnode list, if on one.
2217          */
2218         if (vp->v_mount != NULL)
2219                 insmntque(vp, (struct mount *)0);
2220
2221         /*
2222          * If special device, remove it from special device alias list
2223          * if it is on one.  This should normally only occur if a vnode is
2224          * being revoked as the device should otherwise have been released
2225          * naturally.
2226          */
2227         if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
2228                 v_release_rdev(vp);
2229         }
2230
2231         /*
2232          * If it is on the freelist and not already at the head,
2233          * move it to the head of the list. The test of the
2234          * VDOOMED flag and the reference count of zero is because
2235          * it will be removed from the free list by getnewvnode,
2236          * but will not have its reference count incremented until
2237          * after calling vgone. If the reference count were
2238          * incremented first, vgone would (incorrectly) try to
2239          * close the previous instance of the underlying object.
2240          */
2241         if (vp->v_usecount == 0 && !(vp->v_flag & VDOOMED)) {
2242                 s = splbio();
2243                 lwkt_gettoken(&ilock, &vnode_free_list_token);
2244                 if (vp->v_flag & VFREE)
2245                         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2246                 else
2247                         freevnodes++;
2248                 vp->v_flag |= VFREE;
2249                 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2250                 lwkt_reltoken(&ilock);
2251                 splx(s);
2252         }
2253         vp->v_type = VBAD;
2254         lwkt_reltoken(vlock);
2255 }
2256
2257 /*
2258  * Lookup a vnode by device number.
2259  */
2260 int
2261 vfinddev(dev_t dev, enum vtype type, struct vnode **vpp)
2262 {
2263         lwkt_tokref ilock;
2264         struct vnode *vp;
2265
2266         lwkt_gettoken(&ilock, &spechash_token);
2267         SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
2268                 if (type == vp->v_type) {
2269                         *vpp = vp;
2270                         lwkt_reltoken(&ilock);
2271                         return (1);
2272                 }
2273         }
2274         lwkt_reltoken(&ilock);
2275         return (0);
2276 }
2277
2278 /*
2279  * Calculate the total number of references to a special device.  This
2280  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
2281  * an overloaded field.  Since udev2dev can now return NODEV, we have
2282  * to check for a NULL v_rdev.
2283  */
2284 int
2285 count_dev(dev_t dev)
2286 {
2287         lwkt_tokref ilock;
2288         struct vnode *vp;
2289         int count = 0;
2290
2291         if (SLIST_FIRST(&dev->si_hlist)) {
2292                 lwkt_gettoken(&ilock, &spechash_token);
2293                 SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
2294                         count += vp->v_usecount;
2295                 }
2296                 lwkt_reltoken(&ilock);
2297         }
2298         return(count);
2299 }
2300
2301 int
2302 count_udev(udev_t udev)
2303 {
2304         dev_t dev;
2305
2306         if ((dev = udev2dev(udev, 0)) == NODEV)
2307                 return(0);
2308         return(count_dev(dev));
2309 }
2310
2311 int
2312 vcount(struct vnode *vp)
2313 {
2314         if (vp->v_rdev == NULL)
2315                 return(0);
2316         return(count_dev(vp->v_rdev));
2317 }
2318
2319 /*
2320  * Print out a description of a vnode.
2321  */
2322 static char *typename[] =
2323 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
2324
2325 void
2326 vprint(char *label, struct vnode *vp)
2327 {
2328         char buf[96];
2329
2330         if (label != NULL)
2331                 printf("%s: %p: ", label, (void *)vp);
2332         else
2333                 printf("%p: ", (void *)vp);
2334         printf("type %s, usecount %d, writecount %d, refcount %d,",
2335             typename[vp->v_type], vp->v_usecount, vp->v_writecount,
2336             vp->v_holdcnt);
2337         buf[0] = '\0';
2338         if (vp->v_flag & VROOT)
2339                 strcat(buf, "|VROOT");
2340         if (vp->v_flag & VTEXT)
2341                 strcat(buf, "|VTEXT");
2342         if (vp->v_flag & VSYSTEM)
2343                 strcat(buf, "|VSYSTEM");
2344         if (vp->v_flag & VXLOCK)
2345                 strcat(buf, "|VXLOCK");
2346         if (vp->v_flag & VXWANT)
2347                 strcat(buf, "|VXWANT");
2348         if (vp->v_flag & VBWAIT)
2349                 strcat(buf, "|VBWAIT");
2350         if (vp->v_flag & VDOOMED)
2351                 strcat(buf, "|VDOOMED");
2352         if (vp->v_flag & VFREE)
2353                 strcat(buf, "|VFREE");
2354         if (vp->v_flag & VOBJBUF)
2355                 strcat(buf, "|VOBJBUF");
2356         if (buf[0] != '\0')
2357                 printf(" flags (%s)", &buf[1]);
2358         if (vp->v_data == NULL) {
2359                 printf("\n");
2360         } else {
2361                 printf("\n\t");
2362                 VOP_PRINT(vp);
2363         }
2364 }
2365
2366 #ifdef DDB
2367 #include <ddb/ddb.h>
2368 /*
2369  * List all of the locked vnodes in the system.
2370  * Called when debugging the kernel.
2371  */
2372 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
2373 {
2374         struct thread *td = curthread;  /* XXX */
2375         lwkt_tokref ilock;
2376         struct mount *mp, *nmp;
2377         struct vnode *vp;
2378
2379         printf("Locked vnodes\n");
2380         lwkt_gettoken(&ilock, &mountlist_token);
2381         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2382                 if (vfs_busy(mp, LK_NOWAIT, &ilock, td)) {
2383                         nmp = TAILQ_NEXT(mp, mnt_list);
2384                         continue;
2385                 }
2386                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2387                         if (VOP_ISLOCKED(vp, NULL))
2388                                 vprint((char *)0, vp);
2389                 }
2390                 lwkt_gettokref(&ilock);
2391                 nmp = TAILQ_NEXT(mp, mnt_list);
2392                 vfs_unbusy(mp, td);
2393         }
2394         lwkt_reltoken(&ilock);
2395 }
2396 #endif
2397
2398 /*
2399  * Top level filesystem related information gathering.
2400  */
2401 static int      sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
2402
2403 static int
2404 vfs_sysctl(SYSCTL_HANDLER_ARGS)
2405 {
2406         int *name = (int *)arg1 - 1;    /* XXX */
2407         u_int namelen = arg2 + 1;       /* XXX */
2408         struct vfsconf *vfsp;
2409
2410 #if 1 || defined(COMPAT_PRELITE2)
2411         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2412         if (namelen == 1)
2413                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2414 #endif
2415
2416 #ifdef notyet
2417         /* all sysctl names at this level are at least name and field */
2418         if (namelen < 2)
2419                 return (ENOTDIR);               /* overloaded */
2420         if (name[0] != VFS_GENERIC) {
2421                 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2422                         if (vfsp->vfc_typenum == name[0])
2423                                 break;
2424                 if (vfsp == NULL)
2425                         return (EOPNOTSUPP);
2426                 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
2427                     oldp, oldlenp, newp, newlen, p));
2428         }
2429 #endif
2430         switch (name[1]) {
2431         case VFS_MAXTYPENUM:
2432                 if (namelen != 2)
2433                         return (ENOTDIR);
2434                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2435         case VFS_CONF:
2436                 if (namelen != 3)
2437                         return (ENOTDIR);       /* overloaded */
2438                 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2439                         if (vfsp->vfc_typenum == name[2])
2440                                 break;
2441                 if (vfsp == NULL)
2442                         return (EOPNOTSUPP);
2443                 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
2444         }
2445         return (EOPNOTSUPP);
2446 }
2447
2448 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
2449         "Generic filesystem");
2450
2451 #if 1 || defined(COMPAT_PRELITE2)
2452
2453 static int
2454 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2455 {
2456         int error;
2457         struct vfsconf *vfsp;
2458         struct ovfsconf ovfs;
2459
2460         for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
2461                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
2462                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
2463                 ovfs.vfc_index = vfsp->vfc_typenum;
2464                 ovfs.vfc_refcount = vfsp->vfc_refcount;
2465                 ovfs.vfc_flags = vfsp->vfc_flags;
2466                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2467                 if (error)
2468                         return error;
2469         }
2470         return 0;
2471 }
2472
2473 #endif /* 1 || COMPAT_PRELITE2 */
2474
2475 #if 0
2476 #define KINFO_VNODESLOP 10
2477 /*
2478  * Dump vnode list (via sysctl).
2479  * Copyout address of vnode followed by vnode.
2480  */
2481 /* ARGSUSED */
2482 static int
2483 sysctl_vnode(SYSCTL_HANDLER_ARGS)
2484 {
2485         struct proc *p = curproc;       /* XXX */
2486         struct mount *mp, *nmp;
2487         struct vnode *nvp, *vp;
2488         lwkt_tokref ilock;
2489         lwkt_tokref jlock;
2490         int error;
2491
2492 #define VPTRSZ  sizeof (struct vnode *)
2493 #define VNODESZ sizeof (struct vnode)
2494
2495         req->lock = 0;
2496         if (!req->oldptr) /* Make an estimate */
2497                 return (SYSCTL_OUT(req, 0,
2498                         (numvnodes + KINFO_VNODESLOP) * (VPTRSZ + VNODESZ)));
2499
2500         lwkt_gettoken(&ilock, &mountlist_token);
2501         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2502                 if (vfs_busy(mp, LK_NOWAIT, &ilock, p)) {
2503                         nmp = TAILQ_NEXT(mp, mnt_list);
2504                         continue;
2505                 }
2506                 lwkt_gettoken(&jlock, &mntvnode_token);
2507 again:
2508                 for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
2509                      vp != NULL;
2510                      vp = nvp) {
2511                         /*
2512                          * Check that the vp is still associated with
2513                          * this filesystem.  RACE: could have been
2514                          * recycled onto the same filesystem.
2515                          */
2516                         if (vp->v_mount != mp)
2517                                 goto again;
2518                         nvp = TAILQ_NEXT(vp, v_nmntvnodes);
2519                         if ((error = SYSCTL_OUT(req, &vp, VPTRSZ)) ||
2520                             (error = SYSCTL_OUT(req, vp, VNODESZ))) {
2521                                 lwkt_reltoken(&jlock);
2522                                 return (error);
2523                         }
2524                 }
2525                 lwkt_reltoken(&jlock);
2526                 lwkt_gettokref(&ilock);
2527                 nmp = TAILQ_NEXT(mp, mnt_list); /* ZZZ */
2528                 vfs_unbusy(mp, p);
2529         }
2530         lwkt_reltoken(&ilock);
2531
2532         return (0);
2533 }
2534 #endif
2535
2536 /*
2537  * XXX
2538  * Exporting the vnode list on large systems causes them to crash.
2539  * Exporting the vnode list on medium systems causes sysctl to coredump.
2540  */
2541 #if 0
2542 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
2543         0, 0, sysctl_vnode, "S,vnode", "");
2544 #endif
2545
2546 /*
2547  * Check to see if a filesystem is mounted on a block device.
2548  */
2549 int
2550 vfs_mountedon(struct vnode *vp)
2551 {
2552         dev_t dev;
2553
2554         if ((dev = vp->v_rdev) == NULL)
2555                 dev = udev2dev(vp->v_udev, (vp->v_type == VBLK));
2556         if (dev != NODEV && dev->si_mountpoint)
2557                 return (EBUSY);
2558         return (0);
2559 }
2560
2561 /*
2562  * Unmount all filesystems. The list is traversed in reverse order
2563  * of mounting to avoid dependencies.
2564  */
2565 void
2566 vfs_unmountall(void)
2567 {
2568         struct mount *mp;
2569         struct thread *td = curthread;
2570         int error;
2571
2572         if (td->td_proc == NULL)
2573                 td = initproc->p_thread;        /* XXX XXX use proc0 instead? */
2574
2575         /*
2576          * Since this only runs when rebooting, it is not interlocked.
2577          */
2578         while(!TAILQ_EMPTY(&mountlist)) {
2579                 mp = TAILQ_LAST(&mountlist, mntlist);
2580                 error = dounmount(mp, MNT_FORCE, td);
2581                 if (error) {
2582                         TAILQ_REMOVE(&mountlist, mp, mnt_list);
2583                         printf("unmount of %s failed (",
2584                             mp->mnt_stat.f_mntonname);
2585                         if (error == EBUSY)
2586                                 printf("BUSY)\n");
2587                         else
2588                                 printf("%d)\n", error);
2589                 } else {
2590                         /* The unmount has removed mp from the mountlist */
2591                 }
2592         }
2593 }
2594
2595 /*
2596  * Build hash lists of net addresses and hang them off the mount point.
2597  * Called by ufs_mount() to set up the lists of export addresses.
2598  */
2599 static int
2600 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
2601                 struct export_args *argp)
2602 {
2603         struct netcred *np;
2604         struct radix_node_head *rnh;
2605         int i;
2606         struct radix_node *rn;
2607         struct sockaddr *saddr, *smask = 0;
2608         struct domain *dom;
2609         int error;
2610
2611         if (argp->ex_addrlen == 0) {
2612                 if (mp->mnt_flag & MNT_DEFEXPORTED)
2613                         return (EPERM);
2614                 np = &nep->ne_defexported;
2615                 np->netc_exflags = argp->ex_flags;
2616                 np->netc_anon = argp->ex_anon;
2617                 np->netc_anon.cr_ref = 1;
2618                 mp->mnt_flag |= MNT_DEFEXPORTED;
2619                 return (0);
2620         }
2621
2622         if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2623                 return (EINVAL);
2624         if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2625                 return (EINVAL);
2626
2627         i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2628         np = (struct netcred *) malloc(i, M_NETADDR, M_WAITOK);
2629         bzero((caddr_t) np, i);
2630         saddr = (struct sockaddr *) (np + 1);
2631         if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2632                 goto out;
2633         if (saddr->sa_len > argp->ex_addrlen)
2634                 saddr->sa_len = argp->ex_addrlen;
2635         if (argp->ex_masklen) {
2636                 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
2637                 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
2638                 if (error)
2639                         goto out;
2640                 if (smask->sa_len > argp->ex_masklen)
2641                         smask->sa_len = argp->ex_masklen;
2642         }
2643         i = saddr->sa_family;
2644         if ((rnh = nep->ne_rtable[i]) == 0) {
2645                 /*
2646                  * Seems silly to initialize every AF when most are not used,
2647                  * do so on demand here
2648                  */
2649                 for (dom = domains; dom; dom = dom->dom_next)
2650                         if (dom->dom_family == i && dom->dom_rtattach) {
2651                                 dom->dom_rtattach((void **) &nep->ne_rtable[i],
2652                                     dom->dom_rtoffset);
2653                                 break;
2654                         }
2655                 if ((rnh = nep->ne_rtable[i]) == 0) {
2656                         error = ENOBUFS;
2657                         goto out;
2658                 }
2659         }
2660         rn = (*rnh->rnh_addaddr) ((caddr_t) saddr, (caddr_t) smask, rnh,
2661             np->netc_rnodes);
2662         if (rn == 0 || np != (struct netcred *) rn) {   /* already exists */
2663                 error = EPERM;
2664                 goto out;
2665         }
2666         np->netc_exflags = argp->ex_flags;
2667         np->netc_anon = argp->ex_anon;
2668         np->netc_anon.cr_ref = 1;
2669         return (0);
2670 out:
2671         free(np, M_NETADDR);
2672         return (error);
2673 }
2674
2675 /* ARGSUSED */
2676 static int
2677 vfs_free_netcred(struct radix_node *rn, void *w)
2678 {
2679         struct radix_node_head *rnh = (struct radix_node_head *) w;
2680
2681         (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2682         free((caddr_t) rn, M_NETADDR);
2683         return (0);
2684 }
2685
2686 /*
2687  * Free the net address hash lists that are hanging off the mount points.
2688  */
2689 static void
2690 vfs_free_addrlist(struct netexport *nep)
2691 {
2692         int i;
2693         struct radix_node_head *rnh;
2694
2695         for (i = 0; i <= AF_MAX; i++)
2696                 if ((rnh = nep->ne_rtable[i])) {
2697                         (*rnh->rnh_walktree) (rnh, vfs_free_netcred,
2698                             (caddr_t) rnh);
2699                         free((caddr_t) rnh, M_RTABLE);
2700                         nep->ne_rtable[i] = 0;
2701                 }
2702 }
2703
2704 int
2705 vfs_export(struct mount *mp, struct netexport *nep, struct export_args *argp)
2706 {
2707         int error;
2708
2709         if (argp->ex_flags & MNT_DELEXPORT) {
2710                 if (mp->mnt_flag & MNT_EXPUBLIC) {
2711                         vfs_setpublicfs(NULL, NULL, NULL);
2712                         mp->mnt_flag &= ~MNT_EXPUBLIC;
2713                 }
2714                 vfs_free_addrlist(nep);
2715                 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2716         }
2717         if (argp->ex_flags & MNT_EXPORTED) {
2718                 if (argp->ex_flags & MNT_EXPUBLIC) {
2719                         if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2720                                 return (error);
2721                         mp->mnt_flag |= MNT_EXPUBLIC;
2722                 }
2723                 if ((error = vfs_hang_addrlist(mp, nep, argp)))
2724                         return (error);
2725                 mp->mnt_flag |= MNT_EXPORTED;
2726         }
2727         return (0);
2728 }
2729
2730
2731 /*
2732  * Set the publicly exported filesystem (WebNFS). Currently, only
2733  * one public filesystem is possible in the spec (RFC 2054 and 2055)
2734  */
2735 int
2736 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
2737                 struct export_args *argp)
2738 {
2739         int error;
2740         struct vnode *rvp;
2741         char *cp;
2742
2743         /*
2744          * mp == NULL -> invalidate the current info, the FS is
2745          * no longer exported. May be called from either vfs_export
2746          * or unmount, so check if it hasn't already been done.
2747          */
2748         if (mp == NULL) {
2749                 if (nfs_pub.np_valid) {
2750                         nfs_pub.np_valid = 0;
2751                         if (nfs_pub.np_index != NULL) {
2752                                 FREE(nfs_pub.np_index, M_TEMP);
2753                                 nfs_pub.np_index = NULL;
2754                         }
2755                 }
2756                 return (0);
2757         }
2758
2759         /*
2760          * Only one allowed at a time.
2761          */
2762         if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2763                 return (EBUSY);
2764
2765         /*
2766          * Get real filehandle for root of exported FS.
2767          */
2768         bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2769         nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2770
2771         if ((error = VFS_ROOT(mp, &rvp)))
2772                 return (error);
2773
2774         if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2775                 return (error);
2776
2777         vput(rvp);
2778
2779         /*
2780          * If an indexfile was specified, pull it in.
2781          */
2782         if (argp->ex_indexfile != NULL) {
2783                 MALLOC(nfs_pub.np_index, char *, MAXNAMLEN + 1, M_TEMP,
2784                     M_WAITOK);
2785                 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2786                     MAXNAMLEN, (size_t *)0);
2787                 if (!error) {
2788                         /*
2789                          * Check for illegal filenames.
2790                          */
2791                         for (cp = nfs_pub.np_index; *cp; cp++) {
2792                                 if (*cp == '/') {
2793                                         error = EINVAL;
2794                                         break;
2795                                 }
2796                         }
2797                 }
2798                 if (error) {
2799                         FREE(nfs_pub.np_index, M_TEMP);
2800                         return (error);
2801                 }
2802         }
2803
2804         nfs_pub.np_mount = mp;
2805         nfs_pub.np_valid = 1;
2806         return (0);
2807 }
2808
2809 struct netcred *
2810 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2811                 struct sockaddr *nam)
2812 {
2813         struct netcred *np;
2814         struct radix_node_head *rnh;
2815         struct sockaddr *saddr;
2816
2817         np = NULL;
2818         if (mp->mnt_flag & MNT_EXPORTED) {
2819                 /*
2820                  * Lookup in the export list first.
2821                  */
2822                 if (nam != NULL) {
2823                         saddr = nam;
2824                         rnh = nep->ne_rtable[saddr->sa_family];
2825                         if (rnh != NULL) {
2826                                 np = (struct netcred *)
2827                                         (*rnh->rnh_matchaddr)((caddr_t)saddr,
2828                                                               rnh);
2829                                 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2830                                         np = NULL;
2831                         }
2832                 }
2833                 /*
2834                  * If no address match, use the default if it exists.
2835                  */
2836                 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2837                         np = &nep->ne_defexported;
2838         }
2839         return (np);
2840 }
2841
2842 /*
2843  * perform msync on all vnodes under a mount point.  The mount point must
2844  * be locked.  This code is also responsible for lazy-freeing unreferenced
2845  * vnodes whos VM objects no longer contain pages.
2846  *
2847  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2848  */
2849 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2850 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, 
2851                             lwkt_tokref_t vlock, void *data);
2852
2853 void
2854 vfs_msync(struct mount *mp, int flags) 
2855 {
2856         vmntvnodescan(mp, vfs_msync_scan1, vfs_msync_scan2, (void *)flags);
2857 }
2858
2859 /*
2860  * scan1 is a fast pre-check.  There could be hundreds of thousands of
2861  * vnodes, we cannot afford to do anything heavy weight until we have a
2862  * fairly good indication that there is work to do.
2863  */
2864 static
2865 int
2866 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2867 {
2868         int flags = (int)data;
2869
2870         if ((vp->v_flag & VXLOCK) == 0) {
2871                 if (VSHOULDFREE(vp))
2872                         return(0);
2873                 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2874                     (vp->v_flag & VOBJDIRTY) &&
2875                     (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
2876                         return(0);
2877                 }
2878         }
2879         return(-1);
2880 }
2881
2882 static
2883 int
2884 vfs_msync_scan2(struct mount *mp, struct vnode *vp, 
2885                 lwkt_tokref_t vlock, void *data)
2886 {
2887         vm_object_t obj;
2888         int error;
2889         int flags = (int)data;
2890
2891         if (vp->v_flag & VXLOCK)
2892                 return(0);
2893
2894         if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2895             (vp->v_flag & VOBJDIRTY) &&
2896             (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
2897                 error = vget(vp, vlock, LK_EXCLUSIVE | LK_RETRY | LK_NOOBJ | LK_INTERLOCK, curthread);
2898                 if (error == 0) {
2899                         if (VOP_GETVOBJECT(vp, &obj) == 0) {
2900                                 vm_object_page_clean(obj, 0, 0, 
2901                                  flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2902                         }
2903                         vput(vp);
2904                 }
2905                 return(0);
2906         }
2907         vmaybefree(vp);
2908         lwkt_reltoken(vlock);
2909         return(0);
2910 }
2911
2912 /*
2913  * Create the VM object needed for VMIO and mmap support.  This
2914  * is done for all VREG files in the system.  Some filesystems might
2915  * afford the additional metadata buffering capability of the
2916  * VMIO code by making the device node be VMIO mode also.
2917  *
2918  * vp must be locked when vfs_object_create is called.
2919  */
2920 int
2921 vfs_object_create(struct vnode *vp, struct thread *td)
2922 {
2923         return (VOP_CREATEVOBJECT(vp, td));
2924 }
2925
2926 /*
2927  * NOTE: the vnode interlock must be held during the call.  We have to recheck
2928  * the VFREE flag since the vnode may have been removed from the free list
2929  * while we were blocked on vnode_free_list_token.  The use or hold count
2930  * must have already been bumped by the caller.
2931  */
2932 static void
2933 vbusy(struct vnode *vp)
2934 {
2935         lwkt_tokref ilock;
2936
2937         lwkt_gettoken(&ilock, &vnode_free_list_token);
2938         if ((vp->v_flag & VFREE) != 0) {
2939             TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2940             freevnodes--;
2941             vp->v_flag &= ~(VFREE|VAGE);
2942         }
2943         lwkt_reltoken(&ilock);
2944 }
2945
2946 /*
2947  * NOTE: the vnode interlock must be held during the call.  The use or hold
2948  * count must have already been bumped by the caller.  We use a VINFREE to
2949  * interlock against other calls to vfree() which might occur while we 
2950  * are blocked.  The vnode cannot be reused until it has actually been
2951  * placed on the free list, so there are no other races even though the
2952  * use and hold counts are 0.
2953  */
2954 static void
2955 vfree(struct vnode *vp)
2956 {
2957         lwkt_tokref ilock;
2958
2959         if ((vp->v_flag & VINFREE) == 0) {
2960                 vp->v_flag |= VINFREE;
2961                 lwkt_gettoken(&ilock, &vnode_free_list_token); /* can block */
2962                 KASSERT((vp->v_flag & VFREE) == 0, ("vnode already free"));
2963                 if (vp->v_flag & VAGE) {
2964                         TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2965                 } else {
2966                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2967                 }
2968                 freevnodes++;
2969                 vp->v_flag &= ~(VAGE|VINFREE);
2970                 vp->v_flag |= VFREE;
2971                 lwkt_reltoken(&ilock);  /* can block */
2972         }
2973 }
2974
2975
2976 /*
2977  * Record a process's interest in events which might happen to
2978  * a vnode.  Because poll uses the historic select-style interface
2979  * internally, this routine serves as both the ``check for any
2980  * pending events'' and the ``record my interest in future events''
2981  * functions.  (These are done together, while the lock is held,
2982  * to avoid race conditions.)
2983  */
2984 int
2985 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
2986 {
2987         lwkt_tokref ilock;
2988
2989         lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
2990         if (vp->v_pollinfo.vpi_revents & events) {
2991                 /*
2992                  * This leaves events we are not interested
2993                  * in available for the other process which
2994                  * which presumably had requested them
2995                  * (otherwise they would never have been
2996                  * recorded).
2997                  */
2998                 events &= vp->v_pollinfo.vpi_revents;
2999                 vp->v_pollinfo.vpi_revents &= ~events;
3000
3001                 lwkt_reltoken(&ilock);
3002                 return events;
3003         }
3004         vp->v_pollinfo.vpi_events |= events;
3005         selrecord(td, &vp->v_pollinfo.vpi_selinfo);
3006         lwkt_reltoken(&ilock);
3007         return 0;
3008 }
3009
3010 /*
3011  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
3012  * it is possible for us to miss an event due to race conditions, but
3013  * that condition is expected to be rare, so for the moment it is the
3014  * preferred interface.
3015  */
3016 void
3017 vn_pollevent(struct vnode *vp, int events)
3018 {
3019         lwkt_tokref ilock;
3020
3021         lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
3022         if (vp->v_pollinfo.vpi_events & events) {
3023                 /*
3024                  * We clear vpi_events so that we don't
3025                  * call selwakeup() twice if two events are
3026                  * posted before the polling process(es) is
3027                  * awakened.  This also ensures that we take at
3028                  * most one selwakeup() if the polling process
3029                  * is no longer interested.  However, it does
3030                  * mean that only one event can be noticed at
3031                  * a time.  (Perhaps we should only clear those
3032                  * event bits which we note?) XXX
3033                  */
3034                 vp->v_pollinfo.vpi_events = 0;  /* &= ~events ??? */
3035                 vp->v_pollinfo.vpi_revents |= events;
3036                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
3037         }
3038         lwkt_reltoken(&ilock);
3039 }
3040
3041 /*
3042  * Wake up anyone polling on vp because it is being revoked.
3043  * This depends on dead_poll() returning POLLHUP for correct
3044  * behavior.
3045  */
3046 void
3047 vn_pollgone(struct vnode *vp)
3048 {
3049         lwkt_tokref ilock;
3050
3051         lwkt_gettoken(&ilock, &vp->v_pollinfo.vpi_token);
3052         if (vp->v_pollinfo.vpi_events) {
3053                 vp->v_pollinfo.vpi_events = 0;
3054                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
3055         }
3056         lwkt_reltoken(&ilock);
3057 }
3058
3059
3060
3061 /*
3062  * Routine to create and manage a filesystem syncer vnode.
3063  */
3064 #define sync_close ((int (*) (struct  vop_close_args *))nullop)
3065 static int      sync_fsync (struct  vop_fsync_args *);
3066 static int      sync_inactive (struct  vop_inactive_args *);
3067 static int      sync_reclaim  (struct  vop_reclaim_args *);
3068 #define sync_lock ((int (*) (struct  vop_lock_args *))vop_nolock)
3069 #define sync_unlock ((int (*) (struct  vop_unlock_args *))vop_nounlock)
3070 static int      sync_print (struct vop_print_args *);
3071 #define sync_islocked ((int(*) (struct vop_islocked_args *))vop_noislocked)
3072
3073 static vop_t **sync_vnodeop_p;
3074 static struct vnodeopv_entry_desc sync_vnodeop_entries[] = {
3075         { &vop_default_desc,    (vop_t *) vop_eopnotsupp },
3076         { &vop_close_desc,      (vop_t *) sync_close },         /* close */
3077         { &vop_fsync_desc,      (vop_t *) sync_fsync },         /* fsync */
3078         { &vop_inactive_desc,   (vop_t *) sync_inactive },      /* inactive */
3079         { &vop_reclaim_desc,    (vop_t *) sync_reclaim },       /* reclaim */
3080         { &vop_lock_desc,       (vop_t *) sync_lock },          /* lock */
3081         { &vop_unlock_desc,     (vop_t *) sync_unlock },        /* unlock */
3082         { &vop_print_desc,      (vop_t *) sync_print },         /* print */
3083         { &vop_islocked_desc,   (vop_t *) sync_islocked },      /* islocked */
3084         { NULL, NULL }
3085 };
3086 static struct vnodeopv_desc sync_vnodeop_opv_desc =
3087         { &sync_vnodeop_p, sync_vnodeop_entries };
3088
3089 VNODEOP_SET(sync_vnodeop_opv_desc);
3090
3091 /*
3092  * Create a new filesystem syncer vnode for the specified mount point.
3093  * This vnode is placed on the worklist and is responsible for sync'ing
3094  * the filesystem.
3095  *
3096  * NOTE: read-only mounts are also placed on the worklist.  The filesystem
3097  * sync code is also responsible for cleaning up vnodes.
3098  */
3099 int
3100 vfs_allocate_syncvnode(struct mount *mp)
3101 {
3102         struct vnode *vp;
3103         static long start, incr, next;
3104         int error;
3105
3106         /* Allocate a new vnode */
3107         if ((error = getnewvnode(VT_VFS, mp, sync_vnodeop_p, &vp)) != 0) {
3108                 mp->mnt_syncer = NULL;
3109                 return (error);
3110         }
3111         vp->v_type = VNON;
3112         /*
3113          * Place the vnode onto the syncer worklist. We attempt to
3114          * scatter them about on the list so that they will go off
3115          * at evenly distributed times even if all the filesystems
3116          * are mounted at once.
3117          */
3118         next += incr;
3119         if (next == 0 || next > syncer_maxdelay) {
3120                 start /= 2;
3121                 incr /= 2;
3122                 if (start == 0) {
3123                         start = syncer_maxdelay / 2;
3124                         incr = syncer_maxdelay;
3125                 }
3126                 next = start;
3127         }
3128         vn_syncer_add_to_worklist(vp, syncdelay > 0 ? next % syncdelay : 0);
3129         mp->mnt_syncer = vp;
3130         return (0);
3131 }
3132
3133 /*
3134  * Do a lazy sync of the filesystem.
3135  *
3136  * sync_fsync { struct vnode *a_vp, struct ucred *a_cred, int a_waitfor,
3137  *              struct thread *a_td }
3138  */
3139 static int
3140 sync_fsync(struct vop_fsync_args *ap)
3141 {
3142         struct vnode *syncvp = ap->a_vp;
3143         struct mount *mp = syncvp->v_mount;
3144         struct thread *td = ap->a_td;
3145         lwkt_tokref ilock;
3146         int asyncflag;
3147
3148         /*
3149          * We only need to do something if this is a lazy evaluation.
3150          */
3151         if (ap->a_waitfor != MNT_LAZY)
3152                 return (0);
3153
3154         /*
3155          * Move ourselves to the back of the sync list.
3156          */
3157         vn_syncer_add_to_worklist(syncvp, syncdelay);
3158
3159         /*
3160          * Walk the list of vnodes pushing all that are dirty and
3161          * not already on the sync list, and freeing vnodes which have
3162          * no refs and whos VM objects are empty.  vfs_msync() handles
3163          * the VM issues and must be called whether the mount is readonly
3164          * or not.
3165          */
3166         lwkt_gettoken(&ilock, &mountlist_token);
3167         if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &ilock, td) != 0) {
3168                 lwkt_reltoken(&ilock);
3169                 return (0);
3170         }
3171         if (mp->mnt_flag & MNT_RDONLY) {
3172                 vfs_msync(mp, MNT_NOWAIT);
3173         } else {
3174                 asyncflag = mp->mnt_flag & MNT_ASYNC;
3175                 mp->mnt_flag &= ~MNT_ASYNC;     /* ZZZ hack */
3176                 vfs_msync(mp, MNT_NOWAIT);
3177                 VFS_SYNC(mp, MNT_LAZY, td);
3178                 if (asyncflag)
3179                         mp->mnt_flag |= MNT_ASYNC;
3180         }
3181         vfs_unbusy(mp, td);
3182         return (0);
3183 }
3184
3185 /*
3186  * The syncer vnode is no referenced.
3187  *
3188  * sync_inactive { struct vnode *a_vp, struct proc *a_p }
3189  */
3190 static int
3191 sync_inactive(struct vop_inactive_args *ap)
3192 {
3193         vgone(ap->a_vp);
3194         return (0);
3195 }
3196
3197 /*
3198  * The syncer vnode is no longer needed and is being decommissioned.
3199  *
3200  * Modifications to the worklist must be protected at splbio().
3201  *
3202  *      sync_reclaim { struct vnode *a_vp }
3203  */
3204 static int
3205 sync_reclaim(struct vop_reclaim_args *ap)
3206 {
3207         struct vnode *vp = ap->a_vp;
3208         int s;
3209
3210         s = splbio();
3211         vp->v_mount->mnt_syncer = NULL;
3212         if (vp->v_flag & VONWORKLST) {
3213                 LIST_REMOVE(vp, v_synclist);
3214                 vp->v_flag &= ~VONWORKLST;
3215         }
3216         splx(s);
3217
3218         return (0);
3219 }
3220
3221 /*
3222  * Print out a syncer vnode.
3223  *
3224  *      sync_print { struct vnode *a_vp }
3225  */
3226 static int
3227 sync_print(struct vop_print_args *ap)
3228 {
3229         struct vnode *vp = ap->a_vp;
3230
3231         printf("syncer vnode");
3232         if (vp->v_vnlock != NULL)
3233                 lockmgr_printinfo(vp->v_vnlock);
3234         printf("\n");
3235         return (0);
3236 }
3237
3238 /*
3239  * extract the dev_t from a VBLK or VCHR.  The vnode must have been opened
3240  * (or v_rdev might be NULL).
3241  */
3242 dev_t
3243 vn_todev(struct vnode *vp)
3244 {
3245         if (vp->v_type != VBLK && vp->v_type != VCHR)
3246                 return (NODEV);
3247         KKASSERT(vp->v_rdev != NULL);
3248         return (vp->v_rdev);
3249 }
3250
3251 /*
3252  * Check if vnode represents a disk device.  The vnode does not need to be
3253  * opened.
3254  */
3255 int
3256 vn_isdisk(struct vnode *vp, int *errp)
3257 {
3258         dev_t dev;
3259
3260         if (vp->v_type != VBLK && vp->v_type != VCHR) {
3261                 if (errp != NULL)
3262                         *errp = ENOTBLK;
3263                 return (0);
3264         }
3265
3266         if ((dev = vp->v_rdev) == NULL)
3267                 dev = udev2dev(vp->v_udev, (vp->v_type == VBLK));
3268         if (dev == NULL || dev == NODEV) {
3269                 if (errp != NULL)
3270                         *errp = ENXIO;
3271                 return (0);
3272         }
3273         if (dev_is_good(dev) == 0) {
3274                 if (errp != NULL)
3275                         *errp = ENXIO;
3276                 return (0);
3277         }
3278         if ((dev_dflags(dev) & D_DISK) == 0) {
3279                 if (errp != NULL)
3280                         *errp = ENOTBLK;
3281                 return (0);
3282         }
3283         if (errp != NULL)
3284                 *errp = 0;
3285         return (1);
3286 }
3287
3288 void
3289 NDFREE(struct nameidata *ndp, const uint flags)
3290 {
3291         if (!(flags & NDF_NO_FREE_PNBUF) &&
3292             (ndp->ni_cnd.cn_flags & CNP_HASBUF)) {
3293                 zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
3294                 ndp->ni_cnd.cn_flags &= ~CNP_HASBUF;
3295         }
3296         if (!(flags & NDF_NO_DNCP_RELE) &&
3297             (ndp->ni_cnd.cn_flags & CNP_WANTDNCP) &&
3298             ndp->ni_dncp) {
3299                 cache_drop(ndp->ni_dncp);
3300                 ndp->ni_dncp = NULL;
3301         }
3302         if (!(flags & NDF_NO_NCP_RELE) &&
3303             (ndp->ni_cnd.cn_flags & CNP_WANTNCP) &&
3304             ndp->ni_ncp) {
3305                 cache_drop(ndp->ni_ncp);
3306                 ndp->ni_ncp = NULL;
3307         }
3308         if (!(flags & NDF_NO_DVP_UNLOCK) &&
3309             (ndp->ni_cnd.cn_flags & CNP_LOCKPARENT) &&
3310             ndp->ni_dvp != ndp->ni_vp) {
3311                 VOP_UNLOCK(ndp->ni_dvp, NULL, 0, ndp->ni_cnd.cn_td);
3312         }
3313         if (!(flags & NDF_NO_DVP_RELE) &&
3314             (ndp->ni_cnd.cn_flags & (CNP_LOCKPARENT|CNP_WANTPARENT))) {
3315                 vrele(ndp->ni_dvp);
3316                 ndp->ni_dvp = NULL;
3317         }
3318         if (!(flags & NDF_NO_VP_UNLOCK) &&
3319             (ndp->ni_cnd.cn_flags & CNP_LOCKLEAF) && ndp->ni_vp) {
3320                 VOP_UNLOCK(ndp->ni_vp, NULL, 0, ndp->ni_cnd.cn_td);
3321         }
3322         if (!(flags & NDF_NO_VP_RELE) &&
3323             ndp->ni_vp) {
3324                 vrele(ndp->ni_vp);
3325                 ndp->ni_vp = NULL;
3326         }
3327         if (!(flags & NDF_NO_STARTDIR_RELE) &&
3328             (ndp->ni_cnd.cn_flags & CNP_SAVESTART)) {
3329                 vrele(ndp->ni_startdir);
3330                 ndp->ni_startdir = NULL;
3331         }
3332 }
3333
3334 #ifdef DEBUG_VFS_LOCKS
3335
3336 void
3337 assert_vop_locked(struct vnode *vp, const char *str)
3338 {
3339         if (vp && IS_LOCKING_VFS(vp) && !VOP_ISLOCKED(vp, NULL)) {
3340                 panic("%s: %p is not locked shared but should be", str, vp);
3341         }
3342 }
3343
3344 void
3345 assert_vop_unlocked(struct vnode *vp, const char *str)
3346 {
3347         if (vp && IS_LOCKING_VFS(vp)) {
3348                 if (VOP_ISLOCKED(vp, curthread) == LK_EXCLUSIVE) {
3349                         panic("%s: %p is locked but should not be", str, vp);
3350                 }
3351         }
3352 }
3353
3354 #endif