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