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