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