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