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