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