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