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