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