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