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