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