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
5131 CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
5132
5133 /*
5134 * Since this only runs when rebooting, it is not interlocked.
5135 */
5136 TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
5137 vfs_ref(mp);
5138
5139 /*
5140 * Forcibly unmounting "/dev" before "/" would prevent clean
5141 * unmount of the latter.
5142 */
5143 if (mp == rootdevmp)
5144 continue;
5145
5146 unmount_or_warn(mp);
5147 }
5148
5149 if (rootdevmp != NULL)
5150 unmount_or_warn(rootdevmp);
5151 }
5152
5153 static void
vfs_deferred_inactive(struct vnode * vp,int lkflags)5154 vfs_deferred_inactive(struct vnode *vp, int lkflags)
5155 {
5156
5157 ASSERT_VI_LOCKED(vp, __func__);
5158 VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
5159 if ((vp->v_iflag & VI_OWEINACT) == 0) {
5160 vdropl(vp);
5161 return;
5162 }
5163 if (vn_lock(vp, lkflags) == 0) {
5164 VI_LOCK(vp);
5165 vinactive(vp);
5166 VOP_UNLOCK(vp);
5167 vdropl(vp);
5168 return;
5169 }
5170 vdefer_inactive_unlocked(vp);
5171 }
5172
5173 static int
vfs_periodic_inactive_filter(struct vnode * vp,void * arg)5174 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
5175 {
5176
5177 return (vp->v_iflag & VI_DEFINACT);
5178 }
5179
5180 static void __noinline
vfs_periodic_inactive(struct mount * mp,int flags)5181 vfs_periodic_inactive(struct mount *mp, int flags)
5182 {
5183 struct vnode *vp, *mvp;
5184 int lkflags;
5185
5186 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
5187 if (flags != MNT_WAIT)
5188 lkflags |= LK_NOWAIT;
5189
5190 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
5191 if ((vp->v_iflag & VI_DEFINACT) == 0) {
5192 VI_UNLOCK(vp);
5193 continue;
5194 }
5195 vp->v_iflag &= ~VI_DEFINACT;
5196 vfs_deferred_inactive(vp, lkflags);
5197 }
5198 }
5199
5200 static inline bool
vfs_want_msync(struct vnode * vp)5201 vfs_want_msync(struct vnode *vp)
5202 {
5203 struct vm_object *obj;
5204
5205 /*
5206 * This test may be performed without any locks held.
5207 * We rely on vm_object's type stability.
5208 */
5209 if (vp->v_vflag & VV_NOSYNC)
5210 return (false);
5211 obj = vp->v_object;
5212 return (obj != NULL && vm_object_mightbedirty(obj));
5213 }
5214
5215 static int
vfs_periodic_msync_inactive_filter(struct vnode * vp,void * arg __unused)5216 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
5217 {
5218
5219 if (vp->v_vflag & VV_NOSYNC)
5220 return (false);
5221 if (vp->v_iflag & VI_DEFINACT)
5222 return (true);
5223 return (vfs_want_msync(vp));
5224 }
5225
5226 static void __noinline
vfs_periodic_msync_inactive(struct mount * mp,int flags)5227 vfs_periodic_msync_inactive(struct mount *mp, int flags)
5228 {
5229 struct vnode *vp, *mvp;
5230 int lkflags;
5231 bool seen_defer;
5232
5233 lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
5234 if (flags != MNT_WAIT)
5235 lkflags |= LK_NOWAIT;
5236
5237 MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
5238 seen_defer = false;
5239 if (vp->v_iflag & VI_DEFINACT) {
5240 vp->v_iflag &= ~VI_DEFINACT;
5241 seen_defer = true;
5242 }
5243 if (!vfs_want_msync(vp)) {
5244 if (seen_defer)
5245 vfs_deferred_inactive(vp, lkflags);
5246 else
5247 VI_UNLOCK(vp);
5248 continue;
5249 }
5250 if (vget(vp, lkflags) == 0) {
5251 if ((vp->v_vflag & VV_NOSYNC) == 0) {
5252 if (flags == MNT_WAIT)
5253 vnode_pager_clean_sync(vp);
5254 else
5255 vnode_pager_clean_async(vp);
5256 }
5257 vput(vp);
5258 if (seen_defer)
5259 vdrop(vp);
5260 } else {
5261 if (seen_defer)
5262 vdefer_inactive_unlocked(vp);
5263 }
5264 }
5265 }
5266
5267 void
vfs_periodic(struct mount * mp,int flags)5268 vfs_periodic(struct mount *mp, int flags)
5269 {
5270
5271 CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
5272
5273 if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
5274 vfs_periodic_inactive(mp, flags);
5275 else
5276 vfs_periodic_msync_inactive(mp, flags);
5277 }
5278
5279 static void
destroy_vpollinfo_free(struct vpollinfo * vi)5280 destroy_vpollinfo_free(struct vpollinfo *vi)
5281 {
5282
5283 knlist_destroy(&vi->vpi_selinfo.si_note);
5284 mtx_destroy(&vi->vpi_lock);
5285 free(vi, M_VNODEPOLL);
5286 }
5287
5288 static void
destroy_vpollinfo(struct vpollinfo * vi)5289 destroy_vpollinfo(struct vpollinfo *vi)
5290 {
5291 KASSERT(TAILQ_EMPTY(&vi->vpi_inotify),
5292 ("%s: pollinfo %p has lingering watches", __func__, vi));
5293 knlist_clear(&vi->vpi_selinfo.si_note, 1);
5294 seldrain(&vi->vpi_selinfo);
5295 destroy_vpollinfo_free(vi);
5296 }
5297
5298 /*
5299 * Initialize per-vnode helper structure to hold poll-related state.
5300 */
5301 void
v_addpollinfo(struct vnode * vp)5302 v_addpollinfo(struct vnode *vp)
5303 {
5304 struct vpollinfo *vi;
5305
5306 if (atomic_load_ptr(&vp->v_pollinfo) != NULL)
5307 return;
5308 vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
5309 mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
5310 knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
5311 vfs_knlunlock, vfs_knl_assert_lock);
5312 TAILQ_INIT(&vi->vpi_inotify);
5313 VI_LOCK(vp);
5314 if (vp->v_pollinfo != NULL) {
5315 VI_UNLOCK(vp);
5316 destroy_vpollinfo_free(vi);
5317 return;
5318 }
5319 vp->v_pollinfo = vi;
5320 VI_UNLOCK(vp);
5321 }
5322
5323 /*
5324 * Record a process's interest in events which might happen to
5325 * a vnode. Because poll uses the historic select-style interface
5326 * internally, this routine serves as both the ``check for any
5327 * pending events'' and the ``record my interest in future events''
5328 * functions. (These are done together, while the lock is held,
5329 * to avoid race conditions.)
5330 */
5331 int
vn_pollrecord(struct vnode * vp,struct thread * td,int events)5332 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
5333 {
5334
5335 v_addpollinfo(vp);
5336 mtx_lock(&vp->v_pollinfo->vpi_lock);
5337 if (vp->v_pollinfo->vpi_revents & events) {
5338 /*
5339 * This leaves events we are not interested
5340 * in available for the other process which
5341 * which presumably had requested them
5342 * (otherwise they would never have been
5343 * recorded).
5344 */
5345 events &= vp->v_pollinfo->vpi_revents;
5346 vp->v_pollinfo->vpi_revents &= ~events;
5347
5348 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5349 return (events);
5350 }
5351 vp->v_pollinfo->vpi_events |= events;
5352 selrecord(td, &vp->v_pollinfo->vpi_selinfo);
5353 mtx_unlock(&vp->v_pollinfo->vpi_lock);
5354 return (0);
5355 }
5356
5357 /*
5358 * Routine to create and manage a filesystem syncer vnode.
5359 */
5360 #define sync_close ((int (*)(struct vop_close_args *))nullop)
5361 static int sync_fsync(struct vop_fsync_args *);
5362 static int sync_inactive(struct vop_inactive_args *);
5363 static int sync_reclaim(struct vop_reclaim_args *);
5364
5365 static struct vop_vector sync_vnodeops = {
5366 .vop_bypass = VOP_EOPNOTSUPP,
5367 .vop_close = sync_close,
5368 .vop_fsync = sync_fsync,
5369 .vop_getwritemount = vop_stdgetwritemount,
5370 .vop_inactive = sync_inactive,
5371 .vop_need_inactive = vop_stdneed_inactive,
5372 .vop_reclaim = sync_reclaim,
5373 .vop_lock1 = vop_stdlock,
5374 .vop_unlock = vop_stdunlock,
5375 .vop_islocked = vop_stdislocked,
5376 .vop_fplookup_vexec = VOP_EAGAIN,
5377 .vop_fplookup_symlink = VOP_EAGAIN,
5378 };
5379 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5380
5381 /*
5382 * Create a new filesystem syncer vnode for the specified mount point.
5383 */
5384 void
vfs_allocate_syncvnode(struct mount * mp)5385 vfs_allocate_syncvnode(struct mount *mp)
5386 {
5387 struct vnode *vp;
5388 struct bufobj *bo;
5389 static long start, incr, next;
5390 int error;
5391
5392 /* Allocate a new vnode */
5393 error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5394 if (error != 0)
5395 panic("vfs_allocate_syncvnode: getnewvnode() failed");
5396 vp->v_type = VNON;
5397 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5398 vp->v_vflag |= VV_FORCEINSMQ;
5399 error = insmntque1(vp, mp);
5400 if (error != 0)
5401 panic("vfs_allocate_syncvnode: insmntque() failed");
5402 vp->v_vflag &= ~VV_FORCEINSMQ;
5403 vn_set_state(vp, VSTATE_CONSTRUCTED);
5404 VOP_UNLOCK(vp);
5405 /*
5406 * Place the vnode onto the syncer worklist. We attempt to
5407 * scatter them about on the list so that they will go off
5408 * at evenly distributed times even if all the filesystems
5409 * are mounted at once.
5410 */
5411 next += incr;
5412 if (next == 0 || next > syncer_maxdelay) {
5413 start /= 2;
5414 incr /= 2;
5415 if (start == 0) {
5416 start = syncer_maxdelay / 2;
5417 incr = syncer_maxdelay;
5418 }
5419 next = start;
5420 }
5421 bo = &vp->v_bufobj;
5422 BO_LOCK(bo);
5423 vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5424 /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5425 mtx_lock(&sync_mtx);
5426 sync_vnode_count++;
5427 if (mp->mnt_syncer == NULL) {
5428 mp->mnt_syncer = vp;
5429 vp = NULL;
5430 }
5431 mtx_unlock(&sync_mtx);
5432 BO_UNLOCK(bo);
5433 if (vp != NULL) {
5434 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5435 vgone(vp);
5436 vput(vp);
5437 }
5438 }
5439
5440 void
vfs_deallocate_syncvnode(struct mount * mp)5441 vfs_deallocate_syncvnode(struct mount *mp)
5442 {
5443 struct vnode *vp;
5444
5445 mtx_lock(&sync_mtx);
5446 vp = mp->mnt_syncer;
5447 if (vp != NULL)
5448 mp->mnt_syncer = NULL;
5449 mtx_unlock(&sync_mtx);
5450 if (vp != NULL)
5451 vrele(vp);
5452 }
5453
5454 /*
5455 * Do a lazy sync of the filesystem.
5456 */
5457 static int
sync_fsync(struct vop_fsync_args * ap)5458 sync_fsync(struct vop_fsync_args *ap)
5459 {
5460 struct vnode *syncvp = ap->a_vp;
5461 struct mount *mp = syncvp->v_mount;
5462 int error, save;
5463 struct bufobj *bo;
5464
5465 /*
5466 * We only need to do something if this is a lazy evaluation.
5467 */
5468 if (ap->a_waitfor != MNT_LAZY)
5469 return (0);
5470
5471 /*
5472 * Move ourselves to the back of the sync list.
5473 */
5474 bo = &syncvp->v_bufobj;
5475 BO_LOCK(bo);
5476 vn_syncer_add_to_worklist(bo, syncdelay);
5477 BO_UNLOCK(bo);
5478
5479 /*
5480 * Walk the list of vnodes pushing all that are dirty and
5481 * not already on the sync list.
5482 */
5483 if (vfs_busy(mp, MBF_NOWAIT) != 0)
5484 return (0);
5485 VOP_UNLOCK(syncvp);
5486 save = curthread_pflags_set(TDP_SYNCIO);
5487 /*
5488 * The filesystem at hand may be idle with free vnodes stored in the
5489 * batch. Return them instead of letting them stay there indefinitely.
5490 */
5491 vfs_periodic(mp, MNT_NOWAIT);
5492 error = VFS_SYNC(mp, MNT_LAZY);
5493 curthread_pflags_restore(save);
5494 vn_lock(syncvp, LK_EXCLUSIVE | LK_RETRY);
5495 vfs_unbusy(mp);
5496 return (error);
5497 }
5498
5499 /*
5500 * The syncer vnode is no referenced.
5501 */
5502 static int
sync_inactive(struct vop_inactive_args * ap)5503 sync_inactive(struct vop_inactive_args *ap)
5504 {
5505
5506 vgone(ap->a_vp);
5507 return (0);
5508 }
5509
5510 /*
5511 * The syncer vnode is no longer needed and is being decommissioned.
5512 *
5513 * Modifications to the worklist must be protected by sync_mtx.
5514 */
5515 static int
sync_reclaim(struct vop_reclaim_args * ap)5516 sync_reclaim(struct vop_reclaim_args *ap)
5517 {
5518 struct vnode *vp = ap->a_vp;
5519 struct bufobj *bo;
5520
5521 bo = &vp->v_bufobj;
5522 BO_LOCK(bo);
5523 mtx_lock(&sync_mtx);
5524 if (vp->v_mount->mnt_syncer == vp)
5525 vp->v_mount->mnt_syncer = NULL;
5526 if (bo->bo_flag & BO_ONWORKLST) {
5527 LIST_REMOVE(bo, bo_synclist);
5528 syncer_worklist_len--;
5529 sync_vnode_count--;
5530 bo->bo_flag &= ~BO_ONWORKLST;
5531 }
5532 mtx_unlock(&sync_mtx);
5533 BO_UNLOCK(bo);
5534
5535 return (0);
5536 }
5537
5538 int
vn_need_pageq_flush(struct vnode * vp)5539 vn_need_pageq_flush(struct vnode *vp)
5540 {
5541 struct vm_object *obj;
5542
5543 obj = vp->v_object;
5544 return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5545 vm_object_mightbedirty(obj));
5546 }
5547
5548 /*
5549 * Check if vnode represents a disk device
5550 */
5551 bool
vn_isdisk_error(struct vnode * vp,int * errp)5552 vn_isdisk_error(struct vnode *vp, int *errp)
5553 {
5554 int error;
5555
5556 if (vp->v_type != VCHR) {
5557 error = ENOTBLK;
5558 goto out;
5559 }
5560 error = 0;
5561 dev_lock();
5562 if (vp->v_rdev == NULL)
5563 error = ENXIO;
5564 else if (vp->v_rdev->si_devsw == NULL)
5565 error = ENXIO;
5566 else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5567 error = ENOTBLK;
5568 dev_unlock();
5569 out:
5570 *errp = error;
5571 return (error == 0);
5572 }
5573
5574 bool
vn_isdisk(struct vnode * vp)5575 vn_isdisk(struct vnode *vp)
5576 {
5577 int error;
5578
5579 return (vn_isdisk_error(vp, &error));
5580 }
5581
5582 /*
5583 * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5584 * the comment above cache_fplookup for details.
5585 */
5586 int
vaccess_vexec_smr(mode_t file_mode,uid_t file_uid,gid_t file_gid,struct ucred * cred)5587 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5588 {
5589 int error;
5590
5591 VFS_SMR_ASSERT_ENTERED();
5592
5593 /* Check the owner. */
5594 if (cred->cr_uid == file_uid) {
5595 if (file_mode & S_IXUSR)
5596 return (0);
5597 goto out_error;
5598 }
5599
5600 /* Otherwise, check the groups (first match) */
5601 if (groupmember(file_gid, cred)) {
5602 if (file_mode & S_IXGRP)
5603 return (0);
5604 goto out_error;
5605 }
5606
5607 /* Otherwise, check everyone else. */
5608 if (file_mode & S_IXOTH)
5609 return (0);
5610 out_error:
5611 /*
5612 * Permission check failed, but it is possible denial will get overwritten
5613 * (e.g., when root is traversing through a 700 directory owned by someone
5614 * else).
5615 *
5616 * vaccess() calls priv_check_cred which in turn can descent into MAC
5617 * modules overriding this result. It's quite unclear what semantics
5618 * are allowed for them to operate, thus for safety we don't call them
5619 * from within the SMR section. This also means if any such modules
5620 * are present, we have to let the regular lookup decide.
5621 */
5622 error = priv_check_cred_vfs_lookup_nomac(cred);
5623 switch (error) {
5624 case 0:
5625 return (0);
5626 case EAGAIN:
5627 /*
5628 * MAC modules present.
5629 */
5630 return (EAGAIN);
5631 case EPERM:
5632 return (EACCES);
5633 default:
5634 return (error);
5635 }
5636 }
5637
5638 /*
5639 * Common filesystem object access control check routine. Accepts a
5640 * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5641 * Returns 0 on success, or an errno on failure.
5642 */
5643 int
vaccess(__enum_uint8 (vtype)type,mode_t file_mode,uid_t file_uid,gid_t file_gid,accmode_t accmode,struct ucred * cred)5644 vaccess(__enum_uint8(vtype) type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5645 accmode_t accmode, struct ucred *cred)
5646 {
5647 accmode_t dac_granted;
5648 accmode_t priv_granted;
5649
5650 KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5651 ("invalid bit in accmode"));
5652 KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5653 ("VAPPEND without VWRITE"));
5654
5655 /*
5656 * Look for a normal, non-privileged way to access the file/directory
5657 * as requested. If it exists, go with that.
5658 */
5659
5660 dac_granted = 0;
5661
5662 /* Check the owner. */
5663 if (cred->cr_uid == file_uid) {
5664 dac_granted |= VADMIN;
5665 if (file_mode & S_IXUSR)
5666 dac_granted |= VEXEC;
5667 if (file_mode & S_IRUSR)
5668 dac_granted |= VREAD;
5669 if (file_mode & S_IWUSR)
5670 dac_granted |= (VWRITE | VAPPEND);
5671
5672 if ((accmode & dac_granted) == accmode)
5673 return (0);
5674
5675 goto privcheck;
5676 }
5677
5678 /* Otherwise, check the groups (first match) */
5679 if (groupmember(file_gid, cred)) {
5680 if (file_mode & S_IXGRP)
5681 dac_granted |= VEXEC;
5682 if (file_mode & S_IRGRP)
5683 dac_granted |= VREAD;
5684 if (file_mode & S_IWGRP)
5685 dac_granted |= (VWRITE | VAPPEND);
5686
5687 if ((accmode & dac_granted) == accmode)
5688 return (0);
5689
5690 goto privcheck;
5691 }
5692
5693 /* Otherwise, check everyone else. */
5694 if (file_mode & S_IXOTH)
5695 dac_granted |= VEXEC;
5696 if (file_mode & S_IROTH)
5697 dac_granted |= VREAD;
5698 if (file_mode & S_IWOTH)
5699 dac_granted |= (VWRITE | VAPPEND);
5700 if ((accmode & dac_granted) == accmode)
5701 return (0);
5702
5703 privcheck:
5704 /*
5705 * Build a privilege mask to determine if the set of privileges
5706 * satisfies the requirements when combined with the granted mask
5707 * from above. For each privilege, if the privilege is required,
5708 * bitwise or the request type onto the priv_granted mask.
5709 */
5710 priv_granted = 0;
5711
5712 if (type == VDIR) {
5713 /*
5714 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5715 * requests, instead of PRIV_VFS_EXEC.
5716 */
5717 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5718 !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5719 priv_granted |= VEXEC;
5720 } else {
5721 /*
5722 * Ensure that at least one execute bit is on. Otherwise,
5723 * a privileged user will always succeed, and we don't want
5724 * this to happen unless the file really is executable.
5725 */
5726 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5727 (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5728 !priv_check_cred(cred, PRIV_VFS_EXEC))
5729 priv_granted |= VEXEC;
5730 }
5731
5732 if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5733 !priv_check_cred(cred, PRIV_VFS_READ))
5734 priv_granted |= VREAD;
5735
5736 if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5737 !priv_check_cred(cred, PRIV_VFS_WRITE))
5738 priv_granted |= (VWRITE | VAPPEND);
5739
5740 if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5741 !priv_check_cred(cred, PRIV_VFS_ADMIN))
5742 priv_granted |= VADMIN;
5743
5744 if ((accmode & (priv_granted | dac_granted)) == accmode) {
5745 return (0);
5746 }
5747
5748 return ((accmode & VADMIN) ? EPERM : EACCES);
5749 }
5750
5751 /*
5752 * Credential check based on process requesting service, and per-attribute
5753 * permissions.
5754 */
5755 int
extattr_check_cred(struct vnode * vp,int attrnamespace,struct ucred * cred,struct thread * td,accmode_t accmode)5756 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5757 struct thread *td, accmode_t accmode)
5758 {
5759
5760 /*
5761 * Kernel-invoked always succeeds.
5762 */
5763 if (cred == NOCRED)
5764 return (0);
5765
5766 /*
5767 * Do not allow privileged processes in jail to directly manipulate
5768 * system attributes.
5769 */
5770 switch (attrnamespace) {
5771 case EXTATTR_NAMESPACE_SYSTEM:
5772 /* Potentially should be: return (EPERM); */
5773 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5774 case EXTATTR_NAMESPACE_USER:
5775 return (VOP_ACCESS(vp, accmode, cred, td));
5776 default:
5777 return (EPERM);
5778 }
5779 }
5780
5781 #ifdef INVARIANTS
5782 void
assert_vi_locked(struct vnode * vp,const char * str)5783 assert_vi_locked(struct vnode *vp, const char *str)
5784 {
5785 VNASSERT(mtx_owned(VI_MTX(vp)), vp,
5786 ("%s: vnode interlock is not locked but should be", str));
5787 }
5788
5789 void
assert_vi_unlocked(struct vnode * vp,const char * str)5790 assert_vi_unlocked(struct vnode *vp, const char *str)
5791 {
5792 VNASSERT(!mtx_owned(VI_MTX(vp)), vp,
5793 ("%s: vnode interlock is locked but should not be", str));
5794 }
5795
5796 void
assert_vop_locked(struct vnode * vp,const char * str)5797 assert_vop_locked(struct vnode *vp, const char *str)
5798 {
5799 bool locked;
5800
5801 if (KERNEL_PANICKED() || vp == NULL)
5802 return;
5803
5804 #ifdef WITNESS
5805 locked = !((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5806 witness_is_owned(&vp->v_vnlock->lock_object) == -1);
5807 #else
5808 int state = VOP_ISLOCKED(vp);
5809 locked = state != 0 && state != LK_EXCLOTHER;
5810 #endif
5811 VNASSERT(locked, vp, ("%s: vnode is not locked but should be", str));
5812 }
5813
5814 void
assert_vop_unlocked(struct vnode * vp,const char * str)5815 assert_vop_unlocked(struct vnode *vp, const char *str)
5816 {
5817 bool locked;
5818
5819 if (KERNEL_PANICKED() || vp == NULL)
5820 return;
5821
5822 #ifdef WITNESS
5823 locked = (vp->v_irflag & VIRF_CROSSMP) == 0 &&
5824 witness_is_owned(&vp->v_vnlock->lock_object) == 1;
5825 #else
5826 locked = VOP_ISLOCKED(vp) == LK_EXCLUSIVE;
5827 #endif
5828 VNASSERT(!locked, vp, ("%s: vnode is locked but should not be", str));
5829 }
5830
5831 void
assert_vop_elocked(struct vnode * vp,const char * str)5832 assert_vop_elocked(struct vnode *vp, const char *str)
5833 {
5834 bool locked;
5835
5836 if (KERNEL_PANICKED() || vp == NULL)
5837 return;
5838
5839 locked = VOP_ISLOCKED(vp) == LK_EXCLUSIVE;
5840 VNASSERT(locked, vp,
5841 ("%s: vnode is not exclusive locked but should be", str));
5842 }
5843 #endif /* INVARIANTS */
5844
5845 void
vop_rename_fail(struct vop_rename_args * ap)5846 vop_rename_fail(struct vop_rename_args *ap)
5847 {
5848
5849 if (ap->a_tvp != NULL)
5850 vput(ap->a_tvp);
5851 if (ap->a_tdvp == ap->a_tvp)
5852 vrele(ap->a_tdvp);
5853 else
5854 vput(ap->a_tdvp);
5855 vrele(ap->a_fdvp);
5856 vrele(ap->a_fvp);
5857 }
5858
5859 void
vop_rename_pre(void * ap)5860 vop_rename_pre(void *ap)
5861 {
5862 struct vop_rename_args *a = ap;
5863
5864 #ifdef INVARIANTS
5865 struct mount *tmp;
5866
5867 if (a->a_tvp)
5868 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5869 ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5870 ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5871 ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5872
5873 /* Check the source (from). */
5874 if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5875 (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5876 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5877 if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5878 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5879
5880 /* Check the target. */
5881 if (a->a_tvp)
5882 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5883 ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5884
5885 tmp = NULL;
5886 VOP_GETWRITEMOUNT(a->a_tdvp, &tmp);
5887 lockmgr_assert(&tmp->mnt_renamelock, KA_XLOCKED);
5888 vfs_rel(tmp);
5889 #endif
5890 /*
5891 * It may be tempting to add vn_seqc_write_begin/end calls here and
5892 * in vop_rename_post but that's not going to work out since some
5893 * filesystems relookup vnodes mid-rename. This is probably a bug.
5894 *
5895 * For now filesystems are expected to do the relevant calls after they
5896 * decide what vnodes to operate on.
5897 */
5898 if (a->a_tdvp != a->a_fdvp)
5899 vhold(a->a_fdvp);
5900 if (a->a_tvp != a->a_fvp)
5901 vhold(a->a_fvp);
5902 vhold(a->a_tdvp);
5903 if (a->a_tvp)
5904 vhold(a->a_tvp);
5905 }
5906
5907 #ifdef INVARIANTS
5908 void
vop_fplookup_vexec_debugpre(void * ap __unused)5909 vop_fplookup_vexec_debugpre(void *ap __unused)
5910 {
5911
5912 VFS_SMR_ASSERT_ENTERED();
5913 }
5914
5915 void
vop_fplookup_vexec_debugpost(void * ap,int rc)5916 vop_fplookup_vexec_debugpost(void *ap, int rc)
5917 {
5918 struct vop_fplookup_vexec_args *a;
5919 struct vnode *vp;
5920
5921 a = ap;
5922 vp = a->a_vp;
5923
5924 VFS_SMR_ASSERT_ENTERED();
5925 if (rc == EOPNOTSUPP)
5926 VNPASS(VN_IS_DOOMED(vp), vp);
5927 }
5928
5929 void
vop_fplookup_symlink_debugpre(void * ap __unused)5930 vop_fplookup_symlink_debugpre(void *ap __unused)
5931 {
5932
5933 VFS_SMR_ASSERT_ENTERED();
5934 }
5935
5936 void
vop_fplookup_symlink_debugpost(void * ap __unused,int rc __unused)5937 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5938 {
5939
5940 VFS_SMR_ASSERT_ENTERED();
5941 }
5942
5943 static void
vop_fsync_debugprepost(struct vnode * vp,const char * name)5944 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5945 {
5946 struct mount *mp;
5947
5948 if (vp->v_type == VCHR)
5949 ;
5950 /*
5951 * The shared vs. exclusive locking policy for fsync()
5952 * is actually determined by vp's write mount as indicated
5953 * by VOP_GETWRITEMOUNT(), which for stacked filesystems
5954 * may not be the same as vp->v_mount. However, if the
5955 * underlying filesystem which really handles the fsync()
5956 * supports shared locking, the stacked filesystem must also
5957 * be prepared for its VOP_FSYNC() operation to be called
5958 * with only a shared lock. On the other hand, if the
5959 * stacked filesystem claims support for shared write
5960 * locking but the underlying filesystem does not, and the
5961 * caller incorrectly uses a shared lock, this condition
5962 * should still be caught when the stacked filesystem
5963 * invokes VOP_FSYNC() on the underlying filesystem.
5964 */
5965 else {
5966 mp = NULL;
5967 VOP_GETWRITEMOUNT(vp, &mp);
5968 if (vn_lktype_write(mp, vp) == LK_SHARED)
5969 ASSERT_VOP_LOCKED(vp, name);
5970 else
5971 ASSERT_VOP_ELOCKED(vp, name);
5972 if (mp != NULL)
5973 vfs_rel(mp);
5974 }
5975 }
5976
5977 void
vop_fsync_debugpre(void * a)5978 vop_fsync_debugpre(void *a)
5979 {
5980 struct vop_fsync_args *ap;
5981
5982 ap = a;
5983 vop_fsync_debugprepost(ap->a_vp, "fsync");
5984 }
5985
5986 void
vop_fsync_debugpost(void * a,int rc __unused)5987 vop_fsync_debugpost(void *a, int rc __unused)
5988 {
5989 struct vop_fsync_args *ap;
5990
5991 ap = a;
5992 vop_fsync_debugprepost(ap->a_vp, "fsync");
5993 }
5994
5995 void
vop_fdatasync_debugpre(void * a)5996 vop_fdatasync_debugpre(void *a)
5997 {
5998 struct vop_fdatasync_args *ap;
5999
6000 ap = a;
6001 vop_fsync_debugprepost(ap->a_vp, "fsync");
6002 }
6003
6004 void
vop_fdatasync_debugpost(void * a,int rc __unused)6005 vop_fdatasync_debugpost(void *a, int rc __unused)
6006 {
6007 struct vop_fdatasync_args *ap;
6008
6009 ap = a;
6010 vop_fsync_debugprepost(ap->a_vp, "fsync");
6011 }
6012
6013 void
vop_strategy_debugpre(void * ap)6014 vop_strategy_debugpre(void *ap)
6015 {
6016 struct vop_strategy_args *a;
6017 struct buf *bp;
6018
6019 a = ap;
6020 bp = a->a_bp;
6021
6022 /*
6023 * Cluster ops lock their component buffers but not the IO container.
6024 */
6025 if ((bp->b_flags & B_CLUSTER) != 0)
6026 return;
6027
6028 BUF_ASSERT_LOCKED(bp);
6029 }
6030
6031 void
vop_lock_debugpre(void * ap)6032 vop_lock_debugpre(void *ap)
6033 {
6034 struct vop_lock1_args *a = ap;
6035
6036 if ((a->a_flags & LK_INTERLOCK) == 0)
6037 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
6038 else
6039 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
6040 }
6041
6042 void
vop_lock_debugpost(void * ap,int rc)6043 vop_lock_debugpost(void *ap, int rc)
6044 {
6045 struct vop_lock1_args *a = ap;
6046
6047 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
6048 if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
6049 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
6050 }
6051
6052 void
vop_unlock_debugpre(void * ap)6053 vop_unlock_debugpre(void *ap)
6054 {
6055 struct vop_unlock_args *a = ap;
6056 struct vnode *vp = a->a_vp;
6057
6058 VNPASS(vn_get_state(vp) != VSTATE_UNINITIALIZED, vp);
6059 ASSERT_VOP_LOCKED(vp, "VOP_UNLOCK");
6060 }
6061
6062 void
vop_need_inactive_debugpre(void * ap)6063 vop_need_inactive_debugpre(void *ap)
6064 {
6065 struct vop_need_inactive_args *a = ap;
6066
6067 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
6068 }
6069
6070 void
vop_need_inactive_debugpost(void * ap,int rc)6071 vop_need_inactive_debugpost(void *ap, int rc)
6072 {
6073 struct vop_need_inactive_args *a = ap;
6074
6075 ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
6076 }
6077 #endif /* INVARIANTS */
6078
6079 void
vop_allocate_post(void * ap,int rc)6080 vop_allocate_post(void *ap, int rc)
6081 {
6082 struct vop_allocate_args *a;
6083
6084 a = ap;
6085 if (rc == 0)
6086 INOTIFY(a->a_vp, IN_MODIFY);
6087 }
6088
6089 void
vop_copy_file_range_post(void * ap,int rc)6090 vop_copy_file_range_post(void *ap, int rc)
6091 {
6092 struct vop_copy_file_range_args *a;
6093
6094 a = ap;
6095 if (rc == 0) {
6096 INOTIFY(a->a_invp, IN_ACCESS);
6097 INOTIFY(a->a_outvp, IN_MODIFY);
6098 }
6099 }
6100
6101 void
vop_create_pre(void * ap)6102 vop_create_pre(void *ap)
6103 {
6104 struct vop_create_args *a;
6105 struct vnode *dvp;
6106
6107 a = ap;
6108 dvp = a->a_dvp;
6109 vn_seqc_write_begin(dvp);
6110 }
6111
6112 void
vop_create_post(void * ap,int rc)6113 vop_create_post(void *ap, int rc)
6114 {
6115 struct vop_create_args *a;
6116 struct vnode *dvp;
6117
6118 a = ap;
6119 dvp = a->a_dvp;
6120 vn_seqc_write_end(dvp);
6121 if (rc == 0) {
6122 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6123 INOTIFY_NAME(*a->a_vpp, dvp, a->a_cnp, IN_CREATE);
6124 }
6125 }
6126
6127 void
vop_deallocate_post(void * ap,int rc)6128 vop_deallocate_post(void *ap, int rc)
6129 {
6130 struct vop_deallocate_args *a;
6131
6132 a = ap;
6133 if (rc == 0)
6134 INOTIFY(a->a_vp, IN_MODIFY);
6135 }
6136
6137 void
vop_whiteout_pre(void * ap)6138 vop_whiteout_pre(void *ap)
6139 {
6140 struct vop_whiteout_args *a;
6141 struct vnode *dvp;
6142
6143 a = ap;
6144 dvp = a->a_dvp;
6145 vn_seqc_write_begin(dvp);
6146 }
6147
6148 void
vop_whiteout_post(void * ap,int rc)6149 vop_whiteout_post(void *ap, int rc)
6150 {
6151 struct vop_whiteout_args *a;
6152 struct vnode *dvp;
6153
6154 a = ap;
6155 dvp = a->a_dvp;
6156 vn_seqc_write_end(dvp);
6157 }
6158
6159 void
vop_deleteextattr_pre(void * ap)6160 vop_deleteextattr_pre(void *ap)
6161 {
6162 struct vop_deleteextattr_args *a;
6163 struct vnode *vp;
6164
6165 a = ap;
6166 vp = a->a_vp;
6167 vn_seqc_write_begin(vp);
6168 }
6169
6170 void
vop_deleteextattr_post(void * ap,int rc)6171 vop_deleteextattr_post(void *ap, int rc)
6172 {
6173 struct vop_deleteextattr_args *a;
6174 struct vnode *vp;
6175
6176 a = ap;
6177 vp = a->a_vp;
6178 vn_seqc_write_end(vp);
6179 if (!rc) {
6180 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
6181 INOTIFY(vp, IN_ATTRIB);
6182 }
6183 }
6184
6185 void
vop_link_pre(void * ap)6186 vop_link_pre(void *ap)
6187 {
6188 struct vop_link_args *a;
6189 struct vnode *vp, *tdvp;
6190
6191 a = ap;
6192 vp = a->a_vp;
6193 tdvp = a->a_tdvp;
6194 vn_seqc_write_begin(vp);
6195 vn_seqc_write_begin(tdvp);
6196 }
6197
6198 void
vop_link_post(void * ap,int rc)6199 vop_link_post(void *ap, int rc)
6200 {
6201 struct vop_link_args *a;
6202 struct vnode *vp, *tdvp;
6203
6204 a = ap;
6205 vp = a->a_vp;
6206 tdvp = a->a_tdvp;
6207 vn_seqc_write_end(vp);
6208 vn_seqc_write_end(tdvp);
6209 if (!rc) {
6210 VFS_KNOTE_LOCKED(vp, NOTE_LINK);
6211 VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
6212 INOTIFY_NAME(vp, tdvp, a->a_cnp, _IN_ATTRIB_LINKCOUNT);
6213 INOTIFY_NAME(vp, tdvp, a->a_cnp, IN_CREATE);
6214 }
6215 }
6216
6217 void
vop_mkdir_pre(void * ap)6218 vop_mkdir_pre(void *ap)
6219 {
6220 struct vop_mkdir_args *a;
6221 struct vnode *dvp;
6222
6223 a = ap;
6224 dvp = a->a_dvp;
6225 vn_seqc_write_begin(dvp);
6226 }
6227
6228 void
vop_mkdir_post(void * ap,int rc)6229 vop_mkdir_post(void *ap, int rc)
6230 {
6231 struct vop_mkdir_args *a;
6232 struct vnode *dvp;
6233
6234 a = ap;
6235 dvp = a->a_dvp;
6236 vn_seqc_write_end(dvp);
6237 if (!rc) {
6238 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6239 INOTIFY_NAME(*a->a_vpp, dvp, a->a_cnp, IN_CREATE);
6240 }
6241 }
6242
6243 #ifdef INVARIANTS
6244 void
vop_mkdir_debugpost(void * ap,int rc)6245 vop_mkdir_debugpost(void *ap, int rc)
6246 {
6247 struct vop_mkdir_args *a;
6248
6249 a = ap;
6250 if (!rc)
6251 cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
6252 }
6253 #endif
6254
6255 void
vop_mknod_pre(void * ap)6256 vop_mknod_pre(void *ap)
6257 {
6258 struct vop_mknod_args *a;
6259 struct vnode *dvp;
6260
6261 a = ap;
6262 dvp = a->a_dvp;
6263 vn_seqc_write_begin(dvp);
6264 }
6265
6266 void
vop_mknod_post(void * ap,int rc)6267 vop_mknod_post(void *ap, int rc)
6268 {
6269 struct vop_mknod_args *a;
6270 struct vnode *dvp;
6271
6272 a = ap;
6273 dvp = a->a_dvp;
6274 vn_seqc_write_end(dvp);
6275 if (rc == 0) {
6276 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6277 INOTIFY_NAME(*a->a_vpp, dvp, a->a_cnp, IN_CREATE);
6278 }
6279 }
6280
6281 void
vop_reclaim_post(void * ap,int rc)6282 vop_reclaim_post(void *ap, int rc)
6283 {
6284 struct vop_reclaim_args *a;
6285 struct vnode *vp;
6286
6287 a = ap;
6288 vp = a->a_vp;
6289 ASSERT_VOP_IN_SEQC(vp);
6290 if (!rc) {
6291 VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
6292 INOTIFY_REVOKE(vp);
6293 }
6294 }
6295
6296 void
vop_remove_pre(void * ap)6297 vop_remove_pre(void *ap)
6298 {
6299 struct vop_remove_args *a;
6300 struct vnode *dvp, *vp;
6301
6302 a = ap;
6303 dvp = a->a_dvp;
6304 vp = a->a_vp;
6305 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
6306 vn_seqc_write_begin(dvp);
6307 vn_seqc_write_begin(vp);
6308 }
6309
6310 void
vop_remove_post(void * ap,int rc)6311 vop_remove_post(void *ap, int rc)
6312 {
6313 struct vop_remove_args *a;
6314 struct vnode *dvp, *vp;
6315
6316 a = ap;
6317 dvp = a->a_dvp;
6318 vp = a->a_vp;
6319 vn_seqc_write_end(dvp);
6320 vn_seqc_write_end(vp);
6321 if (!rc) {
6322 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6323 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6324 INOTIFY_NAME(vp, dvp, a->a_cnp, _IN_ATTRIB_LINKCOUNT);
6325 INOTIFY_NAME(vp, dvp, a->a_cnp, IN_DELETE);
6326 }
6327 }
6328
6329 void
vop_rename_post(void * ap,int rc)6330 vop_rename_post(void *ap, int rc)
6331 {
6332 struct vop_rename_args *a = ap;
6333 long hint;
6334
6335 if (!rc) {
6336 hint = NOTE_WRITE;
6337 if (a->a_fdvp == a->a_tdvp) {
6338 if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
6339 hint |= NOTE_LINK;
6340 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
6341 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
6342 } else {
6343 hint |= NOTE_EXTEND;
6344 if (a->a_fvp->v_type == VDIR)
6345 hint |= NOTE_LINK;
6346 VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
6347
6348 if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
6349 a->a_tvp->v_type == VDIR)
6350 hint &= ~NOTE_LINK;
6351 VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
6352 }
6353
6354 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
6355 if (a->a_tvp)
6356 VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
6357 INOTIFY_MOVE(a->a_fvp, a->a_fdvp, a->a_fcnp, a->a_tvp,
6358 a->a_tdvp, a->a_tcnp);
6359 }
6360 if (a->a_tdvp != a->a_fdvp)
6361 vdrop(a->a_fdvp);
6362 if (a->a_tvp != a->a_fvp)
6363 vdrop(a->a_fvp);
6364 vdrop(a->a_tdvp);
6365 if (a->a_tvp)
6366 vdrop(a->a_tvp);
6367 }
6368
6369 void
vop_rmdir_pre(void * ap)6370 vop_rmdir_pre(void *ap)
6371 {
6372 struct vop_rmdir_args *a;
6373 struct vnode *dvp, *vp;
6374
6375 a = ap;
6376 dvp = a->a_dvp;
6377 vp = a->a_vp;
6378 vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
6379 vn_seqc_write_begin(dvp);
6380 vn_seqc_write_begin(vp);
6381 }
6382
6383 void
vop_rmdir_post(void * ap,int rc)6384 vop_rmdir_post(void *ap, int rc)
6385 {
6386 struct vop_rmdir_args *a;
6387 struct vnode *dvp, *vp;
6388
6389 a = ap;
6390 dvp = a->a_dvp;
6391 vp = a->a_vp;
6392 vn_seqc_write_end(dvp);
6393 vn_seqc_write_end(vp);
6394 if (!rc) {
6395 vp->v_vflag |= VV_UNLINKED;
6396 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6397 VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6398 INOTIFY_NAME(vp, dvp, a->a_cnp, IN_DELETE);
6399 }
6400 }
6401
6402 void
vop_setattr_pre(void * ap)6403 vop_setattr_pre(void *ap)
6404 {
6405 struct vop_setattr_args *a;
6406 struct vnode *vp;
6407
6408 a = ap;
6409 vp = a->a_vp;
6410 vn_seqc_write_begin(vp);
6411 }
6412
6413 void
vop_setattr_post(void * ap,int rc)6414 vop_setattr_post(void *ap, int rc)
6415 {
6416 struct vop_setattr_args *a;
6417 struct vnode *vp;
6418
6419 a = ap;
6420 vp = a->a_vp;
6421 vn_seqc_write_end(vp);
6422 if (!rc) {
6423 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6424 INOTIFY(vp, IN_ATTRIB);
6425 }
6426 }
6427
6428 void
vop_setacl_pre(void * ap)6429 vop_setacl_pre(void *ap)
6430 {
6431 struct vop_setacl_args *a;
6432 struct vnode *vp;
6433
6434 a = ap;
6435 vp = a->a_vp;
6436 vn_seqc_write_begin(vp);
6437 }
6438
6439 void
vop_setacl_post(void * ap,int rc __unused)6440 vop_setacl_post(void *ap, int rc __unused)
6441 {
6442 struct vop_setacl_args *a;
6443 struct vnode *vp;
6444
6445 a = ap;
6446 vp = a->a_vp;
6447 vn_seqc_write_end(vp);
6448 }
6449
6450 void
vop_setextattr_pre(void * ap)6451 vop_setextattr_pre(void *ap)
6452 {
6453 struct vop_setextattr_args *a;
6454 struct vnode *vp;
6455
6456 a = ap;
6457 vp = a->a_vp;
6458 vn_seqc_write_begin(vp);
6459 }
6460
6461 void
vop_setextattr_post(void * ap,int rc)6462 vop_setextattr_post(void *ap, int rc)
6463 {
6464 struct vop_setextattr_args *a;
6465 struct vnode *vp;
6466
6467 a = ap;
6468 vp = a->a_vp;
6469 vn_seqc_write_end(vp);
6470 if (!rc) {
6471 VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6472 INOTIFY(vp, IN_ATTRIB);
6473 }
6474 }
6475
6476 void
vop_symlink_pre(void * ap)6477 vop_symlink_pre(void *ap)
6478 {
6479 struct vop_symlink_args *a;
6480 struct vnode *dvp;
6481
6482 a = ap;
6483 dvp = a->a_dvp;
6484 vn_seqc_write_begin(dvp);
6485 }
6486
6487 void
vop_symlink_post(void * ap,int rc)6488 vop_symlink_post(void *ap, int rc)
6489 {
6490 struct vop_symlink_args *a;
6491 struct vnode *dvp;
6492
6493 a = ap;
6494 dvp = a->a_dvp;
6495 vn_seqc_write_end(dvp);
6496 if (!rc) {
6497 VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6498 INOTIFY_NAME(*a->a_vpp, dvp, a->a_cnp, IN_CREATE);
6499 }
6500 }
6501
6502 void
vop_open_post(void * ap,int rc)6503 vop_open_post(void *ap, int rc)
6504 {
6505 struct vop_open_args *a = ap;
6506
6507 if (!rc) {
6508 VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6509 INOTIFY(a->a_vp, IN_OPEN);
6510 }
6511 }
6512
6513 void
vop_close_post(void * ap,int rc)6514 vop_close_post(void *ap, int rc)
6515 {
6516 struct vop_close_args *a = ap;
6517
6518 if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6519 !VN_IS_DOOMED(a->a_vp))) {
6520 VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6521 NOTE_CLOSE_WRITE : NOTE_CLOSE);
6522 INOTIFY(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6523 IN_CLOSE_WRITE : IN_CLOSE_NOWRITE);
6524 }
6525 }
6526
6527 void
vop_read_post(void * ap,int rc)6528 vop_read_post(void *ap, int rc)
6529 {
6530 struct vop_read_args *a = ap;
6531
6532 if (!rc) {
6533 VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6534 INOTIFY(a->a_vp, IN_ACCESS);
6535 }
6536 }
6537
6538 void
vop_read_pgcache_post(void * ap,int rc)6539 vop_read_pgcache_post(void *ap, int rc)
6540 {
6541 struct vop_read_pgcache_args *a = ap;
6542
6543 if (rc == 0) {
6544 VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6545 INOTIFY(a->a_vp, IN_ACCESS);
6546 }
6547 }
6548
6549 static struct knlist fs_knlist;
6550
6551 static void
vfs_event_init(void * arg)6552 vfs_event_init(void *arg)
6553 {
6554 knlist_init_mtx(&fs_knlist, NULL);
6555 }
6556 /* XXX - correct order? */
6557 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6558
6559 void
vfs_event_signal(fsid_t * fsid,uint32_t event,intptr_t data __unused)6560 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6561 {
6562
6563 KNOTE_UNLOCKED(&fs_knlist, event);
6564 }
6565
6566 static int filt_fsattach(struct knote *kn);
6567 static void filt_fsdetach(struct knote *kn);
6568 static int filt_fsevent(struct knote *kn, long hint);
6569
6570 const struct filterops fs_filtops = {
6571 .f_isfd = 0,
6572 .f_attach = filt_fsattach,
6573 .f_detach = filt_fsdetach,
6574 .f_event = filt_fsevent,
6575 .f_copy = knote_triv_copy,
6576 };
6577
6578 static int
filt_fsattach(struct knote * kn)6579 filt_fsattach(struct knote *kn)
6580 {
6581
6582 kn->kn_flags |= EV_CLEAR;
6583 knlist_add(&fs_knlist, kn, 0);
6584 return (0);
6585 }
6586
6587 static void
filt_fsdetach(struct knote * kn)6588 filt_fsdetach(struct knote *kn)
6589 {
6590
6591 knlist_remove(&fs_knlist, kn, 0);
6592 }
6593
6594 static int
filt_fsevent(struct knote * kn,long hint)6595 filt_fsevent(struct knote *kn, long hint)
6596 {
6597
6598 kn->kn_fflags |= kn->kn_sfflags & hint;
6599
6600 return (kn->kn_fflags != 0);
6601 }
6602
6603 static int
sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)6604 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6605 {
6606 struct vfsidctl vc;
6607 int error;
6608 struct mount *mp;
6609
6610 if (req->newptr == NULL)
6611 return (EINVAL);
6612 error = SYSCTL_IN(req, &vc, sizeof(vc));
6613 if (error)
6614 return (error);
6615 if (vc.vc_vers != VFS_CTL_VERS1)
6616 return (EINVAL);
6617 mp = vfs_getvfs(&vc.vc_fsid);
6618 if (mp == NULL)
6619 return (ENOENT);
6620 /* ensure that a specific sysctl goes to the right filesystem. */
6621 if (strcmp(vc.vc_fstypename, "*") != 0 &&
6622 strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6623 vfs_rel(mp);
6624 return (EINVAL);
6625 }
6626 VCTLTOREQ(&vc, req);
6627 error = VFS_SYSCTL(mp, vc.vc_op, req);
6628 vfs_rel(mp);
6629 return (error);
6630 }
6631
6632 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6633 NULL, 0, sysctl_vfs_ctl, "",
6634 "Sysctl by fsid");
6635
6636 /*
6637 * Function to initialize a va_filerev field sensibly.
6638 * XXX: Wouldn't a random number make a lot more sense ??
6639 */
6640 u_quad_t
init_va_filerev(void)6641 init_va_filerev(void)
6642 {
6643 struct bintime bt;
6644
6645 getbinuptime(&bt);
6646 return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6647 }
6648
6649 static int filt_vfsread(struct knote *kn, long hint);
6650 static int filt_vfswrite(struct knote *kn, long hint);
6651 static int filt_vfsvnode(struct knote *kn, long hint);
6652 static void filt_vfsdetach(struct knote *kn);
6653 static int filt_vfsdump(struct proc *p, struct knote *kn,
6654 struct kinfo_knote *kin);
6655 static int filt_vfscopy(struct knote *kn, struct proc *p1);
6656
6657 static const struct filterops vfsread_filtops = {
6658 .f_isfd = 1,
6659 .f_detach = filt_vfsdetach,
6660 .f_event = filt_vfsread,
6661 .f_userdump = filt_vfsdump,
6662 .f_copy = filt_vfscopy,
6663 };
6664 static const struct filterops vfswrite_filtops = {
6665 .f_isfd = 1,
6666 .f_detach = filt_vfsdetach,
6667 .f_event = filt_vfswrite,
6668 .f_userdump = filt_vfsdump,
6669 .f_copy = filt_vfscopy,
6670 };
6671 static const struct filterops vfsvnode_filtops = {
6672 .f_isfd = 1,
6673 .f_detach = filt_vfsdetach,
6674 .f_event = filt_vfsvnode,
6675 .f_userdump = filt_vfsdump,
6676 .f_copy = filt_vfscopy,
6677 };
6678
6679 static void
vfs_knllock(void * arg)6680 vfs_knllock(void *arg)
6681 {
6682 struct vnode *vp = arg;
6683
6684 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6685 }
6686
6687 static void
vfs_knlunlock(void * arg)6688 vfs_knlunlock(void *arg)
6689 {
6690 struct vnode *vp = arg;
6691
6692 if (KNLIST_EMPTY(&vp->v_pollinfo->vpi_selinfo.si_note))
6693 vp->v_v2flag &= ~V2_KNOTE;
6694 VOP_UNLOCK(vp);
6695 }
6696
6697 static void
vfs_knl_assert_lock(void * arg,int what)6698 vfs_knl_assert_lock(void *arg, int what)
6699 {
6700 #ifdef INVARIANTS
6701 struct vnode *vp = arg;
6702
6703 if (what == LA_LOCKED)
6704 ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6705 else
6706 ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6707 #endif
6708 }
6709
6710 int
vfs_kqfilter(struct vop_kqfilter_args * ap)6711 vfs_kqfilter(struct vop_kqfilter_args *ap)
6712 {
6713 struct vnode *vp = ap->a_vp;
6714 struct knote *kn = ap->a_kn;
6715 struct knlist *knl;
6716
6717 KASSERT(vp->v_type != VFIFO || (kn->kn_filter != EVFILT_READ &&
6718 kn->kn_filter != EVFILT_WRITE),
6719 ("READ/WRITE filter on a FIFO leaked through"));
6720 switch (kn->kn_filter) {
6721 case EVFILT_READ:
6722 kn->kn_fop = &vfsread_filtops;
6723 break;
6724 case EVFILT_WRITE:
6725 kn->kn_fop = &vfswrite_filtops;
6726 break;
6727 case EVFILT_VNODE:
6728 kn->kn_fop = &vfsvnode_filtops;
6729 break;
6730 default:
6731 return (EINVAL);
6732 }
6733
6734 kn->kn_hook = (caddr_t)vp;
6735
6736 v_addpollinfo(vp);
6737 if (vp->v_pollinfo == NULL)
6738 return (ENOMEM);
6739 knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6740 vhold(vp);
6741 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6742 knlist_add(knl, kn, 1);
6743 vp->v_v2flag |= V2_KNOTE;
6744 VOP_UNLOCK(vp);
6745
6746 return (0);
6747 }
6748
6749 /*
6750 * Detach knote from vnode
6751 */
6752 static void
filt_vfsdetach(struct knote * kn)6753 filt_vfsdetach(struct knote *kn)
6754 {
6755 struct vnode *vp = (struct vnode *)kn->kn_hook;
6756
6757 KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6758 knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6759 vdrop(vp);
6760 }
6761
6762 /*ARGSUSED*/
6763 static int
filt_vfsread(struct knote * kn,long hint)6764 filt_vfsread(struct knote *kn, long hint)
6765 {
6766 struct vnode *vp = (struct vnode *)kn->kn_hook;
6767 off_t size;
6768 int res;
6769
6770 /*
6771 * filesystem is gone, so set the EOF flag and schedule
6772 * the knote for deletion.
6773 */
6774 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6775 VI_LOCK(vp);
6776 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6777 VI_UNLOCK(vp);
6778 return (1);
6779 }
6780
6781 if (vn_getsize_locked(vp, &size, curthread->td_ucred) != 0)
6782 return (0);
6783
6784 VI_LOCK(vp);
6785 kn->kn_data = size - kn->kn_fp->f_offset;
6786 res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6787 VI_UNLOCK(vp);
6788 return (res);
6789 }
6790
6791 /*ARGSUSED*/
6792 static int
filt_vfswrite(struct knote * kn,long hint)6793 filt_vfswrite(struct knote *kn, long hint)
6794 {
6795 struct vnode *vp = (struct vnode *)kn->kn_hook;
6796
6797 VI_LOCK(vp);
6798
6799 /*
6800 * filesystem is gone, so set the EOF flag and schedule
6801 * the knote for deletion.
6802 */
6803 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6804 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6805
6806 kn->kn_data = 0;
6807 VI_UNLOCK(vp);
6808 return (1);
6809 }
6810
6811 static int
filt_vfsvnode(struct knote * kn,long hint)6812 filt_vfsvnode(struct knote *kn, long hint)
6813 {
6814 struct vnode *vp = (struct vnode *)kn->kn_hook;
6815 int res;
6816
6817 VI_LOCK(vp);
6818 if (kn->kn_sfflags & hint)
6819 kn->kn_fflags |= hint;
6820 if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6821 kn->kn_flags |= EV_EOF;
6822 VI_UNLOCK(vp);
6823 return (1);
6824 }
6825 res = (kn->kn_fflags != 0);
6826 VI_UNLOCK(vp);
6827 return (res);
6828 }
6829
6830 static int
filt_vfsdump(struct proc * p,struct knote * kn,struct kinfo_knote * kin)6831 filt_vfsdump(struct proc *p, struct knote *kn, struct kinfo_knote *kin)
6832 {
6833 struct vattr va;
6834 struct vnode *vp;
6835 char *fullpath, *freepath;
6836 int error;
6837
6838 kin->knt_extdata = KNOTE_EXTDATA_VNODE;
6839
6840 vp = kn->kn_fp->f_vnode;
6841 kin->knt_vnode.knt_vnode_type = vntype_to_kinfo(vp->v_type);
6842
6843 va.va_fsid = VNOVAL;
6844 vn_lock(vp, LK_SHARED | LK_RETRY);
6845 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
6846 VOP_UNLOCK(vp);
6847 if (error != 0)
6848 return (error);
6849 kin->knt_vnode.knt_vnode_fsid = va.va_fsid;
6850 kin->knt_vnode.knt_vnode_fileid = va.va_fileid;
6851
6852 freepath = NULL;
6853 fullpath = "-";
6854 error = vn_fullpath(vp, &fullpath, &freepath);
6855 if (error == 0) {
6856 strlcpy(kin->knt_vnode.knt_vnode_fullpath, fullpath,
6857 sizeof(kin->knt_vnode.knt_vnode_fullpath));
6858 }
6859 if (freepath != NULL)
6860 free(freepath, M_TEMP);
6861
6862 return (0);
6863 }
6864
6865 static int
filt_vfscopy(struct knote * kn,struct proc * p1)6866 filt_vfscopy(struct knote *kn, struct proc *p1)
6867 {
6868 struct vnode *vp;
6869
6870 vp = (struct vnode *)kn->kn_hook;
6871 vhold(vp);
6872 return (0);
6873 }
6874
6875 int
vfs_read_dirent(struct vop_readdir_args * ap,struct dirent * dp,off_t off)6876 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6877 {
6878 int error;
6879
6880 if (dp->d_reclen > ap->a_uio->uio_resid)
6881 return (ENAMETOOLONG);
6882 error = uiomove(dp, dp->d_reclen, ap->a_uio);
6883 if (error) {
6884 if (ap->a_ncookies != NULL) {
6885 if (ap->a_cookies != NULL)
6886 free(ap->a_cookies, M_TEMP);
6887 ap->a_cookies = NULL;
6888 *ap->a_ncookies = 0;
6889 }
6890 return (error);
6891 }
6892 if (ap->a_ncookies == NULL)
6893 return (0);
6894
6895 KASSERT(ap->a_cookies,
6896 ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6897
6898 *ap->a_cookies = realloc(*ap->a_cookies,
6899 (*ap->a_ncookies + 1) * sizeof(uint64_t), M_TEMP, M_WAITOK | M_ZERO);
6900 (*ap->a_cookies)[*ap->a_ncookies] = off;
6901 *ap->a_ncookies += 1;
6902 return (0);
6903 }
6904
6905 /*
6906 * The purpose of this routine is to remove granularity from accmode_t,
6907 * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6908 * VADMIN and VAPPEND.
6909 *
6910 * If it returns 0, the caller is supposed to continue with the usual
6911 * access checks using 'accmode' as modified by this routine. If it
6912 * returns nonzero value, the caller is supposed to return that value
6913 * as errno.
6914 *
6915 * Note that after this routine runs, accmode may be zero.
6916 */
6917 int
vfs_unixify_accmode(accmode_t * accmode)6918 vfs_unixify_accmode(accmode_t *accmode)
6919 {
6920 /*
6921 * There is no way to specify explicit "deny" rule using
6922 * file mode or POSIX.1e ACLs.
6923 */
6924 if (*accmode & VEXPLICIT_DENY) {
6925 *accmode = 0;
6926 return (0);
6927 }
6928
6929 /*
6930 * None of these can be translated into usual access bits.
6931 * Also, the common case for NFSv4 ACLs is to not contain
6932 * either of these bits. Caller should check for VWRITE
6933 * on the containing directory instead.
6934 */
6935 if (*accmode & (VDELETE_CHILD | VDELETE))
6936 return (EPERM);
6937
6938 if (*accmode & VADMIN_PERMS) {
6939 *accmode &= ~VADMIN_PERMS;
6940 *accmode |= VADMIN;
6941 }
6942
6943 /*
6944 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6945 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6946 */
6947 *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6948
6949 return (0);
6950 }
6951
6952 /*
6953 * Clear out a doomed vnode (if any) and replace it with a new one as long
6954 * as the fs is not being unmounted. Return the root vnode to the caller.
6955 */
6956 static int __noinline
vfs_cache_root_fallback(struct mount * mp,int flags,struct vnode ** vpp)6957 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6958 {
6959 struct vnode *vp;
6960 int error;
6961
6962 restart:
6963 if (mp->mnt_rootvnode != NULL) {
6964 MNT_ILOCK(mp);
6965 vp = mp->mnt_rootvnode;
6966 if (vp != NULL) {
6967 if (!VN_IS_DOOMED(vp)) {
6968 vrefact(vp);
6969 MNT_IUNLOCK(mp);
6970 error = vn_lock(vp, flags);
6971 if (error == 0) {
6972 *vpp = vp;
6973 return (0);
6974 }
6975 vrele(vp);
6976 goto restart;
6977 }
6978 /*
6979 * Clear the old one.
6980 */
6981 mp->mnt_rootvnode = NULL;
6982 }
6983 MNT_IUNLOCK(mp);
6984 if (vp != NULL) {
6985 vfs_op_barrier_wait(mp);
6986 vrele(vp);
6987 }
6988 }
6989 error = VFS_CACHEDROOT(mp, flags, vpp);
6990 if (error != 0)
6991 return (error);
6992 if (mp->mnt_vfs_ops == 0) {
6993 MNT_ILOCK(mp);
6994 if (mp->mnt_vfs_ops != 0) {
6995 MNT_IUNLOCK(mp);
6996 return (0);
6997 }
6998 if (mp->mnt_rootvnode == NULL) {
6999 vrefact(*vpp);
7000 mp->mnt_rootvnode = *vpp;
7001 } else {
7002 if (mp->mnt_rootvnode != *vpp) {
7003 if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
7004 panic("%s: mismatch between vnode returned "
7005 " by VFS_CACHEDROOT and the one cached "
7006 " (%p != %p)",
7007 __func__, *vpp, mp->mnt_rootvnode);
7008 }
7009 }
7010 }
7011 MNT_IUNLOCK(mp);
7012 }
7013 return (0);
7014 }
7015
7016 int
vfs_cache_root(struct mount * mp,int flags,struct vnode ** vpp)7017 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
7018 {
7019 struct mount_pcpu *mpcpu;
7020 struct vnode *vp;
7021 int error;
7022
7023 if (!vfs_op_thread_enter(mp, &mpcpu))
7024 return (vfs_cache_root_fallback(mp, flags, vpp));
7025 vp = atomic_load_ptr(&mp->mnt_rootvnode);
7026 if (vp == NULL || VN_IS_DOOMED(vp)) {
7027 vfs_op_thread_exit(mp, mpcpu);
7028 return (vfs_cache_root_fallback(mp, flags, vpp));
7029 }
7030 vrefact(vp);
7031 vfs_op_thread_exit(mp, mpcpu);
7032 error = vn_lock(vp, flags);
7033 if (error != 0) {
7034 vrele(vp);
7035 return (vfs_cache_root_fallback(mp, flags, vpp));
7036 }
7037 *vpp = vp;
7038 return (0);
7039 }
7040
7041 struct vnode *
vfs_cache_root_clear(struct mount * mp)7042 vfs_cache_root_clear(struct mount *mp)
7043 {
7044 struct vnode *vp;
7045
7046 /*
7047 * ops > 0 guarantees there is nobody who can see this vnode
7048 */
7049 MPASS(mp->mnt_vfs_ops > 0);
7050 vp = mp->mnt_rootvnode;
7051 if (vp != NULL)
7052 vn_seqc_write_begin(vp);
7053 mp->mnt_rootvnode = NULL;
7054 return (vp);
7055 }
7056
7057 void
vfs_cache_root_set(struct mount * mp,struct vnode * vp)7058 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
7059 {
7060
7061 MPASS(mp->mnt_vfs_ops > 0);
7062 vrefact(vp);
7063 mp->mnt_rootvnode = vp;
7064 }
7065
7066 /*
7067 * These are helper functions for filesystems to traverse all
7068 * their vnodes. See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
7069 *
7070 * This interface replaces MNT_VNODE_FOREACH.
7071 */
7072
7073 struct vnode *
__mnt_vnode_next_all(struct vnode ** mvp,struct mount * mp)7074 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
7075 {
7076 struct vnode *vp;
7077
7078 maybe_yield();
7079 MNT_ILOCK(mp);
7080 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
7081 for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
7082 vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
7083 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
7084 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
7085 continue;
7086 VI_LOCK(vp);
7087 if (VN_IS_DOOMED(vp)) {
7088 VI_UNLOCK(vp);
7089 continue;
7090 }
7091 break;
7092 }
7093 if (vp == NULL) {
7094 __mnt_vnode_markerfree_all(mvp, mp);
7095 /* MNT_IUNLOCK(mp); -- done in above function */
7096 mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
7097 return (NULL);
7098 }
7099 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
7100 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
7101 MNT_IUNLOCK(mp);
7102 return (vp);
7103 }
7104
7105 struct vnode *
__mnt_vnode_first_all(struct vnode ** mvp,struct mount * mp)7106 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
7107 {
7108 struct vnode *vp;
7109
7110 *mvp = vn_alloc_marker(mp);
7111 MNT_ILOCK(mp);
7112 MNT_REF(mp);
7113
7114 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
7115 /* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
7116 if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
7117 continue;
7118 VI_LOCK(vp);
7119 if (VN_IS_DOOMED(vp)) {
7120 VI_UNLOCK(vp);
7121 continue;
7122 }
7123 break;
7124 }
7125 if (vp == NULL) {
7126 MNT_REL(mp);
7127 MNT_IUNLOCK(mp);
7128 vn_free_marker(*mvp);
7129 *mvp = NULL;
7130 return (NULL);
7131 }
7132 TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
7133 MNT_IUNLOCK(mp);
7134 return (vp);
7135 }
7136
7137 void
__mnt_vnode_markerfree_all(struct vnode ** mvp,struct mount * mp)7138 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
7139 {
7140
7141 if (*mvp == NULL) {
7142 MNT_IUNLOCK(mp);
7143 return;
7144 }
7145
7146 mtx_assert(MNT_MTX(mp), MA_OWNED);
7147
7148 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
7149 TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
7150 MNT_REL(mp);
7151 MNT_IUNLOCK(mp);
7152 vn_free_marker(*mvp);
7153 *mvp = NULL;
7154 }
7155
7156 /*
7157 * These are helper functions for filesystems to traverse their
7158 * lazy vnodes. See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
7159 */
7160 static void
mnt_vnode_markerfree_lazy(struct vnode ** mvp,struct mount * mp)7161 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
7162 {
7163
7164 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
7165
7166 MNT_ILOCK(mp);
7167 MNT_REL(mp);
7168 MNT_IUNLOCK(mp);
7169 vn_free_marker(*mvp);
7170 *mvp = NULL;
7171 }
7172
7173 /*
7174 * Relock the mp mount vnode list lock with the vp vnode interlock in the
7175 * conventional lock order during mnt_vnode_next_lazy iteration.
7176 *
7177 * On entry, the mount vnode list lock is held and the vnode interlock is not.
7178 * The list lock is dropped and reacquired. On success, both locks are held.
7179 * On failure, the mount vnode list lock is held but the vnode interlock is
7180 * not, and the procedure may have yielded.
7181 */
7182 static bool
mnt_vnode_next_lazy_relock(struct vnode * mvp,struct mount * mp,struct vnode * vp)7183 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
7184 struct vnode *vp)
7185 {
7186
7187 VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
7188 TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
7189 ("%s: bad marker", __func__));
7190 VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
7191 ("%s: inappropriate vnode", __func__));
7192 ASSERT_VI_UNLOCKED(vp, __func__);
7193 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
7194
7195 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
7196 TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
7197
7198 /*
7199 * Note we may be racing against vdrop which transitioned the hold
7200 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
7201 * if we are the only user after we get the interlock we will just
7202 * vdrop.
7203 */
7204 vhold(vp);
7205 mtx_unlock(&mp->mnt_listmtx);
7206 VI_LOCK(vp);
7207 if (VN_IS_DOOMED(vp)) {
7208 VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
7209 goto out_lost;
7210 }
7211 VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
7212 /*
7213 * There is nothing to do if we are the last user.
7214 */
7215 if (!refcount_release_if_not_last(&vp->v_holdcnt))
7216 goto out_lost;
7217 mtx_lock(&mp->mnt_listmtx);
7218 return (true);
7219 out_lost:
7220 vdropl(vp);
7221 maybe_yield();
7222 mtx_lock(&mp->mnt_listmtx);
7223 return (false);
7224 }
7225
7226 static struct vnode *
mnt_vnode_next_lazy(struct vnode ** mvp,struct mount * mp,mnt_lazy_cb_t * cb,void * cbarg)7227 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
7228 void *cbarg)
7229 {
7230 struct vnode *vp;
7231
7232 mtx_assert(&mp->mnt_listmtx, MA_OWNED);
7233 KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
7234 restart:
7235 vp = TAILQ_NEXT(*mvp, v_lazylist);
7236 while (vp != NULL) {
7237 if (vp->v_type == VMARKER) {
7238 vp = TAILQ_NEXT(vp, v_lazylist);
7239 continue;
7240 }
7241 /*
7242 * See if we want to process the vnode. Note we may encounter a
7243 * long string of vnodes we don't care about and hog the list
7244 * as a result. Check for it and requeue the marker.
7245 */
7246 VNPASS(!VN_IS_DOOMED(vp), vp);
7247 if (!cb(vp, cbarg)) {
7248 if (!should_yield()) {
7249 vp = TAILQ_NEXT(vp, v_lazylist);
7250 continue;
7251 }
7252 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
7253 v_lazylist);
7254 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
7255 v_lazylist);
7256 mtx_unlock(&mp->mnt_listmtx);
7257 kern_yield(PRI_USER);
7258 mtx_lock(&mp->mnt_listmtx);
7259 goto restart;
7260 }
7261 /*
7262 * Try-lock because this is the wrong lock order.
7263 */
7264 if (!VI_TRYLOCK(vp) &&
7265 !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
7266 goto restart;
7267 KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
7268 KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
7269 ("alien vnode on the lazy list %p %p", vp, mp));
7270 VNPASS(vp->v_mount == mp, vp);
7271 VNPASS(!VN_IS_DOOMED(vp), vp);
7272 break;
7273 }
7274 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
7275
7276 /* Check if we are done */
7277 if (vp == NULL) {
7278 mtx_unlock(&mp->mnt_listmtx);
7279 mnt_vnode_markerfree_lazy(mvp, mp);
7280 return (NULL);
7281 }
7282 TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
7283 mtx_unlock(&mp->mnt_listmtx);
7284 ASSERT_VI_LOCKED(vp, "lazy iter");
7285 return (vp);
7286 }
7287
7288 struct vnode *
__mnt_vnode_next_lazy(struct vnode ** mvp,struct mount * mp,mnt_lazy_cb_t * cb,void * cbarg)7289 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
7290 void *cbarg)
7291 {
7292
7293 maybe_yield();
7294 mtx_lock(&mp->mnt_listmtx);
7295 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
7296 }
7297
7298 struct vnode *
__mnt_vnode_first_lazy(struct vnode ** mvp,struct mount * mp,mnt_lazy_cb_t * cb,void * cbarg)7299 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
7300 void *cbarg)
7301 {
7302 struct vnode *vp;
7303
7304 if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
7305 return (NULL);
7306
7307 *mvp = vn_alloc_marker(mp);
7308 MNT_ILOCK(mp);
7309 MNT_REF(mp);
7310 MNT_IUNLOCK(mp);
7311
7312 mtx_lock(&mp->mnt_listmtx);
7313 vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
7314 if (vp == NULL) {
7315 mtx_unlock(&mp->mnt_listmtx);
7316 mnt_vnode_markerfree_lazy(mvp, mp);
7317 return (NULL);
7318 }
7319 TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
7320 return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
7321 }
7322
7323 void
__mnt_vnode_markerfree_lazy(struct vnode ** mvp,struct mount * mp)7324 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
7325 {
7326
7327 if (*mvp == NULL)
7328 return;
7329
7330 mtx_lock(&mp->mnt_listmtx);
7331 TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
7332 mtx_unlock(&mp->mnt_listmtx);
7333 mnt_vnode_markerfree_lazy(mvp, mp);
7334 }
7335
7336 int
vn_dir_check_exec(struct vnode * vp,struct componentname * cnp)7337 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
7338 {
7339
7340 if ((cnp->cn_flags & NOEXECCHECK) != 0) {
7341 cnp->cn_flags &= ~NOEXECCHECK;
7342 return (0);
7343 }
7344
7345 return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, curthread));
7346 }
7347
7348 /*
7349 * Do not use this variant unless you have means other than the hold count
7350 * to prevent the vnode from getting freed.
7351 */
7352 void
vn_seqc_write_begin_locked(struct vnode * vp)7353 vn_seqc_write_begin_locked(struct vnode *vp)
7354 {
7355
7356 ASSERT_VI_LOCKED(vp, __func__);
7357 VNPASS(vp->v_holdcnt > 0, vp);
7358 VNPASS(vp->v_seqc_users >= 0, vp);
7359 vp->v_seqc_users++;
7360 if (vp->v_seqc_users == 1)
7361 seqc_sleepable_write_begin(&vp->v_seqc);
7362 }
7363
7364 void
vn_seqc_write_begin(struct vnode * vp)7365 vn_seqc_write_begin(struct vnode *vp)
7366 {
7367
7368 VI_LOCK(vp);
7369 vn_seqc_write_begin_locked(vp);
7370 VI_UNLOCK(vp);
7371 }
7372
7373 void
vn_seqc_write_end_locked(struct vnode * vp)7374 vn_seqc_write_end_locked(struct vnode *vp)
7375 {
7376
7377 ASSERT_VI_LOCKED(vp, __func__);
7378 VNPASS(vp->v_seqc_users > 0, vp);
7379 vp->v_seqc_users--;
7380 if (vp->v_seqc_users == 0)
7381 seqc_sleepable_write_end(&vp->v_seqc);
7382 }
7383
7384 void
vn_seqc_write_end(struct vnode * vp)7385 vn_seqc_write_end(struct vnode *vp)
7386 {
7387
7388 VI_LOCK(vp);
7389 vn_seqc_write_end_locked(vp);
7390 VI_UNLOCK(vp);
7391 }
7392
7393 /*
7394 * Special case handling for allocating and freeing vnodes.
7395 *
7396 * The counter remains unchanged on free so that a doomed vnode will
7397 * keep testing as in modify as long as it is accessible with SMR.
7398 */
7399 static void
vn_seqc_init(struct vnode * vp)7400 vn_seqc_init(struct vnode *vp)
7401 {
7402
7403 vp->v_seqc = 0;
7404 vp->v_seqc_users = 0;
7405 }
7406
7407 static void
vn_seqc_write_end_free(struct vnode * vp)7408 vn_seqc_write_end_free(struct vnode *vp)
7409 {
7410
7411 VNPASS(seqc_in_modify(vp->v_seqc), vp);
7412 VNPASS(vp->v_seqc_users == 1, vp);
7413 }
7414
7415 void
vn_irflag_set_locked(struct vnode * vp,short toset)7416 vn_irflag_set_locked(struct vnode *vp, short toset)
7417 {
7418 short flags;
7419
7420 ASSERT_VI_LOCKED(vp, __func__);
7421 flags = vn_irflag_read(vp);
7422 VNASSERT((flags & toset) == 0, vp,
7423 ("%s: some of the passed flags already set (have %d, passed %d)\n",
7424 __func__, flags, toset));
7425 atomic_store_short(&vp->v_irflag, flags | toset);
7426 }
7427
7428 void
vn_irflag_set(struct vnode * vp,short toset)7429 vn_irflag_set(struct vnode *vp, short toset)
7430 {
7431
7432 VI_LOCK(vp);
7433 vn_irflag_set_locked(vp, toset);
7434 VI_UNLOCK(vp);
7435 }
7436
7437 void
vn_irflag_set_cond_locked(struct vnode * vp,short toset)7438 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7439 {
7440 short flags;
7441
7442 ASSERT_VI_LOCKED(vp, __func__);
7443 flags = vn_irflag_read(vp);
7444 atomic_store_short(&vp->v_irflag, flags | toset);
7445 }
7446
7447 void
vn_irflag_set_cond(struct vnode * vp,short toset)7448 vn_irflag_set_cond(struct vnode *vp, short toset)
7449 {
7450
7451 VI_LOCK(vp);
7452 vn_irflag_set_cond_locked(vp, toset);
7453 VI_UNLOCK(vp);
7454 }
7455
7456 void
vn_irflag_unset_locked(struct vnode * vp,short tounset)7457 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7458 {
7459 short flags;
7460
7461 ASSERT_VI_LOCKED(vp, __func__);
7462 flags = vn_irflag_read(vp);
7463 VNASSERT((flags & tounset) == tounset, vp,
7464 ("%s: some of the passed flags not set (have %d, passed %d)\n",
7465 __func__, flags, tounset));
7466 atomic_store_short(&vp->v_irflag, flags & ~tounset);
7467 }
7468
7469 void
vn_irflag_unset(struct vnode * vp,short tounset)7470 vn_irflag_unset(struct vnode *vp, short tounset)
7471 {
7472
7473 VI_LOCK(vp);
7474 vn_irflag_unset_locked(vp, tounset);
7475 VI_UNLOCK(vp);
7476 }
7477
7478 int
vn_getsize_locked(struct vnode * vp,off_t * size,struct ucred * cred)7479 vn_getsize_locked(struct vnode *vp, off_t *size, struct ucred *cred)
7480 {
7481 struct vattr vattr;
7482 int error;
7483
7484 ASSERT_VOP_LOCKED(vp, __func__);
7485 error = VOP_GETATTR(vp, &vattr, cred);
7486 if (__predict_true(error == 0)) {
7487 if (vattr.va_size <= OFF_MAX)
7488 *size = vattr.va_size;
7489 else
7490 error = EFBIG;
7491 }
7492 return (error);
7493 }
7494
7495 int
vn_getsize(struct vnode * vp,off_t * size,struct ucred * cred)7496 vn_getsize(struct vnode *vp, off_t *size, struct ucred *cred)
7497 {
7498 int error;
7499
7500 VOP_LOCK(vp, LK_SHARED);
7501 error = vn_getsize_locked(vp, size, cred);
7502 VOP_UNLOCK(vp);
7503 return (error);
7504 }
7505
7506 #ifdef INVARIANTS
7507 void
vn_set_state_validate(struct vnode * vp,__enum_uint8 (vstate)state)7508 vn_set_state_validate(struct vnode *vp, __enum_uint8(vstate) state)
7509 {
7510
7511 switch (vp->v_state) {
7512 case VSTATE_UNINITIALIZED:
7513 switch (state) {
7514 case VSTATE_CONSTRUCTED:
7515 case VSTATE_DESTROYING:
7516 return;
7517 default:
7518 break;
7519 }
7520 break;
7521 case VSTATE_CONSTRUCTED:
7522 ASSERT_VOP_ELOCKED(vp, __func__);
7523 switch (state) {
7524 case VSTATE_DESTROYING:
7525 return;
7526 default:
7527 break;
7528 }
7529 break;
7530 case VSTATE_DESTROYING:
7531 ASSERT_VOP_ELOCKED(vp, __func__);
7532 switch (state) {
7533 case VSTATE_DEAD:
7534 return;
7535 default:
7536 break;
7537 }
7538 break;
7539 case VSTATE_DEAD:
7540 switch (state) {
7541 case VSTATE_UNINITIALIZED:
7542 return;
7543 default:
7544 break;
7545 }
7546 break;
7547 }
7548
7549 vn_printf(vp, "invalid state transition %d -> %d\n", vp->v_state, state);
7550 panic("invalid state transition %d -> %d\n", vp->v_state, state);
7551 }
7552 #endif
7553