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