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