bcachefs: Kill bch2_fs_bug()
[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_iter.h"
13 #include "buckets.h"
14 #include "checksum.h"
15 #include "debug.h"
16 #include "disk_groups.h"
17 #include "error.h"
18 #include "extents.h"
19 #include "inode.h"
20 #include "journal.h"
21 #include "replicas.h"
22 #include "super.h"
23 #include "super-io.h"
24 #include "trace.h"
25 #include "util.h"
26
27 static unsigned bch2_crc_field_size_max[] = {
28         [BCH_EXTENT_ENTRY_crc32] = CRC32_SIZE_MAX,
29         [BCH_EXTENT_ENTRY_crc64] = CRC64_SIZE_MAX,
30         [BCH_EXTENT_ENTRY_crc128] = CRC128_SIZE_MAX,
31 };
32
33 static void bch2_extent_crc_pack(union bch_extent_crc *,
34                                  struct bch_extent_crc_unpacked,
35                                  enum bch_extent_entry_type);
36
37 static struct bch_dev_io_failures *dev_io_failures(struct bch_io_failures *f,
38                                                    unsigned dev)
39 {
40         struct bch_dev_io_failures *i;
41
42         for (i = f->devs; i < f->devs + f->nr; i++)
43                 if (i->dev == dev)
44                         return i;
45
46         return NULL;
47 }
48
49 void bch2_mark_io_failure(struct bch_io_failures *failed,
50                           struct extent_ptr_decoded *p)
51 {
52         struct bch_dev_io_failures *f = dev_io_failures(failed, p->ptr.dev);
53
54         if (!f) {
55                 BUG_ON(failed->nr >= ARRAY_SIZE(failed->devs));
56
57                 f = &failed->devs[failed->nr++];
58                 f->dev          = p->ptr.dev;
59                 f->idx          = p->idx;
60                 f->nr_failed    = 1;
61                 f->nr_retries   = 0;
62         } else if (p->idx != f->idx) {
63                 f->idx          = p->idx;
64                 f->nr_failed    = 1;
65                 f->nr_retries   = 0;
66         } else {
67                 f->nr_failed++;
68         }
69 }
70
71 /*
72  * returns true if p1 is better than p2:
73  */
74 static inline bool ptr_better(struct bch_fs *c,
75                               const struct extent_ptr_decoded p1,
76                               const struct extent_ptr_decoded p2)
77 {
78         if (likely(!p1.idx && !p2.idx)) {
79                 struct bch_dev *dev1 = bch_dev_bkey_exists(c, p1.ptr.dev);
80                 struct bch_dev *dev2 = bch_dev_bkey_exists(c, p2.ptr.dev);
81
82                 u64 l1 = atomic64_read(&dev1->cur_latency[READ]);
83                 u64 l2 = atomic64_read(&dev2->cur_latency[READ]);
84
85                 /* Pick at random, biased in favor of the faster device: */
86
87                 return bch2_rand_range(l1 + l2) > l1;
88         }
89
90         if (force_reconstruct_read(c))
91                 return p1.idx > p2.idx;
92
93         return p1.idx < p2.idx;
94 }
95
96 /*
97  * This picks a non-stale pointer, preferably from a device other than @avoid.
98  * Avoid can be NULL, meaning pick any. If there are no non-stale pointers to
99  * other devices, it will still pick a pointer from avoid.
100  */
101 int bch2_bkey_pick_read_device(struct bch_fs *c, struct bkey_s_c k,
102                                struct bch_io_failures *failed,
103                                struct extent_ptr_decoded *pick)
104 {
105         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
106         const union bch_extent_entry *entry;
107         struct extent_ptr_decoded p;
108         struct bch_dev_io_failures *f;
109         struct bch_dev *ca;
110         int ret = 0;
111
112         if (k.k->type == KEY_TYPE_error)
113                 return -EIO;
114
115         bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
116                 ca = bch_dev_bkey_exists(c, p.ptr.dev);
117
118                 /*
119                  * If there are any dirty pointers it's an error if we can't
120                  * read:
121                  */
122                 if (!ret && !p.ptr.cached)
123                         ret = -EIO;
124
125                 if (p.ptr.cached && ptr_stale(ca, &p.ptr))
126                         continue;
127
128                 f = failed ? dev_io_failures(failed, p.ptr.dev) : NULL;
129                 if (f)
130                         p.idx = f->nr_failed < f->nr_retries
131                                 ? f->idx
132                                 : f->idx + 1;
133
134                 if (!p.idx &&
135                     !bch2_dev_is_readable(ca))
136                         p.idx++;
137
138                 if (force_reconstruct_read(c) &&
139                     !p.idx && p.has_ec)
140                         p.idx++;
141
142                 if (p.idx >= (unsigned) p.has_ec + 1)
143                         continue;
144
145                 if (ret > 0 && !ptr_better(c, p, *pick))
146                         continue;
147
148                 *pick = p;
149                 ret = 1;
150         }
151
152         return ret;
153 }
154
155 /* KEY_TYPE_btree_ptr: */
156
157 const char *bch2_btree_ptr_invalid(const struct bch_fs *c, struct bkey_s_c k)
158 {
159         if (bkey_val_u64s(k.k) > BKEY_BTREE_PTR_VAL_U64s_MAX)
160                 return "value too big";
161
162         return bch2_bkey_ptrs_invalid(c, k);
163 }
164
165 void bch2_btree_ptr_debugcheck(struct bch_fs *c, struct bkey_s_c k)
166 {
167         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
168         const struct bch_extent_ptr *ptr;
169         const char *err;
170         char buf[160];
171         struct bucket_mark mark;
172         struct bch_dev *ca;
173
174         if (!test_bit(BCH_FS_INITIAL_GC_DONE, &c->flags))
175                 return;
176
177         if (!percpu_down_read_trylock(&c->mark_lock))
178                 return;
179
180         bch2_fs_inconsistent_on(!test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) &&
181                 !bch2_bkey_replicas_marked(c, k, false), c,
182                 "btree key bad (replicas not marked in superblock):\n%s",
183                 (bch2_bkey_val_to_text(&PBUF(buf), c, k), buf));
184
185         bkey_for_each_ptr(ptrs, ptr) {
186                 ca = bch_dev_bkey_exists(c, ptr->dev);
187
188                 mark = ptr_bucket_mark(ca, ptr);
189
190                 err = "stale";
191                 if (gen_after(mark.gen, ptr->gen))
192                         goto err;
193
194                 err = "inconsistent";
195                 if (mark.data_type != BCH_DATA_BTREE ||
196                     mark.dirty_sectors < c->opts.btree_node_size)
197                         goto err;
198         }
199 out:
200         percpu_up_read(&c->mark_lock);
201         return;
202 err:
203         bch2_fs_inconsistent(c, "%s btree pointer %s: bucket %zi gen %i mark %08x",
204                 err, (bch2_bkey_val_to_text(&PBUF(buf), c, k), buf),
205                 PTR_BUCKET_NR(ca, ptr),
206                 mark.gen, (unsigned) mark.v.counter);
207         goto out;
208 }
209
210 void bch2_btree_ptr_to_text(struct printbuf *out, struct bch_fs *c,
211                             struct bkey_s_c k)
212 {
213         bch2_bkey_ptrs_to_text(out, c, k);
214 }
215
216 /* KEY_TYPE_extent: */
217
218 const char *bch2_extent_invalid(const struct bch_fs *c, struct bkey_s_c k)
219 {
220         return bch2_bkey_ptrs_invalid(c, k);
221 }
222
223 void bch2_extent_debugcheck(struct bch_fs *c, struct bkey_s_c k)
224 {
225         struct bkey_s_c_extent e = bkey_s_c_to_extent(k);
226         const union bch_extent_entry *entry;
227         struct extent_ptr_decoded p;
228         char buf[160];
229
230         if (!test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags) ||
231             !test_bit(BCH_FS_INITIAL_GC_DONE, &c->flags))
232                 return;
233
234         if (!percpu_down_read_trylock(&c->mark_lock))
235                 return;
236
237         bch2_fs_inconsistent_on(!test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) &&
238                 !bch2_bkey_replicas_marked_locked(c, e.s_c, false), c,
239                 "extent key bad (replicas not marked in superblock):\n%s",
240                 (bch2_bkey_val_to_text(&PBUF(buf), c, e.s_c), buf));
241
242         extent_for_each_ptr_decode(e, p, entry) {
243                 struct bch_dev *ca      = bch_dev_bkey_exists(c, p.ptr.dev);
244                 struct bucket_mark mark = ptr_bucket_mark(ca, &p.ptr);
245                 unsigned stale          = gen_after(mark.gen, p.ptr.gen);
246                 unsigned disk_sectors   = ptr_disk_sectors(p);
247                 unsigned mark_sectors   = p.ptr.cached
248                         ? mark.cached_sectors
249                         : mark.dirty_sectors;
250
251                 bch2_fs_inconsistent_on(stale && !p.ptr.cached, c,
252                         "stale dirty pointer (ptr gen %u bucket %u",
253                         p.ptr.gen, mark.gen);
254
255                 bch2_fs_inconsistent_on(stale > 96, c,
256                         "key too stale: %i", stale);
257
258                 bch2_fs_inconsistent_on(!stale &&
259                         (mark.data_type != BCH_DATA_USER ||
260                          mark_sectors < disk_sectors), c,
261                         "extent pointer not marked: %s:\n"
262                         "type %u sectors %u < %u",
263                         (bch2_bkey_val_to_text(&PBUF(buf), c, e.s_c), buf),
264                         mark.data_type,
265                         mark_sectors, disk_sectors);
266         }
267
268         percpu_up_read(&c->mark_lock);
269 }
270
271 void bch2_extent_to_text(struct printbuf *out, struct bch_fs *c,
272                          struct bkey_s_c k)
273 {
274         bch2_bkey_ptrs_to_text(out, c, k);
275 }
276
277 enum merge_result bch2_extent_merge(struct bch_fs *c,
278                                     struct bkey_s _l, struct bkey_s _r)
279 {
280         struct bkey_s_extent l = bkey_s_to_extent(_l);
281         struct bkey_s_extent r = bkey_s_to_extent(_r);
282         union bch_extent_entry *en_l = l.v->start;
283         union bch_extent_entry *en_r = r.v->start;
284         struct bch_extent_crc_unpacked crc_l, crc_r;
285
286         if (bkey_val_u64s(l.k) != bkey_val_u64s(r.k))
287                 return BCH_MERGE_NOMERGE;
288
289         crc_l = bch2_extent_crc_unpack(l.k, NULL);
290
291         extent_for_each_entry(l, en_l) {
292                 en_r = vstruct_idx(r.v, (u64 *) en_l - l.v->_data);
293
294                 if (extent_entry_type(en_l) != extent_entry_type(en_r))
295                         return BCH_MERGE_NOMERGE;
296
297                 switch (extent_entry_type(en_l)) {
298                 case BCH_EXTENT_ENTRY_ptr: {
299                         const struct bch_extent_ptr *lp = &en_l->ptr;
300                         const struct bch_extent_ptr *rp = &en_r->ptr;
301                         struct bch_dev *ca;
302
303                         if (lp->offset + crc_l.compressed_size != rp->offset ||
304                             lp->dev                     != rp->dev ||
305                             lp->gen                     != rp->gen)
306                                 return BCH_MERGE_NOMERGE;
307
308                         /* We don't allow extents to straddle buckets: */
309                         ca = bch_dev_bkey_exists(c, lp->dev);
310
311                         if (PTR_BUCKET_NR(ca, lp) != PTR_BUCKET_NR(ca, rp))
312                                 return BCH_MERGE_NOMERGE;
313
314                         break;
315                 }
316                 case BCH_EXTENT_ENTRY_stripe_ptr:
317                         if (en_l->stripe_ptr.block      != en_r->stripe_ptr.block ||
318                             en_l->stripe_ptr.idx        != en_r->stripe_ptr.idx)
319                                 return BCH_MERGE_NOMERGE;
320                         break;
321                 case BCH_EXTENT_ENTRY_crc32:
322                 case BCH_EXTENT_ENTRY_crc64:
323                 case BCH_EXTENT_ENTRY_crc128:
324                         crc_l = bch2_extent_crc_unpack(l.k, entry_to_crc(en_l));
325                         crc_r = bch2_extent_crc_unpack(r.k, entry_to_crc(en_r));
326
327                         if (crc_l.csum_type             != crc_r.csum_type ||
328                             crc_l.compression_type      != crc_r.compression_type ||
329                             crc_l.nonce                 != crc_r.nonce)
330                                 return BCH_MERGE_NOMERGE;
331
332                         if (crc_l.offset + crc_l.live_size != crc_l.compressed_size ||
333                             crc_r.offset)
334                                 return BCH_MERGE_NOMERGE;
335
336                         if (!bch2_checksum_mergeable(crc_l.csum_type))
337                                 return BCH_MERGE_NOMERGE;
338
339                         if (crc_l.compression_type)
340                                 return BCH_MERGE_NOMERGE;
341
342                         if (crc_l.csum_type &&
343                             crc_l.uncompressed_size +
344                             crc_r.uncompressed_size > c->sb.encoded_extent_max)
345                                 return BCH_MERGE_NOMERGE;
346
347                         if (crc_l.uncompressed_size + crc_r.uncompressed_size - 1 >
348                             bch2_crc_field_size_max[extent_entry_type(en_l)])
349                                 return BCH_MERGE_NOMERGE;
350
351                         break;
352                 default:
353                         return BCH_MERGE_NOMERGE;
354                 }
355         }
356
357         extent_for_each_entry(l, en_l) {
358                 struct bch_extent_crc_unpacked crc_l, crc_r;
359
360                 en_r = vstruct_idx(r.v, (u64 *) en_l - l.v->_data);
361
362                 if (!extent_entry_is_crc(en_l))
363                         continue;
364
365                 crc_l = bch2_extent_crc_unpack(l.k, entry_to_crc(en_l));
366                 crc_r = bch2_extent_crc_unpack(r.k, entry_to_crc(en_r));
367
368                 crc_l.csum = bch2_checksum_merge(crc_l.csum_type,
369                                                  crc_l.csum,
370                                                  crc_r.csum,
371                                                  crc_r.uncompressed_size << 9);
372
373                 crc_l.uncompressed_size += crc_r.uncompressed_size;
374                 crc_l.compressed_size   += crc_r.compressed_size;
375
376                 bch2_extent_crc_pack(entry_to_crc(en_l), crc_l,
377                                      extent_entry_type(en_l));
378         }
379
380         bch2_key_resize(l.k, l.k->size + r.k->size);
381
382         return BCH_MERGE_MERGE;
383 }
384
385 /* KEY_TYPE_reservation: */
386
387 const char *bch2_reservation_invalid(const struct bch_fs *c, struct bkey_s_c k)
388 {
389         struct bkey_s_c_reservation r = bkey_s_c_to_reservation(k);
390
391         if (bkey_val_bytes(k.k) != sizeof(struct bch_reservation))
392                 return "incorrect value size";
393
394         if (!r.v->nr_replicas || r.v->nr_replicas > BCH_REPLICAS_MAX)
395                 return "invalid nr_replicas";
396
397         return NULL;
398 }
399
400 void bch2_reservation_to_text(struct printbuf *out, struct bch_fs *c,
401                               struct bkey_s_c k)
402 {
403         struct bkey_s_c_reservation r = bkey_s_c_to_reservation(k);
404
405         pr_buf(out, "generation %u replicas %u",
406                le32_to_cpu(r.v->generation),
407                r.v->nr_replicas);
408 }
409
410 enum merge_result bch2_reservation_merge(struct bch_fs *c,
411                                          struct bkey_s _l, struct bkey_s _r)
412 {
413         struct bkey_s_reservation l = bkey_s_to_reservation(_l);
414         struct bkey_s_reservation r = bkey_s_to_reservation(_r);
415
416         if (l.v->generation != r.v->generation ||
417             l.v->nr_replicas != r.v->nr_replicas)
418                 return BCH_MERGE_NOMERGE;
419
420         if ((u64) l.k->size + r.k->size > KEY_SIZE_MAX) {
421                 bch2_key_resize(l.k, KEY_SIZE_MAX);
422                 bch2_cut_front_s(l.k->p, r.s);
423                 return BCH_MERGE_PARTIAL;
424         }
425
426         bch2_key_resize(l.k, l.k->size + r.k->size);
427
428         return BCH_MERGE_MERGE;
429 }
430
431 /* Extent checksum entries: */
432
433 /* returns true if not equal */
434 static inline bool bch2_crc_unpacked_cmp(struct bch_extent_crc_unpacked l,
435                                          struct bch_extent_crc_unpacked r)
436 {
437         return (l.csum_type             != r.csum_type ||
438                 l.compression_type      != r.compression_type ||
439                 l.compressed_size       != r.compressed_size ||
440                 l.uncompressed_size     != r.uncompressed_size ||
441                 l.offset                != r.offset ||
442                 l.live_size             != r.live_size ||
443                 l.nonce                 != r.nonce ||
444                 bch2_crc_cmp(l.csum, r.csum));
445 }
446
447 static inline bool can_narrow_crc(struct bch_extent_crc_unpacked u,
448                                   struct bch_extent_crc_unpacked n)
449 {
450         return !u.compression_type &&
451                 u.csum_type &&
452                 u.uncompressed_size > u.live_size &&
453                 bch2_csum_type_is_encryption(u.csum_type) ==
454                 bch2_csum_type_is_encryption(n.csum_type);
455 }
456
457 bool bch2_can_narrow_extent_crcs(struct bkey_s_c k,
458                                  struct bch_extent_crc_unpacked n)
459 {
460         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
461         struct bch_extent_crc_unpacked crc;
462         const union bch_extent_entry *i;
463
464         if (!n.csum_type)
465                 return false;
466
467         bkey_for_each_crc(k.k, ptrs, crc, i)
468                 if (can_narrow_crc(crc, n))
469                         return true;
470
471         return false;
472 }
473
474 /*
475  * We're writing another replica for this extent, so while we've got the data in
476  * memory we'll be computing a new checksum for the currently live data.
477  *
478  * If there are other replicas we aren't moving, and they are checksummed but
479  * not compressed, we can modify them to point to only the data that is
480  * currently live (so that readers won't have to bounce) while we've got the
481  * checksum we need:
482  */
483 bool bch2_bkey_narrow_crcs(struct bkey_i *k, struct bch_extent_crc_unpacked n)
484 {
485         struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
486         struct bch_extent_crc_unpacked u;
487         struct extent_ptr_decoded p;
488         union bch_extent_entry *i;
489         bool ret = false;
490
491         /* Find a checksum entry that covers only live data: */
492         if (!n.csum_type) {
493                 bkey_for_each_crc(&k->k, ptrs, u, i)
494                         if (!u.compression_type &&
495                             u.csum_type &&
496                             u.live_size == u.uncompressed_size) {
497                                 n = u;
498                                 goto found;
499                         }
500                 return false;
501         }
502 found:
503         BUG_ON(n.compression_type);
504         BUG_ON(n.offset);
505         BUG_ON(n.live_size != k->k.size);
506
507 restart_narrow_pointers:
508         ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
509
510         bkey_for_each_ptr_decode(&k->k, ptrs, p, i)
511                 if (can_narrow_crc(p.crc, n)) {
512                         bch2_bkey_drop_ptr(bkey_i_to_s(k), &i->ptr);
513                         p.ptr.offset += p.crc.offset;
514                         p.crc = n;
515                         bch2_extent_ptr_decoded_append(k, &p);
516                         ret = true;
517                         goto restart_narrow_pointers;
518                 }
519
520         return ret;
521 }
522
523 static void bch2_extent_crc_pack(union bch_extent_crc *dst,
524                                  struct bch_extent_crc_unpacked src,
525                                  enum bch_extent_entry_type type)
526 {
527 #define set_common_fields(_dst, _src)                                   \
528                 _dst.type               = 1 << type;                    \
529                 _dst.csum_type          = _src.csum_type,               \
530                 _dst.compression_type   = _src.compression_type,        \
531                 _dst._compressed_size   = _src.compressed_size - 1,     \
532                 _dst._uncompressed_size = _src.uncompressed_size - 1,   \
533                 _dst.offset             = _src.offset
534
535         switch (type) {
536         case BCH_EXTENT_ENTRY_crc32:
537                 set_common_fields(dst->crc32, src);
538                 dst->crc32.csum  = *((__le32 *) &src.csum.lo);
539                 break;
540         case BCH_EXTENT_ENTRY_crc64:
541                 set_common_fields(dst->crc64, src);
542                 dst->crc64.nonce        = src.nonce;
543                 dst->crc64.csum_lo      = src.csum.lo;
544                 dst->crc64.csum_hi      = *((__le16 *) &src.csum.hi);
545                 break;
546         case BCH_EXTENT_ENTRY_crc128:
547                 set_common_fields(dst->crc128, src);
548                 dst->crc128.nonce       = src.nonce;
549                 dst->crc128.csum        = src.csum;
550                 break;
551         default:
552                 BUG();
553         }
554 #undef set_common_fields
555 }
556
557 void bch2_extent_crc_append(struct bkey_i *k,
558                             struct bch_extent_crc_unpacked new)
559 {
560         struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
561         union bch_extent_crc *crc = (void *) ptrs.end;
562         enum bch_extent_entry_type type;
563
564         if (bch_crc_bytes[new.csum_type]        <= 4 &&
565             new.uncompressed_size - 1           <= CRC32_SIZE_MAX &&
566             new.nonce                           <= CRC32_NONCE_MAX)
567                 type = BCH_EXTENT_ENTRY_crc32;
568         else if (bch_crc_bytes[new.csum_type]   <= 10 &&
569                    new.uncompressed_size - 1    <= CRC64_SIZE_MAX &&
570                    new.nonce                    <= CRC64_NONCE_MAX)
571                 type = BCH_EXTENT_ENTRY_crc64;
572         else if (bch_crc_bytes[new.csum_type]   <= 16 &&
573                    new.uncompressed_size - 1    <= CRC128_SIZE_MAX &&
574                    new.nonce                    <= CRC128_NONCE_MAX)
575                 type = BCH_EXTENT_ENTRY_crc128;
576         else
577                 BUG();
578
579         bch2_extent_crc_pack(crc, new, type);
580
581         k->k.u64s += extent_entry_u64s(ptrs.end);
582
583         EBUG_ON(bkey_val_u64s(&k->k) > BKEY_EXTENT_VAL_U64s_MAX);
584 }
585
586 /* Generic code for keys with pointers: */
587
588 unsigned bch2_bkey_nr_ptrs(struct bkey_s_c k)
589 {
590         return bch2_bkey_devs(k).nr;
591 }
592
593 unsigned bch2_bkey_nr_ptrs_allocated(struct bkey_s_c k)
594 {
595         return k.k->type == KEY_TYPE_reservation
596                 ? bkey_s_c_to_reservation(k).v->nr_replicas
597                 : bch2_bkey_dirty_devs(k).nr;
598 }
599
600 unsigned bch2_bkey_nr_ptrs_fully_allocated(struct bkey_s_c k)
601 {
602         unsigned ret = 0;
603
604         if (k.k->type == KEY_TYPE_reservation) {
605                 ret = bkey_s_c_to_reservation(k).v->nr_replicas;
606         } else {
607                 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
608                 const union bch_extent_entry *entry;
609                 struct extent_ptr_decoded p;
610
611                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
612                         ret += !p.ptr.cached &&
613                                 p.crc.compression_type == BCH_COMPRESSION_TYPE_none;
614         }
615
616         return ret;
617 }
618
619 unsigned bch2_bkey_sectors_compressed(struct bkey_s_c k)
620 {
621         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
622         const union bch_extent_entry *entry;
623         struct extent_ptr_decoded p;
624         unsigned ret = 0;
625
626         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
627                 if (!p.ptr.cached &&
628                     p.crc.compression_type != BCH_COMPRESSION_TYPE_none)
629                         ret += p.crc.compressed_size;
630
631         return ret;
632 }
633
634 bool bch2_check_range_allocated(struct bch_fs *c, struct bpos pos, u64 size,
635                                 unsigned nr_replicas)
636 {
637         struct btree_trans trans;
638         struct btree_iter *iter;
639         struct bpos end = pos;
640         struct bkey_s_c k;
641         bool ret = true;
642         int err;
643
644         end.offset += size;
645
646         bch2_trans_init(&trans, c, 0, 0);
647
648         for_each_btree_key(&trans, iter, BTREE_ID_EXTENTS, pos,
649                            BTREE_ITER_SLOTS, k, err) {
650                 if (bkey_cmp(bkey_start_pos(k.k), end) >= 0)
651                         break;
652
653                 if (nr_replicas > bch2_bkey_nr_ptrs_fully_allocated(k)) {
654                         ret = false;
655                         break;
656                 }
657         }
658         bch2_trans_exit(&trans);
659
660         return ret;
661 }
662
663 static unsigned bch2_extent_ptr_durability(struct bch_fs *c,
664                                            struct extent_ptr_decoded p)
665 {
666         unsigned durability = 0;
667         struct bch_dev *ca;
668
669         if (p.ptr.cached)
670                 return 0;
671
672         ca = bch_dev_bkey_exists(c, p.ptr.dev);
673
674         if (ca->mi.state != BCH_MEMBER_STATE_FAILED)
675                 durability = max_t(unsigned, durability, ca->mi.durability);
676
677         if (p.has_ec) {
678                 struct stripe *s =
679                         genradix_ptr(&c->stripes[0], p.ec.idx);
680
681                 if (WARN_ON(!s))
682                         goto out;
683
684                 durability = max_t(unsigned, durability, s->nr_redundant);
685         }
686 out:
687         return durability;
688 }
689
690 unsigned bch2_bkey_durability(struct bch_fs *c, struct bkey_s_c k)
691 {
692         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
693         const union bch_extent_entry *entry;
694         struct extent_ptr_decoded p;
695         unsigned durability = 0;
696
697         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
698                 durability += bch2_extent_ptr_durability(c, p);
699
700         return durability;
701 }
702
703 void bch2_bkey_mark_replicas_cached(struct bch_fs *c, struct bkey_s k,
704                                     unsigned target,
705                                     unsigned nr_desired_replicas)
706 {
707         struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
708         union bch_extent_entry *entry;
709         struct extent_ptr_decoded p;
710         int extra = bch2_bkey_durability(c, k.s_c) - nr_desired_replicas;
711
712         if (target && extra > 0)
713                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
714                         int n = bch2_extent_ptr_durability(c, p);
715
716                         if (n && n <= extra &&
717                             !bch2_dev_in_target(c, p.ptr.dev, target)) {
718                                 entry->ptr.cached = true;
719                                 extra -= n;
720                         }
721                 }
722
723         if (extra > 0)
724                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
725                         int n = bch2_extent_ptr_durability(c, p);
726
727                         if (n && n <= extra) {
728                                 entry->ptr.cached = true;
729                                 extra -= n;
730                         }
731                 }
732 }
733
734 void bch2_bkey_append_ptr(struct bkey_i *k,
735                           struct bch_extent_ptr ptr)
736 {
737         EBUG_ON(bch2_bkey_has_device(bkey_i_to_s_c(k), ptr.dev));
738
739         switch (k->k.type) {
740         case KEY_TYPE_btree_ptr:
741         case KEY_TYPE_extent:
742                 EBUG_ON(bkey_val_u64s(&k->k) >= BKEY_EXTENT_VAL_U64s_MAX);
743
744                 ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
745
746                 memcpy((void *) &k->v + bkey_val_bytes(&k->k),
747                        &ptr,
748                        sizeof(ptr));
749                 k->u64s++;
750                 break;
751         default:
752                 BUG();
753         }
754 }
755
756 static inline void __extent_entry_insert(struct bkey_i *k,
757                                          union bch_extent_entry *dst,
758                                          union bch_extent_entry *new)
759 {
760         union bch_extent_entry *end = bkey_val_end(bkey_i_to_s(k));
761
762         memmove_u64s_up_small((u64 *) dst + extent_entry_u64s(new),
763                               dst, (u64 *) end - (u64 *) dst);
764         k->k.u64s += extent_entry_u64s(new);
765         memcpy_u64s_small(dst, new, extent_entry_u64s(new));
766 }
767
768 void bch2_extent_ptr_decoded_append(struct bkey_i *k,
769                                     struct extent_ptr_decoded *p)
770 {
771         struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
772         struct bch_extent_crc_unpacked crc =
773                 bch2_extent_crc_unpack(&k->k, NULL);
774         union bch_extent_entry *pos;
775
776         if (!bch2_crc_unpacked_cmp(crc, p->crc)) {
777                 pos = ptrs.start;
778                 goto found;
779         }
780
781         bkey_for_each_crc(&k->k, ptrs, crc, pos)
782                 if (!bch2_crc_unpacked_cmp(crc, p->crc)) {
783                         pos = extent_entry_next(pos);
784                         goto found;
785                 }
786
787         bch2_extent_crc_append(k, p->crc);
788         pos = bkey_val_end(bkey_i_to_s(k));
789 found:
790         p->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
791         __extent_entry_insert(k, pos, to_entry(&p->ptr));
792
793         if (p->has_ec) {
794                 p->ec.type = 1 << BCH_EXTENT_ENTRY_stripe_ptr;
795                 __extent_entry_insert(k, pos, to_entry(&p->ec));
796         }
797 }
798
799 static union bch_extent_entry *extent_entry_prev(struct bkey_ptrs ptrs,
800                                           union bch_extent_entry *entry)
801 {
802         union bch_extent_entry *i = ptrs.start;
803
804         if (i == entry)
805                 return NULL;
806
807         while (extent_entry_next(i) != entry)
808                 i = extent_entry_next(i);
809         return i;
810 }
811
812 union bch_extent_entry *bch2_bkey_drop_ptr(struct bkey_s k,
813                                            struct bch_extent_ptr *ptr)
814 {
815         struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
816         union bch_extent_entry *dst, *src, *prev;
817         bool drop_crc = true;
818
819         EBUG_ON(ptr < &ptrs.start->ptr ||
820                 ptr >= &ptrs.end->ptr);
821         EBUG_ON(ptr->type != 1 << BCH_EXTENT_ENTRY_ptr);
822
823         src = extent_entry_next(to_entry(ptr));
824         if (src != ptrs.end &&
825             !extent_entry_is_crc(src))
826                 drop_crc = false;
827
828         dst = to_entry(ptr);
829         while ((prev = extent_entry_prev(ptrs, dst))) {
830                 if (extent_entry_is_ptr(prev))
831                         break;
832
833                 if (extent_entry_is_crc(prev)) {
834                         if (drop_crc)
835                                 dst = prev;
836                         break;
837                 }
838
839                 dst = prev;
840         }
841
842         memmove_u64s_down(dst, src,
843                           (u64 *) ptrs.end - (u64 *) src);
844         k.k->u64s -= (u64 *) src - (u64 *) dst;
845
846         return dst;
847 }
848
849 void bch2_bkey_drop_device(struct bkey_s k, unsigned dev)
850 {
851         struct bch_extent_ptr *ptr;
852
853         bch2_bkey_drop_ptrs(k, ptr, ptr->dev == dev);
854 }
855
856 const struct bch_extent_ptr *
857 bch2_bkey_has_device(struct bkey_s_c k, unsigned dev)
858 {
859         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
860         const struct bch_extent_ptr *ptr;
861
862         bkey_for_each_ptr(ptrs, ptr)
863                 if (ptr->dev == dev)
864                         return ptr;
865
866         return NULL;
867 }
868
869 bool bch2_bkey_has_target(struct bch_fs *c, struct bkey_s_c k, unsigned target)
870 {
871         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
872         const struct bch_extent_ptr *ptr;
873
874         bkey_for_each_ptr(ptrs, ptr)
875                 if (bch2_dev_in_target(c, ptr->dev, target) &&
876                     (!ptr->cached ||
877                      !ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr)))
878                         return true;
879
880         return false;
881 }
882
883 bool bch2_bkey_matches_ptr(struct bch_fs *c, struct bkey_s_c k,
884                            struct bch_extent_ptr m, u64 offset)
885 {
886         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
887         const union bch_extent_entry *entry;
888         struct extent_ptr_decoded p;
889
890         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
891                 if (p.ptr.dev   == m.dev &&
892                     p.ptr.gen   == m.gen &&
893                     (s64) p.ptr.offset + p.crc.offset - bkey_start_offset(k.k) ==
894                     (s64) m.offset  - offset)
895                         return true;
896
897         return false;
898 }
899
900 /*
901  * bch_extent_normalize - clean up an extent, dropping stale pointers etc.
902  *
903  * Returns true if @k should be dropped entirely
904  *
905  * For existing keys, only called when btree nodes are being rewritten, not when
906  * they're merely being compacted/resorted in memory.
907  */
908 bool bch2_extent_normalize(struct bch_fs *c, struct bkey_s k)
909 {
910         struct bch_extent_ptr *ptr;
911
912         bch2_bkey_drop_ptrs(k, ptr,
913                 ptr->cached &&
914                 ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr));
915
916         /* will only happen if all pointers were cached: */
917         if (!bch2_bkey_nr_ptrs(k.s_c))
918                 k.k->type = KEY_TYPE_discard;
919
920         return bkey_whiteout(k.k);
921 }
922
923 void bch2_bkey_ptrs_to_text(struct printbuf *out, struct bch_fs *c,
924                             struct bkey_s_c k)
925 {
926         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
927         const union bch_extent_entry *entry;
928         struct bch_extent_crc_unpacked crc;
929         const struct bch_extent_ptr *ptr;
930         const struct bch_extent_stripe_ptr *ec;
931         struct bch_dev *ca;
932         bool first = true;
933
934         bkey_extent_entry_for_each(ptrs, entry) {
935                 if (!first)
936                         pr_buf(out, " ");
937
938                 switch (__extent_entry_type(entry)) {
939                 case BCH_EXTENT_ENTRY_ptr:
940                         ptr = entry_to_ptr(entry);
941                         ca = ptr->dev < c->sb.nr_devices && c->devs[ptr->dev]
942                                 ? bch_dev_bkey_exists(c, ptr->dev)
943                                 : NULL;
944
945                         pr_buf(out, "ptr: %u:%llu gen %u%s%s", ptr->dev,
946                                (u64) ptr->offset, ptr->gen,
947                                ptr->cached ? " cached" : "",
948                                ca && ptr_stale(ca, ptr)
949                                ? " stale" : "");
950                         break;
951                 case BCH_EXTENT_ENTRY_crc32:
952                 case BCH_EXTENT_ENTRY_crc64:
953                 case BCH_EXTENT_ENTRY_crc128:
954                         crc = bch2_extent_crc_unpack(k.k, entry_to_crc(entry));
955
956                         pr_buf(out, "crc: c_size %u size %u offset %u nonce %u csum %u compress %u",
957                                crc.compressed_size,
958                                crc.uncompressed_size,
959                                crc.offset, crc.nonce,
960                                crc.csum_type,
961                                crc.compression_type);
962                         break;
963                 case BCH_EXTENT_ENTRY_stripe_ptr:
964                         ec = &entry->stripe_ptr;
965
966                         pr_buf(out, "ec: idx %llu block %u",
967                                (u64) ec->idx, ec->block);
968                         break;
969                 default:
970                         pr_buf(out, "(invalid extent entry %.16llx)", *((u64 *) entry));
971                         return;
972                 }
973
974                 first = false;
975         }
976 }
977
978 static const char *extent_ptr_invalid(const struct bch_fs *c,
979                                       struct bkey_s_c k,
980                                       const struct bch_extent_ptr *ptr,
981                                       unsigned size_ondisk,
982                                       bool metadata)
983 {
984         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
985         const struct bch_extent_ptr *ptr2;
986         struct bch_dev *ca;
987
988         if (!bch2_dev_exists2(c, ptr->dev))
989                 return "pointer to invalid device";
990
991         ca = bch_dev_bkey_exists(c, ptr->dev);
992         if (!ca)
993                 return "pointer to invalid device";
994
995         bkey_for_each_ptr(ptrs, ptr2)
996                 if (ptr != ptr2 && ptr->dev == ptr2->dev)
997                         return "multiple pointers to same device";
998
999         if (ptr->offset + size_ondisk > bucket_to_sector(ca, ca->mi.nbuckets))
1000                 return "offset past end of device";
1001
1002         if (ptr->offset < bucket_to_sector(ca, ca->mi.first_bucket))
1003                 return "offset before first bucket";
1004
1005         if (bucket_remainder(ca, ptr->offset) +
1006             size_ondisk > ca->mi.bucket_size)
1007                 return "spans multiple buckets";
1008
1009         return NULL;
1010 }
1011
1012 const char *bch2_bkey_ptrs_invalid(const struct bch_fs *c, struct bkey_s_c k)
1013 {
1014         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1015         const union bch_extent_entry *entry;
1016         struct bch_extent_crc_unpacked crc;
1017         unsigned size_ondisk = k.k->size;
1018         const char *reason;
1019         unsigned nonce = UINT_MAX;
1020
1021         if (k.k->type == KEY_TYPE_btree_ptr)
1022                 size_ondisk = c->opts.btree_node_size;
1023
1024         bkey_extent_entry_for_each(ptrs, entry) {
1025                 if (__extent_entry_type(entry) >= BCH_EXTENT_ENTRY_MAX)
1026                         return "invalid extent entry type";
1027
1028                 if (k.k->type == KEY_TYPE_btree_ptr &&
1029                     !extent_entry_is_ptr(entry))
1030                         return "has non ptr field";
1031
1032                 switch (extent_entry_type(entry)) {
1033                 case BCH_EXTENT_ENTRY_ptr:
1034                         reason = extent_ptr_invalid(c, k, &entry->ptr,
1035                                                     size_ondisk, false);
1036                         if (reason)
1037                                 return reason;
1038                         break;
1039                 case BCH_EXTENT_ENTRY_crc32:
1040                 case BCH_EXTENT_ENTRY_crc64:
1041                 case BCH_EXTENT_ENTRY_crc128:
1042                         crc = bch2_extent_crc_unpack(k.k, entry_to_crc(entry));
1043
1044                         if (crc.offset + crc.live_size >
1045                             crc.uncompressed_size)
1046                                 return "checksum offset + key size > uncompressed size";
1047
1048                         size_ondisk = crc.compressed_size;
1049
1050                         if (!bch2_checksum_type_valid(c, crc.csum_type))
1051                                 return "invalid checksum type";
1052
1053                         if (crc.compression_type >= BCH_COMPRESSION_TYPE_NR)
1054                                 return "invalid compression type";
1055
1056                         if (bch2_csum_type_is_encryption(crc.csum_type)) {
1057                                 if (nonce == UINT_MAX)
1058                                         nonce = crc.offset + crc.nonce;
1059                                 else if (nonce != crc.offset + crc.nonce)
1060                                         return "incorrect nonce";
1061                         }
1062                         break;
1063                 case BCH_EXTENT_ENTRY_stripe_ptr:
1064                         break;
1065                 }
1066         }
1067
1068         return NULL;
1069 }
1070
1071 void bch2_ptr_swab(const struct bkey_format *f, struct bkey_packed *k)
1072 {
1073         union bch_extent_entry *entry;
1074         u64 *d = (u64 *) bkeyp_val(f, k);
1075         unsigned i;
1076
1077         for (i = 0; i < bkeyp_val_u64s(f, k); i++)
1078                 d[i] = swab64(d[i]);
1079
1080         for (entry = (union bch_extent_entry *) d;
1081              entry < (union bch_extent_entry *) (d + bkeyp_val_u64s(f, k));
1082              entry = extent_entry_next(entry)) {
1083                 switch (extent_entry_type(entry)) {
1084                 case BCH_EXTENT_ENTRY_ptr:
1085                         break;
1086                 case BCH_EXTENT_ENTRY_crc32:
1087                         entry->crc32.csum = swab32(entry->crc32.csum);
1088                         break;
1089                 case BCH_EXTENT_ENTRY_crc64:
1090                         entry->crc64.csum_hi = swab16(entry->crc64.csum_hi);
1091                         entry->crc64.csum_lo = swab64(entry->crc64.csum_lo);
1092                         break;
1093                 case BCH_EXTENT_ENTRY_crc128:
1094                         entry->crc128.csum.hi = (__force __le64)
1095                                 swab64((__force u64) entry->crc128.csum.hi);
1096                         entry->crc128.csum.lo = (__force __le64)
1097                                 swab64((__force u64) entry->crc128.csum.lo);
1098                         break;
1099                 case BCH_EXTENT_ENTRY_stripe_ptr:
1100                         break;
1101                 }
1102         }
1103 }
1104
1105 /* Generic extent code: */
1106
1107 int bch2_cut_front_s(struct bpos where, struct bkey_s k)
1108 {
1109         unsigned new_val_u64s = bkey_val_u64s(k.k);
1110         int val_u64s_delta;
1111         u64 sub;
1112
1113         if (bkey_cmp(where, bkey_start_pos(k.k)) <= 0)
1114                 return 0;
1115
1116         EBUG_ON(bkey_cmp(where, k.k->p) > 0);
1117
1118         sub = where.offset - bkey_start_offset(k.k);
1119
1120         k.k->size -= sub;
1121
1122         if (!k.k->size) {
1123                 k.k->type = KEY_TYPE_deleted;
1124                 new_val_u64s = 0;
1125         }
1126
1127         switch (k.k->type) {
1128         case KEY_TYPE_extent:
1129         case KEY_TYPE_reflink_v: {
1130                 struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
1131                 union bch_extent_entry *entry;
1132                 bool seen_crc = false;
1133
1134                 bkey_extent_entry_for_each(ptrs, entry) {
1135                         switch (extent_entry_type(entry)) {
1136                         case BCH_EXTENT_ENTRY_ptr:
1137                                 if (!seen_crc)
1138                                         entry->ptr.offset += sub;
1139                                 break;
1140                         case BCH_EXTENT_ENTRY_crc32:
1141                                 entry->crc32.offset += sub;
1142                                 break;
1143                         case BCH_EXTENT_ENTRY_crc64:
1144                                 entry->crc64.offset += sub;
1145                                 break;
1146                         case BCH_EXTENT_ENTRY_crc128:
1147                                 entry->crc128.offset += sub;
1148                                 break;
1149                         case BCH_EXTENT_ENTRY_stripe_ptr:
1150                                 break;
1151                         }
1152
1153                         if (extent_entry_is_crc(entry))
1154                                 seen_crc = true;
1155                 }
1156
1157                 break;
1158         }
1159         case KEY_TYPE_reflink_p: {
1160                 struct bkey_s_reflink_p p = bkey_s_to_reflink_p(k);
1161
1162                 le64_add_cpu(&p.v->idx, sub);
1163                 break;
1164         }
1165         case KEY_TYPE_inline_data: {
1166                 struct bkey_s_inline_data d = bkey_s_to_inline_data(k);
1167
1168                 sub = min_t(u64, sub << 9, bkey_val_bytes(d.k));
1169
1170                 memmove(d.v->data,
1171                         d.v->data + sub,
1172                         bkey_val_bytes(d.k) - sub);
1173
1174                 new_val_u64s -= sub >> 3;
1175                 break;
1176         }
1177         }
1178
1179         val_u64s_delta = bkey_val_u64s(k.k) - new_val_u64s;
1180         BUG_ON(val_u64s_delta < 0);
1181
1182         set_bkey_val_u64s(k.k, new_val_u64s);
1183         memset(bkey_val_end(k), 0, val_u64s_delta * sizeof(u64));
1184         return -val_u64s_delta;
1185 }
1186
1187 int bch2_cut_back_s(struct bpos where, struct bkey_s k)
1188 {
1189         unsigned new_val_u64s = bkey_val_u64s(k.k);
1190         int val_u64s_delta;
1191         u64 len = 0;
1192
1193         if (bkey_cmp(where, k.k->p) >= 0)
1194                 return 0;
1195
1196         EBUG_ON(bkey_cmp(where, bkey_start_pos(k.k)) < 0);
1197
1198         len = where.offset - bkey_start_offset(k.k);
1199
1200         k.k->p = where;
1201         k.k->size = len;
1202
1203         if (!len) {
1204                 k.k->type = KEY_TYPE_deleted;
1205                 new_val_u64s = 0;
1206         }
1207
1208         switch (k.k->type) {
1209         case KEY_TYPE_inline_data:
1210                 new_val_u64s = min(new_val_u64s, k.k->size << 6);
1211                 break;
1212         }
1213
1214         val_u64s_delta = bkey_val_u64s(k.k) - new_val_u64s;
1215         BUG_ON(val_u64s_delta < 0);
1216
1217         set_bkey_val_u64s(k.k, new_val_u64s);
1218         memset(bkey_val_end(k), 0, val_u64s_delta * sizeof(u64));
1219         return -val_u64s_delta;
1220 }