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