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