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