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