1ac4f0522043ea098527af26a070fdab25853520
[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_is_compressed(crc_l))
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 >
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 !crc_is_compressed(u) &&
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 (!crc_is_compressed(u) &&
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(crc_is_compressed(n));
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               <= 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        <= 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        <= 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 && !crc_is_compressed(p.crc);
613         }
614
615         return ret;
616 }
617
618 unsigned bch2_bkey_sectors_compressed(struct bkey_s_c k)
619 {
620         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
621         const union bch_extent_entry *entry;
622         struct extent_ptr_decoded p;
623         unsigned ret = 0;
624
625         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
626                 if (!p.ptr.cached && crc_is_compressed(p.crc))
627                         ret += p.crc.compressed_size;
628
629         return ret;
630 }
631
632 bool bch2_bkey_is_incompressible(struct bkey_s_c k)
633 {
634         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
635         const union bch_extent_entry *entry;
636         struct bch_extent_crc_unpacked crc;
637
638         bkey_for_each_crc(k.k, ptrs, crc, entry)
639                 if (crc.compression_type == BCH_COMPRESSION_TYPE_incompressible)
640                         return true;
641         return false;
642 }
643
644 bool bch2_check_range_allocated(struct bch_fs *c, struct bpos pos, u64 size,
645                                 unsigned nr_replicas)
646 {
647         struct btree_trans trans;
648         struct btree_iter *iter;
649         struct bpos end = pos;
650         struct bkey_s_c k;
651         bool ret = true;
652         int err;
653
654         end.offset += size;
655
656         bch2_trans_init(&trans, c, 0, 0);
657
658         for_each_btree_key(&trans, iter, BTREE_ID_EXTENTS, pos,
659                            BTREE_ITER_SLOTS, k, err) {
660                 if (bkey_cmp(bkey_start_pos(k.k), end) >= 0)
661                         break;
662
663                 if (nr_replicas > bch2_bkey_nr_ptrs_fully_allocated(k)) {
664                         ret = false;
665                         break;
666                 }
667         }
668         bch2_trans_exit(&trans);
669
670         return ret;
671 }
672
673 static unsigned bch2_extent_ptr_durability(struct bch_fs *c,
674                                            struct extent_ptr_decoded p)
675 {
676         unsigned durability = 0;
677         struct bch_dev *ca;
678
679         if (p.ptr.cached)
680                 return 0;
681
682         ca = bch_dev_bkey_exists(c, p.ptr.dev);
683
684         if (ca->mi.state != BCH_MEMBER_STATE_FAILED)
685                 durability = max_t(unsigned, durability, ca->mi.durability);
686
687         if (p.has_ec) {
688                 struct stripe *s =
689                         genradix_ptr(&c->stripes[0], p.ec.idx);
690
691                 if (WARN_ON(!s))
692                         goto out;
693
694                 durability = max_t(unsigned, durability, s->nr_redundant);
695         }
696 out:
697         return durability;
698 }
699
700 unsigned bch2_bkey_durability(struct bch_fs *c, struct bkey_s_c k)
701 {
702         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
703         const union bch_extent_entry *entry;
704         struct extent_ptr_decoded p;
705         unsigned durability = 0;
706
707         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
708                 durability += bch2_extent_ptr_durability(c, p);
709
710         return durability;
711 }
712
713 void bch2_bkey_mark_replicas_cached(struct bch_fs *c, struct bkey_s k,
714                                     unsigned target,
715                                     unsigned nr_desired_replicas)
716 {
717         struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
718         union bch_extent_entry *entry;
719         struct extent_ptr_decoded p;
720         int extra = bch2_bkey_durability(c, k.s_c) - nr_desired_replicas;
721
722         if (target && extra > 0)
723                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
724                         int n = bch2_extent_ptr_durability(c, p);
725
726                         if (n && n <= extra &&
727                             !bch2_dev_in_target(c, p.ptr.dev, target)) {
728                                 entry->ptr.cached = true;
729                                 extra -= n;
730                         }
731                 }
732
733         if (extra > 0)
734                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
735                         int n = bch2_extent_ptr_durability(c, p);
736
737                         if (n && n <= extra) {
738                                 entry->ptr.cached = true;
739                                 extra -= n;
740                         }
741                 }
742 }
743
744 void bch2_bkey_append_ptr(struct bkey_i *k,
745                           struct bch_extent_ptr ptr)
746 {
747         EBUG_ON(bch2_bkey_has_device(bkey_i_to_s_c(k), ptr.dev));
748
749         switch (k->k.type) {
750         case KEY_TYPE_btree_ptr:
751         case KEY_TYPE_btree_ptr_v2:
752         case KEY_TYPE_extent:
753                 EBUG_ON(bkey_val_u64s(&k->k) >= BKEY_EXTENT_VAL_U64s_MAX);
754
755                 ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
756
757                 memcpy((void *) &k->v + bkey_val_bytes(&k->k),
758                        &ptr,
759                        sizeof(ptr));
760                 k->u64s++;
761                 break;
762         default:
763                 BUG();
764         }
765 }
766
767 static inline void __extent_entry_insert(struct bkey_i *k,
768                                          union bch_extent_entry *dst,
769                                          union bch_extent_entry *new)
770 {
771         union bch_extent_entry *end = bkey_val_end(bkey_i_to_s(k));
772
773         memmove_u64s_up_small((u64 *) dst + extent_entry_u64s(new),
774                               dst, (u64 *) end - (u64 *) dst);
775         k->k.u64s += extent_entry_u64s(new);
776         memcpy_u64s_small(dst, new, extent_entry_u64s(new));
777 }
778
779 void bch2_extent_ptr_decoded_append(struct bkey_i *k,
780                                     struct extent_ptr_decoded *p)
781 {
782         struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
783         struct bch_extent_crc_unpacked crc =
784                 bch2_extent_crc_unpack(&k->k, NULL);
785         union bch_extent_entry *pos;
786
787         if (!bch2_crc_unpacked_cmp(crc, p->crc)) {
788                 pos = ptrs.start;
789                 goto found;
790         }
791
792         bkey_for_each_crc(&k->k, ptrs, crc, pos)
793                 if (!bch2_crc_unpacked_cmp(crc, p->crc)) {
794                         pos = extent_entry_next(pos);
795                         goto found;
796                 }
797
798         bch2_extent_crc_append(k, p->crc);
799         pos = bkey_val_end(bkey_i_to_s(k));
800 found:
801         p->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
802         __extent_entry_insert(k, pos, to_entry(&p->ptr));
803
804         if (p->has_ec) {
805                 p->ec.type = 1 << BCH_EXTENT_ENTRY_stripe_ptr;
806                 __extent_entry_insert(k, pos, to_entry(&p->ec));
807         }
808 }
809
810 static union bch_extent_entry *extent_entry_prev(struct bkey_ptrs ptrs,
811                                           union bch_extent_entry *entry)
812 {
813         union bch_extent_entry *i = ptrs.start;
814
815         if (i == entry)
816                 return NULL;
817
818         while (extent_entry_next(i) != entry)
819                 i = extent_entry_next(i);
820         return i;
821 }
822
823 union bch_extent_entry *bch2_bkey_drop_ptr(struct bkey_s k,
824                                            struct bch_extent_ptr *ptr)
825 {
826         struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
827         union bch_extent_entry *dst, *src, *prev;
828         bool drop_crc = true;
829
830         EBUG_ON(ptr < &ptrs.start->ptr ||
831                 ptr >= &ptrs.end->ptr);
832         EBUG_ON(ptr->type != 1 << BCH_EXTENT_ENTRY_ptr);
833
834         src = extent_entry_next(to_entry(ptr));
835         if (src != ptrs.end &&
836             !extent_entry_is_crc(src))
837                 drop_crc = false;
838
839         dst = to_entry(ptr);
840         while ((prev = extent_entry_prev(ptrs, dst))) {
841                 if (extent_entry_is_ptr(prev))
842                         break;
843
844                 if (extent_entry_is_crc(prev)) {
845                         if (drop_crc)
846                                 dst = prev;
847                         break;
848                 }
849
850                 dst = prev;
851         }
852
853         memmove_u64s_down(dst, src,
854                           (u64 *) ptrs.end - (u64 *) src);
855         k.k->u64s -= (u64 *) src - (u64 *) dst;
856
857         return dst;
858 }
859
860 void bch2_bkey_drop_device(struct bkey_s k, unsigned dev)
861 {
862         struct bch_extent_ptr *ptr;
863
864         bch2_bkey_drop_ptrs(k, ptr, ptr->dev == dev);
865 }
866
867 const struct bch_extent_ptr *
868 bch2_bkey_has_device(struct bkey_s_c k, unsigned dev)
869 {
870         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
871         const struct bch_extent_ptr *ptr;
872
873         bkey_for_each_ptr(ptrs, ptr)
874                 if (ptr->dev == dev)
875                         return ptr;
876
877         return NULL;
878 }
879
880 bool bch2_bkey_has_target(struct bch_fs *c, struct bkey_s_c k, unsigned target)
881 {
882         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
883         const struct bch_extent_ptr *ptr;
884
885         bkey_for_each_ptr(ptrs, ptr)
886                 if (bch2_dev_in_target(c, ptr->dev, target) &&
887                     (!ptr->cached ||
888                      !ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr)))
889                         return true;
890
891         return false;
892 }
893
894 bool bch2_bkey_matches_ptr(struct bch_fs *c, struct bkey_s_c k,
895                            struct bch_extent_ptr m, u64 offset)
896 {
897         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
898         const union bch_extent_entry *entry;
899         struct extent_ptr_decoded p;
900
901         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
902                 if (p.ptr.dev   == m.dev &&
903                     p.ptr.gen   == m.gen &&
904                     (s64) p.ptr.offset + p.crc.offset - bkey_start_offset(k.k) ==
905                     (s64) m.offset  - offset)
906                         return true;
907
908         return false;
909 }
910
911 /*
912  * bch_extent_normalize - clean up an extent, dropping stale pointers etc.
913  *
914  * Returns true if @k should be dropped entirely
915  *
916  * For existing keys, only called when btree nodes are being rewritten, not when
917  * they're merely being compacted/resorted in memory.
918  */
919 bool bch2_extent_normalize(struct bch_fs *c, struct bkey_s k)
920 {
921         struct bch_extent_ptr *ptr;
922
923         bch2_bkey_drop_ptrs(k, ptr,
924                 ptr->cached &&
925                 ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr));
926
927         /* will only happen if all pointers were cached: */
928         if (!bch2_bkey_nr_ptrs(k.s_c))
929                 k.k->type = KEY_TYPE_discard;
930
931         return bkey_whiteout(k.k);
932 }
933
934 void bch2_bkey_ptrs_to_text(struct printbuf *out, struct bch_fs *c,
935                             struct bkey_s_c k)
936 {
937         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
938         const union bch_extent_entry *entry;
939         struct bch_extent_crc_unpacked crc;
940         const struct bch_extent_ptr *ptr;
941         const struct bch_extent_stripe_ptr *ec;
942         struct bch_dev *ca;
943         bool first = true;
944
945         bkey_extent_entry_for_each(ptrs, entry) {
946                 if (!first)
947                         pr_buf(out, " ");
948
949                 switch (__extent_entry_type(entry)) {
950                 case BCH_EXTENT_ENTRY_ptr:
951                         ptr = entry_to_ptr(entry);
952                         ca = ptr->dev < c->sb.nr_devices && c->devs[ptr->dev]
953                                 ? bch_dev_bkey_exists(c, ptr->dev)
954                                 : NULL;
955
956                         pr_buf(out, "ptr: %u:%llu gen %u%s%s", ptr->dev,
957                                (u64) ptr->offset, ptr->gen,
958                                ptr->cached ? " cached" : "",
959                                ca && ptr_stale(ca, ptr)
960                                ? " stale" : "");
961                         break;
962                 case BCH_EXTENT_ENTRY_crc32:
963                 case BCH_EXTENT_ENTRY_crc64:
964                 case BCH_EXTENT_ENTRY_crc128:
965                         crc = bch2_extent_crc_unpack(k.k, entry_to_crc(entry));
966
967                         pr_buf(out, "crc: c_size %u size %u offset %u nonce %u csum %u compress %u",
968                                crc.compressed_size,
969                                crc.uncompressed_size,
970                                crc.offset, crc.nonce,
971                                crc.csum_type,
972                                crc.compression_type);
973                         break;
974                 case BCH_EXTENT_ENTRY_stripe_ptr:
975                         ec = &entry->stripe_ptr;
976
977                         pr_buf(out, "ec: idx %llu block %u",
978                                (u64) ec->idx, ec->block);
979                         break;
980                 default:
981                         pr_buf(out, "(invalid extent entry %.16llx)", *((u64 *) entry));
982                         return;
983                 }
984
985                 first = false;
986         }
987 }
988
989 static const char *extent_ptr_invalid(const struct bch_fs *c,
990                                       struct bkey_s_c k,
991                                       const struct bch_extent_ptr *ptr,
992                                       unsigned size_ondisk,
993                                       bool metadata)
994 {
995         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
996         const struct bch_extent_ptr *ptr2;
997         struct bch_dev *ca;
998
999         if (!bch2_dev_exists2(c, ptr->dev))
1000                 return "pointer to invalid device";
1001
1002         ca = bch_dev_bkey_exists(c, ptr->dev);
1003         if (!ca)
1004                 return "pointer to invalid device";
1005
1006         bkey_for_each_ptr(ptrs, ptr2)
1007                 if (ptr != ptr2 && ptr->dev == ptr2->dev)
1008                         return "multiple pointers to same device";
1009
1010         if (ptr->offset + size_ondisk > bucket_to_sector(ca, ca->mi.nbuckets))
1011                 return "offset past end of device";
1012
1013         if (ptr->offset < bucket_to_sector(ca, ca->mi.first_bucket))
1014                 return "offset before first bucket";
1015
1016         if (bucket_remainder(ca, ptr->offset) +
1017             size_ondisk > ca->mi.bucket_size)
1018                 return "spans multiple buckets";
1019
1020         return NULL;
1021 }
1022
1023 const char *bch2_bkey_ptrs_invalid(const struct bch_fs *c, struct bkey_s_c k)
1024 {
1025         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1026         const union bch_extent_entry *entry;
1027         struct bch_extent_crc_unpacked crc;
1028         unsigned size_ondisk = k.k->size;
1029         const char *reason;
1030         unsigned nonce = UINT_MAX;
1031
1032         if (k.k->type == KEY_TYPE_btree_ptr)
1033                 size_ondisk = c->opts.btree_node_size;
1034         if (k.k->type == KEY_TYPE_btree_ptr_v2)
1035                 size_ondisk = le16_to_cpu(bkey_s_c_to_btree_ptr_v2(k).v->sectors);
1036
1037         bkey_extent_entry_for_each(ptrs, entry) {
1038                 if (__extent_entry_type(entry) >= BCH_EXTENT_ENTRY_MAX)
1039                         return "invalid extent entry type";
1040
1041                 if (k.k->type == KEY_TYPE_btree_ptr &&
1042                     !extent_entry_is_ptr(entry))
1043                         return "has non ptr field";
1044
1045                 switch (extent_entry_type(entry)) {
1046                 case BCH_EXTENT_ENTRY_ptr:
1047                         reason = extent_ptr_invalid(c, k, &entry->ptr,
1048                                                     size_ondisk, false);
1049                         if (reason)
1050                                 return reason;
1051                         break;
1052                 case BCH_EXTENT_ENTRY_crc32:
1053                 case BCH_EXTENT_ENTRY_crc64:
1054                 case BCH_EXTENT_ENTRY_crc128:
1055                         crc = bch2_extent_crc_unpack(k.k, entry_to_crc(entry));
1056
1057                         if (crc.offset + crc.live_size >
1058                             crc.uncompressed_size)
1059                                 return "checksum offset + key size > uncompressed size";
1060
1061                         size_ondisk = crc.compressed_size;
1062
1063                         if (!bch2_checksum_type_valid(c, crc.csum_type))
1064                                 return "invalid checksum type";
1065
1066                         if (crc.compression_type >= BCH_COMPRESSION_TYPE_NR)
1067                                 return "invalid compression type";
1068
1069                         if (bch2_csum_type_is_encryption(crc.csum_type)) {
1070                                 if (nonce == UINT_MAX)
1071                                         nonce = crc.offset + crc.nonce;
1072                                 else if (nonce != crc.offset + crc.nonce)
1073                                         return "incorrect nonce";
1074                         }
1075                         break;
1076                 case BCH_EXTENT_ENTRY_stripe_ptr:
1077                         break;
1078                 }
1079         }
1080
1081         return NULL;
1082 }
1083
1084 void bch2_ptr_swab(struct bkey_s k)
1085 {
1086         struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
1087         union bch_extent_entry *entry;
1088         u64 *d;
1089
1090         for (d =  (u64 *) ptrs.start;
1091              d != (u64 *) ptrs.end;
1092              d++)
1093                 *d = swab64(*d);
1094
1095         for (entry = ptrs.start;
1096              entry < ptrs.end;
1097              entry = extent_entry_next(entry)) {
1098                 switch (extent_entry_type(entry)) {
1099                 case BCH_EXTENT_ENTRY_ptr:
1100                         break;
1101                 case BCH_EXTENT_ENTRY_crc32:
1102                         entry->crc32.csum = swab32(entry->crc32.csum);
1103                         break;
1104                 case BCH_EXTENT_ENTRY_crc64:
1105                         entry->crc64.csum_hi = swab16(entry->crc64.csum_hi);
1106                         entry->crc64.csum_lo = swab64(entry->crc64.csum_lo);
1107                         break;
1108                 case BCH_EXTENT_ENTRY_crc128:
1109                         entry->crc128.csum.hi = (__force __le64)
1110                                 swab64((__force u64) entry->crc128.csum.hi);
1111                         entry->crc128.csum.lo = (__force __le64)
1112                                 swab64((__force u64) entry->crc128.csum.lo);
1113                         break;
1114                 case BCH_EXTENT_ENTRY_stripe_ptr:
1115                         break;
1116                 }
1117         }
1118 }
1119
1120 /* Generic extent code: */
1121
1122 int bch2_cut_front_s(struct bpos where, struct bkey_s k)
1123 {
1124         unsigned new_val_u64s = bkey_val_u64s(k.k);
1125         int val_u64s_delta;
1126         u64 sub;
1127
1128         if (bkey_cmp(where, bkey_start_pos(k.k)) <= 0)
1129                 return 0;
1130
1131         EBUG_ON(bkey_cmp(where, k.k->p) > 0);
1132
1133         sub = where.offset - bkey_start_offset(k.k);
1134
1135         k.k->size -= sub;
1136
1137         if (!k.k->size) {
1138                 k.k->type = KEY_TYPE_deleted;
1139                 new_val_u64s = 0;
1140         }
1141
1142         switch (k.k->type) {
1143         case KEY_TYPE_extent:
1144         case KEY_TYPE_reflink_v: {
1145                 struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
1146                 union bch_extent_entry *entry;
1147                 bool seen_crc = false;
1148
1149                 bkey_extent_entry_for_each(ptrs, entry) {
1150                         switch (extent_entry_type(entry)) {
1151                         case BCH_EXTENT_ENTRY_ptr:
1152                                 if (!seen_crc)
1153                                         entry->ptr.offset += sub;
1154                                 break;
1155                         case BCH_EXTENT_ENTRY_crc32:
1156                                 entry->crc32.offset += sub;
1157                                 break;
1158                         case BCH_EXTENT_ENTRY_crc64:
1159                                 entry->crc64.offset += sub;
1160                                 break;
1161                         case BCH_EXTENT_ENTRY_crc128:
1162                                 entry->crc128.offset += sub;
1163                                 break;
1164                         case BCH_EXTENT_ENTRY_stripe_ptr:
1165                                 break;
1166                         }
1167
1168                         if (extent_entry_is_crc(entry))
1169                                 seen_crc = true;
1170                 }
1171
1172                 break;
1173         }
1174         case KEY_TYPE_reflink_p: {
1175                 struct bkey_s_reflink_p p = bkey_s_to_reflink_p(k);
1176
1177                 le64_add_cpu(&p.v->idx, sub);
1178                 break;
1179         }
1180         case KEY_TYPE_inline_data: {
1181                 struct bkey_s_inline_data d = bkey_s_to_inline_data(k);
1182
1183                 sub = min_t(u64, sub << 9, bkey_val_bytes(d.k));
1184
1185                 memmove(d.v->data,
1186                         d.v->data + sub,
1187                         bkey_val_bytes(d.k) - sub);
1188
1189                 new_val_u64s -= sub >> 3;
1190                 break;
1191         }
1192         }
1193
1194         val_u64s_delta = bkey_val_u64s(k.k) - new_val_u64s;
1195         BUG_ON(val_u64s_delta < 0);
1196
1197         set_bkey_val_u64s(k.k, new_val_u64s);
1198         memset(bkey_val_end(k), 0, val_u64s_delta * sizeof(u64));
1199         return -val_u64s_delta;
1200 }
1201
1202 int bch2_cut_back_s(struct bpos where, struct bkey_s k)
1203 {
1204         unsigned new_val_u64s = bkey_val_u64s(k.k);
1205         int val_u64s_delta;
1206         u64 len = 0;
1207
1208         if (bkey_cmp(where, k.k->p) >= 0)
1209                 return 0;
1210
1211         EBUG_ON(bkey_cmp(where, bkey_start_pos(k.k)) < 0);
1212
1213         len = where.offset - bkey_start_offset(k.k);
1214
1215         k.k->p = where;
1216         k.k->size = len;
1217
1218         if (!len) {
1219                 k.k->type = KEY_TYPE_deleted;
1220                 new_val_u64s = 0;
1221         }
1222
1223         switch (k.k->type) {
1224         case KEY_TYPE_inline_data:
1225                 new_val_u64s = min(new_val_u64s, k.k->size << 6);
1226                 break;
1227         }
1228
1229         val_u64s_delta = bkey_val_u64s(k.k) - new_val_u64s;
1230         BUG_ON(val_u64s_delta < 0);
1231
1232         set_bkey_val_u64s(k.k, new_val_u64s);
1233         memset(bkey_val_end(k), 0, val_u64s_delta * sizeof(u64));
1234         return -val_u64s_delta;
1235 }