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