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