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