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