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