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