xref: /linux/fs/bcachefs/btree_iter.c (revision daa121128a2d2ac6006159e2c47676e4fcd21eab)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "bkey_methods.h"
5 #include "bkey_buf.h"
6 #include "btree_cache.h"
7 #include "btree_iter.h"
8 #include "btree_journal_iter.h"
9 #include "btree_key_cache.h"
10 #include "btree_locking.h"
11 #include "btree_update.h"
12 #include "debug.h"
13 #include "error.h"
14 #include "extents.h"
15 #include "journal.h"
16 #include "journal_io.h"
17 #include "replicas.h"
18 #include "snapshot.h"
19 #include "trace.h"
20 
21 #include <linux/random.h>
22 #include <linux/prefetch.h>
23 
24 static inline void btree_path_list_remove(struct btree_trans *, struct btree_path *);
25 static inline void btree_path_list_add(struct btree_trans *,
26 			btree_path_idx_t, btree_path_idx_t);
27 
28 static inline unsigned long btree_iter_ip_allocated(struct btree_iter *iter)
29 {
30 #ifdef TRACK_PATH_ALLOCATED
31 	return iter->ip_allocated;
32 #else
33 	return 0;
34 #endif
35 }
36 
37 static btree_path_idx_t btree_path_alloc(struct btree_trans *, btree_path_idx_t);
38 static void bch2_trans_srcu_lock(struct btree_trans *);
39 
40 static inline int __btree_path_cmp(const struct btree_path *l,
41 				   enum btree_id	r_btree_id,
42 				   bool			r_cached,
43 				   struct bpos		r_pos,
44 				   unsigned		r_level)
45 {
46 	/*
47 	 * Must match lock ordering as defined by __bch2_btree_node_lock:
48 	 */
49 	return   cmp_int(l->btree_id,	r_btree_id) ?:
50 		 cmp_int((int) l->cached,	(int) r_cached) ?:
51 		 bpos_cmp(l->pos,	r_pos) ?:
52 		-cmp_int(l->level,	r_level);
53 }
54 
55 static inline int btree_path_cmp(const struct btree_path *l,
56 				 const struct btree_path *r)
57 {
58 	return __btree_path_cmp(l, r->btree_id, r->cached, r->pos, r->level);
59 }
60 
61 static inline struct bpos bkey_successor(struct btree_iter *iter, struct bpos p)
62 {
63 	/* Are we iterating over keys in all snapshots? */
64 	if (iter->flags & BTREE_ITER_all_snapshots) {
65 		p = bpos_successor(p);
66 	} else {
67 		p = bpos_nosnap_successor(p);
68 		p.snapshot = iter->snapshot;
69 	}
70 
71 	return p;
72 }
73 
74 static inline struct bpos bkey_predecessor(struct btree_iter *iter, struct bpos p)
75 {
76 	/* Are we iterating over keys in all snapshots? */
77 	if (iter->flags & BTREE_ITER_all_snapshots) {
78 		p = bpos_predecessor(p);
79 	} else {
80 		p = bpos_nosnap_predecessor(p);
81 		p.snapshot = iter->snapshot;
82 	}
83 
84 	return p;
85 }
86 
87 static inline struct bpos btree_iter_search_key(struct btree_iter *iter)
88 {
89 	struct bpos pos = iter->pos;
90 
91 	if ((iter->flags & BTREE_ITER_is_extents) &&
92 	    !bkey_eq(pos, POS_MAX))
93 		pos = bkey_successor(iter, pos);
94 	return pos;
95 }
96 
97 static inline bool btree_path_pos_before_node(struct btree_path *path,
98 					      struct btree *b)
99 {
100 	return bpos_lt(path->pos, b->data->min_key);
101 }
102 
103 static inline bool btree_path_pos_after_node(struct btree_path *path,
104 					     struct btree *b)
105 {
106 	return bpos_gt(path->pos, b->key.k.p);
107 }
108 
109 static inline bool btree_path_pos_in_node(struct btree_path *path,
110 					  struct btree *b)
111 {
112 	return path->btree_id == b->c.btree_id &&
113 		!btree_path_pos_before_node(path, b) &&
114 		!btree_path_pos_after_node(path, b);
115 }
116 
117 /* Btree iterator: */
118 
119 #ifdef CONFIG_BCACHEFS_DEBUG
120 
121 static void bch2_btree_path_verify_cached(struct btree_trans *trans,
122 					  struct btree_path *path)
123 {
124 	struct bkey_cached *ck;
125 	bool locked = btree_node_locked(path, 0);
126 
127 	if (!bch2_btree_node_relock(trans, path, 0))
128 		return;
129 
130 	ck = (void *) path->l[0].b;
131 	BUG_ON(ck->key.btree_id != path->btree_id ||
132 	       !bkey_eq(ck->key.pos, path->pos));
133 
134 	if (!locked)
135 		btree_node_unlock(trans, path, 0);
136 }
137 
138 static void bch2_btree_path_verify_level(struct btree_trans *trans,
139 				struct btree_path *path, unsigned level)
140 {
141 	struct btree_path_level *l;
142 	struct btree_node_iter tmp;
143 	bool locked;
144 	struct bkey_packed *p, *k;
145 	struct printbuf buf1 = PRINTBUF;
146 	struct printbuf buf2 = PRINTBUF;
147 	struct printbuf buf3 = PRINTBUF;
148 	const char *msg;
149 
150 	if (!bch2_debug_check_iterators)
151 		return;
152 
153 	l	= &path->l[level];
154 	tmp	= l->iter;
155 	locked	= btree_node_locked(path, level);
156 
157 	if (path->cached) {
158 		if (!level)
159 			bch2_btree_path_verify_cached(trans, path);
160 		return;
161 	}
162 
163 	if (!btree_path_node(path, level))
164 		return;
165 
166 	if (!bch2_btree_node_relock_notrace(trans, path, level))
167 		return;
168 
169 	BUG_ON(!btree_path_pos_in_node(path, l->b));
170 
171 	bch2_btree_node_iter_verify(&l->iter, l->b);
172 
173 	/*
174 	 * For interior nodes, the iterator will have skipped past deleted keys:
175 	 */
176 	p = level
177 		? bch2_btree_node_iter_prev(&tmp, l->b)
178 		: bch2_btree_node_iter_prev_all(&tmp, l->b);
179 	k = bch2_btree_node_iter_peek_all(&l->iter, l->b);
180 
181 	if (p && bkey_iter_pos_cmp(l->b, p, &path->pos) >= 0) {
182 		msg = "before";
183 		goto err;
184 	}
185 
186 	if (k && bkey_iter_pos_cmp(l->b, k, &path->pos) < 0) {
187 		msg = "after";
188 		goto err;
189 	}
190 
191 	if (!locked)
192 		btree_node_unlock(trans, path, level);
193 	return;
194 err:
195 	bch2_bpos_to_text(&buf1, path->pos);
196 
197 	if (p) {
198 		struct bkey uk = bkey_unpack_key(l->b, p);
199 
200 		bch2_bkey_to_text(&buf2, &uk);
201 	} else {
202 		prt_printf(&buf2, "(none)");
203 	}
204 
205 	if (k) {
206 		struct bkey uk = bkey_unpack_key(l->b, k);
207 
208 		bch2_bkey_to_text(&buf3, &uk);
209 	} else {
210 		prt_printf(&buf3, "(none)");
211 	}
212 
213 	panic("path should be %s key at level %u:\n"
214 	      "path pos %s\n"
215 	      "prev key %s\n"
216 	      "cur  key %s\n",
217 	      msg, level, buf1.buf, buf2.buf, buf3.buf);
218 }
219 
220 static void bch2_btree_path_verify(struct btree_trans *trans,
221 				   struct btree_path *path)
222 {
223 	struct bch_fs *c = trans->c;
224 	unsigned i;
225 
226 	EBUG_ON(path->btree_id >= BTREE_ID_NR);
227 
228 	for (i = 0; i < (!path->cached ? BTREE_MAX_DEPTH : 1); i++) {
229 		if (!path->l[i].b) {
230 			BUG_ON(!path->cached &&
231 			       bch2_btree_id_root(c, path->btree_id)->b->c.level > i);
232 			break;
233 		}
234 
235 		bch2_btree_path_verify_level(trans, path, i);
236 	}
237 
238 	bch2_btree_path_verify_locks(path);
239 }
240 
241 void bch2_trans_verify_paths(struct btree_trans *trans)
242 {
243 	struct btree_path *path;
244 	unsigned iter;
245 
246 	trans_for_each_path(trans, path, iter)
247 		bch2_btree_path_verify(trans, path);
248 }
249 
250 static void bch2_btree_iter_verify(struct btree_iter *iter)
251 {
252 	struct btree_trans *trans = iter->trans;
253 
254 	BUG_ON(iter->btree_id >= BTREE_ID_NR);
255 
256 	BUG_ON(!!(iter->flags & BTREE_ITER_cached) != btree_iter_path(trans, iter)->cached);
257 
258 	BUG_ON((iter->flags & BTREE_ITER_is_extents) &&
259 	       (iter->flags & BTREE_ITER_all_snapshots));
260 
261 	BUG_ON(!(iter->flags & BTREE_ITER_snapshot_field) &&
262 	       (iter->flags & BTREE_ITER_all_snapshots) &&
263 	       !btree_type_has_snapshot_field(iter->btree_id));
264 
265 	if (iter->update_path)
266 		bch2_btree_path_verify(trans, &trans->paths[iter->update_path]);
267 	bch2_btree_path_verify(trans, btree_iter_path(trans, iter));
268 }
269 
270 static void bch2_btree_iter_verify_entry_exit(struct btree_iter *iter)
271 {
272 	BUG_ON((iter->flags & BTREE_ITER_filter_snapshots) &&
273 	       !iter->pos.snapshot);
274 
275 	BUG_ON(!(iter->flags & BTREE_ITER_all_snapshots) &&
276 	       iter->pos.snapshot != iter->snapshot);
277 
278 	BUG_ON(bkey_lt(iter->pos, bkey_start_pos(&iter->k)) ||
279 	       bkey_gt(iter->pos, iter->k.p));
280 }
281 
282 static int bch2_btree_iter_verify_ret(struct btree_iter *iter, struct bkey_s_c k)
283 {
284 	struct btree_trans *trans = iter->trans;
285 	struct btree_iter copy;
286 	struct bkey_s_c prev;
287 	int ret = 0;
288 
289 	if (!bch2_debug_check_iterators)
290 		return 0;
291 
292 	if (!(iter->flags & BTREE_ITER_filter_snapshots))
293 		return 0;
294 
295 	if (bkey_err(k) || !k.k)
296 		return 0;
297 
298 	BUG_ON(!bch2_snapshot_is_ancestor(trans->c,
299 					  iter->snapshot,
300 					  k.k->p.snapshot));
301 
302 	bch2_trans_iter_init(trans, &copy, iter->btree_id, iter->pos,
303 			     BTREE_ITER_nopreserve|
304 			     BTREE_ITER_all_snapshots);
305 	prev = bch2_btree_iter_prev(&copy);
306 	if (!prev.k)
307 		goto out;
308 
309 	ret = bkey_err(prev);
310 	if (ret)
311 		goto out;
312 
313 	if (bkey_eq(prev.k->p, k.k->p) &&
314 	    bch2_snapshot_is_ancestor(trans->c, iter->snapshot,
315 				      prev.k->p.snapshot) > 0) {
316 		struct printbuf buf1 = PRINTBUF, buf2 = PRINTBUF;
317 
318 		bch2_bkey_to_text(&buf1, k.k);
319 		bch2_bkey_to_text(&buf2, prev.k);
320 
321 		panic("iter snap %u\n"
322 		      "k    %s\n"
323 		      "prev %s\n",
324 		      iter->snapshot,
325 		      buf1.buf, buf2.buf);
326 	}
327 out:
328 	bch2_trans_iter_exit(trans, &copy);
329 	return ret;
330 }
331 
332 void bch2_assert_pos_locked(struct btree_trans *trans, enum btree_id id,
333 			    struct bpos pos, bool key_cache)
334 {
335 	struct btree_path *path;
336 	struct trans_for_each_path_inorder_iter iter;
337 	struct printbuf buf = PRINTBUF;
338 
339 	btree_trans_sort_paths(trans);
340 
341 	trans_for_each_path_inorder(trans, path, iter) {
342 		int cmp = cmp_int(path->btree_id, id) ?:
343 			cmp_int(path->cached, key_cache);
344 
345 		if (cmp > 0)
346 			break;
347 		if (cmp < 0)
348 			continue;
349 
350 		if (!btree_node_locked(path, 0) ||
351 		    !path->should_be_locked)
352 			continue;
353 
354 		if (!key_cache) {
355 			if (bkey_ge(pos, path->l[0].b->data->min_key) &&
356 			    bkey_le(pos, path->l[0].b->key.k.p))
357 				return;
358 		} else {
359 			if (bkey_eq(pos, path->pos))
360 				return;
361 		}
362 	}
363 
364 	bch2_dump_trans_paths_updates(trans);
365 	bch2_bpos_to_text(&buf, pos);
366 
367 	panic("not locked: %s %s%s\n",
368 	      bch2_btree_id_str(id), buf.buf,
369 	      key_cache ? " cached" : "");
370 }
371 
372 #else
373 
374 static inline void bch2_btree_path_verify_level(struct btree_trans *trans,
375 						struct btree_path *path, unsigned l) {}
376 static inline void bch2_btree_path_verify(struct btree_trans *trans,
377 					  struct btree_path *path) {}
378 static inline void bch2_btree_iter_verify(struct btree_iter *iter) {}
379 static inline void bch2_btree_iter_verify_entry_exit(struct btree_iter *iter) {}
380 static inline int bch2_btree_iter_verify_ret(struct btree_iter *iter, struct bkey_s_c k) { return 0; }
381 
382 #endif
383 
384 /* Btree path: fixups after btree updates */
385 
386 static void btree_node_iter_set_set_pos(struct btree_node_iter *iter,
387 					struct btree *b,
388 					struct bset_tree *t,
389 					struct bkey_packed *k)
390 {
391 	struct btree_node_iter_set *set;
392 
393 	btree_node_iter_for_each(iter, set)
394 		if (set->end == t->end_offset) {
395 			set->k = __btree_node_key_to_offset(b, k);
396 			bch2_btree_node_iter_sort(iter, b);
397 			return;
398 		}
399 
400 	bch2_btree_node_iter_push(iter, b, k, btree_bkey_last(b, t));
401 }
402 
403 static void __bch2_btree_path_fix_key_modified(struct btree_path *path,
404 					       struct btree *b,
405 					       struct bkey_packed *where)
406 {
407 	struct btree_path_level *l = &path->l[b->c.level];
408 
409 	if (where != bch2_btree_node_iter_peek_all(&l->iter, l->b))
410 		return;
411 
412 	if (bkey_iter_pos_cmp(l->b, where, &path->pos) < 0)
413 		bch2_btree_node_iter_advance(&l->iter, l->b);
414 }
415 
416 void bch2_btree_path_fix_key_modified(struct btree_trans *trans,
417 				      struct btree *b,
418 				      struct bkey_packed *where)
419 {
420 	struct btree_path *path;
421 	unsigned i;
422 
423 	trans_for_each_path_with_node(trans, b, path, i) {
424 		__bch2_btree_path_fix_key_modified(path, b, where);
425 		bch2_btree_path_verify_level(trans, path, b->c.level);
426 	}
427 }
428 
429 static void __bch2_btree_node_iter_fix(struct btree_path *path,
430 				       struct btree *b,
431 				       struct btree_node_iter *node_iter,
432 				       struct bset_tree *t,
433 				       struct bkey_packed *where,
434 				       unsigned clobber_u64s,
435 				       unsigned new_u64s)
436 {
437 	const struct bkey_packed *end = btree_bkey_last(b, t);
438 	struct btree_node_iter_set *set;
439 	unsigned offset = __btree_node_key_to_offset(b, where);
440 	int shift = new_u64s - clobber_u64s;
441 	unsigned old_end = t->end_offset - shift;
442 	unsigned orig_iter_pos = node_iter->data[0].k;
443 	bool iter_current_key_modified =
444 		orig_iter_pos >= offset &&
445 		orig_iter_pos <= offset + clobber_u64s;
446 
447 	btree_node_iter_for_each(node_iter, set)
448 		if (set->end == old_end)
449 			goto found;
450 
451 	/* didn't find the bset in the iterator - might have to readd it: */
452 	if (new_u64s &&
453 	    bkey_iter_pos_cmp(b, where, &path->pos) >= 0) {
454 		bch2_btree_node_iter_push(node_iter, b, where, end);
455 		goto fixup_done;
456 	} else {
457 		/* Iterator is after key that changed */
458 		return;
459 	}
460 found:
461 	set->end = t->end_offset;
462 
463 	/* Iterator hasn't gotten to the key that changed yet: */
464 	if (set->k < offset)
465 		return;
466 
467 	if (new_u64s &&
468 	    bkey_iter_pos_cmp(b, where, &path->pos) >= 0) {
469 		set->k = offset;
470 	} else if (set->k < offset + clobber_u64s) {
471 		set->k = offset + new_u64s;
472 		if (set->k == set->end)
473 			bch2_btree_node_iter_set_drop(node_iter, set);
474 	} else {
475 		/* Iterator is after key that changed */
476 		set->k = (int) set->k + shift;
477 		return;
478 	}
479 
480 	bch2_btree_node_iter_sort(node_iter, b);
481 fixup_done:
482 	if (node_iter->data[0].k != orig_iter_pos)
483 		iter_current_key_modified = true;
484 
485 	/*
486 	 * When a new key is added, and the node iterator now points to that
487 	 * key, the iterator might have skipped past deleted keys that should
488 	 * come after the key the iterator now points to. We have to rewind to
489 	 * before those deleted keys - otherwise
490 	 * bch2_btree_node_iter_prev_all() breaks:
491 	 */
492 	if (!bch2_btree_node_iter_end(node_iter) &&
493 	    iter_current_key_modified &&
494 	    b->c.level) {
495 		struct bkey_packed *k, *k2, *p;
496 
497 		k = bch2_btree_node_iter_peek_all(node_iter, b);
498 
499 		for_each_bset(b, t) {
500 			bool set_pos = false;
501 
502 			if (node_iter->data[0].end == t->end_offset)
503 				continue;
504 
505 			k2 = bch2_btree_node_iter_bset_pos(node_iter, b, t);
506 
507 			while ((p = bch2_bkey_prev_all(b, t, k2)) &&
508 			       bkey_iter_cmp(b, k, p) < 0) {
509 				k2 = p;
510 				set_pos = true;
511 			}
512 
513 			if (set_pos)
514 				btree_node_iter_set_set_pos(node_iter,
515 							    b, t, k2);
516 		}
517 	}
518 }
519 
520 void bch2_btree_node_iter_fix(struct btree_trans *trans,
521 			      struct btree_path *path,
522 			      struct btree *b,
523 			      struct btree_node_iter *node_iter,
524 			      struct bkey_packed *where,
525 			      unsigned clobber_u64s,
526 			      unsigned new_u64s)
527 {
528 	struct bset_tree *t = bch2_bkey_to_bset_inlined(b, where);
529 	struct btree_path *linked;
530 	unsigned i;
531 
532 	if (node_iter != &path->l[b->c.level].iter) {
533 		__bch2_btree_node_iter_fix(path, b, node_iter, t,
534 					   where, clobber_u64s, new_u64s);
535 
536 		if (bch2_debug_check_iterators)
537 			bch2_btree_node_iter_verify(node_iter, b);
538 	}
539 
540 	trans_for_each_path_with_node(trans, b, linked, i) {
541 		__bch2_btree_node_iter_fix(linked, b,
542 					   &linked->l[b->c.level].iter, t,
543 					   where, clobber_u64s, new_u64s);
544 		bch2_btree_path_verify_level(trans, linked, b->c.level);
545 	}
546 }
547 
548 /* Btree path level: pointer to a particular btree node and node iter */
549 
550 static inline struct bkey_s_c __btree_iter_unpack(struct bch_fs *c,
551 						  struct btree_path_level *l,
552 						  struct bkey *u,
553 						  struct bkey_packed *k)
554 {
555 	if (unlikely(!k)) {
556 		/*
557 		 * signal to bch2_btree_iter_peek_slot() that we're currently at
558 		 * a hole
559 		 */
560 		u->type = KEY_TYPE_deleted;
561 		return bkey_s_c_null;
562 	}
563 
564 	return bkey_disassemble(l->b, k, u);
565 }
566 
567 static inline struct bkey_s_c btree_path_level_peek_all(struct bch_fs *c,
568 							struct btree_path_level *l,
569 							struct bkey *u)
570 {
571 	return __btree_iter_unpack(c, l, u,
572 			bch2_btree_node_iter_peek_all(&l->iter, l->b));
573 }
574 
575 static inline struct bkey_s_c btree_path_level_peek(struct btree_trans *trans,
576 						    struct btree_path *path,
577 						    struct btree_path_level *l,
578 						    struct bkey *u)
579 {
580 	struct bkey_s_c k = __btree_iter_unpack(trans->c, l, u,
581 			bch2_btree_node_iter_peek(&l->iter, l->b));
582 
583 	path->pos = k.k ? k.k->p : l->b->key.k.p;
584 	trans->paths_sorted = false;
585 	bch2_btree_path_verify_level(trans, path, l - path->l);
586 	return k;
587 }
588 
589 static inline struct bkey_s_c btree_path_level_prev(struct btree_trans *trans,
590 						    struct btree_path *path,
591 						    struct btree_path_level *l,
592 						    struct bkey *u)
593 {
594 	struct bkey_s_c k = __btree_iter_unpack(trans->c, l, u,
595 			bch2_btree_node_iter_prev(&l->iter, l->b));
596 
597 	path->pos = k.k ? k.k->p : l->b->data->min_key;
598 	trans->paths_sorted = false;
599 	bch2_btree_path_verify_level(trans, path, l - path->l);
600 	return k;
601 }
602 
603 static inline bool btree_path_advance_to_pos(struct btree_path *path,
604 					     struct btree_path_level *l,
605 					     int max_advance)
606 {
607 	struct bkey_packed *k;
608 	int nr_advanced = 0;
609 
610 	while ((k = bch2_btree_node_iter_peek_all(&l->iter, l->b)) &&
611 	       bkey_iter_pos_cmp(l->b, k, &path->pos) < 0) {
612 		if (max_advance > 0 && nr_advanced >= max_advance)
613 			return false;
614 
615 		bch2_btree_node_iter_advance(&l->iter, l->b);
616 		nr_advanced++;
617 	}
618 
619 	return true;
620 }
621 
622 static inline void __btree_path_level_init(struct btree_path *path,
623 					   unsigned level)
624 {
625 	struct btree_path_level *l = &path->l[level];
626 
627 	bch2_btree_node_iter_init(&l->iter, l->b, &path->pos);
628 
629 	/*
630 	 * Iterators to interior nodes should always be pointed at the first non
631 	 * whiteout:
632 	 */
633 	if (level)
634 		bch2_btree_node_iter_peek(&l->iter, l->b);
635 }
636 
637 void bch2_btree_path_level_init(struct btree_trans *trans,
638 				struct btree_path *path,
639 				struct btree *b)
640 {
641 	BUG_ON(path->cached);
642 
643 	EBUG_ON(!btree_path_pos_in_node(path, b));
644 
645 	path->l[b->c.level].lock_seq = six_lock_seq(&b->c.lock);
646 	path->l[b->c.level].b = b;
647 	__btree_path_level_init(path, b->c.level);
648 }
649 
650 /* Btree path: fixups after btree node updates: */
651 
652 static void bch2_trans_revalidate_updates_in_node(struct btree_trans *trans, struct btree *b)
653 {
654 	struct bch_fs *c = trans->c;
655 
656 	trans_for_each_update(trans, i)
657 		if (!i->cached &&
658 		    i->level	== b->c.level &&
659 		    i->btree_id	== b->c.btree_id &&
660 		    bpos_cmp(i->k->k.p, b->data->min_key) >= 0 &&
661 		    bpos_cmp(i->k->k.p, b->data->max_key) <= 0) {
662 			i->old_v = bch2_btree_path_peek_slot(trans->paths + i->path, &i->old_k).v;
663 
664 			if (unlikely(trans->journal_replay_not_finished)) {
665 				struct bkey_i *j_k =
666 					bch2_journal_keys_peek_slot(c, i->btree_id, i->level,
667 								    i->k->k.p);
668 
669 				if (j_k) {
670 					i->old_k = j_k->k;
671 					i->old_v = &j_k->v;
672 				}
673 			}
674 		}
675 }
676 
677 /*
678  * A btree node is being replaced - update the iterator to point to the new
679  * node:
680  */
681 void bch2_trans_node_add(struct btree_trans *trans,
682 			 struct btree_path *path,
683 			 struct btree *b)
684 {
685 	struct btree_path *prev;
686 
687 	BUG_ON(!btree_path_pos_in_node(path, b));
688 
689 	while ((prev = prev_btree_path(trans, path)) &&
690 	       btree_path_pos_in_node(prev, b))
691 		path = prev;
692 
693 	for (;
694 	     path && btree_path_pos_in_node(path, b);
695 	     path = next_btree_path(trans, path))
696 		if (path->uptodate == BTREE_ITER_UPTODATE && !path->cached) {
697 			enum btree_node_locked_type t =
698 				btree_lock_want(path, b->c.level);
699 
700 			if (t != BTREE_NODE_UNLOCKED) {
701 				btree_node_unlock(trans, path, b->c.level);
702 				six_lock_increment(&b->c.lock, (enum six_lock_type) t);
703 				mark_btree_node_locked(trans, path, b->c.level, t);
704 			}
705 
706 			bch2_btree_path_level_init(trans, path, b);
707 		}
708 
709 	bch2_trans_revalidate_updates_in_node(trans, b);
710 }
711 
712 /*
713  * A btree node has been modified in such a way as to invalidate iterators - fix
714  * them:
715  */
716 void bch2_trans_node_reinit_iter(struct btree_trans *trans, struct btree *b)
717 {
718 	struct btree_path *path;
719 	unsigned i;
720 
721 	trans_for_each_path_with_node(trans, b, path, i)
722 		__btree_path_level_init(path, b->c.level);
723 
724 	bch2_trans_revalidate_updates_in_node(trans, b);
725 }
726 
727 /* Btree path: traverse, set_pos: */
728 
729 static inline int btree_path_lock_root(struct btree_trans *trans,
730 				       struct btree_path *path,
731 				       unsigned depth_want,
732 				       unsigned long trace_ip)
733 {
734 	struct bch_fs *c = trans->c;
735 	struct btree *b, **rootp = &bch2_btree_id_root(c, path->btree_id)->b;
736 	enum six_lock_type lock_type;
737 	unsigned i;
738 	int ret;
739 
740 	EBUG_ON(path->nodes_locked);
741 
742 	while (1) {
743 		b = READ_ONCE(*rootp);
744 		path->level = READ_ONCE(b->c.level);
745 
746 		if (unlikely(path->level < depth_want)) {
747 			/*
748 			 * the root is at a lower depth than the depth we want:
749 			 * got to the end of the btree, or we're walking nodes
750 			 * greater than some depth and there are no nodes >=
751 			 * that depth
752 			 */
753 			path->level = depth_want;
754 			for (i = path->level; i < BTREE_MAX_DEPTH; i++)
755 				path->l[i].b = NULL;
756 			return 1;
757 		}
758 
759 		lock_type = __btree_lock_want(path, path->level);
760 		ret = btree_node_lock(trans, path, &b->c,
761 				      path->level, lock_type, trace_ip);
762 		if (unlikely(ret)) {
763 			if (bch2_err_matches(ret, BCH_ERR_lock_fail_root_changed))
764 				continue;
765 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
766 				return ret;
767 			BUG();
768 		}
769 
770 		if (likely(b == READ_ONCE(*rootp) &&
771 			   b->c.level == path->level &&
772 			   !race_fault())) {
773 			for (i = 0; i < path->level; i++)
774 				path->l[i].b = ERR_PTR(-BCH_ERR_no_btree_node_lock_root);
775 			path->l[path->level].b = b;
776 			for (i = path->level + 1; i < BTREE_MAX_DEPTH; i++)
777 				path->l[i].b = NULL;
778 
779 			mark_btree_node_locked(trans, path, path->level,
780 					       (enum btree_node_locked_type) lock_type);
781 			bch2_btree_path_level_init(trans, path, b);
782 			return 0;
783 		}
784 
785 		six_unlock_type(&b->c.lock, lock_type);
786 	}
787 }
788 
789 noinline
790 static int btree_path_prefetch(struct btree_trans *trans, struct btree_path *path)
791 {
792 	struct bch_fs *c = trans->c;
793 	struct btree_path_level *l = path_l(path);
794 	struct btree_node_iter node_iter = l->iter;
795 	struct bkey_packed *k;
796 	struct bkey_buf tmp;
797 	unsigned nr = test_bit(BCH_FS_started, &c->flags)
798 		? (path->level > 1 ? 0 :  2)
799 		: (path->level > 1 ? 1 : 16);
800 	bool was_locked = btree_node_locked(path, path->level);
801 	int ret = 0;
802 
803 	bch2_bkey_buf_init(&tmp);
804 
805 	while (nr-- && !ret) {
806 		if (!bch2_btree_node_relock(trans, path, path->level))
807 			break;
808 
809 		bch2_btree_node_iter_advance(&node_iter, l->b);
810 		k = bch2_btree_node_iter_peek(&node_iter, l->b);
811 		if (!k)
812 			break;
813 
814 		bch2_bkey_buf_unpack(&tmp, c, l->b, k);
815 		ret = bch2_btree_node_prefetch(trans, path, tmp.k, path->btree_id,
816 					       path->level - 1);
817 	}
818 
819 	if (!was_locked)
820 		btree_node_unlock(trans, path, path->level);
821 
822 	bch2_bkey_buf_exit(&tmp, c);
823 	return ret;
824 }
825 
826 static int btree_path_prefetch_j(struct btree_trans *trans, struct btree_path *path,
827 				 struct btree_and_journal_iter *jiter)
828 {
829 	struct bch_fs *c = trans->c;
830 	struct bkey_s_c k;
831 	struct bkey_buf tmp;
832 	unsigned nr = test_bit(BCH_FS_started, &c->flags)
833 		? (path->level > 1 ? 0 :  2)
834 		: (path->level > 1 ? 1 : 16);
835 	bool was_locked = btree_node_locked(path, path->level);
836 	int ret = 0;
837 
838 	bch2_bkey_buf_init(&tmp);
839 
840 	while (nr-- && !ret) {
841 		if (!bch2_btree_node_relock(trans, path, path->level))
842 			break;
843 
844 		bch2_btree_and_journal_iter_advance(jiter);
845 		k = bch2_btree_and_journal_iter_peek(jiter);
846 		if (!k.k)
847 			break;
848 
849 		bch2_bkey_buf_reassemble(&tmp, c, k);
850 		ret = bch2_btree_node_prefetch(trans, path, tmp.k, path->btree_id,
851 					       path->level - 1);
852 	}
853 
854 	if (!was_locked)
855 		btree_node_unlock(trans, path, path->level);
856 
857 	bch2_bkey_buf_exit(&tmp, c);
858 	return ret;
859 }
860 
861 static noinline void btree_node_mem_ptr_set(struct btree_trans *trans,
862 					    struct btree_path *path,
863 					    unsigned plevel, struct btree *b)
864 {
865 	struct btree_path_level *l = &path->l[plevel];
866 	bool locked = btree_node_locked(path, plevel);
867 	struct bkey_packed *k;
868 	struct bch_btree_ptr_v2 *bp;
869 
870 	if (!bch2_btree_node_relock(trans, path, plevel))
871 		return;
872 
873 	k = bch2_btree_node_iter_peek_all(&l->iter, l->b);
874 	BUG_ON(k->type != KEY_TYPE_btree_ptr_v2);
875 
876 	bp = (void *) bkeyp_val(&l->b->format, k);
877 	bp->mem_ptr = (unsigned long)b;
878 
879 	if (!locked)
880 		btree_node_unlock(trans, path, plevel);
881 }
882 
883 static noinline int btree_node_iter_and_journal_peek(struct btree_trans *trans,
884 						     struct btree_path *path,
885 						     unsigned flags,
886 						     struct bkey_buf *out)
887 {
888 	struct bch_fs *c = trans->c;
889 	struct btree_path_level *l = path_l(path);
890 	struct btree_and_journal_iter jiter;
891 	struct bkey_s_c k;
892 	int ret = 0;
893 
894 	__bch2_btree_and_journal_iter_init_node_iter(trans, &jiter, l->b, l->iter, path->pos);
895 
896 	k = bch2_btree_and_journal_iter_peek(&jiter);
897 
898 	bch2_bkey_buf_reassemble(out, c, k);
899 
900 	if ((flags & BTREE_ITER_prefetch) &&
901 	    c->opts.btree_node_prefetch)
902 		ret = btree_path_prefetch_j(trans, path, &jiter);
903 
904 	bch2_btree_and_journal_iter_exit(&jiter);
905 	return ret;
906 }
907 
908 static __always_inline int btree_path_down(struct btree_trans *trans,
909 					   struct btree_path *path,
910 					   unsigned flags,
911 					   unsigned long trace_ip)
912 {
913 	struct bch_fs *c = trans->c;
914 	struct btree_path_level *l = path_l(path);
915 	struct btree *b;
916 	unsigned level = path->level - 1;
917 	enum six_lock_type lock_type = __btree_lock_want(path, level);
918 	struct bkey_buf tmp;
919 	int ret;
920 
921 	EBUG_ON(!btree_node_locked(path, path->level));
922 
923 	bch2_bkey_buf_init(&tmp);
924 
925 	if (unlikely(trans->journal_replay_not_finished)) {
926 		ret = btree_node_iter_and_journal_peek(trans, path, flags, &tmp);
927 		if (ret)
928 			goto err;
929 	} else {
930 		struct bkey_packed *k = bch2_btree_node_iter_peek(&l->iter, l->b);
931 		if (!k) {
932 			struct printbuf buf = PRINTBUF;
933 
934 			prt_str(&buf, "node not found at pos ");
935 			bch2_bpos_to_text(&buf, path->pos);
936 			prt_str(&buf, " within parent node ");
937 			bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&l->b->key));
938 
939 			bch2_fs_fatal_error(c, "%s", buf.buf);
940 			printbuf_exit(&buf);
941 			ret = -BCH_ERR_btree_need_topology_repair;
942 			goto err;
943 		}
944 
945 		bch2_bkey_buf_unpack(&tmp, c, l->b, k);
946 
947 		if ((flags & BTREE_ITER_prefetch) &&
948 		    c->opts.btree_node_prefetch) {
949 			ret = btree_path_prefetch(trans, path);
950 			if (ret)
951 				goto err;
952 		}
953 	}
954 
955 	b = bch2_btree_node_get(trans, path, tmp.k, level, lock_type, trace_ip);
956 	ret = PTR_ERR_OR_ZERO(b);
957 	if (unlikely(ret))
958 		goto err;
959 
960 	if (likely(!trans->journal_replay_not_finished &&
961 		   tmp.k->k.type == KEY_TYPE_btree_ptr_v2) &&
962 	    unlikely(b != btree_node_mem_ptr(tmp.k)))
963 		btree_node_mem_ptr_set(trans, path, level + 1, b);
964 
965 	if (btree_node_read_locked(path, level + 1))
966 		btree_node_unlock(trans, path, level + 1);
967 
968 	mark_btree_node_locked(trans, path, level,
969 			       (enum btree_node_locked_type) lock_type);
970 	path->level = level;
971 	bch2_btree_path_level_init(trans, path, b);
972 
973 	bch2_btree_path_verify_locks(path);
974 err:
975 	bch2_bkey_buf_exit(&tmp, c);
976 	return ret;
977 }
978 
979 static int bch2_btree_path_traverse_all(struct btree_trans *trans)
980 {
981 	struct bch_fs *c = trans->c;
982 	struct btree_path *path;
983 	unsigned long trace_ip = _RET_IP_;
984 	unsigned i;
985 	int ret = 0;
986 
987 	if (trans->in_traverse_all)
988 		return -BCH_ERR_transaction_restart_in_traverse_all;
989 
990 	trans->in_traverse_all = true;
991 retry_all:
992 	trans->restarted = 0;
993 	trans->last_restarted_ip = 0;
994 
995 	trans_for_each_path(trans, path, i)
996 		path->should_be_locked = false;
997 
998 	btree_trans_sort_paths(trans);
999 
1000 	bch2_trans_unlock(trans);
1001 	cond_resched();
1002 	trans->locked = true;
1003 
1004 	if (unlikely(trans->memory_allocation_failure)) {
1005 		struct closure cl;
1006 
1007 		closure_init_stack(&cl);
1008 
1009 		do {
1010 			ret = bch2_btree_cache_cannibalize_lock(trans, &cl);
1011 			closure_sync(&cl);
1012 		} while (ret);
1013 	}
1014 
1015 	/* Now, redo traversals in correct order: */
1016 	i = 0;
1017 	while (i < trans->nr_sorted) {
1018 		btree_path_idx_t idx = trans->sorted[i];
1019 
1020 		/*
1021 		 * Traversing a path can cause another path to be added at about
1022 		 * the same position:
1023 		 */
1024 		if (trans->paths[idx].uptodate) {
1025 			__btree_path_get(&trans->paths[idx], false);
1026 			ret = bch2_btree_path_traverse_one(trans, idx, 0, _THIS_IP_);
1027 			__btree_path_put(&trans->paths[idx], false);
1028 
1029 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
1030 			    bch2_err_matches(ret, ENOMEM))
1031 				goto retry_all;
1032 			if (ret)
1033 				goto err;
1034 		} else {
1035 			i++;
1036 		}
1037 	}
1038 
1039 	/*
1040 	 * We used to assert that all paths had been traversed here
1041 	 * (path->uptodate < BTREE_ITER_NEED_TRAVERSE); however, since
1042 	 * path->should_be_locked is not set yet, we might have unlocked and
1043 	 * then failed to relock a path - that's fine.
1044 	 */
1045 err:
1046 	bch2_btree_cache_cannibalize_unlock(trans);
1047 
1048 	trans->in_traverse_all = false;
1049 
1050 	trace_and_count(c, trans_traverse_all, trans, trace_ip);
1051 	return ret;
1052 }
1053 
1054 static inline bool btree_path_check_pos_in_node(struct btree_path *path,
1055 						unsigned l, int check_pos)
1056 {
1057 	if (check_pos < 0 && btree_path_pos_before_node(path, path->l[l].b))
1058 		return false;
1059 	if (check_pos > 0 && btree_path_pos_after_node(path, path->l[l].b))
1060 		return false;
1061 	return true;
1062 }
1063 
1064 static inline bool btree_path_good_node(struct btree_trans *trans,
1065 					struct btree_path *path,
1066 					unsigned l, int check_pos)
1067 {
1068 	return is_btree_node(path, l) &&
1069 		bch2_btree_node_relock(trans, path, l) &&
1070 		btree_path_check_pos_in_node(path, l, check_pos);
1071 }
1072 
1073 static void btree_path_set_level_down(struct btree_trans *trans,
1074 				      struct btree_path *path,
1075 				      unsigned new_level)
1076 {
1077 	unsigned l;
1078 
1079 	path->level = new_level;
1080 
1081 	for (l = path->level + 1; l < BTREE_MAX_DEPTH; l++)
1082 		if (btree_lock_want(path, l) == BTREE_NODE_UNLOCKED)
1083 			btree_node_unlock(trans, path, l);
1084 
1085 	btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
1086 	bch2_btree_path_verify(trans, path);
1087 }
1088 
1089 static noinline unsigned __btree_path_up_until_good_node(struct btree_trans *trans,
1090 							 struct btree_path *path,
1091 							 int check_pos)
1092 {
1093 	unsigned i, l = path->level;
1094 again:
1095 	while (btree_path_node(path, l) &&
1096 	       !btree_path_good_node(trans, path, l, check_pos))
1097 		__btree_path_set_level_up(trans, path, l++);
1098 
1099 	/* If we need intent locks, take them too: */
1100 	for (i = l + 1;
1101 	     i < path->locks_want && btree_path_node(path, i);
1102 	     i++)
1103 		if (!bch2_btree_node_relock(trans, path, i)) {
1104 			while (l <= i)
1105 				__btree_path_set_level_up(trans, path, l++);
1106 			goto again;
1107 		}
1108 
1109 	return l;
1110 }
1111 
1112 static inline unsigned btree_path_up_until_good_node(struct btree_trans *trans,
1113 						     struct btree_path *path,
1114 						     int check_pos)
1115 {
1116 	return likely(btree_node_locked(path, path->level) &&
1117 		      btree_path_check_pos_in_node(path, path->level, check_pos))
1118 		? path->level
1119 		: __btree_path_up_until_good_node(trans, path, check_pos);
1120 }
1121 
1122 /*
1123  * This is the main state machine for walking down the btree - walks down to a
1124  * specified depth
1125  *
1126  * Returns 0 on success, -EIO on error (error reading in a btree node).
1127  *
1128  * On error, caller (peek_node()/peek_key()) must return NULL; the error is
1129  * stashed in the iterator and returned from bch2_trans_exit().
1130  */
1131 int bch2_btree_path_traverse_one(struct btree_trans *trans,
1132 				 btree_path_idx_t path_idx,
1133 				 unsigned flags,
1134 				 unsigned long trace_ip)
1135 {
1136 	struct btree_path *path = &trans->paths[path_idx];
1137 	unsigned depth_want = path->level;
1138 	int ret = -((int) trans->restarted);
1139 
1140 	if (unlikely(ret))
1141 		goto out;
1142 
1143 	if (unlikely(!trans->srcu_held))
1144 		bch2_trans_srcu_lock(trans);
1145 
1146 	/*
1147 	 * Ensure we obey path->should_be_locked: if it's set, we can't unlock
1148 	 * and re-traverse the path without a transaction restart:
1149 	 */
1150 	if (path->should_be_locked) {
1151 		ret = bch2_btree_path_relock(trans, path, trace_ip);
1152 		goto out;
1153 	}
1154 
1155 	if (path->cached) {
1156 		ret = bch2_btree_path_traverse_cached(trans, path, flags);
1157 		goto out;
1158 	}
1159 
1160 	path = &trans->paths[path_idx];
1161 
1162 	if (unlikely(path->level >= BTREE_MAX_DEPTH))
1163 		goto out_uptodate;
1164 
1165 	path->level = btree_path_up_until_good_node(trans, path, 0);
1166 	unsigned max_level = path->level;
1167 
1168 	EBUG_ON(btree_path_node(path, path->level) &&
1169 		!btree_node_locked(path, path->level));
1170 
1171 	/*
1172 	 * Note: path->nodes[path->level] may be temporarily NULL here - that
1173 	 * would indicate to other code that we got to the end of the btree,
1174 	 * here it indicates that relocking the root failed - it's critical that
1175 	 * btree_path_lock_root() comes next and that it can't fail
1176 	 */
1177 	while (path->level > depth_want) {
1178 		ret = btree_path_node(path, path->level)
1179 			? btree_path_down(trans, path, flags, trace_ip)
1180 			: btree_path_lock_root(trans, path, depth_want, trace_ip);
1181 		if (unlikely(ret)) {
1182 			if (ret == 1) {
1183 				/*
1184 				 * No nodes at this level - got to the end of
1185 				 * the btree:
1186 				 */
1187 				ret = 0;
1188 				goto out;
1189 			}
1190 
1191 			__bch2_btree_path_unlock(trans, path);
1192 			path->level = depth_want;
1193 			path->l[path->level].b = ERR_PTR(ret);
1194 			goto out;
1195 		}
1196 	}
1197 
1198 	if (unlikely(max_level > path->level)) {
1199 		struct btree_path *linked;
1200 		unsigned iter;
1201 
1202 		trans_for_each_path_with_node(trans, path_l(path)->b, linked, iter)
1203 			for (unsigned j = path->level + 1; j < max_level; j++)
1204 				linked->l[j] = path->l[j];
1205 	}
1206 
1207 out_uptodate:
1208 	path->uptodate = BTREE_ITER_UPTODATE;
1209 out:
1210 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart) != !!trans->restarted)
1211 		panic("ret %s (%i) trans->restarted %s (%i)\n",
1212 		      bch2_err_str(ret), ret,
1213 		      bch2_err_str(trans->restarted), trans->restarted);
1214 	bch2_btree_path_verify(trans, path);
1215 	return ret;
1216 }
1217 
1218 static inline void btree_path_copy(struct btree_trans *trans, struct btree_path *dst,
1219 			    struct btree_path *src)
1220 {
1221 	unsigned i, offset = offsetof(struct btree_path, pos);
1222 
1223 	memcpy((void *) dst + offset,
1224 	       (void *) src + offset,
1225 	       sizeof(struct btree_path) - offset);
1226 
1227 	for (i = 0; i < BTREE_MAX_DEPTH; i++) {
1228 		unsigned t = btree_node_locked_type(dst, i);
1229 
1230 		if (t != BTREE_NODE_UNLOCKED)
1231 			six_lock_increment(&dst->l[i].b->c.lock, t);
1232 	}
1233 }
1234 
1235 static btree_path_idx_t btree_path_clone(struct btree_trans *trans, btree_path_idx_t src,
1236 					 bool intent, unsigned long ip)
1237 {
1238 	btree_path_idx_t new = btree_path_alloc(trans, src);
1239 	btree_path_copy(trans, trans->paths + new, trans->paths + src);
1240 	__btree_path_get(trans->paths + new, intent);
1241 #ifdef TRACK_PATH_ALLOCATED
1242 	trans->paths[new].ip_allocated = ip;
1243 #endif
1244 	return new;
1245 }
1246 
1247 __flatten
1248 btree_path_idx_t __bch2_btree_path_make_mut(struct btree_trans *trans,
1249 			btree_path_idx_t path, bool intent, unsigned long ip)
1250 {
1251 	__btree_path_put(trans->paths + path, intent);
1252 	path = btree_path_clone(trans, path, intent, ip);
1253 	trans->paths[path].preserve = false;
1254 	return path;
1255 }
1256 
1257 btree_path_idx_t __must_check
1258 __bch2_btree_path_set_pos(struct btree_trans *trans,
1259 			  btree_path_idx_t path_idx, struct bpos new_pos,
1260 			  bool intent, unsigned long ip)
1261 {
1262 	int cmp = bpos_cmp(new_pos, trans->paths[path_idx].pos);
1263 
1264 	bch2_trans_verify_not_in_restart(trans);
1265 	EBUG_ON(!trans->paths[path_idx].ref);
1266 
1267 	path_idx = bch2_btree_path_make_mut(trans, path_idx, intent, ip);
1268 
1269 	struct btree_path *path = trans->paths + path_idx;
1270 	path->pos		= new_pos;
1271 	trans->paths_sorted	= false;
1272 
1273 	if (unlikely(path->cached)) {
1274 		btree_node_unlock(trans, path, 0);
1275 		path->l[0].b = ERR_PTR(-BCH_ERR_no_btree_node_up);
1276 		btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
1277 		goto out;
1278 	}
1279 
1280 	unsigned level = btree_path_up_until_good_node(trans, path, cmp);
1281 
1282 	if (btree_path_node(path, level)) {
1283 		struct btree_path_level *l = &path->l[level];
1284 
1285 		BUG_ON(!btree_node_locked(path, level));
1286 		/*
1287 		 * We might have to skip over many keys, or just a few: try
1288 		 * advancing the node iterator, and if we have to skip over too
1289 		 * many keys just reinit it (or if we're rewinding, since that
1290 		 * is expensive).
1291 		 */
1292 		if (cmp < 0 ||
1293 		    !btree_path_advance_to_pos(path, l, 8))
1294 			bch2_btree_node_iter_init(&l->iter, l->b, &path->pos);
1295 
1296 		/*
1297 		 * Iterators to interior nodes should always be pointed at the first non
1298 		 * whiteout:
1299 		 */
1300 		if (unlikely(level))
1301 			bch2_btree_node_iter_peek(&l->iter, l->b);
1302 	}
1303 
1304 	if (unlikely(level != path->level)) {
1305 		btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
1306 		__bch2_btree_path_unlock(trans, path);
1307 	}
1308 out:
1309 	bch2_btree_path_verify(trans, path);
1310 	return path_idx;
1311 }
1312 
1313 /* Btree path: main interface: */
1314 
1315 static struct btree_path *have_path_at_pos(struct btree_trans *trans, struct btree_path *path)
1316 {
1317 	struct btree_path *sib;
1318 
1319 	sib = prev_btree_path(trans, path);
1320 	if (sib && !btree_path_cmp(sib, path))
1321 		return sib;
1322 
1323 	sib = next_btree_path(trans, path);
1324 	if (sib && !btree_path_cmp(sib, path))
1325 		return sib;
1326 
1327 	return NULL;
1328 }
1329 
1330 static struct btree_path *have_node_at_pos(struct btree_trans *trans, struct btree_path *path)
1331 {
1332 	struct btree_path *sib;
1333 
1334 	sib = prev_btree_path(trans, path);
1335 	if (sib && sib->level == path->level && path_l(sib)->b == path_l(path)->b)
1336 		return sib;
1337 
1338 	sib = next_btree_path(trans, path);
1339 	if (sib && sib->level == path->level && path_l(sib)->b == path_l(path)->b)
1340 		return sib;
1341 
1342 	return NULL;
1343 }
1344 
1345 static inline void __bch2_path_free(struct btree_trans *trans, btree_path_idx_t path)
1346 {
1347 	__bch2_btree_path_unlock(trans, trans->paths + path);
1348 	btree_path_list_remove(trans, trans->paths + path);
1349 	__clear_bit(path, trans->paths_allocated);
1350 }
1351 
1352 static bool bch2_btree_path_can_relock(struct btree_trans *trans, struct btree_path *path)
1353 {
1354 	unsigned l = path->level;
1355 
1356 	do {
1357 		if (!btree_path_node(path, l))
1358 			break;
1359 
1360 		if (!is_btree_node(path, l))
1361 			return false;
1362 
1363 		if (path->l[l].lock_seq != path->l[l].b->c.lock.seq)
1364 			return false;
1365 
1366 		l++;
1367 	} while (l < path->locks_want);
1368 
1369 	return true;
1370 }
1371 
1372 void bch2_path_put(struct btree_trans *trans, btree_path_idx_t path_idx, bool intent)
1373 {
1374 	struct btree_path *path = trans->paths + path_idx, *dup;
1375 
1376 	if (!__btree_path_put(path, intent))
1377 		return;
1378 
1379 	dup = path->preserve
1380 		? have_path_at_pos(trans, path)
1381 		: have_node_at_pos(trans, path);
1382 
1383 	if (!dup && !(!path->preserve && !is_btree_node(path, path->level)))
1384 		return;
1385 
1386 	if (path->should_be_locked && !trans->restarted) {
1387 		if (!dup)
1388 			return;
1389 
1390 		if (!(trans->locked
1391 		      ? bch2_btree_path_relock_norestart(trans, dup)
1392 		      : bch2_btree_path_can_relock(trans, dup)))
1393 			return;
1394 	}
1395 
1396 	if (dup) {
1397 		dup->preserve		|= path->preserve;
1398 		dup->should_be_locked	|= path->should_be_locked;
1399 	}
1400 
1401 	__bch2_path_free(trans, path_idx);
1402 }
1403 
1404 static void bch2_path_put_nokeep(struct btree_trans *trans, btree_path_idx_t path,
1405 				 bool intent)
1406 {
1407 	if (!__btree_path_put(trans->paths + path, intent))
1408 		return;
1409 
1410 	__bch2_path_free(trans, path);
1411 }
1412 
1413 void __noreturn bch2_trans_restart_error(struct btree_trans *trans, u32 restart_count)
1414 {
1415 	panic("trans->restart_count %u, should be %u, last restarted by %pS\n",
1416 	      trans->restart_count, restart_count,
1417 	      (void *) trans->last_begin_ip);
1418 }
1419 
1420 void __noreturn bch2_trans_in_restart_error(struct btree_trans *trans)
1421 {
1422 	panic("in transaction restart: %s, last restarted by %pS\n",
1423 	      bch2_err_str(trans->restarted),
1424 	      (void *) trans->last_restarted_ip);
1425 }
1426 
1427 void __noreturn bch2_trans_unlocked_error(struct btree_trans *trans)
1428 {
1429 	panic("trans should be locked, unlocked by %pS\n",
1430 	      (void *) trans->last_unlock_ip);
1431 }
1432 
1433 noinline __cold
1434 void bch2_trans_updates_to_text(struct printbuf *buf, struct btree_trans *trans)
1435 {
1436 	prt_printf(buf, "transaction updates for %s journal seq %llu\n",
1437 	       trans->fn, trans->journal_res.seq);
1438 	printbuf_indent_add(buf, 2);
1439 
1440 	trans_for_each_update(trans, i) {
1441 		struct bkey_s_c old = { &i->old_k, i->old_v };
1442 
1443 		prt_printf(buf, "update: btree=%s cached=%u %pS\n",
1444 		       bch2_btree_id_str(i->btree_id),
1445 		       i->cached,
1446 		       (void *) i->ip_allocated);
1447 
1448 		prt_printf(buf, "  old ");
1449 		bch2_bkey_val_to_text(buf, trans->c, old);
1450 		prt_newline(buf);
1451 
1452 		prt_printf(buf, "  new ");
1453 		bch2_bkey_val_to_text(buf, trans->c, bkey_i_to_s_c(i->k));
1454 		prt_newline(buf);
1455 	}
1456 
1457 	for (struct jset_entry *e = trans->journal_entries;
1458 	     e != btree_trans_journal_entries_top(trans);
1459 	     e = vstruct_next(e))
1460 		bch2_journal_entry_to_text(buf, trans->c, e);
1461 
1462 	printbuf_indent_sub(buf, 2);
1463 }
1464 
1465 noinline __cold
1466 void bch2_dump_trans_updates(struct btree_trans *trans)
1467 {
1468 	struct printbuf buf = PRINTBUF;
1469 
1470 	bch2_trans_updates_to_text(&buf, trans);
1471 	bch2_print_string_as_lines(KERN_ERR, buf.buf);
1472 	printbuf_exit(&buf);
1473 }
1474 
1475 static void bch2_btree_path_to_text_short(struct printbuf *out, struct btree_trans *trans, btree_path_idx_t path_idx)
1476 {
1477 	struct btree_path *path = trans->paths + path_idx;
1478 
1479 	prt_printf(out, "path: idx %2u ref %u:%u %c %c %c btree=%s l=%u pos ",
1480 		   path_idx, path->ref, path->intent_ref,
1481 		   path->preserve ? 'P' : ' ',
1482 		   path->should_be_locked ? 'S' : ' ',
1483 		   path->cached ? 'C' : 'B',
1484 		   bch2_btree_id_str(path->btree_id),
1485 		   path->level);
1486 	bch2_bpos_to_text(out, path->pos);
1487 
1488 #ifdef TRACK_PATH_ALLOCATED
1489 	prt_printf(out, " %pS", (void *) path->ip_allocated);
1490 #endif
1491 }
1492 
1493 static const char *btree_node_locked_str(enum btree_node_locked_type t)
1494 {
1495 	switch (t) {
1496 	case BTREE_NODE_UNLOCKED:
1497 		return "unlocked";
1498 	case BTREE_NODE_READ_LOCKED:
1499 		return "read";
1500 	case BTREE_NODE_INTENT_LOCKED:
1501 		return "intent";
1502 	case BTREE_NODE_WRITE_LOCKED:
1503 		return "write";
1504 	default:
1505 		return NULL;
1506 	}
1507 }
1508 
1509 void bch2_btree_path_to_text(struct printbuf *out, struct btree_trans *trans, btree_path_idx_t path_idx)
1510 {
1511 	bch2_btree_path_to_text_short(out, trans, path_idx);
1512 
1513 	struct btree_path *path = trans->paths + path_idx;
1514 
1515 	prt_printf(out, " uptodate %u locks_want %u", path->uptodate, path->locks_want);
1516 	prt_newline(out);
1517 
1518 	printbuf_indent_add(out, 2);
1519 	for (unsigned l = 0; l < BTREE_MAX_DEPTH; l++) {
1520 		prt_printf(out, "l=%u locks %s seq %u node ", l,
1521 			   btree_node_locked_str(btree_node_locked_type(path, l)),
1522 			   path->l[l].lock_seq);
1523 
1524 		int ret = PTR_ERR_OR_ZERO(path->l[l].b);
1525 		if (ret)
1526 			prt_str(out, bch2_err_str(ret));
1527 		else
1528 			prt_printf(out, "%px", path->l[l].b);
1529 		prt_newline(out);
1530 	}
1531 	printbuf_indent_sub(out, 2);
1532 }
1533 
1534 static noinline __cold
1535 void __bch2_trans_paths_to_text(struct printbuf *out, struct btree_trans *trans,
1536 				bool nosort)
1537 {
1538 	struct trans_for_each_path_inorder_iter iter;
1539 
1540 	if (!nosort)
1541 		btree_trans_sort_paths(trans);
1542 
1543 	trans_for_each_path_idx_inorder(trans, iter) {
1544 		bch2_btree_path_to_text_short(out, trans, iter.path_idx);
1545 		prt_newline(out);
1546 	}
1547 }
1548 
1549 noinline __cold
1550 void bch2_trans_paths_to_text(struct printbuf *out, struct btree_trans *trans)
1551 {
1552 	__bch2_trans_paths_to_text(out, trans, false);
1553 }
1554 
1555 static noinline __cold
1556 void __bch2_dump_trans_paths_updates(struct btree_trans *trans, bool nosort)
1557 {
1558 	struct printbuf buf = PRINTBUF;
1559 
1560 	__bch2_trans_paths_to_text(&buf, trans, nosort);
1561 	bch2_trans_updates_to_text(&buf, trans);
1562 
1563 	bch2_print_string_as_lines(KERN_ERR, buf.buf);
1564 	printbuf_exit(&buf);
1565 }
1566 
1567 noinline __cold
1568 void bch2_dump_trans_paths_updates(struct btree_trans *trans)
1569 {
1570 	__bch2_dump_trans_paths_updates(trans, false);
1571 }
1572 
1573 noinline __cold
1574 static void bch2_trans_update_max_paths(struct btree_trans *trans)
1575 {
1576 	struct btree_transaction_stats *s = btree_trans_stats(trans);
1577 	struct printbuf buf = PRINTBUF;
1578 	size_t nr = bitmap_weight(trans->paths_allocated, trans->nr_paths);
1579 
1580 	bch2_trans_paths_to_text(&buf, trans);
1581 
1582 	if (!buf.allocation_failure) {
1583 		mutex_lock(&s->lock);
1584 		if (nr > s->nr_max_paths) {
1585 			s->nr_max_paths = nr;
1586 			swap(s->max_paths_text, buf.buf);
1587 		}
1588 		mutex_unlock(&s->lock);
1589 	}
1590 
1591 	printbuf_exit(&buf);
1592 
1593 	trans->nr_paths_max = nr;
1594 }
1595 
1596 noinline __cold
1597 int __bch2_btree_trans_too_many_iters(struct btree_trans *trans)
1598 {
1599 	if (trace_trans_restart_too_many_iters_enabled()) {
1600 		struct printbuf buf = PRINTBUF;
1601 
1602 		bch2_trans_paths_to_text(&buf, trans);
1603 		trace_trans_restart_too_many_iters(trans, _THIS_IP_, buf.buf);
1604 		printbuf_exit(&buf);
1605 	}
1606 
1607 	count_event(trans->c, trans_restart_too_many_iters);
1608 
1609 	return btree_trans_restart(trans, BCH_ERR_transaction_restart_too_many_iters);
1610 }
1611 
1612 static noinline void btree_path_overflow(struct btree_trans *trans)
1613 {
1614 	bch2_dump_trans_paths_updates(trans);
1615 	bch_err(trans->c, "trans path overflow");
1616 }
1617 
1618 static noinline void btree_paths_realloc(struct btree_trans *trans)
1619 {
1620 	unsigned nr = trans->nr_paths * 2;
1621 
1622 	void *p = kvzalloc(BITS_TO_LONGS(nr) * sizeof(unsigned long) +
1623 			  sizeof(struct btree_trans_paths) +
1624 			  nr * sizeof(struct btree_path) +
1625 			  nr * sizeof(btree_path_idx_t) + 8 +
1626 			  nr * sizeof(struct btree_insert_entry), GFP_KERNEL|__GFP_NOFAIL);
1627 
1628 	unsigned long *paths_allocated = p;
1629 	memcpy(paths_allocated, trans->paths_allocated, BITS_TO_LONGS(trans->nr_paths) * sizeof(unsigned long));
1630 	p += BITS_TO_LONGS(nr) * sizeof(unsigned long);
1631 
1632 	p += sizeof(struct btree_trans_paths);
1633 	struct btree_path *paths = p;
1634 	*trans_paths_nr(paths) = nr;
1635 	memcpy(paths, trans->paths, trans->nr_paths * sizeof(struct btree_path));
1636 	p += nr * sizeof(struct btree_path);
1637 
1638 	btree_path_idx_t *sorted = p;
1639 	memcpy(sorted, trans->sorted, trans->nr_sorted * sizeof(btree_path_idx_t));
1640 	p += nr * sizeof(btree_path_idx_t) + 8;
1641 
1642 	struct btree_insert_entry *updates = p;
1643 	memcpy(updates, trans->updates, trans->nr_paths * sizeof(struct btree_insert_entry));
1644 
1645 	unsigned long *old = trans->paths_allocated;
1646 
1647 	rcu_assign_pointer(trans->paths_allocated,	paths_allocated);
1648 	rcu_assign_pointer(trans->paths,		paths);
1649 	rcu_assign_pointer(trans->sorted,		sorted);
1650 	rcu_assign_pointer(trans->updates,		updates);
1651 
1652 	trans->nr_paths		= nr;
1653 
1654 	if (old != trans->_paths_allocated)
1655 		kfree_rcu_mightsleep(old);
1656 }
1657 
1658 static inline btree_path_idx_t btree_path_alloc(struct btree_trans *trans,
1659 						btree_path_idx_t pos)
1660 {
1661 	btree_path_idx_t idx = find_first_zero_bit(trans->paths_allocated, trans->nr_paths);
1662 
1663 	if (unlikely(idx == trans->nr_paths)) {
1664 		if (trans->nr_paths == BTREE_ITER_MAX) {
1665 			btree_path_overflow(trans);
1666 			return 0;
1667 		}
1668 
1669 		btree_paths_realloc(trans);
1670 	}
1671 
1672 	/*
1673 	 * Do this before marking the new path as allocated, since it won't be
1674 	 * initialized yet:
1675 	 */
1676 	if (unlikely(idx > trans->nr_paths_max))
1677 		bch2_trans_update_max_paths(trans);
1678 
1679 	__set_bit(idx, trans->paths_allocated);
1680 
1681 	struct btree_path *path = &trans->paths[idx];
1682 	path->ref		= 0;
1683 	path->intent_ref	= 0;
1684 	path->nodes_locked	= 0;
1685 
1686 	btree_path_list_add(trans, pos, idx);
1687 	trans->paths_sorted = false;
1688 	return idx;
1689 }
1690 
1691 btree_path_idx_t bch2_path_get(struct btree_trans *trans,
1692 			     enum btree_id btree_id, struct bpos pos,
1693 			     unsigned locks_want, unsigned level,
1694 			     unsigned flags, unsigned long ip)
1695 {
1696 	struct btree_path *path;
1697 	bool cached = flags & BTREE_ITER_cached;
1698 	bool intent = flags & BTREE_ITER_intent;
1699 	struct trans_for_each_path_inorder_iter iter;
1700 	btree_path_idx_t path_pos = 0, path_idx;
1701 
1702 	bch2_trans_verify_not_unlocked(trans);
1703 	bch2_trans_verify_not_in_restart(trans);
1704 	bch2_trans_verify_locks(trans);
1705 
1706 	btree_trans_sort_paths(trans);
1707 
1708 	trans_for_each_path_inorder(trans, path, iter) {
1709 		if (__btree_path_cmp(path,
1710 				     btree_id,
1711 				     cached,
1712 				     pos,
1713 				     level) > 0)
1714 			break;
1715 
1716 		path_pos = iter.path_idx;
1717 	}
1718 
1719 	if (path_pos &&
1720 	    trans->paths[path_pos].cached	== cached &&
1721 	    trans->paths[path_pos].btree_id	== btree_id &&
1722 	    trans->paths[path_pos].level	== level) {
1723 		__btree_path_get(trans->paths + path_pos, intent);
1724 		path_idx = bch2_btree_path_set_pos(trans, path_pos, pos, intent, ip);
1725 		path = trans->paths + path_idx;
1726 	} else {
1727 		path_idx = btree_path_alloc(trans, path_pos);
1728 		path = trans->paths + path_idx;
1729 
1730 		__btree_path_get(path, intent);
1731 		path->pos			= pos;
1732 		path->btree_id			= btree_id;
1733 		path->cached			= cached;
1734 		path->uptodate			= BTREE_ITER_NEED_TRAVERSE;
1735 		path->should_be_locked		= false;
1736 		path->level			= level;
1737 		path->locks_want		= locks_want;
1738 		path->nodes_locked		= 0;
1739 		for (unsigned i = 0; i < ARRAY_SIZE(path->l); i++)
1740 			path->l[i].b		= ERR_PTR(-BCH_ERR_no_btree_node_init);
1741 #ifdef TRACK_PATH_ALLOCATED
1742 		path->ip_allocated		= ip;
1743 #endif
1744 		trans->paths_sorted		= false;
1745 	}
1746 
1747 	if (!(flags & BTREE_ITER_nopreserve))
1748 		path->preserve = true;
1749 
1750 	if (path->intent_ref)
1751 		locks_want = max(locks_want, level + 1);
1752 
1753 	/*
1754 	 * If the path has locks_want greater than requested, we don't downgrade
1755 	 * it here - on transaction restart because btree node split needs to
1756 	 * upgrade locks, we might be putting/getting the iterator again.
1757 	 * Downgrading iterators only happens via bch2_trans_downgrade(), after
1758 	 * a successful transaction commit.
1759 	 */
1760 
1761 	locks_want = min(locks_want, BTREE_MAX_DEPTH);
1762 	if (locks_want > path->locks_want)
1763 		bch2_btree_path_upgrade_noupgrade_sibs(trans, path, locks_want, NULL);
1764 
1765 	return path_idx;
1766 }
1767 
1768 btree_path_idx_t bch2_path_get_unlocked_mut(struct btree_trans *trans,
1769 					    enum btree_id btree_id,
1770 					    unsigned level,
1771 					    struct bpos pos)
1772 {
1773 	btree_path_idx_t path_idx = bch2_path_get(trans, btree_id, pos, level + 1, level,
1774 			     BTREE_ITER_nopreserve|
1775 			     BTREE_ITER_intent, _RET_IP_);
1776 	path_idx = bch2_btree_path_make_mut(trans, path_idx, true, _RET_IP_);
1777 
1778 	struct btree_path *path = trans->paths + path_idx;
1779 	bch2_btree_path_downgrade(trans, path);
1780 	__bch2_btree_path_unlock(trans, path);
1781 	return path_idx;
1782 }
1783 
1784 struct bkey_s_c bch2_btree_path_peek_slot(struct btree_path *path, struct bkey *u)
1785 {
1786 
1787 	struct btree_path_level *l = path_l(path);
1788 	struct bkey_packed *_k;
1789 	struct bkey_s_c k;
1790 
1791 	if (unlikely(!l->b))
1792 		return bkey_s_c_null;
1793 
1794 	EBUG_ON(path->uptodate != BTREE_ITER_UPTODATE);
1795 	EBUG_ON(!btree_node_locked(path, path->level));
1796 
1797 	if (!path->cached) {
1798 		_k = bch2_btree_node_iter_peek_all(&l->iter, l->b);
1799 		k = _k ? bkey_disassemble(l->b, _k, u) : bkey_s_c_null;
1800 
1801 		EBUG_ON(k.k && bkey_deleted(k.k) && bpos_eq(k.k->p, path->pos));
1802 
1803 		if (!k.k || !bpos_eq(path->pos, k.k->p))
1804 			goto hole;
1805 	} else {
1806 		struct bkey_cached *ck = (void *) path->l[0].b;
1807 
1808 		EBUG_ON(ck &&
1809 			(path->btree_id != ck->key.btree_id ||
1810 			 !bkey_eq(path->pos, ck->key.pos)));
1811 		if (!ck || !ck->valid)
1812 			return bkey_s_c_null;
1813 
1814 		*u = ck->k->k;
1815 		k = bkey_i_to_s_c(ck->k);
1816 	}
1817 
1818 	return k;
1819 hole:
1820 	bkey_init(u);
1821 	u->p = path->pos;
1822 	return (struct bkey_s_c) { u, NULL };
1823 }
1824 
1825 
1826 void bch2_set_btree_iter_dontneed(struct btree_iter *iter)
1827 {
1828 	struct btree_trans *trans = iter->trans;
1829 
1830 	if (!iter->path || trans->restarted)
1831 		return;
1832 
1833 	struct btree_path *path = btree_iter_path(trans, iter);
1834 	path->preserve		= false;
1835 	if (path->ref == 1)
1836 		path->should_be_locked	= false;
1837 }
1838 /* Btree iterators: */
1839 
1840 int __must_check
1841 __bch2_btree_iter_traverse(struct btree_iter *iter)
1842 {
1843 	return bch2_btree_path_traverse(iter->trans, iter->path, iter->flags);
1844 }
1845 
1846 int __must_check
1847 bch2_btree_iter_traverse(struct btree_iter *iter)
1848 {
1849 	struct btree_trans *trans = iter->trans;
1850 	int ret;
1851 
1852 	bch2_trans_verify_not_unlocked(trans);
1853 
1854 	iter->path = bch2_btree_path_set_pos(trans, iter->path,
1855 					btree_iter_search_key(iter),
1856 					iter->flags & BTREE_ITER_intent,
1857 					btree_iter_ip_allocated(iter));
1858 
1859 	ret = bch2_btree_path_traverse(iter->trans, iter->path, iter->flags);
1860 	if (ret)
1861 		return ret;
1862 
1863 	struct btree_path *path = btree_iter_path(trans, iter);
1864 	if (btree_path_node(path, path->level))
1865 		btree_path_set_should_be_locked(path);
1866 	return 0;
1867 }
1868 
1869 /* Iterate across nodes (leaf and interior nodes) */
1870 
1871 struct btree *bch2_btree_iter_peek_node(struct btree_iter *iter)
1872 {
1873 	struct btree_trans *trans = iter->trans;
1874 	struct btree *b = NULL;
1875 	int ret;
1876 
1877 	EBUG_ON(trans->paths[iter->path].cached);
1878 	bch2_btree_iter_verify(iter);
1879 
1880 	ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
1881 	if (ret)
1882 		goto err;
1883 
1884 	struct btree_path *path = btree_iter_path(trans, iter);
1885 	b = btree_path_node(path, path->level);
1886 	if (!b)
1887 		goto out;
1888 
1889 	BUG_ON(bpos_lt(b->key.k.p, iter->pos));
1890 
1891 	bkey_init(&iter->k);
1892 	iter->k.p = iter->pos = b->key.k.p;
1893 
1894 	iter->path = bch2_btree_path_set_pos(trans, iter->path, b->key.k.p,
1895 					iter->flags & BTREE_ITER_intent,
1896 					btree_iter_ip_allocated(iter));
1897 	btree_path_set_should_be_locked(btree_iter_path(trans, iter));
1898 out:
1899 	bch2_btree_iter_verify_entry_exit(iter);
1900 	bch2_btree_iter_verify(iter);
1901 
1902 	return b;
1903 err:
1904 	b = ERR_PTR(ret);
1905 	goto out;
1906 }
1907 
1908 struct btree *bch2_btree_iter_peek_node_and_restart(struct btree_iter *iter)
1909 {
1910 	struct btree *b;
1911 
1912 	while (b = bch2_btree_iter_peek_node(iter),
1913 	       bch2_err_matches(PTR_ERR_OR_ZERO(b), BCH_ERR_transaction_restart))
1914 		bch2_trans_begin(iter->trans);
1915 
1916 	return b;
1917 }
1918 
1919 struct btree *bch2_btree_iter_next_node(struct btree_iter *iter)
1920 {
1921 	struct btree_trans *trans = iter->trans;
1922 	struct btree *b = NULL;
1923 	int ret;
1924 
1925 	EBUG_ON(trans->paths[iter->path].cached);
1926 	bch2_trans_verify_not_in_restart(trans);
1927 	bch2_btree_iter_verify(iter);
1928 
1929 	struct btree_path *path = btree_iter_path(trans, iter);
1930 
1931 	/* already at end? */
1932 	if (!btree_path_node(path, path->level))
1933 		return NULL;
1934 
1935 	/* got to end? */
1936 	if (!btree_path_node(path, path->level + 1)) {
1937 		btree_path_set_level_up(trans, path);
1938 		return NULL;
1939 	}
1940 
1941 	if (!bch2_btree_node_relock(trans, path, path->level + 1)) {
1942 		__bch2_btree_path_unlock(trans, path);
1943 		path->l[path->level].b		= ERR_PTR(-BCH_ERR_no_btree_node_relock);
1944 		path->l[path->level + 1].b	= ERR_PTR(-BCH_ERR_no_btree_node_relock);
1945 		btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
1946 		trace_and_count(trans->c, trans_restart_relock_next_node, trans, _THIS_IP_, path);
1947 		ret = btree_trans_restart(trans, BCH_ERR_transaction_restart_relock);
1948 		goto err;
1949 	}
1950 
1951 	b = btree_path_node(path, path->level + 1);
1952 
1953 	if (bpos_eq(iter->pos, b->key.k.p)) {
1954 		__btree_path_set_level_up(trans, path, path->level++);
1955 	} else {
1956 		if (btree_lock_want(path, path->level + 1) == BTREE_NODE_UNLOCKED)
1957 			btree_node_unlock(trans, path, path->level + 1);
1958 
1959 		/*
1960 		 * Haven't gotten to the end of the parent node: go back down to
1961 		 * the next child node
1962 		 */
1963 		iter->path = bch2_btree_path_set_pos(trans, iter->path,
1964 					bpos_successor(iter->pos),
1965 					iter->flags & BTREE_ITER_intent,
1966 					btree_iter_ip_allocated(iter));
1967 
1968 		path = btree_iter_path(trans, iter);
1969 		btree_path_set_level_down(trans, path, iter->min_depth);
1970 
1971 		ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
1972 		if (ret)
1973 			goto err;
1974 
1975 		path = btree_iter_path(trans, iter);
1976 		b = path->l[path->level].b;
1977 	}
1978 
1979 	bkey_init(&iter->k);
1980 	iter->k.p = iter->pos = b->key.k.p;
1981 
1982 	iter->path = bch2_btree_path_set_pos(trans, iter->path, b->key.k.p,
1983 					iter->flags & BTREE_ITER_intent,
1984 					btree_iter_ip_allocated(iter));
1985 	btree_path_set_should_be_locked(btree_iter_path(trans, iter));
1986 	EBUG_ON(btree_iter_path(trans, iter)->uptodate);
1987 out:
1988 	bch2_btree_iter_verify_entry_exit(iter);
1989 	bch2_btree_iter_verify(iter);
1990 
1991 	return b;
1992 err:
1993 	b = ERR_PTR(ret);
1994 	goto out;
1995 }
1996 
1997 /* Iterate across keys (in leaf nodes only) */
1998 
1999 inline bool bch2_btree_iter_advance(struct btree_iter *iter)
2000 {
2001 	struct bpos pos = iter->k.p;
2002 	bool ret = !(iter->flags & BTREE_ITER_all_snapshots
2003 		     ? bpos_eq(pos, SPOS_MAX)
2004 		     : bkey_eq(pos, SPOS_MAX));
2005 
2006 	if (ret && !(iter->flags & BTREE_ITER_is_extents))
2007 		pos = bkey_successor(iter, pos);
2008 	bch2_btree_iter_set_pos(iter, pos);
2009 	return ret;
2010 }
2011 
2012 inline bool bch2_btree_iter_rewind(struct btree_iter *iter)
2013 {
2014 	struct bpos pos = bkey_start_pos(&iter->k);
2015 	bool ret = !(iter->flags & BTREE_ITER_all_snapshots
2016 		     ? bpos_eq(pos, POS_MIN)
2017 		     : bkey_eq(pos, POS_MIN));
2018 
2019 	if (ret && !(iter->flags & BTREE_ITER_is_extents))
2020 		pos = bkey_predecessor(iter, pos);
2021 	bch2_btree_iter_set_pos(iter, pos);
2022 	return ret;
2023 }
2024 
2025 static noinline
2026 void bch2_btree_trans_peek_prev_updates(struct btree_trans *trans, struct btree_iter *iter,
2027 					struct bkey_s_c *k)
2028 {
2029 	struct bpos end = path_l(btree_iter_path(trans, iter))->b->data->min_key;
2030 
2031 	trans_for_each_update(trans, i)
2032 		if (!i->key_cache_already_flushed &&
2033 		    i->btree_id == iter->btree_id &&
2034 		    bpos_le(i->k->k.p, iter->pos) &&
2035 		    bpos_ge(i->k->k.p, k->k ? k->k->p : end)) {
2036 			iter->k = i->k->k;
2037 			*k = bkey_i_to_s_c(i->k);
2038 		}
2039 }
2040 
2041 static noinline
2042 void bch2_btree_trans_peek_updates(struct btree_trans *trans, struct btree_iter *iter,
2043 				   struct bkey_s_c *k)
2044 {
2045 	struct btree_path *path = btree_iter_path(trans, iter);
2046 	struct bpos end = path_l(path)->b->key.k.p;
2047 
2048 	trans_for_each_update(trans, i)
2049 		if (!i->key_cache_already_flushed &&
2050 		    i->btree_id == iter->btree_id &&
2051 		    bpos_ge(i->k->k.p, path->pos) &&
2052 		    bpos_le(i->k->k.p, k->k ? k->k->p : end)) {
2053 			iter->k = i->k->k;
2054 			*k = bkey_i_to_s_c(i->k);
2055 		}
2056 }
2057 
2058 static noinline
2059 void bch2_btree_trans_peek_slot_updates(struct btree_trans *trans, struct btree_iter *iter,
2060 					struct bkey_s_c *k)
2061 {
2062 	trans_for_each_update(trans, i)
2063 		if (!i->key_cache_already_flushed &&
2064 		    i->btree_id == iter->btree_id &&
2065 		    bpos_eq(i->k->k.p, iter->pos)) {
2066 			iter->k = i->k->k;
2067 			*k = bkey_i_to_s_c(i->k);
2068 		}
2069 }
2070 
2071 static struct bkey_i *bch2_btree_journal_peek(struct btree_trans *trans,
2072 					      struct btree_iter *iter,
2073 					      struct bpos end_pos)
2074 {
2075 	struct btree_path *path = btree_iter_path(trans, iter);
2076 
2077 	return bch2_journal_keys_peek_upto(trans->c, iter->btree_id,
2078 					   path->level,
2079 					   path->pos,
2080 					   end_pos,
2081 					   &iter->journal_idx);
2082 }
2083 
2084 static noinline
2085 struct bkey_s_c btree_trans_peek_slot_journal(struct btree_trans *trans,
2086 					      struct btree_iter *iter)
2087 {
2088 	struct btree_path *path = btree_iter_path(trans, iter);
2089 	struct bkey_i *k = bch2_btree_journal_peek(trans, iter, path->pos);
2090 
2091 	if (k) {
2092 		iter->k = k->k;
2093 		return bkey_i_to_s_c(k);
2094 	} else {
2095 		return bkey_s_c_null;
2096 	}
2097 }
2098 
2099 static noinline
2100 struct bkey_s_c btree_trans_peek_journal(struct btree_trans *trans,
2101 					 struct btree_iter *iter,
2102 					 struct bkey_s_c k)
2103 {
2104 	struct btree_path *path = btree_iter_path(trans, iter);
2105 	struct bkey_i *next_journal =
2106 		bch2_btree_journal_peek(trans, iter,
2107 				k.k ? k.k->p : path_l(path)->b->key.k.p);
2108 
2109 	if (next_journal) {
2110 		iter->k = next_journal->k;
2111 		k = bkey_i_to_s_c(next_journal);
2112 	}
2113 
2114 	return k;
2115 }
2116 
2117 /*
2118  * Checks btree key cache for key at iter->pos and returns it if present, or
2119  * bkey_s_c_null:
2120  */
2121 static noinline
2122 struct bkey_s_c btree_trans_peek_key_cache(struct btree_iter *iter, struct bpos pos)
2123 {
2124 	struct btree_trans *trans = iter->trans;
2125 	struct bch_fs *c = trans->c;
2126 	struct bkey u;
2127 	struct bkey_s_c k;
2128 	int ret;
2129 
2130 	bch2_trans_verify_not_in_restart(trans);
2131 	bch2_trans_verify_not_unlocked(trans);
2132 
2133 	if ((iter->flags & BTREE_ITER_key_cache_fill) &&
2134 	    bpos_eq(iter->pos, pos))
2135 		return bkey_s_c_null;
2136 
2137 	if (!bch2_btree_key_cache_find(c, iter->btree_id, pos))
2138 		return bkey_s_c_null;
2139 
2140 	if (!iter->key_cache_path)
2141 		iter->key_cache_path = bch2_path_get(trans, iter->btree_id, pos,
2142 						     iter->flags & BTREE_ITER_intent, 0,
2143 						     iter->flags|BTREE_ITER_cached|
2144 						     BTREE_ITER_cached_nofill,
2145 						     _THIS_IP_);
2146 
2147 	iter->key_cache_path = bch2_btree_path_set_pos(trans, iter->key_cache_path, pos,
2148 					iter->flags & BTREE_ITER_intent,
2149 					btree_iter_ip_allocated(iter));
2150 
2151 	ret =   bch2_btree_path_traverse(trans, iter->key_cache_path,
2152 					 iter->flags|BTREE_ITER_cached) ?:
2153 		bch2_btree_path_relock(trans, btree_iter_path(trans, iter), _THIS_IP_);
2154 	if (unlikely(ret))
2155 		return bkey_s_c_err(ret);
2156 
2157 	btree_path_set_should_be_locked(trans->paths + iter->key_cache_path);
2158 
2159 	k = bch2_btree_path_peek_slot(trans->paths + iter->key_cache_path, &u);
2160 	if (k.k && !bkey_err(k)) {
2161 		iter->k = u;
2162 		k.k = &iter->k;
2163 	}
2164 	return k;
2165 }
2166 
2167 static struct bkey_s_c __bch2_btree_iter_peek(struct btree_iter *iter, struct bpos search_key)
2168 {
2169 	struct btree_trans *trans = iter->trans;
2170 	struct bkey_s_c k, k2;
2171 	int ret;
2172 
2173 	EBUG_ON(btree_iter_path(trans, iter)->cached);
2174 	bch2_btree_iter_verify(iter);
2175 
2176 	while (1) {
2177 		struct btree_path_level *l;
2178 
2179 		iter->path = bch2_btree_path_set_pos(trans, iter->path, search_key,
2180 					iter->flags & BTREE_ITER_intent,
2181 					btree_iter_ip_allocated(iter));
2182 
2183 		ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
2184 		if (unlikely(ret)) {
2185 			/* ensure that iter->k is consistent with iter->pos: */
2186 			bch2_btree_iter_set_pos(iter, iter->pos);
2187 			k = bkey_s_c_err(ret);
2188 			goto out;
2189 		}
2190 
2191 		struct btree_path *path = btree_iter_path(trans, iter);
2192 		l = path_l(path);
2193 
2194 		if (unlikely(!l->b)) {
2195 			/* No btree nodes at requested level: */
2196 			bch2_btree_iter_set_pos(iter, SPOS_MAX);
2197 			k = bkey_s_c_null;
2198 			goto out;
2199 		}
2200 
2201 		btree_path_set_should_be_locked(path);
2202 
2203 		k = btree_path_level_peek_all(trans->c, l, &iter->k);
2204 
2205 		if (unlikely(iter->flags & BTREE_ITER_with_key_cache) &&
2206 		    k.k &&
2207 		    (k2 = btree_trans_peek_key_cache(iter, k.k->p)).k) {
2208 			k = k2;
2209 			ret = bkey_err(k);
2210 			if (ret) {
2211 				bch2_btree_iter_set_pos(iter, iter->pos);
2212 				goto out;
2213 			}
2214 		}
2215 
2216 		if (unlikely(iter->flags & BTREE_ITER_with_journal))
2217 			k = btree_trans_peek_journal(trans, iter, k);
2218 
2219 		if (unlikely((iter->flags & BTREE_ITER_with_updates) &&
2220 			     trans->nr_updates))
2221 			bch2_btree_trans_peek_updates(trans, iter, &k);
2222 
2223 		if (k.k && bkey_deleted(k.k)) {
2224 			/*
2225 			 * If we've got a whiteout, and it's after the search
2226 			 * key, advance the search key to the whiteout instead
2227 			 * of just after the whiteout - it might be a btree
2228 			 * whiteout, with a real key at the same position, since
2229 			 * in the btree deleted keys sort before non deleted.
2230 			 */
2231 			search_key = !bpos_eq(search_key, k.k->p)
2232 				? k.k->p
2233 				: bpos_successor(k.k->p);
2234 			continue;
2235 		}
2236 
2237 		if (likely(k.k)) {
2238 			break;
2239 		} else if (likely(!bpos_eq(l->b->key.k.p, SPOS_MAX))) {
2240 			/* Advance to next leaf node: */
2241 			search_key = bpos_successor(l->b->key.k.p);
2242 		} else {
2243 			/* End of btree: */
2244 			bch2_btree_iter_set_pos(iter, SPOS_MAX);
2245 			k = bkey_s_c_null;
2246 			goto out;
2247 		}
2248 	}
2249 out:
2250 	bch2_btree_iter_verify(iter);
2251 
2252 	return k;
2253 }
2254 
2255 /**
2256  * bch2_btree_iter_peek_upto() - returns first key greater than or equal to
2257  * iterator's current position
2258  * @iter:	iterator to peek from
2259  * @end:	search limit: returns keys less than or equal to @end
2260  *
2261  * Returns:	key if found, or an error extractable with bkey_err().
2262  */
2263 struct bkey_s_c bch2_btree_iter_peek_upto(struct btree_iter *iter, struct bpos end)
2264 {
2265 	struct btree_trans *trans = iter->trans;
2266 	struct bpos search_key = btree_iter_search_key(iter);
2267 	struct bkey_s_c k;
2268 	struct bpos iter_pos;
2269 	int ret;
2270 
2271 	bch2_trans_verify_not_unlocked(trans);
2272 	EBUG_ON((iter->flags & BTREE_ITER_filter_snapshots) && bkey_eq(end, POS_MAX));
2273 
2274 	if (iter->update_path) {
2275 		bch2_path_put_nokeep(trans, iter->update_path,
2276 				     iter->flags & BTREE_ITER_intent);
2277 		iter->update_path = 0;
2278 	}
2279 
2280 	bch2_btree_iter_verify_entry_exit(iter);
2281 
2282 	while (1) {
2283 		k = __bch2_btree_iter_peek(iter, search_key);
2284 		if (unlikely(!k.k))
2285 			goto end;
2286 		if (unlikely(bkey_err(k)))
2287 			goto out_no_locked;
2288 
2289 		/*
2290 		 * We need to check against @end before FILTER_SNAPSHOTS because
2291 		 * if we get to a different inode that requested we might be
2292 		 * seeing keys for a different snapshot tree that will all be
2293 		 * filtered out.
2294 		 *
2295 		 * But we can't do the full check here, because bkey_start_pos()
2296 		 * isn't monotonically increasing before FILTER_SNAPSHOTS, and
2297 		 * that's what we check against in extents mode:
2298 		 */
2299 		if (unlikely(!(iter->flags & BTREE_ITER_is_extents)
2300 			     ? bkey_gt(k.k->p, end)
2301 			     : k.k->p.inode > end.inode))
2302 			goto end;
2303 
2304 		if (iter->update_path &&
2305 		    !bkey_eq(trans->paths[iter->update_path].pos, k.k->p)) {
2306 			bch2_path_put_nokeep(trans, iter->update_path,
2307 					     iter->flags & BTREE_ITER_intent);
2308 			iter->update_path = 0;
2309 		}
2310 
2311 		if ((iter->flags & BTREE_ITER_filter_snapshots) &&
2312 		    (iter->flags & BTREE_ITER_intent) &&
2313 		    !(iter->flags & BTREE_ITER_is_extents) &&
2314 		    !iter->update_path) {
2315 			struct bpos pos = k.k->p;
2316 
2317 			if (pos.snapshot < iter->snapshot) {
2318 				search_key = bpos_successor(k.k->p);
2319 				continue;
2320 			}
2321 
2322 			pos.snapshot = iter->snapshot;
2323 
2324 			/*
2325 			 * advance, same as on exit for iter->path, but only up
2326 			 * to snapshot
2327 			 */
2328 			__btree_path_get(trans->paths + iter->path, iter->flags & BTREE_ITER_intent);
2329 			iter->update_path = iter->path;
2330 
2331 			iter->update_path = bch2_btree_path_set_pos(trans,
2332 						iter->update_path, pos,
2333 						iter->flags & BTREE_ITER_intent,
2334 						_THIS_IP_);
2335 			ret = bch2_btree_path_traverse(trans, iter->update_path, iter->flags);
2336 			if (unlikely(ret)) {
2337 				k = bkey_s_c_err(ret);
2338 				goto out_no_locked;
2339 			}
2340 		}
2341 
2342 		/*
2343 		 * We can never have a key in a leaf node at POS_MAX, so
2344 		 * we don't have to check these successor() calls:
2345 		 */
2346 		if ((iter->flags & BTREE_ITER_filter_snapshots) &&
2347 		    !bch2_snapshot_is_ancestor(trans->c,
2348 					       iter->snapshot,
2349 					       k.k->p.snapshot)) {
2350 			search_key = bpos_successor(k.k->p);
2351 			continue;
2352 		}
2353 
2354 		if (bkey_whiteout(k.k) &&
2355 		    !(iter->flags & BTREE_ITER_all_snapshots)) {
2356 			search_key = bkey_successor(iter, k.k->p);
2357 			continue;
2358 		}
2359 
2360 		/*
2361 		 * iter->pos should be mononotically increasing, and always be
2362 		 * equal to the key we just returned - except extents can
2363 		 * straddle iter->pos:
2364 		 */
2365 		if (!(iter->flags & BTREE_ITER_is_extents))
2366 			iter_pos = k.k->p;
2367 		else
2368 			iter_pos = bkey_max(iter->pos, bkey_start_pos(k.k));
2369 
2370 		if (unlikely(!(iter->flags & BTREE_ITER_is_extents)
2371 			     ? bkey_gt(iter_pos, end)
2372 			     : bkey_ge(iter_pos, end)))
2373 			goto end;
2374 
2375 		break;
2376 	}
2377 
2378 	iter->pos = iter_pos;
2379 
2380 	iter->path = bch2_btree_path_set_pos(trans, iter->path, k.k->p,
2381 				iter->flags & BTREE_ITER_intent,
2382 				btree_iter_ip_allocated(iter));
2383 
2384 	btree_path_set_should_be_locked(btree_iter_path(trans, iter));
2385 out_no_locked:
2386 	if (iter->update_path) {
2387 		ret = bch2_btree_path_relock(trans, trans->paths + iter->update_path, _THIS_IP_);
2388 		if (unlikely(ret))
2389 			k = bkey_s_c_err(ret);
2390 		else
2391 			btree_path_set_should_be_locked(trans->paths + iter->update_path);
2392 	}
2393 
2394 	if (!(iter->flags & BTREE_ITER_all_snapshots))
2395 		iter->pos.snapshot = iter->snapshot;
2396 
2397 	ret = bch2_btree_iter_verify_ret(iter, k);
2398 	if (unlikely(ret)) {
2399 		bch2_btree_iter_set_pos(iter, iter->pos);
2400 		k = bkey_s_c_err(ret);
2401 	}
2402 
2403 	bch2_btree_iter_verify_entry_exit(iter);
2404 
2405 	return k;
2406 end:
2407 	bch2_btree_iter_set_pos(iter, end);
2408 	k = bkey_s_c_null;
2409 	goto out_no_locked;
2410 }
2411 
2412 /**
2413  * bch2_btree_iter_next() - returns first key greater than iterator's current
2414  * position
2415  * @iter:	iterator to peek from
2416  *
2417  * Returns:	key if found, or an error extractable with bkey_err().
2418  */
2419 struct bkey_s_c bch2_btree_iter_next(struct btree_iter *iter)
2420 {
2421 	if (!bch2_btree_iter_advance(iter))
2422 		return bkey_s_c_null;
2423 
2424 	return bch2_btree_iter_peek(iter);
2425 }
2426 
2427 /**
2428  * bch2_btree_iter_peek_prev() - returns first key less than or equal to
2429  * iterator's current position
2430  * @iter:	iterator to peek from
2431  *
2432  * Returns:	key if found, or an error extractable with bkey_err().
2433  */
2434 struct bkey_s_c bch2_btree_iter_peek_prev(struct btree_iter *iter)
2435 {
2436 	struct btree_trans *trans = iter->trans;
2437 	struct bpos search_key = iter->pos;
2438 	struct bkey_s_c k;
2439 	struct bkey saved_k;
2440 	const struct bch_val *saved_v;
2441 	btree_path_idx_t saved_path = 0;
2442 	int ret;
2443 
2444 	bch2_trans_verify_not_unlocked(trans);
2445 	EBUG_ON(btree_iter_path(trans, iter)->cached ||
2446 		btree_iter_path(trans, iter)->level);
2447 
2448 	if (iter->flags & BTREE_ITER_with_journal)
2449 		return bkey_s_c_err(-BCH_ERR_btree_iter_with_journal_not_supported);
2450 
2451 	bch2_btree_iter_verify(iter);
2452 	bch2_btree_iter_verify_entry_exit(iter);
2453 
2454 	if (iter->flags & BTREE_ITER_filter_snapshots)
2455 		search_key.snapshot = U32_MAX;
2456 
2457 	while (1) {
2458 		iter->path = bch2_btree_path_set_pos(trans, iter->path, search_key,
2459 						iter->flags & BTREE_ITER_intent,
2460 						btree_iter_ip_allocated(iter));
2461 
2462 		ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
2463 		if (unlikely(ret)) {
2464 			/* ensure that iter->k is consistent with iter->pos: */
2465 			bch2_btree_iter_set_pos(iter, iter->pos);
2466 			k = bkey_s_c_err(ret);
2467 			goto out_no_locked;
2468 		}
2469 
2470 		struct btree_path *path = btree_iter_path(trans, iter);
2471 
2472 		k = btree_path_level_peek(trans, path, &path->l[0], &iter->k);
2473 		if (!k.k ||
2474 		    ((iter->flags & BTREE_ITER_is_extents)
2475 		     ? bpos_ge(bkey_start_pos(k.k), search_key)
2476 		     : bpos_gt(k.k->p, search_key)))
2477 			k = btree_path_level_prev(trans, path, &path->l[0], &iter->k);
2478 
2479 		if (unlikely((iter->flags & BTREE_ITER_with_updates) &&
2480 			     trans->nr_updates))
2481 			bch2_btree_trans_peek_prev_updates(trans, iter, &k);
2482 
2483 		if (likely(k.k)) {
2484 			if (iter->flags & BTREE_ITER_filter_snapshots) {
2485 				if (k.k->p.snapshot == iter->snapshot)
2486 					goto got_key;
2487 
2488 				/*
2489 				 * If we have a saved candidate, and we're no
2490 				 * longer at the same _key_ (not pos), return
2491 				 * that candidate
2492 				 */
2493 				if (saved_path && !bkey_eq(k.k->p, saved_k.p)) {
2494 					bch2_path_put_nokeep(trans, iter->path,
2495 						      iter->flags & BTREE_ITER_intent);
2496 					iter->path = saved_path;
2497 					saved_path = 0;
2498 					iter->k	= saved_k;
2499 					k.v	= saved_v;
2500 					goto got_key;
2501 				}
2502 
2503 				if (bch2_snapshot_is_ancestor(trans->c,
2504 							      iter->snapshot,
2505 							      k.k->p.snapshot)) {
2506 					if (saved_path)
2507 						bch2_path_put_nokeep(trans, saved_path,
2508 						      iter->flags & BTREE_ITER_intent);
2509 					saved_path = btree_path_clone(trans, iter->path,
2510 								iter->flags & BTREE_ITER_intent,
2511 								_THIS_IP_);
2512 					path = btree_iter_path(trans, iter);
2513 					saved_k = *k.k;
2514 					saved_v = k.v;
2515 				}
2516 
2517 				search_key = bpos_predecessor(k.k->p);
2518 				continue;
2519 			}
2520 got_key:
2521 			if (bkey_whiteout(k.k) &&
2522 			    !(iter->flags & BTREE_ITER_all_snapshots)) {
2523 				search_key = bkey_predecessor(iter, k.k->p);
2524 				if (iter->flags & BTREE_ITER_filter_snapshots)
2525 					search_key.snapshot = U32_MAX;
2526 				continue;
2527 			}
2528 
2529 			btree_path_set_should_be_locked(path);
2530 			break;
2531 		} else if (likely(!bpos_eq(path->l[0].b->data->min_key, POS_MIN))) {
2532 			/* Advance to previous leaf node: */
2533 			search_key = bpos_predecessor(path->l[0].b->data->min_key);
2534 		} else {
2535 			/* Start of btree: */
2536 			bch2_btree_iter_set_pos(iter, POS_MIN);
2537 			k = bkey_s_c_null;
2538 			goto out_no_locked;
2539 		}
2540 	}
2541 
2542 	EBUG_ON(bkey_gt(bkey_start_pos(k.k), iter->pos));
2543 
2544 	/* Extents can straddle iter->pos: */
2545 	if (bkey_lt(k.k->p, iter->pos))
2546 		iter->pos = k.k->p;
2547 
2548 	if (iter->flags & BTREE_ITER_filter_snapshots)
2549 		iter->pos.snapshot = iter->snapshot;
2550 out_no_locked:
2551 	if (saved_path)
2552 		bch2_path_put_nokeep(trans, saved_path, iter->flags & BTREE_ITER_intent);
2553 
2554 	bch2_btree_iter_verify_entry_exit(iter);
2555 	bch2_btree_iter_verify(iter);
2556 
2557 	return k;
2558 }
2559 
2560 /**
2561  * bch2_btree_iter_prev() - returns first key less than iterator's current
2562  * position
2563  * @iter:	iterator to peek from
2564  *
2565  * Returns:	key if found, or an error extractable with bkey_err().
2566  */
2567 struct bkey_s_c bch2_btree_iter_prev(struct btree_iter *iter)
2568 {
2569 	if (!bch2_btree_iter_rewind(iter))
2570 		return bkey_s_c_null;
2571 
2572 	return bch2_btree_iter_peek_prev(iter);
2573 }
2574 
2575 struct bkey_s_c bch2_btree_iter_peek_slot(struct btree_iter *iter)
2576 {
2577 	struct btree_trans *trans = iter->trans;
2578 	struct bpos search_key;
2579 	struct bkey_s_c k;
2580 	int ret;
2581 
2582 	bch2_trans_verify_not_unlocked(trans);
2583 	bch2_btree_iter_verify(iter);
2584 	bch2_btree_iter_verify_entry_exit(iter);
2585 	EBUG_ON(btree_iter_path(trans, iter)->level && (iter->flags & BTREE_ITER_with_key_cache));
2586 
2587 	/* extents can't span inode numbers: */
2588 	if ((iter->flags & BTREE_ITER_is_extents) &&
2589 	    unlikely(iter->pos.offset == KEY_OFFSET_MAX)) {
2590 		if (iter->pos.inode == KEY_INODE_MAX)
2591 			return bkey_s_c_null;
2592 
2593 		bch2_btree_iter_set_pos(iter, bpos_nosnap_successor(iter->pos));
2594 	}
2595 
2596 	search_key = btree_iter_search_key(iter);
2597 	iter->path = bch2_btree_path_set_pos(trans, iter->path, search_key,
2598 					iter->flags & BTREE_ITER_intent,
2599 					btree_iter_ip_allocated(iter));
2600 
2601 	ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
2602 	if (unlikely(ret)) {
2603 		k = bkey_s_c_err(ret);
2604 		goto out_no_locked;
2605 	}
2606 
2607 	if ((iter->flags & BTREE_ITER_cached) ||
2608 	    !(iter->flags & (BTREE_ITER_is_extents|BTREE_ITER_filter_snapshots))) {
2609 		k = bkey_s_c_null;
2610 
2611 		if (unlikely((iter->flags & BTREE_ITER_with_updates) &&
2612 			     trans->nr_updates)) {
2613 			bch2_btree_trans_peek_slot_updates(trans, iter, &k);
2614 			if (k.k)
2615 				goto out;
2616 		}
2617 
2618 		if (unlikely(iter->flags & BTREE_ITER_with_journal) &&
2619 		    (k = btree_trans_peek_slot_journal(trans, iter)).k)
2620 			goto out;
2621 
2622 		if (unlikely(iter->flags & BTREE_ITER_with_key_cache) &&
2623 		    (k = btree_trans_peek_key_cache(iter, iter->pos)).k) {
2624 			if (!bkey_err(k))
2625 				iter->k = *k.k;
2626 			/* We're not returning a key from iter->path: */
2627 			goto out_no_locked;
2628 		}
2629 
2630 		k = bch2_btree_path_peek_slot(trans->paths + iter->path, &iter->k);
2631 		if (unlikely(!k.k))
2632 			goto out_no_locked;
2633 	} else {
2634 		struct bpos next;
2635 		struct bpos end = iter->pos;
2636 
2637 		if (iter->flags & BTREE_ITER_is_extents)
2638 			end.offset = U64_MAX;
2639 
2640 		EBUG_ON(btree_iter_path(trans, iter)->level);
2641 
2642 		if (iter->flags & BTREE_ITER_intent) {
2643 			struct btree_iter iter2;
2644 
2645 			bch2_trans_copy_iter(&iter2, iter);
2646 			k = bch2_btree_iter_peek_upto(&iter2, end);
2647 
2648 			if (k.k && !bkey_err(k)) {
2649 				swap(iter->key_cache_path, iter2.key_cache_path);
2650 				iter->k = iter2.k;
2651 				k.k = &iter->k;
2652 			}
2653 			bch2_trans_iter_exit(trans, &iter2);
2654 		} else {
2655 			struct bpos pos = iter->pos;
2656 
2657 			k = bch2_btree_iter_peek_upto(iter, end);
2658 			if (unlikely(bkey_err(k)))
2659 				bch2_btree_iter_set_pos(iter, pos);
2660 			else
2661 				iter->pos = pos;
2662 		}
2663 
2664 		if (unlikely(bkey_err(k)))
2665 			goto out_no_locked;
2666 
2667 		next = k.k ? bkey_start_pos(k.k) : POS_MAX;
2668 
2669 		if (bkey_lt(iter->pos, next)) {
2670 			bkey_init(&iter->k);
2671 			iter->k.p = iter->pos;
2672 
2673 			if (iter->flags & BTREE_ITER_is_extents) {
2674 				bch2_key_resize(&iter->k,
2675 						min_t(u64, KEY_SIZE_MAX,
2676 						      (next.inode == iter->pos.inode
2677 						       ? next.offset
2678 						       : KEY_OFFSET_MAX) -
2679 						      iter->pos.offset));
2680 				EBUG_ON(!iter->k.size);
2681 			}
2682 
2683 			k = (struct bkey_s_c) { &iter->k, NULL };
2684 		}
2685 	}
2686 out:
2687 	btree_path_set_should_be_locked(btree_iter_path(trans, iter));
2688 out_no_locked:
2689 	bch2_btree_iter_verify_entry_exit(iter);
2690 	bch2_btree_iter_verify(iter);
2691 	ret = bch2_btree_iter_verify_ret(iter, k);
2692 	if (unlikely(ret))
2693 		return bkey_s_c_err(ret);
2694 
2695 	return k;
2696 }
2697 
2698 struct bkey_s_c bch2_btree_iter_next_slot(struct btree_iter *iter)
2699 {
2700 	if (!bch2_btree_iter_advance(iter))
2701 		return bkey_s_c_null;
2702 
2703 	return bch2_btree_iter_peek_slot(iter);
2704 }
2705 
2706 struct bkey_s_c bch2_btree_iter_prev_slot(struct btree_iter *iter)
2707 {
2708 	if (!bch2_btree_iter_rewind(iter))
2709 		return bkey_s_c_null;
2710 
2711 	return bch2_btree_iter_peek_slot(iter);
2712 }
2713 
2714 struct bkey_s_c bch2_btree_iter_peek_and_restart_outlined(struct btree_iter *iter)
2715 {
2716 	struct bkey_s_c k;
2717 
2718 	while (btree_trans_too_many_iters(iter->trans) ||
2719 	       (k = bch2_btree_iter_peek_type(iter, iter->flags),
2720 		bch2_err_matches(bkey_err(k), BCH_ERR_transaction_restart)))
2721 		bch2_trans_begin(iter->trans);
2722 
2723 	return k;
2724 }
2725 
2726 /* new transactional stuff: */
2727 
2728 #ifdef CONFIG_BCACHEFS_DEBUG
2729 static void btree_trans_verify_sorted_refs(struct btree_trans *trans)
2730 {
2731 	struct btree_path *path;
2732 	unsigned i;
2733 
2734 	BUG_ON(trans->nr_sorted != bitmap_weight(trans->paths_allocated, trans->nr_paths) - 1);
2735 
2736 	trans_for_each_path(trans, path, i) {
2737 		BUG_ON(path->sorted_idx >= trans->nr_sorted);
2738 		BUG_ON(trans->sorted[path->sorted_idx] != i);
2739 	}
2740 
2741 	for (i = 0; i < trans->nr_sorted; i++) {
2742 		unsigned idx = trans->sorted[i];
2743 
2744 		BUG_ON(!test_bit(idx, trans->paths_allocated));
2745 		BUG_ON(trans->paths[idx].sorted_idx != i);
2746 	}
2747 }
2748 
2749 static void btree_trans_verify_sorted(struct btree_trans *trans)
2750 {
2751 	struct btree_path *path, *prev = NULL;
2752 	struct trans_for_each_path_inorder_iter iter;
2753 
2754 	if (!bch2_debug_check_iterators)
2755 		return;
2756 
2757 	trans_for_each_path_inorder(trans, path, iter) {
2758 		if (prev && btree_path_cmp(prev, path) > 0) {
2759 			__bch2_dump_trans_paths_updates(trans, true);
2760 			panic("trans paths out of order!\n");
2761 		}
2762 		prev = path;
2763 	}
2764 }
2765 #else
2766 static inline void btree_trans_verify_sorted_refs(struct btree_trans *trans) {}
2767 static inline void btree_trans_verify_sorted(struct btree_trans *trans) {}
2768 #endif
2769 
2770 void __bch2_btree_trans_sort_paths(struct btree_trans *trans)
2771 {
2772 	int i, l = 0, r = trans->nr_sorted, inc = 1;
2773 	bool swapped;
2774 
2775 	btree_trans_verify_sorted_refs(trans);
2776 
2777 	if (trans->paths_sorted)
2778 		goto out;
2779 
2780 	/*
2781 	 * Cocktail shaker sort: this is efficient because iterators will be
2782 	 * mostly sorted.
2783 	 */
2784 	do {
2785 		swapped = false;
2786 
2787 		for (i = inc > 0 ? l : r - 2;
2788 		     i + 1 < r && i >= l;
2789 		     i += inc) {
2790 			if (btree_path_cmp(trans->paths + trans->sorted[i],
2791 					   trans->paths + trans->sorted[i + 1]) > 0) {
2792 				swap(trans->sorted[i], trans->sorted[i + 1]);
2793 				trans->paths[trans->sorted[i]].sorted_idx = i;
2794 				trans->paths[trans->sorted[i + 1]].sorted_idx = i + 1;
2795 				swapped = true;
2796 			}
2797 		}
2798 
2799 		if (inc > 0)
2800 			--r;
2801 		else
2802 			l++;
2803 		inc = -inc;
2804 	} while (swapped);
2805 
2806 	trans->paths_sorted = true;
2807 out:
2808 	btree_trans_verify_sorted(trans);
2809 }
2810 
2811 static inline void btree_path_list_remove(struct btree_trans *trans,
2812 					  struct btree_path *path)
2813 {
2814 	EBUG_ON(path->sorted_idx >= trans->nr_sorted);
2815 #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
2816 	trans->nr_sorted--;
2817 	memmove_u64s_down_small(trans->sorted + path->sorted_idx,
2818 				trans->sorted + path->sorted_idx + 1,
2819 				DIV_ROUND_UP(trans->nr_sorted - path->sorted_idx,
2820 					     sizeof(u64) / sizeof(btree_path_idx_t)));
2821 #else
2822 	array_remove_item(trans->sorted, trans->nr_sorted, path->sorted_idx);
2823 #endif
2824 	for (unsigned i = path->sorted_idx; i < trans->nr_sorted; i++)
2825 		trans->paths[trans->sorted[i]].sorted_idx = i;
2826 }
2827 
2828 static inline void btree_path_list_add(struct btree_trans *trans,
2829 				       btree_path_idx_t pos,
2830 				       btree_path_idx_t path_idx)
2831 {
2832 	struct btree_path *path = trans->paths + path_idx;
2833 
2834 	path->sorted_idx = pos ? trans->paths[pos].sorted_idx + 1 : trans->nr_sorted;
2835 
2836 #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
2837 	memmove_u64s_up_small(trans->sorted + path->sorted_idx + 1,
2838 			      trans->sorted + path->sorted_idx,
2839 			      DIV_ROUND_UP(trans->nr_sorted - path->sorted_idx,
2840 					   sizeof(u64) / sizeof(btree_path_idx_t)));
2841 	trans->nr_sorted++;
2842 	trans->sorted[path->sorted_idx] = path_idx;
2843 #else
2844 	array_insert_item(trans->sorted, trans->nr_sorted, path->sorted_idx, path_idx);
2845 #endif
2846 
2847 	for (unsigned i = path->sorted_idx; i < trans->nr_sorted; i++)
2848 		trans->paths[trans->sorted[i]].sorted_idx = i;
2849 
2850 	btree_trans_verify_sorted_refs(trans);
2851 }
2852 
2853 void bch2_trans_iter_exit(struct btree_trans *trans, struct btree_iter *iter)
2854 {
2855 	if (iter->update_path)
2856 		bch2_path_put_nokeep(trans, iter->update_path,
2857 			      iter->flags & BTREE_ITER_intent);
2858 	if (iter->path)
2859 		bch2_path_put(trans, iter->path,
2860 			      iter->flags & BTREE_ITER_intent);
2861 	if (iter->key_cache_path)
2862 		bch2_path_put(trans, iter->key_cache_path,
2863 			      iter->flags & BTREE_ITER_intent);
2864 	iter->path		= 0;
2865 	iter->update_path	= 0;
2866 	iter->key_cache_path	= 0;
2867 	iter->trans		= NULL;
2868 }
2869 
2870 void bch2_trans_iter_init_outlined(struct btree_trans *trans,
2871 			  struct btree_iter *iter,
2872 			  enum btree_id btree_id, struct bpos pos,
2873 			  unsigned flags)
2874 {
2875 	bch2_trans_iter_init_common(trans, iter, btree_id, pos, 0, 0,
2876 			       bch2_btree_iter_flags(trans, btree_id, flags),
2877 			       _RET_IP_);
2878 }
2879 
2880 void bch2_trans_node_iter_init(struct btree_trans *trans,
2881 			       struct btree_iter *iter,
2882 			       enum btree_id btree_id,
2883 			       struct bpos pos,
2884 			       unsigned locks_want,
2885 			       unsigned depth,
2886 			       unsigned flags)
2887 {
2888 	flags |= BTREE_ITER_not_extents;
2889 	flags |= BTREE_ITER_snapshot_field;
2890 	flags |= BTREE_ITER_all_snapshots;
2891 
2892 	bch2_trans_iter_init_common(trans, iter, btree_id, pos, locks_want, depth,
2893 			       __bch2_btree_iter_flags(trans, btree_id, flags),
2894 			       _RET_IP_);
2895 
2896 	iter->min_depth	= depth;
2897 
2898 	struct btree_path *path = btree_iter_path(trans, iter);
2899 	BUG_ON(path->locks_want	 < min(locks_want, BTREE_MAX_DEPTH));
2900 	BUG_ON(path->level	!= depth);
2901 	BUG_ON(iter->min_depth	!= depth);
2902 }
2903 
2904 void bch2_trans_copy_iter(struct btree_iter *dst, struct btree_iter *src)
2905 {
2906 	struct btree_trans *trans = src->trans;
2907 
2908 	*dst = *src;
2909 #ifdef TRACK_PATH_ALLOCATED
2910 	dst->ip_allocated = _RET_IP_;
2911 #endif
2912 	if (src->path)
2913 		__btree_path_get(trans->paths + src->path, src->flags & BTREE_ITER_intent);
2914 	if (src->update_path)
2915 		__btree_path_get(trans->paths + src->update_path, src->flags & BTREE_ITER_intent);
2916 	dst->key_cache_path = 0;
2917 }
2918 
2919 void *__bch2_trans_kmalloc(struct btree_trans *trans, size_t size)
2920 {
2921 	struct bch_fs *c = trans->c;
2922 	unsigned new_top = trans->mem_top + size;
2923 	unsigned old_bytes = trans->mem_bytes;
2924 	unsigned new_bytes = roundup_pow_of_two(new_top);
2925 	int ret;
2926 	void *new_mem;
2927 	void *p;
2928 
2929 	WARN_ON_ONCE(new_bytes > BTREE_TRANS_MEM_MAX);
2930 
2931 	struct btree_transaction_stats *s = btree_trans_stats(trans);
2932 	s->max_mem = max(s->max_mem, new_bytes);
2933 
2934 	if (trans->used_mempool) {
2935 		if (trans->mem_bytes >= new_bytes)
2936 			goto out_change_top;
2937 
2938 		/* No more space from mempool item, need malloc new one */
2939 		new_mem = kmalloc(new_bytes, GFP_NOWAIT|__GFP_NOWARN);
2940 		if (unlikely(!new_mem)) {
2941 			bch2_trans_unlock(trans);
2942 
2943 			new_mem = kmalloc(new_bytes, GFP_KERNEL);
2944 			if (!new_mem)
2945 				return ERR_PTR(-BCH_ERR_ENOMEM_trans_kmalloc);
2946 
2947 			ret = bch2_trans_relock(trans);
2948 			if (ret) {
2949 				kfree(new_mem);
2950 				return ERR_PTR(ret);
2951 			}
2952 		}
2953 		memcpy(new_mem, trans->mem, trans->mem_top);
2954 		trans->used_mempool = false;
2955 		mempool_free(trans->mem, &c->btree_trans_mem_pool);
2956 		goto out_new_mem;
2957 	}
2958 
2959 	new_mem = krealloc(trans->mem, new_bytes, GFP_NOWAIT|__GFP_NOWARN);
2960 	if (unlikely(!new_mem)) {
2961 		bch2_trans_unlock(trans);
2962 
2963 		new_mem = krealloc(trans->mem, new_bytes, GFP_KERNEL);
2964 		if (!new_mem && new_bytes <= BTREE_TRANS_MEM_MAX) {
2965 			new_mem = mempool_alloc(&c->btree_trans_mem_pool, GFP_KERNEL);
2966 			new_bytes = BTREE_TRANS_MEM_MAX;
2967 			memcpy(new_mem, trans->mem, trans->mem_top);
2968 			trans->used_mempool = true;
2969 			kfree(trans->mem);
2970 		}
2971 
2972 		if (!new_mem)
2973 			return ERR_PTR(-BCH_ERR_ENOMEM_trans_kmalloc);
2974 
2975 		trans->mem = new_mem;
2976 		trans->mem_bytes = new_bytes;
2977 
2978 		ret = bch2_trans_relock(trans);
2979 		if (ret)
2980 			return ERR_PTR(ret);
2981 	}
2982 out_new_mem:
2983 	trans->mem = new_mem;
2984 	trans->mem_bytes = new_bytes;
2985 
2986 	if (old_bytes) {
2987 		trace_and_count(c, trans_restart_mem_realloced, trans, _RET_IP_, new_bytes);
2988 		return ERR_PTR(btree_trans_restart(trans, BCH_ERR_transaction_restart_mem_realloced));
2989 	}
2990 out_change_top:
2991 	p = trans->mem + trans->mem_top;
2992 	trans->mem_top += size;
2993 	memset(p, 0, size);
2994 	return p;
2995 }
2996 
2997 static inline void check_srcu_held_too_long(struct btree_trans *trans)
2998 {
2999 	WARN(trans->srcu_held && time_after(jiffies, trans->srcu_lock_time + HZ * 10),
3000 	     "btree trans held srcu lock (delaying memory reclaim) for %lu seconds",
3001 	     (jiffies - trans->srcu_lock_time) / HZ);
3002 }
3003 
3004 void bch2_trans_srcu_unlock(struct btree_trans *trans)
3005 {
3006 	if (trans->srcu_held) {
3007 		struct bch_fs *c = trans->c;
3008 		struct btree_path *path;
3009 		unsigned i;
3010 
3011 		trans_for_each_path(trans, path, i)
3012 			if (path->cached && !btree_node_locked(path, 0))
3013 				path->l[0].b = ERR_PTR(-BCH_ERR_no_btree_node_srcu_reset);
3014 
3015 		check_srcu_held_too_long(trans);
3016 		srcu_read_unlock(&c->btree_trans_barrier, trans->srcu_idx);
3017 		trans->srcu_held = false;
3018 	}
3019 }
3020 
3021 static void bch2_trans_srcu_lock(struct btree_trans *trans)
3022 {
3023 	if (!trans->srcu_held) {
3024 		trans->srcu_idx = srcu_read_lock(&trans->c->btree_trans_barrier);
3025 		trans->srcu_lock_time	= jiffies;
3026 		trans->srcu_held = true;
3027 	}
3028 }
3029 
3030 /**
3031  * bch2_trans_begin() - reset a transaction after a interrupted attempt
3032  * @trans: transaction to reset
3033  *
3034  * Returns:	current restart counter, to be used with trans_was_restarted()
3035  *
3036  * While iterating over nodes or updating nodes a attempt to lock a btree node
3037  * may return BCH_ERR_transaction_restart when the trylock fails. When this
3038  * occurs bch2_trans_begin() should be called and the transaction retried.
3039  */
3040 u32 bch2_trans_begin(struct btree_trans *trans)
3041 {
3042 	struct btree_path *path;
3043 	unsigned i;
3044 	u64 now;
3045 
3046 	bch2_trans_reset_updates(trans);
3047 
3048 	trans->restart_count++;
3049 	trans->mem_top			= 0;
3050 	trans->journal_entries		= NULL;
3051 
3052 	trans_for_each_path(trans, path, i) {
3053 		path->should_be_locked = false;
3054 
3055 		/*
3056 		 * If the transaction wasn't restarted, we're presuming to be
3057 		 * doing something new: dont keep iterators excpt the ones that
3058 		 * are in use - except for the subvolumes btree:
3059 		 */
3060 		if (!trans->restarted && path->btree_id != BTREE_ID_subvolumes)
3061 			path->preserve = false;
3062 
3063 		/*
3064 		 * XXX: we probably shouldn't be doing this if the transaction
3065 		 * was restarted, but currently we still overflow transaction
3066 		 * iterators if we do that
3067 		 */
3068 		if (!path->ref && !path->preserve)
3069 			__bch2_path_free(trans, i);
3070 		else
3071 			path->preserve = false;
3072 	}
3073 
3074 	now = local_clock();
3075 
3076 	if (!IS_ENABLED(CONFIG_BCACHEFS_NO_LATENCY_ACCT) &&
3077 	    time_after64(now, trans->last_begin_time + 10))
3078 		__bch2_time_stats_update(&btree_trans_stats(trans)->duration,
3079 					 trans->last_begin_time, now);
3080 
3081 	if (!trans->restarted &&
3082 	    (need_resched() ||
3083 	     time_after64(now, trans->last_begin_time + BTREE_TRANS_MAX_LOCK_HOLD_TIME_NS))) {
3084 		bch2_trans_unlock(trans);
3085 		cond_resched();
3086 		now = local_clock();
3087 	}
3088 	trans->last_begin_time = now;
3089 
3090 	if (unlikely(trans->srcu_held &&
3091 		     time_after(jiffies, trans->srcu_lock_time + msecs_to_jiffies(10))))
3092 		bch2_trans_srcu_unlock(trans);
3093 
3094 	trans->last_begin_ip = _RET_IP_;
3095 	trans->locked  = true;
3096 
3097 	if (trans->restarted) {
3098 		bch2_btree_path_traverse_all(trans);
3099 		trans->notrace_relock_fail = false;
3100 	}
3101 
3102 	bch2_trans_verify_not_unlocked(trans);
3103 	return trans->restart_count;
3104 }
3105 
3106 const char *bch2_btree_transaction_fns[BCH_TRANSACTIONS_NR] = { "(unknown)" };
3107 
3108 unsigned bch2_trans_get_fn_idx(const char *fn)
3109 {
3110 	for (unsigned i = 0; i < ARRAY_SIZE(bch2_btree_transaction_fns); i++)
3111 		if (!bch2_btree_transaction_fns[i] ||
3112 		    bch2_btree_transaction_fns[i] == fn) {
3113 			bch2_btree_transaction_fns[i] = fn;
3114 			return i;
3115 		}
3116 
3117 	pr_warn_once("BCH_TRANSACTIONS_NR not big enough!");
3118 	return 0;
3119 }
3120 
3121 struct btree_trans *__bch2_trans_get(struct bch_fs *c, unsigned fn_idx)
3122 	__acquires(&c->btree_trans_barrier)
3123 {
3124 	struct btree_trans *trans;
3125 
3126 	if (IS_ENABLED(__KERNEL__)) {
3127 		trans = this_cpu_xchg(c->btree_trans_bufs->trans, NULL);
3128 		if (trans) {
3129 			memset(trans, 0, offsetof(struct btree_trans, list));
3130 			goto got_trans;
3131 		}
3132 	}
3133 
3134 	trans = mempool_alloc(&c->btree_trans_pool, GFP_NOFS);
3135 	memset(trans, 0, sizeof(*trans));
3136 	closure_init_stack(&trans->ref);
3137 
3138 	seqmutex_lock(&c->btree_trans_lock);
3139 	if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG)) {
3140 		struct btree_trans *pos;
3141 		pid_t pid = current->pid;
3142 
3143 		trans->locking_wait.task = current;
3144 
3145 		list_for_each_entry(pos, &c->btree_trans_list, list) {
3146 			struct task_struct *pos_task = READ_ONCE(pos->locking_wait.task);
3147 			/*
3148 			 * We'd much prefer to be stricter here and completely
3149 			 * disallow multiple btree_trans in the same thread -
3150 			 * but the data move path calls bch2_write when we
3151 			 * already have a btree_trans initialized.
3152 			 */
3153 			BUG_ON(pos_task &&
3154 			       pid == pos_task->pid &&
3155 			       pos->locked);
3156 
3157 			if (pos_task && pid < pos_task->pid) {
3158 				list_add_tail(&trans->list, &pos->list);
3159 				goto list_add_done;
3160 			}
3161 		}
3162 	}
3163 	list_add_tail(&trans->list, &c->btree_trans_list);
3164 list_add_done:
3165 	seqmutex_unlock(&c->btree_trans_lock);
3166 got_trans:
3167 	trans->c		= c;
3168 	trans->last_begin_time	= local_clock();
3169 	trans->fn_idx		= fn_idx;
3170 	trans->locking_wait.task = current;
3171 	trans->locked		= true;
3172 	trans->journal_replay_not_finished =
3173 		unlikely(!test_bit(JOURNAL_replay_done, &c->journal.flags)) &&
3174 		atomic_inc_not_zero(&c->journal_keys.ref);
3175 	trans->nr_paths		= ARRAY_SIZE(trans->_paths);
3176 	trans->paths_allocated	= trans->_paths_allocated;
3177 	trans->sorted		= trans->_sorted;
3178 	trans->paths		= trans->_paths;
3179 	trans->updates		= trans->_updates;
3180 
3181 	*trans_paths_nr(trans->paths) = BTREE_ITER_INITIAL;
3182 
3183 	trans->paths_allocated[0] = 1;
3184 
3185 	if (fn_idx < BCH_TRANSACTIONS_NR) {
3186 		trans->fn = bch2_btree_transaction_fns[fn_idx];
3187 
3188 		struct btree_transaction_stats *s = &c->btree_transaction_stats[fn_idx];
3189 
3190 		if (s->max_mem) {
3191 			unsigned expected_mem_bytes = roundup_pow_of_two(s->max_mem);
3192 
3193 			trans->mem = kmalloc(expected_mem_bytes, GFP_KERNEL);
3194 			if (likely(trans->mem))
3195 				trans->mem_bytes = expected_mem_bytes;
3196 		}
3197 
3198 		trans->nr_paths_max = s->nr_max_paths;
3199 		trans->journal_entries_size = s->journal_entries_size;
3200 	}
3201 
3202 	trans->srcu_idx		= srcu_read_lock(&c->btree_trans_barrier);
3203 	trans->srcu_lock_time	= jiffies;
3204 	trans->srcu_held	= true;
3205 	return trans;
3206 }
3207 
3208 static void check_btree_paths_leaked(struct btree_trans *trans)
3209 {
3210 #ifdef CONFIG_BCACHEFS_DEBUG
3211 	struct bch_fs *c = trans->c;
3212 	struct btree_path *path;
3213 	unsigned i;
3214 
3215 	trans_for_each_path(trans, path, i)
3216 		if (path->ref)
3217 			goto leaked;
3218 	return;
3219 leaked:
3220 	bch_err(c, "btree paths leaked from %s!", trans->fn);
3221 	trans_for_each_path(trans, path, i)
3222 		if (path->ref)
3223 			printk(KERN_ERR "  btree %s %pS\n",
3224 			       bch2_btree_id_str(path->btree_id),
3225 			       (void *) path->ip_allocated);
3226 	/* Be noisy about this: */
3227 	bch2_fatal_error(c);
3228 #endif
3229 }
3230 
3231 void bch2_trans_put(struct btree_trans *trans)
3232 	__releases(&c->btree_trans_barrier)
3233 {
3234 	struct bch_fs *c = trans->c;
3235 
3236 	bch2_trans_unlock(trans);
3237 
3238 	trans_for_each_update(trans, i)
3239 		__btree_path_put(trans->paths + i->path, true);
3240 	trans->nr_updates	= 0;
3241 	trans->locking_wait.task = NULL;
3242 
3243 	check_btree_paths_leaked(trans);
3244 
3245 	if (trans->srcu_held) {
3246 		check_srcu_held_too_long(trans);
3247 		srcu_read_unlock(&c->btree_trans_barrier, trans->srcu_idx);
3248 	}
3249 
3250 	if (trans->fs_usage_deltas) {
3251 		if (trans->fs_usage_deltas->size + sizeof(trans->fs_usage_deltas) ==
3252 		    REPLICAS_DELTA_LIST_MAX)
3253 			mempool_free(trans->fs_usage_deltas,
3254 				     &c->replicas_delta_pool);
3255 		else
3256 			kfree(trans->fs_usage_deltas);
3257 	}
3258 
3259 	if (unlikely(trans->journal_replay_not_finished))
3260 		bch2_journal_keys_put(c);
3261 
3262 	unsigned long *paths_allocated = trans->paths_allocated;
3263 	trans->paths_allocated	= NULL;
3264 	trans->paths		= NULL;
3265 
3266 	if (paths_allocated != trans->_paths_allocated)
3267 		kvfree_rcu_mightsleep(paths_allocated);
3268 
3269 	if (trans->used_mempool)
3270 		mempool_free(trans->mem, &c->btree_trans_mem_pool);
3271 	else
3272 		kfree(trans->mem);
3273 
3274 	/* Userspace doesn't have a real percpu implementation: */
3275 	if (IS_ENABLED(__KERNEL__))
3276 		trans = this_cpu_xchg(c->btree_trans_bufs->trans, trans);
3277 
3278 	if (trans) {
3279 		closure_sync(&trans->ref);
3280 
3281 		seqmutex_lock(&c->btree_trans_lock);
3282 		list_del(&trans->list);
3283 		seqmutex_unlock(&c->btree_trans_lock);
3284 
3285 		mempool_free(trans, &c->btree_trans_pool);
3286 	}
3287 }
3288 
3289 static void __maybe_unused
3290 bch2_btree_bkey_cached_common_to_text(struct printbuf *out,
3291 				      struct btree_bkey_cached_common *b)
3292 {
3293 	struct six_lock_count c = six_lock_counts(&b->lock);
3294 	struct task_struct *owner;
3295 	pid_t pid;
3296 
3297 	rcu_read_lock();
3298 	owner = READ_ONCE(b->lock.owner);
3299 	pid = owner ? owner->pid : 0;
3300 	rcu_read_unlock();
3301 
3302 	prt_printf(out, "\t%px %c l=%u %s:", b, b->cached ? 'c' : 'b',
3303 		   b->level, bch2_btree_id_str(b->btree_id));
3304 	bch2_bpos_to_text(out, btree_node_pos(b));
3305 
3306 	prt_printf(out, "\t locks %u:%u:%u held by pid %u",
3307 		   c.n[0], c.n[1], c.n[2], pid);
3308 }
3309 
3310 void bch2_btree_trans_to_text(struct printbuf *out, struct btree_trans *trans)
3311 {
3312 	struct btree_bkey_cached_common *b;
3313 	static char lock_types[] = { 'r', 'i', 'w' };
3314 	struct task_struct *task = READ_ONCE(trans->locking_wait.task);
3315 	unsigned l, idx;
3316 
3317 	/* before rcu_read_lock(): */
3318 	bch2_printbuf_make_room(out, 4096);
3319 
3320 	if (!out->nr_tabstops) {
3321 		printbuf_tabstop_push(out, 16);
3322 		printbuf_tabstop_push(out, 32);
3323 	}
3324 
3325 	prt_printf(out, "%i %s\n", task ? task->pid : 0, trans->fn);
3326 
3327 	/* trans->paths is rcu protected vs. freeing */
3328 	rcu_read_lock();
3329 	out->atomic++;
3330 
3331 	struct btree_path *paths = rcu_dereference(trans->paths);
3332 	if (!paths)
3333 		goto out;
3334 
3335 	unsigned long *paths_allocated = trans_paths_allocated(paths);
3336 
3337 	trans_for_each_path_idx_from(paths_allocated, *trans_paths_nr(paths), idx, 1) {
3338 		struct btree_path *path = paths + idx;
3339 		if (!path->nodes_locked)
3340 			continue;
3341 
3342 		prt_printf(out, "  path %u %c l=%u %s:",
3343 		       idx,
3344 		       path->cached ? 'c' : 'b',
3345 		       path->level,
3346 		       bch2_btree_id_str(path->btree_id));
3347 		bch2_bpos_to_text(out, path->pos);
3348 		prt_newline(out);
3349 
3350 		for (l = 0; l < BTREE_MAX_DEPTH; l++) {
3351 			if (btree_node_locked(path, l) &&
3352 			    !IS_ERR_OR_NULL(b = (void *) READ_ONCE(path->l[l].b))) {
3353 				prt_printf(out, "    %c l=%u ",
3354 					   lock_types[btree_node_locked_type(path, l)], l);
3355 				bch2_btree_bkey_cached_common_to_text(out, b);
3356 				prt_newline(out);
3357 			}
3358 		}
3359 	}
3360 
3361 	b = READ_ONCE(trans->locking);
3362 	if (b) {
3363 		prt_printf(out, "  blocked for %lluus on\n",
3364 			   div_u64(local_clock() - trans->locking_wait.start_time, 1000));
3365 		prt_printf(out, "    %c", lock_types[trans->locking_wait.lock_want]);
3366 		bch2_btree_bkey_cached_common_to_text(out, b);
3367 		prt_newline(out);
3368 	}
3369 out:
3370 	--out->atomic;
3371 	rcu_read_unlock();
3372 }
3373 
3374 void bch2_fs_btree_iter_exit(struct bch_fs *c)
3375 {
3376 	struct btree_transaction_stats *s;
3377 	struct btree_trans *trans;
3378 	int cpu;
3379 
3380 	if (c->btree_trans_bufs)
3381 		for_each_possible_cpu(cpu) {
3382 			struct btree_trans *trans =
3383 				per_cpu_ptr(c->btree_trans_bufs, cpu)->trans;
3384 
3385 			if (trans) {
3386 				closure_sync(&trans->ref);
3387 
3388 				seqmutex_lock(&c->btree_trans_lock);
3389 				list_del(&trans->list);
3390 				seqmutex_unlock(&c->btree_trans_lock);
3391 			}
3392 			kfree(trans);
3393 		}
3394 	free_percpu(c->btree_trans_bufs);
3395 
3396 	trans = list_first_entry_or_null(&c->btree_trans_list, struct btree_trans, list);
3397 	if (trans)
3398 		panic("%s leaked btree_trans\n", trans->fn);
3399 
3400 	for (s = c->btree_transaction_stats;
3401 	     s < c->btree_transaction_stats + ARRAY_SIZE(c->btree_transaction_stats);
3402 	     s++) {
3403 		kfree(s->max_paths_text);
3404 		bch2_time_stats_exit(&s->lock_hold_times);
3405 	}
3406 
3407 	if (c->btree_trans_barrier_initialized)
3408 		cleanup_srcu_struct(&c->btree_trans_barrier);
3409 	mempool_exit(&c->btree_trans_mem_pool);
3410 	mempool_exit(&c->btree_trans_pool);
3411 }
3412 
3413 void bch2_fs_btree_iter_init_early(struct bch_fs *c)
3414 {
3415 	struct btree_transaction_stats *s;
3416 
3417 	for (s = c->btree_transaction_stats;
3418 	     s < c->btree_transaction_stats + ARRAY_SIZE(c->btree_transaction_stats);
3419 	     s++) {
3420 		bch2_time_stats_init(&s->duration);
3421 		bch2_time_stats_init(&s->lock_hold_times);
3422 		mutex_init(&s->lock);
3423 	}
3424 
3425 	INIT_LIST_HEAD(&c->btree_trans_list);
3426 	seqmutex_init(&c->btree_trans_lock);
3427 }
3428 
3429 int bch2_fs_btree_iter_init(struct bch_fs *c)
3430 {
3431 	int ret;
3432 
3433 	c->btree_trans_bufs = alloc_percpu(struct btree_trans_buf);
3434 	if (!c->btree_trans_bufs)
3435 		return -ENOMEM;
3436 
3437 	ret   = mempool_init_kmalloc_pool(&c->btree_trans_pool, 1,
3438 					  sizeof(struct btree_trans)) ?:
3439 		mempool_init_kmalloc_pool(&c->btree_trans_mem_pool, 1,
3440 					  BTREE_TRANS_MEM_MAX) ?:
3441 		init_srcu_struct(&c->btree_trans_barrier);
3442 	if (!ret)
3443 		c->btree_trans_barrier_initialized = true;
3444 	return ret;
3445 }
3446