]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_subr.c
disallow clock_settime too far in the future to avoid panic
[FreeBSD/FreeBSD.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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)vfs_subr.c  8.31 (Berkeley) 5/26/95
35  */
36
37 /*
38  * External virtual filesystem routines
39  */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include "opt_compat.h"
45 #include "opt_ddb.h"
46 #include "opt_watchdog.h"
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/bio.h>
51 #include <sys/buf.h>
52 #include <sys/condvar.h>
53 #include <sys/conf.h>
54 #include <sys/counter.h>
55 #include <sys/dirent.h>
56 #include <sys/event.h>
57 #include <sys/eventhandler.h>
58 #include <sys/extattr.h>
59 #include <sys/file.h>
60 #include <sys/fcntl.h>
61 #include <sys/jail.h>
62 #include <sys/kdb.h>
63 #include <sys/kernel.h>
64 #include <sys/kthread.h>
65 #include <sys/lockf.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.h>
68 #include <sys/namei.h>
69 #include <sys/pctrie.h>
70 #include <sys/priv.h>
71 #include <sys/reboot.h>
72 #include <sys/refcount.h>
73 #include <sys/rwlock.h>
74 #include <sys/sched.h>
75 #include <sys/sleepqueue.h>
76 #include <sys/smp.h>
77 #include <sys/stat.h>
78 #include <sys/sysctl.h>
79 #include <sys/syslog.h>
80 #include <sys/vmmeter.h>
81 #include <sys/vnode.h>
82 #include <sys/watchdog.h>
83
84 #include <machine/stdarg.h>
85
86 #include <security/mac/mac_framework.h>
87
88 #include <vm/vm.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_extern.h>
91 #include <vm/pmap.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_kern.h>
95 #include <vm/uma.h>
96
97 #ifdef DDB
98 #include <ddb/ddb.h>
99 #endif
100
101 static void     delmntque(struct vnode *vp);
102 static int      flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
103                     int slpflag, int slptimeo);
104 static void     syncer_shutdown(void *arg, int howto);
105 static int      vtryrecycle(struct vnode *vp);
106 static void     v_init_counters(struct vnode *);
107 static void     v_incr_usecount(struct vnode *);
108 static void     v_incr_usecount_locked(struct vnode *);
109 static void     v_incr_devcount(struct vnode *);
110 static void     v_decr_devcount(struct vnode *);
111 static void     vgonel(struct vnode *);
112 static void     vfs_knllock(void *arg);
113 static void     vfs_knlunlock(void *arg);
114 static void     vfs_knl_assert_locked(void *arg);
115 static void     vfs_knl_assert_unlocked(void *arg);
116 static void     vnlru_return_batches(struct vfsops *mnt_op);
117 static void     destroy_vpollinfo(struct vpollinfo *vi);
118
119 /*
120  * Number of vnodes in existence.  Increased whenever getnewvnode()
121  * allocates a new vnode, decreased in vdropl() for VI_DOOMED vnode.
122  */
123 static unsigned long    numvnodes;
124
125 SYSCTL_ULONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0,
126     "Number of vnodes in existence");
127
128 static counter_u64_t vnodes_created;
129 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, vnodes_created, CTLFLAG_RD, &vnodes_created,
130     "Number of vnodes created by getnewvnode");
131
132 static u_long mnt_free_list_batch = 128;
133 SYSCTL_ULONG(_vfs, OID_AUTO, mnt_free_list_batch, CTLFLAG_RW,
134     &mnt_free_list_batch, 0, "Limit of vnodes held on mnt's free list");
135
136 /*
137  * Conversion tables for conversion from vnode types to inode formats
138  * and back.
139  */
140 enum vtype iftovt_tab[16] = {
141         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
142         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
143 };
144 int vttoif_tab[10] = {
145         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
146         S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
147 };
148
149 /*
150  * List of vnodes that are ready for recycling.
151  */
152 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
153
154 /*
155  * "Free" vnode target.  Free vnodes are rarely completely free, but are
156  * just ones that are cheap to recycle.  Usually they are for files which
157  * have been stat'd but not read; these usually have inode and namecache
158  * data attached to them.  This target is the preferred minimum size of a
159  * sub-cache consisting mostly of such files. The system balances the size
160  * of this sub-cache with its complement to try to prevent either from
161  * thrashing while the other is relatively inactive.  The targets express
162  * a preference for the best balance.
163  *
164  * "Above" this target there are 2 further targets (watermarks) related
165  * to recyling of free vnodes.  In the best-operating case, the cache is
166  * exactly full, the free list has size between vlowat and vhiwat above the
167  * free target, and recycling from it and normal use maintains this state.
168  * Sometimes the free list is below vlowat or even empty, but this state
169  * is even better for immediate use provided the cache is not full.
170  * Otherwise, vnlru_proc() runs to reclaim enough vnodes (usually non-free
171  * ones) to reach one of these states.  The watermarks are currently hard-
172  * coded as 4% and 9% of the available space higher.  These and the default
173  * of 25% for wantfreevnodes are too large if the memory size is large.
174  * E.g., 9% of 75% of MAXVNODES is more than 566000 vnodes to reclaim
175  * whenever vnlru_proc() becomes active.
176  */
177 static u_long wantfreevnodes;
178 SYSCTL_ULONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
179     &wantfreevnodes, 0, "Target for minimum number of \"free\" vnodes");
180 static u_long freevnodes;
181 SYSCTL_ULONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD,
182     &freevnodes, 0, "Number of \"free\" vnodes");
183
184 static counter_u64_t recycles_count;
185 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, recycles, CTLFLAG_RD, &recycles_count,
186     "Number of vnodes recycled to meet vnode cache targets");
187
188 /*
189  * Various variables used for debugging the new implementation of
190  * reassignbuf().
191  * XXX these are probably of (very) limited utility now.
192  */
193 static int reassignbufcalls;
194 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0,
195     "Number of calls to reassignbuf");
196
197 static counter_u64_t free_owe_inact;
198 SYSCTL_COUNTER_U64(_vfs, OID_AUTO, free_owe_inact, CTLFLAG_RD, &free_owe_inact,
199     "Number of times free vnodes kept on active list due to VFS "
200     "owing inactivation");
201
202 /* To keep more than one thread at a time from running vfs_getnewfsid */
203 static struct mtx mntid_mtx;
204
205 /*
206  * Lock for any access to the following:
207  *      vnode_free_list
208  *      numvnodes
209  *      freevnodes
210  */
211 static struct mtx vnode_free_list_mtx;
212
213 /* Publicly exported FS */
214 struct nfs_public nfs_pub;
215
216 static uma_zone_t buf_trie_zone;
217
218 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
219 static uma_zone_t vnode_zone;
220 static uma_zone_t vnodepoll_zone;
221
222 /*
223  * The workitem queue.
224  *
225  * It is useful to delay writes of file data and filesystem metadata
226  * for tens of seconds so that quickly created and deleted files need
227  * not waste disk bandwidth being created and removed. To realize this,
228  * we append vnodes to a "workitem" queue. When running with a soft
229  * updates implementation, most pending metadata dependencies should
230  * not wait for more than a few seconds. Thus, mounted on block devices
231  * are delayed only about a half the time that file data is delayed.
232  * Similarly, directory updates are more critical, so are only delayed
233  * about a third the time that file data is delayed. Thus, there are
234  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
235  * one each second (driven off the filesystem syncer process). The
236  * syncer_delayno variable indicates the next queue that is to be processed.
237  * Items that need to be processed soon are placed in this queue:
238  *
239  *      syncer_workitem_pending[syncer_delayno]
240  *
241  * A delay of fifteen seconds is done by placing the request fifteen
242  * entries later in the queue:
243  *
244  *      syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
245  *
246  */
247 static int syncer_delayno;
248 static long syncer_mask;
249 LIST_HEAD(synclist, bufobj);
250 static struct synclist *syncer_workitem_pending;
251 /*
252  * The sync_mtx protects:
253  *      bo->bo_synclist
254  *      sync_vnode_count
255  *      syncer_delayno
256  *      syncer_state
257  *      syncer_workitem_pending
258  *      syncer_worklist_len
259  *      rushjob
260  */
261 static struct mtx sync_mtx;
262 static struct cv sync_wakeup;
263
264 #define SYNCER_MAXDELAY         32
265 static int syncer_maxdelay = SYNCER_MAXDELAY;   /* maximum delay time */
266 static int syncdelay = 30;              /* max time to delay syncing data */
267 static int filedelay = 30;              /* time to delay syncing files */
268 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
269     "Time to delay syncing files (in seconds)");
270 static int dirdelay = 29;               /* time to delay syncing directories */
271 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
272     "Time to delay syncing directories (in seconds)");
273 static int metadelay = 28;              /* time to delay syncing metadata */
274 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
275     "Time to delay syncing metadata (in seconds)");
276 static int rushjob;             /* number of slots to run ASAP */
277 static int stat_rush_requests;  /* number of times I/O speeded up */
278 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0,
279     "Number of times I/O speeded up (rush requests)");
280
281 /*
282  * When shutting down the syncer, run it at four times normal speed.
283  */
284 #define SYNCER_SHUTDOWN_SPEEDUP         4
285 static int sync_vnode_count;
286 static int syncer_worklist_len;
287 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
288     syncer_state;
289
290 /* Target for maximum number of vnodes. */
291 int desiredvnodes;
292 static int gapvnodes;           /* gap between wanted and desired */
293 static int vhiwat;              /* enough extras after expansion */
294 static int vlowat;              /* minimal extras before expansion */
295 static int vstir;               /* nonzero to stir non-free vnodes */
296 static volatile int vsmalltrigger = 8;  /* pref to keep if > this many pages */
297
298 static int
299 sysctl_update_desiredvnodes(SYSCTL_HANDLER_ARGS)
300 {
301         int error, old_desiredvnodes;
302
303         old_desiredvnodes = desiredvnodes;
304         if ((error = sysctl_handle_int(oidp, arg1, arg2, req)) != 0)
305                 return (error);
306         if (old_desiredvnodes != desiredvnodes) {
307                 wantfreevnodes = desiredvnodes / 4;
308                 /* XXX locking seems to be incomplete. */
309                 vfs_hash_changesize(desiredvnodes);
310                 cache_changesize(desiredvnodes);
311         }
312         return (0);
313 }
314
315 SYSCTL_PROC(_kern, KERN_MAXVNODES, maxvnodes,
316     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, &desiredvnodes, 0,
317     sysctl_update_desiredvnodes, "I", "Target for maximum number of vnodes");
318 SYSCTL_ULONG(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
319     &wantfreevnodes, 0, "Old name for vfs.wantfreevnodes (legacy)");
320 static int vnlru_nowhere;
321 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
322     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
323
324 /* Shift count for (uintptr_t)vp to initialize vp->v_hash. */
325 static int vnsz2log;
326
327 /*
328  * Support for the bufobj clean & dirty pctrie.
329  */
330 static void *
331 buf_trie_alloc(struct pctrie *ptree)
332 {
333
334         return uma_zalloc(buf_trie_zone, M_NOWAIT);
335 }
336
337 static void
338 buf_trie_free(struct pctrie *ptree, void *node)
339 {
340
341         uma_zfree(buf_trie_zone, node);
342 }
343 PCTRIE_DEFINE(BUF, buf, b_lblkno, buf_trie_alloc, buf_trie_free);
344
345 /*
346  * Initialize the vnode management data structures.
347  *
348  * Reevaluate the following cap on the number of vnodes after the physical
349  * memory size exceeds 512GB.  In the limit, as the physical memory size
350  * grows, the ratio of the memory size in KB to to vnodes approaches 64:1.
351  */
352 #ifndef MAXVNODES_MAX
353 #define MAXVNODES_MAX   (512 * 1024 * 1024 / 64)        /* 8M */
354 #endif
355
356 /*
357  * Initialize a vnode as it first enters the zone.
358  */
359 static int
360 vnode_init(void *mem, int size, int flags)
361 {
362         struct vnode *vp;
363         struct bufobj *bo;
364
365         vp = mem;
366         bzero(vp, size);
367         /*
368          * Setup locks.
369          */
370         vp->v_vnlock = &vp->v_lock;
371         mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
372         /*
373          * By default, don't allow shared locks unless filesystems opt-in.
374          */
375         lockinit(vp->v_vnlock, PVFS, "vnode", VLKTIMEOUT,
376             LK_NOSHARE | LK_IS_VNODE);
377         /*
378          * Initialize bufobj.
379          */
380         bo = &vp->v_bufobj;
381         rw_init(BO_LOCKPTR(bo), "bufobj interlock");
382         bo->bo_private = vp;
383         TAILQ_INIT(&bo->bo_clean.bv_hd);
384         TAILQ_INIT(&bo->bo_dirty.bv_hd);
385         /*
386          * Initialize namecache.
387          */
388         LIST_INIT(&vp->v_cache_src);
389         TAILQ_INIT(&vp->v_cache_dst);
390         /*
391          * Initialize rangelocks.
392          */
393         rangelock_init(&vp->v_rl);
394         return (0);
395 }
396
397 /*
398  * Free a vnode when it is cleared from the zone.
399  */
400 static void
401 vnode_fini(void *mem, int size)
402 {
403         struct vnode *vp;
404         struct bufobj *bo;
405
406         vp = mem;
407         rangelock_destroy(&vp->v_rl);
408         lockdestroy(vp->v_vnlock);
409         mtx_destroy(&vp->v_interlock);
410         bo = &vp->v_bufobj;
411         rw_destroy(BO_LOCKPTR(bo));
412 }
413
414 /*
415  * Provide the size of NFS nclnode and NFS fh for calculation of the
416  * vnode memory consumption.  The size is specified directly to
417  * eliminate dependency on NFS-private header.
418  *
419  * Other filesystems may use bigger or smaller (like UFS and ZFS)
420  * private inode data, but the NFS-based estimation is ample enough.
421  * Still, we care about differences in the size between 64- and 32-bit
422  * platforms.
423  *
424  * Namecache structure size is heuristically
425  * sizeof(struct namecache_ts) + CACHE_PATH_CUTOFF + 1.
426  */
427 #ifdef _LP64
428 #define NFS_NCLNODE_SZ  (528 + 64)
429 #define NC_SZ           148
430 #else
431 #define NFS_NCLNODE_SZ  (360 + 32)
432 #define NC_SZ           92
433 #endif
434
435 static void
436 vntblinit(void *dummy __unused)
437 {
438         u_int i;
439         int physvnodes, virtvnodes;
440
441         /*
442          * Desiredvnodes is a function of the physical memory size and the
443          * kernel's heap size.  Generally speaking, it scales with the
444          * physical memory size.  The ratio of desiredvnodes to the physical
445          * memory size is 1:16 until desiredvnodes exceeds 98,304.
446          * Thereafter, the
447          * marginal ratio of desiredvnodes to the physical memory size is
448          * 1:64.  However, desiredvnodes is limited by the kernel's heap
449          * size.  The memory required by desiredvnodes vnodes and vm objects
450          * must not exceed 1/10th of the kernel's heap size.
451          */
452         physvnodes = maxproc + pgtok(vm_cnt.v_page_count) / 64 +
453             3 * min(98304 * 16, pgtok(vm_cnt.v_page_count)) / 64;
454         virtvnodes = vm_kmem_size / (10 * (sizeof(struct vm_object) +
455             sizeof(struct vnode) + NC_SZ * ncsizefactor + NFS_NCLNODE_SZ));
456         desiredvnodes = min(physvnodes, virtvnodes);
457         if (desiredvnodes > MAXVNODES_MAX) {
458                 if (bootverbose)
459                         printf("Reducing kern.maxvnodes %d -> %d\n",
460                             desiredvnodes, MAXVNODES_MAX);
461                 desiredvnodes = MAXVNODES_MAX;
462         }
463         wantfreevnodes = desiredvnodes / 4;
464         mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
465         TAILQ_INIT(&vnode_free_list);
466         mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
467         vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
468             vnode_init, vnode_fini, UMA_ALIGN_PTR, 0);
469         vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
470             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
471         /*
472          * Preallocate enough nodes to support one-per buf so that
473          * we can not fail an insert.  reassignbuf() callers can not
474          * tolerate the insertion failure.
475          */
476         buf_trie_zone = uma_zcreate("BUF TRIE", pctrie_node_size(),
477             NULL, NULL, pctrie_zone_init, NULL, UMA_ALIGN_PTR, 
478             UMA_ZONE_NOFREE | UMA_ZONE_VM);
479         uma_prealloc(buf_trie_zone, nbuf);
480
481         vnodes_created = counter_u64_alloc(M_WAITOK);
482         recycles_count = counter_u64_alloc(M_WAITOK);
483         free_owe_inact = counter_u64_alloc(M_WAITOK);
484
485         /*
486          * Initialize the filesystem syncer.
487          */
488         syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
489             &syncer_mask);
490         syncer_maxdelay = syncer_mask + 1;
491         mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
492         cv_init(&sync_wakeup, "syncer");
493         for (i = 1; i <= sizeof(struct vnode); i <<= 1)
494                 vnsz2log++;
495         vnsz2log--;
496 }
497 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
498
499
500 /*
501  * Mark a mount point as busy. Used to synchronize access and to delay
502  * unmounting. Eventually, mountlist_mtx is not released on failure.
503  *
504  * vfs_busy() is a custom lock, it can block the caller.
505  * vfs_busy() only sleeps if the unmount is active on the mount point.
506  * For a mountpoint mp, vfs_busy-enforced lock is before lock of any
507  * vnode belonging to mp.
508  *
509  * Lookup uses vfs_busy() to traverse mount points.
510  * root fs                      var fs
511  * / vnode lock         A       / vnode lock (/var)             D
512  * /var vnode lock      B       /log vnode lock(/var/log)       E
513  * vfs_busy lock        C       vfs_busy lock                   F
514  *
515  * Within each file system, the lock order is C->A->B and F->D->E.
516  *
517  * When traversing across mounts, the system follows that lock order:
518  *
519  *        C->A->B
520  *              |
521  *              +->F->D->E
522  *
523  * The lookup() process for namei("/var") illustrates the process:
524  *  VOP_LOOKUP() obtains B while A is held
525  *  vfs_busy() obtains a shared lock on F while A and B are held
526  *  vput() releases lock on B
527  *  vput() releases lock on A
528  *  VFS_ROOT() obtains lock on D while shared lock on F is held
529  *  vfs_unbusy() releases shared lock on F
530  *  vn_lock() obtains lock on deadfs vnode vp_crossmp instead of A.
531  *    Attempt to lock A (instead of vp_crossmp) while D is held would
532  *    violate the global order, causing deadlocks.
533  *
534  * dounmount() locks B while F is drained.
535  */
536 int
537 vfs_busy(struct mount *mp, int flags)
538 {
539
540         MPASS((flags & ~MBF_MASK) == 0);
541         CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
542
543         MNT_ILOCK(mp);
544         MNT_REF(mp);
545         /*
546          * If mount point is currently being unmounted, sleep until the
547          * mount point fate is decided.  If thread doing the unmounting fails,
548          * it will clear MNTK_UNMOUNT flag before waking us up, indicating
549          * that this mount point has survived the unmount attempt and vfs_busy
550          * should retry.  Otherwise the unmounter thread will set MNTK_REFEXPIRE
551          * flag in addition to MNTK_UNMOUNT, indicating that mount point is
552          * about to be really destroyed.  vfs_busy needs to release its
553          * reference on the mount point in this case and return with ENOENT,
554          * telling the caller that mount mount it tried to busy is no longer
555          * valid.
556          */
557         while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
558                 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
559                         MNT_REL(mp);
560                         MNT_IUNLOCK(mp);
561                         CTR1(KTR_VFS, "%s: failed busying before sleeping",
562                             __func__);
563                         return (ENOENT);
564                 }
565                 if (flags & MBF_MNTLSTLOCK)
566                         mtx_unlock(&mountlist_mtx);
567                 mp->mnt_kern_flag |= MNTK_MWAIT;
568                 msleep(mp, MNT_MTX(mp), PVFS | PDROP, "vfs_busy", 0);
569                 if (flags & MBF_MNTLSTLOCK)
570                         mtx_lock(&mountlist_mtx);
571                 MNT_ILOCK(mp);
572         }
573         if (flags & MBF_MNTLSTLOCK)
574                 mtx_unlock(&mountlist_mtx);
575         mp->mnt_lockref++;
576         MNT_IUNLOCK(mp);
577         return (0);
578 }
579
580 /*
581  * Free a busy filesystem.
582  */
583 void
584 vfs_unbusy(struct mount *mp)
585 {
586
587         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
588         MNT_ILOCK(mp);
589         MNT_REL(mp);
590         KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
591         mp->mnt_lockref--;
592         if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
593                 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
594                 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
595                 mp->mnt_kern_flag &= ~MNTK_DRAINING;
596                 wakeup(&mp->mnt_lockref);
597         }
598         MNT_IUNLOCK(mp);
599 }
600
601 /*
602  * Lookup a mount point by filesystem identifier.
603  */
604 struct mount *
605 vfs_getvfs(fsid_t *fsid)
606 {
607         struct mount *mp;
608
609         CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
610         mtx_lock(&mountlist_mtx);
611         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
612                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
613                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
614                         vfs_ref(mp);
615                         mtx_unlock(&mountlist_mtx);
616                         return (mp);
617                 }
618         }
619         mtx_unlock(&mountlist_mtx);
620         CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
621         return ((struct mount *) 0);
622 }
623
624 /*
625  * Lookup a mount point by filesystem identifier, busying it before
626  * returning.
627  *
628  * To avoid congestion on mountlist_mtx, implement simple direct-mapped
629  * cache for popular filesystem identifiers.  The cache is lockess, using
630  * the fact that struct mount's are never freed.  In worst case we may
631  * get pointer to unmounted or even different filesystem, so we have to
632  * check what we got, and go slow way if so.
633  */
634 struct mount *
635 vfs_busyfs(fsid_t *fsid)
636 {
637 #define FSID_CACHE_SIZE 256
638         typedef struct mount * volatile vmp_t;
639         static vmp_t cache[FSID_CACHE_SIZE];
640         struct mount *mp;
641         int error;
642         uint32_t hash;
643
644         CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
645         hash = fsid->val[0] ^ fsid->val[1];
646         hash = (hash >> 16 ^ hash) & (FSID_CACHE_SIZE - 1);
647         mp = cache[hash];
648         if (mp == NULL ||
649             mp->mnt_stat.f_fsid.val[0] != fsid->val[0] ||
650             mp->mnt_stat.f_fsid.val[1] != fsid->val[1])
651                 goto slow;
652         if (vfs_busy(mp, 0) != 0) {
653                 cache[hash] = NULL;
654                 goto slow;
655         }
656         if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
657             mp->mnt_stat.f_fsid.val[1] == fsid->val[1])
658                 return (mp);
659         else
660             vfs_unbusy(mp);
661
662 slow:
663         mtx_lock(&mountlist_mtx);
664         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
665                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
666                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
667                         error = vfs_busy(mp, MBF_MNTLSTLOCK);
668                         if (error) {
669                                 cache[hash] = NULL;
670                                 mtx_unlock(&mountlist_mtx);
671                                 return (NULL);
672                         }
673                         cache[hash] = mp;
674                         return (mp);
675                 }
676         }
677         CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
678         mtx_unlock(&mountlist_mtx);
679         return ((struct mount *) 0);
680 }
681
682 /*
683  * Check if a user can access privileged mount options.
684  */
685 int
686 vfs_suser(struct mount *mp, struct thread *td)
687 {
688         int error;
689
690         /*
691          * If the thread is jailed, but this is not a jail-friendly file
692          * system, deny immediately.
693          */
694         if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
695                 return (EPERM);
696
697         /*
698          * If the file system was mounted outside the jail of the calling
699          * thread, deny immediately.
700          */
701         if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
702                 return (EPERM);
703
704         /*
705          * If file system supports delegated administration, we don't check
706          * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
707          * by the file system itself.
708          * If this is not the user that did original mount, we check for
709          * the PRIV_VFS_MOUNT_OWNER privilege.
710          */
711         if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
712             mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
713                 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
714                         return (error);
715         }
716         return (0);
717 }
718
719 /*
720  * Get a new unique fsid.  Try to make its val[0] unique, since this value
721  * will be used to create fake device numbers for stat().  Also try (but
722  * not so hard) make its val[0] unique mod 2^16, since some emulators only
723  * support 16-bit device numbers.  We end up with unique val[0]'s for the
724  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
725  *
726  * Keep in mind that several mounts may be running in parallel.  Starting
727  * the search one past where the previous search terminated is both a
728  * micro-optimization and a defense against returning the same fsid to
729  * different mounts.
730  */
731 void
732 vfs_getnewfsid(struct mount *mp)
733 {
734         static uint16_t mntid_base;
735         struct mount *nmp;
736         fsid_t tfsid;
737         int mtype;
738
739         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
740         mtx_lock(&mntid_mtx);
741         mtype = mp->mnt_vfc->vfc_typenum;
742         tfsid.val[1] = mtype;
743         mtype = (mtype & 0xFF) << 24;
744         for (;;) {
745                 tfsid.val[0] = makedev(255,
746                     mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
747                 mntid_base++;
748                 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
749                         break;
750                 vfs_rel(nmp);
751         }
752         mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
753         mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
754         mtx_unlock(&mntid_mtx);
755 }
756
757 /*
758  * Knob to control the precision of file timestamps:
759  *
760  *   0 = seconds only; nanoseconds zeroed.
761  *   1 = seconds and nanoseconds, accurate within 1/HZ.
762  *   2 = seconds and nanoseconds, truncated to microseconds.
763  * >=3 = seconds and nanoseconds, maximum precision.
764  */
765 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
766
767 static int timestamp_precision = TSP_USEC;
768 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
769     &timestamp_precision, 0, "File timestamp precision (0: seconds, "
770     "1: sec + ns accurate to 1/HZ, 2: sec + ns truncated to us, "
771     "3+: sec + ns (max. precision))");
772
773 /*
774  * Get a current timestamp.
775  */
776 void
777 vfs_timestamp(struct timespec *tsp)
778 {
779         struct timeval tv;
780
781         switch (timestamp_precision) {
782         case TSP_SEC:
783                 tsp->tv_sec = time_second;
784                 tsp->tv_nsec = 0;
785                 break;
786         case TSP_HZ:
787                 getnanotime(tsp);
788                 break;
789         case TSP_USEC:
790                 microtime(&tv);
791                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
792                 break;
793         case TSP_NSEC:
794         default:
795                 nanotime(tsp);
796                 break;
797         }
798 }
799
800 /*
801  * Set vnode attributes to VNOVAL
802  */
803 void
804 vattr_null(struct vattr *vap)
805 {
806
807         vap->va_type = VNON;
808         vap->va_size = VNOVAL;
809         vap->va_bytes = VNOVAL;
810         vap->va_mode = VNOVAL;
811         vap->va_nlink = VNOVAL;
812         vap->va_uid = VNOVAL;
813         vap->va_gid = VNOVAL;
814         vap->va_fsid = VNOVAL;
815         vap->va_fileid = VNOVAL;
816         vap->va_blocksize = VNOVAL;
817         vap->va_rdev = VNOVAL;
818         vap->va_atime.tv_sec = VNOVAL;
819         vap->va_atime.tv_nsec = VNOVAL;
820         vap->va_mtime.tv_sec = VNOVAL;
821         vap->va_mtime.tv_nsec = VNOVAL;
822         vap->va_ctime.tv_sec = VNOVAL;
823         vap->va_ctime.tv_nsec = VNOVAL;
824         vap->va_birthtime.tv_sec = VNOVAL;
825         vap->va_birthtime.tv_nsec = VNOVAL;
826         vap->va_flags = VNOVAL;
827         vap->va_gen = VNOVAL;
828         vap->va_vaflags = 0;
829 }
830
831 /*
832  * This routine is called when we have too many vnodes.  It attempts
833  * to free <count> vnodes and will potentially free vnodes that still
834  * have VM backing store (VM backing store is typically the cause
835  * of a vnode blowout so we want to do this).  Therefore, this operation
836  * is not considered cheap.
837  *
838  * A number of conditions may prevent a vnode from being reclaimed.
839  * the buffer cache may have references on the vnode, a directory
840  * vnode may still have references due to the namei cache representing
841  * underlying files, or the vnode may be in active use.   It is not
842  * desirable to reuse such vnodes.  These conditions may cause the
843  * number of vnodes to reach some minimum value regardless of what
844  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
845  */
846 static int
847 vlrureclaim(struct mount *mp, int reclaim_nc_src, int trigger)
848 {
849         struct vnode *vp;
850         int count, done, target;
851
852         done = 0;
853         vn_start_write(NULL, &mp, V_WAIT);
854         MNT_ILOCK(mp);
855         count = mp->mnt_nvnodelistsize;
856         target = count * (int64_t)gapvnodes / imax(desiredvnodes, 1);
857         target = target / 10 + 1;
858         while (count != 0 && done < target) {
859                 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
860                 while (vp != NULL && vp->v_type == VMARKER)
861                         vp = TAILQ_NEXT(vp, v_nmntvnodes);
862                 if (vp == NULL)
863                         break;
864                 /*
865                  * XXX LRU is completely broken for non-free vnodes.  First
866                  * by calling here in mountpoint order, then by moving
867                  * unselected vnodes to the end here, and most grossly by
868                  * removing the vlruvp() function that was supposed to
869                  * maintain the order.  (This function was born broken
870                  * since syncer problems prevented it doing anything.)  The
871                  * order is closer to LRC (C = Created).
872                  *
873                  * LRU reclaiming of vnodes seems to have last worked in
874                  * FreeBSD-3 where LRU wasn't mentioned under any spelling.
875                  * Then there was no hold count, and inactive vnodes were
876                  * simply put on the free list in LRU order.  The separate
877                  * lists also break LRU.  We prefer to reclaim from the
878                  * free list for technical reasons.  This tends to thrash
879                  * the free list to keep very unrecently used held vnodes.
880                  * The problem is mitigated by keeping the free list large.
881                  */
882                 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
883                 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
884                 --count;
885                 if (!VI_TRYLOCK(vp))
886                         goto next_iter;
887                 /*
888                  * If it's been deconstructed already, it's still
889                  * referenced, or it exceeds the trigger, skip it.
890                  * Also skip free vnodes.  We are trying to make space
891                  * to expand the free list, not reduce it.
892                  */
893                 if (vp->v_usecount ||
894                     (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
895                     ((vp->v_iflag & VI_FREE) != 0) ||
896                     (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
897                     vp->v_object->resident_page_count > trigger)) {
898                         VI_UNLOCK(vp);
899                         goto next_iter;
900                 }
901                 MNT_IUNLOCK(mp);
902                 vholdl(vp);
903                 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
904                         vdrop(vp);
905                         goto next_iter_mntunlocked;
906                 }
907                 VI_LOCK(vp);
908                 /*
909                  * v_usecount may have been bumped after VOP_LOCK() dropped
910                  * the vnode interlock and before it was locked again.
911                  *
912                  * It is not necessary to recheck VI_DOOMED because it can
913                  * only be set by another thread that holds both the vnode
914                  * lock and vnode interlock.  If another thread has the
915                  * vnode lock before we get to VOP_LOCK() and obtains the
916                  * vnode interlock after VOP_LOCK() drops the vnode
917                  * interlock, the other thread will be unable to drop the
918                  * vnode lock before our VOP_LOCK() call fails.
919                  */
920                 if (vp->v_usecount ||
921                     (!reclaim_nc_src && !LIST_EMPTY(&vp->v_cache_src)) ||
922                     (vp->v_iflag & VI_FREE) != 0 ||
923                     (vp->v_object != NULL &&
924                     vp->v_object->resident_page_count > trigger)) {
925                         VOP_UNLOCK(vp, LK_INTERLOCK);
926                         vdrop(vp);
927                         goto next_iter_mntunlocked;
928                 }
929                 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
930                     ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
931                 counter_u64_add(recycles_count, 1);
932                 vgonel(vp);
933                 VOP_UNLOCK(vp, 0);
934                 vdropl(vp);
935                 done++;
936 next_iter_mntunlocked:
937                 if (!should_yield())
938                         goto relock_mnt;
939                 goto yield;
940 next_iter:
941                 if (!should_yield())
942                         continue;
943                 MNT_IUNLOCK(mp);
944 yield:
945                 kern_yield(PRI_USER);
946 relock_mnt:
947                 MNT_ILOCK(mp);
948         }
949         MNT_IUNLOCK(mp);
950         vn_finished_write(mp);
951         return done;
952 }
953
954 static int max_vnlru_free = 10000; /* limit on vnode free requests per call */
955 SYSCTL_INT(_debug, OID_AUTO, max_vnlru_free, CTLFLAG_RW, &max_vnlru_free,
956     0,
957     "limit on vnode free requests per call to the vnlru_free routine");
958
959 /*
960  * Attempt to reduce the free list by the requested amount.
961  */
962 static void
963 vnlru_free_locked(int count, struct vfsops *mnt_op)
964 {
965         struct vnode *vp;
966         struct mount *mp;
967         bool tried_batches;
968
969         tried_batches = false;
970         mtx_assert(&vnode_free_list_mtx, MA_OWNED);
971         if (count > max_vnlru_free)
972                 count = max_vnlru_free;
973         for (; count > 0; count--) {
974                 vp = TAILQ_FIRST(&vnode_free_list);
975                 /*
976                  * The list can be modified while the free_list_mtx
977                  * has been dropped and vp could be NULL here.
978                  */
979                 if (vp == NULL) {
980                         if (tried_batches)
981                                 break;
982                         mtx_unlock(&vnode_free_list_mtx);
983                         vnlru_return_batches(mnt_op);
984                         tried_batches = true;
985                         mtx_lock(&vnode_free_list_mtx);
986                         continue;
987                 }
988
989                 VNASSERT(vp->v_op != NULL, vp,
990                     ("vnlru_free: vnode already reclaimed."));
991                 KASSERT((vp->v_iflag & VI_FREE) != 0,
992                     ("Removing vnode not on freelist"));
993                 KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
994                     ("Mangling active vnode"));
995                 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
996
997                 /*
998                  * Don't recycle if our vnode is from different type
999                  * of mount point.  Note that mp is type-safe, the
1000                  * check does not reach unmapped address even if
1001                  * vnode is reclaimed.
1002                  * Don't recycle if we can't get the interlock without
1003                  * blocking.
1004                  */
1005                 if ((mnt_op != NULL && (mp = vp->v_mount) != NULL &&
1006                     mp->mnt_op != mnt_op) || !VI_TRYLOCK(vp)) {
1007                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_actfreelist);
1008                         continue;
1009                 }
1010                 VNASSERT((vp->v_iflag & VI_FREE) != 0 && vp->v_holdcnt == 0,
1011                     vp, ("vp inconsistent on freelist"));
1012
1013                 /*
1014                  * The clear of VI_FREE prevents activation of the
1015                  * vnode.  There is no sense in putting the vnode on
1016                  * the mount point active list, only to remove it
1017                  * later during recycling.  Inline the relevant part
1018                  * of vholdl(), to avoid triggering assertions or
1019                  * activating.
1020                  */
1021                 freevnodes--;
1022                 vp->v_iflag &= ~VI_FREE;
1023                 refcount_acquire(&vp->v_holdcnt);
1024
1025                 mtx_unlock(&vnode_free_list_mtx);
1026                 VI_UNLOCK(vp);
1027                 vtryrecycle(vp);
1028                 /*
1029                  * If the recycled succeeded this vdrop will actually free
1030                  * the vnode.  If not it will simply place it back on
1031                  * the free list.
1032                  */
1033                 vdrop(vp);
1034                 mtx_lock(&vnode_free_list_mtx);
1035         }
1036 }
1037
1038 void
1039 vnlru_free(int count, struct vfsops *mnt_op)
1040 {
1041
1042         mtx_lock(&vnode_free_list_mtx);
1043         vnlru_free_locked(count, mnt_op);
1044         mtx_unlock(&vnode_free_list_mtx);
1045 }
1046
1047
1048 /* XXX some names and initialization are bad for limits and watermarks. */
1049 static int
1050 vspace(void)
1051 {
1052         int space;
1053
1054         gapvnodes = imax(desiredvnodes - wantfreevnodes, 100);
1055         vhiwat = gapvnodes / 11; /* 9% -- just under the 10% in vlrureclaim() */
1056         vlowat = vhiwat / 2;
1057         if (numvnodes > desiredvnodes)
1058                 return (0);
1059         space = desiredvnodes - numvnodes;
1060         if (freevnodes > wantfreevnodes)
1061                 space += freevnodes - wantfreevnodes;
1062         return (space);
1063 }
1064
1065 static void
1066 vnlru_return_batch_locked(struct mount *mp)
1067 {
1068         struct vnode *vp;
1069
1070         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
1071
1072         if (mp->mnt_tmpfreevnodelistsize == 0)
1073                 return;
1074
1075         TAILQ_FOREACH(vp, &mp->mnt_tmpfreevnodelist, v_actfreelist) {
1076                 VNASSERT((vp->v_mflag & VMP_TMPMNTFREELIST) != 0, vp,
1077                     ("vnode without VMP_TMPMNTFREELIST on mnt_tmpfreevnodelist"));
1078                 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
1079         }
1080         mtx_lock(&vnode_free_list_mtx);
1081         TAILQ_CONCAT(&vnode_free_list, &mp->mnt_tmpfreevnodelist, v_actfreelist);
1082         freevnodes += mp->mnt_tmpfreevnodelistsize;
1083         mtx_unlock(&vnode_free_list_mtx);
1084         mp->mnt_tmpfreevnodelistsize = 0;
1085 }
1086
1087 static void
1088 vnlru_return_batch(struct mount *mp)
1089 {
1090
1091         mtx_lock(&mp->mnt_listmtx);
1092         vnlru_return_batch_locked(mp);
1093         mtx_unlock(&mp->mnt_listmtx);
1094 }
1095
1096 static void
1097 vnlru_return_batches(struct vfsops *mnt_op)
1098 {
1099         struct mount *mp, *nmp;
1100         bool need_unbusy;
1101
1102         mtx_lock(&mountlist_mtx);
1103         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1104                 need_unbusy = false;
1105                 if (mnt_op != NULL && mp->mnt_op != mnt_op)
1106                         goto next;
1107                 if (mp->mnt_tmpfreevnodelistsize == 0)
1108                         goto next;
1109                 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) == 0) {
1110                         vnlru_return_batch(mp);
1111                         need_unbusy = true;
1112                         mtx_lock(&mountlist_mtx);
1113                 }
1114 next:
1115                 nmp = TAILQ_NEXT(mp, mnt_list);
1116                 if (need_unbusy)
1117                         vfs_unbusy(mp);
1118         }
1119         mtx_unlock(&mountlist_mtx);
1120 }
1121
1122 /*
1123  * Attempt to recycle vnodes in a context that is always safe to block.
1124  * Calling vlrurecycle() from the bowels of filesystem code has some
1125  * interesting deadlock problems.
1126  */
1127 static struct proc *vnlruproc;
1128 static int vnlruproc_sig;
1129
1130 static void
1131 vnlru_proc(void)
1132 {
1133         struct mount *mp, *nmp;
1134         unsigned long ofreevnodes, onumvnodes;
1135         int done, force, reclaim_nc_src, trigger, usevnodes;
1136
1137         EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, vnlruproc,
1138             SHUTDOWN_PRI_FIRST);
1139
1140         force = 0;
1141         for (;;) {
1142                 kproc_suspend_check(vnlruproc);
1143                 mtx_lock(&vnode_free_list_mtx);
1144                 /*
1145                  * If numvnodes is too large (due to desiredvnodes being
1146                  * adjusted using its sysctl, or emergency growth), first
1147                  * try to reduce it by discarding from the free list.
1148                  */
1149                 if (numvnodes > desiredvnodes)
1150                         vnlru_free_locked(numvnodes - desiredvnodes, NULL);
1151                 /*
1152                  * Sleep if the vnode cache is in a good state.  This is
1153                  * when it is not over-full and has space for about a 4%
1154                  * or 9% expansion (by growing its size or inexcessively
1155                  * reducing its free list).  Otherwise, try to reclaim
1156                  * space for a 10% expansion.
1157                  */
1158                 if (vstir && force == 0) {
1159                         force = 1;
1160                         vstir = 0;
1161                 }
1162                 if (vspace() >= vlowat && force == 0) {
1163                         vnlruproc_sig = 0;
1164                         wakeup(&vnlruproc_sig);
1165                         msleep(vnlruproc, &vnode_free_list_mtx,
1166                             PVFS|PDROP, "vlruwt", hz);
1167                         continue;
1168                 }
1169                 mtx_unlock(&vnode_free_list_mtx);
1170                 done = 0;
1171                 ofreevnodes = freevnodes;
1172                 onumvnodes = numvnodes;
1173                 /*
1174                  * Calculate parameters for recycling.  These are the same
1175                  * throughout the loop to give some semblance of fairness.
1176                  * The trigger point is to avoid recycling vnodes with lots
1177                  * of resident pages.  We aren't trying to free memory; we
1178                  * are trying to recycle or at least free vnodes.
1179                  */
1180                 if (numvnodes <= desiredvnodes)
1181                         usevnodes = numvnodes - freevnodes;
1182                 else
1183                         usevnodes = numvnodes;
1184                 if (usevnodes <= 0)
1185                         usevnodes = 1;
1186                 /*
1187                  * The trigger value is is chosen to give a conservatively
1188                  * large value to ensure that it alone doesn't prevent
1189                  * making progress.  The value can easily be so large that
1190                  * it is effectively infinite in some congested and
1191                  * misconfigured cases, and this is necessary.  Normally
1192                  * it is about 8 to 100 (pages), which is quite large.
1193                  */
1194                 trigger = vm_cnt.v_page_count * 2 / usevnodes;
1195                 if (force < 2)
1196                         trigger = vsmalltrigger;
1197                 reclaim_nc_src = force >= 3;
1198                 mtx_lock(&mountlist_mtx);
1199                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
1200                         if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
1201                                 nmp = TAILQ_NEXT(mp, mnt_list);
1202                                 continue;
1203                         }
1204                         done += vlrureclaim(mp, reclaim_nc_src, trigger);
1205                         mtx_lock(&mountlist_mtx);
1206                         nmp = TAILQ_NEXT(mp, mnt_list);
1207                         vfs_unbusy(mp);
1208                 }
1209                 mtx_unlock(&mountlist_mtx);
1210                 if (onumvnodes > desiredvnodes && numvnodes <= desiredvnodes)
1211                         uma_reclaim();
1212                 if (done == 0) {
1213                         if (force == 0 || force == 1) {
1214                                 force = 2;
1215                                 continue;
1216                         }
1217                         if (force == 2) {
1218                                 force = 3;
1219                                 continue;
1220                         }
1221                         force = 0;
1222                         vnlru_nowhere++;
1223                         tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
1224                 } else
1225                         kern_yield(PRI_USER);
1226                 /*
1227                  * After becoming active to expand above low water, keep
1228                  * active until above high water.
1229                  */
1230                 force = vspace() < vhiwat;
1231         }
1232 }
1233
1234 static struct kproc_desc vnlru_kp = {
1235         "vnlru",
1236         vnlru_proc,
1237         &vnlruproc
1238 };
1239 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
1240     &vnlru_kp);
1241  
1242 /*
1243  * Routines having to do with the management of the vnode table.
1244  */
1245
1246 /*
1247  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
1248  * before we actually vgone().  This function must be called with the vnode
1249  * held to prevent the vnode from being returned to the free list midway
1250  * through vgone().
1251  */
1252 static int
1253 vtryrecycle(struct vnode *vp)
1254 {
1255         struct mount *vnmp;
1256
1257         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
1258         VNASSERT(vp->v_holdcnt, vp,
1259             ("vtryrecycle: Recycling vp %p without a reference.", vp));
1260         /*
1261          * This vnode may found and locked via some other list, if so we
1262          * can't recycle it yet.
1263          */
1264         if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1265                 CTR2(KTR_VFS,
1266                     "%s: impossible to recycle, vp %p lock is already held",
1267                     __func__, vp);
1268                 return (EWOULDBLOCK);
1269         }
1270         /*
1271          * Don't recycle if its filesystem is being suspended.
1272          */
1273         if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
1274                 VOP_UNLOCK(vp, 0);
1275                 CTR2(KTR_VFS,
1276                     "%s: impossible to recycle, cannot start the write for %p",
1277                     __func__, vp);
1278                 return (EBUSY);
1279         }
1280         /*
1281          * If we got this far, we need to acquire the interlock and see if
1282          * anyone picked up this vnode from another list.  If not, we will
1283          * mark it with DOOMED via vgonel() so that anyone who does find it
1284          * will skip over it.
1285          */
1286         VI_LOCK(vp);
1287         if (vp->v_usecount) {
1288                 VOP_UNLOCK(vp, LK_INTERLOCK);
1289                 vn_finished_write(vnmp);
1290                 CTR2(KTR_VFS,
1291                     "%s: impossible to recycle, %p is already referenced",
1292                     __func__, vp);
1293                 return (EBUSY);
1294         }
1295         if ((vp->v_iflag & VI_DOOMED) == 0) {
1296                 counter_u64_add(recycles_count, 1);
1297                 vgonel(vp);
1298         }
1299         VOP_UNLOCK(vp, LK_INTERLOCK);
1300         vn_finished_write(vnmp);
1301         return (0);
1302 }
1303
1304 static void
1305 vcheckspace(void)
1306 {
1307
1308         if (vspace() < vlowat && vnlruproc_sig == 0) {
1309                 vnlruproc_sig = 1;
1310                 wakeup(vnlruproc);
1311         }
1312 }
1313
1314 /*
1315  * Wait if necessary for space for a new vnode.
1316  */
1317 static int
1318 getnewvnode_wait(int suspended)
1319 {
1320
1321         mtx_assert(&vnode_free_list_mtx, MA_OWNED);
1322         if (numvnodes >= desiredvnodes) {
1323                 if (suspended) {
1324                         /*
1325                          * The file system is being suspended.  We cannot
1326                          * risk a deadlock here, so allow allocation of
1327                          * another vnode even if this would give too many.
1328                          */
1329                         return (0);
1330                 }
1331                 if (vnlruproc_sig == 0) {
1332                         vnlruproc_sig = 1;      /* avoid unnecessary wakeups */
1333                         wakeup(vnlruproc);
1334                 }
1335                 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
1336                     "vlruwk", hz);
1337         }
1338         /* Post-adjust like the pre-adjust in getnewvnode(). */
1339         if (numvnodes + 1 > desiredvnodes && freevnodes > 1)
1340                 vnlru_free_locked(1, NULL);
1341         return (numvnodes >= desiredvnodes ? ENFILE : 0);
1342 }
1343
1344 /*
1345  * This hack is fragile, and probably not needed any more now that the
1346  * watermark handling works.
1347  */
1348 void
1349 getnewvnode_reserve(u_int count)
1350 {
1351         struct thread *td;
1352
1353         /* Pre-adjust like the pre-adjust in getnewvnode(), with any count. */
1354         /* XXX no longer so quick, but this part is not racy. */
1355         mtx_lock(&vnode_free_list_mtx);
1356         if (numvnodes + count > desiredvnodes && freevnodes > wantfreevnodes)
1357                 vnlru_free_locked(ulmin(numvnodes + count - desiredvnodes,
1358                     freevnodes - wantfreevnodes), NULL);
1359         mtx_unlock(&vnode_free_list_mtx);
1360
1361         td = curthread;
1362         /* First try to be quick and racy. */
1363         if (atomic_fetchadd_long(&numvnodes, count) + count <= desiredvnodes) {
1364                 td->td_vp_reserv += count;
1365                 vcheckspace();  /* XXX no longer so quick, but more racy */
1366                 return;
1367         } else
1368                 atomic_subtract_long(&numvnodes, count);
1369
1370         mtx_lock(&vnode_free_list_mtx);
1371         while (count > 0) {
1372                 if (getnewvnode_wait(0) == 0) {
1373                         count--;
1374                         td->td_vp_reserv++;
1375                         atomic_add_long(&numvnodes, 1);
1376                 }
1377         }
1378         vcheckspace();
1379         mtx_unlock(&vnode_free_list_mtx);
1380 }
1381
1382 /*
1383  * This hack is fragile, especially if desiredvnodes or wantvnodes are
1384  * misconfgured or changed significantly.  Reducing desiredvnodes below
1385  * the reserved amount should cause bizarre behaviour like reducing it
1386  * below the number of active vnodes -- the system will try to reduce
1387  * numvnodes to match, but should fail, so the subtraction below should
1388  * not overflow.
1389  */
1390 void
1391 getnewvnode_drop_reserve(void)
1392 {
1393         struct thread *td;
1394
1395         td = curthread;
1396         atomic_subtract_long(&numvnodes, td->td_vp_reserv);
1397         td->td_vp_reserv = 0;
1398 }
1399
1400 /*
1401  * Return the next vnode from the free list.
1402  */
1403 int
1404 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
1405     struct vnode **vpp)
1406 {
1407         struct vnode *vp;
1408         struct thread *td;
1409         struct lock_object *lo;
1410         static int cyclecount;
1411         int error;
1412
1413         CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
1414         vp = NULL;
1415         td = curthread;
1416         if (td->td_vp_reserv > 0) {
1417                 td->td_vp_reserv -= 1;
1418                 goto alloc;
1419         }
1420         mtx_lock(&vnode_free_list_mtx);
1421         if (numvnodes < desiredvnodes)
1422                 cyclecount = 0;
1423         else if (cyclecount++ >= freevnodes) {
1424                 cyclecount = 0;
1425                 vstir = 1;
1426         }
1427         /*
1428          * Grow the vnode cache if it will not be above its target max
1429          * after growing.  Otherwise, if the free list is nonempty, try
1430          * to reclaim 1 item from it before growing the cache (possibly
1431          * above its target max if the reclamation failed or is delayed).
1432          * Otherwise, wait for some space.  In all cases, schedule
1433          * vnlru_proc() if we are getting short of space.  The watermarks
1434          * should be chosen so that we never wait or even reclaim from
1435          * the free list to below its target minimum.
1436          */
1437         if (numvnodes + 1 <= desiredvnodes)
1438                 ;
1439         else if (freevnodes > 0)
1440                 vnlru_free_locked(1, NULL);
1441         else {
1442                 error = getnewvnode_wait(mp != NULL && (mp->mnt_kern_flag &
1443                     MNTK_SUSPEND));
1444 #if 0   /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
1445                 if (error != 0) {
1446                         mtx_unlock(&vnode_free_list_mtx);
1447                         return (error);
1448                 }
1449 #endif
1450         }
1451         vcheckspace();
1452         atomic_add_long(&numvnodes, 1);
1453         mtx_unlock(&vnode_free_list_mtx);
1454 alloc:
1455         counter_u64_add(vnodes_created, 1);
1456         vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
1457         /*
1458          * Locks are given the generic name "vnode" when created.
1459          * Follow the historic practice of using the filesystem
1460          * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
1461          *
1462          * Locks live in a witness group keyed on their name. Thus,
1463          * when a lock is renamed, it must also move from the witness
1464          * group of its old name to the witness group of its new name.
1465          *
1466          * The change only needs to be made when the vnode moves
1467          * from one filesystem type to another. We ensure that each
1468          * filesystem use a single static name pointer for its tag so
1469          * that we can compare pointers rather than doing a strcmp().
1470          */
1471         lo = &vp->v_vnlock->lock_object;
1472         if (lo->lo_name != tag) {
1473                 lo->lo_name = tag;
1474                 WITNESS_DESTROY(lo);
1475                 WITNESS_INIT(lo, tag);
1476         }
1477         /*
1478          * By default, don't allow shared locks unless filesystems opt-in.
1479          */
1480         vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
1481         /*
1482          * Finalize various vnode identity bits.
1483          */
1484         KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
1485         KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
1486         KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
1487         vp->v_type = VNON;
1488         vp->v_tag = tag;
1489         vp->v_op = vops;
1490         v_init_counters(vp);
1491         vp->v_bufobj.bo_ops = &buf_ops_bio;
1492 #ifdef DIAGNOSTIC
1493         if (mp == NULL && vops != &dead_vnodeops)
1494                 printf("NULL mp in getnewvnode(9), tag %s\n", tag);
1495 #endif
1496 #ifdef MAC
1497         mac_vnode_init(vp);
1498         if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1499                 mac_vnode_associate_singlelabel(mp, vp);
1500 #endif
1501         if (mp != NULL) {
1502                 vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
1503                 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1504                         vp->v_vflag |= VV_NOKNOTE;
1505         }
1506
1507         /*
1508          * For the filesystems which do not use vfs_hash_insert(),
1509          * still initialize v_hash to have vfs_hash_index() useful.
1510          * E.g., nullfs uses vfs_hash_index() on the lower vnode for
1511          * its own hashing.
1512          */
1513         vp->v_hash = (uintptr_t)vp >> vnsz2log;
1514
1515         *vpp = vp;
1516         return (0);
1517 }
1518
1519 /*
1520  * Delete from old mount point vnode list, if on one.
1521  */
1522 static void
1523 delmntque(struct vnode *vp)
1524 {
1525         struct mount *mp;
1526         int active;
1527
1528         mp = vp->v_mount;
1529         if (mp == NULL)
1530                 return;
1531         MNT_ILOCK(mp);
1532         VI_LOCK(vp);
1533         KASSERT(mp->mnt_activevnodelistsize <= mp->mnt_nvnodelistsize,
1534             ("Active vnode list size %d > Vnode list size %d",
1535              mp->mnt_activevnodelistsize, mp->mnt_nvnodelistsize));
1536         active = vp->v_iflag & VI_ACTIVE;
1537         vp->v_iflag &= ~VI_ACTIVE;
1538         if (active) {
1539                 mtx_lock(&mp->mnt_listmtx);
1540                 TAILQ_REMOVE(&mp->mnt_activevnodelist, vp, v_actfreelist);
1541                 mp->mnt_activevnodelistsize--;
1542                 mtx_unlock(&mp->mnt_listmtx);
1543         }
1544         vp->v_mount = NULL;
1545         VI_UNLOCK(vp);
1546         VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1547                 ("bad mount point vnode list size"));
1548         TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1549         mp->mnt_nvnodelistsize--;
1550         MNT_REL(mp);
1551         MNT_IUNLOCK(mp);
1552 }
1553
1554 static void
1555 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1556 {
1557
1558         vp->v_data = NULL;
1559         vp->v_op = &dead_vnodeops;
1560         vgone(vp);
1561         vput(vp);
1562 }
1563
1564 /*
1565  * Insert into list of vnodes for the new mount point, if available.
1566  */
1567 int
1568 insmntque1(struct vnode *vp, struct mount *mp,
1569         void (*dtr)(struct vnode *, void *), void *dtr_arg)
1570 {
1571
1572         KASSERT(vp->v_mount == NULL,
1573                 ("insmntque: vnode already on per mount vnode list"));
1574         VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1575         ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
1576
1577         /*
1578          * We acquire the vnode interlock early to ensure that the
1579          * vnode cannot be recycled by another process releasing a
1580          * holdcnt on it before we get it on both the vnode list
1581          * and the active vnode list. The mount mutex protects only
1582          * manipulation of the vnode list and the vnode freelist
1583          * mutex protects only manipulation of the active vnode list.
1584          * Hence the need to hold the vnode interlock throughout.
1585          */
1586         MNT_ILOCK(mp);
1587         VI_LOCK(vp);
1588         if (((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1589             ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1590             mp->mnt_nvnodelistsize == 0)) &&
1591             (vp->v_vflag & VV_FORCEINSMQ) == 0) {
1592                 VI_UNLOCK(vp);
1593                 MNT_IUNLOCK(mp);
1594                 if (dtr != NULL)
1595                         dtr(vp, dtr_arg);
1596                 return (EBUSY);
1597         }
1598         vp->v_mount = mp;
1599         MNT_REF(mp);
1600         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1601         VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1602                 ("neg mount point vnode list size"));
1603         mp->mnt_nvnodelistsize++;
1604         KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
1605             ("Activating already active vnode"));
1606         vp->v_iflag |= VI_ACTIVE;
1607         mtx_lock(&mp->mnt_listmtx);
1608         TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
1609         mp->mnt_activevnodelistsize++;
1610         mtx_unlock(&mp->mnt_listmtx);
1611         VI_UNLOCK(vp);
1612         MNT_IUNLOCK(mp);
1613         return (0);
1614 }
1615
1616 int
1617 insmntque(struct vnode *vp, struct mount *mp)
1618 {
1619
1620         return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1621 }
1622
1623 /*
1624  * Flush out and invalidate all buffers associated with a bufobj
1625  * Called with the underlying object locked.
1626  */
1627 int
1628 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1629 {
1630         int error;
1631
1632         BO_LOCK(bo);
1633         if (flags & V_SAVE) {
1634                 error = bufobj_wwait(bo, slpflag, slptimeo);
1635                 if (error) {
1636                         BO_UNLOCK(bo);
1637                         return (error);
1638                 }
1639                 if (bo->bo_dirty.bv_cnt > 0) {
1640                         BO_UNLOCK(bo);
1641                         if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1642                                 return (error);
1643                         /*
1644                          * XXX We could save a lock/unlock if this was only
1645                          * enabled under INVARIANTS
1646                          */
1647                         BO_LOCK(bo);
1648                         if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1649                                 panic("vinvalbuf: dirty bufs");
1650                 }
1651         }
1652         /*
1653          * If you alter this loop please notice that interlock is dropped and
1654          * reacquired in flushbuflist.  Special care is needed to ensure that
1655          * no race conditions occur from this.
1656          */
1657         do {
1658                 error = flushbuflist(&bo->bo_clean,
1659                     flags, bo, slpflag, slptimeo);
1660                 if (error == 0 && !(flags & V_CLEANONLY))
1661                         error = flushbuflist(&bo->bo_dirty,
1662                             flags, bo, slpflag, slptimeo);
1663                 if (error != 0 && error != EAGAIN) {
1664                         BO_UNLOCK(bo);
1665                         return (error);
1666                 }
1667         } while (error != 0);
1668
1669         /*
1670          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1671          * have write I/O in-progress but if there is a VM object then the
1672          * VM object can also have read-I/O in-progress.
1673          */
1674         do {
1675                 bufobj_wwait(bo, 0, 0);
1676                 if ((flags & V_VMIO) == 0) {
1677                         BO_UNLOCK(bo);
1678                         if (bo->bo_object != NULL) {
1679                                 VM_OBJECT_WLOCK(bo->bo_object);
1680                                 vm_object_pip_wait(bo->bo_object, "bovlbx");
1681                                 VM_OBJECT_WUNLOCK(bo->bo_object);
1682                         }
1683                         BO_LOCK(bo);
1684                 }
1685         } while (bo->bo_numoutput > 0);
1686         BO_UNLOCK(bo);
1687
1688         /*
1689          * Destroy the copy in the VM cache, too.
1690          */
1691         if (bo->bo_object != NULL &&
1692             (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
1693                 VM_OBJECT_WLOCK(bo->bo_object);
1694                 vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
1695                     OBJPR_CLEANONLY : 0);
1696                 VM_OBJECT_WUNLOCK(bo->bo_object);
1697         }
1698
1699 #ifdef INVARIANTS
1700         BO_LOCK(bo);
1701         if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
1702             V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
1703             bo->bo_clean.bv_cnt > 0))
1704                 panic("vinvalbuf: flush failed");
1705         if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
1706             bo->bo_dirty.bv_cnt > 0)
1707                 panic("vinvalbuf: flush dirty failed");
1708         BO_UNLOCK(bo);
1709 #endif
1710         return (0);
1711 }
1712
1713 /*
1714  * Flush out and invalidate all buffers associated with a vnode.
1715  * Called with the underlying object locked.
1716  */
1717 int
1718 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1719 {
1720
1721         CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1722         ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1723         if (vp->v_object != NULL && vp->v_object->handle != vp)
1724                 return (0);
1725         return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1726 }
1727
1728 /*
1729  * Flush out buffers on the specified list.
1730  *
1731  */
1732 static int
1733 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1734     int slptimeo)
1735 {
1736         struct buf *bp, *nbp;
1737         int retval, error;
1738         daddr_t lblkno;
1739         b_xflags_t xflags;
1740
1741         ASSERT_BO_WLOCKED(bo);
1742
1743         retval = 0;
1744         TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1745                 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1746                     ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1747                         continue;
1748                 }
1749                 if (nbp != NULL) {
1750                         lblkno = nbp->b_lblkno;
1751                         xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
1752                 }
1753                 retval = EAGAIN;
1754                 error = BUF_TIMELOCK(bp,
1755                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
1756                     "flushbuf", slpflag, slptimeo);
1757                 if (error) {
1758                         BO_LOCK(bo);
1759                         return (error != ENOLCK ? error : EAGAIN);
1760                 }
1761                 KASSERT(bp->b_bufobj == bo,
1762                     ("bp %p wrong b_bufobj %p should be %p",
1763                     bp, bp->b_bufobj, bo));
1764                 /*
1765                  * XXX Since there are no node locks for NFS, I
1766                  * believe there is a slight chance that a delayed
1767                  * write will occur while sleeping just above, so
1768                  * check for it.
1769                  */
1770                 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1771                     (flags & V_SAVE)) {
1772                         bremfree(bp);
1773                         bp->b_flags |= B_ASYNC;
1774                         bwrite(bp);
1775                         BO_LOCK(bo);
1776                         return (EAGAIN);        /* XXX: why not loop ? */
1777                 }
1778                 bremfree(bp);
1779                 bp->b_flags |= (B_INVAL | B_RELBUF);
1780                 bp->b_flags &= ~B_ASYNC;
1781                 brelse(bp);
1782                 BO_LOCK(bo);
1783                 if (nbp == NULL)
1784                         break;
1785                 nbp = gbincore(bo, lblkno);
1786                 if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1787                     != xflags)
1788                         break;                  /* nbp invalid */
1789         }
1790         return (retval);
1791 }
1792
1793 int
1794 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
1795 {
1796         struct buf *bp;
1797         int error;
1798         daddr_t lblkno;
1799
1800         ASSERT_BO_LOCKED(bo);
1801
1802         for (lblkno = startn;;) {
1803 again:
1804                 bp = BUF_PCTRIE_LOOKUP_GE(&bufv->bv_root, lblkno);
1805                 if (bp == NULL || bp->b_lblkno >= endn ||
1806                     bp->b_lblkno < startn)
1807                         break;
1808                 error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1809                     LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
1810                 if (error != 0) {
1811                         BO_RLOCK(bo);
1812                         if (error == ENOLCK)
1813                                 goto again;
1814                         return (error);
1815                 }
1816                 KASSERT(bp->b_bufobj == bo,
1817                     ("bp %p wrong b_bufobj %p should be %p",
1818                     bp, bp->b_bufobj, bo));
1819                 lblkno = bp->b_lblkno + 1;
1820                 if ((bp->b_flags & B_MANAGED) == 0)
1821                         bremfree(bp);
1822                 bp->b_flags |= B_RELBUF;
1823                 /*
1824                  * In the VMIO case, use the B_NOREUSE flag to hint that the
1825                  * pages backing each buffer in the range are unlikely to be
1826                  * reused.  Dirty buffers will have the hint applied once
1827                  * they've been written.
1828                  */
1829                 if (bp->b_vp->v_object != NULL)
1830                         bp->b_flags |= B_NOREUSE;
1831                 brelse(bp);
1832                 BO_RLOCK(bo);
1833         }
1834         return (0);
1835 }
1836
1837 /*
1838  * Truncate a file's buffer and pages to a specified length.  This
1839  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1840  * sync activity.
1841  */
1842 int
1843 vtruncbuf(struct vnode *vp, struct ucred *cred, off_t length, int blksize)
1844 {
1845         struct buf *bp, *nbp;
1846         int anyfreed;
1847         int trunclbn;
1848         struct bufobj *bo;
1849
1850         CTR5(KTR_VFS, "%s: vp %p with cred %p and block %d:%ju", __func__,
1851             vp, cred, blksize, (uintmax_t)length);
1852
1853         /*
1854          * Round up to the *next* lbn.
1855          */
1856         trunclbn = howmany(length, blksize);
1857
1858         ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1859 restart:
1860         bo = &vp->v_bufobj;
1861         BO_LOCK(bo);
1862         anyfreed = 1;
1863         for (;anyfreed;) {
1864                 anyfreed = 0;
1865                 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1866                         if (bp->b_lblkno < trunclbn)
1867                                 continue;
1868                         if (BUF_LOCK(bp,
1869                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1870                             BO_LOCKPTR(bo)) == ENOLCK)
1871                                 goto restart;
1872
1873                         bremfree(bp);
1874                         bp->b_flags |= (B_INVAL | B_RELBUF);
1875                         bp->b_flags &= ~B_ASYNC;
1876                         brelse(bp);
1877                         anyfreed = 1;
1878
1879                         BO_LOCK(bo);
1880                         if (nbp != NULL &&
1881                             (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1882                             (nbp->b_vp != vp) ||
1883                             (nbp->b_flags & B_DELWRI))) {
1884                                 BO_UNLOCK(bo);
1885                                 goto restart;
1886                         }
1887                 }
1888
1889                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1890                         if (bp->b_lblkno < trunclbn)
1891                                 continue;
1892                         if (BUF_LOCK(bp,
1893                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1894                             BO_LOCKPTR(bo)) == ENOLCK)
1895                                 goto restart;
1896                         bremfree(bp);
1897                         bp->b_flags |= (B_INVAL | B_RELBUF);
1898                         bp->b_flags &= ~B_ASYNC;
1899                         brelse(bp);
1900                         anyfreed = 1;
1901
1902                         BO_LOCK(bo);
1903                         if (nbp != NULL &&
1904                             (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1905                             (nbp->b_vp != vp) ||
1906                             (nbp->b_flags & B_DELWRI) == 0)) {
1907                                 BO_UNLOCK(bo);
1908                                 goto restart;
1909                         }
1910                 }
1911         }
1912
1913         if (length > 0) {
1914 restartsync:
1915                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1916                         if (bp->b_lblkno > 0)
1917                                 continue;
1918                         /*
1919                          * Since we hold the vnode lock this should only
1920                          * fail if we're racing with the buf daemon.
1921                          */
1922                         if (BUF_LOCK(bp,
1923                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1924                             BO_LOCKPTR(bo)) == ENOLCK) {
1925                                 goto restart;
1926                         }
1927                         VNASSERT((bp->b_flags & B_DELWRI), vp,
1928                             ("buf(%p) on dirty queue without DELWRI", bp));
1929
1930                         bremfree(bp);
1931                         bawrite(bp);
1932                         BO_LOCK(bo);
1933                         goto restartsync;
1934                 }
1935         }
1936
1937         bufobj_wwait(bo, 0, 0);
1938         BO_UNLOCK(bo);
1939         vnode_pager_setsize(vp, length);
1940
1941         return (0);
1942 }
1943
1944 static void
1945 buf_vlist_remove(struct buf *bp)
1946 {
1947         struct bufv *bv;
1948
1949         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1950         ASSERT_BO_WLOCKED(bp->b_bufobj);
1951         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1952             (BX_VNDIRTY|BX_VNCLEAN),
1953             ("buf_vlist_remove: Buf %p is on two lists", bp));
1954         if (bp->b_xflags & BX_VNDIRTY)
1955                 bv = &bp->b_bufobj->bo_dirty;
1956         else
1957                 bv = &bp->b_bufobj->bo_clean;
1958         BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
1959         TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1960         bv->bv_cnt--;
1961         bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1962 }
1963
1964 /*
1965  * Add the buffer to the sorted clean or dirty block list.
1966  *
1967  * NOTE: xflags is passed as a constant, optimizing this inline function!
1968  */
1969 static void
1970 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1971 {
1972         struct bufv *bv;
1973         struct buf *n;
1974         int error;
1975
1976         ASSERT_BO_WLOCKED(bo);
1977         KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
1978             ("dead bo %p", bo));
1979         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1980             ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1981         bp->b_xflags |= xflags;
1982         if (xflags & BX_VNDIRTY)
1983                 bv = &bo->bo_dirty;
1984         else
1985                 bv = &bo->bo_clean;
1986
1987         /*
1988          * Keep the list ordered.  Optimize empty list insertion.  Assume
1989          * we tend to grow at the tail so lookup_le should usually be cheaper
1990          * than _ge. 
1991          */
1992         if (bv->bv_cnt == 0 ||
1993             bp->b_lblkno > TAILQ_LAST(&bv->bv_hd, buflists)->b_lblkno)
1994                 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1995         else if ((n = BUF_PCTRIE_LOOKUP_LE(&bv->bv_root, bp->b_lblkno)) == NULL)
1996                 TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
1997         else
1998                 TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
1999         error = BUF_PCTRIE_INSERT(&bv->bv_root, bp);
2000         if (error)
2001                 panic("buf_vlist_add:  Preallocated nodes insufficient.");
2002         bv->bv_cnt++;
2003 }
2004
2005 /*
2006  * Look up a buffer using the buffer tries.
2007  */
2008 struct buf *
2009 gbincore(struct bufobj *bo, daddr_t lblkno)
2010 {
2011         struct buf *bp;
2012
2013         ASSERT_BO_LOCKED(bo);
2014         bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2015         if (bp != NULL)
2016                 return (bp);
2017         return BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno);
2018 }
2019
2020 /*
2021  * Associate a buffer with a vnode.
2022  */
2023 void
2024 bgetvp(struct vnode *vp, struct buf *bp)
2025 {
2026         struct bufobj *bo;
2027
2028         bo = &vp->v_bufobj;
2029         ASSERT_BO_WLOCKED(bo);
2030         VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2031
2032         CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2033         VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2034             ("bgetvp: bp already attached! %p", bp));
2035
2036         vhold(vp);
2037         bp->b_vp = vp;
2038         bp->b_bufobj = bo;
2039         /*
2040          * Insert onto list for new vnode.
2041          */
2042         buf_vlist_add(bp, bo, BX_VNCLEAN);
2043 }
2044
2045 /*
2046  * Disassociate a buffer from a vnode.
2047  */
2048 void
2049 brelvp(struct buf *bp)
2050 {
2051         struct bufobj *bo;
2052         struct vnode *vp;
2053
2054         CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2055         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2056
2057         /*
2058          * Delete from old vnode list, if on one.
2059          */
2060         vp = bp->b_vp;          /* XXX */
2061         bo = bp->b_bufobj;
2062         BO_LOCK(bo);
2063         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2064                 buf_vlist_remove(bp);
2065         else
2066                 panic("brelvp: Buffer %p not on queue.", bp);
2067         if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2068                 bo->bo_flag &= ~BO_ONWORKLST;
2069                 mtx_lock(&sync_mtx);
2070                 LIST_REMOVE(bo, bo_synclist);
2071                 syncer_worklist_len--;
2072                 mtx_unlock(&sync_mtx);
2073         }
2074         bp->b_vp = NULL;
2075         bp->b_bufobj = NULL;
2076         BO_UNLOCK(bo);
2077         vdrop(vp);
2078 }
2079
2080 /*
2081  * Add an item to the syncer work queue.
2082  */
2083 static void
2084 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2085 {
2086         int slot;
2087
2088         ASSERT_BO_WLOCKED(bo);
2089
2090         mtx_lock(&sync_mtx);
2091         if (bo->bo_flag & BO_ONWORKLST)
2092                 LIST_REMOVE(bo, bo_synclist);
2093         else {
2094                 bo->bo_flag |= BO_ONWORKLST;
2095                 syncer_worklist_len++;
2096         }
2097
2098         if (delay > syncer_maxdelay - 2)
2099                 delay = syncer_maxdelay - 2;
2100         slot = (syncer_delayno + delay) & syncer_mask;
2101
2102         LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2103         mtx_unlock(&sync_mtx);
2104 }
2105
2106 static int
2107 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2108 {
2109         int error, len;
2110
2111         mtx_lock(&sync_mtx);
2112         len = syncer_worklist_len - sync_vnode_count;
2113         mtx_unlock(&sync_mtx);
2114         error = SYSCTL_OUT(req, &len, sizeof(len));
2115         return (error);
2116 }
2117
2118 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
2119     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2120
2121 static struct proc *updateproc;
2122 static void sched_sync(void);
2123 static struct kproc_desc up_kp = {
2124         "syncer",
2125         sched_sync,
2126         &updateproc
2127 };
2128 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2129
2130 static int
2131 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2132 {
2133         struct vnode *vp;
2134         struct mount *mp;
2135
2136         *bo = LIST_FIRST(slp);
2137         if (*bo == NULL)
2138                 return (0);
2139         vp = bo2vnode(*bo);
2140         if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2141                 return (1);
2142         /*
2143          * We use vhold in case the vnode does not
2144          * successfully sync.  vhold prevents the vnode from
2145          * going away when we unlock the sync_mtx so that
2146          * we can acquire the vnode interlock.
2147          */
2148         vholdl(vp);
2149         mtx_unlock(&sync_mtx);
2150         VI_UNLOCK(vp);
2151         if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2152                 vdrop(vp);
2153                 mtx_lock(&sync_mtx);
2154                 return (*bo == LIST_FIRST(slp));
2155         }
2156         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2157         (void) VOP_FSYNC(vp, MNT_LAZY, td);
2158         VOP_UNLOCK(vp, 0);
2159         vn_finished_write(mp);
2160         BO_LOCK(*bo);
2161         if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
2162                 /*
2163                  * Put us back on the worklist.  The worklist
2164                  * routine will remove us from our current
2165                  * position and then add us back in at a later
2166                  * position.
2167                  */
2168                 vn_syncer_add_to_worklist(*bo, syncdelay);
2169         }
2170         BO_UNLOCK(*bo);
2171         vdrop(vp);
2172         mtx_lock(&sync_mtx);
2173         return (0);
2174 }
2175
2176 static int first_printf = 1;
2177
2178 /*
2179  * System filesystem synchronizer daemon.
2180  */
2181 static void
2182 sched_sync(void)
2183 {
2184         struct synclist *next, *slp;
2185         struct bufobj *bo;
2186         long starttime;
2187         struct thread *td = curthread;
2188         int last_work_seen;
2189         int net_worklist_len;
2190         int syncer_final_iter;
2191         int error;
2192
2193         last_work_seen = 0;
2194         syncer_final_iter = 0;
2195         syncer_state = SYNCER_RUNNING;
2196         starttime = time_uptime;
2197         td->td_pflags |= TDP_NORUNNINGBUF;
2198
2199         EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
2200             SHUTDOWN_PRI_LAST);
2201
2202         mtx_lock(&sync_mtx);
2203         for (;;) {
2204                 if (syncer_state == SYNCER_FINAL_DELAY &&
2205                     syncer_final_iter == 0) {
2206                         mtx_unlock(&sync_mtx);
2207                         kproc_suspend_check(td->td_proc);
2208                         mtx_lock(&sync_mtx);
2209                 }
2210                 net_worklist_len = syncer_worklist_len - sync_vnode_count;
2211                 if (syncer_state != SYNCER_RUNNING &&
2212                     starttime != time_uptime) {
2213                         if (first_printf) {
2214                                 printf("\nSyncing disks, vnodes remaining... ");
2215                                 first_printf = 0;
2216                         }
2217                         printf("%d ", net_worklist_len);
2218                 }
2219                 starttime = time_uptime;
2220
2221                 /*
2222                  * Push files whose dirty time has expired.  Be careful
2223                  * of interrupt race on slp queue.
2224                  *
2225                  * Skip over empty worklist slots when shutting down.
2226                  */
2227                 do {
2228                         slp = &syncer_workitem_pending[syncer_delayno];
2229                         syncer_delayno += 1;
2230                         if (syncer_delayno == syncer_maxdelay)
2231                                 syncer_delayno = 0;
2232                         next = &syncer_workitem_pending[syncer_delayno];
2233                         /*
2234                          * If the worklist has wrapped since the
2235                          * it was emptied of all but syncer vnodes,
2236                          * switch to the FINAL_DELAY state and run
2237                          * for one more second.
2238                          */
2239                         if (syncer_state == SYNCER_SHUTTING_DOWN &&
2240                             net_worklist_len == 0 &&
2241                             last_work_seen == syncer_delayno) {
2242                                 syncer_state = SYNCER_FINAL_DELAY;
2243                                 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
2244                         }
2245                 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
2246                     syncer_worklist_len > 0);
2247
2248                 /*
2249                  * Keep track of the last time there was anything
2250                  * on the worklist other than syncer vnodes.
2251                  * Return to the SHUTTING_DOWN state if any
2252                  * new work appears.
2253                  */
2254                 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
2255                         last_work_seen = syncer_delayno;
2256                 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
2257                         syncer_state = SYNCER_SHUTTING_DOWN;
2258                 while (!LIST_EMPTY(slp)) {
2259                         error = sync_vnode(slp, &bo, td);
2260                         if (error == 1) {
2261                                 LIST_REMOVE(bo, bo_synclist);
2262                                 LIST_INSERT_HEAD(next, bo, bo_synclist);
2263                                 continue;
2264                         }
2265
2266                         if (first_printf == 0) {
2267                                 /*
2268                                  * Drop the sync mutex, because some watchdog
2269                                  * drivers need to sleep while patting
2270                                  */
2271                                 mtx_unlock(&sync_mtx);
2272                                 wdog_kern_pat(WD_LASTVAL);
2273                                 mtx_lock(&sync_mtx);
2274                         }
2275
2276                 }
2277                 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
2278                         syncer_final_iter--;
2279                 /*
2280                  * The variable rushjob allows the kernel to speed up the
2281                  * processing of the filesystem syncer process. A rushjob
2282                  * value of N tells the filesystem syncer to process the next
2283                  * N seconds worth of work on its queue ASAP. Currently rushjob
2284                  * is used by the soft update code to speed up the filesystem
2285                  * syncer process when the incore state is getting so far
2286                  * ahead of the disk that the kernel memory pool is being
2287                  * threatened with exhaustion.
2288                  */
2289                 if (rushjob > 0) {
2290                         rushjob -= 1;
2291                         continue;
2292                 }
2293                 /*
2294                  * Just sleep for a short period of time between
2295                  * iterations when shutting down to allow some I/O
2296                  * to happen.
2297                  *
2298                  * If it has taken us less than a second to process the
2299                  * current work, then wait. Otherwise start right over
2300                  * again. We can still lose time if any single round
2301                  * takes more than two seconds, but it does not really
2302                  * matter as we are just trying to generally pace the
2303                  * filesystem activity.
2304                  */
2305                 if (syncer_state != SYNCER_RUNNING ||
2306                     time_uptime == starttime) {
2307                         thread_lock(td);
2308                         sched_prio(td, PPAUSE);
2309                         thread_unlock(td);
2310                 }
2311                 if (syncer_state != SYNCER_RUNNING)
2312                         cv_timedwait(&sync_wakeup, &sync_mtx,
2313                             hz / SYNCER_SHUTDOWN_SPEEDUP);
2314                 else if (time_uptime == starttime)
2315                         cv_timedwait(&sync_wakeup, &sync_mtx, hz);
2316         }
2317 }
2318
2319 /*
2320  * Request the syncer daemon to speed up its work.
2321  * We never push it to speed up more than half of its
2322  * normal turn time, otherwise it could take over the cpu.
2323  */
2324 int
2325 speedup_syncer(void)
2326 {
2327         int ret = 0;
2328
2329         mtx_lock(&sync_mtx);
2330         if (rushjob < syncdelay / 2) {
2331                 rushjob += 1;
2332                 stat_rush_requests += 1;
2333                 ret = 1;
2334         }
2335         mtx_unlock(&sync_mtx);
2336         cv_broadcast(&sync_wakeup);
2337         return (ret);
2338 }
2339
2340 /*
2341  * Tell the syncer to speed up its work and run though its work
2342  * list several times, then tell it to shut down.
2343  */
2344 static void
2345 syncer_shutdown(void *arg, int howto)
2346 {
2347
2348         if (howto & RB_NOSYNC)
2349                 return;
2350         mtx_lock(&sync_mtx);
2351         syncer_state = SYNCER_SHUTTING_DOWN;
2352         rushjob = 0;
2353         mtx_unlock(&sync_mtx);
2354         cv_broadcast(&sync_wakeup);
2355         kproc_shutdown(arg, howto);
2356 }
2357
2358 void
2359 syncer_suspend(void)
2360 {
2361
2362         syncer_shutdown(updateproc, 0);
2363 }
2364
2365 void
2366 syncer_resume(void)
2367 {
2368
2369         mtx_lock(&sync_mtx);
2370         first_printf = 1;
2371         syncer_state = SYNCER_RUNNING;
2372         mtx_unlock(&sync_mtx);
2373         cv_broadcast(&sync_wakeup);
2374         kproc_resume(updateproc);
2375 }
2376
2377 /*
2378  * Reassign a buffer from one vnode to another.
2379  * Used to assign file specific control information
2380  * (indirect blocks) to the vnode to which they belong.
2381  */
2382 void
2383 reassignbuf(struct buf *bp)
2384 {
2385         struct vnode *vp;
2386         struct bufobj *bo;
2387         int delay;
2388 #ifdef INVARIANTS
2389         struct bufv *bv;
2390 #endif
2391
2392         vp = bp->b_vp;
2393         bo = bp->b_bufobj;
2394         ++reassignbufcalls;
2395
2396         CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
2397             bp, bp->b_vp, bp->b_flags);
2398         /*
2399          * B_PAGING flagged buffers cannot be reassigned because their vp
2400          * is not fully linked in.
2401          */
2402         if (bp->b_flags & B_PAGING)
2403                 panic("cannot reassign paging buffer");
2404
2405         /*
2406          * Delete from old vnode list, if on one.
2407          */
2408         BO_LOCK(bo);
2409         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2410                 buf_vlist_remove(bp);
2411         else
2412                 panic("reassignbuf: Buffer %p not on queue.", bp);
2413         /*
2414          * If dirty, put on list of dirty buffers; otherwise insert onto list
2415          * of clean buffers.
2416          */
2417         if (bp->b_flags & B_DELWRI) {
2418                 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
2419                         switch (vp->v_type) {
2420                         case VDIR:
2421                                 delay = dirdelay;
2422                                 break;
2423                         case VCHR:
2424                                 delay = metadelay;
2425                                 break;
2426                         default:
2427                                 delay = filedelay;
2428                         }
2429                         vn_syncer_add_to_worklist(bo, delay);
2430                 }
2431                 buf_vlist_add(bp, bo, BX_VNDIRTY);
2432         } else {
2433                 buf_vlist_add(bp, bo, BX_VNCLEAN);
2434
2435                 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2436                         mtx_lock(&sync_mtx);
2437                         LIST_REMOVE(bo, bo_synclist);
2438                         syncer_worklist_len--;
2439                         mtx_unlock(&sync_mtx);
2440                         bo->bo_flag &= ~BO_ONWORKLST;
2441                 }
2442         }
2443 #ifdef INVARIANTS
2444         bv = &bo->bo_clean;
2445         bp = TAILQ_FIRST(&bv->bv_hd);
2446         KASSERT(bp == NULL || bp->b_bufobj == bo,
2447             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2448         bp = TAILQ_LAST(&bv->bv_hd, buflists);
2449         KASSERT(bp == NULL || bp->b_bufobj == bo,
2450             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2451         bv = &bo->bo_dirty;
2452         bp = TAILQ_FIRST(&bv->bv_hd);
2453         KASSERT(bp == NULL || bp->b_bufobj == bo,
2454             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2455         bp = TAILQ_LAST(&bv->bv_hd, buflists);
2456         KASSERT(bp == NULL || bp->b_bufobj == bo,
2457             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
2458 #endif
2459         BO_UNLOCK(bo);
2460 }
2461
2462 /*
2463  * A temporary hack until refcount_* APIs are sorted out.
2464  */
2465 static __inline int
2466 vfs_refcount_acquire_if_not_zero(volatile u_int *count)
2467 {
2468         u_int old;
2469
2470         old = *count;
2471         for (;;) {
2472                 if (old == 0)
2473                         return (0);
2474                 if (atomic_fcmpset_int(count, &old, old + 1))
2475                         return (1);
2476         }
2477 }
2478
2479 static __inline int
2480 vfs_refcount_release_if_not_last(volatile u_int *count)
2481 {
2482         u_int old;
2483
2484         old = *count;
2485         for (;;) {
2486                 if (old == 1)
2487                         return (0);
2488                 if (atomic_fcmpset_int(count, &old, old - 1))
2489                         return (1);
2490         }
2491 }
2492
2493 static void
2494 v_init_counters(struct vnode *vp)
2495 {
2496
2497         VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
2498             vp, ("%s called for an initialized vnode", __FUNCTION__));
2499         ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
2500
2501         refcount_init(&vp->v_holdcnt, 1);
2502         refcount_init(&vp->v_usecount, 1);
2503 }
2504
2505 static void
2506 v_incr_usecount_locked(struct vnode *vp)
2507 {
2508
2509         ASSERT_VI_LOCKED(vp, __func__);
2510         if ((vp->v_iflag & VI_OWEINACT) != 0) {
2511                 VNASSERT(vp->v_usecount == 0, vp,
2512                     ("vnode with usecount and VI_OWEINACT set"));
2513                 vp->v_iflag &= ~VI_OWEINACT;
2514         }
2515         refcount_acquire(&vp->v_usecount);
2516         v_incr_devcount(vp);
2517 }
2518
2519 /*
2520  * Increment the use count on the vnode, taking care to reference
2521  * the driver's usecount if this is a chardev.
2522  */
2523 static void
2524 v_incr_usecount(struct vnode *vp)
2525 {
2526
2527         ASSERT_VI_UNLOCKED(vp, __func__);
2528         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2529
2530         if (vp->v_type != VCHR &&
2531             vfs_refcount_acquire_if_not_zero(&vp->v_usecount)) {
2532                 VNASSERT((vp->v_iflag & VI_OWEINACT) == 0, vp,
2533                     ("vnode with usecount and VI_OWEINACT set"));
2534         } else {
2535                 VI_LOCK(vp);
2536                 v_incr_usecount_locked(vp);
2537                 VI_UNLOCK(vp);
2538         }
2539 }
2540
2541 /*
2542  * Increment si_usecount of the associated device, if any.
2543  */
2544 static void
2545 v_incr_devcount(struct vnode *vp)
2546 {
2547
2548         ASSERT_VI_LOCKED(vp, __FUNCTION__);
2549         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2550                 dev_lock();
2551                 vp->v_rdev->si_usecount++;
2552                 dev_unlock();
2553         }
2554 }
2555
2556 /*
2557  * Decrement si_usecount of the associated device, if any.
2558  */
2559 static void
2560 v_decr_devcount(struct vnode *vp)
2561 {
2562
2563         ASSERT_VI_LOCKED(vp, __FUNCTION__);
2564         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2565                 dev_lock();
2566                 vp->v_rdev->si_usecount--;
2567                 dev_unlock();
2568         }
2569 }
2570
2571 /*
2572  * Grab a particular vnode from the free list, increment its
2573  * reference count and lock it.  VI_DOOMED is set if the vnode
2574  * is being destroyed.  Only callers who specify LK_RETRY will
2575  * see doomed vnodes.  If inactive processing was delayed in
2576  * vput try to do it here.
2577  *
2578  * Notes on lockless counter manipulation:
2579  * _vhold, vputx and other routines make various decisions based
2580  * on either holdcnt or usecount being 0. As long as either counter
2581  * is not transitioning 0->1 nor 1->0, the manipulation can be done
2582  * with atomic operations. Otherwise the interlock is taken covering
2583  * both the atomic and additional actions.
2584  */
2585 int
2586 vget(struct vnode *vp, int flags, struct thread *td)
2587 {
2588         int error, oweinact;
2589
2590         VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2591             ("vget: invalid lock operation"));
2592
2593         if ((flags & LK_INTERLOCK) != 0)
2594                 ASSERT_VI_LOCKED(vp, __func__);
2595         else
2596                 ASSERT_VI_UNLOCKED(vp, __func__);
2597         if ((flags & LK_VNHELD) != 0)
2598                 VNASSERT((vp->v_holdcnt > 0), vp,
2599                     ("vget: LK_VNHELD passed but vnode not held"));
2600
2601         CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2602
2603         if ((flags & LK_VNHELD) == 0)
2604                 _vhold(vp, (flags & LK_INTERLOCK) != 0);
2605
2606         if ((error = vn_lock(vp, flags)) != 0) {
2607                 vdrop(vp);
2608                 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2609                     vp);
2610                 return (error);
2611         }
2612         if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2613                 panic("vget: vn_lock failed to return ENOENT\n");
2614         /*
2615          * We don't guarantee that any particular close will
2616          * trigger inactive processing so just make a best effort
2617          * here at preventing a reference to a removed file.  If
2618          * we don't succeed no harm is done.
2619          *
2620          * Upgrade our holdcnt to a usecount.
2621          */
2622         if (vp->v_type == VCHR ||
2623             !vfs_refcount_acquire_if_not_zero(&vp->v_usecount)) {
2624                 VI_LOCK(vp);
2625                 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2626                         oweinact = 0;
2627                 } else {
2628                         oweinact = 1;
2629                         vp->v_iflag &= ~VI_OWEINACT;
2630                 }
2631                 refcount_acquire(&vp->v_usecount);
2632                 v_incr_devcount(vp);
2633                 if (oweinact && VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2634                     (flags & LK_NOWAIT) == 0)
2635                         vinactive(vp, td);
2636                 VI_UNLOCK(vp);
2637         }
2638         return (0);
2639 }
2640
2641 /*
2642  * Increase the reference (use) and hold count of a vnode.
2643  * This will also remove the vnode from the free list if it is presently free.
2644  */
2645 void
2646 vref(struct vnode *vp)
2647 {
2648
2649         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2650         _vhold(vp, false);
2651         v_incr_usecount(vp);
2652 }
2653
2654 void
2655 vrefl(struct vnode *vp)
2656 {
2657
2658         ASSERT_VI_LOCKED(vp, __func__);
2659         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2660         _vhold(vp, true);
2661         v_incr_usecount_locked(vp);
2662 }
2663
2664 void
2665 vrefact(struct vnode *vp)
2666 {
2667
2668         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2669         if (__predict_false(vp->v_type == VCHR)) {
2670                 VNASSERT(vp->v_holdcnt > 0 && vp->v_usecount > 0, vp,
2671                     ("%s: wrong ref counts", __func__));
2672                 vref(vp);
2673                 return;
2674         }
2675 #ifdef INVARIANTS
2676         int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
2677         VNASSERT(old > 0, vp, ("%s: wrong hold count", __func__));
2678         old = atomic_fetchadd_int(&vp->v_usecount, 1);
2679         VNASSERT(old > 0, vp, ("%s: wrong use count", __func__));
2680 #else
2681         refcount_acquire(&vp->v_holdcnt);
2682         refcount_acquire(&vp->v_usecount);
2683 #endif
2684 }
2685
2686 /*
2687  * Return reference count of a vnode.
2688  *
2689  * The results of this call are only guaranteed when some mechanism is used to
2690  * stop other processes from gaining references to the vnode.  This may be the
2691  * case if the caller holds the only reference.  This is also useful when stale
2692  * data is acceptable as race conditions may be accounted for by some other
2693  * means.
2694  */
2695 int
2696 vrefcnt(struct vnode *vp)
2697 {
2698
2699         return (vp->v_usecount);
2700 }
2701
2702 #define VPUTX_VRELE     1
2703 #define VPUTX_VPUT      2
2704 #define VPUTX_VUNREF    3
2705
2706 /*
2707  * Decrement the use and hold counts for a vnode.
2708  *
2709  * See an explanation near vget() as to why atomic operation is safe.
2710  */
2711 static void
2712 vputx(struct vnode *vp, int func)
2713 {
2714         int error;
2715
2716         KASSERT(vp != NULL, ("vputx: null vp"));
2717         if (func == VPUTX_VUNREF)
2718                 ASSERT_VOP_LOCKED(vp, "vunref");
2719         else if (func == VPUTX_VPUT)
2720                 ASSERT_VOP_LOCKED(vp, "vput");
2721         else
2722                 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2723         ASSERT_VI_UNLOCKED(vp, __func__);
2724         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2725
2726         if (vp->v_type != VCHR &&
2727             vfs_refcount_release_if_not_last(&vp->v_usecount)) {
2728                 if (func == VPUTX_VPUT)
2729                         VOP_UNLOCK(vp, 0);
2730                 vdrop(vp);
2731                 return;
2732         }
2733
2734         VI_LOCK(vp);
2735
2736         /*
2737          * We want to hold the vnode until the inactive finishes to
2738          * prevent vgone() races.  We drop the use count here and the
2739          * hold count below when we're done.
2740          */
2741         if (!refcount_release(&vp->v_usecount) ||
2742             (vp->v_iflag & VI_DOINGINACT)) {
2743                 if (func == VPUTX_VPUT)
2744                         VOP_UNLOCK(vp, 0);
2745                 v_decr_devcount(vp);
2746                 vdropl(vp);
2747                 return;
2748         }
2749
2750         v_decr_devcount(vp);
2751
2752         error = 0;
2753
2754         if (vp->v_usecount != 0) {
2755                 vn_printf(vp, "vputx: usecount not zero for vnode ");
2756                 panic("vputx: usecount not zero");
2757         }
2758
2759         CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2760
2761         /*
2762          * We must call VOP_INACTIVE with the node locked. Mark
2763          * as VI_DOINGINACT to avoid recursion.
2764          */
2765         vp->v_iflag |= VI_OWEINACT;
2766         switch (func) {
2767         case VPUTX_VRELE:
2768                 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2769                 VI_LOCK(vp);
2770                 break;
2771         case VPUTX_VPUT:
2772                 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2773                         error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
2774                             LK_NOWAIT);
2775                         VI_LOCK(vp);
2776                 }
2777                 break;
2778         case VPUTX_VUNREF:
2779                 if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2780                         error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
2781                         VI_LOCK(vp);
2782                 }
2783                 break;
2784         }
2785         VNASSERT(vp->v_usecount == 0 || (vp->v_iflag & VI_OWEINACT) == 0, vp,
2786             ("vnode with usecount and VI_OWEINACT set"));
2787         if (error == 0) {
2788                 if (vp->v_iflag & VI_OWEINACT)
2789                         vinactive(vp, curthread);
2790                 if (func != VPUTX_VUNREF)
2791                         VOP_UNLOCK(vp, 0);
2792         }
2793         vdropl(vp);
2794 }
2795
2796 /*
2797  * Vnode put/release.
2798  * If count drops to zero, call inactive routine and return to freelist.
2799  */
2800 void
2801 vrele(struct vnode *vp)
2802 {
2803
2804         vputx(vp, VPUTX_VRELE);
2805 }
2806
2807 /*
2808  * Release an already locked vnode.  This give the same effects as
2809  * unlock+vrele(), but takes less time and avoids releasing and
2810  * re-aquiring the lock (as vrele() acquires the lock internally.)
2811  */
2812 void
2813 vput(struct vnode *vp)
2814 {
2815
2816         vputx(vp, VPUTX_VPUT);
2817 }
2818
2819 /*
2820  * Release an exclusively locked vnode. Do not unlock the vnode lock.
2821  */
2822 void
2823 vunref(struct vnode *vp)
2824 {
2825
2826         vputx(vp, VPUTX_VUNREF);
2827 }
2828
2829 /*
2830  * Increase the hold count and activate if this is the first reference.
2831  */
2832 void
2833 _vhold(struct vnode *vp, bool locked)
2834 {
2835         struct mount *mp;
2836
2837         if (locked)
2838                 ASSERT_VI_LOCKED(vp, __func__);
2839         else
2840                 ASSERT_VI_UNLOCKED(vp, __func__);
2841         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2842         if (!locked && vfs_refcount_acquire_if_not_zero(&vp->v_holdcnt)) {
2843                 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2844                     ("_vhold: vnode with holdcnt is free"));
2845                 return;
2846         }
2847
2848         if (!locked)
2849                 VI_LOCK(vp);
2850         if ((vp->v_iflag & VI_FREE) == 0) {
2851                 refcount_acquire(&vp->v_holdcnt);
2852                 if (!locked)
2853                         VI_UNLOCK(vp);
2854                 return;
2855         }
2856         VNASSERT(vp->v_holdcnt == 0, vp,
2857             ("%s: wrong hold count", __func__));
2858         VNASSERT(vp->v_op != NULL, vp,
2859             ("%s: vnode already reclaimed.", __func__));
2860         /*
2861          * Remove a vnode from the free list, mark it as in use,
2862          * and put it on the active list.
2863          */
2864         VNASSERT(vp->v_mount != NULL, vp,
2865             ("_vhold: vnode not on per mount vnode list"));
2866         mp = vp->v_mount;
2867         mtx_lock(&mp->mnt_listmtx);
2868         if ((vp->v_mflag & VMP_TMPMNTFREELIST) != 0) {
2869                 TAILQ_REMOVE(&mp->mnt_tmpfreevnodelist, vp, v_actfreelist);
2870                 mp->mnt_tmpfreevnodelistsize--;
2871                 vp->v_mflag &= ~VMP_TMPMNTFREELIST;
2872         } else {
2873                 mtx_lock(&vnode_free_list_mtx);
2874                 TAILQ_REMOVE(&vnode_free_list, vp, v_actfreelist);
2875                 freevnodes--;
2876                 mtx_unlock(&vnode_free_list_mtx);
2877         }
2878         KASSERT((vp->v_iflag & VI_ACTIVE) == 0,
2879             ("Activating already active vnode"));
2880         vp->v_iflag &= ~VI_FREE;
2881         vp->v_iflag |= VI_ACTIVE;
2882         TAILQ_INSERT_HEAD(&mp->mnt_activevnodelist, vp, v_actfreelist);
2883         mp->mnt_activevnodelistsize++;
2884         mtx_unlock(&mp->mnt_listmtx);
2885         refcount_acquire(&vp->v_holdcnt);
2886         if (!locked)
2887                 VI_UNLOCK(vp);
2888 }
2889
2890 /*
2891  * Drop the hold count of the vnode.  If this is the last reference to
2892  * the vnode we place it on the free list unless it has been vgone'd
2893  * (marked VI_DOOMED) in which case we will free it.
2894  *
2895  * Because the vnode vm object keeps a hold reference on the vnode if
2896  * there is at least one resident non-cached page, the vnode cannot
2897  * leave the active list without the page cleanup done.
2898  */
2899 void
2900 _vdrop(struct vnode *vp, bool locked)
2901 {
2902         struct bufobj *bo;
2903         struct mount *mp;
2904         int active;
2905
2906         if (locked)
2907                 ASSERT_VI_LOCKED(vp, __func__);
2908         else
2909                 ASSERT_VI_UNLOCKED(vp, __func__);
2910         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2911         if ((int)vp->v_holdcnt <= 0)
2912                 panic("vdrop: holdcnt %d", vp->v_holdcnt);
2913         if (vfs_refcount_release_if_not_last(&vp->v_holdcnt)) {
2914                 if (locked)
2915                         VI_UNLOCK(vp);
2916                 return;
2917         }
2918
2919         if (!locked)
2920                 VI_LOCK(vp);
2921         if (refcount_release(&vp->v_holdcnt) == 0) {
2922                 VI_UNLOCK(vp);
2923                 return;
2924         }
2925         if ((vp->v_iflag & VI_DOOMED) == 0) {
2926                 /*
2927                  * Mark a vnode as free: remove it from its active list
2928                  * and put it up for recycling on the freelist.
2929                  */
2930                 VNASSERT(vp->v_op != NULL, vp,
2931                     ("vdropl: vnode already reclaimed."));
2932                 VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2933                     ("vnode already free"));
2934                 VNASSERT(vp->v_holdcnt == 0, vp,
2935                     ("vdropl: freeing when we shouldn't"));
2936                 active = vp->v_iflag & VI_ACTIVE;
2937                 if ((vp->v_iflag & VI_OWEINACT) == 0) {
2938                         vp->v_iflag &= ~VI_ACTIVE;
2939                         mp = vp->v_mount;
2940                         if (mp != NULL) {
2941                                 mtx_lock(&mp->mnt_listmtx);
2942                                 if (active) {
2943                                         TAILQ_REMOVE(&mp->mnt_activevnodelist,
2944                                             vp, v_actfreelist);
2945                                         mp->mnt_activevnodelistsize--;
2946                                 }
2947                                 TAILQ_INSERT_TAIL(&mp->mnt_tmpfreevnodelist,
2948                                     vp, v_actfreelist);
2949                                 mp->mnt_tmpfreevnodelistsize++;
2950                                 vp->v_iflag |= VI_FREE;
2951                                 vp->v_mflag |= VMP_TMPMNTFREELIST;
2952                                 VI_UNLOCK(vp);
2953                                 if (mp->mnt_tmpfreevnodelistsize >=
2954                                     mnt_free_list_batch)
2955                                         vnlru_return_batch_locked(mp);
2956                                 mtx_unlock(&mp->mnt_listmtx);
2957                         } else {
2958                                 VNASSERT(active == 0, vp,
2959                                     ("vdropl: active vnode not on per mount "
2960                                     "vnode list"));
2961                                 mtx_lock(&vnode_free_list_mtx);
2962                                 TAILQ_INSERT_TAIL(&vnode_free_list, vp,
2963                                     v_actfreelist);
2964                                 freevnodes++;
2965                                 vp->v_iflag |= VI_FREE;
2966                                 VI_UNLOCK(vp);
2967                                 mtx_unlock(&vnode_free_list_mtx);
2968                         }
2969                 } else {
2970                         VI_UNLOCK(vp);
2971                         counter_u64_add(free_owe_inact, 1);
2972                 }
2973                 return;
2974         }
2975         /*
2976          * The vnode has been marked for destruction, so free it.
2977          *
2978          * The vnode will be returned to the zone where it will
2979          * normally remain until it is needed for another vnode. We
2980          * need to cleanup (or verify that the cleanup has already
2981          * been done) any residual data left from its current use
2982          * so as not to contaminate the freshly allocated vnode.
2983          */
2984         CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
2985         atomic_subtract_long(&numvnodes, 1);
2986         bo = &vp->v_bufobj;
2987         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
2988             ("cleaned vnode still on the free list."));
2989         VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
2990         VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
2991         VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
2992         VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
2993         VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
2994         VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
2995         VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
2996             ("clean blk trie not empty"));
2997         VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
2998         VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
2999             ("dirty blk trie not empty"));
3000         VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
3001         VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
3002         VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
3003         VNASSERT(TAILQ_EMPTY(&vp->v_rl.rl_waiters), vp,
3004             ("Dangling rangelock waiters"));
3005         VI_UNLOCK(vp);
3006 #ifdef MAC
3007         mac_vnode_destroy(vp);
3008 #endif
3009         if (vp->v_pollinfo != NULL) {
3010                 destroy_vpollinfo(vp->v_pollinfo);
3011                 vp->v_pollinfo = NULL;
3012         }
3013 #ifdef INVARIANTS
3014         /* XXX Elsewhere we detect an already freed vnode via NULL v_op. */
3015         vp->v_op = NULL;
3016 #endif
3017         vp->v_mountedhere = NULL;
3018         vp->v_unpcb = NULL;
3019         vp->v_rdev = NULL;
3020         vp->v_fifoinfo = NULL;
3021         vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
3022         vp->v_iflag = 0;
3023         vp->v_vflag = 0;
3024         bo->bo_flag = 0;
3025         uma_zfree(vnode_zone, vp);
3026 }
3027
3028 /*
3029  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
3030  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
3031  * OWEINACT tracks whether a vnode missed a call to inactive due to a
3032  * failed lock upgrade.
3033  */
3034 void
3035 vinactive(struct vnode *vp, struct thread *td)
3036 {
3037         struct vm_object *obj;
3038
3039         ASSERT_VOP_ELOCKED(vp, "vinactive");
3040         ASSERT_VI_LOCKED(vp, "vinactive");
3041         VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
3042             ("vinactive: recursed on VI_DOINGINACT"));
3043         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3044         vp->v_iflag |= VI_DOINGINACT;
3045         vp->v_iflag &= ~VI_OWEINACT;
3046         VI_UNLOCK(vp);
3047         /*
3048          * Before moving off the active list, we must be sure that any
3049          * modified pages are converted into the vnode's dirty
3050          * buffers, since these will no longer be checked once the
3051          * vnode is on the inactive list.
3052          *
3053          * The write-out of the dirty pages is asynchronous.  At the
3054          * point that VOP_INACTIVE() is called, there could still be
3055          * pending I/O and dirty pages in the object.
3056          */
3057         if ((obj = vp->v_object) != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
3058             (obj->flags & OBJ_MIGHTBEDIRTY) != 0) {
3059                 VM_OBJECT_WLOCK(obj);
3060                 vm_object_page_clean(obj, 0, 0, 0);
3061                 VM_OBJECT_WUNLOCK(obj);
3062         }
3063         VOP_INACTIVE(vp, td);
3064         VI_LOCK(vp);
3065         VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
3066             ("vinactive: lost VI_DOINGINACT"));
3067         vp->v_iflag &= ~VI_DOINGINACT;
3068 }
3069
3070 /*
3071  * Remove any vnodes in the vnode table belonging to mount point mp.
3072  *
3073  * If FORCECLOSE is not specified, there should not be any active ones,
3074  * return error if any are found (nb: this is a user error, not a
3075  * system error). If FORCECLOSE is specified, detach any active vnodes
3076  * that are found.
3077  *
3078  * If WRITECLOSE is set, only flush out regular file vnodes open for
3079  * writing.
3080  *
3081  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
3082  *
3083  * `rootrefs' specifies the base reference count for the root vnode
3084  * of this filesystem. The root vnode is considered busy if its
3085  * v_usecount exceeds this value. On a successful return, vflush(, td)
3086  * will call vrele() on the root vnode exactly rootrefs times.
3087  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
3088  * be zero.
3089  */
3090 #ifdef DIAGNOSTIC
3091 static int busyprt = 0;         /* print out busy vnodes */
3092 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
3093 #endif
3094
3095 int
3096 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
3097 {
3098         struct vnode *vp, *mvp, *rootvp = NULL;
3099         struct vattr vattr;
3100         int busy = 0, error;
3101
3102         CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
3103             rootrefs, flags);
3104         if (rootrefs > 0) {
3105                 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
3106                     ("vflush: bad args"));
3107                 /*
3108                  * Get the filesystem root vnode. We can vput() it
3109                  * immediately, since with rootrefs > 0, it won't go away.
3110                  */
3111                 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
3112                         CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
3113                             __func__, error);
3114                         return (error);
3115                 }
3116                 vput(rootvp);
3117         }
3118 loop:
3119         MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3120                 vholdl(vp);
3121                 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
3122                 if (error) {
3123                         vdrop(vp);
3124                         MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3125                         goto loop;
3126                 }
3127                 /*
3128                  * Skip over a vnodes marked VV_SYSTEM.
3129                  */
3130                 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
3131                         VOP_UNLOCK(vp, 0);
3132                         vdrop(vp);
3133                         continue;
3134                 }
3135                 /*
3136                  * If WRITECLOSE is set, flush out unlinked but still open
3137                  * files (even if open only for reading) and regular file
3138                  * vnodes open for writing.
3139                  */
3140                 if (flags & WRITECLOSE) {
3141                         if (vp->v_object != NULL) {
3142                                 VM_OBJECT_WLOCK(vp->v_object);
3143                                 vm_object_page_clean(vp->v_object, 0, 0, 0);
3144                                 VM_OBJECT_WUNLOCK(vp->v_object);
3145                         }
3146                         error = VOP_FSYNC(vp, MNT_WAIT, td);
3147                         if (error != 0) {
3148                                 VOP_UNLOCK(vp, 0);
3149                                 vdrop(vp);
3150                                 MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
3151                                 return (error);
3152                         }
3153                         error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3154                         VI_LOCK(vp);
3155
3156                         if ((vp->v_type == VNON ||
3157                             (error == 0 && vattr.va_nlink > 0)) &&
3158                             (vp->v_writecount == 0 || vp->v_type != VREG)) {
3159                                 VOP_UNLOCK(vp, 0);
3160                                 vdropl(vp);
3161                                 continue;
3162                         }
3163                 } else
3164                         VI_LOCK(vp);
3165                 /*
3166                  * With v_usecount == 0, all we need to do is clear out the
3167                  * vnode data structures and we are done.
3168                  *
3169                  * If FORCECLOSE is set, forcibly close the vnode.
3170                  */
3171                 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
3172                         vgonel(vp);
3173                 } else {
3174                         busy++;
3175 #ifdef DIAGNOSTIC
3176                         if (busyprt)
3177                                 vn_printf(vp, "vflush: busy vnode ");
3178 #endif
3179                 }
3180                 VOP_UNLOCK(vp, 0);
3181                 vdropl(vp);
3182         }
3183         if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
3184                 /*
3185                  * If just the root vnode is busy, and if its refcount
3186                  * is equal to `rootrefs', then go ahead and kill it.
3187                  */
3188                 VI_LOCK(rootvp);
3189                 KASSERT(busy > 0, ("vflush: not busy"));
3190                 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
3191                     ("vflush: usecount %d < rootrefs %d",
3192                      rootvp->v_usecount, rootrefs));
3193                 if (busy == 1 && rootvp->v_usecount == rootrefs) {
3194                         VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
3195                         vgone(rootvp);
3196                         VOP_UNLOCK(rootvp, 0);
3197                         busy = 0;
3198                 } else
3199                         VI_UNLOCK(rootvp);
3200         }
3201         if (busy) {
3202                 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
3203                     busy);
3204                 return (EBUSY);
3205         }
3206         for (; rootrefs > 0; rootrefs--)
3207                 vrele(rootvp);
3208         return (0);
3209 }
3210
3211 /*
3212  * Recycle an unused vnode to the front of the free list.
3213  */
3214 int
3215 vrecycle(struct vnode *vp)
3216 {
3217         int recycled;
3218
3219         VI_LOCK(vp);
3220         recycled = vrecyclel(vp);
3221         VI_UNLOCK(vp);
3222         return (recycled);
3223 }
3224
3225 /*
3226  * vrecycle, with the vp interlock held.
3227  */
3228 int
3229 vrecyclel(struct vnode *vp)
3230 {
3231         int recycled;
3232
3233         ASSERT_VOP_ELOCKED(vp, __func__);
3234         ASSERT_VI_LOCKED(vp, __func__);
3235         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3236         recycled = 0;
3237         if (vp->v_usecount == 0) {
3238                 recycled = 1;
3239                 vgonel(vp);
3240         }
3241         return (recycled);
3242 }
3243
3244 /*
3245  * Eliminate all activity associated with a vnode
3246  * in preparation for reuse.
3247  */
3248 void
3249 vgone(struct vnode *vp)
3250 {
3251         VI_LOCK(vp);
3252         vgonel(vp);
3253         VI_UNLOCK(vp);
3254 }
3255
3256 static void
3257 notify_lowervp_vfs_dummy(struct mount *mp __unused,
3258     struct vnode *lowervp __unused)
3259 {
3260 }
3261
3262 /*
3263  * Notify upper mounts about reclaimed or unlinked vnode.
3264  */
3265 void
3266 vfs_notify_upper(struct vnode *vp, int event)
3267 {
3268         static struct vfsops vgonel_vfsops = {
3269                 .vfs_reclaim_lowervp = notify_lowervp_vfs_dummy,
3270                 .vfs_unlink_lowervp = notify_lowervp_vfs_dummy,
3271         };
3272         struct mount *mp, *ump, *mmp;
3273
3274         mp = vp->v_mount;
3275         if (mp == NULL)
3276                 return;
3277
3278         MNT_ILOCK(mp);
3279         if (TAILQ_EMPTY(&mp->mnt_uppers))
3280                 goto unlock;
3281         MNT_IUNLOCK(mp);
3282         mmp = malloc(sizeof(struct mount), M_TEMP, M_WAITOK | M_ZERO);
3283         mmp->mnt_op = &vgonel_vfsops;
3284         mmp->mnt_kern_flag |= MNTK_MARKER;
3285         MNT_ILOCK(mp);
3286         mp->mnt_kern_flag |= MNTK_VGONE_UPPER;
3287         for (ump = TAILQ_FIRST(&mp->mnt_uppers); ump != NULL;) {
3288                 if ((ump->mnt_kern_flag & MNTK_MARKER) != 0) {
3289                         ump = TAILQ_NEXT(ump, mnt_upper_link);
3290                         continue;
3291                 }
3292                 TAILQ_INSERT_AFTER(&mp->mnt_uppers, ump, mmp, mnt_upper_link);
3293                 MNT_IUNLOCK(mp);
3294                 switch (event) {
3295                 case VFS_NOTIFY_UPPER_RECLAIM:
3296                         VFS_RECLAIM_LOWERVP(ump, vp);
3297                         break;
3298                 case VFS_NOTIFY_UPPER_UNLINK:
3299                         VFS_UNLINK_LOWERVP(ump, vp);
3300                         break;
3301                 default:
3302                         KASSERT(0, ("invalid event %d", event));
3303                         break;
3304                 }
3305                 MNT_ILOCK(mp);
3306                 ump = TAILQ_NEXT(mmp, mnt_upper_link);
3307                 TAILQ_REMOVE(&mp->mnt_uppers, mmp, mnt_upper_link);
3308         }
3309         free(mmp, M_TEMP);
3310         mp->mnt_kern_flag &= ~MNTK_VGONE_UPPER;
3311         if ((mp->mnt_kern_flag & MNTK_VGONE_WAITER) != 0) {
3312                 mp->mnt_kern_flag &= ~MNTK_VGONE_WAITER;
3313                 wakeup(&mp->mnt_uppers);
3314         }
3315 unlock:
3316         MNT_IUNLOCK(mp);
3317 }
3318
3319 /*
3320  * vgone, with the vp interlock held.
3321  */
3322 static void
3323 vgonel(struct vnode *vp)
3324 {
3325         struct thread *td;
3326         int oweinact;
3327         int active;
3328         struct mount *mp;
3329
3330         ASSERT_VOP_ELOCKED(vp, "vgonel");
3331         ASSERT_VI_LOCKED(vp, "vgonel");
3332         VNASSERT(vp->v_holdcnt, vp,
3333             ("vgonel: vp %p has no reference.", vp));
3334         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3335         td = curthread;
3336
3337         /*
3338          * Don't vgonel if we're already doomed.
3339          */
3340         if (vp->v_iflag & VI_DOOMED)
3341                 return;
3342         vp->v_iflag |= VI_DOOMED;
3343
3344         /*
3345          * Check to see if the vnode is in use.  If so, we have to call
3346          * VOP_CLOSE() and VOP_INACTIVE().
3347          */
3348         active = vp->v_usecount;
3349         oweinact = (vp->v_iflag & VI_OWEINACT);
3350         VI_UNLOCK(vp);
3351         vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
3352
3353         /*
3354          * If purging an active vnode, it must be closed and
3355          * deactivated before being reclaimed.
3356          */
3357         if (active)
3358                 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
3359         if (oweinact || active) {
3360                 VI_LOCK(vp);
3361                 if ((vp->v_iflag & VI_DOINGINACT) == 0)
3362                         vinactive(vp, td);
3363                 VI_UNLOCK(vp);
3364         }
3365         if (vp->v_type == VSOCK)
3366                 vfs_unp_reclaim(vp);
3367
3368         /*
3369          * Clean out any buffers associated with the vnode.
3370          * If the flush fails, just toss the buffers.
3371          */
3372         mp = NULL;
3373         if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
3374                 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
3375         if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
3376                 while (vinvalbuf(vp, 0, 0, 0) != 0)
3377                         ;
3378         }
3379
3380         BO_LOCK(&vp->v_bufobj);
3381         KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
3382             vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
3383             TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
3384             vp->v_bufobj.bo_clean.bv_cnt == 0,
3385             ("vp %p bufobj not invalidated", vp));
3386
3387         /*
3388          * For VMIO bufobj, BO_DEAD is set in vm_object_terminate()
3389          * after the object's page queue is flushed.
3390          */
3391         if (vp->v_bufobj.bo_object == NULL)
3392                 vp->v_bufobj.bo_flag |= BO_DEAD;
3393         BO_UNLOCK(&vp->v_bufobj);
3394
3395         /*
3396          * Reclaim the vnode.
3397          */
3398         if (VOP_RECLAIM(vp, td))
3399                 panic("vgone: cannot reclaim");
3400         if (mp != NULL)
3401                 vn_finished_secondary_write(mp);
3402         VNASSERT(vp->v_object == NULL, vp,
3403             ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
3404         /*
3405          * Clear the advisory locks and wake up waiting threads.
3406          */
3407         (void)VOP_ADVLOCKPURGE(vp);
3408         vp->v_lockf = NULL;
3409         /*
3410          * Delete from old mount point vnode list.
3411          */
3412         delmntque(vp);
3413         cache_purge(vp);
3414         /*
3415          * Done with purge, reset to the standard lock and invalidate
3416          * the vnode.
3417          */
3418         VI_LOCK(vp);
3419         vp->v_vnlock = &vp->v_lock;
3420         vp->v_op = &dead_vnodeops;
3421         vp->v_tag = "none";
3422         vp->v_type = VBAD;
3423 }
3424
3425 /*
3426  * Calculate the total number of references to a special device.
3427  */
3428 int
3429 vcount(struct vnode *vp)
3430 {
3431         int count;
3432
3433         dev_lock();
3434         count = vp->v_rdev->si_usecount;
3435         dev_unlock();
3436         return (count);
3437 }
3438
3439 /*
3440  * Same as above, but using the struct cdev *as argument
3441  */
3442 int
3443 count_dev(struct cdev *dev)
3444 {
3445         int count;
3446
3447         dev_lock();
3448         count = dev->si_usecount;
3449         dev_unlock();
3450         return(count);
3451 }
3452
3453 /*
3454  * Print out a description of a vnode.
3455  */
3456 static char *typename[] =
3457 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
3458  "VMARKER"};
3459
3460 void
3461 vn_printf(struct vnode *vp, const char *fmt, ...)
3462 {
3463         va_list ap;
3464         char buf[256], buf2[16];
3465         u_long flags;
3466
3467         va_start(ap, fmt);
3468         vprintf(fmt, ap);
3469         va_end(ap);
3470         printf("%p: ", (void *)vp);
3471         printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
3472         printf("    usecount %d, writecount %d, refcount %d mountedhere %p\n",
3473             vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
3474         buf[0] = '\0';
3475         buf[1] = '\0';
3476         if (vp->v_vflag & VV_ROOT)
3477                 strlcat(buf, "|VV_ROOT", sizeof(buf));
3478         if (vp->v_vflag & VV_ISTTY)
3479                 strlcat(buf, "|VV_ISTTY", sizeof(buf));
3480         if (vp->v_vflag & VV_NOSYNC)
3481                 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
3482         if (vp->v_vflag & VV_ETERNALDEV)
3483                 strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
3484         if (vp->v_vflag & VV_CACHEDLABEL)
3485                 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
3486         if (vp->v_vflag & VV_TEXT)
3487                 strlcat(buf, "|VV_TEXT", sizeof(buf));
3488         if (vp->v_vflag & VV_COPYONWRITE)
3489                 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
3490         if (vp->v_vflag & VV_SYSTEM)
3491                 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
3492         if (vp->v_vflag & VV_PROCDEP)
3493                 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
3494         if (vp->v_vflag & VV_NOKNOTE)
3495                 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
3496         if (vp->v_vflag & VV_DELETED)
3497                 strlcat(buf, "|VV_DELETED", sizeof(buf));
3498         if (vp->v_vflag & VV_MD)
3499                 strlcat(buf, "|VV_MD", sizeof(buf));
3500         if (vp->v_vflag & VV_FORCEINSMQ)
3501                 strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
3502         flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
3503             VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
3504             VV_NOKNOTE | VV_DELETED | VV_MD | VV_FORCEINSMQ);
3505         if (flags != 0) {
3506                 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
3507                 strlcat(buf, buf2, sizeof(buf));
3508         }
3509         if (vp->v_iflag & VI_MOUNT)
3510                 strlcat(buf, "|VI_MOUNT", sizeof(buf));
3511         if (vp->v_iflag & VI_DOOMED)
3512                 strlcat(buf, "|VI_DOOMED", sizeof(buf));
3513         if (vp->v_iflag & VI_FREE)
3514                 strlcat(buf, "|VI_FREE", sizeof(buf));
3515         if (vp->v_iflag & VI_ACTIVE)
3516                 strlcat(buf, "|VI_ACTIVE", sizeof(buf));
3517         if (vp->v_iflag & VI_DOINGINACT)
3518                 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
3519         if (vp->v_iflag & VI_OWEINACT)
3520                 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
3521         flags = vp->v_iflag & ~(VI_MOUNT | VI_DOOMED | VI_FREE |
3522             VI_ACTIVE | VI_DOINGINACT | VI_OWEINACT);
3523         if (flags != 0) {
3524                 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
3525                 strlcat(buf, buf2, sizeof(buf));
3526         }
3527         printf("    flags (%s)\n", buf + 1);
3528         if (mtx_owned(VI_MTX(vp)))
3529                 printf(" VI_LOCKed");
3530         if (vp->v_object != NULL)
3531                 printf("    v_object %p ref %d pages %d "
3532                     "cleanbuf %d dirtybuf %d\n",
3533                     vp->v_object, vp->v_object->ref_count,
3534                     vp->v_object->resident_page_count,
3535                     vp->v_bufobj.bo_clean.bv_cnt,
3536                     vp->v_bufobj.bo_dirty.bv_cnt);
3537         printf("    ");
3538         lockmgr_printinfo(vp->v_vnlock);
3539         if (vp->v_data != NULL)
3540                 VOP_PRINT(vp);
3541 }
3542
3543 #ifdef DDB
3544 /*
3545  * List all of the locked vnodes in the system.
3546  * Called when debugging the kernel.
3547  */
3548 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
3549 {
3550         struct mount *mp;
3551         struct vnode *vp;
3552
3553         /*
3554          * Note: because this is DDB, we can't obey the locking semantics
3555          * for these structures, which means we could catch an inconsistent
3556          * state and dereference a nasty pointer.  Not much to be done
3557          * about that.
3558          */
3559         db_printf("Locked vnodes\n");
3560         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3561                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3562                         if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
3563                                 vn_printf(vp, "vnode ");
3564                 }
3565         }
3566 }
3567
3568 /*
3569  * Show details about the given vnode.
3570  */
3571 DB_SHOW_COMMAND(vnode, db_show_vnode)
3572 {
3573         struct vnode *vp;
3574
3575         if (!have_addr)
3576                 return;
3577         vp = (struct vnode *)addr;
3578         vn_printf(vp, "vnode ");
3579 }
3580
3581 /*
3582  * Show details about the given mount point.
3583  */
3584 DB_SHOW_COMMAND(mount, db_show_mount)
3585 {
3586         struct mount *mp;
3587         struct vfsopt *opt;
3588         struct statfs *sp;
3589         struct vnode *vp;
3590         char buf[512];
3591         uint64_t mflags;
3592         u_int flags;
3593
3594         if (!have_addr) {
3595                 /* No address given, print short info about all mount points. */
3596                 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3597                         db_printf("%p %s on %s (%s)\n", mp,
3598                             mp->mnt_stat.f_mntfromname,
3599                             mp->mnt_stat.f_mntonname,
3600                             mp->mnt_stat.f_fstypename);
3601                         if (db_pager_quit)
3602                                 break;
3603                 }
3604                 db_printf("\nMore info: show mount <addr>\n");
3605                 return;
3606         }
3607
3608         mp = (struct mount *)addr;
3609         db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
3610             mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
3611
3612         buf[0] = '\0';
3613         mflags = mp->mnt_flag;
3614 #define MNT_FLAG(flag)  do {                                            \
3615         if (mflags & (flag)) {                                          \
3616                 if (buf[0] != '\0')                                     \
3617                         strlcat(buf, ", ", sizeof(buf));                \
3618                 strlcat(buf, (#flag) + 4, sizeof(buf));                 \
3619                 mflags &= ~(flag);                                      \
3620         }                                                               \
3621 } while (0)
3622         MNT_FLAG(MNT_RDONLY);
3623         MNT_FLAG(MNT_SYNCHRONOUS);
3624         MNT_FLAG(MNT_NOEXEC);
3625         MNT_FLAG(MNT_NOSUID);
3626         MNT_FLAG(MNT_NFS4ACLS);
3627         MNT_FLAG(MNT_UNION);
3628         MNT_FLAG(MNT_ASYNC);
3629         MNT_FLAG(MNT_SUIDDIR);
3630         MNT_FLAG(MNT_SOFTDEP);
3631         MNT_FLAG(MNT_NOSYMFOLLOW);
3632         MNT_FLAG(MNT_GJOURNAL);
3633         MNT_FLAG(MNT_MULTILABEL);
3634         MNT_FLAG(MNT_ACLS);
3635         MNT_FLAG(MNT_NOATIME);
3636         MNT_FLAG(MNT_NOCLUSTERR);
3637         MNT_FLAG(MNT_NOCLUSTERW);
3638         MNT_FLAG(MNT_SUJ);
3639         MNT_FLAG(MNT_EXRDONLY);
3640         MNT_FLAG(MNT_EXPORTED);
3641         MNT_FLAG(MNT_DEFEXPORTED);
3642         MNT_FLAG(MNT_EXPORTANON);
3643         MNT_FLAG(MNT_EXKERB);
3644         MNT_FLAG(MNT_EXPUBLIC);
3645         MNT_FLAG(MNT_LOCAL);
3646         MNT_FLAG(MNT_QUOTA);
3647         MNT_FLAG(MNT_ROOTFS);
3648         MNT_FLAG(MNT_USER);
3649         MNT_FLAG(MNT_IGNORE);
3650         MNT_FLAG(MNT_UPDATE);
3651         MNT_FLAG(MNT_DELEXPORT);
3652         MNT_FLAG(MNT_RELOAD);
3653         MNT_FLAG(MNT_FORCE);
3654         MNT_FLAG(MNT_SNAPSHOT);
3655         MNT_FLAG(MNT_BYFSID);
3656 #undef MNT_FLAG
3657         if (mflags != 0) {
3658                 if (buf[0] != '\0')
3659                         strlcat(buf, ", ", sizeof(buf));
3660                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3661                     "0x%016jx", mflags);
3662         }
3663         db_printf("    mnt_flag = %s\n", buf);
3664
3665         buf[0] = '\0';
3666         flags = mp->mnt_kern_flag;
3667 #define MNT_KERN_FLAG(flag)     do {                                    \
3668         if (flags & (flag)) {                                           \
3669                 if (buf[0] != '\0')                                     \
3670                         strlcat(buf, ", ", sizeof(buf));                \
3671                 strlcat(buf, (#flag) + 5, sizeof(buf));                 \
3672                 flags &= ~(flag);                                       \
3673         }                                                               \
3674 } while (0)
3675         MNT_KERN_FLAG(MNTK_UNMOUNTF);
3676         MNT_KERN_FLAG(MNTK_ASYNC);
3677         MNT_KERN_FLAG(MNTK_SOFTDEP);
3678         MNT_KERN_FLAG(MNTK_NOINSMNTQ);
3679         MNT_KERN_FLAG(MNTK_DRAINING);
3680         MNT_KERN_FLAG(MNTK_REFEXPIRE);
3681         MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
3682         MNT_KERN_FLAG(MNTK_SHARED_WRITES);
3683         MNT_KERN_FLAG(MNTK_NO_IOPF);
3684         MNT_KERN_FLAG(MNTK_VGONE_UPPER);
3685         MNT_KERN_FLAG(MNTK_VGONE_WAITER);
3686         MNT_KERN_FLAG(MNTK_LOOKUP_EXCL_DOTDOT);
3687         MNT_KERN_FLAG(MNTK_MARKER);
3688         MNT_KERN_FLAG(MNTK_USES_BCACHE);
3689         MNT_KERN_FLAG(MNTK_NOASYNC);
3690         MNT_KERN_FLAG(MNTK_UNMOUNT);
3691         MNT_KERN_FLAG(MNTK_MWAIT);
3692         MNT_KERN_FLAG(MNTK_SUSPEND);
3693         MNT_KERN_FLAG(MNTK_SUSPEND2);
3694         MNT_KERN_FLAG(MNTK_SUSPENDED);
3695         MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
3696         MNT_KERN_FLAG(MNTK_NOKNOTE);
3697 #undef MNT_KERN_FLAG
3698         if (flags != 0) {
3699                 if (buf[0] != '\0')
3700                         strlcat(buf, ", ", sizeof(buf));
3701                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
3702                     "0x%08x", flags);
3703         }
3704         db_printf("    mnt_kern_flag = %s\n", buf);
3705
3706         db_printf("    mnt_opt = ");
3707         opt = TAILQ_FIRST(mp->mnt_opt);
3708         if (opt != NULL) {
3709                 db_printf("%s", opt->name);
3710                 opt = TAILQ_NEXT(opt, link);
3711                 while (opt != NULL) {
3712                         db_printf(", %s", opt->name);
3713                         opt = TAILQ_NEXT(opt, link);
3714                 }
3715         }
3716         db_printf("\n");
3717
3718         sp = &mp->mnt_stat;
3719         db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
3720             "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
3721             "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
3722             "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
3723             (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
3724             (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
3725             (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
3726             (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
3727             (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
3728             (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
3729             (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
3730             (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
3731
3732         db_printf("    mnt_cred = { uid=%u ruid=%u",
3733             (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
3734         if (jailed(mp->mnt_cred))
3735                 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
3736         db_printf(" }\n");
3737         db_printf("    mnt_ref = %d\n", mp->mnt_ref);
3738         db_printf("    mnt_gen = %d\n", mp->mnt_gen);
3739         db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
3740         db_printf("    mnt_activevnodelistsize = %d\n",
3741             mp->mnt_activevnodelistsize);
3742         db_printf("    mnt_writeopcount = %d\n", mp->mnt_writeopcount);
3743         db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
3744         db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
3745         db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
3746         db_printf("    mnt_lockref = %d\n", mp->mnt_lockref);
3747         db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
3748         db_printf("    mnt_secondary_accwrites = %d\n",
3749             mp->mnt_secondary_accwrites);
3750         db_printf("    mnt_gjprovider = %s\n",
3751             mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
3752
3753         db_printf("\n\nList of active vnodes\n");
3754         TAILQ_FOREACH(vp, &mp->mnt_activevnodelist, v_actfreelist) {
3755                 if (vp->v_type != VMARKER) {
3756                         vn_printf(vp, "vnode ");
3757                         if (db_pager_quit)
3758                                 break;
3759                 }
3760         }
3761         db_printf("\n\nList of inactive vnodes\n");
3762         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3763                 if (vp->v_type != VMARKER && (vp->v_iflag & VI_ACTIVE) == 0) {
3764                         vn_printf(vp, "vnode ");
3765                         if (db_pager_quit)
3766                                 break;
3767                 }
3768         }
3769 }
3770 #endif  /* DDB */
3771
3772 /*
3773  * Fill in a struct xvfsconf based on a struct vfsconf.
3774  */
3775 static int
3776 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
3777 {
3778         struct xvfsconf xvfsp;
3779
3780         bzero(&xvfsp, sizeof(xvfsp));
3781         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3782         xvfsp.vfc_typenum = vfsp->vfc_typenum;
3783         xvfsp.vfc_refcount = vfsp->vfc_refcount;
3784         xvfsp.vfc_flags = vfsp->vfc_flags;
3785         /*
3786          * These are unused in userland, we keep them
3787          * to not break binary compatibility.
3788          */
3789         xvfsp.vfc_vfsops = NULL;
3790         xvfsp.vfc_next = NULL;
3791         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3792 }
3793
3794 #ifdef COMPAT_FREEBSD32
3795 struct xvfsconf32 {
3796         uint32_t        vfc_vfsops;
3797         char            vfc_name[MFSNAMELEN];
3798         int32_t         vfc_typenum;
3799         int32_t         vfc_refcount;
3800         int32_t         vfc_flags;
3801         uint32_t        vfc_next;
3802 };
3803
3804 static int
3805 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
3806 {
3807         struct xvfsconf32 xvfsp;
3808
3809         bzero(&xvfsp, sizeof(xvfsp));
3810         strcpy(xvfsp.vfc_name, vfsp->vfc_name);
3811         xvfsp.vfc_typenum = vfsp->vfc_typenum;
3812         xvfsp.vfc_refcount = vfsp->vfc_refcount;
3813         xvfsp.vfc_flags = vfsp->vfc_flags;
3814         return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3815 }
3816 #endif
3817
3818 /*
3819  * Top level filesystem related information gathering.
3820  */
3821 static int
3822 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
3823 {
3824         struct vfsconf *vfsp;
3825         int error;
3826
3827         error = 0;
3828         vfsconf_slock();
3829         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3830 #ifdef COMPAT_FREEBSD32
3831                 if (req->flags & SCTL_MASK32)
3832                         error = vfsconf2x32(req, vfsp);
3833                 else
3834 #endif
3835                         error = vfsconf2x(req, vfsp);
3836                 if (error)
3837                         break;
3838         }
3839         vfsconf_sunlock();
3840         return (error);
3841 }
3842
3843 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
3844     CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
3845     "S,xvfsconf", "List of all configured filesystems");
3846
3847 #ifndef BURN_BRIDGES
3848 static int      sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
3849
3850 static int
3851 vfs_sysctl(SYSCTL_HANDLER_ARGS)
3852 {
3853         int *name = (int *)arg1 - 1;    /* XXX */
3854         u_int namelen = arg2 + 1;       /* XXX */
3855         struct vfsconf *vfsp;
3856
3857         log(LOG_WARNING, "userland calling deprecated sysctl, "
3858             "please rebuild world\n");
3859
3860 #if 1 || defined(COMPAT_PRELITE2)
3861         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
3862         if (namelen == 1)
3863                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
3864 #endif
3865
3866         switch (name[1]) {
3867         case VFS_MAXTYPENUM:
3868                 if (namelen != 2)
3869                         return (ENOTDIR);
3870                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
3871         case VFS_CONF:
3872                 if (namelen != 3)
3873                         return (ENOTDIR);       /* overloaded */
3874                 vfsconf_slock();
3875                 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3876                         if (vfsp->vfc_typenum == name[2])
3877                                 break;
3878                 }
3879                 vfsconf_sunlock();
3880                 if (vfsp == NULL)
3881                         return (EOPNOTSUPP);
3882 #ifdef COMPAT_FREEBSD32
3883                 if (req->flags & SCTL_MASK32)
3884                         return (vfsconf2x32(req, vfsp));
3885                 else
3886 #endif
3887                         return (vfsconf2x(req, vfsp));
3888         }
3889         return (EOPNOTSUPP);
3890 }
3891
3892 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
3893     CTLFLAG_MPSAFE, vfs_sysctl,
3894     "Generic filesystem");
3895
3896 #if 1 || defined(COMPAT_PRELITE2)
3897
3898 static int
3899 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
3900 {
3901         int error;
3902         struct vfsconf *vfsp;
3903         struct ovfsconf ovfs;
3904
3905         vfsconf_slock();
3906         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3907                 bzero(&ovfs, sizeof(ovfs));
3908                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
3909                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
3910                 ovfs.vfc_index = vfsp->vfc_typenum;
3911                 ovfs.vfc_refcount = vfsp->vfc_refcount;
3912                 ovfs.vfc_flags = vfsp->vfc_flags;
3913                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
3914                 if (error != 0) {
3915                         vfsconf_sunlock();
3916                         return (error);
3917                 }
3918         }
3919         vfsconf_sunlock();
3920         return (0);
3921 }
3922
3923 #endif /* 1 || COMPAT_PRELITE2 */
3924 #endif /* !BURN_BRIDGES */
3925
3926 #define KINFO_VNODESLOP         10
3927 #ifdef notyet
3928 /*
3929  * Dump vnode list (via sysctl).
3930  */
3931 /* ARGSUSED */
3932 static int
3933 sysctl_vnode(SYSCTL_HANDLER_ARGS)
3934 {
3935         struct xvnode *xvn;
3936         struct mount *mp;
3937         struct vnode *vp;
3938         int error, len, n;
3939
3940         /*
3941          * Stale numvnodes access is not fatal here.
3942          */
3943         req->lock = 0;
3944         len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
3945         if (!req->oldptr)
3946                 /* Make an estimate */
3947                 return (SYSCTL_OUT(req, 0, len));
3948
3949         error = sysctl_wire_old_buffer(req, 0);
3950         if (error != 0)
3951                 return (error);
3952         xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3953         n = 0;
3954         mtx_lock(&mountlist_mtx);
3955         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3956                 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
3957                         continue;
3958                 MNT_ILOCK(mp);
3959                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3960                         if (n == len)
3961                                 break;
3962                         vref(vp);
3963                         xvn[n].xv_size = sizeof *xvn;
3964                         xvn[n].xv_vnode = vp;
3965                         xvn[n].xv_id = 0;       /* XXX compat */
3966 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3967                         XV_COPY(usecount);
3968                         XV_COPY(writecount);
3969                         XV_COPY(holdcnt);
3970                         XV_COPY(mount);
3971                         XV_COPY(numoutput);
3972                         XV_COPY(type);
3973 #undef XV_COPY
3974                         xvn[n].xv_flag = vp->v_vflag;
3975
3976                         switch (vp->v_type) {
3977                         case VREG:
3978                         case VDIR:
3979                         case VLNK:
3980                                 break;
3981                         case VBLK:
3982                         case VCHR:
3983                                 if (vp->v_rdev == NULL) {
3984                                         vrele(vp);
3985                                         continue;
3986                                 }
3987                                 xvn[n].xv_dev = dev2udev(vp->v_rdev);
3988                                 break;
3989                         case VSOCK:
3990                                 xvn[n].xv_socket = vp->v_socket;
3991                                 break;
3992                         case VFIFO:
3993                                 xvn[n].xv_fifo = vp->v_fifoinfo;
3994                                 break;
3995                         case VNON:
3996                         case VBAD:
3997                         default:
3998                                 /* shouldn't happen? */
3999                                 vrele(vp);
4000                                 continue;
4001                         }
4002                         vrele(vp);
4003                         ++n;
4004                 }
4005                 MNT_IUNLOCK(mp);
4006                 mtx_lock(&mountlist_mtx);
4007                 vfs_unbusy(mp);
4008                 if (n == len)
4009                         break;
4010         }
4011         mtx_unlock(&mountlist_mtx);
4012
4013         error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
4014         free(xvn, M_TEMP);
4015         return (error);
4016 }
4017
4018 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE | CTLFLAG_RD |
4019     CTLFLAG_MPSAFE, 0, 0, sysctl_vnode, "S,xvnode",
4020     "");
4021 #endif
4022
4023 static void
4024 unmount_or_warn(struct mount *mp)
4025 {
4026         int error;
4027
4028         error = dounmount(mp, MNT_FORCE, curthread);
4029         if (error != 0) {
4030                 printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
4031                 if (error == EBUSY)
4032                         printf("BUSY)\n");
4033                 else
4034                         printf("%d)\n", error);
4035         }
4036 }
4037
4038 /*
4039  * Unmount all filesystems. The list is traversed in reverse order
4040  * of mounting to avoid dependencies.
4041  */
4042 void
4043 vfs_unmountall(void)
4044 {
4045         struct mount *mp, *tmp;
4046
4047         CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
4048
4049         /*
4050          * Since this only runs when rebooting, it is not interlocked.
4051          */
4052         TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
4053                 vfs_ref(mp);
4054
4055                 /*
4056                  * Forcibly unmounting "/dev" before "/" would prevent clean
4057                  * unmount of the latter.
4058                  */
4059                 if (mp == rootdevmp)
4060                         continue;
4061
4062                 unmount_or_warn(mp);
4063         }
4064
4065         if (rootdevmp != NULL)
4066                 unmount_or_warn(rootdevmp);
4067 }
4068
4069 /*
4070  * perform msync on all vnodes under a mount point
4071  * the mount point must be locked.
4072  */
4073 void
4074 vfs_msync(struct mount *mp, int flags)
4075 {
4076         struct vnode *vp, *mvp;
4077         struct vm_object *obj;
4078
4079         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
4080
4081         vnlru_return_batch(mp);
4082
4083         MNT_VNODE_FOREACH_ACTIVE(vp, mp, mvp) {
4084                 obj = vp->v_object;
4085                 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
4086                     (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
4087                         if (!vget(vp,
4088                             LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
4089                             curthread)) {
4090                                 if (vp->v_vflag & VV_NOSYNC) {  /* unlinked */
4091                                         vput(vp);
4092                                         continue;
4093                                 }
4094
4095                                 obj = vp->v_object;
4096                                 if (obj != NULL) {
4097                                         VM_OBJECT_WLOCK(obj);
4098                                         vm_object_page_clean(obj, 0, 0,
4099                                             flags == MNT_WAIT ?
4100                                             OBJPC_SYNC : OBJPC_NOSYNC);
4101                                         VM_OBJECT_WUNLOCK(obj);
4102                                 }
4103                                 vput(vp);
4104                         }
4105                 } else
4106                         VI_UNLOCK(vp);
4107         }
4108 }
4109
4110 static void
4111 destroy_vpollinfo_free(struct vpollinfo *vi)
4112 {
4113
4114         knlist_destroy(&vi->vpi_selinfo.si_note);
4115         mtx_destroy(&vi->vpi_lock);
4116         uma_zfree(vnodepoll_zone, vi);
4117 }
4118
4119 static void
4120 destroy_vpollinfo(struct vpollinfo *vi)
4121 {
4122
4123         knlist_clear(&vi->vpi_selinfo.si_note, 1);
4124         seldrain(&vi->vpi_selinfo);
4125         destroy_vpollinfo_free(vi);
4126 }
4127
4128 /*
4129  * Initialize per-vnode helper structure to hold poll-related state.
4130  */
4131 void
4132 v_addpollinfo(struct vnode *vp)
4133 {
4134         struct vpollinfo *vi;
4135
4136         if (vp->v_pollinfo != NULL)
4137                 return;
4138         vi = uma_zalloc(vnodepoll_zone, M_WAITOK | M_ZERO);
4139         mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
4140         knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
4141             vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
4142         VI_LOCK(vp);
4143         if (vp->v_pollinfo != NULL) {
4144                 VI_UNLOCK(vp);
4145                 destroy_vpollinfo_free(vi);
4146                 return;
4147         }
4148         vp->v_pollinfo = vi;
4149         VI_UNLOCK(vp);
4150 }
4151
4152 /*
4153  * Record a process's interest in events which might happen to
4154  * a vnode.  Because poll uses the historic select-style interface
4155  * internally, this routine serves as both the ``check for any
4156  * pending events'' and the ``record my interest in future events''
4157  * functions.  (These are done together, while the lock is held,
4158  * to avoid race conditions.)
4159  */
4160 int
4161 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
4162 {
4163
4164         v_addpollinfo(vp);
4165         mtx_lock(&vp->v_pollinfo->vpi_lock);
4166         if (vp->v_pollinfo->vpi_revents & events) {
4167                 /*
4168                  * This leaves events we are not interested
4169                  * in available for the other process which
4170                  * which presumably had requested them
4171                  * (otherwise they would never have been
4172                  * recorded).
4173                  */
4174                 events &= vp->v_pollinfo->vpi_revents;
4175                 vp->v_pollinfo->vpi_revents &= ~events;
4176
4177                 mtx_unlock(&vp->v_pollinfo->vpi_lock);
4178                 return (events);
4179         }
4180         vp->v_pollinfo->vpi_events |= events;
4181         selrecord(td, &vp->v_pollinfo->vpi_selinfo);
4182         mtx_unlock(&vp->v_pollinfo->vpi_lock);
4183         return (0);
4184 }
4185
4186 /*
4187  * Routine to create and manage a filesystem syncer vnode.
4188  */
4189 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
4190 static int      sync_fsync(struct  vop_fsync_args *);
4191 static int      sync_inactive(struct  vop_inactive_args *);
4192 static int      sync_reclaim(struct  vop_reclaim_args *);
4193
4194 static struct vop_vector sync_vnodeops = {
4195         .vop_bypass =   VOP_EOPNOTSUPP,
4196         .vop_close =    sync_close,             /* close */
4197         .vop_fsync =    sync_fsync,             /* fsync */
4198         .vop_inactive = sync_inactive,  /* inactive */
4199         .vop_reclaim =  sync_reclaim,   /* reclaim */
4200         .vop_lock1 =    vop_stdlock,    /* lock */
4201         .vop_unlock =   vop_stdunlock,  /* unlock */
4202         .vop_islocked = vop_stdislocked,        /* islocked */
4203 };
4204
4205 /*
4206  * Create a new filesystem syncer vnode for the specified mount point.
4207  */
4208 void
4209 vfs_allocate_syncvnode(struct mount *mp)
4210 {
4211         struct vnode *vp;
4212         struct bufobj *bo;
4213         static long start, incr, next;
4214         int error;
4215
4216         /* Allocate a new vnode */
4217         error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
4218         if (error != 0)
4219                 panic("vfs_allocate_syncvnode: getnewvnode() failed");
4220         vp->v_type = VNON;
4221         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4222         vp->v_vflag |= VV_FORCEINSMQ;
4223         error = insmntque(vp, mp);
4224         if (error != 0)
4225                 panic("vfs_allocate_syncvnode: insmntque() failed");
4226         vp->v_vflag &= ~VV_FORCEINSMQ;
4227         VOP_UNLOCK(vp, 0);
4228         /*
4229          * Place the vnode onto the syncer worklist. We attempt to
4230          * scatter them about on the list so that they will go off
4231          * at evenly distributed times even if all the filesystems
4232          * are mounted at once.
4233          */
4234         next += incr;
4235         if (next == 0 || next > syncer_maxdelay) {
4236                 start /= 2;
4237                 incr /= 2;
4238                 if (start == 0) {
4239                         start = syncer_maxdelay / 2;
4240                         incr = syncer_maxdelay;
4241                 }
4242                 next = start;
4243         }
4244         bo = &vp->v_bufobj;
4245         BO_LOCK(bo);
4246         vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
4247         /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
4248         mtx_lock(&sync_mtx);
4249         sync_vnode_count++;
4250         if (mp->mnt_syncer == NULL) {
4251                 mp->mnt_syncer = vp;
4252                 vp = NULL;
4253         }
4254         mtx_unlock(&sync_mtx);
4255         BO_UNLOCK(bo);
4256         if (vp != NULL) {
4257                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4258                 vgone(vp);
4259                 vput(vp);
4260         }
4261 }
4262
4263 void
4264 vfs_deallocate_syncvnode(struct mount *mp)
4265 {
4266         struct vnode *vp;
4267
4268         mtx_lock(&sync_mtx);
4269         vp = mp->mnt_syncer;
4270         if (vp != NULL)
4271                 mp->mnt_syncer = NULL;
4272         mtx_unlock(&sync_mtx);
4273         if (vp != NULL)
4274                 vrele(vp);
4275 }
4276
4277 /*
4278  * Do a lazy sync of the filesystem.
4279  */
4280 static int
4281 sync_fsync(struct vop_fsync_args *ap)
4282 {
4283         struct vnode *syncvp = ap->a_vp;
4284         struct mount *mp = syncvp->v_mount;
4285         int error, save;
4286         struct bufobj *bo;
4287
4288         /*
4289          * We only need to do something if this is a lazy evaluation.
4290          */
4291         if (ap->a_waitfor != MNT_LAZY)
4292                 return (0);
4293
4294         /*
4295          * Move ourselves to the back of the sync list.
4296          */
4297         bo = &syncvp->v_bufobj;
4298         BO_LOCK(bo);
4299         vn_syncer_add_to_worklist(bo, syncdelay);
4300         BO_UNLOCK(bo);
4301
4302         /*
4303          * Walk the list of vnodes pushing all that are dirty and
4304          * not already on the sync list.
4305          */
4306         if (vfs_busy(mp, MBF_NOWAIT) != 0)
4307                 return (0);
4308         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
4309                 vfs_unbusy(mp);
4310                 return (0);
4311         }
4312         save = curthread_pflags_set(TDP_SYNCIO);
4313         vfs_msync(mp, MNT_NOWAIT);
4314         error = VFS_SYNC(mp, MNT_LAZY);
4315         curthread_pflags_restore(save);
4316         vn_finished_write(mp);
4317         vfs_unbusy(mp);
4318         return (error);
4319 }
4320
4321 /*
4322  * The syncer vnode is no referenced.
4323  */
4324 static int
4325 sync_inactive(struct vop_inactive_args *ap)
4326 {
4327
4328         vgone(ap->a_vp);
4329         return (0);
4330 }
4331
4332 /*
4333  * The syncer vnode is no longer needed and is being decommissioned.
4334  *
4335  * Modifications to the worklist must be protected by sync_mtx.
4336  */
4337 static int
4338 sync_reclaim(struct vop_reclaim_args *ap)
4339 {
4340         struct vnode *vp = ap->a_vp;
4341         struct bufobj *bo;
4342
4343         bo = &vp->v_bufobj;
4344         BO_LOCK(bo);
4345         mtx_lock(&sync_mtx);
4346         if (vp->v_mount->mnt_syncer == vp)
4347                 vp->v_mount->mnt_syncer = NULL;
4348         if (bo->bo_flag & BO_ONWORKLST) {
4349                 LIST_REMOVE(bo, bo_synclist);
4350                 syncer_worklist_len--;
4351                 sync_vnode_count--;
4352                 bo->bo_flag &= ~BO_ONWORKLST;
4353         }
4354         mtx_unlock(&sync_mtx);
4355         BO_UNLOCK(bo);
4356
4357         return (0);
4358 }
4359
4360 /*
4361  * Check if vnode represents a disk device
4362  */
4363 int
4364 vn_isdisk(struct vnode *vp, int *errp)
4365 {
4366         int error;
4367
4368         if (vp->v_type != VCHR) {
4369                 error = ENOTBLK;
4370                 goto out;
4371         }
4372         error = 0;
4373         dev_lock();
4374         if (vp->v_rdev == NULL)
4375                 error = ENXIO;
4376         else if (vp->v_rdev->si_devsw == NULL)
4377                 error = ENXIO;
4378         else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
4379                 error = ENOTBLK;
4380         dev_unlock();
4381 out:
4382         if (errp != NULL)
4383                 *errp = error;
4384         return (error == 0);
4385 }
4386
4387 /*
4388  * Common filesystem object access control check routine.  Accepts a
4389  * vnode's type, "mode", uid and gid, requested access mode, credentials,
4390  * and optional call-by-reference privused argument allowing vaccess()
4391  * to indicate to the caller whether privilege was used to satisfy the
4392  * request (obsoleted).  Returns 0 on success, or an errno on failure.
4393  */
4394 int
4395 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
4396     accmode_t accmode, struct ucred *cred, int *privused)
4397 {
4398         accmode_t dac_granted;
4399         accmode_t priv_granted;
4400
4401         KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
4402             ("invalid bit in accmode"));
4403         KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
4404             ("VAPPEND without VWRITE"));
4405
4406         /*
4407          * Look for a normal, non-privileged way to access the file/directory
4408          * as requested.  If it exists, go with that.
4409          */
4410
4411         if (privused != NULL)
4412                 *privused = 0;
4413
4414         dac_granted = 0;
4415
4416         /* Check the owner. */
4417         if (cred->cr_uid == file_uid) {
4418                 dac_granted |= VADMIN;
4419                 if (file_mode & S_IXUSR)
4420                         dac_granted |= VEXEC;
4421                 if (file_mode & S_IRUSR)
4422                         dac_granted |= VREAD;
4423                 if (file_mode & S_IWUSR)
4424                         dac_granted |= (VWRITE | VAPPEND);
4425
4426                 if ((accmode & dac_granted) == accmode)
4427                         return (0);
4428
4429                 goto privcheck;
4430         }
4431
4432         /* Otherwise, check the groups (first match) */
4433         if (groupmember(file_gid, cred)) {
4434                 if (file_mode & S_IXGRP)
4435                         dac_granted |= VEXEC;
4436                 if (file_mode & S_IRGRP)
4437                         dac_granted |= VREAD;
4438                 if (file_mode & S_IWGRP)
4439                         dac_granted |= (VWRITE | VAPPEND);
4440
4441                 if ((accmode & dac_granted) == accmode)
4442                         return (0);
4443
4444                 goto privcheck;
4445         }
4446
4447         /* Otherwise, check everyone else. */
4448         if (file_mode & S_IXOTH)
4449                 dac_granted |= VEXEC;
4450         if (file_mode & S_IROTH)
4451                 dac_granted |= VREAD;
4452         if (file_mode & S_IWOTH)
4453                 dac_granted |= (VWRITE | VAPPEND);
4454         if ((accmode & dac_granted) == accmode)
4455                 return (0);
4456
4457 privcheck:
4458         /*
4459          * Build a privilege mask to determine if the set of privileges
4460          * satisfies the requirements when combined with the granted mask
4461          * from above.  For each privilege, if the privilege is required,
4462          * bitwise or the request type onto the priv_granted mask.
4463          */
4464         priv_granted = 0;
4465
4466         if (type == VDIR) {
4467                 /*
4468                  * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
4469                  * requests, instead of PRIV_VFS_EXEC.
4470                  */
4471                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4472                     !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
4473                         priv_granted |= VEXEC;
4474         } else {
4475                 /*
4476                  * Ensure that at least one execute bit is on. Otherwise,
4477                  * a privileged user will always succeed, and we don't want
4478                  * this to happen unless the file really is executable.
4479                  */
4480                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
4481                     (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
4482                     !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
4483                         priv_granted |= VEXEC;
4484         }
4485
4486         if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
4487             !priv_check_cred(cred, PRIV_VFS_READ, 0))
4488                 priv_granted |= VREAD;
4489
4490         if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
4491             !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
4492                 priv_granted |= (VWRITE | VAPPEND);
4493
4494         if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
4495             !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
4496                 priv_granted |= VADMIN;
4497
4498         if ((accmode & (priv_granted | dac_granted)) == accmode) {
4499                 /* XXX audit: privilege used */
4500                 if (privused != NULL)
4501                         *privused = 1;
4502                 return (0);
4503         }
4504
4505         return ((accmode & VADMIN) ? EPERM : EACCES);
4506 }
4507
4508 /*
4509  * Credential check based on process requesting service, and per-attribute
4510  * permissions.
4511  */
4512 int
4513 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
4514     struct thread *td, accmode_t accmode)
4515 {
4516
4517         /*
4518          * Kernel-invoked always succeeds.
4519          */
4520         if (cred == NOCRED)
4521                 return (0);
4522
4523         /*
4524          * Do not allow privileged processes in jail to directly manipulate
4525          * system attributes.
4526          */
4527         switch (attrnamespace) {
4528         case EXTATTR_NAMESPACE_SYSTEM:
4529                 /* Potentially should be: return (EPERM); */
4530                 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
4531         case EXTATTR_NAMESPACE_USER:
4532                 return (VOP_ACCESS(vp, accmode, cred, td));
4533         default:
4534                 return (EPERM);
4535         }
4536 }
4537
4538 #ifdef DEBUG_VFS_LOCKS
4539 /*
4540  * This only exists to suppress warnings from unlocked specfs accesses.  It is
4541  * no longer ok to have an unlocked VFS.
4542  */
4543 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL ||            \
4544         (vp)->v_type == VCHR || (vp)->v_type == VBAD)
4545
4546 int vfs_badlock_ddb = 1;        /* Drop into debugger on violation. */
4547 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0,
4548     "Drop into debugger on lock violation");
4549
4550 int vfs_badlock_mutex = 1;      /* Check for interlock across VOPs. */
4551 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex,
4552     0, "Check for interlock across VOPs");
4553
4554 int vfs_badlock_print = 1;      /* Print lock violations. */
4555 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print,
4556     0, "Print lock violations");
4557
4558 int vfs_badlock_vnode = 1;      /* Print vnode details on lock violations. */
4559 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_vnode, CTLFLAG_RW, &vfs_badlock_vnode,
4560     0, "Print vnode details on lock violations");
4561
4562 #ifdef KDB
4563 int vfs_badlock_backtrace = 1;  /* Print backtrace at lock violations. */
4564 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW,
4565     &vfs_badlock_backtrace, 0, "Print backtrace at lock violations");
4566 #endif
4567
4568 static void
4569 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
4570 {
4571
4572 #ifdef KDB
4573         if (vfs_badlock_backtrace)
4574                 kdb_backtrace();
4575 #endif
4576         if (vfs_badlock_vnode)
4577                 vn_printf(vp, "vnode ");
4578         if (vfs_badlock_print)
4579                 printf("%s: %p %s\n", str, (void *)vp, msg);
4580         if (vfs_badlock_ddb)
4581                 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4582 }
4583
4584 void
4585 assert_vi_locked(struct vnode *vp, const char *str)
4586 {
4587
4588         if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
4589                 vfs_badlock("interlock is not locked but should be", str, vp);
4590 }
4591
4592 void
4593 assert_vi_unlocked(struct vnode *vp, const char *str)
4594 {
4595
4596         if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
4597                 vfs_badlock("interlock is locked but should not be", str, vp);
4598 }
4599
4600 void
4601 assert_vop_locked(struct vnode *vp, const char *str)
4602 {
4603         int locked;
4604
4605         if (!IGNORE_LOCK(vp)) {
4606                 locked = VOP_ISLOCKED(vp);
4607                 if (locked == 0 || locked == LK_EXCLOTHER)
4608                         vfs_badlock("is not locked but should be", str, vp);
4609         }
4610 }
4611
4612 void
4613 assert_vop_unlocked(struct vnode *vp, const char *str)
4614 {
4615
4616         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
4617                 vfs_badlock("is locked but should not be", str, vp);
4618 }
4619
4620 void
4621 assert_vop_elocked(struct vnode *vp, const char *str)
4622 {
4623
4624         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
4625                 vfs_badlock("is not exclusive locked but should be", str, vp);
4626 }
4627 #endif /* DEBUG_VFS_LOCKS */
4628
4629 void
4630 vop_rename_fail(struct vop_rename_args *ap)
4631 {
4632
4633         if (ap->a_tvp != NULL)
4634                 vput(ap->a_tvp);
4635         if (ap->a_tdvp == ap->a_tvp)
4636                 vrele(ap->a_tdvp);
4637         else
4638                 vput(ap->a_tdvp);
4639         vrele(ap->a_fdvp);
4640         vrele(ap->a_fvp);
4641 }
4642
4643 void
4644 vop_rename_pre(void *ap)
4645 {
4646         struct vop_rename_args *a = ap;
4647
4648 #ifdef DEBUG_VFS_LOCKS
4649         if (a->a_tvp)
4650                 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
4651         ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
4652         ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
4653         ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
4654
4655         /* Check the source (from). */
4656         if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
4657             (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
4658                 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
4659         if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
4660                 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
4661
4662         /* Check the target. */
4663         if (a->a_tvp)
4664                 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
4665         ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
4666 #endif
4667         if (a->a_tdvp != a->a_fdvp)
4668                 vhold(a->a_fdvp);
4669         if (a->a_tvp != a->a_fvp)
4670                 vhold(a->a_fvp);
4671         vhold(a->a_tdvp);
4672         if (a->a_tvp)
4673                 vhold(a->a_tvp);
4674 }
4675
4676 #ifdef DEBUG_VFS_LOCKS
4677 void
4678 vop_strategy_pre(void *ap)
4679 {
4680         struct vop_strategy_args *a;
4681         struct buf *bp;
4682
4683         a = ap;
4684         bp = a->a_bp;
4685
4686         /*
4687          * Cluster ops lock their component buffers but not the IO container.
4688          */
4689         if ((bp->b_flags & B_CLUSTER) != 0)
4690                 return;
4691
4692         if (panicstr == NULL && !BUF_ISLOCKED(bp)) {
4693                 if (vfs_badlock_print)
4694                         printf(
4695                             "VOP_STRATEGY: bp is not locked but should be\n");
4696                 if (vfs_badlock_ddb)
4697                         kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
4698         }
4699 }
4700
4701 void
4702 vop_lock_pre(void *ap)
4703 {
4704         struct vop_lock1_args *a = ap;
4705
4706         if ((a->a_flags & LK_INTERLOCK) == 0)
4707                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4708         else
4709                 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
4710 }
4711
4712 void
4713 vop_lock_post(void *ap, int rc)
4714 {
4715         struct vop_lock1_args *a = ap;
4716
4717         ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
4718         if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
4719                 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
4720 }
4721
4722 void
4723 vop_unlock_pre(void *ap)
4724 {
4725         struct vop_unlock_args *a = ap;
4726
4727         if (a->a_flags & LK_INTERLOCK)
4728                 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
4729         ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
4730 }
4731
4732 void
4733 vop_unlock_post(void *ap, int rc)
4734 {
4735         struct vop_unlock_args *a = ap;
4736
4737         if (a->a_flags & LK_INTERLOCK)
4738                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
4739 }
4740 #endif
4741
4742 void
4743 vop_create_post(void *ap, int rc)
4744 {
4745         struct vop_create_args *a = ap;
4746
4747         if (!rc)
4748                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4749 }
4750
4751 void
4752 vop_deleteextattr_post(void *ap, int rc)
4753 {
4754         struct vop_deleteextattr_args *a = ap;
4755
4756         if (!rc)
4757                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4758 }
4759
4760 void
4761 vop_link_post(void *ap, int rc)
4762 {
4763         struct vop_link_args *a = ap;
4764
4765         if (!rc) {
4766                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
4767                 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
4768         }
4769 }
4770
4771 void
4772 vop_mkdir_post(void *ap, int rc)
4773 {
4774         struct vop_mkdir_args *a = ap;
4775
4776         if (!rc)
4777                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4778 }
4779
4780 void
4781 vop_mknod_post(void *ap, int rc)
4782 {
4783         struct vop_mknod_args *a = ap;
4784
4785         if (!rc)
4786                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4787 }
4788
4789 void
4790 vop_reclaim_post(void *ap, int rc)
4791 {
4792         struct vop_reclaim_args *a = ap;
4793
4794         if (!rc)
4795                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_REVOKE);
4796 }
4797
4798 void
4799 vop_remove_post(void *ap, int rc)
4800 {
4801         struct vop_remove_args *a = ap;
4802
4803         if (!rc) {
4804                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4805                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4806         }
4807 }
4808
4809 void
4810 vop_rename_post(void *ap, int rc)
4811 {
4812         struct vop_rename_args *a = ap;
4813         long hint;
4814
4815         if (!rc) {
4816                 hint = NOTE_WRITE;
4817                 if (a->a_fdvp == a->a_tdvp) {
4818                         if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
4819                                 hint |= NOTE_LINK;
4820                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4821                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4822                 } else {
4823                         hint |= NOTE_EXTEND;
4824                         if (a->a_fvp->v_type == VDIR)
4825                                 hint |= NOTE_LINK;
4826                         VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
4827
4828                         if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
4829                             a->a_tvp->v_type == VDIR)
4830                                 hint &= ~NOTE_LINK;
4831                         VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
4832                 }
4833
4834                 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
4835                 if (a->a_tvp)
4836                         VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
4837         }
4838         if (a->a_tdvp != a->a_fdvp)
4839                 vdrop(a->a_fdvp);
4840         if (a->a_tvp != a->a_fvp)
4841                 vdrop(a->a_fvp);
4842         vdrop(a->a_tdvp);
4843         if (a->a_tvp)
4844                 vdrop(a->a_tvp);
4845 }
4846
4847 void
4848 vop_rmdir_post(void *ap, int rc)
4849 {
4850         struct vop_rmdir_args *a = ap;
4851
4852         if (!rc) {
4853                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
4854                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
4855         }
4856 }
4857
4858 void
4859 vop_setattr_post(void *ap, int rc)
4860 {
4861         struct vop_setattr_args *a = ap;
4862
4863         if (!rc)
4864                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4865 }
4866
4867 void
4868 vop_setextattr_post(void *ap, int rc)
4869 {
4870         struct vop_setextattr_args *a = ap;
4871
4872         if (!rc)
4873                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4874 }
4875
4876 void
4877 vop_symlink_post(void *ap, int rc)
4878 {
4879         struct vop_symlink_args *a = ap;
4880
4881         if (!rc)
4882                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4883 }
4884
4885 void
4886 vop_open_post(void *ap, int rc)
4887 {
4888         struct vop_open_args *a = ap;
4889
4890         if (!rc)
4891                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
4892 }
4893
4894 void
4895 vop_close_post(void *ap, int rc)
4896 {
4897         struct vop_close_args *a = ap;
4898
4899         if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
4900             (a->a_vp->v_iflag & VI_DOOMED) == 0)) {
4901                 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
4902                     NOTE_CLOSE_WRITE : NOTE_CLOSE);
4903         }
4904 }
4905
4906 void
4907 vop_read_post(void *ap, int rc)
4908 {
4909         struct vop_read_args *a = ap;
4910
4911         if (!rc)
4912                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
4913 }
4914
4915 void
4916 vop_readdir_post(void *ap, int rc)
4917 {
4918         struct vop_readdir_args *a = ap;
4919
4920         if (!rc)
4921                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
4922 }
4923
4924 static struct knlist fs_knlist;
4925
4926 static void
4927 vfs_event_init(void *arg)
4928 {
4929         knlist_init_mtx(&fs_knlist, NULL);
4930 }
4931 /* XXX - correct order? */
4932 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
4933
4934 void
4935 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
4936 {
4937
4938         KNOTE_UNLOCKED(&fs_knlist, event);
4939 }
4940
4941 static int      filt_fsattach(struct knote *kn);
4942 static void     filt_fsdetach(struct knote *kn);
4943 static int      filt_fsevent(struct knote *kn, long hint);
4944
4945 struct filterops fs_filtops = {
4946         .f_isfd = 0,
4947         .f_attach = filt_fsattach,
4948         .f_detach = filt_fsdetach,
4949         .f_event = filt_fsevent
4950 };
4951
4952 static int
4953 filt_fsattach(struct knote *kn)
4954 {
4955
4956         kn->kn_flags |= EV_CLEAR;
4957         knlist_add(&fs_knlist, kn, 0);
4958         return (0);
4959 }
4960
4961 static void
4962 filt_fsdetach(struct knote *kn)
4963 {
4964
4965         knlist_remove(&fs_knlist, kn, 0);
4966 }
4967
4968 static int
4969 filt_fsevent(struct knote *kn, long hint)
4970 {
4971
4972         kn->kn_fflags |= hint;
4973         return (kn->kn_fflags != 0);
4974 }
4975
4976 static int
4977 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
4978 {
4979         struct vfsidctl vc;
4980         int error;
4981         struct mount *mp;
4982
4983         error = SYSCTL_IN(req, &vc, sizeof(vc));
4984         if (error)
4985                 return (error);
4986         if (vc.vc_vers != VFS_CTL_VERS1)
4987                 return (EINVAL);
4988         mp = vfs_getvfs(&vc.vc_fsid);
4989         if (mp == NULL)
4990                 return (ENOENT);
4991         /* ensure that a specific sysctl goes to the right filesystem. */
4992         if (strcmp(vc.vc_fstypename, "*") != 0 &&
4993             strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
4994                 vfs_rel(mp);
4995                 return (EINVAL);
4996         }
4997         VCTLTOREQ(&vc, req);
4998         error = VFS_SYSCTL(mp, vc.vc_op, req);
4999         vfs_rel(mp);
5000         return (error);
5001 }
5002
5003 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_WR,
5004     NULL, 0, sysctl_vfs_ctl, "",
5005     "Sysctl by fsid");
5006
5007 /*
5008  * Function to initialize a va_filerev field sensibly.
5009  * XXX: Wouldn't a random number make a lot more sense ??
5010  */
5011 u_quad_t
5012 init_va_filerev(void)
5013 {
5014         struct bintime bt;
5015
5016         getbinuptime(&bt);
5017         return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
5018 }
5019
5020 static int      filt_vfsread(struct knote *kn, long hint);
5021 static int      filt_vfswrite(struct knote *kn, long hint);
5022 static int      filt_vfsvnode(struct knote *kn, long hint);
5023 static void     filt_vfsdetach(struct knote *kn);
5024 static struct filterops vfsread_filtops = {
5025         .f_isfd = 1,
5026         .f_detach = filt_vfsdetach,
5027         .f_event = filt_vfsread
5028 };
5029 static struct filterops vfswrite_filtops = {
5030         .f_isfd = 1,
5031         .f_detach = filt_vfsdetach,
5032         .f_event = filt_vfswrite
5033 };
5034 static struct filterops vfsvnode_filtops = {
5035         .f_isfd = 1,
5036         .f_detach = filt_vfsdetach,
5037         .f_event = filt_vfsvnode
5038 };
5039
5040 static void
5041 vfs_knllock(void *arg)
5042 {
5043         struct vnode *vp = arg;
5044
5045         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5046 }
5047
5048 static void
5049 vfs_knlunlock(void *arg)
5050 {
5051         struct vnode *vp = arg;
5052
5053         VOP_UNLOCK(vp, 0);
5054 }
5055
5056 static void
5057 vfs_knl_assert_locked(void *arg)
5058 {
5059 #ifdef DEBUG_VFS_LOCKS
5060         struct vnode *vp = arg;
5061
5062         ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
5063 #endif
5064 }
5065
5066 static void
5067 vfs_knl_assert_unlocked(void *arg)
5068 {
5069 #ifdef DEBUG_VFS_LOCKS
5070         struct vnode *vp = arg;
5071
5072         ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
5073 #endif
5074 }
5075
5076 int
5077 vfs_kqfilter(struct vop_kqfilter_args *ap)
5078 {
5079         struct vnode *vp = ap->a_vp;
5080         struct knote *kn = ap->a_kn;
5081         struct knlist *knl;
5082
5083         switch (kn->kn_filter) {
5084         case EVFILT_READ:
5085                 kn->kn_fop = &vfsread_filtops;
5086                 break;
5087         case EVFILT_WRITE:
5088                 kn->kn_fop = &vfswrite_filtops;
5089                 break;
5090         case EVFILT_VNODE:
5091                 kn->kn_fop = &vfsvnode_filtops;
5092                 break;
5093         default:
5094                 return (EINVAL);
5095         }
5096
5097         kn->kn_hook = (caddr_t)vp;
5098
5099         v_addpollinfo(vp);
5100         if (vp->v_pollinfo == NULL)
5101                 return (ENOMEM);
5102         knl = &vp->v_pollinfo->vpi_selinfo.si_note;
5103         vhold(vp);
5104         knlist_add(knl, kn, 0);
5105
5106         return (0);
5107 }
5108
5109 /*
5110  * Detach knote from vnode
5111  */
5112 static void
5113 filt_vfsdetach(struct knote *kn)
5114 {
5115         struct vnode *vp = (struct vnode *)kn->kn_hook;
5116
5117         KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
5118         knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
5119         vdrop(vp);
5120 }
5121
5122 /*ARGSUSED*/
5123 static int
5124 filt_vfsread(struct knote *kn, long hint)
5125 {
5126         struct vnode *vp = (struct vnode *)kn->kn_hook;
5127         struct vattr va;
5128         int res;
5129
5130         /*
5131          * filesystem is gone, so set the EOF flag and schedule
5132          * the knote for deletion.
5133          */
5134         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5135                 VI_LOCK(vp);
5136                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5137                 VI_UNLOCK(vp);
5138                 return (1);
5139         }
5140
5141         if (VOP_GETATTR(vp, &va, curthread->td_ucred))
5142                 return (0);
5143
5144         VI_LOCK(vp);
5145         kn->kn_data = va.va_size - kn->kn_fp->f_offset;
5146         res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
5147         VI_UNLOCK(vp);
5148         return (res);
5149 }
5150
5151 /*ARGSUSED*/
5152 static int
5153 filt_vfswrite(struct knote *kn, long hint)
5154 {
5155         struct vnode *vp = (struct vnode *)kn->kn_hook;
5156
5157         VI_LOCK(vp);
5158
5159         /*
5160          * filesystem is gone, so set the EOF flag and schedule
5161          * the knote for deletion.
5162          */
5163         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
5164                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
5165
5166         kn->kn_data = 0;
5167         VI_UNLOCK(vp);
5168         return (1);
5169 }
5170
5171 static int
5172 filt_vfsvnode(struct knote *kn, long hint)
5173 {
5174         struct vnode *vp = (struct vnode *)kn->kn_hook;
5175         int res;
5176
5177         VI_LOCK(vp);
5178         if (kn->kn_sfflags & hint)
5179                 kn->kn_fflags |= hint;
5180         if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
5181                 kn->kn_flags |= EV_EOF;
5182                 VI_UNLOCK(vp);
5183                 return (1);
5184         }
5185         res = (kn->kn_fflags != 0);
5186         VI_UNLOCK(vp);
5187         return (res);
5188 }
5189
5190 int
5191 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
5192 {
5193         int error;
5194
5195         if (dp->d_reclen > ap->a_uio->uio_resid)
5196                 return (ENAMETOOLONG);
5197         error = uiomove(dp, dp->d_reclen, ap->a_uio);
5198         if (error) {
5199                 if (ap->a_ncookies != NULL) {
5200                         if (ap->a_cookies != NULL)
5201                                 free(ap->a_cookies, M_TEMP);
5202                         ap->a_cookies = NULL;
5203                         *ap->a_ncookies = 0;
5204                 }
5205                 return (error);
5206         }
5207         if (ap->a_ncookies == NULL)
5208                 return (0);
5209
5210         KASSERT(ap->a_cookies,
5211             ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
5212
5213         *ap->a_cookies = realloc(*ap->a_cookies,
5214             (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
5215         (*ap->a_cookies)[*ap->a_ncookies] = off;
5216         *ap->a_ncookies += 1;
5217         return (0);
5218 }
5219
5220 /*
5221  * Mark for update the access time of the file if the filesystem
5222  * supports VOP_MARKATIME.  This functionality is used by execve and
5223  * mmap, so we want to avoid the I/O implied by directly setting
5224  * va_atime for the sake of efficiency.
5225  */
5226 void
5227 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
5228 {
5229         struct mount *mp;
5230
5231         mp = vp->v_mount;
5232         ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
5233         if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
5234                 (void)VOP_MARKATIME(vp);
5235 }
5236
5237 /*
5238  * The purpose of this routine is to remove granularity from accmode_t,
5239  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
5240  * VADMIN and VAPPEND.
5241  *
5242  * If it returns 0, the caller is supposed to continue with the usual
5243  * access checks using 'accmode' as modified by this routine.  If it
5244  * returns nonzero value, the caller is supposed to return that value
5245  * as errno.
5246  *
5247  * Note that after this routine runs, accmode may be zero.
5248  */
5249 int
5250 vfs_unixify_accmode(accmode_t *accmode)
5251 {
5252         /*
5253          * There is no way to specify explicit "deny" rule using
5254          * file mode or POSIX.1e ACLs.
5255          */
5256         if (*accmode & VEXPLICIT_DENY) {
5257                 *accmode = 0;
5258                 return (0);
5259         }
5260
5261         /*
5262          * None of these can be translated into usual access bits.
5263          * Also, the common case for NFSv4 ACLs is to not contain
5264          * either of these bits. Caller should check for VWRITE
5265          * on the containing directory instead.
5266          */
5267         if (*accmode & (VDELETE_CHILD | VDELETE))
5268                 return (EPERM);
5269
5270         if (*accmode & VADMIN_PERMS) {
5271                 *accmode &= ~VADMIN_PERMS;
5272                 *accmode |= VADMIN;
5273         }
5274
5275         /*
5276          * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
5277          * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
5278          */
5279         *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
5280
5281         return (0);
5282 }
5283
5284 /*
5285  * These are helper functions for filesystems to traverse all
5286  * their vnodes.  See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
5287  *
5288  * This interface replaces MNT_VNODE_FOREACH.
5289  */
5290
5291 MALLOC_DEFINE(M_VNODE_MARKER, "vnodemarker", "vnode marker");
5292
5293 struct vnode *
5294 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
5295 {
5296         struct vnode *vp;
5297
5298         if (should_yield())
5299                 kern_yield(PRI_USER);
5300         MNT_ILOCK(mp);
5301         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5302         for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
5303             vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
5304                 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5305                 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5306                         continue;
5307                 VI_LOCK(vp);
5308                 if ((vp->v_iflag & VI_DOOMED) != 0) {
5309                         VI_UNLOCK(vp);
5310                         continue;
5311                 }
5312                 break;
5313         }
5314         if (vp == NULL) {
5315                 __mnt_vnode_markerfree_all(mvp, mp);
5316                 /* MNT_IUNLOCK(mp); -- done in above function */
5317                 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
5318                 return (NULL);
5319         }
5320         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5321         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5322         MNT_IUNLOCK(mp);
5323         return (vp);
5324 }
5325
5326 struct vnode *
5327 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
5328 {
5329         struct vnode *vp;
5330
5331         *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5332         MNT_ILOCK(mp);
5333         MNT_REF(mp);
5334         (*mvp)->v_mount = mp;
5335         (*mvp)->v_type = VMARKER;
5336
5337         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
5338                 /* Allow a racy peek at VI_DOOMED to save a lock acquisition. */
5339                 if (vp->v_type == VMARKER || (vp->v_iflag & VI_DOOMED) != 0)
5340                         continue;
5341                 VI_LOCK(vp);
5342                 if ((vp->v_iflag & VI_DOOMED) != 0) {
5343                         VI_UNLOCK(vp);
5344                         continue;
5345                 }
5346                 break;
5347         }
5348         if (vp == NULL) {
5349                 MNT_REL(mp);
5350                 MNT_IUNLOCK(mp);
5351                 free(*mvp, M_VNODE_MARKER);
5352                 *mvp = NULL;
5353                 return (NULL);
5354         }
5355         TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
5356         MNT_IUNLOCK(mp);
5357         return (vp);
5358 }
5359
5360 void
5361 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
5362 {
5363
5364         if (*mvp == NULL) {
5365                 MNT_IUNLOCK(mp);
5366                 return;
5367         }
5368
5369         mtx_assert(MNT_MTX(mp), MA_OWNED);
5370
5371         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5372         TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
5373         MNT_REL(mp);
5374         MNT_IUNLOCK(mp);
5375         free(*mvp, M_VNODE_MARKER);
5376         *mvp = NULL;
5377 }
5378
5379 /*
5380  * These are helper functions for filesystems to traverse their
5381  * active vnodes.  See MNT_VNODE_FOREACH_ACTIVE() in sys/mount.h
5382  */
5383 static void
5384 mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5385 {
5386
5387         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5388
5389         MNT_ILOCK(mp);
5390         MNT_REL(mp);
5391         MNT_IUNLOCK(mp);
5392         free(*mvp, M_VNODE_MARKER);
5393         *mvp = NULL;
5394 }
5395
5396 /*
5397  * Relock the mp mount vnode list lock with the vp vnode interlock in the
5398  * conventional lock order during mnt_vnode_next_active iteration.
5399  *
5400  * On entry, the mount vnode list lock is held and the vnode interlock is not.
5401  * The list lock is dropped and reacquired.  On success, both locks are held.
5402  * On failure, the mount vnode list lock is held but the vnode interlock is
5403  * not, and the procedure may have yielded.
5404  */
5405 static bool
5406 mnt_vnode_next_active_relock(struct vnode *mvp, struct mount *mp,
5407     struct vnode *vp)
5408 {
5409         const struct vnode *tmp;
5410         bool held, ret;
5411
5412         VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
5413             TAILQ_NEXT(mvp, v_actfreelist) != NULL, mvp,
5414             ("%s: bad marker", __func__));
5415         VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
5416             ("%s: inappropriate vnode", __func__));
5417         ASSERT_VI_UNLOCKED(vp, __func__);
5418         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5419
5420         ret = false;
5421
5422         TAILQ_REMOVE(&mp->mnt_activevnodelist, mvp, v_actfreelist);
5423         TAILQ_INSERT_BEFORE(vp, mvp, v_actfreelist);
5424
5425         /*
5426          * Use a hold to prevent vp from disappearing while the mount vnode
5427          * list lock is dropped and reacquired.  Normally a hold would be
5428          * acquired with vhold(), but that might try to acquire the vnode
5429          * interlock, which would be a LOR with the mount vnode list lock.
5430          */
5431         held = vfs_refcount_acquire_if_not_zero(&vp->v_holdcnt);
5432         mtx_unlock(&mp->mnt_listmtx);
5433         if (!held)
5434                 goto abort;
5435         VI_LOCK(vp);
5436         if (!vfs_refcount_release_if_not_last(&vp->v_holdcnt)) {
5437                 vdropl(vp);
5438                 goto abort;
5439         }
5440         mtx_lock(&mp->mnt_listmtx);
5441
5442         /*
5443          * Determine whether the vnode is still the next one after the marker,
5444          * excepting any other markers.  If the vnode has not been doomed by
5445          * vgone() then the hold should have ensured that it remained on the
5446          * active list.  If it has been doomed but is still on the active list,
5447          * don't abort, but rather skip over it (avoid spinning on doomed
5448          * vnodes).
5449          */
5450         tmp = mvp;
5451         do {
5452                 tmp = TAILQ_NEXT(tmp, v_actfreelist);
5453         } while (tmp != NULL && tmp->v_type == VMARKER);
5454         if (tmp != vp) {
5455                 mtx_unlock(&mp->mnt_listmtx);
5456                 VI_UNLOCK(vp);
5457                 goto abort;
5458         }
5459
5460         ret = true;
5461         goto out;
5462 abort:
5463         maybe_yield();
5464         mtx_lock(&mp->mnt_listmtx);
5465 out:
5466         if (ret)
5467                 ASSERT_VI_LOCKED(vp, __func__);
5468         else
5469                 ASSERT_VI_UNLOCKED(vp, __func__);
5470         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5471         return (ret);
5472 }
5473
5474 static struct vnode *
5475 mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5476 {
5477         struct vnode *vp, *nvp;
5478
5479         mtx_assert(&mp->mnt_listmtx, MA_OWNED);
5480         KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
5481 restart:
5482         vp = TAILQ_NEXT(*mvp, v_actfreelist);
5483         while (vp != NULL) {
5484                 if (vp->v_type == VMARKER) {
5485                         vp = TAILQ_NEXT(vp, v_actfreelist);
5486                         continue;
5487                 }
5488                 /*
5489                  * Try-lock because this is the wrong lock order.  If that does
5490                  * not succeed, drop the mount vnode list lock and try to
5491                  * reacquire it and the vnode interlock in the right order.
5492                  */
5493                 if (!VI_TRYLOCK(vp) &&
5494                     !mnt_vnode_next_active_relock(*mvp, mp, vp))
5495                         goto restart;
5496                 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
5497                 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
5498                     ("alien vnode on the active list %p %p", vp, mp));
5499                 if (vp->v_mount == mp && (vp->v_iflag & VI_DOOMED) == 0)
5500                         break;
5501                 nvp = TAILQ_NEXT(vp, v_actfreelist);
5502                 VI_UNLOCK(vp);
5503                 vp = nvp;
5504         }
5505         TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5506
5507         /* Check if we are done */
5508         if (vp == NULL) {
5509                 mtx_unlock(&mp->mnt_listmtx);
5510                 mnt_vnode_markerfree_active(mvp, mp);
5511                 return (NULL);
5512         }
5513         TAILQ_INSERT_AFTER(&mp->mnt_activevnodelist, vp, *mvp, v_actfreelist);
5514         mtx_unlock(&mp->mnt_listmtx);
5515         ASSERT_VI_LOCKED(vp, "active iter");
5516         KASSERT((vp->v_iflag & VI_ACTIVE) != 0, ("Non-active vp %p", vp));
5517         return (vp);
5518 }
5519
5520 struct vnode *
5521 __mnt_vnode_next_active(struct vnode **mvp, struct mount *mp)
5522 {
5523
5524         if (should_yield())
5525                 kern_yield(PRI_USER);
5526         mtx_lock(&mp->mnt_listmtx);
5527         return (mnt_vnode_next_active(mvp, mp));
5528 }
5529
5530 struct vnode *
5531 __mnt_vnode_first_active(struct vnode **mvp, struct mount *mp)
5532 {
5533         struct vnode *vp;
5534
5535         *mvp = malloc(sizeof(struct vnode), M_VNODE_MARKER, M_WAITOK | M_ZERO);
5536         MNT_ILOCK(mp);
5537         MNT_REF(mp);
5538         MNT_IUNLOCK(mp);
5539         (*mvp)->v_type = VMARKER;
5540         (*mvp)->v_mount = mp;
5541
5542         mtx_lock(&mp->mnt_listmtx);
5543         vp = TAILQ_FIRST(&mp->mnt_activevnodelist);
5544         if (vp == NULL) {
5545                 mtx_unlock(&mp->mnt_listmtx);
5546                 mnt_vnode_markerfree_active(mvp, mp);
5547                 return (NULL);
5548         }
5549         TAILQ_INSERT_BEFORE(vp, *mvp, v_actfreelist);
5550         return (mnt_vnode_next_active(mvp, mp));
5551 }
5552
5553 void
5554 __mnt_vnode_markerfree_active(struct vnode **mvp, struct mount *mp)
5555 {
5556
5557         if (*mvp == NULL)
5558                 return;
5559
5560         mtx_lock(&mp->mnt_listmtx);
5561         TAILQ_REMOVE(&mp->mnt_activevnodelist, *mvp, v_actfreelist);
5562         mtx_unlock(&mp->mnt_listmtx);
5563         mnt_vnode_markerfree_active(mvp, mp);
5564 }