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