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