]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_iter.c
Update bcachefs sources to a0d7001b0f bcachefs: Change bch2_dev_lookup() to not use...
[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 __btree_path_traverse_all(struct btree_trans *trans, int ret,
1424                                      unsigned long trace_ip)
1425 {
1426         struct bch_fs *c = trans->c;
1427         struct btree_path *path;
1428         int i;
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(ret == -ENOMEM)) {
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         if (unlikely(ret == -EIO))
1468                 goto out;
1469
1470         BUG_ON(ret && ret != -EINTR);
1471
1472         /* Now, redo traversals in correct order: */
1473         i = 0;
1474         while (i < trans->nr_sorted) {
1475                 path = trans->paths + trans->sorted[i];
1476
1477                 /*
1478                  * Traversing a path can cause another path to be added at about
1479                  * the same position:
1480                  */
1481                 if (path->uptodate) {
1482                         ret = btree_path_traverse_one(trans, path, 0, _THIS_IP_);
1483                         if (ret)
1484                                 goto retry_all;
1485                 } else {
1486                         i++;
1487                 }
1488         }
1489
1490         /*
1491          * BTREE_ITER_NEED_RELOCK is ok here - if we called bch2_trans_unlock()
1492          * and relock(), relock() won't relock since path->should_be_locked
1493          * isn't set yet, which is all fine
1494          */
1495         trans_for_each_path(trans, path)
1496                 BUG_ON(path->uptodate >= BTREE_ITER_NEED_TRAVERSE);
1497 out:
1498         bch2_btree_cache_cannibalize_unlock(c);
1499
1500         trans->in_traverse_all = false;
1501
1502         trace_trans_traverse_all(trans->fn, trace_ip);
1503         return ret;
1504 }
1505
1506 static int bch2_btree_path_traverse_all(struct btree_trans *trans)
1507 {
1508         return __btree_path_traverse_all(trans, 0, _RET_IP_);
1509 }
1510
1511 static inline bool btree_path_good_node(struct btree_trans *trans,
1512                                         struct btree_path *path,
1513                                         unsigned l, int check_pos)
1514 {
1515         if (!is_btree_node(path, l) ||
1516             !bch2_btree_node_relock(trans, path, l))
1517                 return false;
1518
1519         if (check_pos < 0 && btree_path_pos_before_node(path, path->l[l].b))
1520                 return false;
1521         if (check_pos > 0 && btree_path_pos_after_node(path, path->l[l].b))
1522                 return false;
1523         return true;
1524 }
1525
1526 static inline unsigned btree_path_up_until_good_node(struct btree_trans *trans,
1527                                                      struct btree_path *path,
1528                                                      int check_pos)
1529 {
1530         unsigned i, l = path->level;
1531
1532         while (btree_path_node(path, l) &&
1533                !btree_path_good_node(trans, path, l, check_pos)) {
1534                 btree_node_unlock(path, l);
1535                 path->l[l].b = BTREE_ITER_NO_NODE_UP;
1536                 l++;
1537         }
1538
1539         /* If we need intent locks, take them too: */
1540         for (i = l + 1;
1541              i < path->locks_want && btree_path_node(path, i);
1542              i++)
1543                 if (!bch2_btree_node_relock(trans, path, i))
1544                         while (l <= i) {
1545                                 btree_node_unlock(path, l);
1546                                 path->l[l].b = BTREE_ITER_NO_NODE_UP;
1547                                 l++;
1548                         }
1549
1550         return l;
1551 }
1552
1553 /*
1554  * This is the main state machine for walking down the btree - walks down to a
1555  * specified depth
1556  *
1557  * Returns 0 on success, -EIO on error (error reading in a btree node).
1558  *
1559  * On error, caller (peek_node()/peek_key()) must return NULL; the error is
1560  * stashed in the iterator and returned from bch2_trans_exit().
1561  */
1562 static int btree_path_traverse_one(struct btree_trans *trans,
1563                                    struct btree_path *path,
1564                                    unsigned flags,
1565                                    unsigned long trace_ip)
1566 {
1567         unsigned depth_want = path->level;
1568         int ret = 0;
1569
1570         if (unlikely(trans->restarted)) {
1571                 ret = -EINTR;
1572                 goto out;
1573         }
1574
1575         /*
1576          * Ensure we obey path->should_be_locked: if it's set, we can't unlock
1577          * and re-traverse the path without a transaction restart:
1578          */
1579         if (path->should_be_locked) {
1580                 ret = bch2_btree_path_relock(trans, path, trace_ip) ? 0 : -EINTR;
1581                 goto out;
1582         }
1583
1584         if (path->cached) {
1585                 ret = bch2_btree_path_traverse_cached(trans, path, flags);
1586                 goto out;
1587         }
1588
1589         if (unlikely(path->level >= BTREE_MAX_DEPTH))
1590                 goto out;
1591
1592         path->level = btree_path_up_until_good_node(trans, path, 0);
1593
1594         /*
1595          * Note: path->nodes[path->level] may be temporarily NULL here - that
1596          * would indicate to other code that we got to the end of the btree,
1597          * here it indicates that relocking the root failed - it's critical that
1598          * btree_path_lock_root() comes next and that it can't fail
1599          */
1600         while (path->level > depth_want) {
1601                 ret = btree_path_node(path, path->level)
1602                         ? btree_path_down(trans, path, flags, trace_ip)
1603                         : btree_path_lock_root(trans, path, depth_want, trace_ip);
1604                 if (unlikely(ret)) {
1605                         if (ret == 1) {
1606                                 /*
1607                                  * No nodes at this level - got to the end of
1608                                  * the btree:
1609                                  */
1610                                 ret = 0;
1611                                 goto out;
1612                         }
1613
1614                         __bch2_btree_path_unlock(path);
1615                         path->level = depth_want;
1616
1617                         if (ret == -EIO)
1618                                 path->l[path->level].b =
1619                                         BTREE_ITER_NO_NODE_ERROR;
1620                         else
1621                                 path->l[path->level].b =
1622                                         BTREE_ITER_NO_NODE_DOWN;
1623                         goto out;
1624                 }
1625         }
1626
1627         path->uptodate = BTREE_ITER_UPTODATE;
1628 out:
1629         BUG_ON((ret == -EINTR) != !!trans->restarted);
1630         bch2_btree_path_verify(trans, path);
1631         return ret;
1632 }
1633
1634 static int __btree_path_traverse_all(struct btree_trans *, int, unsigned long);
1635
1636 int __must_check bch2_btree_path_traverse(struct btree_trans *trans,
1637                                           struct btree_path *path, unsigned flags)
1638 {
1639         if (path->uptodate < BTREE_ITER_NEED_RELOCK)
1640                 return 0;
1641
1642         return  bch2_trans_cond_resched(trans) ?:
1643                 btree_path_traverse_one(trans, path, flags, _RET_IP_);
1644 }
1645
1646 static void btree_path_copy(struct btree_trans *trans, struct btree_path *dst,
1647                             struct btree_path *src)
1648 {
1649         unsigned i;
1650
1651         memcpy(&dst->pos, &src->pos,
1652                sizeof(struct btree_path) - offsetof(struct btree_path, pos));
1653
1654         for (i = 0; i < BTREE_MAX_DEPTH; i++)
1655                 if (btree_node_locked(dst, i))
1656                         six_lock_increment(&dst->l[i].b->c.lock,
1657                                            __btree_lock_want(dst, i));
1658
1659         btree_path_check_sort(trans, dst, 0);
1660 }
1661
1662 static struct btree_path *btree_path_clone(struct btree_trans *trans, struct btree_path *src,
1663                                            bool intent)
1664 {
1665         struct btree_path *new = btree_path_alloc(trans, src);
1666
1667         btree_path_copy(trans, new, src);
1668         __btree_path_get(new, intent);
1669         return new;
1670 }
1671
1672 inline struct btree_path * __must_check
1673 bch2_btree_path_make_mut(struct btree_trans *trans,
1674                          struct btree_path *path, bool intent,
1675                          unsigned long ip)
1676 {
1677         if (path->ref > 1 || path->preserve) {
1678                 __btree_path_put(path, intent);
1679                 path = btree_path_clone(trans, path, intent);
1680                 path->preserve = false;
1681 #ifdef CONFIG_BCACHEFS_DEBUG
1682                 path->ip_allocated = ip;
1683 #endif
1684                 btree_trans_verify_sorted(trans);
1685         }
1686
1687         return path;
1688 }
1689
1690 struct btree_path * __must_check
1691 bch2_btree_path_set_pos(struct btree_trans *trans,
1692                    struct btree_path *path, struct bpos new_pos,
1693                    bool intent, unsigned long ip)
1694 {
1695         int cmp = bpos_cmp(new_pos, path->pos);
1696         unsigned l = path->level;
1697
1698         EBUG_ON(trans->restarted);
1699         EBUG_ON(!path->ref);
1700
1701         if (!cmp)
1702                 return path;
1703
1704         path = bch2_btree_path_make_mut(trans, path, intent, ip);
1705
1706         path->pos               = new_pos;
1707         path->should_be_locked  = false;
1708
1709         btree_path_check_sort(trans, path, cmp);
1710
1711         if (unlikely(path->cached)) {
1712                 btree_node_unlock(path, 0);
1713                 path->l[0].b = BTREE_ITER_NO_NODE_CACHED;
1714                 btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
1715                 goto out;
1716         }
1717
1718         l = btree_path_up_until_good_node(trans, path, cmp);
1719
1720         if (btree_path_node(path, l)) {
1721                 /*
1722                  * We might have to skip over many keys, or just a few: try
1723                  * advancing the node iterator, and if we have to skip over too
1724                  * many keys just reinit it (or if we're rewinding, since that
1725                  * is expensive).
1726                  */
1727                 if (cmp < 0 ||
1728                     !btree_path_advance_to_pos(path, &path->l[l], 8))
1729                         __btree_path_level_init(path, l);
1730         }
1731
1732         if (l != path->level) {
1733                 btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
1734                 __bch2_btree_path_unlock(path);
1735         }
1736 out:
1737         bch2_btree_path_verify(trans, path);
1738         return path;
1739 }
1740
1741 /* Btree path: main interface: */
1742
1743 static struct btree_path *have_path_at_pos(struct btree_trans *trans, struct btree_path *path)
1744 {
1745         struct btree_path *next;
1746
1747         next = prev_btree_path(trans, path);
1748         if (next && !btree_path_cmp(next, path))
1749                 return next;
1750
1751         next = next_btree_path(trans, path);
1752         if (next && !btree_path_cmp(next, path))
1753                 return next;
1754
1755         return NULL;
1756 }
1757
1758 static struct btree_path *have_node_at_pos(struct btree_trans *trans, struct btree_path *path)
1759 {
1760         struct btree_path *next;
1761
1762         next = prev_btree_path(trans, path);
1763         if (next && next->level == path->level && path_l(next)->b == path_l(path)->b)
1764                 return next;
1765
1766         next = next_btree_path(trans, path);
1767         if (next && next->level == path->level && path_l(next)->b == path_l(path)->b)
1768                 return next;
1769
1770         return NULL;
1771 }
1772
1773 static inline void __bch2_path_free(struct btree_trans *trans, struct btree_path *path)
1774 {
1775         __bch2_btree_path_unlock(path);
1776         btree_path_list_remove(trans, path);
1777         trans->paths_allocated &= ~(1ULL << path->idx);
1778 }
1779
1780 void bch2_path_put(struct btree_trans *trans, struct btree_path *path, bool intent)
1781 {
1782         struct btree_path *dup;
1783
1784         EBUG_ON(trans->paths + path->idx != path);
1785         EBUG_ON(!path->ref);
1786
1787         if (!__btree_path_put(path, intent))
1788                 return;
1789
1790         /*
1791          * Perhaps instead we should check for duplicate paths in traverse_all:
1792          */
1793         if (path->preserve &&
1794             (dup = have_path_at_pos(trans, path))) {
1795                 dup->preserve = true;
1796                 path->preserve = false;
1797                 goto free;
1798         }
1799
1800         if (!path->preserve &&
1801             (dup = have_node_at_pos(trans, path)))
1802                 goto free;
1803         return;
1804 free:
1805         if (path->should_be_locked &&
1806             !btree_node_locked(dup, path->level))
1807                 return;
1808
1809         dup->should_be_locked |= path->should_be_locked;
1810         __bch2_path_free(trans, path);
1811 }
1812
1813 noinline __cold
1814 void bch2_dump_trans_paths_updates(struct btree_trans *trans)
1815 {
1816         struct btree_path *path;
1817         struct btree_insert_entry *i;
1818         unsigned idx;
1819         char buf1[300], buf2[300];
1820
1821         btree_trans_verify_sorted(trans);
1822
1823         trans_for_each_path_inorder(trans, path, idx)
1824                 printk(KERN_ERR "path: idx %u ref %u:%u%s%s btree %s pos %s locks %u %pS\n",
1825                        path->idx, path->ref, path->intent_ref,
1826                        path->should_be_locked ? " S" : "",
1827                        path->preserve ? " P" : "",
1828                        bch2_btree_ids[path->btree_id],
1829                        (bch2_bpos_to_text(&PBUF(buf1), path->pos), buf1),
1830                        path->nodes_locked,
1831 #ifdef CONFIG_BCACHEFS_DEBUG
1832                        (void *) path->ip_allocated
1833 #else
1834                        NULL
1835 #endif
1836                        );
1837
1838         trans_for_each_update(trans, i) {
1839                 struct bkey u;
1840                 struct bkey_s_c old = bch2_btree_path_peek_slot(i->path, &u);
1841
1842                 printk(KERN_ERR "update: btree %s %pS\n  old %s\n  new %s",
1843                        bch2_btree_ids[i->btree_id],
1844                        (void *) i->ip_allocated,
1845                        (bch2_bkey_val_to_text(&PBUF(buf1), trans->c, old), buf1),
1846                        (bch2_bkey_val_to_text(&PBUF(buf2), trans->c, bkey_i_to_s_c(i->k)), buf2));
1847         }
1848 }
1849
1850 static struct btree_path *btree_path_alloc(struct btree_trans *trans,
1851                                            struct btree_path *pos)
1852 {
1853         struct btree_path *path;
1854         unsigned idx;
1855
1856         if (unlikely(trans->paths_allocated ==
1857                      ~((~0ULL << 1) << (BTREE_ITER_MAX - 1)))) {
1858                 bch2_dump_trans_paths_updates(trans);
1859                 panic("trans path oveflow\n");
1860         }
1861
1862         idx = __ffs64(~trans->paths_allocated);
1863         trans->paths_allocated |= 1ULL << idx;
1864
1865         path = &trans->paths[idx];
1866
1867         path->idx               = idx;
1868         path->ref               = 0;
1869         path->intent_ref        = 0;
1870         path->nodes_locked      = 0;
1871         path->nodes_intent_locked = 0;
1872
1873         btree_path_list_add(trans, pos, path);
1874         return path;
1875 }
1876
1877 struct btree_path *bch2_path_get(struct btree_trans *trans,
1878                                  enum btree_id btree_id, struct bpos pos,
1879                                  unsigned locks_want, unsigned level,
1880                                  unsigned flags, unsigned long ip)
1881 {
1882         struct btree_path *path, *path_pos = NULL;
1883         bool cached = flags & BTREE_ITER_CACHED;
1884         bool intent = flags & BTREE_ITER_INTENT;
1885         int i;
1886
1887         BUG_ON(trans->restarted);
1888
1889         trans_for_each_path_inorder(trans, path, i) {
1890                 if (__btree_path_cmp(path,
1891                                      btree_id,
1892                                      cached,
1893                                      pos,
1894                                      level) > 0)
1895                         break;
1896
1897                 path_pos = path;
1898         }
1899
1900         if (path_pos &&
1901             path_pos->cached    == cached &&
1902             path_pos->btree_id  == btree_id &&
1903             path_pos->level     == level) {
1904                 __btree_path_get(path_pos, intent);
1905                 path = bch2_btree_path_set_pos(trans, path_pos, pos, intent, ip);
1906         } else {
1907                 path = btree_path_alloc(trans, path_pos);
1908                 path_pos = NULL;
1909
1910                 __btree_path_get(path, intent);
1911                 path->pos                       = pos;
1912                 path->btree_id                  = btree_id;
1913                 path->cached                    = cached;
1914                 path->uptodate                  = BTREE_ITER_NEED_TRAVERSE;
1915                 path->should_be_locked          = false;
1916                 path->level                     = level;
1917                 path->locks_want                = locks_want;
1918                 path->nodes_locked              = 0;
1919                 path->nodes_intent_locked       = 0;
1920                 for (i = 0; i < ARRAY_SIZE(path->l); i++)
1921                         path->l[i].b            = BTREE_ITER_NO_NODE_INIT;
1922 #ifdef CONFIG_BCACHEFS_DEBUG
1923                 path->ip_allocated              = ip;
1924 #endif
1925                 btree_trans_verify_sorted(trans);
1926         }
1927
1928         if (!(flags & BTREE_ITER_NOPRESERVE))
1929                 path->preserve = true;
1930
1931         if (path->intent_ref)
1932                 locks_want = max(locks_want, level + 1);
1933
1934         /*
1935          * If the path has locks_want greater than requested, we don't downgrade
1936          * it here - on transaction restart because btree node split needs to
1937          * upgrade locks, we might be putting/getting the iterator again.
1938          * Downgrading iterators only happens via bch2_trans_downgrade(), after
1939          * a successful transaction commit.
1940          */
1941
1942         locks_want = min(locks_want, BTREE_MAX_DEPTH);
1943         if (locks_want > path->locks_want) {
1944                 path->locks_want = locks_want;
1945                 btree_path_get_locks(trans, path, true);
1946         }
1947
1948         return path;
1949 }
1950
1951 inline struct bkey_s_c bch2_btree_path_peek_slot(struct btree_path *path, struct bkey *u)
1952 {
1953
1954         struct bkey_s_c k;
1955
1956         if (!path->cached) {
1957                 struct btree_path_level *l = path_l(path);
1958                 struct bkey_packed *_k;
1959
1960                 EBUG_ON(path->uptodate != BTREE_ITER_UPTODATE);
1961
1962                 _k = bch2_btree_node_iter_peek_all(&l->iter, l->b);
1963                 k = _k ? bkey_disassemble(l->b, _k, u) : bkey_s_c_null;
1964
1965                 EBUG_ON(k.k && bkey_deleted(k.k) && bpos_cmp(k.k->p, path->pos) == 0);
1966
1967                 if (!k.k || bpos_cmp(path->pos, k.k->p))
1968                         goto hole;
1969         } else {
1970                 struct bkey_cached *ck = (void *) path->l[0].b;
1971
1972                 EBUG_ON(ck &&
1973                         (path->btree_id != ck->key.btree_id ||
1974                          bkey_cmp(path->pos, ck->key.pos)));
1975
1976                 /* BTREE_ITER_CACHED_NOFILL|BTREE_ITER_CACHED_NOCREATE? */
1977                 if (unlikely(!ck || !ck->valid))
1978                         return bkey_s_c_null;
1979
1980                 EBUG_ON(path->uptodate != BTREE_ITER_UPTODATE);
1981
1982                 k = bkey_i_to_s_c(ck->k);
1983         }
1984
1985         return k;
1986 hole:
1987         bkey_init(u);
1988         u->p = path->pos;
1989         return (struct bkey_s_c) { u, NULL };
1990 }
1991
1992 /* Btree iterators: */
1993
1994 int __must_check
1995 __bch2_btree_iter_traverse(struct btree_iter *iter)
1996 {
1997         return bch2_btree_path_traverse(iter->trans, iter->path, iter->flags);
1998 }
1999
2000 int __must_check
2001 bch2_btree_iter_traverse(struct btree_iter *iter)
2002 {
2003         int ret;
2004
2005         iter->path = bch2_btree_path_set_pos(iter->trans, iter->path,
2006                                         btree_iter_search_key(iter),
2007                                         iter->flags & BTREE_ITER_INTENT,
2008                                         btree_iter_ip_allocated(iter));
2009
2010         ret = bch2_btree_path_traverse(iter->trans, iter->path, iter->flags);
2011         if (ret)
2012                 return ret;
2013
2014         iter->path->should_be_locked = true;
2015         return 0;
2016 }
2017
2018 /* Iterate across nodes (leaf and interior nodes) */
2019
2020 struct btree *bch2_btree_iter_peek_node(struct btree_iter *iter)
2021 {
2022         struct btree_trans *trans = iter->trans;
2023         struct btree *b = NULL;
2024         int ret;
2025
2026         EBUG_ON(iter->path->cached);
2027         bch2_btree_iter_verify(iter);
2028
2029         ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
2030         if (ret)
2031                 goto err;
2032
2033         b = btree_path_node(iter->path, iter->path->level);
2034         if (!b)
2035                 goto out;
2036
2037         BUG_ON(bpos_cmp(b->key.k.p, iter->pos) < 0);
2038
2039         bkey_init(&iter->k);
2040         iter->k.p = iter->pos = b->key.k.p;
2041
2042         iter->path = bch2_btree_path_set_pos(trans, iter->path, b->key.k.p,
2043                                         iter->flags & BTREE_ITER_INTENT,
2044                                         btree_iter_ip_allocated(iter));
2045         iter->path->should_be_locked = true;
2046         BUG_ON(iter->path->uptodate);
2047 out:
2048         bch2_btree_iter_verify_entry_exit(iter);
2049         bch2_btree_iter_verify(iter);
2050
2051         return b;
2052 err:
2053         b = ERR_PTR(ret);
2054         goto out;
2055 }
2056
2057 struct btree *bch2_btree_iter_next_node(struct btree_iter *iter)
2058 {
2059         struct btree_trans *trans = iter->trans;
2060         struct btree_path *path = iter->path;
2061         struct btree *b = NULL;
2062         unsigned l;
2063         int ret;
2064
2065         BUG_ON(trans->restarted);
2066         EBUG_ON(iter->path->cached);
2067         bch2_btree_iter_verify(iter);
2068
2069         /* already at end? */
2070         if (!btree_path_node(path, path->level))
2071                 return NULL;
2072
2073         /* got to end? */
2074         if (!btree_path_node(path, path->level + 1)) {
2075                 btree_node_unlock(path, path->level);
2076                 path->l[path->level].b = BTREE_ITER_NO_NODE_UP;
2077                 path->level++;
2078                 return NULL;
2079         }
2080
2081         if (!bch2_btree_node_relock(trans, path, path->level + 1)) {
2082                 __bch2_btree_path_unlock(path);
2083                 path->l[path->level].b = BTREE_ITER_NO_NODE_GET_LOCKS;
2084                 path->l[path->level + 1].b = BTREE_ITER_NO_NODE_GET_LOCKS;
2085                 trace_trans_restart_relock_next_node(trans->fn, _THIS_IP_,
2086                                            path->btree_id, &path->pos);
2087                 btree_trans_restart(trans);
2088                 ret = -EINTR;
2089                 goto err;
2090         }
2091
2092         b = btree_path_node(path, path->level + 1);
2093
2094         if (!bpos_cmp(iter->pos, b->key.k.p)) {
2095                 btree_node_unlock(path, path->level);
2096                 path->l[path->level].b = BTREE_ITER_NO_NODE_UP;
2097                 path->level++;
2098         } else {
2099                 /*
2100                  * Haven't gotten to the end of the parent node: go back down to
2101                  * the next child node
2102                  */
2103                 path = iter->path =
2104                         bch2_btree_path_set_pos(trans, path, bpos_successor(iter->pos),
2105                                            iter->flags & BTREE_ITER_INTENT,
2106                                            btree_iter_ip_allocated(iter));
2107
2108                 path->level = iter->min_depth;
2109
2110                 for (l = path->level + 1; l < BTREE_MAX_DEPTH; l++)
2111                         if (btree_lock_want(path, l) == BTREE_NODE_UNLOCKED)
2112                                 btree_node_unlock(path, l);
2113
2114                 btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
2115                 bch2_btree_iter_verify(iter);
2116
2117                 ret = bch2_btree_path_traverse(trans, path, iter->flags);
2118                 if (ret)
2119                         goto err;
2120
2121                 b = path->l[path->level].b;
2122         }
2123
2124         bkey_init(&iter->k);
2125         iter->k.p = iter->pos = b->key.k.p;
2126
2127         iter->path = bch2_btree_path_set_pos(trans, iter->path, b->key.k.p,
2128                                         iter->flags & BTREE_ITER_INTENT,
2129                                         btree_iter_ip_allocated(iter));
2130         iter->path->should_be_locked = true;
2131         BUG_ON(iter->path->uptodate);
2132 out:
2133         bch2_btree_iter_verify_entry_exit(iter);
2134         bch2_btree_iter_verify(iter);
2135
2136         return b;
2137 err:
2138         b = ERR_PTR(ret);
2139         goto out;
2140 }
2141
2142 /* Iterate across keys (in leaf nodes only) */
2143
2144 inline bool bch2_btree_iter_advance(struct btree_iter *iter)
2145 {
2146         struct bpos pos = iter->k.p;
2147         bool ret = (iter->flags & BTREE_ITER_ALL_SNAPSHOTS
2148                     ? bpos_cmp(pos, SPOS_MAX)
2149                     : bkey_cmp(pos, SPOS_MAX)) != 0;
2150
2151         if (ret && !(iter->flags & BTREE_ITER_IS_EXTENTS))
2152                 pos = bkey_successor(iter, pos);
2153         bch2_btree_iter_set_pos(iter, pos);
2154         return ret;
2155 }
2156
2157 inline bool bch2_btree_iter_rewind(struct btree_iter *iter)
2158 {
2159         struct bpos pos = bkey_start_pos(&iter->k);
2160         bool ret = (iter->flags & BTREE_ITER_ALL_SNAPSHOTS
2161                     ? bpos_cmp(pos, POS_MIN)
2162                     : bkey_cmp(pos, POS_MIN)) != 0;
2163
2164         if (ret && !(iter->flags & BTREE_ITER_IS_EXTENTS))
2165                 pos = bkey_predecessor(iter, pos);
2166         bch2_btree_iter_set_pos(iter, pos);
2167         return ret;
2168 }
2169
2170 static inline struct bkey_i *btree_trans_peek_updates(struct btree_trans *trans,
2171                                                       enum btree_id btree_id,
2172                                                       struct bpos pos)
2173 {
2174         struct btree_insert_entry *i;
2175
2176         trans_for_each_update(trans, i)
2177                 if ((cmp_int(btree_id,  i->btree_id) ?:
2178                      bpos_cmp(pos,      i->k->k.p)) <= 0) {
2179                         if (btree_id == i->btree_id)
2180                                 return i->k;
2181                         break;
2182                 }
2183
2184         return NULL;
2185 }
2186
2187 static noinline
2188 struct bkey_i *__btree_trans_peek_journal(struct btree_trans *trans,
2189                                           struct btree_path *path)
2190 {
2191         struct journal_keys *keys = &trans->c->journal_keys;
2192         size_t idx = bch2_journal_key_search(keys, path->btree_id,
2193                                              path->level, path->pos);
2194
2195         while (idx < keys->nr && keys->d[idx].overwritten)
2196                 idx++;
2197
2198         return (idx < keys->nr &&
2199                 keys->d[idx].btree_id   == path->btree_id &&
2200                 keys->d[idx].level      == path->level)
2201                 ? keys->d[idx].k
2202                 : NULL;
2203 }
2204
2205 static noinline
2206 struct bkey_s_c btree_trans_peek_journal(struct btree_trans *trans,
2207                                          struct btree_iter *iter,
2208                                          struct bkey_s_c k)
2209 {
2210         struct bkey_i *next_journal =
2211                 __btree_trans_peek_journal(trans, iter->path);
2212
2213         if (next_journal &&
2214             bpos_cmp(next_journal->k.p,
2215                      k.k ? k.k->p : iter->path->l[0].b->key.k.p) <= 0) {
2216                 iter->k = next_journal->k;
2217                 k = bkey_i_to_s_c(next_journal);
2218         }
2219
2220         return k;
2221 }
2222
2223 /*
2224  * Checks btree key cache for key at iter->pos and returns it if present, or
2225  * bkey_s_c_null:
2226  */
2227 static noinline
2228 struct bkey_s_c btree_trans_peek_key_cache(struct btree_iter *iter, struct bpos pos)
2229 {
2230         struct btree_trans *trans = iter->trans;
2231         struct bch_fs *c = trans->c;
2232         struct bkey u;
2233         int ret;
2234
2235         if (!bch2_btree_key_cache_find(c, iter->btree_id, pos))
2236                 return bkey_s_c_null;
2237
2238         if (!iter->key_cache_path)
2239                 iter->key_cache_path = bch2_path_get(trans, iter->btree_id, pos,
2240                                                      iter->flags & BTREE_ITER_INTENT, 0,
2241                                                      iter->flags|BTREE_ITER_CACHED,
2242                                                      _THIS_IP_);
2243
2244         iter->key_cache_path = bch2_btree_path_set_pos(trans, iter->key_cache_path, pos,
2245                                         iter->flags & BTREE_ITER_INTENT,
2246                                         btree_iter_ip_allocated(iter));
2247
2248         ret = bch2_btree_path_traverse(trans, iter->key_cache_path, iter->flags|BTREE_ITER_CACHED);
2249         if (unlikely(ret))
2250                 return bkey_s_c_err(ret);
2251
2252         iter->key_cache_path->should_be_locked = true;
2253
2254         return bch2_btree_path_peek_slot(iter->key_cache_path, &u);
2255 }
2256
2257 static struct bkey_s_c __bch2_btree_iter_peek(struct btree_iter *iter, struct bpos search_key)
2258 {
2259         struct btree_trans *trans = iter->trans;
2260         struct bkey_i *next_update;
2261         struct bkey_s_c k, k2;
2262         int ret;
2263
2264         EBUG_ON(iter->path->cached || iter->path->level);
2265         bch2_btree_iter_verify(iter);
2266
2267         while (1) {
2268                 iter->path = bch2_btree_path_set_pos(trans, iter->path, search_key,
2269                                         iter->flags & BTREE_ITER_INTENT,
2270                                         btree_iter_ip_allocated(iter));
2271
2272                 ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
2273                 if (unlikely(ret)) {
2274                         /* ensure that iter->k is consistent with iter->pos: */
2275                         bch2_btree_iter_set_pos(iter, iter->pos);
2276                         k = bkey_s_c_err(ret);
2277                         goto out;
2278                 }
2279
2280                 iter->path->should_be_locked = true;
2281
2282                 k = btree_path_level_peek_all(trans->c, &iter->path->l[0], &iter->k);
2283
2284                 if (unlikely(iter->flags & BTREE_ITER_WITH_KEY_CACHE) &&
2285                     k.k &&
2286                     (k2 = btree_trans_peek_key_cache(iter, k.k->p)).k) {
2287                         ret = bkey_err(k2);
2288                         if (ret) {
2289                                 k = k2;
2290                                 bch2_btree_iter_set_pos(iter, iter->pos);
2291                                 goto out;
2292                         }
2293
2294                         k = k2;
2295                         iter->k = *k.k;
2296                 }
2297
2298                 if (unlikely(iter->flags & BTREE_ITER_WITH_JOURNAL))
2299                         k = btree_trans_peek_journal(trans, iter, k);
2300
2301                 next_update = iter->flags & BTREE_ITER_WITH_UPDATES
2302                         ? btree_trans_peek_updates(trans, iter->btree_id, search_key)
2303                         : NULL;
2304                 if (next_update &&
2305                     bpos_cmp(next_update->k.p,
2306                              k.k ? k.k->p : iter->path->l[0].b->key.k.p) <= 0) {
2307                         iter->k = next_update->k;
2308                         k = bkey_i_to_s_c(next_update);
2309                 }
2310
2311                 if (k.k && bkey_deleted(k.k)) {
2312                         /*
2313                          * If we've got a whiteout, and it's after the search
2314                          * key, advance the search key to the whiteout instead
2315                          * of just after the whiteout - it might be a btree
2316                          * whiteout, with a real key at the same position, since
2317                          * in the btree deleted keys sort before non deleted.
2318                          */
2319                         search_key = bpos_cmp(search_key, k.k->p)
2320                                 ? k.k->p
2321                                 : bpos_successor(k.k->p);
2322                         continue;
2323                 }
2324
2325                 if (likely(k.k)) {
2326                         break;
2327                 } else if (likely(bpos_cmp(iter->path->l[0].b->key.k.p, SPOS_MAX))) {
2328                         /* Advance to next leaf node: */
2329                         search_key = bpos_successor(iter->path->l[0].b->key.k.p);
2330                 } else {
2331                         /* End of btree: */
2332                         bch2_btree_iter_set_pos(iter, SPOS_MAX);
2333                         k = bkey_s_c_null;
2334                         goto out;
2335                 }
2336         }
2337 out:
2338         bch2_btree_iter_verify(iter);
2339
2340         return k;
2341 }
2342
2343 /**
2344  * bch2_btree_iter_peek: returns first key greater than or equal to iterator's
2345  * current position
2346  */
2347 struct bkey_s_c bch2_btree_iter_peek(struct btree_iter *iter)
2348 {
2349         struct btree_trans *trans = iter->trans;
2350         struct bpos search_key = btree_iter_search_key(iter);
2351         struct bkey_s_c k;
2352         int ret;
2353
2354         if (iter->update_path) {
2355                 bch2_path_put(trans, iter->update_path,
2356                               iter->flags & BTREE_ITER_INTENT);
2357                 iter->update_path = NULL;
2358         }
2359
2360         bch2_btree_iter_verify_entry_exit(iter);
2361
2362         while (1) {
2363                 k = __bch2_btree_iter_peek(iter, search_key);
2364                 if (!k.k || bkey_err(k))
2365                         goto out;
2366
2367                 if (iter->update_path &&
2368                     bkey_cmp(iter->update_path->pos, k.k->p)) {
2369                         bch2_path_put(trans, iter->update_path,
2370                                       iter->flags & BTREE_ITER_INTENT);
2371                         iter->update_path = NULL;
2372                 }
2373
2374                 if ((iter->flags & BTREE_ITER_FILTER_SNAPSHOTS) &&
2375                     (iter->flags & BTREE_ITER_INTENT) &&
2376                     !(iter->flags & BTREE_ITER_IS_EXTENTS) &&
2377                     !iter->update_path) {
2378                         struct bpos pos = k.k->p;
2379
2380                         if (pos.snapshot < iter->snapshot) {
2381                                 search_key = bpos_successor(k.k->p);
2382                                 continue;
2383                         }
2384
2385                         pos.snapshot = iter->snapshot;
2386
2387                         /*
2388                          * advance, same as on exit for iter->path, but only up
2389                          * to snapshot
2390                          */
2391                         __btree_path_get(iter->path, iter->flags & BTREE_ITER_INTENT);
2392                         iter->update_path = iter->path;
2393
2394                         iter->update_path = bch2_btree_path_set_pos(trans,
2395                                                 iter->update_path, pos,
2396                                                 iter->flags & BTREE_ITER_INTENT,
2397                                                 btree_iter_ip_allocated(iter));
2398
2399                         BUG_ON(!(iter->update_path->nodes_locked & 1));
2400                         iter->update_path->should_be_locked = true;
2401                 }
2402
2403                 /*
2404                  * We can never have a key in a leaf node at POS_MAX, so
2405                  * we don't have to check these successor() calls:
2406                  */
2407                 if ((iter->flags & BTREE_ITER_FILTER_SNAPSHOTS) &&
2408                     !bch2_snapshot_is_ancestor(trans->c,
2409                                                iter->snapshot,
2410                                                k.k->p.snapshot)) {
2411                         search_key = bpos_successor(k.k->p);
2412                         continue;
2413                 }
2414
2415                 if (bkey_whiteout(k.k) &&
2416                     !(iter->flags & BTREE_ITER_ALL_SNAPSHOTS)) {
2417                         search_key = bkey_successor(iter, k.k->p);
2418                         continue;
2419                 }
2420
2421                 break;
2422         }
2423
2424         /*
2425          * iter->pos should be mononotically increasing, and always be equal to
2426          * the key we just returned - except extents can straddle iter->pos:
2427          */
2428         if (!(iter->flags & BTREE_ITER_IS_EXTENTS))
2429                 iter->pos = k.k->p;
2430         else if (bkey_cmp(bkey_start_pos(k.k), iter->pos) > 0)
2431                 iter->pos = bkey_start_pos(k.k);
2432
2433         iter->path = bch2_btree_path_set_pos(trans, iter->path, k.k->p,
2434                                 iter->flags & BTREE_ITER_INTENT,
2435                                 btree_iter_ip_allocated(iter));
2436         BUG_ON(!iter->path->nodes_locked);
2437 out:
2438         if (iter->update_path) {
2439                 BUG_ON(!(iter->update_path->nodes_locked & 1));
2440                 iter->update_path->should_be_locked = true;
2441         }
2442         iter->path->should_be_locked = true;
2443
2444         if (!(iter->flags & BTREE_ITER_ALL_SNAPSHOTS))
2445                 iter->pos.snapshot = iter->snapshot;
2446
2447         ret = bch2_btree_iter_verify_ret(iter, k);
2448         if (unlikely(ret)) {
2449                 bch2_btree_iter_set_pos(iter, iter->pos);
2450                 k = bkey_s_c_err(ret);
2451         }
2452
2453         bch2_btree_iter_verify_entry_exit(iter);
2454
2455         return k;
2456 }
2457
2458 /**
2459  * bch2_btree_iter_next: returns first key greater than iterator's current
2460  * position
2461  */
2462 struct bkey_s_c bch2_btree_iter_next(struct btree_iter *iter)
2463 {
2464         if (!bch2_btree_iter_advance(iter))
2465                 return bkey_s_c_null;
2466
2467         return bch2_btree_iter_peek(iter);
2468 }
2469
2470 /**
2471  * bch2_btree_iter_peek_prev: returns first key less than or equal to
2472  * iterator's current position
2473  */
2474 struct bkey_s_c bch2_btree_iter_peek_prev(struct btree_iter *iter)
2475 {
2476         struct btree_trans *trans = iter->trans;
2477         struct bpos search_key = iter->pos;
2478         struct btree_path *saved_path = NULL;
2479         struct bkey_s_c k;
2480         struct bkey saved_k;
2481         const struct bch_val *saved_v;
2482         int ret;
2483
2484         EBUG_ON(iter->path->cached || iter->path->level);
2485         EBUG_ON(iter->flags & BTREE_ITER_WITH_UPDATES);
2486
2487         if (iter->flags & BTREE_ITER_WITH_JOURNAL)
2488                 return bkey_s_c_err(-EIO);
2489
2490         bch2_btree_iter_verify(iter);
2491         bch2_btree_iter_verify_entry_exit(iter);
2492
2493         if (iter->flags & BTREE_ITER_FILTER_SNAPSHOTS)
2494                 search_key.snapshot = U32_MAX;
2495
2496         while (1) {
2497                 iter->path = bch2_btree_path_set_pos(trans, iter->path, search_key,
2498                                                 iter->flags & BTREE_ITER_INTENT,
2499                                                 btree_iter_ip_allocated(iter));
2500
2501                 ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
2502                 if (unlikely(ret)) {
2503                         /* ensure that iter->k is consistent with iter->pos: */
2504                         bch2_btree_iter_set_pos(iter, iter->pos);
2505                         k = bkey_s_c_err(ret);
2506                         goto out;
2507                 }
2508
2509                 k = btree_path_level_peek(trans->c, iter->path,
2510                                           &iter->path->l[0], &iter->k);
2511                 if (!k.k ||
2512                     ((iter->flags & BTREE_ITER_IS_EXTENTS)
2513                      ? bpos_cmp(bkey_start_pos(k.k), search_key) >= 0
2514                      : bpos_cmp(k.k->p, search_key) > 0))
2515                         k = btree_path_level_prev(trans->c, iter->path,
2516                                                   &iter->path->l[0], &iter->k);
2517
2518                 btree_path_check_sort(trans, iter->path, 0);
2519
2520                 if (likely(k.k)) {
2521                         if (iter->flags & BTREE_ITER_FILTER_SNAPSHOTS) {
2522                                 if (k.k->p.snapshot == iter->snapshot)
2523                                         goto got_key;
2524
2525                                 /*
2526                                  * If we have a saved candidate, and we're no
2527                                  * longer at the same _key_ (not pos), return
2528                                  * that candidate
2529                                  */
2530                                 if (saved_path && bkey_cmp(k.k->p, saved_k.p)) {
2531                                         bch2_path_put(trans, iter->path,
2532                                                       iter->flags & BTREE_ITER_INTENT);
2533                                         iter->path = saved_path;
2534                                         saved_path = NULL;
2535                                         iter->k = saved_k;
2536                                         k.v     = saved_v;
2537                                         goto got_key;
2538                                 }
2539
2540                                 if (bch2_snapshot_is_ancestor(iter->trans->c,
2541                                                               iter->snapshot,
2542                                                               k.k->p.snapshot)) {
2543                                         if (saved_path)
2544                                                 bch2_path_put(trans, saved_path,
2545                                                       iter->flags & BTREE_ITER_INTENT);
2546                                         saved_path = btree_path_clone(trans, iter->path,
2547                                                                 iter->flags & BTREE_ITER_INTENT);
2548                                         saved_k = *k.k;
2549                                         saved_v = k.v;
2550                                 }
2551
2552                                 search_key = bpos_predecessor(k.k->p);
2553                                 continue;
2554                         }
2555 got_key:
2556                         if (bkey_whiteout(k.k) &&
2557                             !(iter->flags & BTREE_ITER_ALL_SNAPSHOTS)) {
2558                                 search_key = bkey_predecessor(iter, k.k->p);
2559                                 if (iter->flags & BTREE_ITER_FILTER_SNAPSHOTS)
2560                                         search_key.snapshot = U32_MAX;
2561                                 continue;
2562                         }
2563
2564                         break;
2565                 } else if (likely(bpos_cmp(iter->path->l[0].b->data->min_key, POS_MIN))) {
2566                         /* Advance to previous leaf node: */
2567                         search_key = bpos_predecessor(iter->path->l[0].b->data->min_key);
2568                 } else {
2569                         /* Start of btree: */
2570                         bch2_btree_iter_set_pos(iter, POS_MIN);
2571                         k = bkey_s_c_null;
2572                         goto out;
2573                 }
2574         }
2575
2576         EBUG_ON(bkey_cmp(bkey_start_pos(k.k), iter->pos) > 0);
2577
2578         /* Extents can straddle iter->pos: */
2579         if (bkey_cmp(k.k->p, iter->pos) < 0)
2580                 iter->pos = k.k->p;
2581
2582         if (iter->flags & BTREE_ITER_FILTER_SNAPSHOTS)
2583                 iter->pos.snapshot = iter->snapshot;
2584 out:
2585         if (saved_path)
2586                 bch2_path_put(trans, saved_path, iter->flags & BTREE_ITER_INTENT);
2587         iter->path->should_be_locked = true;
2588
2589         bch2_btree_iter_verify_entry_exit(iter);
2590         bch2_btree_iter_verify(iter);
2591
2592         return k;
2593 }
2594
2595 /**
2596  * bch2_btree_iter_prev: returns first key less than iterator's current
2597  * position
2598  */
2599 struct bkey_s_c bch2_btree_iter_prev(struct btree_iter *iter)
2600 {
2601         if (!bch2_btree_iter_rewind(iter))
2602                 return bkey_s_c_null;
2603
2604         return bch2_btree_iter_peek_prev(iter);
2605 }
2606
2607 struct bkey_s_c bch2_btree_iter_peek_slot(struct btree_iter *iter)
2608 {
2609         struct btree_trans *trans = iter->trans;
2610         struct bpos search_key;
2611         struct bkey_s_c k;
2612         int ret;
2613
2614         EBUG_ON(iter->path->level);
2615         bch2_btree_iter_verify(iter);
2616         bch2_btree_iter_verify_entry_exit(iter);
2617
2618         /* extents can't span inode numbers: */
2619         if ((iter->flags & BTREE_ITER_IS_EXTENTS) &&
2620             unlikely(iter->pos.offset == KEY_OFFSET_MAX)) {
2621                 if (iter->pos.inode == KEY_INODE_MAX)
2622                         return bkey_s_c_null;
2623
2624                 bch2_btree_iter_set_pos(iter, bpos_nosnap_successor(iter->pos));
2625         }
2626
2627         search_key = btree_iter_search_key(iter);
2628         iter->path = bch2_btree_path_set_pos(trans, iter->path, search_key,
2629                                         iter->flags & BTREE_ITER_INTENT,
2630                                         btree_iter_ip_allocated(iter));
2631
2632         ret = bch2_btree_path_traverse(trans, iter->path, iter->flags);
2633         if (unlikely(ret))
2634                 return bkey_s_c_err(ret);
2635
2636         if ((iter->flags & BTREE_ITER_CACHED) ||
2637             !(iter->flags & (BTREE_ITER_IS_EXTENTS|BTREE_ITER_FILTER_SNAPSHOTS))) {
2638                 struct bkey_i *next_update;
2639
2640                 if ((iter->flags & BTREE_ITER_WITH_UPDATES) &&
2641                     (next_update = btree_trans_peek_updates(trans,
2642                                                 iter->btree_id, search_key)) &&
2643                     !bpos_cmp(next_update->k.p, iter->pos)) {
2644                         iter->k = next_update->k;
2645                         k = bkey_i_to_s_c(next_update);
2646                         goto out;
2647                 }
2648
2649                 if (unlikely(iter->flags & BTREE_ITER_WITH_JOURNAL) &&
2650                     (next_update = __btree_trans_peek_journal(trans, iter->path)) &&
2651                     !bpos_cmp(next_update->k.p, iter->pos)) {
2652                         iter->k = next_update->k;
2653                         k = bkey_i_to_s_c(next_update);
2654                         goto out;
2655                 }
2656
2657                 if (unlikely(iter->flags & BTREE_ITER_WITH_KEY_CACHE) &&
2658                     (k = btree_trans_peek_key_cache(iter, iter->pos)).k) {
2659                         if (!bkey_err(k))
2660                                 iter->k = *k.k;
2661                         goto out;
2662                 }
2663
2664                 k = bch2_btree_path_peek_slot(iter->path, &iter->k);
2665         } else {
2666                 struct bpos next;
2667
2668                 if (iter->flags & BTREE_ITER_INTENT) {
2669                         struct btree_iter iter2;
2670
2671                         bch2_trans_copy_iter(&iter2, iter);
2672                         k = bch2_btree_iter_peek(&iter2);
2673
2674                         if (k.k && !bkey_err(k)) {
2675                                 iter->k = iter2.k;
2676                                 k.k = &iter->k;
2677                         }
2678                         bch2_trans_iter_exit(trans, &iter2);
2679                 } else {
2680                         struct bpos pos = iter->pos;
2681
2682                         k = bch2_btree_iter_peek(iter);
2683                         iter->pos = pos;
2684                 }
2685
2686                 if (unlikely(bkey_err(k)))
2687                         return k;
2688
2689                 next = k.k ? bkey_start_pos(k.k) : POS_MAX;
2690
2691                 if (bkey_cmp(iter->pos, next) < 0) {
2692                         bkey_init(&iter->k);
2693                         iter->k.p = iter->pos;
2694
2695                         if (iter->flags & BTREE_ITER_IS_EXTENTS) {
2696                                 bch2_key_resize(&iter->k,
2697                                                 min_t(u64, KEY_SIZE_MAX,
2698                                                       (next.inode == iter->pos.inode
2699                                                        ? next.offset
2700                                                        : KEY_OFFSET_MAX) -
2701                                                       iter->pos.offset));
2702                                 EBUG_ON(!iter->k.size);
2703                         }
2704
2705                         k = (struct bkey_s_c) { &iter->k, NULL };
2706                 }
2707         }
2708 out:
2709         iter->path->should_be_locked = true;
2710
2711         bch2_btree_iter_verify_entry_exit(iter);
2712         bch2_btree_iter_verify(iter);
2713         ret = bch2_btree_iter_verify_ret(iter, k);
2714         if (unlikely(ret))
2715                 return bkey_s_c_err(ret);
2716
2717         return k;
2718 }
2719
2720 struct bkey_s_c bch2_btree_iter_next_slot(struct btree_iter *iter)
2721 {
2722         if (!bch2_btree_iter_advance(iter))
2723                 return bkey_s_c_null;
2724
2725         return bch2_btree_iter_peek_slot(iter);
2726 }
2727
2728 struct bkey_s_c bch2_btree_iter_prev_slot(struct btree_iter *iter)
2729 {
2730         if (!bch2_btree_iter_rewind(iter))
2731                 return bkey_s_c_null;
2732
2733         return bch2_btree_iter_peek_slot(iter);
2734 }
2735
2736 /* new transactional stuff: */
2737
2738 static inline void btree_path_verify_sorted_ref(struct btree_trans *trans,
2739                                                 struct btree_path *path)
2740 {
2741         EBUG_ON(path->sorted_idx >= trans->nr_sorted);
2742         EBUG_ON(trans->sorted[path->sorted_idx] != path->idx);
2743         EBUG_ON(!(trans->paths_allocated & (1ULL << path->idx)));
2744 }
2745
2746 static inline void btree_trans_verify_sorted_refs(struct btree_trans *trans)
2747 {
2748 #ifdef CONFIG_BCACHEFS_DEBUG
2749         unsigned i;
2750
2751         for (i = 0; i < trans->nr_sorted; i++)
2752                 btree_path_verify_sorted_ref(trans, trans->paths + trans->sorted[i]);
2753 #endif
2754 }
2755
2756 static void btree_trans_verify_sorted(struct btree_trans *trans)
2757 {
2758 #ifdef CONFIG_BCACHEFS_DEBUG
2759         struct btree_path *path, *prev = NULL;
2760         unsigned i;
2761
2762         trans_for_each_path_inorder(trans, path, i) {
2763                 BUG_ON(prev && btree_path_cmp(prev, path) > 0);
2764                 prev = path;
2765         }
2766 #endif
2767 }
2768
2769 static inline void btree_path_swap(struct btree_trans *trans,
2770                                    struct btree_path *l, struct btree_path *r)
2771 {
2772         swap(l->sorted_idx, r->sorted_idx);
2773         swap(trans->sorted[l->sorted_idx],
2774              trans->sorted[r->sorted_idx]);
2775
2776         btree_path_verify_sorted_ref(trans, l);
2777         btree_path_verify_sorted_ref(trans, r);
2778 }
2779
2780 static void btree_path_check_sort(struct btree_trans *trans, struct btree_path *path,
2781                                   int cmp)
2782 {
2783         struct btree_path *n;
2784
2785         if (cmp <= 0) {
2786                 n = prev_btree_path(trans, path);
2787                 if (n && btree_path_cmp(n, path) > 0) {
2788                         do {
2789                                 btree_path_swap(trans, n, path);
2790                                 n = prev_btree_path(trans, path);
2791                         } while (n && btree_path_cmp(n, path) > 0);
2792
2793                         goto out;
2794                 }
2795         }
2796
2797         if (cmp >= 0) {
2798                 n = next_btree_path(trans, path);
2799                 if (n && btree_path_cmp(path, n) > 0) {
2800                         do {
2801                                 btree_path_swap(trans, path, n);
2802                                 n = next_btree_path(trans, path);
2803                         } while (n && btree_path_cmp(path, n) > 0);
2804                 }
2805         }
2806 out:
2807         btree_trans_verify_sorted(trans);
2808 }
2809
2810 static inline void btree_path_list_remove(struct btree_trans *trans,
2811                                           struct btree_path *path)
2812 {
2813         unsigned i;
2814
2815         EBUG_ON(path->sorted_idx >= trans->nr_sorted);
2816
2817         array_remove_item(trans->sorted, trans->nr_sorted, path->sorted_idx);
2818
2819         for (i = path->sorted_idx; i < trans->nr_sorted; i++)
2820                 trans->paths[trans->sorted[i]].sorted_idx = i;
2821
2822         path->sorted_idx = U8_MAX;
2823
2824         btree_trans_verify_sorted_refs(trans);
2825 }
2826
2827 static inline void btree_path_list_add(struct btree_trans *trans,
2828                                        struct btree_path *pos,
2829                                        struct btree_path *path)
2830 {
2831         unsigned i;
2832
2833         btree_trans_verify_sorted_refs(trans);
2834
2835         path->sorted_idx = pos ? pos->sorted_idx + 1 : 0;
2836
2837         array_insert_item(trans->sorted, trans->nr_sorted, path->sorted_idx, path->idx);
2838
2839         for (i = path->sorted_idx; i < trans->nr_sorted; i++)
2840                 trans->paths[trans->sorted[i]].sorted_idx = i;
2841
2842         btree_trans_verify_sorted_refs(trans);
2843 }
2844
2845 void bch2_trans_iter_exit(struct btree_trans *trans, struct btree_iter *iter)
2846 {
2847         if (iter->path)
2848                 bch2_path_put(trans, iter->path,
2849                               iter->flags & BTREE_ITER_INTENT);
2850         if (iter->update_path)
2851                 bch2_path_put(trans, iter->update_path,
2852                               iter->flags & BTREE_ITER_INTENT);
2853         if (iter->key_cache_path)
2854                 bch2_path_put(trans, iter->key_cache_path,
2855                               iter->flags & BTREE_ITER_INTENT);
2856         iter->path = NULL;
2857         iter->update_path = NULL;
2858         iter->key_cache_path = NULL;
2859 }
2860
2861 static void __bch2_trans_iter_init(struct btree_trans *trans,
2862                                    struct btree_iter *iter,
2863                                    unsigned btree_id, struct bpos pos,
2864                                    unsigned locks_want,
2865                                    unsigned depth,
2866                                    unsigned flags,
2867                                    unsigned long ip)
2868 {
2869         EBUG_ON(trans->restarted);
2870
2871         if (!(flags & (BTREE_ITER_ALL_SNAPSHOTS|BTREE_ITER_NOT_EXTENTS)) &&
2872             btree_node_type_is_extents(btree_id))
2873                 flags |= BTREE_ITER_IS_EXTENTS;
2874
2875         if (!(flags & __BTREE_ITER_ALL_SNAPSHOTS) &&
2876             !btree_type_has_snapshots(btree_id))
2877                 flags &= ~BTREE_ITER_ALL_SNAPSHOTS;
2878
2879         if (!(flags & BTREE_ITER_ALL_SNAPSHOTS) &&
2880             btree_type_has_snapshots(btree_id))
2881                 flags |= BTREE_ITER_FILTER_SNAPSHOTS;
2882
2883         if (!test_bit(JOURNAL_REPLAY_DONE, &trans->c->journal.flags))
2884                 flags |= BTREE_ITER_WITH_JOURNAL;
2885
2886         if (!btree_id_cached(trans->c, btree_id)) {
2887                 flags &= ~BTREE_ITER_CACHED;
2888                 flags &= ~BTREE_ITER_WITH_KEY_CACHE;
2889         } else if (!(flags & BTREE_ITER_CACHED))
2890                 flags |= BTREE_ITER_WITH_KEY_CACHE;
2891
2892         iter->trans     = trans;
2893         iter->path      = NULL;
2894         iter->update_path = NULL;
2895         iter->key_cache_path = NULL;
2896         iter->btree_id  = btree_id;
2897         iter->min_depth = depth;
2898         iter->flags     = flags;
2899         iter->snapshot  = pos.snapshot;
2900         iter->pos       = pos;
2901         iter->k.type    = KEY_TYPE_deleted;
2902         iter->k.p       = pos;
2903         iter->k.size    = 0;
2904 #ifdef CONFIG_BCACHEFS_DEBUG
2905         iter->ip_allocated = ip;
2906 #endif
2907
2908         iter->path = bch2_path_get(trans, btree_id, iter->pos,
2909                                    locks_want, depth, flags, ip);
2910 }
2911
2912 void bch2_trans_iter_init(struct btree_trans *trans,
2913                           struct btree_iter *iter,
2914                           unsigned btree_id, struct bpos pos,
2915                           unsigned flags)
2916 {
2917         __bch2_trans_iter_init(trans, iter, btree_id, pos,
2918                                0, 0, flags, _RET_IP_);
2919 }
2920
2921 void bch2_trans_node_iter_init(struct btree_trans *trans,
2922                                struct btree_iter *iter,
2923                                enum btree_id btree_id,
2924                                struct bpos pos,
2925                                unsigned locks_want,
2926                                unsigned depth,
2927                                unsigned flags)
2928 {
2929         __bch2_trans_iter_init(trans, iter, btree_id, pos, locks_want, depth,
2930                                BTREE_ITER_NOT_EXTENTS|
2931                                __BTREE_ITER_ALL_SNAPSHOTS|
2932                                BTREE_ITER_ALL_SNAPSHOTS|
2933                                flags, _RET_IP_);
2934         BUG_ON(iter->path->locks_want    < min(locks_want, BTREE_MAX_DEPTH));
2935         BUG_ON(iter->path->level        != depth);
2936         BUG_ON(iter->min_depth          != depth);
2937 }
2938
2939 void bch2_trans_copy_iter(struct btree_iter *dst, struct btree_iter *src)
2940 {
2941         *dst = *src;
2942         if (src->path)
2943                 __btree_path_get(src->path, src->flags & BTREE_ITER_INTENT);
2944         if (src->update_path)
2945                 __btree_path_get(src->update_path, src->flags & BTREE_ITER_INTENT);
2946         dst->key_cache_path = NULL;
2947 }
2948
2949 void *bch2_trans_kmalloc(struct btree_trans *trans, size_t size)
2950 {
2951         size_t new_top = trans->mem_top + size;
2952         void *p;
2953
2954         if (new_top > trans->mem_bytes) {
2955                 size_t old_bytes = trans->mem_bytes;
2956                 size_t new_bytes = roundup_pow_of_two(new_top);
2957                 void *new_mem;
2958
2959                 WARN_ON_ONCE(new_bytes > BTREE_TRANS_MEM_MAX);
2960
2961                 new_mem = krealloc(trans->mem, new_bytes, GFP_NOFS);
2962                 if (!new_mem && new_bytes <= BTREE_TRANS_MEM_MAX) {
2963                         new_mem = mempool_alloc(&trans->c->btree_trans_mem_pool, GFP_KERNEL);
2964                         new_bytes = BTREE_TRANS_MEM_MAX;
2965                         kfree(trans->mem);
2966                 }
2967
2968                 if (!new_mem)
2969                         return ERR_PTR(-ENOMEM);
2970
2971                 trans->mem = new_mem;
2972                 trans->mem_bytes = new_bytes;
2973
2974                 if (old_bytes) {
2975                         trace_trans_restart_mem_realloced(trans->fn, _RET_IP_, new_bytes);
2976                         btree_trans_restart(trans);
2977                         return ERR_PTR(-EINTR);
2978                 }
2979         }
2980
2981         p = trans->mem + trans->mem_top;
2982         trans->mem_top += size;
2983         memset(p, 0, size);
2984         return p;
2985 }
2986
2987 /**
2988  * bch2_trans_begin() - reset a transaction after a interrupted attempt
2989  * @trans: transaction to reset
2990  *
2991  * While iterating over nodes or updating nodes a attempt to lock a btree
2992  * node may return EINTR when the trylock fails. When this occurs
2993  * bch2_trans_begin() should be called and the transaction retried.
2994  */
2995 void bch2_trans_begin(struct btree_trans *trans)
2996 {
2997         struct btree_insert_entry *i;
2998         struct btree_path *path;
2999
3000         trans_for_each_update(trans, i)
3001                 __btree_path_put(i->path, true);
3002
3003         memset(&trans->journal_res, 0, sizeof(trans->journal_res));
3004         trans->extra_journal_res        = 0;
3005         trans->nr_updates               = 0;
3006         trans->mem_top                  = 0;
3007
3008         trans->hooks                    = NULL;
3009         trans->extra_journal_entries    = NULL;
3010         trans->extra_journal_entry_u64s = 0;
3011
3012         if (trans->fs_usage_deltas) {
3013                 trans->fs_usage_deltas->used = 0;
3014                 memset(&trans->fs_usage_deltas->memset_start, 0,
3015                        (void *) &trans->fs_usage_deltas->memset_end -
3016                        (void *) &trans->fs_usage_deltas->memset_start);
3017         }
3018
3019         trans_for_each_path(trans, path) {
3020                 path->should_be_locked = false;
3021
3022                 /*
3023                  * XXX: we probably shouldn't be doing this if the transaction
3024                  * was restarted, but currently we still overflow transaction
3025                  * iterators if we do that
3026                  */
3027                 if (!path->ref && !path->preserve)
3028                         __bch2_path_free(trans, path);
3029                 else if (!path->ref)
3030                         path->preserve = false;
3031         }
3032
3033         bch2_trans_cond_resched(trans);
3034
3035         if (trans->restarted)
3036                 bch2_btree_path_traverse_all(trans);
3037
3038         trans->restarted = false;
3039 }
3040
3041 static void bch2_trans_alloc_paths(struct btree_trans *trans, struct bch_fs *c)
3042 {
3043         size_t paths_bytes      = sizeof(struct btree_path) * BTREE_ITER_MAX;
3044         size_t updates_bytes    = sizeof(struct btree_insert_entry) * BTREE_ITER_MAX;
3045         void *p = NULL;
3046
3047         BUG_ON(trans->used_mempool);
3048
3049 #ifdef __KERNEL__
3050         p = this_cpu_xchg(c->btree_paths_bufs->path , NULL);
3051 #endif
3052         if (!p)
3053                 p = mempool_alloc(&trans->c->btree_paths_pool, GFP_NOFS);
3054
3055         trans->paths            = p; p += paths_bytes;
3056         trans->updates          = p; p += updates_bytes;
3057 }
3058
3059 void __bch2_trans_init(struct btree_trans *trans, struct bch_fs *c,
3060                        unsigned expected_nr_iters,
3061                        size_t expected_mem_bytes,
3062                        const char *fn)
3063         __acquires(&c->btree_trans_barrier)
3064 {
3065         BUG_ON(lock_class_is_held(&bch2_btree_node_lock_key));
3066
3067         memset(trans, 0, sizeof(*trans));
3068         trans->c                = c;
3069         trans->fn               = fn;
3070
3071         bch2_trans_alloc_paths(trans, c);
3072
3073         if (expected_mem_bytes) {
3074                 trans->mem_bytes = roundup_pow_of_two(expected_mem_bytes);
3075                 trans->mem = kmalloc(trans->mem_bytes, GFP_KERNEL|__GFP_NOFAIL);
3076
3077                 if (!unlikely(trans->mem)) {
3078                         trans->mem = mempool_alloc(&c->btree_trans_mem_pool, GFP_KERNEL);
3079                         trans->mem_bytes = BTREE_TRANS_MEM_MAX;
3080                 }
3081         }
3082
3083         trans->srcu_idx = srcu_read_lock(&c->btree_trans_barrier);
3084
3085         trans->pid = current->pid;
3086         mutex_lock(&c->btree_trans_lock);
3087         list_add(&trans->list, &c->btree_trans_list);
3088         mutex_unlock(&c->btree_trans_lock);
3089 }
3090
3091 static void check_btree_paths_leaked(struct btree_trans *trans)
3092 {
3093 #ifdef CONFIG_BCACHEFS_DEBUG
3094         struct bch_fs *c = trans->c;
3095         struct btree_path *path;
3096
3097         trans_for_each_path(trans, path)
3098                 if (path->ref)
3099                         goto leaked;
3100         return;
3101 leaked:
3102         bch_err(c, "btree paths leaked from %s!", trans->fn);
3103         trans_for_each_path(trans, path)
3104                 if (path->ref)
3105                         printk(KERN_ERR "  btree %s %pS\n",
3106                                bch2_btree_ids[path->btree_id],
3107                                (void *) path->ip_allocated);
3108         /* Be noisy about this: */
3109         bch2_fatal_error(c);
3110 #endif
3111 }
3112
3113 void bch2_trans_exit(struct btree_trans *trans)
3114         __releases(&c->btree_trans_barrier)
3115 {
3116         struct btree_insert_entry *i;
3117         struct bch_fs *c = trans->c;
3118
3119         bch2_trans_unlock(trans);
3120
3121         trans_for_each_update(trans, i)
3122                 __btree_path_put(i->path, true);
3123         trans->nr_updates               = 0;
3124
3125         check_btree_paths_leaked(trans);
3126
3127         mutex_lock(&c->btree_trans_lock);
3128         list_del(&trans->list);
3129         mutex_unlock(&c->btree_trans_lock);
3130
3131         srcu_read_unlock(&c->btree_trans_barrier, trans->srcu_idx);
3132
3133         bch2_journal_preres_put(&c->journal, &trans->journal_preres);
3134
3135         if (trans->fs_usage_deltas) {
3136                 if (trans->fs_usage_deltas->size + sizeof(trans->fs_usage_deltas) ==
3137                     REPLICAS_DELTA_LIST_MAX)
3138                         mempool_free(trans->fs_usage_deltas,
3139                                      &c->replicas_delta_pool);
3140                 else
3141                         kfree(trans->fs_usage_deltas);
3142         }
3143
3144         if (trans->mem_bytes == BTREE_TRANS_MEM_MAX)
3145                 mempool_free(trans->mem, &c->btree_trans_mem_pool);
3146         else
3147                 kfree(trans->mem);
3148
3149 #ifdef __KERNEL__
3150         /*
3151          * Userspace doesn't have a real percpu implementation:
3152          */
3153         trans->paths = this_cpu_xchg(c->btree_paths_bufs->path, trans->paths);
3154 #endif
3155
3156         if (trans->paths)
3157                 mempool_free(trans->paths, &c->btree_paths_pool);
3158
3159         trans->mem      = (void *) 0x1;
3160         trans->paths    = (void *) 0x1;
3161 }
3162
3163 static void __maybe_unused
3164 bch2_btree_path_node_to_text(struct printbuf *out,
3165                              struct btree_bkey_cached_common *_b,
3166                              bool cached)
3167 {
3168         pr_buf(out, "    l=%u %s:",
3169                _b->level, bch2_btree_ids[_b->btree_id]);
3170         bch2_bpos_to_text(out, btree_node_pos(_b, cached));
3171 }
3172
3173 static bool trans_has_locks(struct btree_trans *trans)
3174 {
3175         struct btree_path *path;
3176
3177         trans_for_each_path(trans, path)
3178                 if (path->nodes_locked)
3179                         return true;
3180         return false;
3181 }
3182
3183 void bch2_btree_trans_to_text(struct printbuf *out, struct bch_fs *c)
3184 {
3185         struct btree_trans *trans;
3186         struct btree_path *path;
3187         struct btree *b;
3188         static char lock_types[] = { 'r', 'i', 'w' };
3189         unsigned l;
3190
3191         mutex_lock(&c->btree_trans_lock);
3192         list_for_each_entry(trans, &c->btree_trans_list, list) {
3193                 if (!trans_has_locks(trans))
3194                         continue;
3195
3196                 pr_buf(out, "%i %s\n", trans->pid, trans->fn);
3197
3198                 trans_for_each_path(trans, path) {
3199                         if (!path->nodes_locked)
3200                                 continue;
3201
3202                         pr_buf(out, "  path %u %c l=%u %s:",
3203                                path->idx,
3204                                path->cached ? 'c' : 'b',
3205                                path->level,
3206                                bch2_btree_ids[path->btree_id]);
3207                         bch2_bpos_to_text(out, path->pos);
3208                         pr_buf(out, "\n");
3209
3210                         for (l = 0; l < BTREE_MAX_DEPTH; l++) {
3211                                 if (btree_node_locked(path, l)) {
3212                                         pr_buf(out, "    %s l=%u ",
3213                                                btree_node_intent_locked(path, l) ? "i" : "r", l);
3214                                         bch2_btree_path_node_to_text(out,
3215                                                         (void *) path->l[l].b,
3216                                                         path->cached);
3217                                         pr_buf(out, "\n");
3218                                 }
3219                         }
3220                 }
3221
3222                 b = READ_ONCE(trans->locking);
3223                 if (b) {
3224                         path = &trans->paths[trans->locking_path_idx];
3225                         pr_buf(out, "  locking path %u %c l=%u %c %s:",
3226                                trans->locking_path_idx,
3227                                path->cached ? 'c' : 'b',
3228                                trans->locking_level,
3229                                lock_types[trans->locking_lock_type],
3230                                bch2_btree_ids[trans->locking_btree_id]);
3231                         bch2_bpos_to_text(out, trans->locking_pos);
3232
3233                         pr_buf(out, " node ");
3234                         bch2_btree_path_node_to_text(out,
3235                                         (void *) b, path->cached);
3236                         pr_buf(out, "\n");
3237                 }
3238         }
3239         mutex_unlock(&c->btree_trans_lock);
3240 }
3241
3242 void bch2_fs_btree_iter_exit(struct bch_fs *c)
3243 {
3244         if (c->btree_trans_barrier_initialized)
3245                 cleanup_srcu_struct(&c->btree_trans_barrier);
3246         mempool_exit(&c->btree_trans_mem_pool);
3247         mempool_exit(&c->btree_paths_pool);
3248 }
3249
3250 int bch2_fs_btree_iter_init(struct bch_fs *c)
3251 {
3252         unsigned nr = BTREE_ITER_MAX;
3253         int ret;
3254
3255         INIT_LIST_HEAD(&c->btree_trans_list);
3256         mutex_init(&c->btree_trans_lock);
3257
3258         ret   = mempool_init_kmalloc_pool(&c->btree_paths_pool, 1,
3259                         sizeof(struct btree_path) * nr +
3260                         sizeof(struct btree_insert_entry) * nr) ?:
3261                 mempool_init_kmalloc_pool(&c->btree_trans_mem_pool, 1,
3262                                           BTREE_TRANS_MEM_MAX) ?:
3263                 init_srcu_struct(&c->btree_trans_barrier);
3264         if (!ret)
3265                 c->btree_trans_barrier_initialized = true;
3266         return ret;
3267 }