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