bcachefs: extent_ptr_decoded
[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 static void sort_key_next(struct btree_node_iter_large *iter,
31                           struct btree *b,
32                           struct btree_node_iter_set *i)
33 {
34         i->k += __btree_node_offset_to_key(b, i->k)->u64s;
35
36         if (i->k == i->end)
37                 *i = iter->data[--iter->used];
38 }
39
40 /*
41  * Returns true if l > r - unless l == r, in which case returns true if l is
42  * older than r.
43  *
44  * Necessary for btree_sort_fixup() - if there are multiple keys that compare
45  * equal in different sets, we have to process them newest to oldest.
46  */
47 #define key_sort_cmp(h, l, r)                                           \
48 ({                                                                      \
49         bkey_cmp_packed(b,                                              \
50                         __btree_node_offset_to_key(b, (l).k),           \
51                         __btree_node_offset_to_key(b, (r).k))           \
52                                                                         \
53         ?: (l).k - (r).k;                                               \
54 })
55
56 static inline bool should_drop_next_key(struct btree_node_iter_large *iter,
57                                         struct btree *b)
58 {
59         struct btree_node_iter_set *l = iter->data, *r = iter->data + 1;
60         struct bkey_packed *k = __btree_node_offset_to_key(b, l->k);
61
62         if (bkey_whiteout(k))
63                 return true;
64
65         if (iter->used < 2)
66                 return false;
67
68         if (iter->used > 2 &&
69             key_sort_cmp(iter, r[0], r[1]) >= 0)
70                 r++;
71
72         /*
73          * key_sort_cmp() ensures that when keys compare equal the older key
74          * comes first; so if l->k compares equal to r->k then l->k is older and
75          * should be dropped.
76          */
77         return !bkey_cmp_packed(b,
78                                 __btree_node_offset_to_key(b, l->k),
79                                 __btree_node_offset_to_key(b, r->k));
80 }
81
82 struct btree_nr_keys bch2_key_sort_fix_overlapping(struct bset *dst,
83                                         struct btree *b,
84                                         struct btree_node_iter_large *iter)
85 {
86         struct bkey_packed *out = dst->start;
87         struct btree_nr_keys nr;
88
89         memset(&nr, 0, sizeof(nr));
90
91         heap_resort(iter, key_sort_cmp);
92
93         while (!bch2_btree_node_iter_large_end(iter)) {
94                 if (!should_drop_next_key(iter, b)) {
95                         struct bkey_packed *k =
96                                 __btree_node_offset_to_key(b, iter->data->k);
97
98                         bkey_copy(out, k);
99                         btree_keys_account_key_add(&nr, 0, out);
100                         out = bkey_next(out);
101                 }
102
103                 sort_key_next(iter, b, iter->data);
104                 heap_sift_down(iter, 0, key_sort_cmp);
105         }
106
107         dst->u64s = cpu_to_le16((u64 *) out - dst->_data);
108         return nr;
109 }
110
111 /* Common among btree and extent ptrs */
112
113 const struct bch_extent_ptr *
114 bch2_extent_has_device(struct bkey_s_c_extent e, unsigned dev)
115 {
116         const struct bch_extent_ptr *ptr;
117
118         extent_for_each_ptr(e, ptr)
119                 if (ptr->dev == dev)
120                         return ptr;
121
122         return NULL;
123 }
124
125 bool bch2_extent_drop_device(struct bkey_s_extent e, unsigned dev)
126 {
127         struct bch_extent_ptr *ptr;
128         bool dropped = false;
129
130         extent_for_each_ptr_backwards(e, ptr)
131                 if (ptr->dev == dev) {
132                         __bch2_extent_drop_ptr(e, ptr);
133                         dropped = true;
134                 }
135
136         if (dropped)
137                 bch2_extent_drop_redundant_crcs(e);
138         return dropped;
139 }
140
141 const struct bch_extent_ptr *
142 bch2_extent_has_group(struct bch_fs *c, struct bkey_s_c_extent e, unsigned group)
143 {
144         const struct bch_extent_ptr *ptr;
145
146         extent_for_each_ptr(e, ptr) {
147                 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
148
149                 if (ca->mi.group &&
150                     ca->mi.group - 1 == group)
151                         return ptr;
152         }
153
154         return NULL;
155 }
156
157 const struct bch_extent_ptr *
158 bch2_extent_has_target(struct bch_fs *c, struct bkey_s_c_extent e, unsigned target)
159 {
160         const struct bch_extent_ptr *ptr;
161
162         extent_for_each_ptr(e, ptr)
163                 if (bch2_dev_in_target(c, ptr->dev, target) &&
164                     (!ptr->cached ||
165                      !ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr)))
166                         return ptr;
167
168         return NULL;
169 }
170
171 unsigned bch2_extent_nr_ptrs(struct bkey_s_c_extent e)
172 {
173         const struct bch_extent_ptr *ptr;
174         unsigned nr_ptrs = 0;
175
176         extent_for_each_ptr(e, ptr)
177                 nr_ptrs++;
178
179         return nr_ptrs;
180 }
181
182 unsigned bch2_extent_nr_dirty_ptrs(struct bkey_s_c k)
183 {
184         struct bkey_s_c_extent e;
185         const struct bch_extent_ptr *ptr;
186         unsigned nr_ptrs = 0;
187
188         switch (k.k->type) {
189         case BCH_EXTENT:
190         case BCH_EXTENT_CACHED:
191                 e = bkey_s_c_to_extent(k);
192
193                 extent_for_each_ptr(e, ptr)
194                         nr_ptrs += !ptr->cached;
195                 break;
196
197         case BCH_RESERVATION:
198                 nr_ptrs = bkey_s_c_to_reservation(k).v->nr_replicas;
199                 break;
200         }
201
202         return nr_ptrs;
203 }
204
205 unsigned bch2_extent_ptr_durability(struct bch_fs *c,
206                                     const struct bch_extent_ptr *ptr)
207 {
208         struct bch_dev *ca;
209
210         if (ptr->cached)
211                 return 0;
212
213         ca = bch_dev_bkey_exists(c, ptr->dev);
214
215         if (ca->mi.state == BCH_MEMBER_STATE_FAILED)
216                 return 0;
217
218         return ca->mi.durability;
219 }
220
221 unsigned bch2_extent_durability(struct bch_fs *c, struct bkey_s_c_extent e)
222 {
223         const struct bch_extent_ptr *ptr;
224         unsigned durability = 0;
225
226         extent_for_each_ptr(e, ptr)
227                 durability += bch2_extent_ptr_durability(c, ptr);
228
229         return durability;
230 }
231
232 unsigned bch2_extent_is_compressed(struct bkey_s_c k)
233 {
234         struct bkey_s_c_extent e;
235         const struct bch_extent_ptr *ptr;
236         struct bch_extent_crc_unpacked crc;
237         unsigned ret = 0;
238
239         switch (k.k->type) {
240         case BCH_EXTENT:
241         case BCH_EXTENT_CACHED:
242                 e = bkey_s_c_to_extent(k);
243
244                 extent_for_each_ptr_crc(e, ptr, crc)
245                         if (!ptr->cached &&
246                             crc.compression_type != BCH_COMPRESSION_NONE &&
247                             crc.compressed_size < crc.live_size)
248                                 ret = max_t(unsigned, ret, crc.compressed_size);
249         }
250
251         return ret;
252 }
253
254 bool bch2_extent_matches_ptr(struct bch_fs *c, struct bkey_s_c_extent e,
255                              struct bch_extent_ptr m, u64 offset)
256 {
257         const struct bch_extent_ptr *ptr;
258         struct bch_extent_crc_unpacked crc;
259
260         extent_for_each_ptr_crc(e, ptr, crc)
261                 if (ptr->dev    == m.dev &&
262                     ptr->gen    == m.gen &&
263                     (s64) ptr->offset + crc.offset - bkey_start_offset(e.k) ==
264                     (s64) m.offset  - offset)
265                         return ptr;
266
267         return NULL;
268 }
269
270 /* Doesn't cleanup redundant crcs */
271 void __bch2_extent_drop_ptr(struct bkey_s_extent e, struct bch_extent_ptr *ptr)
272 {
273         EBUG_ON(ptr < &e.v->start->ptr ||
274                 ptr >= &extent_entry_last(e)->ptr);
275         EBUG_ON(ptr->type != 1 << BCH_EXTENT_ENTRY_ptr);
276         memmove_u64s_down(ptr, ptr + 1,
277                           (u64 *) extent_entry_last(e) - (u64 *) (ptr + 1));
278         e.k->u64s -= sizeof(*ptr) / sizeof(u64);
279 }
280
281 void bch2_extent_drop_ptr(struct bkey_s_extent e, struct bch_extent_ptr *ptr)
282 {
283         __bch2_extent_drop_ptr(e, ptr);
284         bch2_extent_drop_redundant_crcs(e);
285 }
286
287 static inline bool can_narrow_crc(struct bch_extent_crc_unpacked u,
288                                   struct bch_extent_crc_unpacked n)
289 {
290         return !u.compression_type &&
291                 u.csum_type &&
292                 u.uncompressed_size > u.live_size &&
293                 bch2_csum_type_is_encryption(u.csum_type) ==
294                 bch2_csum_type_is_encryption(n.csum_type);
295 }
296
297 bool bch2_can_narrow_extent_crcs(struct bkey_s_c_extent e,
298                                  struct bch_extent_crc_unpacked n)
299 {
300         struct bch_extent_crc_unpacked crc;
301         const union bch_extent_entry *i;
302
303         if (!n.csum_type)
304                 return false;
305
306         extent_for_each_crc(e, crc, i)
307                 if (can_narrow_crc(crc, n))
308                         return true;
309
310         return false;
311 }
312
313 /*
314  * We're writing another replica for this extent, so while we've got the data in
315  * memory we'll be computing a new checksum for the currently live data.
316  *
317  * If there are other replicas we aren't moving, and they are checksummed but
318  * not compressed, we can modify them to point to only the data that is
319  * currently live (so that readers won't have to bounce) while we've got the
320  * checksum we need:
321  */
322 bool bch2_extent_narrow_crcs(struct bkey_i_extent *e,
323                              struct bch_extent_crc_unpacked n)
324 {
325         struct bch_extent_crc_unpacked u;
326         struct bch_extent_ptr *ptr;
327         union bch_extent_entry *i;
328
329         /* Find a checksum entry that covers only live data: */
330         if (!n.csum_type)
331                 extent_for_each_crc(extent_i_to_s(e), u, i)
332                         if (!u.compression_type &&
333                             u.csum_type &&
334                             u.live_size == u.uncompressed_size) {
335                                 n = u;
336                                 break;
337                         }
338
339         if (!bch2_can_narrow_extent_crcs(extent_i_to_s_c(e), n))
340                 return false;
341
342         BUG_ON(n.compression_type);
343         BUG_ON(n.offset);
344         BUG_ON(n.live_size != e->k.size);
345
346         bch2_extent_crc_append(e, n);
347 restart_narrow_pointers:
348         extent_for_each_ptr_crc(extent_i_to_s(e), ptr, u)
349                 if (can_narrow_crc(u, n)) {
350                         ptr->offset += u.offset;
351                         extent_ptr_append(e, *ptr);
352                         __bch2_extent_drop_ptr(extent_i_to_s(e), ptr);
353                         goto restart_narrow_pointers;
354                 }
355
356         bch2_extent_drop_redundant_crcs(extent_i_to_s(e));
357         return true;
358 }
359
360 /* returns true if not equal */
361 static inline bool bch2_crc_unpacked_cmp(struct bch_extent_crc_unpacked l,
362                                          struct bch_extent_crc_unpacked r)
363 {
364         return (l.csum_type             != r.csum_type ||
365                 l.compression_type      != r.compression_type ||
366                 l.compressed_size       != r.compressed_size ||
367                 l.uncompressed_size     != r.uncompressed_size ||
368                 l.offset                != r.offset ||
369                 l.live_size             != r.live_size ||
370                 l.nonce                 != r.nonce ||
371                 bch2_crc_cmp(l.csum, r.csum));
372 }
373
374 void bch2_extent_drop_redundant_crcs(struct bkey_s_extent e)
375 {
376         union bch_extent_entry *entry = e.v->start;
377         union bch_extent_crc *crc, *prev = NULL;
378         struct bch_extent_crc_unpacked u, prev_u = { 0 };
379
380         while (entry != extent_entry_last(e)) {
381                 union bch_extent_entry *next = extent_entry_next(entry);
382                 size_t crc_u64s = extent_entry_u64s(entry);
383
384                 if (!extent_entry_is_crc(entry))
385                         goto next;
386
387                 crc = entry_to_crc(entry);
388                 u = bch2_extent_crc_unpack(e.k, crc);
389
390                 if (next == extent_entry_last(e)) {
391                         /* crc entry with no pointers after it: */
392                         goto drop;
393                 }
394
395                 if (extent_entry_is_crc(next)) {
396                         /* no pointers before next crc entry: */
397                         goto drop;
398                 }
399
400                 if (prev && !bch2_crc_unpacked_cmp(u, prev_u)) {
401                         /* identical to previous crc entry: */
402                         goto drop;
403                 }
404
405                 if (!prev &&
406                     !u.csum_type &&
407                     !u.compression_type) {
408                         /* null crc entry: */
409                         union bch_extent_entry *e2;
410
411                         extent_for_each_entry_from(e, e2, extent_entry_next(entry)) {
412                                 if (!extent_entry_is_ptr(e2))
413                                         break;
414
415                                 e2->ptr.offset += u.offset;
416                         }
417                         goto drop;
418                 }
419
420                 prev = crc;
421                 prev_u = u;
422 next:
423                 entry = next;
424                 continue;
425 drop:
426                 memmove_u64s_down(crc, next,
427                                   (u64 *) extent_entry_last(e) - (u64 *) next);
428                 e.k->u64s -= crc_u64s;
429         }
430
431         EBUG_ON(bkey_val_u64s(e.k) && !bch2_extent_nr_ptrs(e.c));
432 }
433
434 static bool should_drop_ptr(const struct bch_fs *c,
435                             struct bkey_s_c_extent e,
436                             const struct bch_extent_ptr *ptr)
437 {
438         return ptr->cached && ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr);
439 }
440
441 static void bch2_extent_drop_stale(struct bch_fs *c, struct bkey_s_extent e)
442 {
443         struct bch_extent_ptr *ptr = &e.v->start->ptr;
444         bool dropped = false;
445
446         while ((ptr = extent_ptr_next(e, ptr)))
447                 if (should_drop_ptr(c, e.c, ptr)) {
448                         __bch2_extent_drop_ptr(e, ptr);
449                         dropped = true;
450                 } else
451                         ptr++;
452
453         if (dropped)
454                 bch2_extent_drop_redundant_crcs(e);
455 }
456
457 bool bch2_ptr_normalize(struct bch_fs *c, struct btree *b, struct bkey_s k)
458 {
459         return bch2_extent_normalize(c, k);
460 }
461
462 void bch2_ptr_swab(const struct bkey_format *f, struct bkey_packed *k)
463 {
464         switch (k->type) {
465         case BCH_EXTENT:
466         case BCH_EXTENT_CACHED: {
467                 union bch_extent_entry *entry;
468                 u64 *d = (u64 *) bkeyp_val(f, k);
469                 unsigned i;
470
471                 for (i = 0; i < bkeyp_val_u64s(f, k); i++)
472                         d[i] = swab64(d[i]);
473
474                 for (entry = (union bch_extent_entry *) d;
475                      entry < (union bch_extent_entry *) (d + bkeyp_val_u64s(f, k));
476                      entry = extent_entry_next(entry)) {
477                         switch (extent_entry_type(entry)) {
478                         case BCH_EXTENT_ENTRY_crc32:
479                                 entry->crc32.csum = swab32(entry->crc32.csum);
480                                 break;
481                         case BCH_EXTENT_ENTRY_crc64:
482                                 entry->crc64.csum_hi = swab16(entry->crc64.csum_hi);
483                                 entry->crc64.csum_lo = swab64(entry->crc64.csum_lo);
484                                 break;
485                         case BCH_EXTENT_ENTRY_crc128:
486                                 entry->crc128.csum.hi = (__force __le64)
487                                         swab64((__force u64) entry->crc128.csum.hi);
488                                 entry->crc128.csum.lo = (__force __le64)
489                                         swab64((__force u64) entry->crc128.csum.lo);
490                                 break;
491                         case BCH_EXTENT_ENTRY_ptr:
492                                 break;
493                         }
494                 }
495                 break;
496         }
497         }
498 }
499
500 static const char *extent_ptr_invalid(const struct bch_fs *c,
501                                       struct bkey_s_c_extent e,
502                                       const struct bch_extent_ptr *ptr,
503                                       unsigned size_ondisk,
504                                       bool metadata)
505 {
506         const struct bch_extent_ptr *ptr2;
507         struct bch_dev *ca;
508
509         if (ptr->dev >= c->sb.nr_devices ||
510             !c->devs[ptr->dev])
511                 return "pointer to invalid device";
512
513         ca = bch_dev_bkey_exists(c, ptr->dev);
514         if (!ca)
515                 return "pointer to invalid device";
516
517         extent_for_each_ptr(e, ptr2)
518                 if (ptr != ptr2 && ptr->dev == ptr2->dev)
519                         return "multiple pointers to same device";
520
521         if (ptr->offset + size_ondisk > bucket_to_sector(ca, ca->mi.nbuckets))
522                 return "offset past end of device";
523
524         if (ptr->offset < bucket_to_sector(ca, ca->mi.first_bucket))
525                 return "offset before first bucket";
526
527         if (bucket_remainder(ca, ptr->offset) +
528             size_ondisk > ca->mi.bucket_size)
529                 return "spans multiple buckets";
530
531         return NULL;
532 }
533
534 static size_t extent_print_ptrs(struct bch_fs *c, char *buf,
535                                 size_t size, struct bkey_s_c_extent e)
536 {
537         char *out = buf, *end = buf + size;
538         const union bch_extent_entry *entry;
539         struct bch_extent_crc_unpacked crc;
540         const struct bch_extent_ptr *ptr;
541         struct bch_dev *ca;
542         bool first = true;
543
544 #define p(...)  (out += scnprintf(out, end - out, __VA_ARGS__))
545
546         extent_for_each_entry(e, entry) {
547                 if (!first)
548                         p(" ");
549
550                 switch (__extent_entry_type(entry)) {
551                 case BCH_EXTENT_ENTRY_crc32:
552                 case BCH_EXTENT_ENTRY_crc64:
553                 case BCH_EXTENT_ENTRY_crc128:
554                         crc = bch2_extent_crc_unpack(e.k, entry_to_crc(entry));
555
556                         p("crc: c_size %u size %u offset %u nonce %u csum %u compress %u",
557                           crc.compressed_size,
558                           crc.uncompressed_size,
559                           crc.offset, crc.nonce,
560                           crc.csum_type,
561                           crc.compression_type);
562                         break;
563                 case BCH_EXTENT_ENTRY_ptr:
564                         ptr = entry_to_ptr(entry);
565                         ca = ptr->dev < c->sb.nr_devices && c->devs[ptr->dev]
566                                 ? bch_dev_bkey_exists(c, ptr->dev)
567                                 : NULL;
568
569                         p("ptr: %u:%llu gen %u%s%s", ptr->dev,
570                           (u64) ptr->offset, ptr->gen,
571                           ptr->cached ? " cached" : "",
572                           ca && ptr_stale(ca, ptr)
573                           ? " stale" : "");
574                         break;
575                 default:
576                         p("(invalid extent entry %.16llx)", *((u64 *) entry));
577                         goto out;
578                 }
579
580                 first = false;
581         }
582 out:
583         if (bkey_extent_is_cached(e.k))
584                 p(" cached");
585 #undef p
586         return out - buf;
587 }
588
589 static inline bool dev_latency_better(struct bch_fs *c,
590                               const struct bch_extent_ptr *ptr1,
591                               const struct bch_extent_ptr *ptr2)
592 {
593         struct bch_dev *dev1 = bch_dev_bkey_exists(c, ptr1->dev);
594         struct bch_dev *dev2 = bch_dev_bkey_exists(c, ptr2->dev);
595         u64 l1 = atomic64_read(&dev1->cur_latency[READ]);
596         u64 l2 = atomic64_read(&dev2->cur_latency[READ]);
597
598         /* Pick at random, biased in favor of the faster device: */
599
600         return bch2_rand_range(l1 + l2) > l1;
601 }
602
603 static int extent_pick_read_device(struct bch_fs *c,
604                                    struct bkey_s_c_extent e,
605                                    struct bch_devs_mask *avoid,
606                                    struct extent_ptr_decoded *pick)
607 {
608         const struct bch_extent_ptr *ptr;
609         struct bch_extent_crc_unpacked crc;
610         struct bch_dev *ca;
611         int ret = 0;
612
613         extent_for_each_ptr_crc(e, ptr, crc) {
614                 ca = bch_dev_bkey_exists(c, ptr->dev);
615
616                 if (ptr->cached && ptr_stale(ca, ptr))
617                         continue;
618
619                 if (avoid && test_bit(ptr->dev, avoid->d))
620                         continue;
621
622                 if (ret && !dev_latency_better(c, ptr, &pick->ptr))
623                         continue;
624
625                 *pick = (struct extent_ptr_decoded) {
626                         .ptr    = *ptr,
627                         .crc    = crc,
628                 };
629
630                 ret = 1;
631         }
632
633         return ret;
634 }
635
636 /* Btree ptrs */
637
638 const char *bch2_btree_ptr_invalid(const struct bch_fs *c, struct bkey_s_c k)
639 {
640         if (bkey_extent_is_cached(k.k))
641                 return "cached";
642
643         if (k.k->size)
644                 return "nonzero key size";
645
646         if (bkey_val_u64s(k.k) > BKEY_BTREE_PTR_VAL_U64s_MAX)
647                 return "value too big";
648
649         switch (k.k->type) {
650         case BCH_EXTENT: {
651                 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
652                 const union bch_extent_entry *entry;
653                 const struct bch_extent_ptr *ptr;
654                 const char *reason;
655
656                 extent_for_each_entry(e, entry) {
657                         if (__extent_entry_type(entry) >= BCH_EXTENT_ENTRY_MAX)
658                                 return "invalid extent entry type";
659
660                         if (extent_entry_is_crc(entry))
661                                 return "has crc field";
662                 }
663
664                 extent_for_each_ptr(e, ptr) {
665                         reason = extent_ptr_invalid(c, e, ptr,
666                                                     c->opts.btree_node_size,
667                                                     true);
668                         if (reason)
669                                 return reason;
670                 }
671
672                 return NULL;
673         }
674
675         default:
676                 return "invalid value type";
677         }
678 }
679
680 void bch2_btree_ptr_debugcheck(struct bch_fs *c, struct btree *b,
681                                struct bkey_s_c k)
682 {
683         struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
684         const struct bch_extent_ptr *ptr;
685         unsigned seq;
686         const char *err;
687         char buf[160];
688         struct bucket_mark mark;
689         struct bch_dev *ca;
690         unsigned replicas = 0;
691         bool bad;
692
693         extent_for_each_ptr(e, ptr) {
694                 ca = bch_dev_bkey_exists(c, ptr->dev);
695                 replicas++;
696
697                 if (!test_bit(BCH_FS_ALLOC_READ_DONE, &c->flags))
698                         continue;
699
700                 err = "stale";
701                 if (ptr_stale(ca, ptr))
702                         goto err;
703
704                 do {
705                         seq = read_seqcount_begin(&c->gc_pos_lock);
706                         mark = ptr_bucket_mark(ca, ptr);
707
708                         bad = gc_pos_cmp(c->gc_pos, gc_pos_btree_node(b)) > 0 &&
709                                 (mark.data_type != BCH_DATA_BTREE ||
710                                  mark.dirty_sectors < c->opts.btree_node_size);
711                 } while (read_seqcount_retry(&c->gc_pos_lock, seq));
712
713                 err = "inconsistent";
714                 if (bad)
715                         goto err;
716         }
717
718         if (!bch2_bkey_replicas_marked(c, BCH_DATA_BTREE, e.s_c)) {
719                 bch2_bkey_val_to_text(c, btree_node_type(b),
720                                      buf, sizeof(buf), k);
721                 bch2_fs_bug(c,
722                         "btree key bad (replicas not marked in superblock):\n%s",
723                         buf);
724                 return;
725         }
726
727         return;
728 err:
729         bch2_bkey_val_to_text(c, btree_node_type(b), buf, sizeof(buf), k);
730         bch2_fs_bug(c, "%s btree pointer %s: bucket %zi "
731                       "gen %i mark %08x",
732                       err, buf, PTR_BUCKET_NR(ca, ptr),
733                       mark.gen, (unsigned) mark.v.counter);
734 }
735
736 int bch2_btree_ptr_to_text(struct bch_fs *c, char *buf,
737                            size_t size, struct bkey_s_c k)
738 {
739         char *out = buf, *end = buf + size;
740         const char *invalid;
741
742 #define p(...)  (out += scnprintf(out, end - out, __VA_ARGS__))
743
744         if (bkey_extent_is_data(k.k))
745                 out += extent_print_ptrs(c, buf, size, bkey_s_c_to_extent(k));
746
747         invalid = bch2_btree_ptr_invalid(c, k);
748         if (invalid)
749                 p(" invalid: %s", invalid);
750 #undef p
751         return out - buf;
752 }
753
754 int bch2_btree_pick_ptr(struct bch_fs *c, const struct btree *b,
755                         struct bch_devs_mask *avoid,
756                         struct extent_ptr_decoded *pick)
757 {
758         return extent_pick_read_device(c, bkey_i_to_s_c_extent(&b->key),
759                                        avoid, pick);
760 }
761
762 /* Extents */
763
764 static bool __bch2_cut_front(struct bpos where, struct bkey_s k)
765 {
766         u64 len = 0;
767
768         if (bkey_cmp(where, bkey_start_pos(k.k)) <= 0)
769                 return false;
770
771         EBUG_ON(bkey_cmp(where, k.k->p) > 0);
772
773         len = k.k->p.offset - where.offset;
774
775         BUG_ON(len > k.k->size);
776
777         /*
778          * Don't readjust offset if the key size is now 0, because that could
779          * cause offset to point to the next bucket:
780          */
781         if (!len)
782                 k.k->type = KEY_TYPE_DELETED;
783         else if (bkey_extent_is_data(k.k)) {
784                 struct bkey_s_extent e = bkey_s_to_extent(k);
785                 union bch_extent_entry *entry;
786                 bool seen_crc = false;
787
788                 extent_for_each_entry(e, entry) {
789                         switch (extent_entry_type(entry)) {
790                         case BCH_EXTENT_ENTRY_ptr:
791                                 if (!seen_crc)
792                                         entry->ptr.offset += e.k->size - len;
793                                 break;
794                         case BCH_EXTENT_ENTRY_crc32:
795                                 entry->crc32.offset += e.k->size - len;
796                                 break;
797                         case BCH_EXTENT_ENTRY_crc64:
798                                 entry->crc64.offset += e.k->size - len;
799                                 break;
800                         case BCH_EXTENT_ENTRY_crc128:
801                                 entry->crc128.offset += e.k->size - len;
802                                 break;
803                         }
804
805                         if (extent_entry_is_crc(entry))
806                                 seen_crc = true;
807                 }
808         }
809
810         k.k->size = len;
811
812         return true;
813 }
814
815 bool bch2_cut_front(struct bpos where, struct bkey_i *k)
816 {
817         return __bch2_cut_front(where, bkey_i_to_s(k));
818 }
819
820 bool bch2_cut_back(struct bpos where, struct bkey *k)
821 {
822         u64 len = 0;
823
824         if (bkey_cmp(where, k->p) >= 0)
825                 return false;
826
827         EBUG_ON(bkey_cmp(where, bkey_start_pos(k)) < 0);
828
829         len = where.offset - bkey_start_offset(k);
830
831         BUG_ON(len > k->size);
832
833         k->p = where;
834         k->size = len;
835
836         if (!len)
837                 k->type = KEY_TYPE_DELETED;
838
839         return true;
840 }
841
842 /**
843  * bch_key_resize - adjust size of @k
844  *
845  * bkey_start_offset(k) will be preserved, modifies where the extent ends
846  */
847 void bch2_key_resize(struct bkey *k,
848                     unsigned new_size)
849 {
850         k->p.offset -= k->size;
851         k->p.offset += new_size;
852         k->size = new_size;
853 }
854
855 /*
856  * In extent_sort_fix_overlapping(), insert_fixup_extent(),
857  * extent_merge_inline() - we're modifying keys in place that are packed. To do
858  * that we have to unpack the key, modify the unpacked key - then this
859  * copies/repacks the unpacked to the original as necessary.
860  */
861 static void extent_save(struct btree *b, struct bkey_packed *dst,
862                         struct bkey *src)
863 {
864         struct bkey_format *f = &b->format;
865         struct bkey_i *dst_unpacked;
866
867         if ((dst_unpacked = packed_to_bkey(dst)))
868                 dst_unpacked->k = *src;
869         else
870                 BUG_ON(!bch2_bkey_pack_key(dst, src, f));
871 }
872
873 static bool extent_i_save(struct btree *b, struct bkey_packed *dst,
874                           struct bkey_i *src)
875 {
876         struct bkey_format *f = &b->format;
877         struct bkey_i *dst_unpacked;
878         struct bkey_packed tmp;
879
880         if ((dst_unpacked = packed_to_bkey(dst)))
881                 dst_unpacked->k = src->k;
882         else if (bch2_bkey_pack_key(&tmp, &src->k, f))
883                 memcpy_u64s(dst, &tmp, f->key_u64s);
884         else
885                 return false;
886
887         memcpy_u64s(bkeyp_val(f, dst), &src->v, bkey_val_u64s(&src->k));
888         return true;
889 }
890
891 /*
892  * If keys compare equal, compare by pointer order:
893  *
894  * Necessary for sort_fix_overlapping() - if there are multiple keys that
895  * compare equal in different sets, we have to process them newest to oldest.
896  */
897 #define extent_sort_cmp(h, l, r)                                        \
898 ({                                                                      \
899         struct bkey _ul = bkey_unpack_key(b,                            \
900                                 __btree_node_offset_to_key(b, (l).k));  \
901         struct bkey _ur = bkey_unpack_key(b,                            \
902                                 __btree_node_offset_to_key(b, (r).k));  \
903                                                                         \
904         bkey_cmp(bkey_start_pos(&_ul),                                  \
905                  bkey_start_pos(&_ur)) ?: (r).k - (l).k;                \
906 })
907
908 static inline void extent_sort_sift(struct btree_node_iter_large *iter,
909                                     struct btree *b, size_t i)
910 {
911         heap_sift_down(iter, i, extent_sort_cmp);
912 }
913
914 static inline void extent_sort_next(struct btree_node_iter_large *iter,
915                                     struct btree *b,
916                                     struct btree_node_iter_set *i)
917 {
918         sort_key_next(iter, b, i);
919         heap_sift_down(iter, i - iter->data, extent_sort_cmp);
920 }
921
922 static void extent_sort_append(struct bch_fs *c,
923                                struct btree *b,
924                                struct btree_nr_keys *nr,
925                                struct bkey_packed *start,
926                                struct bkey_packed **prev,
927                                struct bkey_packed *k)
928 {
929         struct bkey_format *f = &b->format;
930         BKEY_PADDED(k) tmp;
931
932         if (bkey_whiteout(k))
933                 return;
934
935         bch2_bkey_unpack(b, &tmp.k, k);
936
937         if (*prev &&
938             bch2_extent_merge(c, b, (void *) *prev, &tmp.k))
939                 return;
940
941         if (*prev) {
942                 bch2_bkey_pack(*prev, (void *) *prev, f);
943
944                 btree_keys_account_key_add(nr, 0, *prev);
945                 *prev = bkey_next(*prev);
946         } else {
947                 *prev = start;
948         }
949
950         bkey_copy(*prev, &tmp.k);
951 }
952
953 struct btree_nr_keys bch2_extent_sort_fix_overlapping(struct bch_fs *c,
954                                         struct bset *dst,
955                                         struct btree *b,
956                                         struct btree_node_iter_large *iter)
957 {
958         struct bkey_format *f = &b->format;
959         struct btree_node_iter_set *_l = iter->data, *_r;
960         struct bkey_packed *prev = NULL, *out, *lk, *rk;
961         struct bkey l_unpacked, r_unpacked;
962         struct bkey_s l, r;
963         struct btree_nr_keys nr;
964
965         memset(&nr, 0, sizeof(nr));
966
967         heap_resort(iter, extent_sort_cmp);
968
969         while (!bch2_btree_node_iter_large_end(iter)) {
970                 lk = __btree_node_offset_to_key(b, _l->k);
971
972                 if (iter->used == 1) {
973                         extent_sort_append(c, b, &nr, dst->start, &prev, lk);
974                         extent_sort_next(iter, b, _l);
975                         continue;
976                 }
977
978                 _r = iter->data + 1;
979                 if (iter->used > 2 &&
980                     extent_sort_cmp(iter, _r[0], _r[1]) >= 0)
981                         _r++;
982
983                 rk = __btree_node_offset_to_key(b, _r->k);
984
985                 l = __bkey_disassemble(b, lk, &l_unpacked);
986                 r = __bkey_disassemble(b, rk, &r_unpacked);
987
988                 /* If current key and next key don't overlap, just append */
989                 if (bkey_cmp(l.k->p, bkey_start_pos(r.k)) <= 0) {
990                         extent_sort_append(c, b, &nr, dst->start, &prev, lk);
991                         extent_sort_next(iter, b, _l);
992                         continue;
993                 }
994
995                 /* Skip 0 size keys */
996                 if (!r.k->size) {
997                         extent_sort_next(iter, b, _r);
998                         continue;
999                 }
1000
1001                 /*
1002                  * overlap: keep the newer key and trim the older key so they
1003                  * don't overlap. comparing pointers tells us which one is
1004                  * newer, since the bsets are appended one after the other.
1005                  */
1006
1007                 /* can't happen because of comparison func */
1008                 BUG_ON(_l->k < _r->k &&
1009                        !bkey_cmp(bkey_start_pos(l.k), bkey_start_pos(r.k)));
1010
1011                 if (_l->k > _r->k) {
1012                         /* l wins, trim r */
1013                         if (bkey_cmp(l.k->p, r.k->p) >= 0) {
1014                                 sort_key_next(iter, b, _r);
1015                         } else {
1016                                 __bch2_cut_front(l.k->p, r);
1017                                 extent_save(b, rk, r.k);
1018                         }
1019
1020                         extent_sort_sift(iter, b, _r - iter->data);
1021                 } else if (bkey_cmp(l.k->p, r.k->p) > 0) {
1022                         BKEY_PADDED(k) tmp;
1023
1024                         /*
1025                          * r wins, but it overlaps in the middle of l - split l:
1026                          */
1027                         bkey_reassemble(&tmp.k, l.s_c);
1028                         bch2_cut_back(bkey_start_pos(r.k), &tmp.k.k);
1029
1030                         __bch2_cut_front(r.k->p, l);
1031                         extent_save(b, lk, l.k);
1032
1033                         extent_sort_sift(iter, b, 0);
1034
1035                         extent_sort_append(c, b, &nr, dst->start, &prev,
1036                                            bkey_to_packed(&tmp.k));
1037                 } else {
1038                         bch2_cut_back(bkey_start_pos(r.k), l.k);
1039                         extent_save(b, lk, l.k);
1040                 }
1041         }
1042
1043         if (prev) {
1044                 bch2_bkey_pack(prev, (void *) prev, f);
1045                 btree_keys_account_key_add(&nr, 0, prev);
1046                 out = bkey_next(prev);
1047         } else {
1048                 out = dst->start;
1049         }
1050
1051         dst->u64s = cpu_to_le16((u64 *) out - dst->_data);
1052         return nr;
1053 }
1054
1055 struct extent_insert_state {
1056         struct btree_insert             *trans;
1057         struct btree_insert_entry       *insert;
1058         struct bpos                     committed;
1059         struct bch_fs_usage             stats;
1060
1061         /* for deleting: */
1062         struct bkey_i                   whiteout;
1063         bool                            update_journal;
1064         bool                            update_btree;
1065         bool                            deleting;
1066 };
1067
1068 static void bch2_add_sectors(struct extent_insert_state *s,
1069                              struct bkey_s_c k, u64 offset, s64 sectors)
1070 {
1071         struct bch_fs *c = s->trans->c;
1072         struct btree *b = s->insert->iter->l[0].b;
1073
1074         EBUG_ON(bkey_cmp(bkey_start_pos(k.k), b->data->min_key) < 0);
1075
1076         if (!sectors)
1077                 return;
1078
1079         bch2_mark_key(c, k, sectors, BCH_DATA_USER, gc_pos_btree_node(b),
1080                       &s->stats, s->trans->journal_res.seq, 0);
1081 }
1082
1083 static void bch2_subtract_sectors(struct extent_insert_state *s,
1084                                  struct bkey_s_c k, u64 offset, s64 sectors)
1085 {
1086         bch2_add_sectors(s, k, offset, -sectors);
1087 }
1088
1089 /* These wrappers subtract exactly the sectors that we're removing from @k */
1090 static void bch2_cut_subtract_back(struct extent_insert_state *s,
1091                                   struct bpos where, struct bkey_s k)
1092 {
1093         bch2_subtract_sectors(s, k.s_c, where.offset,
1094                              k.k->p.offset - where.offset);
1095         bch2_cut_back(where, k.k);
1096 }
1097
1098 static void bch2_cut_subtract_front(struct extent_insert_state *s,
1099                                    struct bpos where, struct bkey_s k)
1100 {
1101         bch2_subtract_sectors(s, k.s_c, bkey_start_offset(k.k),
1102                              where.offset - bkey_start_offset(k.k));
1103         __bch2_cut_front(where, k);
1104 }
1105
1106 static void bch2_drop_subtract(struct extent_insert_state *s, struct bkey_s k)
1107 {
1108         if (k.k->size)
1109                 bch2_subtract_sectors(s, k.s_c,
1110                                      bkey_start_offset(k.k), k.k->size);
1111         k.k->size = 0;
1112         k.k->type = KEY_TYPE_DELETED;
1113 }
1114
1115 static bool bch2_extent_merge_inline(struct bch_fs *,
1116                                      struct btree_iter *,
1117                                      struct bkey_packed *,
1118                                      struct bkey_packed *,
1119                                      bool);
1120
1121 static void verify_extent_nonoverlapping(struct btree *b,
1122                                          struct btree_node_iter *_iter,
1123                                          struct bkey_i *insert)
1124 {
1125 #ifdef CONFIG_BCACHEFS_DEBUG
1126         struct btree_node_iter iter;
1127         struct bkey_packed *k;
1128         struct bkey uk;
1129
1130         iter = *_iter;
1131         k = bch2_btree_node_iter_prev_filter(&iter, b, KEY_TYPE_DISCARD);
1132         BUG_ON(k &&
1133                (uk = bkey_unpack_key(b, k),
1134                 bkey_cmp(uk.p, bkey_start_pos(&insert->k)) > 0));
1135
1136         iter = *_iter;
1137         k = bch2_btree_node_iter_peek_filter(&iter, b, KEY_TYPE_DISCARD);
1138 #if 0
1139         BUG_ON(k &&
1140                (uk = bkey_unpack_key(b, k),
1141                 bkey_cmp(insert->k.p, bkey_start_pos(&uk))) > 0);
1142 #else
1143         if (k &&
1144             (uk = bkey_unpack_key(b, k),
1145              bkey_cmp(insert->k.p, bkey_start_pos(&uk))) > 0) {
1146                 char buf1[100];
1147                 char buf2[100];
1148
1149                 bch2_bkey_to_text(buf1, sizeof(buf1), &insert->k);
1150                 bch2_bkey_to_text(buf2, sizeof(buf2), &uk);
1151
1152                 bch2_dump_btree_node(b);
1153                 panic("insert > next :\n"
1154                       "insert %s\n"
1155                       "next   %s\n",
1156                       buf1, buf2);
1157         }
1158 #endif
1159
1160 #endif
1161 }
1162
1163 static void verify_modified_extent(struct btree_iter *iter,
1164                                    struct bkey_packed *k)
1165 {
1166         bch2_btree_iter_verify(iter, iter->l[0].b);
1167         bch2_verify_insert_pos(iter->l[0].b, k, k, k->u64s);
1168 }
1169
1170 static void extent_bset_insert(struct bch_fs *c, struct btree_iter *iter,
1171                                struct bkey_i *insert)
1172 {
1173         struct btree_iter_level *l = &iter->l[0];
1174         struct btree_node_iter node_iter;
1175         struct bkey_packed *k;
1176
1177         BUG_ON(insert->k.u64s > bch_btree_keys_u64s_remaining(c, l->b));
1178
1179         EBUG_ON(bkey_deleted(&insert->k) || !insert->k.size);
1180         verify_extent_nonoverlapping(l->b, &l->iter, insert);
1181
1182         node_iter = l->iter;
1183         k = bch2_btree_node_iter_prev_filter(&node_iter, l->b, KEY_TYPE_DISCARD);
1184         if (k && !bkey_written(l->b, k) &&
1185             bch2_extent_merge_inline(c, iter, k, bkey_to_packed(insert), true))
1186                 return;
1187
1188         node_iter = l->iter;
1189         k = bch2_btree_node_iter_peek_filter(&node_iter, l->b, KEY_TYPE_DISCARD);
1190         if (k && !bkey_written(l->b, k) &&
1191             bch2_extent_merge_inline(c, iter, bkey_to_packed(insert), k, false))
1192                 return;
1193
1194         k = bch2_btree_node_iter_bset_pos(&l->iter, l->b, bset_tree_last(l->b));
1195
1196         bch2_bset_insert(l->b, &l->iter, k, insert, 0);
1197         bch2_btree_node_iter_fix(iter, l->b, &l->iter, k, 0, k->u64s);
1198         bch2_btree_iter_verify(iter, l->b);
1199 }
1200
1201 static void extent_insert_committed(struct extent_insert_state *s)
1202 {
1203         struct bch_fs *c = s->trans->c;
1204         struct btree_iter *iter = s->insert->iter;
1205         struct bkey_i *insert = s->insert->k;
1206         BKEY_PADDED(k) split;
1207
1208         EBUG_ON(bkey_cmp(insert->k.p, s->committed) < 0);
1209         EBUG_ON(bkey_cmp(s->committed, bkey_start_pos(&insert->k)) < 0);
1210
1211         bkey_copy(&split.k, insert);
1212         if (s->deleting)
1213                 split.k.k.type = KEY_TYPE_DISCARD;
1214
1215         if (!(s->trans->flags & BTREE_INSERT_JOURNAL_REPLAY))
1216                 bch2_cut_subtract_back(s, s->committed,
1217                                        bkey_i_to_s(&split.k));
1218         else
1219                 bch2_cut_back(s->committed, &split.k.k);
1220
1221         if (!bkey_cmp(s->committed, iter->pos))
1222                 return;
1223
1224         bch2_btree_iter_set_pos_same_leaf(iter, s->committed);
1225
1226         if (s->update_btree) {
1227                 if (debug_check_bkeys(c))
1228                         bch2_bkey_debugcheck(c, iter->l[0].b,
1229                                              bkey_i_to_s_c(&split.k));
1230
1231                 EBUG_ON(bkey_deleted(&split.k.k) || !split.k.k.size);
1232
1233                 extent_bset_insert(c, iter, &split.k);
1234         }
1235
1236         if (s->update_journal) {
1237                 bkey_copy(&split.k, !s->deleting ? insert : &s->whiteout);
1238                 if (s->deleting)
1239                         split.k.k.type = KEY_TYPE_DISCARD;
1240
1241                 bch2_cut_back(s->committed, &split.k.k);
1242
1243                 EBUG_ON(bkey_deleted(&split.k.k) || !split.k.k.size);
1244
1245                 bch2_btree_journal_key(s->trans, iter, &split.k);
1246         }
1247
1248         bch2_cut_front(s->committed, insert);
1249
1250         insert->k.needs_whiteout        = false;
1251         s->trans->did_work              = true;
1252 }
1253
1254 void bch2_extent_trim_atomic(struct bkey_i *k, struct btree_iter *iter)
1255 {
1256         struct btree *b = iter->l[0].b;
1257
1258         BUG_ON(iter->uptodate > BTREE_ITER_NEED_PEEK);
1259
1260         bch2_cut_back(b->key.k.p, &k->k);
1261
1262         BUG_ON(bkey_cmp(bkey_start_pos(&k->k), b->data->min_key) < 0);
1263 }
1264
1265 enum btree_insert_ret
1266 bch2_extent_can_insert(struct btree_insert *trans,
1267                        struct btree_insert_entry *insert,
1268                        unsigned *u64s)
1269 {
1270         struct btree_iter_level *l = &insert->iter->l[0];
1271         struct btree_node_iter node_iter = l->iter;
1272         enum bch_extent_overlap overlap;
1273         struct bkey_packed *_k;
1274         struct bkey unpacked;
1275         struct bkey_s_c k;
1276         int sectors;
1277
1278         BUG_ON(trans->flags & BTREE_INSERT_ATOMIC &&
1279                !bch2_extent_is_atomic(&insert->k->k, insert->iter));
1280
1281         /*
1282          * We avoid creating whiteouts whenever possible when deleting, but
1283          * those optimizations mean we may potentially insert two whiteouts
1284          * instead of one (when we overlap with the front of one extent and the
1285          * back of another):
1286          */
1287         if (bkey_whiteout(&insert->k->k))
1288                 *u64s += BKEY_U64s;
1289
1290         _k = bch2_btree_node_iter_peek_filter(&node_iter, l->b,
1291                                               KEY_TYPE_DISCARD);
1292         if (!_k)
1293                 return BTREE_INSERT_OK;
1294
1295         k = bkey_disassemble(l->b, _k, &unpacked);
1296
1297         overlap = bch2_extent_overlap(&insert->k->k, k.k);
1298
1299         /* account for having to split existing extent: */
1300         if (overlap == BCH_EXTENT_OVERLAP_MIDDLE)
1301                 *u64s += _k->u64s;
1302
1303         if (overlap == BCH_EXTENT_OVERLAP_MIDDLE &&
1304             (sectors = bch2_extent_is_compressed(k))) {
1305                 int flags = BCH_DISK_RESERVATION_BTREE_LOCKS_HELD;
1306
1307                 if (trans->flags & BTREE_INSERT_NOFAIL)
1308                         flags |= BCH_DISK_RESERVATION_NOFAIL;
1309
1310                 switch (bch2_disk_reservation_add(trans->c,
1311                                 trans->disk_res,
1312                                 sectors * bch2_extent_nr_dirty_ptrs(k),
1313                                 flags)) {
1314                 case 0:
1315                         break;
1316                 case -ENOSPC:
1317                         return BTREE_INSERT_ENOSPC;
1318                 case -EINTR:
1319                         return BTREE_INSERT_NEED_GC_LOCK;
1320                 default:
1321                         BUG();
1322                 }
1323         }
1324
1325         return BTREE_INSERT_OK;
1326 }
1327
1328 static void
1329 extent_squash(struct extent_insert_state *s, struct bkey_i *insert,
1330               struct bkey_packed *_k, struct bkey_s k,
1331               enum bch_extent_overlap overlap)
1332 {
1333         struct bch_fs *c = s->trans->c;
1334         struct btree_iter *iter = s->insert->iter;
1335         struct btree_iter_level *l = &iter->l[0];
1336
1337         switch (overlap) {
1338         case BCH_EXTENT_OVERLAP_FRONT:
1339                 /* insert overlaps with start of k: */
1340                 bch2_cut_subtract_front(s, insert->k.p, k);
1341                 BUG_ON(bkey_deleted(k.k));
1342                 extent_save(l->b, _k, k.k);
1343                 verify_modified_extent(iter, _k);
1344                 break;
1345
1346         case BCH_EXTENT_OVERLAP_BACK:
1347                 /* insert overlaps with end of k: */
1348                 bch2_cut_subtract_back(s, bkey_start_pos(&insert->k), k);
1349                 BUG_ON(bkey_deleted(k.k));
1350                 extent_save(l->b, _k, k.k);
1351
1352                 /*
1353                  * As the auxiliary tree is indexed by the end of the
1354                  * key and we've just changed the end, update the
1355                  * auxiliary tree.
1356                  */
1357                 bch2_bset_fix_invalidated_key(l->b, _k);
1358                 bch2_btree_node_iter_fix(iter, l->b, &l->iter,
1359                                          _k, _k->u64s, _k->u64s);
1360                 verify_modified_extent(iter, _k);
1361                 break;
1362
1363         case BCH_EXTENT_OVERLAP_ALL: {
1364                 /* The insert key completely covers k, invalidate k */
1365                 if (!bkey_whiteout(k.k))
1366                         btree_account_key_drop(l->b, _k);
1367
1368                 bch2_drop_subtract(s, k);
1369
1370                 if (_k >= btree_bset_last(l->b)->start) {
1371                         unsigned u64s = _k->u64s;
1372
1373                         bch2_bset_delete(l->b, _k, _k->u64s);
1374                         bch2_btree_node_iter_fix(iter, l->b, &l->iter,
1375                                                  _k, u64s, 0);
1376                         bch2_btree_iter_verify(iter, l->b);
1377                 } else {
1378                         extent_save(l->b, _k, k.k);
1379                         bch2_btree_node_iter_fix(iter, l->b, &l->iter,
1380                                                  _k, _k->u64s, _k->u64s);
1381                         verify_modified_extent(iter, _k);
1382                 }
1383
1384                 break;
1385         }
1386         case BCH_EXTENT_OVERLAP_MIDDLE: {
1387                 BKEY_PADDED(k) split;
1388                 /*
1389                  * The insert key falls 'in the middle' of k
1390                  * The insert key splits k in 3:
1391                  * - start only in k, preserve
1392                  * - middle common section, invalidate in k
1393                  * - end only in k, preserve
1394                  *
1395                  * We update the old key to preserve the start,
1396                  * insert will be the new common section,
1397                  * we manually insert the end that we are preserving.
1398                  *
1399                  * modify k _before_ doing the insert (which will move
1400                  * what k points to)
1401                  */
1402                 bkey_reassemble(&split.k, k.s_c);
1403                 split.k.k.needs_whiteout |= bkey_written(l->b, _k);
1404
1405                 bch2_cut_back(bkey_start_pos(&insert->k), &split.k.k);
1406                 BUG_ON(bkey_deleted(&split.k.k));
1407
1408                 bch2_cut_subtract_front(s, insert->k.p, k);
1409                 BUG_ON(bkey_deleted(k.k));
1410                 extent_save(l->b, _k, k.k);
1411                 verify_modified_extent(iter, _k);
1412
1413                 bch2_add_sectors(s, bkey_i_to_s_c(&split.k),
1414                                 bkey_start_offset(&split.k.k),
1415                                 split.k.k.size);
1416                 extent_bset_insert(c, iter, &split.k);
1417                 break;
1418         }
1419         }
1420 }
1421
1422 static void __bch2_insert_fixup_extent(struct extent_insert_state *s)
1423 {
1424         struct btree_iter *iter = s->insert->iter;
1425         struct btree_iter_level *l = &iter->l[0];
1426         struct bkey_packed *_k;
1427         struct bkey unpacked;
1428         struct bkey_i *insert = s->insert->k;
1429
1430         while (bkey_cmp(s->committed, insert->k.p) < 0 &&
1431                (_k = bch2_btree_node_iter_peek_filter(&l->iter, l->b,
1432                                                       KEY_TYPE_DISCARD))) {
1433                 struct bkey_s k = __bkey_disassemble(l->b, _k, &unpacked);
1434                 enum bch_extent_overlap overlap = bch2_extent_overlap(&insert->k, k.k);
1435
1436                 EBUG_ON(bkey_cmp(iter->pos, k.k->p) >= 0);
1437
1438                 if (bkey_cmp(bkey_start_pos(k.k), insert->k.p) >= 0)
1439                         break;
1440
1441                 s->committed = bpos_min(s->insert->k->k.p, k.k->p);
1442
1443                 if (!bkey_whiteout(k.k))
1444                         s->update_journal = true;
1445
1446                 if (!s->update_journal) {
1447                         bch2_cut_front(s->committed, insert);
1448                         bch2_cut_front(s->committed, &s->whiteout);
1449                         bch2_btree_iter_set_pos_same_leaf(iter, s->committed);
1450                         goto next;
1451                 }
1452
1453                 /*
1454                  * When deleting, if possible just do it by switching the type
1455                  * of the key we're deleting, instead of creating and inserting
1456                  * a new whiteout:
1457                  */
1458                 if (s->deleting &&
1459                     !s->update_btree &&
1460                     !bkey_cmp(insert->k.p, k.k->p) &&
1461                     !bkey_cmp(bkey_start_pos(&insert->k), bkey_start_pos(k.k))) {
1462                         if (!bkey_whiteout(k.k)) {
1463                                 btree_account_key_drop(l->b, _k);
1464                                 bch2_subtract_sectors(s, k.s_c,
1465                                                       bkey_start_offset(k.k), k.k->size);
1466                                 _k->type = KEY_TYPE_DISCARD;
1467                                 reserve_whiteout(l->b, _k);
1468                         }
1469                         break;
1470                 }
1471
1472                 if (k.k->needs_whiteout || bkey_written(l->b, _k)) {
1473                         insert->k.needs_whiteout = true;
1474                         s->update_btree = true;
1475                 }
1476
1477                 if (s->update_btree &&
1478                     overlap == BCH_EXTENT_OVERLAP_ALL &&
1479                     bkey_whiteout(k.k) &&
1480                     k.k->needs_whiteout) {
1481                         unreserve_whiteout(l->b, _k);
1482                         _k->needs_whiteout = false;
1483                 }
1484
1485                 extent_squash(s, insert, _k, k, overlap);
1486
1487                 if (!s->update_btree)
1488                         bch2_cut_front(s->committed, insert);
1489 next:
1490                 if (overlap == BCH_EXTENT_OVERLAP_FRONT ||
1491                     overlap == BCH_EXTENT_OVERLAP_MIDDLE)
1492                         break;
1493         }
1494
1495         if (bkey_cmp(s->committed, insert->k.p) < 0)
1496                 s->committed = bpos_min(s->insert->k->k.p, l->b->key.k.p);
1497
1498         /*
1499          * may have skipped past some deleted extents greater than the insert
1500          * key, before we got to a non deleted extent and knew we could bail out
1501          * rewind the iterator a bit if necessary:
1502          */
1503         {
1504                 struct btree_node_iter node_iter = l->iter;
1505
1506                 while ((_k = bch2_btree_node_iter_prev_all(&node_iter, l->b)) &&
1507                        bkey_cmp_left_packed(l->b, _k, &s->committed) > 0)
1508                         l->iter = node_iter;
1509         }
1510 }
1511
1512 /**
1513  * bch_extent_insert_fixup - insert a new extent and deal with overlaps
1514  *
1515  * this may result in not actually doing the insert, or inserting some subset
1516  * of the insert key. For cmpxchg operations this is where that logic lives.
1517  *
1518  * All subsets of @insert that need to be inserted are inserted using
1519  * bch2_btree_insert_and_journal(). If @b or @res fills up, this function
1520  * returns false, setting @iter->pos for the prefix of @insert that actually got
1521  * inserted.
1522  *
1523  * BSET INVARIANTS: this function is responsible for maintaining all the
1524  * invariants for bsets of extents in memory. things get really hairy with 0
1525  * size extents
1526  *
1527  * within one bset:
1528  *
1529  * bkey_start_pos(bkey_next(k)) >= k
1530  * or bkey_start_offset(bkey_next(k)) >= k->offset
1531  *
1532  * i.e. strict ordering, no overlapping extents.
1533  *
1534  * multiple bsets (i.e. full btree node):
1535  *
1536  * âˆ€ k, j
1537  *   k.size != 0 âˆ§ j.size != 0 â†’
1538  *     Â¬ (k > bkey_start_pos(j) âˆ§ k < j)
1539  *
1540  * i.e. no two overlapping keys _of nonzero size_
1541  *
1542  * We can't realistically maintain this invariant for zero size keys because of
1543  * the key merging done in bch2_btree_insert_key() - for two mergeable keys k, j
1544  * there may be another 0 size key between them in another bset, and it will
1545  * thus overlap with the merged key.
1546  *
1547  * In addition, the end of iter->pos indicates how much has been processed.
1548  * If the end of iter->pos is not the same as the end of insert, then
1549  * key insertion needs to continue/be retried.
1550  */
1551 enum btree_insert_ret
1552 bch2_insert_fixup_extent(struct btree_insert *trans,
1553                          struct btree_insert_entry *insert)
1554 {
1555         struct bch_fs *c        = trans->c;
1556         struct btree_iter *iter = insert->iter;
1557         struct btree *b         = iter->l[0].b;
1558         struct extent_insert_state s = {
1559                 .trans          = trans,
1560                 .insert         = insert,
1561                 .committed      = iter->pos,
1562
1563                 .whiteout       = *insert->k,
1564                 .update_journal = !bkey_whiteout(&insert->k->k),
1565                 .update_btree   = !bkey_whiteout(&insert->k->k),
1566                 .deleting       = bkey_whiteout(&insert->k->k),
1567         };
1568
1569         EBUG_ON(iter->level);
1570         EBUG_ON(!insert->k->k.size);
1571
1572         /*
1573          * As we process overlapping extents, we advance @iter->pos both to
1574          * signal to our caller (btree_insert_key()) how much of @insert->k has
1575          * been inserted, and also to keep @iter->pos consistent with
1576          * @insert->k and the node iterator that we're advancing:
1577          */
1578         EBUG_ON(bkey_cmp(iter->pos, bkey_start_pos(&insert->k->k)));
1579
1580         if (!s.deleting &&
1581             !(trans->flags & BTREE_INSERT_JOURNAL_REPLAY))
1582                 bch2_add_sectors(&s, bkey_i_to_s_c(insert->k),
1583                                 bkey_start_offset(&insert->k->k),
1584                                 insert->k->k.size);
1585
1586         __bch2_insert_fixup_extent(&s);
1587
1588         extent_insert_committed(&s);
1589
1590         bch2_fs_usage_apply(c, &s.stats, trans->disk_res,
1591                            gc_pos_btree_node(b));
1592
1593         EBUG_ON(bkey_cmp(iter->pos, bkey_start_pos(&insert->k->k)));
1594         EBUG_ON(bkey_cmp(iter->pos, s.committed));
1595
1596         if (insert->k->k.size) {
1597                 /* got to the end of this leaf node */
1598                 BUG_ON(bkey_cmp(iter->pos, b->key.k.p));
1599                 return BTREE_INSERT_NEED_TRAVERSE;
1600         }
1601
1602         return BTREE_INSERT_OK;
1603 }
1604
1605 const char *bch2_extent_invalid(const struct bch_fs *c, struct bkey_s_c k)
1606 {
1607         if (bkey_val_u64s(k.k) > BKEY_EXTENT_VAL_U64s_MAX)
1608                 return "value too big";
1609
1610         if (!k.k->size)
1611                 return "zero key size";
1612
1613         switch (k.k->type) {
1614         case BCH_EXTENT:
1615         case BCH_EXTENT_CACHED: {
1616                 struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
1617                 const union bch_extent_entry *entry;
1618                 struct bch_extent_crc_unpacked crc;
1619                 const struct bch_extent_ptr *ptr;
1620                 unsigned size_ondisk = e.k->size;
1621                 const char *reason;
1622                 unsigned nonce = UINT_MAX;
1623
1624                 extent_for_each_entry(e, entry) {
1625                         if (__extent_entry_type(entry) >= BCH_EXTENT_ENTRY_MAX)
1626                                 return "invalid extent entry type";
1627
1628                         if (extent_entry_is_crc(entry)) {
1629                                 crc = bch2_extent_crc_unpack(e.k, entry_to_crc(entry));
1630
1631                                 if (crc.offset + e.k->size >
1632                                     crc.uncompressed_size)
1633                                         return "checksum offset + key size > uncompressed size";
1634
1635                                 size_ondisk = crc.compressed_size;
1636
1637                                 if (!bch2_checksum_type_valid(c, crc.csum_type))
1638                                         return "invalid checksum type";
1639
1640                                 if (crc.compression_type >= BCH_COMPRESSION_NR)
1641                                         return "invalid compression type";
1642
1643                                 if (bch2_csum_type_is_encryption(crc.csum_type)) {
1644                                         if (nonce == UINT_MAX)
1645                                                 nonce = crc.offset + crc.nonce;
1646                                         else if (nonce != crc.offset + crc.nonce)
1647                                                 return "incorrect nonce";
1648                                 }
1649                         } else {
1650                                 ptr = entry_to_ptr(entry);
1651
1652                                 reason = extent_ptr_invalid(c, e, &entry->ptr,
1653                                                             size_ondisk, false);
1654                                 if (reason)
1655                                         return reason;
1656                         }
1657                 }
1658
1659                 return NULL;
1660         }
1661
1662         case BCH_RESERVATION: {
1663                 struct bkey_s_c_reservation r = bkey_s_c_to_reservation(k);
1664
1665                 if (bkey_val_bytes(k.k) != sizeof(struct bch_reservation))
1666                         return "incorrect value size";
1667
1668                 if (!r.v->nr_replicas || r.v->nr_replicas > BCH_REPLICAS_MAX)
1669                         return "invalid nr_replicas";
1670
1671                 return NULL;
1672         }
1673
1674         default:
1675                 return "invalid value type";
1676         }
1677 }
1678
1679 static void bch2_extent_debugcheck_extent(struct bch_fs *c, struct btree *b,
1680                                           struct bkey_s_c_extent e)
1681 {
1682         const struct bch_extent_ptr *ptr;
1683         struct bch_dev *ca;
1684         struct bucket_mark mark;
1685         unsigned seq, stale;
1686         char buf[160];
1687         bool bad;
1688         unsigned replicas = 0;
1689
1690         /*
1691          * XXX: we should be doing most/all of these checks at startup time,
1692          * where we check bch2_bkey_invalid() in btree_node_read_done()
1693          *
1694          * But note that we can't check for stale pointers or incorrect gc marks
1695          * until after journal replay is done (it might be an extent that's
1696          * going to get overwritten during replay)
1697          */
1698
1699         extent_for_each_ptr(e, ptr) {
1700                 ca = bch_dev_bkey_exists(c, ptr->dev);
1701                 replicas++;
1702
1703                 /*
1704                  * If journal replay hasn't finished, we might be seeing keys
1705                  * that will be overwritten by the time journal replay is done:
1706                  */
1707                 if (!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags))
1708                         continue;
1709
1710                 stale = 0;
1711
1712                 do {
1713                         seq = read_seqcount_begin(&c->gc_pos_lock);
1714                         mark = ptr_bucket_mark(ca, ptr);
1715
1716                         /* between mark and bucket gen */
1717                         smp_rmb();
1718
1719                         stale = ptr_stale(ca, ptr);
1720
1721                         bch2_fs_bug_on(stale && !ptr->cached, c,
1722                                          "stale dirty pointer");
1723
1724                         bch2_fs_bug_on(stale > 96, c,
1725                                          "key too stale: %i",
1726                                          stale);
1727
1728                         if (stale)
1729                                 break;
1730
1731                         bad = gc_pos_cmp(c->gc_pos, gc_pos_btree_node(b)) > 0 &&
1732                                 (mark.data_type != BCH_DATA_USER ||
1733                                  !(ptr->cached
1734                                    ? mark.cached_sectors
1735                                    : mark.dirty_sectors));
1736                 } while (read_seqcount_retry(&c->gc_pos_lock, seq));
1737
1738                 if (bad)
1739                         goto bad_ptr;
1740         }
1741
1742         if (replicas > BCH_REPLICAS_MAX) {
1743                 bch2_bkey_val_to_text(c, btree_node_type(b), buf,
1744                                      sizeof(buf), e.s_c);
1745                 bch2_fs_bug(c,
1746                         "extent key bad (too many replicas: %u): %s",
1747                         replicas, buf);
1748                 return;
1749         }
1750
1751         if (!bkey_extent_is_cached(e.k) &&
1752             !bch2_bkey_replicas_marked(c, BCH_DATA_USER, e.s_c)) {
1753                 bch2_bkey_val_to_text(c, btree_node_type(b),
1754                                      buf, sizeof(buf), e.s_c);
1755                 bch2_fs_bug(c,
1756                         "extent key bad (replicas not marked in superblock):\n%s",
1757                         buf);
1758                 return;
1759         }
1760
1761         return;
1762
1763 bad_ptr:
1764         bch2_bkey_val_to_text(c, btree_node_type(b), buf,
1765                              sizeof(buf), e.s_c);
1766         bch2_fs_bug(c, "extent pointer bad gc mark: %s:\nbucket %zu "
1767                    "gen %i type %u", buf,
1768                    PTR_BUCKET_NR(ca, ptr), mark.gen, mark.data_type);
1769         return;
1770 }
1771
1772 void bch2_extent_debugcheck(struct bch_fs *c, struct btree *b, struct bkey_s_c k)
1773 {
1774         switch (k.k->type) {
1775         case BCH_EXTENT:
1776         case BCH_EXTENT_CACHED:
1777                 bch2_extent_debugcheck_extent(c, b, bkey_s_c_to_extent(k));
1778                 break;
1779         case BCH_RESERVATION:
1780                 break;
1781         default:
1782                 BUG();
1783         }
1784 }
1785
1786 int bch2_extent_to_text(struct bch_fs *c, char *buf,
1787                         size_t size, struct bkey_s_c k)
1788 {
1789         char *out = buf, *end = buf + size;
1790         const char *invalid;
1791
1792 #define p(...)  (out += scnprintf(out, end - out, __VA_ARGS__))
1793
1794         if (bkey_extent_is_data(k.k))
1795                 out += extent_print_ptrs(c, buf, size, bkey_s_c_to_extent(k));
1796
1797         invalid = bch2_extent_invalid(c, k);
1798         if (invalid)
1799                 p(" invalid: %s", invalid);
1800 #undef p
1801         return out - buf;
1802 }
1803
1804 static void bch2_extent_crc_init(union bch_extent_crc *crc,
1805                                  struct bch_extent_crc_unpacked new)
1806 {
1807 #define common_fields(_crc)                                             \
1808                 .csum_type              = _crc.csum_type,               \
1809                 .compression_type       = _crc.compression_type,        \
1810                 ._compressed_size       = _crc.compressed_size - 1,     \
1811                 ._uncompressed_size     = _crc.uncompressed_size - 1,   \
1812                 .offset                 = _crc.offset
1813
1814         if (bch_crc_bytes[new.csum_type]        <= 4 &&
1815             new.uncompressed_size               <= CRC32_SIZE_MAX &&
1816             new.nonce                           <= CRC32_NONCE_MAX) {
1817                 crc->crc32 = (struct bch_extent_crc32) {
1818                         .type = 1 << BCH_EXTENT_ENTRY_crc32,
1819                         common_fields(new),
1820                         .csum                   = *((__le32 *) &new.csum.lo),
1821                 };
1822                 return;
1823         }
1824
1825         if (bch_crc_bytes[new.csum_type]        <= 10 &&
1826             new.uncompressed_size               <= CRC64_SIZE_MAX &&
1827             new.nonce                           <= CRC64_NONCE_MAX) {
1828                 crc->crc64 = (struct bch_extent_crc64) {
1829                         .type = 1 << BCH_EXTENT_ENTRY_crc64,
1830                         common_fields(new),
1831                         .nonce                  = new.nonce,
1832                         .csum_lo                = new.csum.lo,
1833                         .csum_hi                = *((__le16 *) &new.csum.hi),
1834                 };
1835                 return;
1836         }
1837
1838         if (bch_crc_bytes[new.csum_type]        <= 16 &&
1839             new.uncompressed_size               <= CRC128_SIZE_MAX &&
1840             new.nonce                           <= CRC128_NONCE_MAX) {
1841                 crc->crc128 = (struct bch_extent_crc128) {
1842                         .type = 1 << BCH_EXTENT_ENTRY_crc128,
1843                         common_fields(new),
1844                         .nonce                  = new.nonce,
1845                         .csum                   = new.csum,
1846                 };
1847                 return;
1848         }
1849 #undef common_fields
1850         BUG();
1851 }
1852
1853 void bch2_extent_crc_append(struct bkey_i_extent *e,
1854                             struct bch_extent_crc_unpacked new)
1855 {
1856         struct bch_extent_crc_unpacked crc;
1857         const union bch_extent_entry *i;
1858
1859         BUG_ON(new.compressed_size > new.uncompressed_size);
1860         BUG_ON(new.live_size != e->k.size);
1861         BUG_ON(!new.compressed_size || !new.uncompressed_size);
1862
1863         /*
1864          * Look up the last crc entry, so we can check if we need to add
1865          * another:
1866          */
1867         extent_for_each_crc(extent_i_to_s(e), crc, i)
1868                 ;
1869
1870         if (!bch2_crc_unpacked_cmp(crc, new))
1871                 return;
1872
1873         bch2_extent_crc_init((void *) extent_entry_last(extent_i_to_s(e)), new);
1874         __extent_entry_push(e);
1875 }
1876
1877 /*
1878  * bch_extent_normalize - clean up an extent, dropping stale pointers etc.
1879  *
1880  * Returns true if @k should be dropped entirely
1881  *
1882  * For existing keys, only called when btree nodes are being rewritten, not when
1883  * they're merely being compacted/resorted in memory.
1884  */
1885 bool bch2_extent_normalize(struct bch_fs *c, struct bkey_s k)
1886 {
1887         struct bkey_s_extent e;
1888
1889         switch (k.k->type) {
1890         case KEY_TYPE_ERROR:
1891                 return false;
1892
1893         case KEY_TYPE_DELETED:
1894                 return true;
1895         case KEY_TYPE_DISCARD:
1896                 return bversion_zero(k.k->version);
1897         case KEY_TYPE_COOKIE:
1898                 return false;
1899
1900         case BCH_EXTENT:
1901         case BCH_EXTENT_CACHED:
1902                 e = bkey_s_to_extent(k);
1903
1904                 bch2_extent_drop_stale(c, e);
1905
1906                 if (!bkey_val_u64s(e.k)) {
1907                         if (bkey_extent_is_cached(e.k)) {
1908                                 k.k->type = KEY_TYPE_DISCARD;
1909                                 if (bversion_zero(k.k->version))
1910                                         return true;
1911                         } else {
1912                                 k.k->type = KEY_TYPE_ERROR;
1913                         }
1914                 }
1915
1916                 return false;
1917         case BCH_RESERVATION:
1918                 return false;
1919         default:
1920                 BUG();
1921         }
1922 }
1923
1924 void bch2_extent_mark_replicas_cached(struct bch_fs *c,
1925                                       struct bkey_s_extent e,
1926                                       unsigned target,
1927                                       unsigned nr_desired_replicas)
1928 {
1929         struct bch_extent_ptr *ptr;
1930         int extra = bch2_extent_durability(c, e.c) - nr_desired_replicas;
1931
1932         if (target && extra > 0)
1933                 extent_for_each_ptr(e, ptr) {
1934                         int n = bch2_extent_ptr_durability(c, ptr);
1935
1936                         if (n && n <= extra &&
1937                             !bch2_dev_in_target(c, ptr->dev, target)) {
1938                                 ptr->cached = true;
1939                                 extra -= n;
1940                         }
1941                 }
1942
1943         if (extra > 0)
1944                 extent_for_each_ptr(e, ptr) {
1945                         int n = bch2_extent_ptr_durability(c, ptr);
1946
1947                         if (n && n <= extra) {
1948                                 ptr->cached = true;
1949                                 extra -= n;
1950                         }
1951                 }
1952 }
1953
1954 /*
1955  * This picks a non-stale pointer, preferably from a device other than @avoid.
1956  * Avoid can be NULL, meaning pick any. If there are no non-stale pointers to
1957  * other devices, it will still pick a pointer from avoid.
1958  */
1959 int bch2_extent_pick_ptr(struct bch_fs *c, struct bkey_s_c k,
1960                          struct bch_devs_mask *avoid,
1961                          struct extent_ptr_decoded *pick)
1962 {
1963         int ret;
1964
1965         switch (k.k->type) {
1966         case KEY_TYPE_ERROR:
1967                 return -EIO;
1968
1969         case BCH_EXTENT:
1970         case BCH_EXTENT_CACHED:
1971                 ret = extent_pick_read_device(c, bkey_s_c_to_extent(k),
1972                                               avoid, pick);
1973
1974                 if (!ret && !bkey_extent_is_cached(k.k))
1975                         ret = -EIO;
1976
1977                 return ret;
1978
1979         default:
1980                 return 0;
1981         }
1982 }
1983
1984 enum merge_result bch2_extent_merge(struct bch_fs *c, struct btree *b,
1985                                     struct bkey_i *l, struct bkey_i *r)
1986 {
1987         struct bkey_s_extent el, er;
1988         union bch_extent_entry *en_l, *en_r;
1989
1990         if (key_merging_disabled(c))
1991                 return BCH_MERGE_NOMERGE;
1992
1993         /*
1994          * Generic header checks
1995          * Assumes left and right are in order
1996          * Left and right must be exactly aligned
1997          */
1998
1999         if (l->k.u64s           != r->k.u64s ||
2000             l->k.type           != r->k.type ||
2001             bversion_cmp(l->k.version, r->k.version) ||
2002             bkey_cmp(l->k.p, bkey_start_pos(&r->k)))
2003                 return BCH_MERGE_NOMERGE;
2004
2005         switch (l->k.type) {
2006         case KEY_TYPE_DISCARD:
2007         case KEY_TYPE_ERROR:
2008                 /* These types are mergeable, and no val to check */
2009                 break;
2010
2011         case BCH_EXTENT:
2012         case BCH_EXTENT_CACHED:
2013                 el = bkey_i_to_s_extent(l);
2014                 er = bkey_i_to_s_extent(r);
2015
2016                 extent_for_each_entry(el, en_l) {
2017                         struct bch_extent_ptr *lp, *rp;
2018                         struct bch_dev *ca;
2019
2020                         en_r = vstruct_idx(er.v, (u64 *) en_l - el.v->_data);
2021
2022                         if ((extent_entry_type(en_l) !=
2023                              extent_entry_type(en_r)) ||
2024                             extent_entry_is_crc(en_l))
2025                                 return BCH_MERGE_NOMERGE;
2026
2027                         lp = &en_l->ptr;
2028                         rp = &en_r->ptr;
2029
2030                         if (lp->offset + el.k->size     != rp->offset ||
2031                             lp->dev                     != rp->dev ||
2032                             lp->gen                     != rp->gen)
2033                                 return BCH_MERGE_NOMERGE;
2034
2035                         /* We don't allow extents to straddle buckets: */
2036                         ca = bch_dev_bkey_exists(c, lp->dev);
2037
2038                         if (PTR_BUCKET_NR(ca, lp) != PTR_BUCKET_NR(ca, rp))
2039                                 return BCH_MERGE_NOMERGE;
2040                 }
2041
2042                 break;
2043         case BCH_RESERVATION: {
2044                 struct bkey_i_reservation *li = bkey_i_to_reservation(l);
2045                 struct bkey_i_reservation *ri = bkey_i_to_reservation(r);
2046
2047                 if (li->v.generation != ri->v.generation ||
2048                     li->v.nr_replicas != ri->v.nr_replicas)
2049                         return BCH_MERGE_NOMERGE;
2050                 break;
2051         }
2052         default:
2053                 return BCH_MERGE_NOMERGE;
2054         }
2055
2056         l->k.needs_whiteout |= r->k.needs_whiteout;
2057
2058         /* Keys with no pointers aren't restricted to one bucket and could
2059          * overflow KEY_SIZE
2060          */
2061         if ((u64) l->k.size + r->k.size > KEY_SIZE_MAX) {
2062                 bch2_key_resize(&l->k, KEY_SIZE_MAX);
2063                 bch2_cut_front(l->k.p, r);
2064                 return BCH_MERGE_PARTIAL;
2065         }
2066
2067         bch2_key_resize(&l->k, l->k.size + r->k.size);
2068
2069         return BCH_MERGE_MERGE;
2070 }
2071
2072 /*
2073  * When merging an extent that we're inserting into a btree node, the new merged
2074  * extent could overlap with an existing 0 size extent - if we don't fix that,
2075  * it'll break the btree node iterator so this code finds those 0 size extents
2076  * and shifts them out of the way.
2077  *
2078  * Also unpacks and repacks.
2079  */
2080 static bool bch2_extent_merge_inline(struct bch_fs *c,
2081                                      struct btree_iter *iter,
2082                                      struct bkey_packed *l,
2083                                      struct bkey_packed *r,
2084                                      bool back_merge)
2085 {
2086         struct btree *b = iter->l[0].b;
2087         struct btree_node_iter *node_iter = &iter->l[0].iter;
2088         BKEY_PADDED(k) li, ri;
2089         struct bkey_packed *m   = back_merge ? l : r;
2090         struct bkey_i *mi       = back_merge ? &li.k : &ri.k;
2091         struct bset_tree *t     = bch2_bkey_to_bset(b, m);
2092         enum merge_result ret;
2093
2094         EBUG_ON(bkey_written(b, m));
2095
2096         /*
2097          * We need to save copies of both l and r, because we might get a
2098          * partial merge (which modifies both) and then fails to repack
2099          */
2100         bch2_bkey_unpack(b, &li.k, l);
2101         bch2_bkey_unpack(b, &ri.k, r);
2102
2103         ret = bch2_extent_merge(c, b, &li.k, &ri.k);
2104         if (ret == BCH_MERGE_NOMERGE)
2105                 return false;
2106
2107         /*
2108          * check if we overlap with deleted extents - would break the sort
2109          * order:
2110          */
2111         if (back_merge) {
2112                 struct bkey_packed *n = bkey_next(m);
2113
2114                 if (n != btree_bkey_last(b, t) &&
2115                     bkey_cmp_left_packed(b, n, &li.k.k.p) <= 0 &&
2116                     bkey_deleted(n))
2117                         return false;
2118         } else if (ret == BCH_MERGE_MERGE) {
2119                 struct bkey_packed *prev = bch2_bkey_prev_all(b, t, m);
2120
2121                 if (prev &&
2122                     bkey_cmp_left_packed_byval(b, prev,
2123                                 bkey_start_pos(&li.k.k)) > 0)
2124                         return false;
2125         }
2126
2127         if (ret == BCH_MERGE_PARTIAL) {
2128                 if (!extent_i_save(b, m, mi))
2129                         return false;
2130
2131                 if (!back_merge)
2132                         bkey_copy(packed_to_bkey(l), &li.k);
2133                 else
2134                         bkey_copy(packed_to_bkey(r), &ri.k);
2135         } else {
2136                 if (!extent_i_save(b, m, &li.k))
2137                         return false;
2138         }
2139
2140         bch2_bset_fix_invalidated_key(b, m);
2141         bch2_btree_node_iter_fix(iter, b, node_iter,
2142                                  m, m->u64s, m->u64s);
2143         verify_modified_extent(iter, m);
2144
2145         return ret == BCH_MERGE_MERGE;
2146 }
2147
2148 int bch2_check_range_allocated(struct bch_fs *c, struct bpos pos, u64 size)
2149 {
2150         struct btree_iter iter;
2151         struct bpos end = pos;
2152         struct bkey_s_c k;
2153         int ret = 0;
2154
2155         end.offset += size;
2156
2157         for_each_btree_key(&iter, c, BTREE_ID_EXTENTS, pos,
2158                              BTREE_ITER_SLOTS, k) {
2159                 if (bkey_cmp(bkey_start_pos(k.k), end) >= 0)
2160                         break;
2161
2162                 if (!bch2_extent_is_fully_allocated(k)) {
2163                         ret = -ENOSPC;
2164                         break;
2165                 }
2166         }
2167         bch2_btree_iter_unlock(&iter);
2168
2169         return ret;
2170 }