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