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