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