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