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