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