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