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