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