xref: /linux-6.15/fs/btrfs/locking.c (revision 9580503b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2008 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/sched.h>
7 #include <linux/pagemap.h>
8 #include <linux/spinlock.h>
9 #include <linux/page-flags.h>
10 #include <asm/bug.h>
11 #include <trace/events/btrfs.h>
12 #include "misc.h"
13 #include "ctree.h"
14 #include "extent_io.h"
15 #include "locking.h"
16 #include "accessors.h"
17 
18 /*
19  * Lockdep class keys for extent_buffer->lock's in this root.  For a given
20  * eb, the lockdep key is determined by the btrfs_root it belongs to and
21  * the level the eb occupies in the tree.
22  *
23  * Different roots are used for different purposes and may nest inside each
24  * other and they require separate keysets.  As lockdep keys should be
25  * static, assign keysets according to the purpose of the root as indicated
26  * by btrfs_root->root_key.objectid.  This ensures that all special purpose
27  * roots have separate keysets.
28  *
29  * Lock-nesting across peer nodes is always done with the immediate parent
30  * node locked thus preventing deadlock.  As lockdep doesn't know this, use
31  * subclass to avoid triggering lockdep warning in such cases.
32  *
33  * The key is set by the readpage_end_io_hook after the buffer has passed
34  * csum validation but before the pages are unlocked.  It is also set by
35  * btrfs_init_new_buffer on freshly allocated blocks.
36  *
37  * We also add a check to make sure the highest level of the tree is the
38  * same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this code
39  * needs update as well.
40  */
41 #ifdef CONFIG_DEBUG_LOCK_ALLOC
42 #if BTRFS_MAX_LEVEL != 8
43 #error
44 #endif
45 
46 #define DEFINE_LEVEL(stem, level)					\
47 	.names[level] = "btrfs-" stem "-0" #level,
48 
49 #define DEFINE_NAME(stem)						\
50 	DEFINE_LEVEL(stem, 0)						\
51 	DEFINE_LEVEL(stem, 1)						\
52 	DEFINE_LEVEL(stem, 2)						\
53 	DEFINE_LEVEL(stem, 3)						\
54 	DEFINE_LEVEL(stem, 4)						\
55 	DEFINE_LEVEL(stem, 5)						\
56 	DEFINE_LEVEL(stem, 6)						\
57 	DEFINE_LEVEL(stem, 7)
58 
59 static struct btrfs_lockdep_keyset {
60 	u64			id;		/* root objectid */
61 	/* Longest entry: btrfs-block-group-00 */
62 	char			names[BTRFS_MAX_LEVEL][24];
63 	struct lock_class_key	keys[BTRFS_MAX_LEVEL];
64 } btrfs_lockdep_keysets[] = {
65 	{ .id = BTRFS_ROOT_TREE_OBJECTID,	DEFINE_NAME("root")	},
66 	{ .id = BTRFS_EXTENT_TREE_OBJECTID,	DEFINE_NAME("extent")	},
67 	{ .id = BTRFS_CHUNK_TREE_OBJECTID,	DEFINE_NAME("chunk")	},
68 	{ .id = BTRFS_DEV_TREE_OBJECTID,	DEFINE_NAME("dev")	},
69 	{ .id = BTRFS_CSUM_TREE_OBJECTID,	DEFINE_NAME("csum")	},
70 	{ .id = BTRFS_QUOTA_TREE_OBJECTID,	DEFINE_NAME("quota")	},
71 	{ .id = BTRFS_TREE_LOG_OBJECTID,	DEFINE_NAME("log")	},
72 	{ .id = BTRFS_TREE_RELOC_OBJECTID,	DEFINE_NAME("treloc")	},
73 	{ .id = BTRFS_DATA_RELOC_TREE_OBJECTID,	DEFINE_NAME("dreloc")	},
74 	{ .id = BTRFS_UUID_TREE_OBJECTID,	DEFINE_NAME("uuid")	},
75 	{ .id = BTRFS_FREE_SPACE_TREE_OBJECTID,	DEFINE_NAME("free-space") },
76 	{ .id = BTRFS_BLOCK_GROUP_TREE_OBJECTID, DEFINE_NAME("block-group") },
77 	{ .id = 0,				DEFINE_NAME("tree")	},
78 };
79 
80 #undef DEFINE_LEVEL
81 #undef DEFINE_NAME
82 
83 void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb, int level)
84 {
85 	struct btrfs_lockdep_keyset *ks;
86 
87 	BUG_ON(level >= ARRAY_SIZE(ks->keys));
88 
89 	/* Find the matching keyset, id 0 is the default entry */
90 	for (ks = btrfs_lockdep_keysets; ks->id; ks++)
91 		if (ks->id == objectid)
92 			break;
93 
94 	lockdep_set_class_and_name(&eb->lock, &ks->keys[level], ks->names[level]);
95 }
96 
97 void btrfs_maybe_reset_lockdep_class(struct btrfs_root *root, struct extent_buffer *eb)
98 {
99 	if (test_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &root->state))
100 		btrfs_set_buffer_lockdep_class(root->root_key.objectid,
101 					       eb, btrfs_header_level(eb));
102 }
103 
104 #endif
105 
106 /*
107  * Extent buffer locking
108  * =====================
109  *
110  * We use a rw_semaphore for tree locking, and the semantics are exactly the
111  * same:
112  *
113  * - reader/writer exclusion
114  * - writer/writer exclusion
115  * - reader/reader sharing
116  * - try-lock semantics for readers and writers
117  *
118  * The rwsem implementation does opportunistic spinning which reduces number of
119  * times the locking task needs to sleep.
120  */
121 
122 /*
123  * __btrfs_tree_read_lock - lock extent buffer for read
124  * @eb:		the eb to be locked
125  * @nest:	the nesting level to be used for lockdep
126  *
127  * This takes the read lock on the extent buffer, using the specified nesting
128  * level for lockdep purposes.
129  */
130 void __btrfs_tree_read_lock(struct extent_buffer *eb, enum btrfs_lock_nesting nest)
131 {
132 	u64 start_ns = 0;
133 
134 	if (trace_btrfs_tree_read_lock_enabled())
135 		start_ns = ktime_get_ns();
136 
137 	down_read_nested(&eb->lock, nest);
138 	trace_btrfs_tree_read_lock(eb, start_ns);
139 }
140 
141 void btrfs_tree_read_lock(struct extent_buffer *eb)
142 {
143 	__btrfs_tree_read_lock(eb, BTRFS_NESTING_NORMAL);
144 }
145 
146 /*
147  * Try-lock for read.
148  *
149  * Return 1 if the rwlock has been taken, 0 otherwise
150  */
151 int btrfs_try_tree_read_lock(struct extent_buffer *eb)
152 {
153 	if (down_read_trylock(&eb->lock)) {
154 		trace_btrfs_try_tree_read_lock(eb);
155 		return 1;
156 	}
157 	return 0;
158 }
159 
160 /*
161  * Try-lock for write.
162  *
163  * Return 1 if the rwlock has been taken, 0 otherwise
164  */
165 int btrfs_try_tree_write_lock(struct extent_buffer *eb)
166 {
167 	if (down_write_trylock(&eb->lock)) {
168 		eb->lock_owner = current->pid;
169 		trace_btrfs_try_tree_write_lock(eb);
170 		return 1;
171 	}
172 	return 0;
173 }
174 
175 /*
176  * Release read lock.
177  */
178 void btrfs_tree_read_unlock(struct extent_buffer *eb)
179 {
180 	trace_btrfs_tree_read_unlock(eb);
181 	up_read(&eb->lock);
182 }
183 
184 /*
185  * Lock eb for write.
186  *
187  * @eb:		the eb to lock
188  * @nest:	the nesting to use for the lock
189  *
190  * Returns with the eb->lock write locked.
191  */
192 void __btrfs_tree_lock(struct extent_buffer *eb, enum btrfs_lock_nesting nest)
193 	__acquires(&eb->lock)
194 {
195 	u64 start_ns = 0;
196 
197 	if (trace_btrfs_tree_lock_enabled())
198 		start_ns = ktime_get_ns();
199 
200 	down_write_nested(&eb->lock, nest);
201 	eb->lock_owner = current->pid;
202 	trace_btrfs_tree_lock(eb, start_ns);
203 }
204 
205 void btrfs_tree_lock(struct extent_buffer *eb)
206 {
207 	__btrfs_tree_lock(eb, BTRFS_NESTING_NORMAL);
208 }
209 
210 /*
211  * Release the write lock.
212  */
213 void btrfs_tree_unlock(struct extent_buffer *eb)
214 {
215 	trace_btrfs_tree_unlock(eb);
216 	eb->lock_owner = 0;
217 	up_write(&eb->lock);
218 }
219 
220 /*
221  * This releases any locks held in the path starting at level and going all the
222  * way up to the root.
223  *
224  * btrfs_search_slot will keep the lock held on higher nodes in a few corner
225  * cases, such as COW of the block at slot zero in the node.  This ignores
226  * those rules, and it should only be called when there are no more updates to
227  * be done higher up in the tree.
228  */
229 void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
230 {
231 	int i;
232 
233 	if (path->keep_locks)
234 		return;
235 
236 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
237 		if (!path->nodes[i])
238 			continue;
239 		if (!path->locks[i])
240 			continue;
241 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
242 		path->locks[i] = 0;
243 	}
244 }
245 
246 /*
247  * Loop around taking references on and locking the root node of the tree until
248  * we end up with a lock on the root node.
249  *
250  * Return: root extent buffer with write lock held
251  */
252 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
253 {
254 	struct extent_buffer *eb;
255 
256 	while (1) {
257 		eb = btrfs_root_node(root);
258 
259 		btrfs_maybe_reset_lockdep_class(root, eb);
260 		btrfs_tree_lock(eb);
261 		if (eb == root->node)
262 			break;
263 		btrfs_tree_unlock(eb);
264 		free_extent_buffer(eb);
265 	}
266 	return eb;
267 }
268 
269 /*
270  * Loop around taking references on and locking the root node of the tree until
271  * we end up with a lock on the root node.
272  *
273  * Return: root extent buffer with read lock held
274  */
275 struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
276 {
277 	struct extent_buffer *eb;
278 
279 	while (1) {
280 		eb = btrfs_root_node(root);
281 
282 		btrfs_maybe_reset_lockdep_class(root, eb);
283 		btrfs_tree_read_lock(eb);
284 		if (eb == root->node)
285 			break;
286 		btrfs_tree_read_unlock(eb);
287 		free_extent_buffer(eb);
288 	}
289 	return eb;
290 }
291 
292 /*
293  * Loop around taking references on and locking the root node of the tree in
294  * nowait mode until we end up with a lock on the root node or returning to
295  * avoid blocking.
296  *
297  * Return: root extent buffer with read lock held or -EAGAIN.
298  */
299 struct extent_buffer *btrfs_try_read_lock_root_node(struct btrfs_root *root)
300 {
301 	struct extent_buffer *eb;
302 
303 	while (1) {
304 		eb = btrfs_root_node(root);
305 		if (!btrfs_try_tree_read_lock(eb)) {
306 			free_extent_buffer(eb);
307 			return ERR_PTR(-EAGAIN);
308 		}
309 		if (eb == root->node)
310 			break;
311 		btrfs_tree_read_unlock(eb);
312 		free_extent_buffer(eb);
313 	}
314 	return eb;
315 }
316 
317 /*
318  * DREW locks
319  * ==========
320  *
321  * DREW stands for double-reader-writer-exclusion lock. It's used in situation
322  * where you want to provide A-B exclusion but not AA or BB.
323  *
324  * Currently implementation gives more priority to reader. If a reader and a
325  * writer both race to acquire their respective sides of the lock the writer
326  * would yield its lock as soon as it detects a concurrent reader. Additionally
327  * if there are pending readers no new writers would be allowed to come in and
328  * acquire the lock.
329  */
330 
331 void btrfs_drew_lock_init(struct btrfs_drew_lock *lock)
332 {
333 	atomic_set(&lock->readers, 0);
334 	atomic_set(&lock->writers, 0);
335 	init_waitqueue_head(&lock->pending_readers);
336 	init_waitqueue_head(&lock->pending_writers);
337 }
338 
339 /* Return true if acquisition is successful, false otherwise */
340 bool btrfs_drew_try_write_lock(struct btrfs_drew_lock *lock)
341 {
342 	if (atomic_read(&lock->readers))
343 		return false;
344 
345 	atomic_inc(&lock->writers);
346 
347 	/* Ensure writers count is updated before we check for pending readers */
348 	smp_mb__after_atomic();
349 	if (atomic_read(&lock->readers)) {
350 		btrfs_drew_write_unlock(lock);
351 		return false;
352 	}
353 
354 	return true;
355 }
356 
357 void btrfs_drew_write_lock(struct btrfs_drew_lock *lock)
358 {
359 	while (true) {
360 		if (btrfs_drew_try_write_lock(lock))
361 			return;
362 		wait_event(lock->pending_writers, !atomic_read(&lock->readers));
363 	}
364 }
365 
366 void btrfs_drew_write_unlock(struct btrfs_drew_lock *lock)
367 {
368 	atomic_dec(&lock->writers);
369 	cond_wake_up(&lock->pending_readers);
370 }
371 
372 void btrfs_drew_read_lock(struct btrfs_drew_lock *lock)
373 {
374 	atomic_inc(&lock->readers);
375 
376 	/*
377 	 * Ensure the pending reader count is perceieved BEFORE this reader
378 	 * goes to sleep in case of active writers. This guarantees new writers
379 	 * won't be allowed and that the current reader will be woken up when
380 	 * the last active writer finishes its jobs.
381 	 */
382 	smp_mb__after_atomic();
383 
384 	wait_event(lock->pending_readers, atomic_read(&lock->writers) == 0);
385 }
386 
387 void btrfs_drew_read_unlock(struct btrfs_drew_lock *lock)
388 {
389 	/*
390 	 * atomic_dec_and_test implies a full barrier, so woken up writers
391 	 * are guaranteed to see the decrement
392 	 */
393 	if (atomic_dec_and_test(&lock->readers))
394 		wake_up(&lock->pending_writers);
395 }
396