]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_update_leaf.c
ee978f33390e5ae28ec5ad0035b6a6ab2eca89e0
[bcachefs-tools-debian] / libbcachefs / btree_update_leaf.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "btree_update.h"
5 #include "btree_update_interior.h"
6 #include "btree_gc.h"
7 #include "btree_io.h"
8 #include "btree_iter.h"
9 #include "btree_key_cache.h"
10 #include "btree_locking.h"
11 #include "buckets.h"
12 #include "debug.h"
13 #include "error.h"
14 #include "extent_update.h"
15 #include "journal.h"
16 #include "journal_reclaim.h"
17 #include "keylist.h"
18 #include "recovery.h"
19 #include "subvolume.h"
20 #include "replicas.h"
21
22 #include <linux/prefetch.h>
23 #include <linux/sort.h>
24 #include <trace/events/bcachefs.h>
25
26 static int __must_check
27 bch2_trans_update_by_path(struct btree_trans *, struct btree_path *,
28                           struct bkey_i *, enum btree_update_flags);
29
30 static inline int btree_insert_entry_cmp(const struct btree_insert_entry *l,
31                                          const struct btree_insert_entry *r)
32 {
33         return   cmp_int(l->btree_id,   r->btree_id) ?:
34                  -cmp_int(l->level,     r->level) ?:
35                  bpos_cmp(l->k->k.p,    r->k->k.p);
36 }
37
38 static inline struct btree_path_level *insert_l(struct btree_insert_entry *i)
39 {
40         return i->path->l + i->level;
41 }
42
43 static inline bool same_leaf_as_prev(struct btree_trans *trans,
44                                      struct btree_insert_entry *i)
45 {
46         return i != trans->updates &&
47                 insert_l(&i[0])->b == insert_l(&i[-1])->b;
48 }
49
50 static inline bool same_leaf_as_next(struct btree_trans *trans,
51                                      struct btree_insert_entry *i)
52 {
53         return i + 1 < trans->updates + trans->nr_updates &&
54                 insert_l(&i[0])->b == insert_l(&i[1])->b;
55 }
56
57 static inline void bch2_btree_node_prep_for_write(struct btree_trans *trans,
58                                                   struct btree_path *path,
59                                                   struct btree *b)
60 {
61         struct bch_fs *c = trans->c;
62
63         if (path->cached)
64                 return;
65
66         if (unlikely(btree_node_just_written(b)) &&
67             bch2_btree_post_write_cleanup(c, b))
68                 bch2_trans_node_reinit_iter(trans, b);
69
70         /*
71          * If the last bset has been written, or if it's gotten too big - start
72          * a new bset to insert into:
73          */
74         if (want_new_bset(c, b))
75                 bch2_btree_init_next(trans, b);
76 }
77
78 void bch2_btree_node_lock_for_insert(struct btree_trans *trans,
79                                      struct btree_path *path,
80                                      struct btree *b)
81 {
82         bch2_btree_node_lock_write(trans, path, b);
83         bch2_btree_node_prep_for_write(trans, path, b);
84 }
85
86 /* Inserting into a given leaf node (last stage of insert): */
87
88 /* Handle overwrites and do insert, for non extents: */
89 bool bch2_btree_bset_insert_key(struct btree_trans *trans,
90                                 struct btree_path *path,
91                                 struct btree *b,
92                                 struct btree_node_iter *node_iter,
93                                 struct bkey_i *insert)
94 {
95         struct bkey_packed *k;
96         unsigned clobber_u64s = 0, new_u64s = 0;
97
98         EBUG_ON(btree_node_just_written(b));
99         EBUG_ON(bset_written(b, btree_bset_last(b)));
100         EBUG_ON(bkey_deleted(&insert->k) && bkey_val_u64s(&insert->k));
101         EBUG_ON(bpos_cmp(insert->k.p, b->data->min_key) < 0);
102         EBUG_ON(bpos_cmp(insert->k.p, b->data->max_key) > 0);
103         EBUG_ON(insert->k.u64s >
104                 bch_btree_keys_u64s_remaining(trans->c, b));
105
106         k = bch2_btree_node_iter_peek_all(node_iter, b);
107         if (k && bkey_cmp_left_packed(b, k, &insert->k.p))
108                 k = NULL;
109
110         /* @k is the key being overwritten/deleted, if any: */
111         EBUG_ON(k && bkey_deleted(k));
112
113         /* Deleting, but not found? nothing to do: */
114         if (bkey_deleted(&insert->k) && !k)
115                 return false;
116
117         if (bkey_deleted(&insert->k)) {
118                 /* Deleting: */
119                 btree_account_key_drop(b, k);
120                 k->type = KEY_TYPE_deleted;
121
122                 if (k->needs_whiteout)
123                         push_whiteout(trans->c, b, insert->k.p);
124                 k->needs_whiteout = false;
125
126                 if (k >= btree_bset_last(b)->start) {
127                         clobber_u64s = k->u64s;
128                         bch2_bset_delete(b, k, clobber_u64s);
129                         goto fix_iter;
130                 } else {
131                         bch2_btree_path_fix_key_modified(trans, b, k);
132                 }
133
134                 return true;
135         }
136
137         if (k) {
138                 /* Overwriting: */
139                 btree_account_key_drop(b, k);
140                 k->type = KEY_TYPE_deleted;
141
142                 insert->k.needs_whiteout = k->needs_whiteout;
143                 k->needs_whiteout = false;
144
145                 if (k >= btree_bset_last(b)->start) {
146                         clobber_u64s = k->u64s;
147                         goto overwrite;
148                 } else {
149                         bch2_btree_path_fix_key_modified(trans, b, k);
150                 }
151         }
152
153         k = bch2_btree_node_iter_bset_pos(node_iter, b, bset_tree_last(b));
154 overwrite:
155         bch2_bset_insert(b, node_iter, k, insert, clobber_u64s);
156         new_u64s = k->u64s;
157 fix_iter:
158         if (clobber_u64s != new_u64s)
159                 bch2_btree_node_iter_fix(trans, path, b, node_iter, k,
160                                          clobber_u64s, new_u64s);
161         return true;
162 }
163
164 static int __btree_node_flush(struct journal *j, struct journal_entry_pin *pin,
165                                unsigned i, u64 seq)
166 {
167         struct bch_fs *c = container_of(j, struct bch_fs, journal);
168         struct btree_write *w = container_of(pin, struct btree_write, journal);
169         struct btree *b = container_of(w, struct btree, writes[i]);
170         unsigned long old, new, v;
171         unsigned idx = w - b->writes;
172
173         six_lock_read(&b->c.lock, NULL, NULL);
174         v = READ_ONCE(b->flags);
175
176         do {
177                 old = new = v;
178
179                 if (!(old & (1 << BTREE_NODE_dirty)) ||
180                     !!(old & (1 << BTREE_NODE_write_idx)) != idx ||
181                     w->journal.seq != seq)
182                         break;
183
184                 new |= 1 << BTREE_NODE_need_write;
185         } while ((v = cmpxchg(&b->flags, old, new)) != old);
186
187         btree_node_write_if_need(c, b, SIX_LOCK_read);
188         six_unlock_read(&b->c.lock);
189         return 0;
190 }
191
192 static int btree_node_flush0(struct journal *j, struct journal_entry_pin *pin, u64 seq)
193 {
194         return __btree_node_flush(j, pin, 0, seq);
195 }
196
197 static int btree_node_flush1(struct journal *j, struct journal_entry_pin *pin, u64 seq)
198 {
199         return __btree_node_flush(j, pin, 1, seq);
200 }
201
202 inline void bch2_btree_add_journal_pin(struct bch_fs *c,
203                                        struct btree *b, u64 seq)
204 {
205         struct btree_write *w = btree_current_write(b);
206
207         bch2_journal_pin_add(&c->journal, seq, &w->journal,
208                              btree_node_write_idx(b) == 0
209                              ? btree_node_flush0
210                              : btree_node_flush1);
211 }
212
213 /**
214  * btree_insert_key - insert a key one key into a leaf node
215  */
216 static bool btree_insert_key_leaf(struct btree_trans *trans,
217                                   struct btree_insert_entry *insert)
218 {
219         struct bch_fs *c = trans->c;
220         struct btree *b = insert_l(insert)->b;
221         struct bset_tree *t = bset_tree_last(b);
222         struct bset *i = bset(b, t);
223         int old_u64s = bset_u64s(t);
224         int old_live_u64s = b->nr.live_u64s;
225         int live_u64s_added, u64s_added;
226
227         if (unlikely(!bch2_btree_bset_insert_key(trans, insert->path, b,
228                                         &insert_l(insert)->iter, insert->k)))
229                 return false;
230
231         i->journal_seq = cpu_to_le64(max(trans->journal_res.seq,
232                                          le64_to_cpu(i->journal_seq)));
233
234         bch2_btree_add_journal_pin(c, b, trans->journal_res.seq);
235
236         if (unlikely(!btree_node_dirty(b)))
237                 set_btree_node_dirty_acct(c, b);
238
239         live_u64s_added = (int) b->nr.live_u64s - old_live_u64s;
240         u64s_added = (int) bset_u64s(t) - old_u64s;
241
242         if (b->sib_u64s[0] != U16_MAX && live_u64s_added < 0)
243                 b->sib_u64s[0] = max(0, (int) b->sib_u64s[0] + live_u64s_added);
244         if (b->sib_u64s[1] != U16_MAX && live_u64s_added < 0)
245                 b->sib_u64s[1] = max(0, (int) b->sib_u64s[1] + live_u64s_added);
246
247         if (u64s_added > live_u64s_added &&
248             bch2_maybe_compact_whiteouts(c, b))
249                 bch2_trans_node_reinit_iter(trans, b);
250
251         return true;
252 }
253
254 /* Cached btree updates: */
255
256 /* Normal update interface: */
257
258 static inline void btree_insert_entry_checks(struct btree_trans *trans,
259                                              struct btree_insert_entry *i)
260 {
261         BUG_ON(bpos_cmp(i->k->k.p, i->path->pos));
262         BUG_ON(i->cached        != i->path->cached);
263         BUG_ON(i->level         != i->path->level);
264         BUG_ON(i->btree_id      != i->path->btree_id);
265         EBUG_ON(!i->level &&
266                 !(i->flags & BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE) &&
267                 test_bit(JOURNAL_REPLAY_DONE, &trans->c->journal.flags) &&
268                 i->k->k.p.snapshot &&
269                 bch2_snapshot_internal_node(trans->c, i->k->k.p.snapshot));
270 }
271
272 static noinline int
273 bch2_trans_journal_preres_get_cold(struct btree_trans *trans, unsigned u64s,
274                                    unsigned long trace_ip)
275 {
276         struct bch_fs *c = trans->c;
277         int ret;
278
279         bch2_trans_unlock(trans);
280
281         ret = bch2_journal_preres_get(&c->journal,
282                         &trans->journal_preres, u64s, 0);
283         if (ret)
284                 return ret;
285
286         if (!bch2_trans_relock(trans)) {
287                 trace_trans_restart_journal_preres_get(trans->fn, trace_ip);
288                 return -EINTR;
289         }
290
291         return 0;
292 }
293
294 static inline int bch2_trans_journal_res_get(struct btree_trans *trans,
295                                              unsigned flags)
296 {
297         struct bch_fs *c = trans->c;
298         int ret;
299
300         if (trans->flags & BTREE_INSERT_JOURNAL_RESERVED)
301                 flags |= JOURNAL_RES_GET_RESERVED;
302
303         ret = bch2_journal_res_get(&c->journal, &trans->journal_res,
304                                    trans->journal_u64s, flags);
305
306         return ret == -EAGAIN ? BTREE_INSERT_NEED_JOURNAL_RES : ret;
307 }
308
309 #define JSET_ENTRY_LOG_U64s             4
310
311 static noinline void journal_transaction_name(struct btree_trans *trans)
312 {
313         struct bch_fs *c = trans->c;
314         struct jset_entry *entry = journal_res_entry(&c->journal, &trans->journal_res);
315         struct jset_entry_log *l = container_of(entry, struct jset_entry_log, entry);
316         unsigned u64s = JSET_ENTRY_LOG_U64s - 1;
317         unsigned b, buflen = u64s * sizeof(u64);
318
319         l->entry.u64s           = cpu_to_le16(u64s);
320         l->entry.btree_id       = 0;
321         l->entry.level          = 0;
322         l->entry.type           = BCH_JSET_ENTRY_log;
323         l->entry.pad[0]         = 0;
324         l->entry.pad[1]         = 0;
325         l->entry.pad[2]         = 0;
326         b = min_t(unsigned, strlen(trans->fn), buflen);
327         memcpy(l->d, trans->fn, b);
328         while (b < buflen)
329                 l->d[b++] = '\0';
330
331         trans->journal_res.offset       += JSET_ENTRY_LOG_U64s;
332         trans->journal_res.u64s         -= JSET_ENTRY_LOG_U64s;
333 }
334
335 static inline enum btree_insert_ret
336 btree_key_can_insert(struct btree_trans *trans,
337                      struct btree *b,
338                      unsigned u64s)
339 {
340         struct bch_fs *c = trans->c;
341
342         if (!bch2_btree_node_insert_fits(c, b, u64s))
343                 return BTREE_INSERT_BTREE_NODE_FULL;
344
345         return BTREE_INSERT_OK;
346 }
347
348 static enum btree_insert_ret
349 btree_key_can_insert_cached(struct btree_trans *trans,
350                             struct btree_path *path,
351                             unsigned u64s)
352 {
353         struct bch_fs *c = trans->c;
354         struct bkey_cached *ck = (void *) path->l[0].b;
355         unsigned new_u64s;
356         struct bkey_i *new_k;
357
358         EBUG_ON(path->level);
359
360         if (!test_bit(BKEY_CACHED_DIRTY, &ck->flags) &&
361             bch2_btree_key_cache_must_wait(c) &&
362             !(trans->flags & BTREE_INSERT_JOURNAL_RECLAIM))
363                 return BTREE_INSERT_NEED_JOURNAL_RECLAIM;
364
365         /*
366          * bch2_varint_decode can read past the end of the buffer by at most 7
367          * bytes (it won't be used):
368          */
369         u64s += 1;
370
371         if (u64s <= ck->u64s)
372                 return BTREE_INSERT_OK;
373
374         new_u64s        = roundup_pow_of_two(u64s);
375         new_k           = krealloc(ck->k, new_u64s * sizeof(u64), GFP_NOFS);
376         if (!new_k) {
377                 bch_err(c, "error allocating memory for key cache key, btree %s u64s %u",
378                         bch2_btree_ids[path->btree_id], new_u64s);
379                 return -ENOMEM;
380         }
381
382         ck->u64s        = new_u64s;
383         ck->k           = new_k;
384         /*
385          * Keys returned by peek() are no longer valid pointers, so we need a
386          * transaction restart:
387          */
388         trace_trans_restart_key_cache_key_realloced(trans->fn, _RET_IP_,
389                                              path->btree_id, &path->pos);
390         /*
391          * Not using btree_trans_restart() because we can't unlock here, we have
392          * write locks held:
393          */
394         trans->restarted = true;
395         return -EINTR;
396 }
397
398 static inline void do_btree_insert_one(struct btree_trans *trans,
399                                        struct btree_insert_entry *i)
400 {
401         struct bch_fs *c = trans->c;
402         struct journal *j = &c->journal;
403         bool did_work;
404
405         EBUG_ON(trans->journal_res.ref !=
406                 !(trans->flags & BTREE_INSERT_JOURNAL_REPLAY));
407
408         i->k->k.needs_whiteout = false;
409
410         did_work = !i->cached
411                 ? btree_insert_key_leaf(trans, i)
412                 : bch2_btree_insert_key_cached(trans, i->path, i->k);
413         if (!did_work)
414                 return;
415
416         if (likely(!(trans->flags & BTREE_INSERT_JOURNAL_REPLAY))) {
417                 bch2_journal_add_keys(j, &trans->journal_res,
418                                       i->btree_id,
419                                       i->level,
420                                       i->k);
421
422                 if (trans->journal_seq)
423                         *trans->journal_seq = trans->journal_res.seq;
424         }
425 }
426
427 /* Triggers: */
428
429 static int run_one_mem_trigger(struct btree_trans *trans,
430                                struct btree_insert_entry *i,
431                                unsigned flags)
432 {
433         struct bkey_s_c old = { &i->old_k, i->old_v };
434         struct bkey_i *new = i->k;
435         int ret;
436
437         if (unlikely(flags & BTREE_TRIGGER_NORUN))
438                 return 0;
439
440         if (!btree_node_type_needs_gc(i->btree_id))
441                 return 0;
442
443         if (old.k->type == new->k.type &&
444             ((1U << old.k->type) & BTREE_TRIGGER_WANTS_OLD_AND_NEW)) {
445                 ret   = bch2_mark_key(trans, old, bkey_i_to_s_c(new),
446                                 BTREE_TRIGGER_INSERT|BTREE_TRIGGER_OVERWRITE|flags);
447         } else {
448                 struct bkey             _deleted = KEY(0, 0, 0);
449                 struct bkey_s_c         deleted = (struct bkey_s_c) { &_deleted, NULL };
450
451                 _deleted.p = i->path->pos;
452
453                 ret   = bch2_mark_key(trans, deleted, bkey_i_to_s_c(new),
454                                 BTREE_TRIGGER_INSERT|flags) ?:
455                         bch2_mark_key(trans, old, deleted,
456                                 BTREE_TRIGGER_OVERWRITE|flags);
457         }
458
459         return ret;
460 }
461
462 static int run_one_trans_trigger(struct btree_trans *trans, struct btree_insert_entry *i,
463                            bool overwrite)
464 {
465         struct bkey_s_c old = { &i->old_k, i->old_v };
466         int ret = 0;
467
468         if ((i->flags & BTREE_TRIGGER_NORUN) ||
469             !(BTREE_NODE_TYPE_HAS_TRANS_TRIGGERS & (1U << i->bkey_type)))
470                 return 0;
471
472         if (!overwrite) {
473                 if (i->insert_trigger_run)
474                         return 0;
475
476                 BUG_ON(i->overwrite_trigger_run);
477                 i->insert_trigger_run = true;
478         } else {
479                 if (i->overwrite_trigger_run)
480                         return 0;
481
482                 BUG_ON(!i->insert_trigger_run);
483                 i->overwrite_trigger_run = true;
484         }
485
486         if (overwrite) {
487                 ret = bch2_trans_mark_old(trans, old, i->flags);
488         } else if (old.k->type == i->k->k.type &&
489             ((1U << old.k->type) & BTREE_TRIGGER_WANTS_OLD_AND_NEW)) {
490                 i->overwrite_trigger_run = true;
491                 ret = bch2_trans_mark_key(trans, old, i->k,
492                                 BTREE_TRIGGER_INSERT|BTREE_TRIGGER_OVERWRITE|i->flags);
493         } else {
494                 ret = bch2_trans_mark_new(trans, i->k, i->flags);
495         }
496
497         if (ret == -EINTR)
498                 trace_trans_restart_mark(trans->fn, _RET_IP_,
499                                          i->btree_id, &i->path->pos);
500         return ret ?: 1;
501 }
502
503 static int run_btree_triggers(struct btree_trans *trans, enum btree_id btree_id,
504                               struct btree_insert_entry *btree_id_start)
505 {
506         struct btree_insert_entry *i;
507         bool trans_trigger_run;
508         int ret, overwrite;
509
510         for (overwrite = 0; overwrite < 2; overwrite++) {
511
512                 /*
513                  * Running triggers will append more updates to the list of updates as
514                  * we're walking it:
515                  */
516                 do {
517                         trans_trigger_run = false;
518
519                         for (i = btree_id_start;
520                              i < trans->updates + trans->nr_updates && i->btree_id <= btree_id;
521                              i++) {
522                                 if (i->btree_id != btree_id)
523                                         continue;
524
525                                 ret = run_one_trans_trigger(trans, i, overwrite);
526                                 if (ret < 0)
527                                         return ret;
528                                 if (ret)
529                                         trans_trigger_run = true;
530                         }
531                 } while (trans_trigger_run);
532         }
533
534         return 0;
535 }
536
537 static int bch2_trans_commit_run_triggers(struct btree_trans *trans)
538 {
539         struct btree_insert_entry *i = NULL, *btree_id_start = trans->updates;
540         unsigned btree_id = 0;
541         int ret = 0;
542
543         /*
544          *
545          * For a given btree, this algorithm runs insert triggers before
546          * overwrite triggers: this is so that when extents are being moved
547          * (e.g. by FALLOCATE_FL_INSERT_RANGE), we don't drop references before
548          * they are re-added.
549          */
550         for (btree_id = 0; btree_id < BTREE_ID_NR; btree_id++) {
551                 if (btree_id == BTREE_ID_alloc)
552                         continue;
553
554                 while (btree_id_start < trans->updates + trans->nr_updates &&
555                        btree_id_start->btree_id < btree_id)
556                         btree_id_start++;
557
558                 ret = run_btree_triggers(trans, btree_id, btree_id_start);
559                 if (ret)
560                         return ret;
561         }
562
563         trans_for_each_update(trans, i) {
564                 if (i->btree_id > BTREE_ID_alloc)
565                         break;
566                 if (i->btree_id == BTREE_ID_alloc) {
567                         ret = run_btree_triggers(trans, BTREE_ID_alloc, i);
568                         if (ret)
569                                 return ret;
570                         break;
571                 }
572         }
573
574         trans_for_each_update(trans, i)
575                 BUG_ON(!(i->flags & BTREE_TRIGGER_NORUN) &&
576                        (BTREE_NODE_TYPE_HAS_TRANS_TRIGGERS & (1U << i->bkey_type)) &&
577                        (!i->insert_trigger_run || !i->overwrite_trigger_run));
578
579         return 0;
580 }
581
582 static noinline int bch2_trans_commit_run_gc_triggers(struct btree_trans *trans)
583 {
584         struct bch_fs *c = trans->c;
585         struct btree_insert_entry *i;
586         int ret = 0;
587
588         trans_for_each_update(trans, i) {
589                 /*
590                  * XXX: synchronization of cached update triggers with gc
591                  * XXX: synchronization of interior node updates with gc
592                  */
593                 BUG_ON(i->cached || i->level);
594
595                 if (gc_visited(c, gc_pos_btree_node(insert_l(i)->b))) {
596                         ret = run_one_mem_trigger(trans, i, i->flags|BTREE_TRIGGER_GC);
597                         if (ret)
598                                 break;
599                 }
600         }
601
602         return ret;
603 }
604
605 static inline int
606 bch2_trans_commit_write_locked(struct btree_trans *trans,
607                                struct btree_insert_entry **stopped_at,
608                                unsigned long trace_ip)
609 {
610         struct bch_fs *c = trans->c;
611         struct btree_insert_entry *i;
612         struct btree_trans_commit_hook *h;
613         unsigned u64s = 0;
614         bool marking = false;
615         int ret;
616
617         if (race_fault()) {
618                 trace_trans_restart_fault_inject(trans->fn, trace_ip);
619                 trans->restarted = true;
620                 return -EINTR;
621         }
622
623         /*
624          * Check if the insert will fit in the leaf node with the write lock
625          * held, otherwise another thread could write the node changing the
626          * amount of space available:
627          */
628
629         prefetch(&trans->c->journal.flags);
630
631         h = trans->hooks;
632         while (h) {
633                 ret = h->fn(trans, h);
634                 if (ret)
635                         return ret;
636                 h = h->next;
637         }
638
639         trans_for_each_update(trans, i) {
640                 /* Multiple inserts might go to same leaf: */
641                 if (!same_leaf_as_prev(trans, i))
642                         u64s = 0;
643
644                 u64s += i->k->k.u64s;
645                 ret = !i->cached
646                         ? btree_key_can_insert(trans, insert_l(i)->b, u64s)
647                         : btree_key_can_insert_cached(trans, i->path, u64s);
648                 if (ret) {
649                         *stopped_at = i;
650                         return ret;
651                 }
652
653                 if (btree_node_type_needs_gc(i->bkey_type))
654                         marking = true;
655         }
656
657         /*
658          * Don't get journal reservation until after we know insert will
659          * succeed:
660          */
661         if (likely(!(trans->flags & BTREE_INSERT_JOURNAL_REPLAY))) {
662                 ret = bch2_trans_journal_res_get(trans,
663                                 JOURNAL_RES_GET_NONBLOCK);
664                 if (ret)
665                         return ret;
666
667                 if (unlikely(trans->journal_transaction_names))
668                         journal_transaction_name(trans);
669         } else {
670                 trans->journal_res.seq = c->journal.replay_journal_seq;
671         }
672
673         if (unlikely(trans->extra_journal_entry_u64s)) {
674                 memcpy_u64s_small(journal_res_entry(&c->journal, &trans->journal_res),
675                                   trans->extra_journal_entries,
676                                   trans->extra_journal_entry_u64s);
677
678                 trans->journal_res.offset       += trans->extra_journal_entry_u64s;
679                 trans->journal_res.u64s         -= trans->extra_journal_entry_u64s;
680         }
681
682         /*
683          * Not allowed to fail after we've gotten our journal reservation - we
684          * have to use it:
685          */
686
687         if (!(trans->flags & BTREE_INSERT_JOURNAL_REPLAY)) {
688                 if (bch2_journal_seq_verify)
689                         trans_for_each_update(trans, i)
690                                 i->k->k.version.lo = trans->journal_res.seq;
691                 else if (bch2_inject_invalid_keys)
692                         trans_for_each_update(trans, i)
693                                 i->k->k.version = MAX_VERSION;
694         }
695
696         if (trans->fs_usage_deltas &&
697             bch2_trans_fs_usage_apply(trans, trans->fs_usage_deltas))
698                 return BTREE_INSERT_NEED_MARK_REPLICAS;
699
700         trans_for_each_update(trans, i)
701                 if (BTREE_NODE_TYPE_HAS_MEM_TRIGGERS & (1U << i->bkey_type)) {
702                         ret = run_one_mem_trigger(trans, i, i->flags);
703                         if (ret)
704                                 return ret;
705                 }
706
707         if (unlikely(c->gc_pos.phase)) {
708                 ret = bch2_trans_commit_run_gc_triggers(trans);
709                 if  (ret)
710                         return ret;
711         }
712
713         trans_for_each_update(trans, i)
714                 do_btree_insert_one(trans, i);
715
716         return ret;
717 }
718
719 static inline void path_upgrade_readers(struct btree_trans *trans, struct btree_path *path)
720 {
721         unsigned l;
722
723         for (l = 0; l < BTREE_MAX_DEPTH; l++)
724                 if (btree_node_read_locked(path, l))
725                         BUG_ON(!bch2_btree_node_upgrade(trans, path, l));
726 }
727
728 static inline void upgrade_readers(struct btree_trans *trans, struct btree_path *path)
729 {
730         struct btree *b = path_l(path)->b;
731
732         do {
733                 if (path->nodes_locked &&
734                     path->nodes_locked != path->nodes_intent_locked)
735                         path_upgrade_readers(trans, path);
736         } while ((path = prev_btree_path(trans, path)) &&
737                  path_l(path)->b == b);
738 }
739
740 /*
741  * Check for nodes that we have both read and intent locks on, and upgrade the
742  * readers to intent:
743  */
744 static inline void normalize_read_intent_locks(struct btree_trans *trans)
745 {
746         struct btree_path *path;
747         unsigned i, nr_read = 0, nr_intent = 0;
748
749         trans_for_each_path_inorder(trans, path, i) {
750                 struct btree_path *next = i + 1 < trans->nr_sorted
751                         ? trans->paths + trans->sorted[i + 1]
752                         : NULL;
753
754                 if (path->nodes_locked) {
755                         if (path->nodes_intent_locked)
756                                 nr_intent++;
757                         else
758                                 nr_read++;
759                 }
760
761                 if (!next || path_l(path)->b != path_l(next)->b) {
762                         if (nr_read && nr_intent)
763                                 upgrade_readers(trans, path);
764
765                         nr_read = nr_intent = 0;
766                 }
767         }
768
769         bch2_trans_verify_locks(trans);
770 }
771
772 static inline bool have_conflicting_read_lock(struct btree_trans *trans, struct btree_path *pos)
773 {
774         struct btree_path *path;
775         unsigned i;
776
777         trans_for_each_path_inorder(trans, path, i) {
778                 //if (path == pos)
779                 //      break;
780
781                 if (path->nodes_locked != path->nodes_intent_locked &&
782                     !bch2_btree_path_upgrade(trans, path, path->level + 1))
783                         return true;
784         }
785
786         return false;
787 }
788
789 static inline int trans_lock_write(struct btree_trans *trans)
790 {
791         struct btree_insert_entry *i;
792
793         trans_for_each_update(trans, i) {
794                 if (same_leaf_as_prev(trans, i))
795                         continue;
796
797                 if (!six_trylock_write(&insert_l(i)->b->c.lock)) {
798                         if (have_conflicting_read_lock(trans, i->path))
799                                 goto fail;
800
801                         btree_node_lock_type(trans, i->path,
802                                              insert_l(i)->b,
803                                              i->path->pos, i->level,
804                                              SIX_LOCK_write, NULL, NULL);
805                 }
806
807                 bch2_btree_node_prep_for_write(trans, i->path, insert_l(i)->b);
808         }
809
810         return 0;
811 fail:
812         while (--i >= trans->updates) {
813                 if (same_leaf_as_prev(trans, i))
814                         continue;
815
816                 bch2_btree_node_unlock_write_inlined(trans, i->path, insert_l(i)->b);
817         }
818
819         trace_trans_restart_would_deadlock_write(trans->fn);
820         return btree_trans_restart(trans);
821 }
822
823 static noinline void bch2_drop_overwrites_from_journal(struct btree_trans *trans)
824 {
825         struct btree_insert_entry *i;
826
827         trans_for_each_update(trans, i)
828                 bch2_journal_key_overwritten(trans->c, i->btree_id, i->level, i->k->k.p);
829 }
830
831 /*
832  * Get journal reservation, take write locks, and attempt to do btree update(s):
833  */
834 static inline int do_bch2_trans_commit(struct btree_trans *trans,
835                                        struct btree_insert_entry **stopped_at,
836                                        unsigned long trace_ip)
837 {
838         struct bch_fs *c = trans->c;
839         struct btree_insert_entry *i;
840         int ret, u64s_delta = 0;
841
842         trans_for_each_update(trans, i) {
843                 const char *invalid = bch2_bkey_invalid(c,
844                                 bkey_i_to_s_c(i->k), i->bkey_type);
845                 if (invalid) {
846                         struct printbuf buf = PRINTBUF;
847
848                         bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(i->k));
849                         bch2_fs_fatal_error(c, "invalid bkey %s on insert from %s -> %ps: %s\n",
850                                             buf.buf, trans->fn, (void *) i->ip_allocated, invalid);
851                         printbuf_exit(&buf);
852                         return -EINVAL;
853                 }
854                 btree_insert_entry_checks(trans, i);
855         }
856
857         trans_for_each_update(trans, i) {
858                 if (i->cached)
859                         continue;
860
861                 u64s_delta += !bkey_deleted(&i->k->k) ? i->k->k.u64s : 0;
862                 u64s_delta -= i->old_btree_u64s;
863
864                 if (!same_leaf_as_next(trans, i)) {
865                         if (u64s_delta <= 0) {
866                                 ret = bch2_foreground_maybe_merge(trans, i->path,
867                                                         i->level, trans->flags);
868                                 if (unlikely(ret))
869                                         return ret;
870                         }
871
872                         u64s_delta = 0;
873                 }
874         }
875
876         ret = bch2_journal_preres_get(&c->journal,
877                         &trans->journal_preres, trans->journal_preres_u64s,
878                         JOURNAL_RES_GET_NONBLOCK|
879                         ((trans->flags & BTREE_INSERT_JOURNAL_RESERVED)
880                          ? JOURNAL_RES_GET_RESERVED : 0));
881         if (unlikely(ret == -EAGAIN))
882                 ret = bch2_trans_journal_preres_get_cold(trans,
883                                                 trans->journal_preres_u64s, trace_ip);
884         if (unlikely(ret))
885                 return ret;
886
887         normalize_read_intent_locks(trans);
888
889         ret = trans_lock_write(trans);
890         if (unlikely(ret))
891                 return ret;
892
893         ret = bch2_trans_commit_write_locked(trans, stopped_at, trace_ip);
894
895         if (!ret && unlikely(!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags)))
896                 bch2_drop_overwrites_from_journal(trans);
897
898         trans_for_each_update(trans, i)
899                 if (!same_leaf_as_prev(trans, i))
900                         bch2_btree_node_unlock_write_inlined(trans, i->path,
901                                                         insert_l(i)->b);
902
903         if (!ret && trans->journal_pin)
904                 bch2_journal_pin_add(&c->journal, trans->journal_res.seq,
905                                      trans->journal_pin, NULL);
906
907         /*
908          * Drop journal reservation after dropping write locks, since dropping
909          * the journal reservation may kick off a journal write:
910          */
911         bch2_journal_res_put(&c->journal, &trans->journal_res);
912
913         if (unlikely(ret))
914                 return ret;
915
916         bch2_trans_downgrade(trans);
917
918         return 0;
919 }
920
921 static int journal_reclaim_wait_done(struct bch_fs *c)
922 {
923         int ret = bch2_journal_error(&c->journal) ?:
924                 !bch2_btree_key_cache_must_wait(c);
925
926         if (!ret)
927                 journal_reclaim_kick(&c->journal);
928         return ret;
929 }
930
931 static noinline
932 int bch2_trans_commit_error(struct btree_trans *trans,
933                             struct btree_insert_entry *i,
934                             int ret, unsigned long trace_ip)
935 {
936         struct bch_fs *c = trans->c;
937
938         switch (ret) {
939         case BTREE_INSERT_BTREE_NODE_FULL:
940                 ret = bch2_btree_split_leaf(trans, i->path, trans->flags);
941                 if (!ret)
942                         return 0;
943
944                 if (ret == -EINTR)
945                         trace_trans_restart_btree_node_split(trans->fn, trace_ip,
946                                                 i->btree_id, &i->path->pos);
947                 break;
948         case BTREE_INSERT_NEED_MARK_REPLICAS:
949                 bch2_trans_unlock(trans);
950
951                 ret = bch2_replicas_delta_list_mark(c, trans->fs_usage_deltas);
952                 if (ret)
953                         break;
954
955                 if (bch2_trans_relock(trans))
956                         return 0;
957
958                 trace_trans_restart_mark_replicas(trans->fn, trace_ip);
959                 ret = -EINTR;
960                 break;
961         case BTREE_INSERT_NEED_JOURNAL_RES:
962                 bch2_trans_unlock(trans);
963
964                 if ((trans->flags & BTREE_INSERT_JOURNAL_RECLAIM) &&
965                     !(trans->flags & BTREE_INSERT_JOURNAL_RESERVED)) {
966                         trans->restarted = true;
967                         ret = -EAGAIN;
968                         break;
969                 }
970
971                 ret = bch2_trans_journal_res_get(trans, JOURNAL_RES_GET_CHECK);
972                 if (ret)
973                         break;
974
975                 if (bch2_trans_relock(trans))
976                         return 0;
977
978                 trace_trans_restart_journal_res_get(trans->fn, trace_ip);
979                 ret = -EINTR;
980                 break;
981         case BTREE_INSERT_NEED_JOURNAL_RECLAIM:
982                 bch2_trans_unlock(trans);
983
984                 trace_trans_blocked_journal_reclaim(trans->fn, trace_ip);
985
986                 wait_event_freezable(c->journal.reclaim_wait,
987                                      (ret = journal_reclaim_wait_done(c)));
988                 if (ret < 0)
989                         break;
990
991                 if (bch2_trans_relock(trans))
992                         return 0;
993
994                 trace_trans_restart_journal_reclaim(trans->fn, trace_ip);
995                 ret = -EINTR;
996                 break;
997         default:
998                 BUG_ON(ret >= 0);
999                 break;
1000         }
1001
1002         BUG_ON((ret == EINTR || ret == -EAGAIN) && !trans->restarted);
1003         BUG_ON(ret == -ENOSPC &&
1004                !(trans->flags & BTREE_INSERT_NOWAIT) &&
1005                (trans->flags & BTREE_INSERT_NOFAIL));
1006
1007         return ret;
1008 }
1009
1010 static noinline int
1011 bch2_trans_commit_get_rw_cold(struct btree_trans *trans)
1012 {
1013         struct bch_fs *c = trans->c;
1014         int ret;
1015
1016         if (likely(!(trans->flags & BTREE_INSERT_LAZY_RW)) ||
1017             test_bit(BCH_FS_STARTED, &c->flags))
1018                 return -EROFS;
1019
1020         bch2_trans_unlock(trans);
1021
1022         ret = bch2_fs_read_write_early(c);
1023         if (ret)
1024                 return ret;
1025
1026         if (!bch2_trans_relock(trans))
1027                 return -EINTR;
1028
1029         percpu_ref_get(&c->writes);
1030         return 0;
1031 }
1032
1033 /*
1034  * This is for updates done in the early part of fsck - btree_gc - before we've
1035  * gone RW. we only add the new key to the list of keys for journal replay to
1036  * do.
1037  */
1038 static noinline int
1039 do_bch2_trans_commit_to_journal_replay(struct btree_trans *trans)
1040 {
1041         struct bch_fs *c = trans->c;
1042         struct btree_insert_entry *i;
1043         int ret = 0;
1044
1045         trans_for_each_update(trans, i) {
1046                 ret = bch2_journal_key_insert(c, i->btree_id, i->level, i->k);
1047                 if (ret)
1048                         break;
1049         }
1050
1051         return ret;
1052 }
1053
1054 int __bch2_trans_commit(struct btree_trans *trans)
1055 {
1056         struct bch_fs *c = trans->c;
1057         struct btree_insert_entry *i = NULL;
1058         unsigned u64s;
1059         int ret = 0;
1060
1061         if (!trans->nr_updates &&
1062             !trans->extra_journal_entry_u64s)
1063                 goto out_reset;
1064
1065         if (trans->flags & BTREE_INSERT_GC_LOCK_HELD)
1066                 lockdep_assert_held(&c->gc_lock);
1067
1068         ret = bch2_trans_commit_run_triggers(trans);
1069         if (ret)
1070                 goto out_reset;
1071
1072         if (unlikely(!test_bit(BCH_FS_MAY_GO_RW, &c->flags))) {
1073                 ret = do_bch2_trans_commit_to_journal_replay(trans);
1074                 goto out_reset;
1075         }
1076
1077         if (!(trans->flags & BTREE_INSERT_NOCHECK_RW) &&
1078             unlikely(!percpu_ref_tryget(&c->writes))) {
1079                 ret = bch2_trans_commit_get_rw_cold(trans);
1080                 if (ret)
1081                         goto out_reset;
1082         }
1083
1084         memset(&trans->journal_preres, 0, sizeof(trans->journal_preres));
1085
1086         trans->journal_u64s             = trans->extra_journal_entry_u64s;
1087         trans->journal_preres_u64s      = 0;
1088
1089         trans->journal_transaction_names = READ_ONCE(c->opts.journal_transaction_names);
1090
1091         if (trans->journal_transaction_names)
1092                 trans->journal_u64s += JSET_ENTRY_LOG_U64s;
1093
1094         trans_for_each_update(trans, i) {
1095                 BUG_ON(!i->path->should_be_locked);
1096
1097                 if (unlikely(!bch2_btree_path_upgrade(trans, i->path, i->level + 1))) {
1098                         trace_trans_restart_upgrade(trans->fn, _RET_IP_,
1099                                                     i->btree_id, &i->path->pos);
1100                         ret = btree_trans_restart(trans);
1101                         goto out;
1102                 }
1103
1104                 BUG_ON(!btree_node_intent_locked(i->path, i->level));
1105
1106                 u64s = jset_u64s(i->k->k.u64s);
1107                 if (i->cached &&
1108                     likely(!(trans->flags & BTREE_INSERT_JOURNAL_REPLAY)))
1109                         trans->journal_preres_u64s += u64s;
1110                 trans->journal_u64s += u64s;
1111         }
1112
1113         if (trans->extra_journal_res) {
1114                 ret = bch2_disk_reservation_add(c, trans->disk_res,
1115                                 trans->extra_journal_res,
1116                                 (trans->flags & BTREE_INSERT_NOFAIL)
1117                                 ? BCH_DISK_RESERVATION_NOFAIL : 0);
1118                 if (ret)
1119                         goto err;
1120         }
1121 retry:
1122         BUG_ON(trans->restarted);
1123         memset(&trans->journal_res, 0, sizeof(trans->journal_res));
1124
1125         ret = do_bch2_trans_commit(trans, &i, _RET_IP_);
1126
1127         /* make sure we didn't drop or screw up locks: */
1128         bch2_trans_verify_locks(trans);
1129
1130         if (ret)
1131                 goto err;
1132 out:
1133         bch2_journal_preres_put(&c->journal, &trans->journal_preres);
1134
1135         if (likely(!(trans->flags & BTREE_INSERT_NOCHECK_RW)))
1136                 percpu_ref_put(&c->writes);
1137 out_reset:
1138         trans_for_each_update(trans, i)
1139                 bch2_path_put(trans, i->path, true);
1140
1141         trans->extra_journal_res        = 0;
1142         trans->nr_updates               = 0;
1143         trans->hooks                    = NULL;
1144         trans->extra_journal_entries    = NULL;
1145         trans->extra_journal_entry_u64s = 0;
1146
1147         if (trans->fs_usage_deltas) {
1148                 trans->fs_usage_deltas->used = 0;
1149                 memset(&trans->fs_usage_deltas->memset_start, 0,
1150                        (void *) &trans->fs_usage_deltas->memset_end -
1151                        (void *) &trans->fs_usage_deltas->memset_start);
1152         }
1153
1154         return ret;
1155 err:
1156         ret = bch2_trans_commit_error(trans, i, ret, _RET_IP_);
1157         if (ret)
1158                 goto out;
1159
1160         goto retry;
1161 }
1162
1163 static int check_pos_snapshot_overwritten(struct btree_trans *trans,
1164                                           enum btree_id id,
1165                                           struct bpos pos)
1166 {
1167         struct bch_fs *c = trans->c;
1168         struct btree_iter iter;
1169         struct bkey_s_c k;
1170         int ret;
1171
1172         if (!btree_type_has_snapshots(id))
1173                 return 0;
1174
1175         if (!snapshot_t(c, pos.snapshot)->children[0])
1176                 return 0;
1177
1178         bch2_trans_iter_init(trans, &iter, id, pos,
1179                              BTREE_ITER_NOT_EXTENTS|
1180                              BTREE_ITER_ALL_SNAPSHOTS);
1181         while (1) {
1182                 k = bch2_btree_iter_prev(&iter);
1183                 ret = bkey_err(k);
1184                 if (ret)
1185                         break;
1186
1187                 if (!k.k)
1188                         break;
1189
1190                 if (bkey_cmp(pos, k.k->p))
1191                         break;
1192
1193                 if (bch2_snapshot_is_ancestor(c, k.k->p.snapshot, pos.snapshot)) {
1194                         ret = 1;
1195                         break;
1196                 }
1197         }
1198         bch2_trans_iter_exit(trans, &iter);
1199
1200         return ret;
1201 }
1202
1203 int bch2_trans_update_extent(struct btree_trans *trans,
1204                              struct btree_iter *orig_iter,
1205                              struct bkey_i *insert,
1206                              enum btree_update_flags flags)
1207 {
1208         struct bch_fs *c = trans->c;
1209         struct btree_iter iter, update_iter;
1210         struct bpos start = bkey_start_pos(&insert->k);
1211         struct bkey_i *update;
1212         struct bkey_s_c k;
1213         enum btree_id btree_id = orig_iter->btree_id;
1214         int ret = 0, compressed_sectors;
1215
1216         bch2_trans_iter_init(trans, &iter, btree_id, start,
1217                              BTREE_ITER_INTENT|
1218                              BTREE_ITER_WITH_UPDATES|
1219                              BTREE_ITER_NOT_EXTENTS);
1220         k = bch2_btree_iter_peek(&iter);
1221         if ((ret = bkey_err(k)))
1222                 goto err;
1223         if (!k.k)
1224                 goto out;
1225
1226         if (bch2_bkey_maybe_mergable(k.k, &insert->k)) {
1227                 /*
1228                  * We can't merge extents if they belong to interior snapshot
1229                  * tree nodes, and there's a snapshot in which one extent is
1230                  * visible and the other is not - i.e. if visibility is
1231                  * different.
1232                  *
1233                  * Instead of checking if visibilitiy of the two extents is
1234                  * different, for now we just check if either has been
1235                  * overwritten:
1236                  */
1237                 ret = check_pos_snapshot_overwritten(trans, btree_id, insert->k.p);
1238                 if (ret < 0)
1239                         goto err;
1240                 if (ret)
1241                         goto nomerge1;
1242
1243                 ret = check_pos_snapshot_overwritten(trans, btree_id, k.k->p);
1244                 if (ret < 0)
1245                         goto err;
1246                 if (ret)
1247                         goto nomerge1;
1248
1249                 update = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1250                 if ((ret = PTR_ERR_OR_ZERO(update)))
1251                         goto err;
1252
1253                 bkey_reassemble(update, k);
1254
1255                 if (bch2_bkey_merge(c, bkey_i_to_s(update), bkey_i_to_s_c(insert))) {
1256                         ret = bch2_btree_delete_at(trans, &iter, flags);
1257                         if (ret)
1258                                 goto err;
1259
1260                         insert = update;
1261                         goto next;
1262                 }
1263         }
1264 nomerge1:
1265         ret = 0;
1266         if (!bkey_cmp(k.k->p, start))
1267                 goto next;
1268
1269         while (bkey_cmp(insert->k.p, bkey_start_pos(k.k)) > 0) {
1270                 bool front_split = bkey_cmp(bkey_start_pos(k.k), start) < 0;
1271                 bool back_split  = bkey_cmp(k.k->p, insert->k.p) > 0;
1272
1273                 /*
1274                  * If we're going to be splitting a compressed extent, note it
1275                  * so that __bch2_trans_commit() can increase our disk
1276                  * reservation:
1277                  */
1278                 if (((front_split && back_split) ||
1279                      ((front_split || back_split) && k.k->p.snapshot != insert->k.p.snapshot)) &&
1280                     (compressed_sectors = bch2_bkey_sectors_compressed(k)))
1281                         trans->extra_journal_res += compressed_sectors;
1282
1283                 if (front_split) {
1284                         update = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1285                         if ((ret = PTR_ERR_OR_ZERO(update)))
1286                                 goto err;
1287
1288                         bkey_reassemble(update, k);
1289
1290                         bch2_cut_back(start, update);
1291
1292                         bch2_trans_iter_init(trans, &update_iter, btree_id, update->k.p,
1293                                              BTREE_ITER_NOT_EXTENTS|
1294                                              BTREE_ITER_ALL_SNAPSHOTS|
1295                                              BTREE_ITER_INTENT);
1296                         ret   = bch2_btree_iter_traverse(&update_iter) ?:
1297                                 bch2_trans_update(trans, &update_iter, update,
1298                                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
1299                                                   flags);
1300                         bch2_trans_iter_exit(trans, &update_iter);
1301
1302                         if (ret)
1303                                 goto err;
1304                 }
1305
1306                 if (k.k->p.snapshot != insert->k.p.snapshot &&
1307                     (front_split || back_split)) {
1308                         update = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1309                         if ((ret = PTR_ERR_OR_ZERO(update)))
1310                                 goto err;
1311
1312                         bkey_reassemble(update, k);
1313
1314                         bch2_cut_front(start, update);
1315                         bch2_cut_back(insert->k.p, update);
1316
1317                         bch2_trans_iter_init(trans, &update_iter, btree_id, update->k.p,
1318                                              BTREE_ITER_NOT_EXTENTS|
1319                                              BTREE_ITER_ALL_SNAPSHOTS|
1320                                              BTREE_ITER_INTENT);
1321                         ret   = bch2_btree_iter_traverse(&update_iter) ?:
1322                                 bch2_trans_update(trans, &update_iter, update,
1323                                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
1324                                                   flags);
1325                         bch2_trans_iter_exit(trans, &update_iter);
1326                         if (ret)
1327                                 goto err;
1328                 }
1329
1330                 if (bkey_cmp(k.k->p, insert->k.p) <= 0) {
1331                         update = bch2_trans_kmalloc(trans, sizeof(*update));
1332                         if ((ret = PTR_ERR_OR_ZERO(update)))
1333                                 goto err;
1334
1335                         bkey_init(&update->k);
1336                         update->k.p = k.k->p;
1337
1338                         if (insert->k.p.snapshot != k.k->p.snapshot) {
1339                                 update->k.p.snapshot = insert->k.p.snapshot;
1340                                 update->k.type = KEY_TYPE_whiteout;
1341                         }
1342
1343                         bch2_trans_iter_init(trans, &update_iter, btree_id, update->k.p,
1344                                              BTREE_ITER_NOT_EXTENTS|
1345                                              BTREE_ITER_INTENT);
1346                         ret   = bch2_btree_iter_traverse(&update_iter) ?:
1347                                 bch2_trans_update(trans, &update_iter, update,
1348                                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
1349                                                   flags);
1350                         bch2_trans_iter_exit(trans, &update_iter);
1351
1352                         if (ret)
1353                                 goto err;
1354                 }
1355
1356                 if (back_split) {
1357                         update = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
1358                         if ((ret = PTR_ERR_OR_ZERO(update)))
1359                                 goto err;
1360
1361                         bkey_reassemble(update, k);
1362                         bch2_cut_front(insert->k.p, update);
1363
1364                         ret = bch2_trans_update_by_path(trans, iter.path, update,
1365                                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
1366                                                   flags);
1367                         if (ret)
1368                                 goto err;
1369                         goto out;
1370                 }
1371 next:
1372                 k = bch2_btree_iter_next(&iter);
1373                 if ((ret = bkey_err(k)))
1374                         goto err;
1375                 if (!k.k)
1376                         goto out;
1377         }
1378
1379         if (bch2_bkey_maybe_mergable(&insert->k, k.k)) {
1380                 ret = check_pos_snapshot_overwritten(trans, btree_id, insert->k.p);
1381                 if (ret < 0)
1382                         goto err;
1383                 if (ret)
1384                         goto nomerge2;
1385
1386                 ret = check_pos_snapshot_overwritten(trans, btree_id, k.k->p);
1387                 if (ret < 0)
1388                         goto err;
1389                 if (ret)
1390                         goto nomerge2;
1391
1392                 bch2_bkey_merge(c, bkey_i_to_s(insert), k);
1393         }
1394 nomerge2:
1395         ret = 0;
1396 out:
1397         if (!bkey_deleted(&insert->k)) {
1398                 /*
1399                  * Rewinding iterators is expensive: get a new one and the one
1400                  * that points to the start of insert will be cloned from:
1401                  */
1402                 bch2_trans_iter_exit(trans, &iter);
1403                 bch2_trans_iter_init(trans, &iter, btree_id, insert->k.p,
1404                                      BTREE_ITER_NOT_EXTENTS|
1405                                      BTREE_ITER_INTENT);
1406                 ret   = bch2_btree_iter_traverse(&iter) ?:
1407                         bch2_trans_update(trans, &iter, insert, flags);
1408         }
1409 err:
1410         bch2_trans_iter_exit(trans, &iter);
1411
1412         return ret;
1413 }
1414
1415 /*
1416  * When deleting, check if we need to emit a whiteout (because we're overwriting
1417  * something in an ancestor snapshot)
1418  */
1419 static int need_whiteout_for_snapshot(struct btree_trans *trans,
1420                                       enum btree_id btree_id, struct bpos pos)
1421 {
1422         struct btree_iter iter;
1423         struct bkey_s_c k;
1424         u32 snapshot = pos.snapshot;
1425         int ret;
1426
1427         if (!bch2_snapshot_parent(trans->c, pos.snapshot))
1428                 return 0;
1429
1430         pos.snapshot++;
1431
1432         for_each_btree_key_norestart(trans, iter, btree_id, pos,
1433                            BTREE_ITER_ALL_SNAPSHOTS|
1434                            BTREE_ITER_NOPRESERVE, k, ret) {
1435                 if (bkey_cmp(k.k->p, pos))
1436                         break;
1437
1438                 if (bch2_snapshot_is_ancestor(trans->c, snapshot,
1439                                               k.k->p.snapshot)) {
1440                         ret = !bkey_whiteout(k.k);
1441                         break;
1442                 }
1443         }
1444         bch2_trans_iter_exit(trans, &iter);
1445
1446         return ret;
1447 }
1448
1449 static int __must_check
1450 bch2_trans_update_by_path(struct btree_trans *trans, struct btree_path *path,
1451                           struct bkey_i *k, enum btree_update_flags flags)
1452 {
1453         struct bch_fs *c = trans->c;
1454         struct btree_insert_entry *i, n;
1455
1456         BUG_ON(!path->should_be_locked);
1457
1458         BUG_ON(trans->nr_updates >= BTREE_ITER_MAX);
1459         BUG_ON(bpos_cmp(k->k.p, path->pos));
1460
1461         n = (struct btree_insert_entry) {
1462                 .flags          = flags,
1463                 .bkey_type      = __btree_node_type(path->level, path->btree_id),
1464                 .btree_id       = path->btree_id,
1465                 .level          = path->level,
1466                 .cached         = path->cached,
1467                 .path           = path,
1468                 .k              = k,
1469                 .ip_allocated   = _RET_IP_,
1470         };
1471
1472 #ifdef CONFIG_BCACHEFS_DEBUG
1473         trans_for_each_update(trans, i)
1474                 BUG_ON(i != trans->updates &&
1475                        btree_insert_entry_cmp(i - 1, i) >= 0);
1476 #endif
1477
1478         /*
1479          * Pending updates are kept sorted: first, find position of new update,
1480          * then delete/trim any updates the new update overwrites:
1481          */
1482         trans_for_each_update(trans, i)
1483                 if (btree_insert_entry_cmp(&n, i) <= 0)
1484                         break;
1485
1486         if (i < trans->updates + trans->nr_updates &&
1487             !btree_insert_entry_cmp(&n, i)) {
1488                 BUG_ON(i->insert_trigger_run || i->overwrite_trigger_run);
1489
1490                 bch2_path_put(trans, i->path, true);
1491                 i->flags        = n.flags;
1492                 i->cached       = n.cached;
1493                 i->k            = n.k;
1494                 i->path         = n.path;
1495                 i->ip_allocated = n.ip_allocated;
1496         } else {
1497                 array_insert_item(trans->updates, trans->nr_updates,
1498                                   i - trans->updates, n);
1499
1500                 i->old_v = bch2_btree_path_peek_slot(path, &i->old_k).v;
1501                 i->old_btree_u64s = !bkey_deleted(&i->old_k) ? i->old_k.u64s : 0;
1502
1503                 if (unlikely(!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags))) {
1504                         struct bkey_i *j_k =
1505                                 bch2_journal_keys_peek(c, n.btree_id, n.level, k->k.p);
1506
1507                         if (j_k && !bpos_cmp(j_k->k.p, i->k->k.p)) {
1508                                 i->old_k = j_k->k;
1509                                 i->old_v = &j_k->v;
1510                         }
1511                 }
1512         }
1513
1514         __btree_path_get(n.path, true);
1515         return 0;
1516 }
1517
1518 int __must_check bch2_trans_update(struct btree_trans *trans, struct btree_iter *iter,
1519                                    struct bkey_i *k, enum btree_update_flags flags)
1520 {
1521         struct btree_path *path = iter->update_path ?: iter->path;
1522         struct bkey_cached *ck;
1523         int ret;
1524
1525         if (iter->flags & BTREE_ITER_IS_EXTENTS)
1526                 return bch2_trans_update_extent(trans, iter, k, flags);
1527
1528         if (bkey_deleted(&k->k) &&
1529             !(flags & BTREE_UPDATE_KEY_CACHE_RECLAIM) &&
1530             (iter->flags & BTREE_ITER_FILTER_SNAPSHOTS)) {
1531                 ret = need_whiteout_for_snapshot(trans, iter->btree_id, k->k.p);
1532                 if (unlikely(ret < 0))
1533                         return ret;
1534
1535                 if (ret)
1536                         k->k.type = KEY_TYPE_whiteout;
1537         }
1538
1539         if (!(flags & BTREE_UPDATE_KEY_CACHE_RECLAIM) &&
1540             !path->cached &&
1541             !path->level &&
1542             btree_id_cached(trans->c, path->btree_id)) {
1543                 if (!iter->key_cache_path ||
1544                     !iter->key_cache_path->should_be_locked ||
1545                     bpos_cmp(iter->key_cache_path->pos, k->k.p)) {
1546                         if (!iter->key_cache_path)
1547                                 iter->key_cache_path =
1548                                         bch2_path_get(trans, path->btree_id, path->pos, 1, 0,
1549                                                       BTREE_ITER_INTENT|
1550                                                       BTREE_ITER_CACHED, _THIS_IP_);
1551
1552                         iter->key_cache_path =
1553                                 bch2_btree_path_set_pos(trans, iter->key_cache_path, path->pos,
1554                                                         iter->flags & BTREE_ITER_INTENT,
1555                                                         _THIS_IP_);
1556
1557                         ret = bch2_btree_path_traverse(trans, iter->key_cache_path,
1558                                                        BTREE_ITER_CACHED);
1559                         if (unlikely(ret))
1560                                 return ret;
1561
1562                         ck = (void *) iter->key_cache_path->l[0].b;
1563
1564                         if (test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
1565                                 trace_trans_restart_key_cache_raced(trans->fn, _RET_IP_);
1566                                 btree_trans_restart(trans);
1567                                 return -EINTR;
1568                         }
1569
1570                         iter->key_cache_path->should_be_locked = true;
1571                 }
1572
1573                 path = iter->key_cache_path;
1574         }
1575
1576         return bch2_trans_update_by_path(trans, path, k, flags);
1577 }
1578
1579 void bch2_trans_commit_hook(struct btree_trans *trans,
1580                             struct btree_trans_commit_hook *h)
1581 {
1582         h->next = trans->hooks;
1583         trans->hooks = h;
1584 }
1585
1586 int __bch2_btree_insert(struct btree_trans *trans,
1587                         enum btree_id id, struct bkey_i *k)
1588 {
1589         struct btree_iter iter;
1590         int ret;
1591
1592         bch2_trans_iter_init(trans, &iter, id, bkey_start_pos(&k->k),
1593                              BTREE_ITER_INTENT);
1594         ret   = bch2_btree_iter_traverse(&iter) ?:
1595                 bch2_trans_update(trans, &iter, k, 0);
1596         bch2_trans_iter_exit(trans, &iter);
1597         return ret;
1598 }
1599
1600 /**
1601  * bch2_btree_insert - insert keys into the extent btree
1602  * @c:                  pointer to struct bch_fs
1603  * @id:                 btree to insert into
1604  * @insert_keys:        list of keys to insert
1605  * @hook:               insert callback
1606  */
1607 int bch2_btree_insert(struct bch_fs *c, enum btree_id id,
1608                       struct bkey_i *k,
1609                       struct disk_reservation *disk_res,
1610                       u64 *journal_seq, int flags)
1611 {
1612         return bch2_trans_do(c, disk_res, journal_seq, flags,
1613                              __bch2_btree_insert(&trans, id, k));
1614 }
1615
1616 int bch2_btree_delete_at(struct btree_trans *trans,
1617                          struct btree_iter *iter, unsigned update_flags)
1618 {
1619         struct bkey_i *k;
1620
1621         k = bch2_trans_kmalloc(trans, sizeof(*k));
1622         if (IS_ERR(k))
1623                 return PTR_ERR(k);
1624
1625         bkey_init(&k->k);
1626         k->k.p = iter->pos;
1627         return bch2_trans_update(trans, iter, k, update_flags);
1628 }
1629
1630 int bch2_btree_delete_range_trans(struct btree_trans *trans, enum btree_id id,
1631                                   struct bpos start, struct bpos end,
1632                                   unsigned iter_flags,
1633                                   u64 *journal_seq)
1634 {
1635         struct btree_iter iter;
1636         struct bkey_s_c k;
1637         int ret = 0;
1638
1639         bch2_trans_iter_init(trans, &iter, id, start, BTREE_ITER_INTENT|iter_flags);
1640 retry:
1641         while ((bch2_trans_begin(trans),
1642                (k = bch2_btree_iter_peek(&iter)).k) &&
1643                !(ret = bkey_err(k)) &&
1644                bkey_cmp(iter.pos, end) < 0) {
1645                 struct disk_reservation disk_res =
1646                         bch2_disk_reservation_init(trans->c, 0);
1647                 struct bkey_i delete;
1648
1649                 bkey_init(&delete.k);
1650
1651                 /*
1652                  * This could probably be more efficient for extents:
1653                  */
1654
1655                 /*
1656                  * For extents, iter.pos won't necessarily be the same as
1657                  * bkey_start_pos(k.k) (for non extents they always will be the
1658                  * same). It's important that we delete starting from iter.pos
1659                  * because the range we want to delete could start in the middle
1660                  * of k.
1661                  *
1662                  * (bch2_btree_iter_peek() does guarantee that iter.pos >=
1663                  * bkey_start_pos(k.k)).
1664                  */
1665                 delete.k.p = iter.pos;
1666
1667                 if (iter.flags & BTREE_ITER_IS_EXTENTS) {
1668                         unsigned max_sectors =
1669                                 KEY_SIZE_MAX & (~0 << trans->c->block_bits);
1670
1671                         /* create the biggest key we can */
1672                         bch2_key_resize(&delete.k, max_sectors);
1673                         bch2_cut_back(end, &delete);
1674
1675                         ret = bch2_extent_trim_atomic(trans, &iter, &delete);
1676                         if (ret)
1677                                 break;
1678                 }
1679
1680                 ret   = bch2_trans_update(trans, &iter, &delete, 0) ?:
1681                         bch2_trans_commit(trans, &disk_res, journal_seq,
1682                                         BTREE_INSERT_NOFAIL);
1683                 bch2_disk_reservation_put(trans->c, &disk_res);
1684                 if (ret)
1685                         break;
1686         }
1687
1688         if (ret == -EINTR) {
1689                 ret = 0;
1690                 goto retry;
1691         }
1692
1693         bch2_trans_iter_exit(trans, &iter);
1694         return ret;
1695 }
1696
1697 /*
1698  * bch_btree_delete_range - delete everything within a given range
1699  *
1700  * Range is a half open interval - [start, end)
1701  */
1702 int bch2_btree_delete_range(struct bch_fs *c, enum btree_id id,
1703                             struct bpos start, struct bpos end,
1704                             unsigned iter_flags,
1705                             u64 *journal_seq)
1706 {
1707         return bch2_trans_do(c, NULL, journal_seq, 0,
1708                              bch2_btree_delete_range_trans(&trans, id, start, end,
1709                                                            iter_flags, journal_seq));
1710 }