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