1076d32945f8818f21e46494523ea975481a4212
[linux-block.git] / fs / bcachefs / extents.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
4  *
5  * Code for managing the extent btree and dynamically updating the writeback
6  * dirty sector count.
7  */
8
9 #include "bcachefs.h"
10 #include "bkey_methods.h"
11 #include "btree_gc.h"
12 #include "btree_update.h"
13 #include "btree_update_interior.h"
14 #include "buckets.h"
15 #include "checksum.h"
16 #include "debug.h"
17 #include "dirent.h"
18 #include "disk_groups.h"
19 #include "error.h"
20 #include "extents.h"
21 #include "inode.h"
22 #include "journal.h"
23 #include "replicas.h"
24 #include "super.h"
25 #include "super-io.h"
26 #include "trace.h"
27 #include "util.h"
28 #include "xattr.h"
29
30 unsigned bch2_bkey_nr_ptrs(struct bkey_s_c k)
31 {
32         struct bkey_ptrs_c p = bch2_bkey_ptrs_c(k);
33         const struct bch_extent_ptr *ptr;
34         unsigned nr_ptrs = 0;
35
36         bkey_for_each_ptr(p, ptr)
37                 nr_ptrs++;
38
39         return nr_ptrs;
40 }
41
42 unsigned bch2_bkey_nr_dirty_ptrs(struct bkey_s_c k)
43 {
44         unsigned nr_ptrs = 0;
45
46         switch (k.k->type) {
47         case KEY_TYPE_btree_ptr:
48         case KEY_TYPE_extent: {
49                 struct bkey_ptrs_c p = bch2_bkey_ptrs_c(k);
50                 const struct bch_extent_ptr *ptr;
51
52                 bkey_for_each_ptr(p, ptr)
53                         nr_ptrs += !ptr->cached;
54                 BUG_ON(!nr_ptrs);
55                 break;
56         }
57         case KEY_TYPE_reservation:
58                 nr_ptrs = bkey_s_c_to_reservation(k).v->nr_replicas;
59                 break;
60         }
61
62         return nr_ptrs;
63 }
64
65 static unsigned bch2_extent_ptr_durability(struct bch_fs *c,
66                                            struct extent_ptr_decoded p)
67 {
68         unsigned i, durability = 0;
69         struct bch_dev *ca;
70
71         if (p.ptr.cached)
72                 return 0;
73
74         ca = bch_dev_bkey_exists(c, p.ptr.dev);
75
76         if (ca->mi.state != BCH_MEMBER_STATE_FAILED)
77                 durability = max_t(unsigned, durability, ca->mi.durability);
78
79         for (i = 0; i < p.ec_nr; i++) {
80                 struct stripe *s =
81                         genradix_ptr(&c->stripes[0], p.idx);
82
83                 if (WARN_ON(!s))
84                         continue;
85
86                 durability = max_t(unsigned, durability, s->nr_redundant);
87         }
88
89         return durability;
90 }
91
92 unsigned bch2_bkey_durability(struct bch_fs *c, struct bkey_s_c k)
93 {
94         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
95         const union bch_extent_entry *entry;
96         struct extent_ptr_decoded p;
97         unsigned durability = 0;
98
99         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
100                 durability += bch2_extent_ptr_durability(c, p);
101
102         return durability;
103 }
104
105 static struct bch_dev_io_failures *dev_io_failures(struct bch_io_failures *f,
106                                                    unsigned dev)
107 {
108         struct bch_dev_io_failures *i;
109
110         for (i = f->devs; i < f->devs + f->nr; i++)
111                 if (i->dev == dev)
112                         return i;
113
114         return NULL;
115 }
116
117 void bch2_mark_io_failure(struct bch_io_failures *failed,
118                           struct extent_ptr_decoded *p)
119 {
120         struct bch_dev_io_failures *f = dev_io_failures(failed, p->ptr.dev);
121
122         if (!f) {
123                 BUG_ON(failed->nr >= ARRAY_SIZE(failed->devs));
124
125                 f = &failed->devs[failed->nr++];
126                 f->dev          = p->ptr.dev;
127                 f->idx          = p->idx;
128                 f->nr_failed    = 1;
129                 f->nr_retries   = 0;
130         } else if (p->idx != f->idx) {
131                 f->idx          = p->idx;
132                 f->nr_failed    = 1;
133                 f->nr_retries   = 0;
134         } else {
135                 f->nr_failed++;
136         }
137 }
138
139 /*
140  * returns true if p1 is better than p2:
141  */
142 static inline bool ptr_better(struct bch_fs *c,
143                               const struct extent_ptr_decoded p1,
144                               const struct extent_ptr_decoded p2)
145 {
146         if (likely(!p1.idx && !p2.idx)) {
147                 struct bch_dev *dev1 = bch_dev_bkey_exists(c, p1.ptr.dev);
148                 struct bch_dev *dev2 = bch_dev_bkey_exists(c, p2.ptr.dev);
149
150                 u64 l1 = atomic64_read(&dev1->cur_latency[READ]);
151                 u64 l2 = atomic64_read(&dev2->cur_latency[READ]);
152
153                 /* Pick at random, biased in favor of the faster device: */
154
155                 return bch2_rand_range(l1 + l2) > l1;
156         }
157
158         if (force_reconstruct_read(c))
159                 return p1.idx > p2.idx;
160
161         return p1.idx < p2.idx;
162 }
163
164 /*
165  * This picks a non-stale pointer, preferably from a device other than @avoid.
166  * Avoid can be NULL, meaning pick any. If there are no non-stale pointers to
167  * other devices, it will still pick a pointer from avoid.
168  */
169 int bch2_bkey_pick_read_device(struct bch_fs *c, struct bkey_s_c k,
170                                struct bch_io_failures *failed,
171                                struct extent_ptr_decoded *pick)
172 {
173         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
174         const union bch_extent_entry *entry;
175         struct extent_ptr_decoded p;
176         struct bch_dev_io_failures *f;
177         struct bch_dev *ca;
178         int ret = 0;
179
180         if (k.k->type == KEY_TYPE_error)
181                 return -EIO;
182
183         bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
184                 ca = bch_dev_bkey_exists(c, p.ptr.dev);
185
186                 /*
187                  * If there are any dirty pointers it's an error if we can't
188                  * read:
189                  */
190                 if (!ret && !p.ptr.cached)
191                         ret = -EIO;
192
193                 if (p.ptr.cached && ptr_stale(ca, &p.ptr))
194                         continue;
195
196                 f = failed ? dev_io_failures(failed, p.ptr.dev) : NULL;
197                 if (f)
198                         p.idx = f->nr_failed < f->nr_retries
199                                 ? f->idx
200                                 : f->idx + 1;
201
202                 if (!p.idx &&
203                     !bch2_dev_is_readable(ca))
204                         p.idx++;
205
206                 if (force_reconstruct_read(c) &&
207                     !p.idx && p.ec_nr)
208                         p.idx++;
209
210                 if (p.idx >= p.ec_nr + 1)
211                         continue;
212
213                 if (ret > 0 && !ptr_better(c, p, *pick))
214                         continue;
215
216                 *pick = p;
217                 ret = 1;
218         }
219
220         return ret;
221 }
222
223 void bch2_bkey_append_ptr(struct bkey_i *k,
224                           struct bch_extent_ptr ptr)
225 {
226         EBUG_ON(bch2_bkey_has_device(bkey_i_to_s_c(k), ptr.dev));
227
228         switch (k->k.type) {
229         case KEY_TYPE_btree_ptr:
230         case KEY_TYPE_extent:
231                 EBUG_ON(bkey_val_u64s(&k->k) >= BKEY_EXTENT_VAL_U64s_MAX);
232
233                 ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
234
235                 memcpy((void *) &k->v + bkey_val_bytes(&k->k),
236                        &ptr,
237                        sizeof(ptr));
238                 k->u64s++;
239                 break;
240         default:
241                 BUG();
242         }
243 }
244
245 void bch2_bkey_drop_device(struct bkey_s k, unsigned dev)
246 {
247         struct bch_extent_ptr *ptr;
248
249         bch2_bkey_drop_ptrs(k, ptr, ptr->dev == dev);
250 }
251
252 /* extent specific utility code */
253
254 const struct bch_extent_ptr *
255 bch2_extent_has_device(struct bkey_s_c_extent e, unsigned dev)
256 {
257         const struct bch_extent_ptr *ptr;
258
259         extent_for_each_ptr(e, ptr)
260                 if (ptr->dev == dev)
261                         return ptr;
262
263         return NULL;
264 }
265
266 const struct bch_extent_ptr *
267 bch2_extent_has_group(struct bch_fs *c, struct bkey_s_c_extent e, unsigned group)
268 {
269         const struct bch_extent_ptr *ptr;
270
271         extent_for_each_ptr(e, ptr) {
272                 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
273
274                 if (ca->mi.group &&
275                     ca->mi.group - 1 == group)
276                         return ptr;
277         }
278
279         return NULL;
280 }
281
282 const struct bch_extent_ptr *
283 bch2_extent_has_target(struct bch_fs *c, struct bkey_s_c_extent e, unsigned target)
284 {
285         const struct bch_extent_ptr *ptr;
286
287         extent_for_each_ptr(e, ptr)
288                 if (bch2_dev_in_target(c, ptr->dev, target) &&
289                     (!ptr->cached ||
290                      !ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr)))
291                         return ptr;
292
293         return NULL;
294 }
295
296 unsigned bch2_extent_is_compressed(struct bkey_s_c k)
297 {
298         unsigned ret = 0;
299
300         switch (k.k->type) {
301         case KEY_TYPE_extent: {
302                 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
303                 const union bch_extent_entry *entry;
304                 struct extent_ptr_decoded p;
305
306                 extent_for_each_ptr_decode(e, p, entry)
307                         if (!p.ptr.cached &&
308                             p.crc.compression_type != BCH_COMPRESSION_NONE)
309                                 ret += p.crc.compressed_size;
310         }
311         }
312
313         return ret;
314 }
315
316 bool bch2_extent_matches_ptr(struct bch_fs *c, struct bkey_s_c_extent e,
317                              struct bch_extent_ptr m, u64 offset)
318 {
319         const union bch_extent_entry *entry;
320         struct extent_ptr_decoded p;
321
322         extent_for_each_ptr_decode(e, p, entry)
323                 if (p.ptr.dev   == m.dev &&
324                     p.ptr.gen   == m.gen &&
325                     (s64) p.ptr.offset + p.crc.offset - bkey_start_offset(e.k) ==
326                     (s64) m.offset  - offset)
327                         return true;
328
329         return false;
330 }
331
332 static union bch_extent_entry *extent_entry_prev(struct bkey_ptrs ptrs,
333                                           union bch_extent_entry *entry)
334 {
335         union bch_extent_entry *i = ptrs.start;
336
337         if (i == entry)
338                 return NULL;
339
340         while (extent_entry_next(i) != entry)
341                 i = extent_entry_next(i);
342         return i;
343 }
344
345 union bch_extent_entry *bch2_bkey_drop_ptr(struct bkey_s k,
346                                            struct bch_extent_ptr *ptr)
347 {
348         struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
349         union bch_extent_entry *dst, *src, *prev;
350         bool drop_crc = true;
351
352         EBUG_ON(ptr < &ptrs.start->ptr ||
353                 ptr >= &ptrs.end->ptr);
354         EBUG_ON(ptr->type != 1 << BCH_EXTENT_ENTRY_ptr);
355
356         src = extent_entry_next(to_entry(ptr));
357         if (src != ptrs.end &&
358             !extent_entry_is_crc(src))
359                 drop_crc = false;
360
361         dst = to_entry(ptr);
362         while ((prev = extent_entry_prev(ptrs, dst))) {
363                 if (extent_entry_is_ptr(prev))
364                         break;
365
366                 if (extent_entry_is_crc(prev)) {
367                         if (drop_crc)
368                                 dst = prev;
369                         break;
370                 }
371
372                 dst = prev;
373         }
374
375         memmove_u64s_down(dst, src,
376                           (u64 *) ptrs.end - (u64 *) src);
377         k.k->u64s -= (u64 *) src - (u64 *) dst;
378
379         return dst;
380 }
381
382 static inline bool can_narrow_crc(struct bch_extent_crc_unpacked u,
383                                   struct bch_extent_crc_unpacked n)
384 {
385         return !u.compression_type &&
386                 u.csum_type &&
387                 u.uncompressed_size > u.live_size &&
388                 bch2_csum_type_is_encryption(u.csum_type) ==
389                 bch2_csum_type_is_encryption(n.csum_type);
390 }
391
392 bool bch2_can_narrow_extent_crcs(struct bkey_s_c_extent e,
393                                  struct bch_extent_crc_unpacked n)
394 {
395         struct bch_extent_crc_unpacked crc;
396         const union bch_extent_entry *i;
397
398         if (!n.csum_type)
399                 return false;
400
401         extent_for_each_crc(e, crc, i)
402                 if (can_narrow_crc(crc, n))
403                         return true;
404
405         return false;
406 }
407
408 /*
409  * We're writing another replica for this extent, so while we've got the data in
410  * memory we'll be computing a new checksum for the currently live data.
411  *
412  * If there are other replicas we aren't moving, and they are checksummed but
413  * not compressed, we can modify them to point to only the data that is
414  * currently live (so that readers won't have to bounce) while we've got the
415  * checksum we need:
416  */
417 bool bch2_extent_narrow_crcs(struct bkey_i_extent *e,
418                              struct bch_extent_crc_unpacked n)
419 {
420         struct bch_extent_crc_unpacked u;
421         struct extent_ptr_decoded p;
422         union bch_extent_entry *i;
423         bool ret = false;
424
425         /* Find a checksum entry that covers only live data: */
426         if (!n.csum_type) {
427                 extent_for_each_crc(extent_i_to_s(e), u, i)
428                         if (!u.compression_type &&
429                             u.csum_type &&
430                             u.live_size == u.uncompressed_size) {
431                                 n = u;
432                                 goto found;
433                         }
434                 return false;
435         }
436 found:
437         BUG_ON(n.compression_type);
438         BUG_ON(n.offset);
439         BUG_ON(n.live_size != e->k.size);
440
441 restart_narrow_pointers:
442         extent_for_each_ptr_decode(extent_i_to_s(e), p, i)
443                 if (can_narrow_crc(p.crc, n)) {
444                         bch2_bkey_drop_ptr(extent_i_to_s(e).s, &i->ptr);
445                         p.ptr.offset += p.crc.offset;
446                         p.crc = n;
447                         bch2_extent_ptr_decoded_append(e, &p);
448                         ret = true;
449                         goto restart_narrow_pointers;
450                 }
451
452         return ret;
453 }
454
455 /* returns true if not equal */
456 static inline bool bch2_crc_unpacked_cmp(struct bch_extent_crc_unpacked l,
457                                          struct bch_extent_crc_unpacked r)
458 {
459         return (l.csum_type             != r.csum_type ||
460                 l.compression_type      != r.compression_type ||
461                 l.compressed_size       != r.compressed_size ||
462                 l.uncompressed_size     != r.uncompressed_size ||
463                 l.offset                != r.offset ||
464                 l.live_size             != r.live_size ||
465                 l.nonce                 != r.nonce ||
466                 bch2_crc_cmp(l.csum, r.csum));
467 }
468
469 void bch2_ptr_swab(const struct bkey_format *f, struct bkey_packed *k)
470 {
471         union bch_extent_entry *entry;
472         u64 *d = (u64 *) bkeyp_val(f, k);
473         unsigned i;
474
475         for (i = 0; i < bkeyp_val_u64s(f, k); i++)
476                 d[i] = swab64(d[i]);
477
478         for (entry = (union bch_extent_entry *) d;
479              entry < (union bch_extent_entry *) (d + bkeyp_val_u64s(f, k));
480              entry = extent_entry_next(entry)) {
481                 switch (extent_entry_type(entry)) {
482                 case BCH_EXTENT_ENTRY_ptr:
483                         break;
484                 case BCH_EXTENT_ENTRY_crc32:
485                         entry->crc32.csum = swab32(entry->crc32.csum);
486                         break;
487                 case BCH_EXTENT_ENTRY_crc64:
488                         entry->crc64.csum_hi = swab16(entry->crc64.csum_hi);
489                         entry->crc64.csum_lo = swab64(entry->crc64.csum_lo);
490                         break;
491                 case BCH_EXTENT_ENTRY_crc128:
492                         entry->crc128.csum.hi = (__force __le64)
493                                 swab64((__force u64) entry->crc128.csum.hi);
494                         entry->crc128.csum.lo = (__force __le64)
495                                 swab64((__force u64) entry->crc128.csum.lo);
496                         break;
497                 case BCH_EXTENT_ENTRY_stripe_ptr:
498                         break;
499                 }
500         }
501 }
502
503 static const char *extent_ptr_invalid(const struct bch_fs *c,
504                                       struct bkey_s_c k,
505                                       const struct bch_extent_ptr *ptr,
506                                       unsigned size_ondisk,
507                                       bool metadata)
508 {
509         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
510         const struct bch_extent_ptr *ptr2;
511         struct bch_dev *ca;
512
513         if (ptr->dev >= c->sb.nr_devices ||
514             !c->devs[ptr->dev])
515                 return "pointer to invalid device";
516
517         ca = bch_dev_bkey_exists(c, ptr->dev);
518         if (!ca)
519                 return "pointer to invalid device";
520
521         bkey_for_each_ptr(ptrs, ptr2)
522                 if (ptr != ptr2 && ptr->dev == ptr2->dev)
523                         return "multiple pointers to same device";
524
525         if (ptr->offset + size_ondisk > bucket_to_sector(ca, ca->mi.nbuckets))
526                 return "offset past end of device";
527
528         if (ptr->offset < bucket_to_sector(ca, ca->mi.first_bucket))
529                 return "offset before first bucket";
530
531         if (bucket_remainder(ca, ptr->offset) +
532             size_ondisk > ca->mi.bucket_size)
533                 return "spans multiple buckets";
534
535         return NULL;
536 }
537
538 static void bkey_ptrs_to_text(struct printbuf *out, struct bch_fs *c,
539                               struct bkey_s_c k)
540 {
541         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
542         const union bch_extent_entry *entry;
543         struct bch_extent_crc_unpacked crc;
544         const struct bch_extent_ptr *ptr;
545         const struct bch_extent_stripe_ptr *ec;
546         struct bch_dev *ca;
547         bool first = true;
548
549         bkey_extent_entry_for_each(ptrs, entry) {
550                 if (!first)
551                         pr_buf(out, " ");
552
553                 switch (__extent_entry_type(entry)) {
554                 case BCH_EXTENT_ENTRY_ptr:
555                         ptr = entry_to_ptr(entry);
556                         ca = ptr->dev < c->sb.nr_devices && c->devs[ptr->dev]
557                                 ? bch_dev_bkey_exists(c, ptr->dev)
558                                 : NULL;
559
560                         pr_buf(out, "ptr: %u:%llu gen %u%s%s", ptr->dev,
561                                (u64) ptr->offset, ptr->gen,
562                                ptr->cached ? " cached" : "",
563                                ca && ptr_stale(ca, ptr)
564                                ? " stale" : "");
565                         break;
566                 case BCH_EXTENT_ENTRY_crc32:
567                 case BCH_EXTENT_ENTRY_crc64:
568                 case BCH_EXTENT_ENTRY_crc128:
569                         crc = bch2_extent_crc_unpack(k.k, entry_to_crc(entry));
570
571                         pr_buf(out, "crc: c_size %u size %u offset %u nonce %u csum %u compress %u",
572                                crc.compressed_size,
573                                crc.uncompressed_size,
574                                crc.offset, crc.nonce,
575                                crc.csum_type,
576                                crc.compression_type);
577                         break;
578                 case BCH_EXTENT_ENTRY_stripe_ptr:
579                         ec = &entry->stripe_ptr;
580
581                         pr_buf(out, "ec: idx %llu block %u",
582                                (u64) ec->idx, ec->block);
583                         break;
584                 default:
585                         pr_buf(out, "(invalid extent entry %.16llx)", *((u64 *) entry));
586                         return;
587                 }
588
589                 first = false;
590         }
591 }
592
593 /* Btree ptrs */
594
595 const char *bch2_btree_ptr_invalid(const struct bch_fs *c, struct bkey_s_c k)
596 {
597         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
598         const union bch_extent_entry *entry;
599         const struct bch_extent_ptr *ptr;
600         const char *reason;
601
602         if (bkey_val_u64s(k.k) > BKEY_BTREE_PTR_VAL_U64s_MAX)
603                 return "value too big";
604
605         bkey_extent_entry_for_each(ptrs, entry) {
606                 if (__extent_entry_type(entry) >= BCH_EXTENT_ENTRY_MAX)
607                         return "invalid extent entry type";
608
609                 if (!extent_entry_is_ptr(entry))
610                         return "has non ptr field";
611         }
612
613         bkey_for_each_ptr(ptrs, ptr) {
614                 reason = extent_ptr_invalid(c, k, ptr,
615                                             c->opts.btree_node_size,
616                                             true);
617                 if (reason)
618                         return reason;
619         }
620
621         return NULL;
622 }
623
624 void bch2_btree_ptr_debugcheck(struct bch_fs *c, struct btree *b,
625                                struct bkey_s_c k)
626 {
627         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
628         const struct bch_extent_ptr *ptr;
629         unsigned seq;
630         const char *err;
631         char buf[160];
632         struct bucket_mark mark;
633         struct bch_dev *ca;
634         unsigned replicas = 0;
635         bool bad;
636
637         bkey_for_each_ptr(ptrs, ptr) {
638                 ca = bch_dev_bkey_exists(c, ptr->dev);
639                 replicas++;
640
641                 if (!test_bit(BCH_FS_ALLOC_READ_DONE, &c->flags))
642                         continue;
643
644                 err = "stale";
645                 if (ptr_stale(ca, ptr))
646                         goto err;
647
648                 do {
649                         seq = read_seqcount_begin(&c->gc_pos_lock);
650                         mark = ptr_bucket_mark(ca, ptr);
651
652                         bad = gc_pos_cmp(c->gc_pos, gc_pos_btree_node(b)) > 0 &&
653                                 (mark.data_type != BCH_DATA_BTREE ||
654                                  mark.dirty_sectors < c->opts.btree_node_size);
655                 } while (read_seqcount_retry(&c->gc_pos_lock, seq));
656
657                 err = "inconsistent";
658                 if (bad)
659                         goto err;
660         }
661
662         if (!test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) &&
663             !bch2_bkey_replicas_marked(c, k, false)) {
664                 bch2_bkey_val_to_text(&PBUF(buf), c, k);
665                 bch2_fs_bug(c,
666                         "btree key bad (replicas not marked in superblock):\n%s",
667                         buf);
668                 return;
669         }
670
671         return;
672 err:
673         bch2_bkey_val_to_text(&PBUF(buf), c, k);
674         bch2_fs_bug(c, "%s btree pointer %s: bucket %zi gen %i mark %08x",
675                     err, buf, PTR_BUCKET_NR(ca, ptr),
676                     mark.gen, (unsigned) mark.v.counter);
677 }
678
679 void bch2_btree_ptr_to_text(struct printbuf *out, struct bch_fs *c,
680                             struct bkey_s_c k)
681 {
682         const char *invalid;
683
684         bkey_ptrs_to_text(out, c, k);
685
686         invalid = bch2_btree_ptr_invalid(c, k);
687         if (invalid)
688                 pr_buf(out, " invalid: %s", invalid);
689 }
690
691 /* Extents */
692
693 bool __bch2_cut_front(struct bpos where, struct bkey_s k)
694 {
695         u64 len = 0;
696
697         if (bkey_cmp(where, bkey_start_pos(k.k)) <= 0)
698                 return false;
699
700         EBUG_ON(bkey_cmp(where, k.k->p) > 0);
701
702         len = k.k->p.offset - where.offset;
703
704         BUG_ON(len > k.k->size);
705
706         /*
707          * Don't readjust offset if the key size is now 0, because that could
708          * cause offset to point to the next bucket:
709          */
710         if (!len)
711                 k.k->type = KEY_TYPE_deleted;
712         else if (bkey_extent_is_data(k.k)) {
713                 struct bkey_s_extent e = bkey_s_to_extent(k);
714                 union bch_extent_entry *entry;
715                 bool seen_crc = false;
716
717                 extent_for_each_entry(e, entry) {
718                         switch (extent_entry_type(entry)) {
719                         case BCH_EXTENT_ENTRY_ptr:
720                                 if (!seen_crc)
721                                         entry->ptr.offset += e.k->size - len;
722                                 break;
723                         case BCH_EXTENT_ENTRY_crc32:
724                                 entry->crc32.offset += e.k->size - len;
725                                 break;
726                         case BCH_EXTENT_ENTRY_crc64:
727                                 entry->crc64.offset += e.k->size - len;
728                                 break;
729                         case BCH_EXTENT_ENTRY_crc128:
730                                 entry->crc128.offset += e.k->size - len;
731                                 break;
732                         case BCH_EXTENT_ENTRY_stripe_ptr:
733                                 break;
734                         }
735
736                         if (extent_entry_is_crc(entry))
737                                 seen_crc = true;
738                 }
739         }
740
741         k.k->size = len;
742
743         return true;
744 }
745
746 bool bch2_cut_back(struct bpos where, struct bkey *k)
747 {
748         u64 len = 0;
749
750         if (bkey_cmp(where, k->p) >= 0)
751                 return false;
752
753         EBUG_ON(bkey_cmp(where, bkey_start_pos(k)) < 0);
754
755         len = where.offset - bkey_start_offset(k);
756
757         BUG_ON(len > k->size);
758
759         k->p = where;
760         k->size = len;
761
762         if (!len)
763                 k->type = KEY_TYPE_deleted;
764
765         return true;
766 }
767
768 /**
769  * bch_key_resize - adjust size of @k
770  *
771  * bkey_start_offset(k) will be preserved, modifies where the extent ends
772  */
773 void bch2_key_resize(struct bkey *k,
774                     unsigned new_size)
775 {
776         k->p.offset -= k->size;
777         k->p.offset += new_size;
778         k->size = new_size;
779 }
780
781 static bool extent_i_save(struct btree *b, struct bkey_packed *dst,
782                           struct bkey_i *src)
783 {
784         struct bkey_format *f = &b->format;
785         struct bkey_i *dst_unpacked;
786         struct bkey_packed tmp;
787
788         if ((dst_unpacked = packed_to_bkey(dst)))
789                 dst_unpacked->k = src->k;
790         else if (bch2_bkey_pack_key(&tmp, &src->k, f))
791                 memcpy_u64s(dst, &tmp, f->key_u64s);
792         else
793                 return false;
794
795         memcpy_u64s(bkeyp_val(f, dst), &src->v, bkey_val_u64s(&src->k));
796         return true;
797 }
798
799 struct extent_insert_state {
800         struct btree_insert             *trans;
801         struct btree_insert_entry       *insert;
802         struct bpos                     committed;
803
804         /* for deleting: */
805         struct bkey_i                   whiteout;
806         bool                            update_journal;
807         bool                            update_btree;
808         bool                            deleting;
809 };
810
811 static bool bch2_extent_merge_inline(struct bch_fs *,
812                                      struct btree_iter *,
813                                      struct bkey_packed *,
814                                      struct bkey_packed *,
815                                      bool);
816
817 static void verify_extent_nonoverlapping(struct btree *b,
818                                          struct btree_node_iter *_iter,
819                                          struct bkey_i *insert)
820 {
821 #ifdef CONFIG_BCACHEFS_DEBUG
822         struct btree_node_iter iter;
823         struct bkey_packed *k;
824         struct bkey uk;
825
826         iter = *_iter;
827         k = bch2_btree_node_iter_prev_filter(&iter, b, KEY_TYPE_discard);
828         BUG_ON(k &&
829                (uk = bkey_unpack_key(b, k),
830                 bkey_cmp(uk.p, bkey_start_pos(&insert->k)) > 0));
831
832         iter = *_iter;
833         k = bch2_btree_node_iter_peek_filter(&iter, b, KEY_TYPE_discard);
834 #if 0
835         BUG_ON(k &&
836                (uk = bkey_unpack_key(b, k),
837                 bkey_cmp(insert->k.p, bkey_start_pos(&uk))) > 0);
838 #else
839         if (k &&
840             (uk = bkey_unpack_key(b, k),
841              bkey_cmp(insert->k.p, bkey_start_pos(&uk))) > 0) {
842                 char buf1[100];
843                 char buf2[100];
844
845                 bch2_bkey_to_text(&PBUF(buf1), &insert->k);
846                 bch2_bkey_to_text(&PBUF(buf2), &uk);
847
848                 bch2_dump_btree_node(b);
849                 panic("insert > next :\n"
850                       "insert %s\n"
851                       "next   %s\n",
852                       buf1, buf2);
853         }
854 #endif
855
856 #endif
857 }
858
859 static void verify_modified_extent(struct btree_iter *iter,
860                                    struct bkey_packed *k)
861 {
862         bch2_btree_iter_verify(iter, iter->l[0].b);
863         bch2_verify_insert_pos(iter->l[0].b, k, k, k->u64s);
864 }
865
866 static void extent_bset_insert(struct bch_fs *c, struct btree_iter *iter,
867                                struct bkey_i *insert)
868 {
869         struct btree_iter_level *l = &iter->l[0];
870         struct btree_node_iter node_iter;
871         struct bkey_packed *k;
872
873         BUG_ON(insert->k.u64s > bch_btree_keys_u64s_remaining(c, l->b));
874
875         EBUG_ON(bkey_deleted(&insert->k) || !insert->k.size);
876         verify_extent_nonoverlapping(l->b, &l->iter, insert);
877
878         node_iter = l->iter;
879         k = bch2_btree_node_iter_prev_filter(&node_iter, l->b, KEY_TYPE_discard);
880         if (k && !bkey_written(l->b, k) &&
881             bch2_extent_merge_inline(c, iter, k, bkey_to_packed(insert), true))
882                 return;
883
884         node_iter = l->iter;
885         k = bch2_btree_node_iter_peek_filter(&node_iter, l->b, KEY_TYPE_discard);
886         if (k && !bkey_written(l->b, k) &&
887             bch2_extent_merge_inline(c, iter, bkey_to_packed(insert), k, false))
888                 return;
889
890         k = bch2_btree_node_iter_bset_pos(&l->iter, l->b, bset_tree_last(l->b));
891
892         bch2_bset_insert(l->b, &l->iter, k, insert, 0);
893         bch2_btree_node_iter_fix(iter, l->b, &l->iter, k, 0, k->u64s);
894         bch2_btree_iter_verify(iter, l->b);
895 }
896
897 static void extent_insert_committed(struct extent_insert_state *s)
898 {
899         struct bch_fs *c = s->trans->c;
900         struct btree_iter *iter = s->insert->iter;
901         struct bkey_i *insert = s->insert->k;
902         BKEY_PADDED(k) split;
903
904         EBUG_ON(bkey_cmp(insert->k.p, s->committed) < 0);
905         EBUG_ON(bkey_cmp(s->committed, bkey_start_pos(&insert->k)) < 0);
906
907         bkey_copy(&split.k, insert);
908         if (s->deleting)
909                 split.k.k.type = KEY_TYPE_discard;
910
911         bch2_cut_back(s->committed, &split.k.k);
912
913         if (!bkey_cmp(s->committed, iter->pos))
914                 return;
915
916         bch2_btree_iter_set_pos_same_leaf(iter, s->committed);
917
918         if (s->update_btree) {
919                 if (debug_check_bkeys(c))
920                         bch2_bkey_debugcheck(c, iter->l[0].b,
921                                              bkey_i_to_s_c(&split.k));
922
923                 EBUG_ON(bkey_deleted(&split.k.k) || !split.k.k.size);
924
925                 extent_bset_insert(c, iter, &split.k);
926         }
927
928         if (s->update_journal) {
929                 bkey_copy(&split.k, !s->deleting ? insert : &s->whiteout);
930                 if (s->deleting)
931                         split.k.k.type = KEY_TYPE_discard;
932
933                 bch2_cut_back(s->committed, &split.k.k);
934
935                 EBUG_ON(bkey_deleted(&split.k.k) || !split.k.k.size);
936
937                 bch2_btree_journal_key(s->trans, iter, &split.k);
938         }
939
940         bch2_cut_front(s->committed, insert);
941
942         insert->k.needs_whiteout        = false;
943 }
944
945 void bch2_extent_trim_atomic(struct bkey_i *k, struct btree_iter *iter)
946 {
947         struct btree *b = iter->l[0].b;
948
949         BUG_ON(iter->uptodate > BTREE_ITER_NEED_PEEK);
950
951         bch2_cut_back(b->key.k.p, &k->k);
952
953         BUG_ON(bkey_cmp(bkey_start_pos(&k->k), b->data->min_key) < 0);
954 }
955
956 enum btree_insert_ret
957 bch2_extent_can_insert(struct btree_insert *trans,
958                        struct btree_insert_entry *insert,
959                        unsigned *u64s)
960 {
961         struct btree_iter_level *l = &insert->iter->l[0];
962         struct btree_node_iter node_iter = l->iter;
963         enum bch_extent_overlap overlap;
964         struct bkey_packed *_k;
965         struct bkey unpacked;
966         struct bkey_s_c k;
967         int sectors;
968
969         BUG_ON(trans->flags & BTREE_INSERT_ATOMIC &&
970                !bch2_extent_is_atomic(&insert->k->k, insert->iter));
971
972         /*
973          * We avoid creating whiteouts whenever possible when deleting, but
974          * those optimizations mean we may potentially insert two whiteouts
975          * instead of one (when we overlap with the front of one extent and the
976          * back of another):
977          */
978         if (bkey_whiteout(&insert->k->k))
979                 *u64s += BKEY_U64s;
980
981         _k = bch2_btree_node_iter_peek_filter(&node_iter, l->b,
982                                               KEY_TYPE_discard);
983         if (!_k)
984                 return BTREE_INSERT_OK;
985
986         k = bkey_disassemble(l->b, _k, &unpacked);
987
988         overlap = bch2_extent_overlap(&insert->k->k, k.k);
989
990         /* account for having to split existing extent: */
991         if (overlap == BCH_EXTENT_OVERLAP_MIDDLE)
992                 *u64s += _k->u64s;
993
994         if (overlap == BCH_EXTENT_OVERLAP_MIDDLE &&
995             (sectors = bch2_extent_is_compressed(k))) {
996                 int flags = BCH_DISK_RESERVATION_BTREE_LOCKS_HELD;
997
998                 if (trans->flags & BTREE_INSERT_NOFAIL)
999                         flags |= BCH_DISK_RESERVATION_NOFAIL;
1000
1001                 switch (bch2_disk_reservation_add(trans->c,
1002                                 trans->disk_res,
1003                                 sectors, flags)) {
1004                 case 0:
1005                         break;
1006                 case -ENOSPC:
1007                         return BTREE_INSERT_ENOSPC;
1008                 case -EINTR:
1009                         return BTREE_INSERT_NEED_GC_LOCK;
1010                 default:
1011                         BUG();
1012                 }
1013         }
1014
1015         return BTREE_INSERT_OK;
1016 }
1017
1018 static void
1019 extent_squash(struct extent_insert_state *s, struct bkey_i *insert,
1020               struct bkey_packed *_k, struct bkey_s k,
1021               enum bch_extent_overlap overlap)
1022 {
1023         struct bch_fs *c = s->trans->c;
1024         struct btree_iter *iter = s->insert->iter;
1025         struct btree_iter_level *l = &iter->l[0];
1026
1027         switch (overlap) {
1028         case BCH_EXTENT_OVERLAP_FRONT:
1029                 /* insert overlaps with start of k: */
1030                 __bch2_cut_front(insert->k.p, k);
1031                 BUG_ON(bkey_deleted(k.k));
1032                 extent_save(l->b, _k, k.k);
1033                 verify_modified_extent(iter, _k);
1034                 break;
1035
1036         case BCH_EXTENT_OVERLAP_BACK:
1037                 /* insert overlaps with end of k: */
1038                 bch2_cut_back(bkey_start_pos(&insert->k), k.k);
1039                 BUG_ON(bkey_deleted(k.k));
1040                 extent_save(l->b, _k, k.k);
1041
1042                 /*
1043                  * As the auxiliary tree is indexed by the end of the
1044                  * key and we've just changed the end, update the
1045                  * auxiliary tree.
1046                  */
1047                 bch2_bset_fix_invalidated_key(l->b, _k);
1048                 bch2_btree_node_iter_fix(iter, l->b, &l->iter,
1049                                          _k, _k->u64s, _k->u64s);
1050                 verify_modified_extent(iter, _k);
1051                 break;
1052
1053         case BCH_EXTENT_OVERLAP_ALL: {
1054                 /* The insert key completely covers k, invalidate k */
1055                 if (!bkey_whiteout(k.k))
1056                         btree_account_key_drop(l->b, _k);
1057
1058                 k.k->size = 0;
1059                 k.k->type = KEY_TYPE_deleted;
1060
1061                 if (_k >= btree_bset_last(l->b)->start) {
1062                         unsigned u64s = _k->u64s;
1063
1064                         bch2_bset_delete(l->b, _k, _k->u64s);
1065                         bch2_btree_node_iter_fix(iter, l->b, &l->iter,
1066                                                  _k, u64s, 0);
1067                         bch2_btree_iter_verify(iter, l->b);
1068                 } else {
1069                         extent_save(l->b, _k, k.k);
1070                         bch2_btree_node_iter_fix(iter, l->b, &l->iter,
1071                                                  _k, _k->u64s, _k->u64s);
1072                         verify_modified_extent(iter, _k);
1073                 }
1074
1075                 break;
1076         }
1077         case BCH_EXTENT_OVERLAP_MIDDLE: {
1078                 BKEY_PADDED(k) split;
1079                 /*
1080                  * The insert key falls 'in the middle' of k
1081                  * The insert key splits k in 3:
1082                  * - start only in k, preserve
1083                  * - middle common section, invalidate in k
1084                  * - end only in k, preserve
1085                  *
1086                  * We update the old key to preserve the start,
1087                  * insert will be the new common section,
1088                  * we manually insert the end that we are preserving.
1089                  *
1090                  * modify k _before_ doing the insert (which will move
1091                  * what k points to)
1092                  */
1093                 bkey_reassemble(&split.k, k.s_c);
1094                 split.k.k.needs_whiteout |= bkey_written(l->b, _k);
1095
1096                 bch2_cut_back(bkey_start_pos(&insert->k), &split.k.k);
1097                 BUG_ON(bkey_deleted(&split.k.k));
1098
1099                 __bch2_cut_front(insert->k.p, k);
1100                 BUG_ON(bkey_deleted(k.k));
1101                 extent_save(l->b, _k, k.k);
1102                 verify_modified_extent(iter, _k);
1103
1104                 extent_bset_insert(c, iter, &split.k);
1105                 break;
1106         }
1107         }
1108 }
1109
1110 static void __bch2_insert_fixup_extent(struct extent_insert_state *s)
1111 {
1112         struct btree_iter *iter = s->insert->iter;
1113         struct btree_iter_level *l = &iter->l[0];
1114         struct bkey_packed *_k;
1115         struct bkey unpacked;
1116         struct bkey_i *insert = s->insert->k;
1117
1118         while (bkey_cmp(s->committed, insert->k.p) < 0 &&
1119                (_k = bch2_btree_node_iter_peek_filter(&l->iter, l->b,
1120                                                       KEY_TYPE_discard))) {
1121                 struct bkey_s k = __bkey_disassemble(l->b, _k, &unpacked);
1122                 enum bch_extent_overlap overlap = bch2_extent_overlap(&insert->k, k.k);
1123
1124                 EBUG_ON(bkey_cmp(iter->pos, k.k->p) >= 0);
1125
1126                 if (bkey_cmp(bkey_start_pos(k.k), insert->k.p) >= 0)
1127                         break;
1128
1129                 s->committed = bpos_min(s->insert->k->k.p, k.k->p);
1130
1131                 if (!bkey_whiteout(k.k))
1132                         s->update_journal = true;
1133
1134                 if (!s->update_journal) {
1135                         bch2_cut_front(s->committed, insert);
1136                         bch2_cut_front(s->committed, &s->whiteout);
1137                         bch2_btree_iter_set_pos_same_leaf(iter, s->committed);
1138                         goto next;
1139                 }
1140
1141                 /*
1142                  * When deleting, if possible just do it by switching the type
1143                  * of the key we're deleting, instead of creating and inserting
1144                  * a new whiteout:
1145                  */
1146                 if (s->deleting &&
1147                     !s->update_btree &&
1148                     !bkey_cmp(insert->k.p, k.k->p) &&
1149                     !bkey_cmp(bkey_start_pos(&insert->k), bkey_start_pos(k.k))) {
1150                         if (!bkey_whiteout(k.k)) {
1151                                 btree_account_key_drop(l->b, _k);
1152                                 _k->type = KEY_TYPE_discard;
1153                                 reserve_whiteout(l->b, _k);
1154                         }
1155                         break;
1156                 }
1157
1158                 if (k.k->needs_whiteout || bkey_written(l->b, _k)) {
1159                         insert->k.needs_whiteout = true;
1160                         s->update_btree = true;
1161                 }
1162
1163                 if (s->update_btree &&
1164                     overlap == BCH_EXTENT_OVERLAP_ALL &&
1165                     bkey_whiteout(k.k) &&
1166                     k.k->needs_whiteout) {
1167                         unreserve_whiteout(l->b, _k);
1168                         _k->needs_whiteout = false;
1169                 }
1170
1171                 extent_squash(s, insert, _k, k, overlap);
1172
1173                 if (!s->update_btree)
1174                         bch2_cut_front(s->committed, insert);
1175 next:
1176                 if (overlap == BCH_EXTENT_OVERLAP_FRONT ||
1177                     overlap == BCH_EXTENT_OVERLAP_MIDDLE)
1178                         break;
1179         }
1180
1181         if (bkey_cmp(s->committed, insert->k.p) < 0)
1182                 s->committed = bpos_min(s->insert->k->k.p, l->b->key.k.p);
1183
1184         /*
1185          * may have skipped past some deleted extents greater than the insert
1186          * key, before we got to a non deleted extent and knew we could bail out
1187          * rewind the iterator a bit if necessary:
1188          */
1189         {
1190                 struct btree_node_iter node_iter = l->iter;
1191
1192                 while ((_k = bch2_btree_node_iter_prev_all(&node_iter, l->b)) &&
1193                        bkey_cmp_left_packed(l->b, _k, &s->committed) > 0)
1194                         l->iter = node_iter;
1195         }
1196 }
1197
1198 /**
1199  * bch_extent_insert_fixup - insert a new extent and deal with overlaps
1200  *
1201  * this may result in not actually doing the insert, or inserting some subset
1202  * of the insert key. For cmpxchg operations this is where that logic lives.
1203  *
1204  * All subsets of @insert that need to be inserted are inserted using
1205  * bch2_btree_insert_and_journal(). If @b or @res fills up, this function
1206  * returns false, setting @iter->pos for the prefix of @insert that actually got
1207  * inserted.
1208  *
1209  * BSET INVARIANTS: this function is responsible for maintaining all the
1210  * invariants for bsets of extents in memory. things get really hairy with 0
1211  * size extents
1212  *
1213  * within one bset:
1214  *
1215  * bkey_start_pos(bkey_next(k)) >= k
1216  * or bkey_start_offset(bkey_next(k)) >= k->offset
1217  *
1218  * i.e. strict ordering, no overlapping extents.
1219  *
1220  * multiple bsets (i.e. full btree node):
1221  *
1222  * âˆ€ k, j
1223  *   k.size != 0 âˆ§ j.size != 0 â†’
1224  *     Â¬ (k > bkey_start_pos(j) âˆ§ k < j)
1225  *
1226  * i.e. no two overlapping keys _of nonzero size_
1227  *
1228  * We can't realistically maintain this invariant for zero size keys because of
1229  * the key merging done in bch2_btree_insert_key() - for two mergeable keys k, j
1230  * there may be another 0 size key between them in another bset, and it will
1231  * thus overlap with the merged key.
1232  *
1233  * In addition, the end of iter->pos indicates how much has been processed.
1234  * If the end of iter->pos is not the same as the end of insert, then
1235  * key insertion needs to continue/be retried.
1236  */
1237 enum btree_insert_ret
1238 bch2_insert_fixup_extent(struct btree_insert *trans,
1239                          struct btree_insert_entry *insert)
1240 {
1241         struct btree_iter *iter = insert->iter;
1242         struct btree *b         = iter->l[0].b;
1243         struct extent_insert_state s = {
1244                 .trans          = trans,
1245                 .insert         = insert,
1246                 .committed      = iter->pos,
1247
1248                 .whiteout       = *insert->k,
1249                 .update_journal = !bkey_whiteout(&insert->k->k),
1250                 .update_btree   = !bkey_whiteout(&insert->k->k),
1251                 .deleting       = bkey_whiteout(&insert->k->k),
1252         };
1253
1254         EBUG_ON(iter->level);
1255         EBUG_ON(!insert->k->k.size);
1256
1257         /*
1258          * As we process overlapping extents, we advance @iter->pos both to
1259          * signal to our caller (btree_insert_key()) how much of @insert->k has
1260          * been inserted, and also to keep @iter->pos consistent with
1261          * @insert->k and the node iterator that we're advancing:
1262          */
1263         EBUG_ON(bkey_cmp(iter->pos, bkey_start_pos(&insert->k->k)));
1264
1265         __bch2_insert_fixup_extent(&s);
1266
1267         extent_insert_committed(&s);
1268
1269         EBUG_ON(bkey_cmp(iter->pos, bkey_start_pos(&insert->k->k)));
1270         EBUG_ON(bkey_cmp(iter->pos, s.committed));
1271
1272         if (insert->k->k.size) {
1273                 /* got to the end of this leaf node */
1274                 BUG_ON(bkey_cmp(iter->pos, b->key.k.p));
1275                 return BTREE_INSERT_NEED_TRAVERSE;
1276         }
1277
1278         return BTREE_INSERT_OK;
1279 }
1280
1281 const char *bch2_extent_invalid(const struct bch_fs *c, struct bkey_s_c k)
1282 {
1283         struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
1284         const union bch_extent_entry *entry;
1285         struct bch_extent_crc_unpacked crc;
1286         const struct bch_extent_ptr *ptr;
1287         unsigned size_ondisk = e.k->size;
1288         const char *reason;
1289         unsigned nonce = UINT_MAX;
1290
1291         if (bkey_val_u64s(e.k) > BKEY_EXTENT_VAL_U64s_MAX)
1292                 return "value too big";
1293
1294         extent_for_each_entry(e, entry) {
1295                 if (__extent_entry_type(entry) >= BCH_EXTENT_ENTRY_MAX)
1296                         return "invalid extent entry type";
1297
1298                 switch (extent_entry_type(entry)) {
1299                 case BCH_EXTENT_ENTRY_ptr:
1300                         ptr = entry_to_ptr(entry);
1301
1302                         reason = extent_ptr_invalid(c, e.s_c, &entry->ptr,
1303                                                     size_ondisk, false);
1304                         if (reason)
1305                                 return reason;
1306                         break;
1307                 case BCH_EXTENT_ENTRY_crc32:
1308                 case BCH_EXTENT_ENTRY_crc64:
1309                 case BCH_EXTENT_ENTRY_crc128:
1310                         crc = bch2_extent_crc_unpack(e.k, entry_to_crc(entry));
1311
1312                         if (crc.offset + e.k->size >
1313                             crc.uncompressed_size)
1314                                 return "checksum offset + key size > uncompressed size";
1315
1316                         size_ondisk = crc.compressed_size;
1317
1318                         if (!bch2_checksum_type_valid(c, crc.csum_type))
1319                                 return "invalid checksum type";
1320
1321                         if (crc.compression_type >= BCH_COMPRESSION_NR)
1322                                 return "invalid compression type";
1323
1324                         if (bch2_csum_type_is_encryption(crc.csum_type)) {
1325                                 if (nonce == UINT_MAX)
1326                                         nonce = crc.offset + crc.nonce;
1327                                 else if (nonce != crc.offset + crc.nonce)
1328                                         return "incorrect nonce";
1329                         }
1330                         break;
1331                 case BCH_EXTENT_ENTRY_stripe_ptr:
1332                         break;
1333                 }
1334         }
1335
1336         return NULL;
1337 }
1338
1339 void bch2_extent_debugcheck(struct bch_fs *c, struct btree *b,
1340                             struct bkey_s_c k)
1341 {
1342         struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
1343         const struct bch_extent_ptr *ptr;
1344         struct bch_dev *ca;
1345         struct bucket_mark mark;
1346         unsigned seq, stale;
1347         char buf[160];
1348         bool bad;
1349         unsigned replicas = 0;
1350
1351         /*
1352          * XXX: we should be doing most/all of these checks at startup time,
1353          * where we check bch2_bkey_invalid() in btree_node_read_done()
1354          *
1355          * But note that we can't check for stale pointers or incorrect gc marks
1356          * until after journal replay is done (it might be an extent that's
1357          * going to get overwritten during replay)
1358          */
1359
1360         extent_for_each_ptr(e, ptr) {
1361                 ca = bch_dev_bkey_exists(c, ptr->dev);
1362                 replicas++;
1363
1364                 /*
1365                  * If journal replay hasn't finished, we might be seeing keys
1366                  * that will be overwritten by the time journal replay is done:
1367                  */
1368                 if (!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags))
1369                         continue;
1370
1371                 stale = 0;
1372
1373                 do {
1374                         seq = read_seqcount_begin(&c->gc_pos_lock);
1375                         mark = ptr_bucket_mark(ca, ptr);
1376
1377                         /* between mark and bucket gen */
1378                         smp_rmb();
1379
1380                         stale = ptr_stale(ca, ptr);
1381
1382                         bch2_fs_bug_on(stale && !ptr->cached, c,
1383                                          "stale dirty pointer");
1384
1385                         bch2_fs_bug_on(stale > 96, c,
1386                                          "key too stale: %i",
1387                                          stale);
1388
1389                         if (stale)
1390                                 break;
1391
1392                         bad = gc_pos_cmp(c->gc_pos, gc_pos_btree_node(b)) > 0 &&
1393                                 (mark.data_type != BCH_DATA_USER ||
1394                                  !(ptr->cached
1395                                    ? mark.cached_sectors
1396                                    : mark.dirty_sectors));
1397                 } while (read_seqcount_retry(&c->gc_pos_lock, seq));
1398
1399                 if (bad)
1400                         goto bad_ptr;
1401         }
1402
1403         if (replicas > BCH_REPLICAS_MAX) {
1404                 bch2_bkey_val_to_text(&PBUF(buf), c, e.s_c);
1405                 bch2_fs_bug(c,
1406                         "extent key bad (too many replicas: %u): %s",
1407                         replicas, buf);
1408                 return;
1409         }
1410
1411         if (!test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) &&
1412             !bch2_bkey_replicas_marked(c, e.s_c, false)) {
1413                 bch2_bkey_val_to_text(&PBUF(buf), c, e.s_c);
1414                 bch2_fs_bug(c,
1415                         "extent key bad (replicas not marked in superblock):\n%s",
1416                         buf);
1417                 return;
1418         }
1419
1420         return;
1421
1422 bad_ptr:
1423         bch2_bkey_val_to_text(&PBUF(buf), c, e.s_c);
1424         bch2_fs_bug(c, "extent pointer bad gc mark: %s:\nbucket %zu "
1425                    "gen %i type %u", buf,
1426                    PTR_BUCKET_NR(ca, ptr), mark.gen, mark.data_type);
1427 }
1428
1429 void bch2_extent_to_text(struct printbuf *out, struct bch_fs *c,
1430                          struct bkey_s_c k)
1431 {
1432         const char *invalid;
1433
1434         bkey_ptrs_to_text(out, c, k);
1435
1436         invalid = bch2_extent_invalid(c, k);
1437         if (invalid)
1438                 pr_buf(out, " invalid: %s", invalid);
1439 }
1440
1441 static void bch2_extent_crc_init(union bch_extent_crc *crc,
1442                                  struct bch_extent_crc_unpacked new)
1443 {
1444 #define common_fields(_crc)                                             \
1445                 .csum_type              = _crc.csum_type,               \
1446                 .compression_type       = _crc.compression_type,        \
1447                 ._compressed_size       = _crc.compressed_size - 1,     \
1448                 ._uncompressed_size     = _crc.uncompressed_size - 1,   \
1449                 .offset                 = _crc.offset
1450
1451         if (bch_crc_bytes[new.csum_type]        <= 4 &&
1452             new.uncompressed_size               <= CRC32_SIZE_MAX &&
1453             new.nonce                           <= CRC32_NONCE_MAX) {
1454                 crc->crc32 = (struct bch_extent_crc32) {
1455                         .type = 1 << BCH_EXTENT_ENTRY_crc32,
1456                         common_fields(new),
1457                         .csum                   = *((__le32 *) &new.csum.lo),
1458                 };
1459                 return;
1460         }
1461
1462         if (bch_crc_bytes[new.csum_type]        <= 10 &&
1463             new.uncompressed_size               <= CRC64_SIZE_MAX &&
1464             new.nonce                           <= CRC64_NONCE_MAX) {
1465                 crc->crc64 = (struct bch_extent_crc64) {
1466                         .type = 1 << BCH_EXTENT_ENTRY_crc64,
1467                         common_fields(new),
1468                         .nonce                  = new.nonce,
1469                         .csum_lo                = new.csum.lo,
1470                         .csum_hi                = *((__le16 *) &new.csum.hi),
1471                 };
1472                 return;
1473         }
1474
1475         if (bch_crc_bytes[new.csum_type]        <= 16 &&
1476             new.uncompressed_size               <= CRC128_SIZE_MAX &&
1477             new.nonce                           <= CRC128_NONCE_MAX) {
1478                 crc->crc128 = (struct bch_extent_crc128) {
1479                         .type = 1 << BCH_EXTENT_ENTRY_crc128,
1480                         common_fields(new),
1481                         .nonce                  = new.nonce,
1482                         .csum                   = new.csum,
1483                 };
1484                 return;
1485         }
1486 #undef common_fields
1487         BUG();
1488 }
1489
1490 void bch2_extent_crc_append(struct bkey_i_extent *e,
1491                             struct bch_extent_crc_unpacked new)
1492 {
1493         bch2_extent_crc_init((void *) extent_entry_last(extent_i_to_s(e)), new);
1494         __extent_entry_push(e);
1495 }
1496
1497 static inline void __extent_entry_insert(struct bkey_i_extent *e,
1498                                          union bch_extent_entry *dst,
1499                                          union bch_extent_entry *new)
1500 {
1501         union bch_extent_entry *end = extent_entry_last(extent_i_to_s(e));
1502
1503         memmove_u64s_up((u64 *) dst + extent_entry_u64s(new),
1504                         dst, (u64 *) end - (u64 *) dst);
1505         e->k.u64s += extent_entry_u64s(new);
1506         memcpy_u64s_small(dst, new, extent_entry_u64s(new));
1507 }
1508
1509 void bch2_extent_ptr_decoded_append(struct bkey_i_extent *e,
1510                                     struct extent_ptr_decoded *p)
1511 {
1512         struct bch_extent_crc_unpacked crc = bch2_extent_crc_unpack(&e->k, NULL);
1513         union bch_extent_entry *pos;
1514         unsigned i;
1515
1516         if (!bch2_crc_unpacked_cmp(crc, p->crc)) {
1517                 pos = e->v.start;
1518                 goto found;
1519         }
1520
1521         extent_for_each_crc(extent_i_to_s(e), crc, pos)
1522                 if (!bch2_crc_unpacked_cmp(crc, p->crc)) {
1523                         pos = extent_entry_next(pos);
1524                         goto found;
1525                 }
1526
1527         bch2_extent_crc_append(e, p->crc);
1528         pos = extent_entry_last(extent_i_to_s(e));
1529 found:
1530         p->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
1531         __extent_entry_insert(e, pos, to_entry(&p->ptr));
1532
1533         for (i = 0; i < p->ec_nr; i++) {
1534                 p->ec[i].type = 1 << BCH_EXTENT_ENTRY_stripe_ptr;
1535                 __extent_entry_insert(e, pos, to_entry(&p->ec[i]));
1536         }
1537 }
1538
1539 /*
1540  * bch_extent_normalize - clean up an extent, dropping stale pointers etc.
1541  *
1542  * Returns true if @k should be dropped entirely
1543  *
1544  * For existing keys, only called when btree nodes are being rewritten, not when
1545  * they're merely being compacted/resorted in memory.
1546  */
1547 bool bch2_extent_normalize(struct bch_fs *c, struct bkey_s k)
1548 {
1549         struct bch_extent_ptr *ptr;
1550
1551         bch2_bkey_drop_ptrs(k, ptr,
1552                 ptr->cached &&
1553                 ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr));
1554
1555         /* will only happen if all pointers were cached: */
1556         if (!bkey_val_u64s(k.k))
1557                 k.k->type = KEY_TYPE_deleted;
1558
1559         return false;
1560 }
1561
1562 void bch2_extent_mark_replicas_cached(struct bch_fs *c,
1563                                       struct bkey_s_extent e,
1564                                       unsigned target,
1565                                       unsigned nr_desired_replicas)
1566 {
1567         union bch_extent_entry *entry;
1568         struct extent_ptr_decoded p;
1569         int extra = bch2_bkey_durability(c, e.s_c) - nr_desired_replicas;
1570
1571         if (target && extra > 0)
1572                 extent_for_each_ptr_decode(e, p, entry) {
1573                         int n = bch2_extent_ptr_durability(c, p);
1574
1575                         if (n && n <= extra &&
1576                             !bch2_dev_in_target(c, p.ptr.dev, target)) {
1577                                 entry->ptr.cached = true;
1578                                 extra -= n;
1579                         }
1580                 }
1581
1582         if (extra > 0)
1583                 extent_for_each_ptr_decode(e, p, entry) {
1584                         int n = bch2_extent_ptr_durability(c, p);
1585
1586                         if (n && n <= extra) {
1587                                 entry->ptr.cached = true;
1588                                 extra -= n;
1589                         }
1590                 }
1591 }
1592
1593 enum merge_result bch2_extent_merge(struct bch_fs *c,
1594                                     struct bkey_i *l, struct bkey_i *r)
1595 {
1596         struct bkey_s_extent el = bkey_i_to_s_extent(l);
1597         struct bkey_s_extent er = bkey_i_to_s_extent(r);
1598         union bch_extent_entry *en_l, *en_r;
1599
1600         if (bkey_val_u64s(&l->k) != bkey_val_u64s(&r->k))
1601                 return BCH_MERGE_NOMERGE;
1602
1603         extent_for_each_entry(el, en_l) {
1604                 struct bch_extent_ptr *lp, *rp;
1605                 struct bch_dev *ca;
1606
1607                 en_r = vstruct_idx(er.v, (u64 *) en_l - el.v->_data);
1608
1609                 if ((extent_entry_type(en_l) !=
1610                      extent_entry_type(en_r)) ||
1611                     !extent_entry_is_ptr(en_l))
1612                         return BCH_MERGE_NOMERGE;
1613
1614                 lp = &en_l->ptr;
1615                 rp = &en_r->ptr;
1616
1617                 if (lp->offset + el.k->size     != rp->offset ||
1618                     lp->dev                     != rp->dev ||
1619                     lp->gen                     != rp->gen)
1620                         return BCH_MERGE_NOMERGE;
1621
1622                 /* We don't allow extents to straddle buckets: */
1623                 ca = bch_dev_bkey_exists(c, lp->dev);
1624
1625                 if (PTR_BUCKET_NR(ca, lp) != PTR_BUCKET_NR(ca, rp))
1626                         return BCH_MERGE_NOMERGE;
1627         }
1628
1629         l->k.needs_whiteout |= r->k.needs_whiteout;
1630
1631         /* Keys with no pointers aren't restricted to one bucket and could
1632          * overflow KEY_SIZE
1633          */
1634         if ((u64) l->k.size + r->k.size > KEY_SIZE_MAX) {
1635                 bch2_key_resize(&l->k, KEY_SIZE_MAX);
1636                 bch2_cut_front(l->k.p, r);
1637                 return BCH_MERGE_PARTIAL;
1638         }
1639
1640         bch2_key_resize(&l->k, l->k.size + r->k.size);
1641
1642         return BCH_MERGE_MERGE;
1643 }
1644
1645 /*
1646  * When merging an extent that we're inserting into a btree node, the new merged
1647  * extent could overlap with an existing 0 size extent - if we don't fix that,
1648  * it'll break the btree node iterator so this code finds those 0 size extents
1649  * and shifts them out of the way.
1650  *
1651  * Also unpacks and repacks.
1652  */
1653 static bool bch2_extent_merge_inline(struct bch_fs *c,
1654                                      struct btree_iter *iter,
1655                                      struct bkey_packed *l,
1656                                      struct bkey_packed *r,
1657                                      bool back_merge)
1658 {
1659         struct btree *b = iter->l[0].b;
1660         struct btree_node_iter *node_iter = &iter->l[0].iter;
1661         BKEY_PADDED(k) li, ri;
1662         struct bkey_packed *m   = back_merge ? l : r;
1663         struct bkey_i *mi       = back_merge ? &li.k : &ri.k;
1664         struct bset_tree *t     = bch2_bkey_to_bset(b, m);
1665         enum merge_result ret;
1666
1667         EBUG_ON(bkey_written(b, m));
1668
1669         /*
1670          * We need to save copies of both l and r, because we might get a
1671          * partial merge (which modifies both) and then fails to repack
1672          */
1673         bch2_bkey_unpack(b, &li.k, l);
1674         bch2_bkey_unpack(b, &ri.k, r);
1675
1676         ret = bch2_bkey_merge(c, &li.k, &ri.k);
1677         if (ret == BCH_MERGE_NOMERGE)
1678                 return false;
1679
1680         /*
1681          * check if we overlap with deleted extents - would break the sort
1682          * order:
1683          */
1684         if (back_merge) {
1685                 struct bkey_packed *n = bkey_next(m);
1686
1687                 if (n != btree_bkey_last(b, t) &&
1688                     bkey_cmp_left_packed(b, n, &li.k.k.p) <= 0 &&
1689                     bkey_deleted(n))
1690                         return false;
1691         } else if (ret == BCH_MERGE_MERGE) {
1692                 struct bkey_packed *prev = bch2_bkey_prev_all(b, t, m);
1693
1694                 if (prev &&
1695                     bkey_cmp_left_packed_byval(b, prev,
1696                                 bkey_start_pos(&li.k.k)) > 0)
1697                         return false;
1698         }
1699
1700         if (ret == BCH_MERGE_PARTIAL) {
1701                 if (!extent_i_save(b, m, mi))
1702                         return false;
1703
1704                 if (!back_merge)
1705                         bkey_copy(packed_to_bkey(l), &li.k);
1706                 else
1707                         bkey_copy(packed_to_bkey(r), &ri.k);
1708         } else {
1709                 if (!extent_i_save(b, m, &li.k))
1710                         return false;
1711         }
1712
1713         bch2_bset_fix_invalidated_key(b, m);
1714         bch2_btree_node_iter_fix(iter, b, node_iter,
1715                                  m, m->u64s, m->u64s);
1716         verify_modified_extent(iter, m);
1717
1718         return ret == BCH_MERGE_MERGE;
1719 }
1720
1721 int bch2_check_range_allocated(struct bch_fs *c, struct bpos pos, u64 size)
1722 {
1723         struct btree_iter iter;
1724         struct bpos end = pos;
1725         struct bkey_s_c k;
1726         int ret = 0;
1727
1728         end.offset += size;
1729
1730         for_each_btree_key(&iter, c, BTREE_ID_EXTENTS, pos,
1731                              BTREE_ITER_SLOTS, k) {
1732                 if (bkey_cmp(bkey_start_pos(k.k), end) >= 0)
1733                         break;
1734
1735                 if (!bch2_extent_is_fully_allocated(k)) {
1736                         ret = -ENOSPC;
1737                         break;
1738                 }
1739         }
1740         bch2_btree_iter_unlock(&iter);
1741
1742         return ret;
1743 }
1744
1745 /* KEY_TYPE_reservation: */
1746
1747 const char *bch2_reservation_invalid(const struct bch_fs *c, struct bkey_s_c k)
1748 {
1749         struct bkey_s_c_reservation r = bkey_s_c_to_reservation(k);
1750
1751         if (bkey_val_bytes(k.k) != sizeof(struct bch_reservation))
1752                 return "incorrect value size";
1753
1754         if (!r.v->nr_replicas || r.v->nr_replicas > BCH_REPLICAS_MAX)
1755                 return "invalid nr_replicas";
1756
1757         return NULL;
1758 }
1759
1760 void bch2_reservation_to_text(struct printbuf *out, struct bch_fs *c,
1761                               struct bkey_s_c k)
1762 {
1763         struct bkey_s_c_reservation r = bkey_s_c_to_reservation(k);
1764
1765         pr_buf(out, "generation %u replicas %u",
1766                le32_to_cpu(r.v->generation),
1767                r.v->nr_replicas);
1768 }
1769
1770 enum merge_result bch2_reservation_merge(struct bch_fs *c,
1771                                          struct bkey_i *l, struct bkey_i *r)
1772 {
1773         struct bkey_i_reservation *li = bkey_i_to_reservation(l);
1774         struct bkey_i_reservation *ri = bkey_i_to_reservation(r);
1775
1776         if (li->v.generation != ri->v.generation ||
1777             li->v.nr_replicas != ri->v.nr_replicas)
1778                 return BCH_MERGE_NOMERGE;
1779
1780         l->k.needs_whiteout |= r->k.needs_whiteout;
1781
1782         /* Keys with no pointers aren't restricted to one bucket and could
1783          * overflow KEY_SIZE
1784          */
1785         if ((u64) l->k.size + r->k.size > KEY_SIZE_MAX) {
1786                 bch2_key_resize(&l->k, KEY_SIZE_MAX);
1787                 bch2_cut_front(l->k.p, r);
1788                 return BCH_MERGE_PARTIAL;
1789         }
1790
1791         bch2_key_resize(&l->k, l->k.size + r->k.size);
1792
1793         return BCH_MERGE_MERGE;
1794 }