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