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