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