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