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