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