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