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