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