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