xref: /linux/fs/bcachefs/extents.c (revision 3652117f854819a148ff0fbe4492587d3520b5e5)
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 "compress.h"
17 #include "debug.h"
18 #include "disk_groups.h"
19 #include "error.h"
20 #include "extents.h"
21 #include "inode.h"
22 #include "journal.h"
23 #include "replicas.h"
24 #include "super.h"
25 #include "super-io.h"
26 #include "trace.h"
27 #include "util.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 		/*
119 		 * Unwritten extent: no need to actually read, treat it as a
120 		 * hole and return 0s:
121 		 */
122 		if (p.ptr.unwritten)
123 			return 0;
124 
125 		ca = bch_dev_bkey_exists(c, p.ptr.dev);
126 
127 		/*
128 		 * If there are any dirty pointers it's an error if we can't
129 		 * read:
130 		 */
131 		if (!ret && !p.ptr.cached)
132 			ret = -EIO;
133 
134 		if (p.ptr.cached && ptr_stale(ca, &p.ptr))
135 			continue;
136 
137 		f = failed ? dev_io_failures(failed, p.ptr.dev) : NULL;
138 		if (f)
139 			p.idx = f->nr_failed < f->nr_retries
140 				? f->idx
141 				: f->idx + 1;
142 
143 		if (!p.idx &&
144 		    !bch2_dev_is_readable(ca))
145 			p.idx++;
146 
147 		if (bch2_force_reconstruct_read &&
148 		    !p.idx && p.has_ec)
149 			p.idx++;
150 
151 		if (p.idx >= (unsigned) p.has_ec + 1)
152 			continue;
153 
154 		if (ret > 0 && !ptr_better(c, p, *pick))
155 			continue;
156 
157 		*pick = p;
158 		ret = 1;
159 	}
160 
161 	return ret;
162 }
163 
164 /* KEY_TYPE_btree_ptr: */
165 
166 int bch2_btree_ptr_invalid(struct bch_fs *c, struct bkey_s_c k,
167 			   enum bkey_invalid_flags flags,
168 			   struct printbuf *err)
169 {
170 	int ret = 0;
171 
172 	bkey_fsck_err_on(bkey_val_u64s(k.k) > BCH_REPLICAS_MAX, c, err,
173 			 btree_ptr_val_too_big,
174 			 "value too big (%zu > %u)", bkey_val_u64s(k.k), BCH_REPLICAS_MAX);
175 
176 	ret = bch2_bkey_ptrs_invalid(c, k, flags, err);
177 fsck_err:
178 	return ret;
179 }
180 
181 void bch2_btree_ptr_to_text(struct printbuf *out, struct bch_fs *c,
182 			    struct bkey_s_c k)
183 {
184 	bch2_bkey_ptrs_to_text(out, c, k);
185 }
186 
187 int bch2_btree_ptr_v2_invalid(struct bch_fs *c, struct bkey_s_c k,
188 			      enum bkey_invalid_flags flags,
189 			      struct printbuf *err)
190 {
191 	int ret = 0;
192 
193 	bkey_fsck_err_on(bkey_val_u64s(k.k) > BKEY_BTREE_PTR_VAL_U64s_MAX, c, err,
194 			 btree_ptr_v2_val_too_big,
195 			 "value too big (%zu > %zu)",
196 			 bkey_val_u64s(k.k), BKEY_BTREE_PTR_VAL_U64s_MAX);
197 
198 	ret = bch2_bkey_ptrs_invalid(c, k, flags, err);
199 fsck_err:
200 	return ret;
201 }
202 
203 void bch2_btree_ptr_v2_to_text(struct printbuf *out, struct bch_fs *c,
204 			       struct bkey_s_c k)
205 {
206 	struct bkey_s_c_btree_ptr_v2 bp = bkey_s_c_to_btree_ptr_v2(k);
207 
208 	prt_printf(out, "seq %llx written %u min_key %s",
209 	       le64_to_cpu(bp.v->seq),
210 	       le16_to_cpu(bp.v->sectors_written),
211 	       BTREE_PTR_RANGE_UPDATED(bp.v) ? "R " : "");
212 
213 	bch2_bpos_to_text(out, bp.v->min_key);
214 	prt_printf(out, " ");
215 	bch2_bkey_ptrs_to_text(out, c, k);
216 }
217 
218 void bch2_btree_ptr_v2_compat(enum btree_id btree_id, unsigned version,
219 			      unsigned big_endian, int write,
220 			      struct bkey_s k)
221 {
222 	struct bkey_s_btree_ptr_v2 bp = bkey_s_to_btree_ptr_v2(k);
223 
224 	compat_bpos(0, btree_id, version, big_endian, write, &bp.v->min_key);
225 
226 	if (version < bcachefs_metadata_version_inode_btree_change &&
227 	    btree_id_is_extents(btree_id) &&
228 	    !bkey_eq(bp.v->min_key, POS_MIN))
229 		bp.v->min_key = write
230 			? bpos_nosnap_predecessor(bp.v->min_key)
231 			: bpos_nosnap_successor(bp.v->min_key);
232 }
233 
234 /* KEY_TYPE_extent: */
235 
236 bool bch2_extent_merge(struct bch_fs *c, struct bkey_s l, struct bkey_s_c r)
237 {
238 	struct bkey_ptrs   l_ptrs = bch2_bkey_ptrs(l);
239 	struct bkey_ptrs_c r_ptrs = bch2_bkey_ptrs_c(r);
240 	union bch_extent_entry *en_l;
241 	const union bch_extent_entry *en_r;
242 	struct extent_ptr_decoded lp, rp;
243 	bool use_right_ptr;
244 	struct bch_dev *ca;
245 
246 	en_l = l_ptrs.start;
247 	en_r = r_ptrs.start;
248 	while (en_l < l_ptrs.end && en_r < r_ptrs.end) {
249 		if (extent_entry_type(en_l) != extent_entry_type(en_r))
250 			return false;
251 
252 		en_l = extent_entry_next(en_l);
253 		en_r = extent_entry_next(en_r);
254 	}
255 
256 	if (en_l < l_ptrs.end || en_r < r_ptrs.end)
257 		return false;
258 
259 	en_l = l_ptrs.start;
260 	en_r = r_ptrs.start;
261 	lp.crc = bch2_extent_crc_unpack(l.k, NULL);
262 	rp.crc = bch2_extent_crc_unpack(r.k, NULL);
263 
264 	while (__bkey_ptr_next_decode(l.k, l_ptrs.end, lp, en_l) &&
265 	       __bkey_ptr_next_decode(r.k, r_ptrs.end, rp, en_r)) {
266 		if (lp.ptr.offset + lp.crc.offset + lp.crc.live_size !=
267 		    rp.ptr.offset + rp.crc.offset ||
268 		    lp.ptr.dev			!= rp.ptr.dev ||
269 		    lp.ptr.gen			!= rp.ptr.gen ||
270 		    lp.ptr.unwritten		!= rp.ptr.unwritten ||
271 		    lp.has_ec			!= rp.has_ec)
272 			return false;
273 
274 		/* Extents may not straddle buckets: */
275 		ca = bch_dev_bkey_exists(c, lp.ptr.dev);
276 		if (PTR_BUCKET_NR(ca, &lp.ptr) != PTR_BUCKET_NR(ca, &rp.ptr))
277 			return false;
278 
279 		if (lp.has_ec			!= rp.has_ec ||
280 		    (lp.has_ec &&
281 		     (lp.ec.block		!= rp.ec.block ||
282 		      lp.ec.redundancy		!= rp.ec.redundancy ||
283 		      lp.ec.idx			!= rp.ec.idx)))
284 			return false;
285 
286 		if (lp.crc.compression_type	!= rp.crc.compression_type ||
287 		    lp.crc.nonce		!= rp.crc.nonce)
288 			return false;
289 
290 		if (lp.crc.offset + lp.crc.live_size + rp.crc.live_size <=
291 		    lp.crc.uncompressed_size) {
292 			/* can use left extent's crc entry */
293 		} else if (lp.crc.live_size <= rp.crc.offset) {
294 			/* can use right extent's crc entry */
295 		} else {
296 			/* check if checksums can be merged: */
297 			if (lp.crc.csum_type		!= rp.crc.csum_type ||
298 			    lp.crc.nonce		!= rp.crc.nonce ||
299 			    crc_is_compressed(lp.crc) ||
300 			    !bch2_checksum_mergeable(lp.crc.csum_type))
301 				return false;
302 
303 			if (lp.crc.offset + lp.crc.live_size != lp.crc.compressed_size ||
304 			    rp.crc.offset)
305 				return false;
306 
307 			if (lp.crc.csum_type &&
308 			    lp.crc.uncompressed_size +
309 			    rp.crc.uncompressed_size > (c->opts.encoded_extent_max >> 9))
310 				return false;
311 		}
312 
313 		en_l = extent_entry_next(en_l);
314 		en_r = extent_entry_next(en_r);
315 	}
316 
317 	en_l = l_ptrs.start;
318 	en_r = r_ptrs.start;
319 	while (en_l < l_ptrs.end && en_r < r_ptrs.end) {
320 		if (extent_entry_is_crc(en_l)) {
321 			struct bch_extent_crc_unpacked crc_l = bch2_extent_crc_unpack(l.k, entry_to_crc(en_l));
322 			struct bch_extent_crc_unpacked crc_r = bch2_extent_crc_unpack(r.k, entry_to_crc(en_r));
323 
324 			if (crc_l.uncompressed_size + crc_r.uncompressed_size >
325 			    bch2_crc_field_size_max[extent_entry_type(en_l)])
326 				return false;
327 		}
328 
329 		en_l = extent_entry_next(en_l);
330 		en_r = extent_entry_next(en_r);
331 	}
332 
333 	use_right_ptr = false;
334 	en_l = l_ptrs.start;
335 	en_r = r_ptrs.start;
336 	while (en_l < l_ptrs.end) {
337 		if (extent_entry_type(en_l) == BCH_EXTENT_ENTRY_ptr &&
338 		    use_right_ptr)
339 			en_l->ptr = en_r->ptr;
340 
341 		if (extent_entry_is_crc(en_l)) {
342 			struct bch_extent_crc_unpacked crc_l =
343 				bch2_extent_crc_unpack(l.k, entry_to_crc(en_l));
344 			struct bch_extent_crc_unpacked crc_r =
345 				bch2_extent_crc_unpack(r.k, entry_to_crc(en_r));
346 
347 			use_right_ptr = false;
348 
349 			if (crc_l.offset + crc_l.live_size + crc_r.live_size <=
350 			    crc_l.uncompressed_size) {
351 				/* can use left extent's crc entry */
352 			} else if (crc_l.live_size <= crc_r.offset) {
353 				/* can use right extent's crc entry */
354 				crc_r.offset -= crc_l.live_size;
355 				bch2_extent_crc_pack(entry_to_crc(en_l), crc_r,
356 						     extent_entry_type(en_l));
357 				use_right_ptr = true;
358 			} else {
359 				crc_l.csum = bch2_checksum_merge(crc_l.csum_type,
360 								 crc_l.csum,
361 								 crc_r.csum,
362 								 crc_r.uncompressed_size << 9);
363 
364 				crc_l.uncompressed_size	+= crc_r.uncompressed_size;
365 				crc_l.compressed_size	+= crc_r.compressed_size;
366 				bch2_extent_crc_pack(entry_to_crc(en_l), crc_l,
367 						     extent_entry_type(en_l));
368 			}
369 		}
370 
371 		en_l = extent_entry_next(en_l);
372 		en_r = extent_entry_next(en_r);
373 	}
374 
375 	bch2_key_resize(l.k, l.k->size + r.k->size);
376 	return true;
377 }
378 
379 /* KEY_TYPE_reservation: */
380 
381 int bch2_reservation_invalid(struct bch_fs *c, struct bkey_s_c k,
382 			     enum bkey_invalid_flags flags,
383 			     struct printbuf *err)
384 {
385 	struct bkey_s_c_reservation r = bkey_s_c_to_reservation(k);
386 	int ret = 0;
387 
388 	bkey_fsck_err_on(!r.v->nr_replicas || r.v->nr_replicas > BCH_REPLICAS_MAX, c, err,
389 			 reservation_key_nr_replicas_invalid,
390 			 "invalid nr_replicas (%u)", r.v->nr_replicas);
391 fsck_err:
392 	return ret;
393 }
394 
395 void bch2_reservation_to_text(struct printbuf *out, struct bch_fs *c,
396 			      struct bkey_s_c k)
397 {
398 	struct bkey_s_c_reservation r = bkey_s_c_to_reservation(k);
399 
400 	prt_printf(out, "generation %u replicas %u",
401 	       le32_to_cpu(r.v->generation),
402 	       r.v->nr_replicas);
403 }
404 
405 bool bch2_reservation_merge(struct bch_fs *c, struct bkey_s _l, struct bkey_s_c _r)
406 {
407 	struct bkey_s_reservation l = bkey_s_to_reservation(_l);
408 	struct bkey_s_c_reservation r = bkey_s_c_to_reservation(_r);
409 
410 	if (l.v->generation != r.v->generation ||
411 	    l.v->nr_replicas != r.v->nr_replicas)
412 		return false;
413 
414 	bch2_key_resize(l.k, l.k->size + r.k->size);
415 	return true;
416 }
417 
418 /* Extent checksum entries: */
419 
420 /* returns true if not equal */
421 static inline bool bch2_crc_unpacked_cmp(struct bch_extent_crc_unpacked l,
422 					 struct bch_extent_crc_unpacked r)
423 {
424 	return (l.csum_type		!= r.csum_type ||
425 		l.compression_type	!= r.compression_type ||
426 		l.compressed_size	!= r.compressed_size ||
427 		l.uncompressed_size	!= r.uncompressed_size ||
428 		l.offset		!= r.offset ||
429 		l.live_size		!= r.live_size ||
430 		l.nonce			!= r.nonce ||
431 		bch2_crc_cmp(l.csum, r.csum));
432 }
433 
434 static inline bool can_narrow_crc(struct bch_extent_crc_unpacked u,
435 				  struct bch_extent_crc_unpacked n)
436 {
437 	return !crc_is_compressed(u) &&
438 		u.csum_type &&
439 		u.uncompressed_size > u.live_size &&
440 		bch2_csum_type_is_encryption(u.csum_type) ==
441 		bch2_csum_type_is_encryption(n.csum_type);
442 }
443 
444 bool bch2_can_narrow_extent_crcs(struct bkey_s_c k,
445 				 struct bch_extent_crc_unpacked n)
446 {
447 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
448 	struct bch_extent_crc_unpacked crc;
449 	const union bch_extent_entry *i;
450 
451 	if (!n.csum_type)
452 		return false;
453 
454 	bkey_for_each_crc(k.k, ptrs, crc, i)
455 		if (can_narrow_crc(crc, n))
456 			return true;
457 
458 	return false;
459 }
460 
461 /*
462  * We're writing another replica for this extent, so while we've got the data in
463  * memory we'll be computing a new checksum for the currently live data.
464  *
465  * If there are other replicas we aren't moving, and they are checksummed but
466  * not compressed, we can modify them to point to only the data that is
467  * currently live (so that readers won't have to bounce) while we've got the
468  * checksum we need:
469  */
470 bool bch2_bkey_narrow_crcs(struct bkey_i *k, struct bch_extent_crc_unpacked n)
471 {
472 	struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
473 	struct bch_extent_crc_unpacked u;
474 	struct extent_ptr_decoded p;
475 	union bch_extent_entry *i;
476 	bool ret = false;
477 
478 	/* Find a checksum entry that covers only live data: */
479 	if (!n.csum_type) {
480 		bkey_for_each_crc(&k->k, ptrs, u, i)
481 			if (!crc_is_compressed(u) &&
482 			    u.csum_type &&
483 			    u.live_size == u.uncompressed_size) {
484 				n = u;
485 				goto found;
486 			}
487 		return false;
488 	}
489 found:
490 	BUG_ON(crc_is_compressed(n));
491 	BUG_ON(n.offset);
492 	BUG_ON(n.live_size != k->k.size);
493 
494 restart_narrow_pointers:
495 	ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
496 
497 	bkey_for_each_ptr_decode(&k->k, ptrs, p, i)
498 		if (can_narrow_crc(p.crc, n)) {
499 			bch2_bkey_drop_ptr_noerror(bkey_i_to_s(k), &i->ptr);
500 			p.ptr.offset += p.crc.offset;
501 			p.crc = n;
502 			bch2_extent_ptr_decoded_append(k, &p);
503 			ret = true;
504 			goto restart_narrow_pointers;
505 		}
506 
507 	return ret;
508 }
509 
510 static void bch2_extent_crc_pack(union bch_extent_crc *dst,
511 				 struct bch_extent_crc_unpacked src,
512 				 enum bch_extent_entry_type type)
513 {
514 #define set_common_fields(_dst, _src)					\
515 		_dst.type		= 1 << type;			\
516 		_dst.csum_type		= _src.csum_type,		\
517 		_dst.compression_type	= _src.compression_type,	\
518 		_dst._compressed_size	= _src.compressed_size - 1,	\
519 		_dst._uncompressed_size	= _src.uncompressed_size - 1,	\
520 		_dst.offset		= _src.offset
521 
522 	switch (type) {
523 	case BCH_EXTENT_ENTRY_crc32:
524 		set_common_fields(dst->crc32, src);
525 		dst->crc32.csum		= (u32 __force) *((__le32 *) &src.csum.lo);
526 		break;
527 	case BCH_EXTENT_ENTRY_crc64:
528 		set_common_fields(dst->crc64, src);
529 		dst->crc64.nonce	= src.nonce;
530 		dst->crc64.csum_lo	= (u64 __force) src.csum.lo;
531 		dst->crc64.csum_hi	= (u64 __force) *((__le16 *) &src.csum.hi);
532 		break;
533 	case BCH_EXTENT_ENTRY_crc128:
534 		set_common_fields(dst->crc128, src);
535 		dst->crc128.nonce	= src.nonce;
536 		dst->crc128.csum	= src.csum;
537 		break;
538 	default:
539 		BUG();
540 	}
541 #undef set_common_fields
542 }
543 
544 void bch2_extent_crc_append(struct bkey_i *k,
545 			    struct bch_extent_crc_unpacked new)
546 {
547 	struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
548 	union bch_extent_crc *crc = (void *) ptrs.end;
549 	enum bch_extent_entry_type type;
550 
551 	if (bch_crc_bytes[new.csum_type]	<= 4 &&
552 	    new.uncompressed_size		<= CRC32_SIZE_MAX &&
553 	    new.nonce				<= CRC32_NONCE_MAX)
554 		type = BCH_EXTENT_ENTRY_crc32;
555 	else if (bch_crc_bytes[new.csum_type]	<= 10 &&
556 		   new.uncompressed_size	<= CRC64_SIZE_MAX &&
557 		   new.nonce			<= CRC64_NONCE_MAX)
558 		type = BCH_EXTENT_ENTRY_crc64;
559 	else if (bch_crc_bytes[new.csum_type]	<= 16 &&
560 		   new.uncompressed_size	<= CRC128_SIZE_MAX &&
561 		   new.nonce			<= CRC128_NONCE_MAX)
562 		type = BCH_EXTENT_ENTRY_crc128;
563 	else
564 		BUG();
565 
566 	bch2_extent_crc_pack(crc, new, type);
567 
568 	k->k.u64s += extent_entry_u64s(ptrs.end);
569 
570 	EBUG_ON(bkey_val_u64s(&k->k) > BKEY_EXTENT_VAL_U64s_MAX);
571 }
572 
573 /* Generic code for keys with pointers: */
574 
575 unsigned bch2_bkey_nr_ptrs(struct bkey_s_c k)
576 {
577 	return bch2_bkey_devs(k).nr;
578 }
579 
580 unsigned bch2_bkey_nr_ptrs_allocated(struct bkey_s_c k)
581 {
582 	return k.k->type == KEY_TYPE_reservation
583 		? bkey_s_c_to_reservation(k).v->nr_replicas
584 		: bch2_bkey_dirty_devs(k).nr;
585 }
586 
587 unsigned bch2_bkey_nr_ptrs_fully_allocated(struct bkey_s_c k)
588 {
589 	unsigned ret = 0;
590 
591 	if (k.k->type == KEY_TYPE_reservation) {
592 		ret = bkey_s_c_to_reservation(k).v->nr_replicas;
593 	} else {
594 		struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
595 		const union bch_extent_entry *entry;
596 		struct extent_ptr_decoded p;
597 
598 		bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
599 			ret += !p.ptr.cached && !crc_is_compressed(p.crc);
600 	}
601 
602 	return ret;
603 }
604 
605 unsigned bch2_bkey_sectors_compressed(struct bkey_s_c k)
606 {
607 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
608 	const union bch_extent_entry *entry;
609 	struct extent_ptr_decoded p;
610 	unsigned ret = 0;
611 
612 	bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
613 		if (!p.ptr.cached && crc_is_compressed(p.crc))
614 			ret += p.crc.compressed_size;
615 
616 	return ret;
617 }
618 
619 bool bch2_bkey_is_incompressible(struct bkey_s_c k)
620 {
621 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
622 	const union bch_extent_entry *entry;
623 	struct bch_extent_crc_unpacked crc;
624 
625 	bkey_for_each_crc(k.k, ptrs, crc, entry)
626 		if (crc.compression_type == BCH_COMPRESSION_TYPE_incompressible)
627 			return true;
628 	return false;
629 }
630 
631 unsigned bch2_bkey_replicas(struct bch_fs *c, struct bkey_s_c k)
632 {
633 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
634 	const union bch_extent_entry *entry;
635 	struct extent_ptr_decoded p = { 0 };
636 	unsigned replicas = 0;
637 
638 	bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
639 		if (p.ptr.cached)
640 			continue;
641 
642 		if (p.has_ec)
643 			replicas += p.ec.redundancy;
644 
645 		replicas++;
646 
647 	}
648 
649 	return replicas;
650 }
651 
652 unsigned bch2_extent_ptr_desired_durability(struct bch_fs *c, struct extent_ptr_decoded *p)
653 {
654 	struct bch_dev *ca;
655 
656 	if (p->ptr.cached)
657 		return 0;
658 
659 	ca = bch_dev_bkey_exists(c, p->ptr.dev);
660 
661 	return ca->mi.durability +
662 		(p->has_ec
663 		 ? p->ec.redundancy
664 		 : 0);
665 }
666 
667 unsigned bch2_extent_ptr_durability(struct bch_fs *c, struct extent_ptr_decoded *p)
668 {
669 	struct bch_dev *ca;
670 
671 	if (p->ptr.cached)
672 		return 0;
673 
674 	ca = bch_dev_bkey_exists(c, p->ptr.dev);
675 
676 	if (ca->mi.state == BCH_MEMBER_STATE_failed)
677 		return 0;
678 
679 	return ca->mi.durability +
680 		(p->has_ec
681 		 ? p->ec.redundancy
682 		 : 0);
683 }
684 
685 unsigned bch2_bkey_durability(struct bch_fs *c, struct bkey_s_c k)
686 {
687 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
688 	const union bch_extent_entry *entry;
689 	struct extent_ptr_decoded p;
690 	unsigned durability = 0;
691 
692 	bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
693 		durability += bch2_extent_ptr_durability(c, &p);
694 
695 	return durability;
696 }
697 
698 static unsigned bch2_bkey_durability_safe(struct bch_fs *c, struct bkey_s_c k)
699 {
700 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
701 	const union bch_extent_entry *entry;
702 	struct extent_ptr_decoded p;
703 	unsigned durability = 0;
704 
705 	bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
706 		if (p.ptr.dev < c->sb.nr_devices && c->devs[p.ptr.dev])
707 			durability += bch2_extent_ptr_durability(c, &p);
708 
709 	return durability;
710 }
711 
712 void bch2_bkey_extent_entry_drop(struct bkey_i *k, union bch_extent_entry *entry)
713 {
714 	union bch_extent_entry *end = bkey_val_end(bkey_i_to_s(k));
715 	union bch_extent_entry *next = extent_entry_next(entry);
716 
717 	memmove_u64s(entry, next, (u64 *) end - (u64 *) next);
718 	k->k.u64s -= extent_entry_u64s(entry);
719 }
720 
721 void bch2_extent_ptr_decoded_append(struct bkey_i *k,
722 				    struct extent_ptr_decoded *p)
723 {
724 	struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(k));
725 	struct bch_extent_crc_unpacked crc =
726 		bch2_extent_crc_unpack(&k->k, NULL);
727 	union bch_extent_entry *pos;
728 
729 	if (!bch2_crc_unpacked_cmp(crc, p->crc)) {
730 		pos = ptrs.start;
731 		goto found;
732 	}
733 
734 	bkey_for_each_crc(&k->k, ptrs, crc, pos)
735 		if (!bch2_crc_unpacked_cmp(crc, p->crc)) {
736 			pos = extent_entry_next(pos);
737 			goto found;
738 		}
739 
740 	bch2_extent_crc_append(k, p->crc);
741 	pos = bkey_val_end(bkey_i_to_s(k));
742 found:
743 	p->ptr.type = 1 << BCH_EXTENT_ENTRY_ptr;
744 	__extent_entry_insert(k, pos, to_entry(&p->ptr));
745 
746 	if (p->has_ec) {
747 		p->ec.type = 1 << BCH_EXTENT_ENTRY_stripe_ptr;
748 		__extent_entry_insert(k, pos, to_entry(&p->ec));
749 	}
750 }
751 
752 static union bch_extent_entry *extent_entry_prev(struct bkey_ptrs ptrs,
753 					  union bch_extent_entry *entry)
754 {
755 	union bch_extent_entry *i = ptrs.start;
756 
757 	if (i == entry)
758 		return NULL;
759 
760 	while (extent_entry_next(i) != entry)
761 		i = extent_entry_next(i);
762 	return i;
763 }
764 
765 /*
766  * Returns pointer to the next entry after the one being dropped:
767  */
768 union bch_extent_entry *bch2_bkey_drop_ptr_noerror(struct bkey_s k,
769 						   struct bch_extent_ptr *ptr)
770 {
771 	struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
772 	union bch_extent_entry *entry = to_entry(ptr), *next;
773 	union bch_extent_entry *ret = entry;
774 	bool drop_crc = true;
775 
776 	EBUG_ON(ptr < &ptrs.start->ptr ||
777 		ptr >= &ptrs.end->ptr);
778 	EBUG_ON(ptr->type != 1 << BCH_EXTENT_ENTRY_ptr);
779 
780 	for (next = extent_entry_next(entry);
781 	     next != ptrs.end;
782 	     next = extent_entry_next(next)) {
783 		if (extent_entry_is_crc(next)) {
784 			break;
785 		} else if (extent_entry_is_ptr(next)) {
786 			drop_crc = false;
787 			break;
788 		}
789 	}
790 
791 	extent_entry_drop(k, entry);
792 
793 	while ((entry = extent_entry_prev(ptrs, entry))) {
794 		if (extent_entry_is_ptr(entry))
795 			break;
796 
797 		if ((extent_entry_is_crc(entry) && drop_crc) ||
798 		    extent_entry_is_stripe_ptr(entry)) {
799 			ret = (void *) ret - extent_entry_bytes(entry);
800 			extent_entry_drop(k, entry);
801 		}
802 	}
803 
804 	return ret;
805 }
806 
807 union bch_extent_entry *bch2_bkey_drop_ptr(struct bkey_s k,
808 					   struct bch_extent_ptr *ptr)
809 {
810 	bool have_dirty = bch2_bkey_dirty_devs(k.s_c).nr;
811 	union bch_extent_entry *ret =
812 		bch2_bkey_drop_ptr_noerror(k, ptr);
813 
814 	/*
815 	 * If we deleted all the dirty pointers and there's still cached
816 	 * pointers, we could set the cached pointers to dirty if they're not
817 	 * stale - but to do that correctly we'd need to grab an open_bucket
818 	 * reference so that we don't race with bucket reuse:
819 	 */
820 	if (have_dirty &&
821 	    !bch2_bkey_dirty_devs(k.s_c).nr) {
822 		k.k->type = KEY_TYPE_error;
823 		set_bkey_val_u64s(k.k, 0);
824 		ret = NULL;
825 	} else if (!bch2_bkey_nr_ptrs(k.s_c)) {
826 		k.k->type = KEY_TYPE_deleted;
827 		set_bkey_val_u64s(k.k, 0);
828 		ret = NULL;
829 	}
830 
831 	return ret;
832 }
833 
834 void bch2_bkey_drop_device(struct bkey_s k, unsigned dev)
835 {
836 	struct bch_extent_ptr *ptr;
837 
838 	bch2_bkey_drop_ptrs(k, ptr, ptr->dev == dev);
839 }
840 
841 void bch2_bkey_drop_device_noerror(struct bkey_s k, unsigned dev)
842 {
843 	struct bch_extent_ptr *ptr = bch2_bkey_has_device(k, dev);
844 
845 	if (ptr)
846 		bch2_bkey_drop_ptr_noerror(k, ptr);
847 }
848 
849 const struct bch_extent_ptr *bch2_bkey_has_device_c(struct bkey_s_c k, unsigned dev)
850 {
851 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
852 	const struct bch_extent_ptr *ptr;
853 
854 	bkey_for_each_ptr(ptrs, ptr)
855 		if (ptr->dev == dev)
856 			return ptr;
857 
858 	return NULL;
859 }
860 
861 bool bch2_bkey_has_target(struct bch_fs *c, struct bkey_s_c k, unsigned target)
862 {
863 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
864 	const struct bch_extent_ptr *ptr;
865 
866 	bkey_for_each_ptr(ptrs, ptr)
867 		if (bch2_dev_in_target(c, ptr->dev, target) &&
868 		    (!ptr->cached ||
869 		     !ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr)))
870 			return true;
871 
872 	return false;
873 }
874 
875 bool bch2_bkey_matches_ptr(struct bch_fs *c, struct bkey_s_c k,
876 			   struct bch_extent_ptr m, u64 offset)
877 {
878 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
879 	const union bch_extent_entry *entry;
880 	struct extent_ptr_decoded p;
881 
882 	bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
883 		if (p.ptr.dev	== m.dev &&
884 		    p.ptr.gen	== m.gen &&
885 		    (s64) p.ptr.offset + p.crc.offset - bkey_start_offset(k.k) ==
886 		    (s64) m.offset  - offset)
887 			return true;
888 
889 	return false;
890 }
891 
892 /*
893  * Returns true if two extents refer to the same data:
894  */
895 bool bch2_extents_match(struct bkey_s_c k1, struct bkey_s_c k2)
896 {
897 	if (k1.k->type != k2.k->type)
898 		return false;
899 
900 	if (bkey_extent_is_direct_data(k1.k)) {
901 		struct bkey_ptrs_c ptrs1 = bch2_bkey_ptrs_c(k1);
902 		struct bkey_ptrs_c ptrs2 = bch2_bkey_ptrs_c(k2);
903 		const union bch_extent_entry *entry1, *entry2;
904 		struct extent_ptr_decoded p1, p2;
905 
906 		if (bkey_extent_is_unwritten(k1) != bkey_extent_is_unwritten(k2))
907 			return false;
908 
909 		bkey_for_each_ptr_decode(k1.k, ptrs1, p1, entry1)
910 			bkey_for_each_ptr_decode(k2.k, ptrs2, p2, entry2)
911 				if (p1.ptr.dev		== p2.ptr.dev &&
912 				    p1.ptr.gen		== p2.ptr.gen &&
913 				    (s64) p1.ptr.offset + p1.crc.offset - bkey_start_offset(k1.k) ==
914 				    (s64) p2.ptr.offset + p2.crc.offset - bkey_start_offset(k2.k))
915 					return true;
916 
917 		return false;
918 	} else {
919 		/* KEY_TYPE_deleted, etc. */
920 		return true;
921 	}
922 }
923 
924 struct bch_extent_ptr *
925 bch2_extent_has_ptr(struct bkey_s_c k1, struct extent_ptr_decoded p1, struct bkey_s k2)
926 {
927 	struct bkey_ptrs ptrs2 = bch2_bkey_ptrs(k2);
928 	union bch_extent_entry *entry2;
929 	struct extent_ptr_decoded p2;
930 
931 	bkey_for_each_ptr_decode(k2.k, ptrs2, p2, entry2)
932 		if (p1.ptr.dev		== p2.ptr.dev &&
933 		    p1.ptr.gen		== p2.ptr.gen &&
934 		    (s64) p1.ptr.offset + p1.crc.offset - bkey_start_offset(k1.k) ==
935 		    (s64) p2.ptr.offset + p2.crc.offset - bkey_start_offset(k2.k))
936 			return &entry2->ptr;
937 
938 	return NULL;
939 }
940 
941 void bch2_extent_ptr_set_cached(struct bkey_s k, struct bch_extent_ptr *ptr)
942 {
943 	struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
944 	union bch_extent_entry *entry;
945 	union bch_extent_entry *ec = NULL;
946 
947 	bkey_extent_entry_for_each(ptrs, entry) {
948 		if (&entry->ptr == ptr) {
949 			ptr->cached = true;
950 			if (ec)
951 				extent_entry_drop(k, ec);
952 			return;
953 		}
954 
955 		if (extent_entry_is_stripe_ptr(entry))
956 			ec = entry;
957 		else if (extent_entry_is_ptr(entry))
958 			ec = NULL;
959 	}
960 
961 	BUG();
962 }
963 
964 /*
965  * bch_extent_normalize - clean up an extent, dropping stale pointers etc.
966  *
967  * Returns true if @k should be dropped entirely
968  *
969  * For existing keys, only called when btree nodes are being rewritten, not when
970  * they're merely being compacted/resorted in memory.
971  */
972 bool bch2_extent_normalize(struct bch_fs *c, struct bkey_s k)
973 {
974 	struct bch_extent_ptr *ptr;
975 
976 	bch2_bkey_drop_ptrs(k, ptr,
977 		ptr->cached &&
978 		ptr_stale(bch_dev_bkey_exists(c, ptr->dev), ptr));
979 
980 	return bkey_deleted(k.k);
981 }
982 
983 void bch2_bkey_ptrs_to_text(struct printbuf *out, struct bch_fs *c,
984 			    struct bkey_s_c k)
985 {
986 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
987 	const union bch_extent_entry *entry;
988 	bool first = true;
989 
990 	if (c)
991 		prt_printf(out, "durability: %u ", bch2_bkey_durability_safe(c, k));
992 
993 	bkey_extent_entry_for_each(ptrs, entry) {
994 		if (!first)
995 			prt_printf(out, " ");
996 
997 		switch (__extent_entry_type(entry)) {
998 		case BCH_EXTENT_ENTRY_ptr: {
999 			const struct bch_extent_ptr *ptr = entry_to_ptr(entry);
1000 			struct bch_dev *ca = c && ptr->dev < c->sb.nr_devices && c->devs[ptr->dev]
1001 				? bch_dev_bkey_exists(c, ptr->dev)
1002 				: NULL;
1003 
1004 			if (!ca) {
1005 				prt_printf(out, "ptr: %u:%llu gen %u%s", ptr->dev,
1006 				       (u64) ptr->offset, ptr->gen,
1007 				       ptr->cached ? " cached" : "");
1008 			} else {
1009 				u32 offset;
1010 				u64 b = sector_to_bucket_and_offset(ca, ptr->offset, &offset);
1011 
1012 				prt_printf(out, "ptr: %u:%llu:%u gen %u",
1013 					   ptr->dev, b, offset, ptr->gen);
1014 				if (ptr->cached)
1015 					prt_str(out, " cached");
1016 				if (ptr->unwritten)
1017 					prt_str(out, " unwritten");
1018 				if (ca && ptr_stale(ca, ptr))
1019 					prt_printf(out, " stale");
1020 			}
1021 			break;
1022 		}
1023 		case BCH_EXTENT_ENTRY_crc32:
1024 		case BCH_EXTENT_ENTRY_crc64:
1025 		case BCH_EXTENT_ENTRY_crc128: {
1026 			struct bch_extent_crc_unpacked crc =
1027 				bch2_extent_crc_unpack(k.k, entry_to_crc(entry));
1028 
1029 			prt_printf(out, "crc: c_size %u size %u offset %u nonce %u csum %s compress %s",
1030 			       crc.compressed_size,
1031 			       crc.uncompressed_size,
1032 			       crc.offset, crc.nonce,
1033 			       bch2_csum_types[crc.csum_type],
1034 			       bch2_compression_types[crc.compression_type]);
1035 			break;
1036 		}
1037 		case BCH_EXTENT_ENTRY_stripe_ptr: {
1038 			const struct bch_extent_stripe_ptr *ec = &entry->stripe_ptr;
1039 
1040 			prt_printf(out, "ec: idx %llu block %u",
1041 			       (u64) ec->idx, ec->block);
1042 			break;
1043 		}
1044 		case BCH_EXTENT_ENTRY_rebalance: {
1045 			const struct bch_extent_rebalance *r = &entry->rebalance;
1046 
1047 			prt_str(out, "rebalance: target ");
1048 			if (c)
1049 				bch2_target_to_text(out, c, r->target);
1050 			else
1051 				prt_printf(out, "%u", r->target);
1052 			prt_str(out, " compression ");
1053 			bch2_compression_opt_to_text(out, r->compression);
1054 			break;
1055 		}
1056 		default:
1057 			prt_printf(out, "(invalid extent entry %.16llx)", *((u64 *) entry));
1058 			return;
1059 		}
1060 
1061 		first = false;
1062 	}
1063 }
1064 
1065 static int extent_ptr_invalid(struct bch_fs *c,
1066 			      struct bkey_s_c k,
1067 			      enum bkey_invalid_flags flags,
1068 			      const struct bch_extent_ptr *ptr,
1069 			      unsigned size_ondisk,
1070 			      bool metadata,
1071 			      struct printbuf *err)
1072 {
1073 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1074 	const struct bch_extent_ptr *ptr2;
1075 	u64 bucket;
1076 	u32 bucket_offset;
1077 	struct bch_dev *ca;
1078 	int ret = 0;
1079 
1080 	if (!bch2_dev_exists2(c, ptr->dev)) {
1081 		/*
1082 		 * If we're in the write path this key might have already been
1083 		 * overwritten, and we could be seeing a device that doesn't
1084 		 * exist anymore due to racing with device removal:
1085 		 */
1086 		if (flags & BKEY_INVALID_WRITE)
1087 			return 0;
1088 
1089 		bkey_fsck_err(c, err, ptr_to_invalid_device,
1090 			   "pointer to invalid device (%u)", ptr->dev);
1091 	}
1092 
1093 	ca = bch_dev_bkey_exists(c, ptr->dev);
1094 	bkey_for_each_ptr(ptrs, ptr2)
1095 		bkey_fsck_err_on(ptr != ptr2 && ptr->dev == ptr2->dev, c, err,
1096 				 ptr_to_duplicate_device,
1097 				 "multiple pointers to same device (%u)", ptr->dev);
1098 
1099 	bucket = sector_to_bucket_and_offset(ca, ptr->offset, &bucket_offset);
1100 
1101 	bkey_fsck_err_on(bucket >= ca->mi.nbuckets, c, err,
1102 			 ptr_after_last_bucket,
1103 			 "pointer past last bucket (%llu > %llu)", bucket, ca->mi.nbuckets);
1104 	bkey_fsck_err_on(ptr->offset < bucket_to_sector(ca, ca->mi.first_bucket), c, err,
1105 			 ptr_before_first_bucket,
1106 			 "pointer before first bucket (%llu < %u)", bucket, ca->mi.first_bucket);
1107 	bkey_fsck_err_on(bucket_offset + size_ondisk > ca->mi.bucket_size, c, err,
1108 			 ptr_spans_multiple_buckets,
1109 			 "pointer spans multiple buckets (%u + %u > %u)",
1110 		       bucket_offset, size_ondisk, ca->mi.bucket_size);
1111 fsck_err:
1112 	return ret;
1113 }
1114 
1115 int bch2_bkey_ptrs_invalid(struct bch_fs *c, struct bkey_s_c k,
1116 			   enum bkey_invalid_flags flags,
1117 			   struct printbuf *err)
1118 {
1119 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1120 	const union bch_extent_entry *entry;
1121 	struct bch_extent_crc_unpacked crc;
1122 	unsigned size_ondisk = k.k->size;
1123 	unsigned nonce = UINT_MAX;
1124 	unsigned nr_ptrs = 0;
1125 	bool have_written = false, have_unwritten = false, have_ec = false, crc_since_last_ptr = false;
1126 	int ret = 0;
1127 
1128 	if (bkey_is_btree_ptr(k.k))
1129 		size_ondisk = btree_sectors(c);
1130 
1131 	bkey_extent_entry_for_each(ptrs, entry) {
1132 		bkey_fsck_err_on(__extent_entry_type(entry) >= BCH_EXTENT_ENTRY_MAX, c, err,
1133 			extent_ptrs_invalid_entry,
1134 			"invalid extent entry type (got %u, max %u)",
1135 			__extent_entry_type(entry), BCH_EXTENT_ENTRY_MAX);
1136 
1137 		bkey_fsck_err_on(bkey_is_btree_ptr(k.k) &&
1138 				 !extent_entry_is_ptr(entry), c, err,
1139 				 btree_ptr_has_non_ptr,
1140 				 "has non ptr field");
1141 
1142 		switch (extent_entry_type(entry)) {
1143 		case BCH_EXTENT_ENTRY_ptr:
1144 			ret = extent_ptr_invalid(c, k, flags, &entry->ptr,
1145 						 size_ondisk, false, err);
1146 			if (ret)
1147 				return ret;
1148 
1149 			bkey_fsck_err_on(entry->ptr.cached && have_ec, c, err,
1150 					 ptr_cached_and_erasure_coded,
1151 					 "cached, erasure coded ptr");
1152 
1153 			if (!entry->ptr.unwritten)
1154 				have_written = true;
1155 			else
1156 				have_unwritten = true;
1157 
1158 			have_ec = false;
1159 			crc_since_last_ptr = false;
1160 			nr_ptrs++;
1161 			break;
1162 		case BCH_EXTENT_ENTRY_crc32:
1163 		case BCH_EXTENT_ENTRY_crc64:
1164 		case BCH_EXTENT_ENTRY_crc128:
1165 			crc = bch2_extent_crc_unpack(k.k, entry_to_crc(entry));
1166 
1167 			bkey_fsck_err_on(crc.offset + crc.live_size > crc.uncompressed_size, c, err,
1168 					 ptr_crc_uncompressed_size_too_small,
1169 					 "checksum offset + key size > uncompressed size");
1170 			bkey_fsck_err_on(!bch2_checksum_type_valid(c, crc.csum_type), c, err,
1171 					 ptr_crc_csum_type_unknown,
1172 					 "invalid checksum type");
1173 			bkey_fsck_err_on(crc.compression_type >= BCH_COMPRESSION_TYPE_NR, c, err,
1174 					 ptr_crc_compression_type_unknown,
1175 					 "invalid compression type");
1176 
1177 			if (bch2_csum_type_is_encryption(crc.csum_type)) {
1178 				if (nonce == UINT_MAX)
1179 					nonce = crc.offset + crc.nonce;
1180 				else if (nonce != crc.offset + crc.nonce)
1181 					bkey_fsck_err(c, err, ptr_crc_nonce_mismatch,
1182 						      "incorrect nonce");
1183 			}
1184 
1185 			bkey_fsck_err_on(crc_since_last_ptr, c, err,
1186 					 ptr_crc_redundant,
1187 					 "redundant crc entry");
1188 			crc_since_last_ptr = true;
1189 
1190 			bkey_fsck_err_on(crc_is_encoded(crc) &&
1191 					 (crc.uncompressed_size > c->opts.encoded_extent_max >> 9) &&
1192 					 (flags & (BKEY_INVALID_WRITE|BKEY_INVALID_COMMIT)), c, err,
1193 					 ptr_crc_uncompressed_size_too_big,
1194 					 "too large encoded extent");
1195 
1196 			size_ondisk = crc.compressed_size;
1197 			break;
1198 		case BCH_EXTENT_ENTRY_stripe_ptr:
1199 			bkey_fsck_err_on(have_ec, c, err,
1200 					 ptr_stripe_redundant,
1201 					 "redundant stripe entry");
1202 			have_ec = true;
1203 			break;
1204 		case BCH_EXTENT_ENTRY_rebalance: {
1205 			const struct bch_extent_rebalance *r = &entry->rebalance;
1206 
1207 			if (!bch2_compression_opt_valid(r->compression)) {
1208 				struct bch_compression_opt opt = __bch2_compression_decode(r->compression);
1209 				prt_printf(err, "invalid compression opt %u:%u",
1210 					   opt.type, opt.level);
1211 				return -BCH_ERR_invalid_bkey;
1212 			}
1213 			break;
1214 		}
1215 		}
1216 	}
1217 
1218 	bkey_fsck_err_on(!nr_ptrs, c, err,
1219 			 extent_ptrs_no_ptrs,
1220 			 "no ptrs");
1221 	bkey_fsck_err_on(nr_ptrs > BCH_BKEY_PTRS_MAX, c, err,
1222 			 extent_ptrs_too_many_ptrs,
1223 			 "too many ptrs: %u > %u", nr_ptrs, BCH_BKEY_PTRS_MAX);
1224 	bkey_fsck_err_on(have_written && have_unwritten, c, err,
1225 			 extent_ptrs_written_and_unwritten,
1226 			 "extent with unwritten and written ptrs");
1227 	bkey_fsck_err_on(k.k->type != KEY_TYPE_extent && have_unwritten, c, err,
1228 			 extent_ptrs_unwritten,
1229 			 "has unwritten ptrs");
1230 	bkey_fsck_err_on(crc_since_last_ptr, c, err,
1231 			 extent_ptrs_redundant_crc,
1232 			 "redundant crc entry");
1233 	bkey_fsck_err_on(have_ec, c, err,
1234 			 extent_ptrs_redundant_stripe,
1235 			 "redundant stripe entry");
1236 fsck_err:
1237 	return ret;
1238 }
1239 
1240 void bch2_ptr_swab(struct bkey_s k)
1241 {
1242 	struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
1243 	union bch_extent_entry *entry;
1244 	u64 *d;
1245 
1246 	for (d =  (u64 *) ptrs.start;
1247 	     d != (u64 *) ptrs.end;
1248 	     d++)
1249 		*d = swab64(*d);
1250 
1251 	for (entry = ptrs.start;
1252 	     entry < ptrs.end;
1253 	     entry = extent_entry_next(entry)) {
1254 		switch (extent_entry_type(entry)) {
1255 		case BCH_EXTENT_ENTRY_ptr:
1256 			break;
1257 		case BCH_EXTENT_ENTRY_crc32:
1258 			entry->crc32.csum = swab32(entry->crc32.csum);
1259 			break;
1260 		case BCH_EXTENT_ENTRY_crc64:
1261 			entry->crc64.csum_hi = swab16(entry->crc64.csum_hi);
1262 			entry->crc64.csum_lo = swab64(entry->crc64.csum_lo);
1263 			break;
1264 		case BCH_EXTENT_ENTRY_crc128:
1265 			entry->crc128.csum.hi = (__force __le64)
1266 				swab64((__force u64) entry->crc128.csum.hi);
1267 			entry->crc128.csum.lo = (__force __le64)
1268 				swab64((__force u64) entry->crc128.csum.lo);
1269 			break;
1270 		case BCH_EXTENT_ENTRY_stripe_ptr:
1271 			break;
1272 		case BCH_EXTENT_ENTRY_rebalance:
1273 			break;
1274 		}
1275 	}
1276 }
1277 
1278 const struct bch_extent_rebalance *bch2_bkey_rebalance_opts(struct bkey_s_c k)
1279 {
1280 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1281 	const union bch_extent_entry *entry;
1282 
1283 	bkey_extent_entry_for_each(ptrs, entry)
1284 		if (__extent_entry_type(entry) == BCH_EXTENT_ENTRY_rebalance)
1285 			return &entry->rebalance;
1286 
1287 	return NULL;
1288 }
1289 
1290 unsigned bch2_bkey_ptrs_need_rebalance(struct bch_fs *c, struct bkey_s_c k,
1291 				       unsigned target, unsigned compression)
1292 {
1293 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1294 	unsigned rewrite_ptrs = 0;
1295 
1296 	if (compression) {
1297 		unsigned compression_type = bch2_compression_opt_to_type(compression);
1298 		const union bch_extent_entry *entry;
1299 		struct extent_ptr_decoded p;
1300 		unsigned i = 0;
1301 
1302 		bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
1303 			if (p.crc.compression_type == BCH_COMPRESSION_TYPE_incompressible) {
1304 				rewrite_ptrs = 0;
1305 				goto incompressible;
1306 			}
1307 
1308 			if (!p.ptr.cached && p.crc.compression_type != compression_type)
1309 				rewrite_ptrs |= 1U << i;
1310 			i++;
1311 		}
1312 	}
1313 incompressible:
1314 	if (target && bch2_target_accepts_data(c, BCH_DATA_user, target)) {
1315 		const struct bch_extent_ptr *ptr;
1316 		unsigned i = 0;
1317 
1318 		bkey_for_each_ptr(ptrs, ptr) {
1319 			if (!ptr->cached && !bch2_dev_in_target(c, ptr->dev, target))
1320 				rewrite_ptrs |= 1U << i;
1321 			i++;
1322 		}
1323 	}
1324 
1325 	return rewrite_ptrs;
1326 }
1327 
1328 bool bch2_bkey_needs_rebalance(struct bch_fs *c, struct bkey_s_c k)
1329 {
1330 	const struct bch_extent_rebalance *r = bch2_bkey_rebalance_opts(k);
1331 
1332 	/*
1333 	 * If it's an indirect extent, we don't delete the rebalance entry when
1334 	 * done so that we know what options were applied - check if it still
1335 	 * needs work done:
1336 	 */
1337 	if (r &&
1338 	    k.k->type == KEY_TYPE_reflink_v &&
1339 	    !bch2_bkey_ptrs_need_rebalance(c, k, r->target, r->compression))
1340 		r = NULL;
1341 
1342 	return r != NULL;
1343 }
1344 
1345 int bch2_bkey_set_needs_rebalance(struct bch_fs *c, struct bkey_i *_k,
1346 				  unsigned target, unsigned compression)
1347 {
1348 	struct bkey_s k = bkey_i_to_s(_k);
1349 	struct bch_extent_rebalance *r;
1350 	bool needs_rebalance;
1351 
1352 	if (!bkey_extent_is_direct_data(k.k))
1353 		return 0;
1354 
1355 	/* get existing rebalance entry: */
1356 	r = (struct bch_extent_rebalance *) bch2_bkey_rebalance_opts(k.s_c);
1357 	if (r) {
1358 		if (k.k->type == KEY_TYPE_reflink_v) {
1359 			/*
1360 			 * indirect extents: existing options take precedence,
1361 			 * so that we don't move extents back and forth if
1362 			 * they're referenced by different inodes with different
1363 			 * options:
1364 			 */
1365 			if (r->target)
1366 				target = r->target;
1367 			if (r->compression)
1368 				compression = r->compression;
1369 		}
1370 
1371 		r->target	= target;
1372 		r->compression	= compression;
1373 	}
1374 
1375 	needs_rebalance = bch2_bkey_ptrs_need_rebalance(c, k.s_c, target, compression);
1376 
1377 	if (needs_rebalance && !r) {
1378 		union bch_extent_entry *new = bkey_val_end(k);
1379 
1380 		new->rebalance.type		= 1U << BCH_EXTENT_ENTRY_rebalance;
1381 		new->rebalance.compression	= compression;
1382 		new->rebalance.target		= target;
1383 		new->rebalance.unused		= 0;
1384 		k.k->u64s += extent_entry_u64s(new);
1385 	} else if (!needs_rebalance && r && k.k->type != KEY_TYPE_reflink_v) {
1386 		/*
1387 		 * For indirect extents, don't delete the rebalance entry when
1388 		 * we're finished so that we know we specifically moved it or
1389 		 * compressed it to its current location/compression type
1390 		 */
1391 		extent_entry_drop(k, (union bch_extent_entry *) r);
1392 	}
1393 
1394 	return 0;
1395 }
1396 
1397 /* Generic extent code: */
1398 
1399 int bch2_cut_front_s(struct bpos where, struct bkey_s k)
1400 {
1401 	unsigned new_val_u64s = bkey_val_u64s(k.k);
1402 	int val_u64s_delta;
1403 	u64 sub;
1404 
1405 	if (bkey_le(where, bkey_start_pos(k.k)))
1406 		return 0;
1407 
1408 	EBUG_ON(bkey_gt(where, k.k->p));
1409 
1410 	sub = where.offset - bkey_start_offset(k.k);
1411 
1412 	k.k->size -= sub;
1413 
1414 	if (!k.k->size) {
1415 		k.k->type = KEY_TYPE_deleted;
1416 		new_val_u64s = 0;
1417 	}
1418 
1419 	switch (k.k->type) {
1420 	case KEY_TYPE_extent:
1421 	case KEY_TYPE_reflink_v: {
1422 		struct bkey_ptrs ptrs = bch2_bkey_ptrs(k);
1423 		union bch_extent_entry *entry;
1424 		bool seen_crc = false;
1425 
1426 		bkey_extent_entry_for_each(ptrs, entry) {
1427 			switch (extent_entry_type(entry)) {
1428 			case BCH_EXTENT_ENTRY_ptr:
1429 				if (!seen_crc)
1430 					entry->ptr.offset += sub;
1431 				break;
1432 			case BCH_EXTENT_ENTRY_crc32:
1433 				entry->crc32.offset += sub;
1434 				break;
1435 			case BCH_EXTENT_ENTRY_crc64:
1436 				entry->crc64.offset += sub;
1437 				break;
1438 			case BCH_EXTENT_ENTRY_crc128:
1439 				entry->crc128.offset += sub;
1440 				break;
1441 			case BCH_EXTENT_ENTRY_stripe_ptr:
1442 				break;
1443 			case BCH_EXTENT_ENTRY_rebalance:
1444 				break;
1445 			}
1446 
1447 			if (extent_entry_is_crc(entry))
1448 				seen_crc = true;
1449 		}
1450 
1451 		break;
1452 	}
1453 	case KEY_TYPE_reflink_p: {
1454 		struct bkey_s_reflink_p p = bkey_s_to_reflink_p(k);
1455 
1456 		le64_add_cpu(&p.v->idx, sub);
1457 		break;
1458 	}
1459 	case KEY_TYPE_inline_data:
1460 	case KEY_TYPE_indirect_inline_data: {
1461 		void *p = bkey_inline_data_p(k);
1462 		unsigned bytes = bkey_inline_data_bytes(k.k);
1463 
1464 		sub = min_t(u64, sub << 9, bytes);
1465 
1466 		memmove(p, p + sub, bytes - sub);
1467 
1468 		new_val_u64s -= sub >> 3;
1469 		break;
1470 	}
1471 	}
1472 
1473 	val_u64s_delta = bkey_val_u64s(k.k) - new_val_u64s;
1474 	BUG_ON(val_u64s_delta < 0);
1475 
1476 	set_bkey_val_u64s(k.k, new_val_u64s);
1477 	memset(bkey_val_end(k), 0, val_u64s_delta * sizeof(u64));
1478 	return -val_u64s_delta;
1479 }
1480 
1481 int bch2_cut_back_s(struct bpos where, struct bkey_s k)
1482 {
1483 	unsigned new_val_u64s = bkey_val_u64s(k.k);
1484 	int val_u64s_delta;
1485 	u64 len = 0;
1486 
1487 	if (bkey_ge(where, k.k->p))
1488 		return 0;
1489 
1490 	EBUG_ON(bkey_lt(where, bkey_start_pos(k.k)));
1491 
1492 	len = where.offset - bkey_start_offset(k.k);
1493 
1494 	k.k->p.offset = where.offset;
1495 	k.k->size = len;
1496 
1497 	if (!len) {
1498 		k.k->type = KEY_TYPE_deleted;
1499 		new_val_u64s = 0;
1500 	}
1501 
1502 	switch (k.k->type) {
1503 	case KEY_TYPE_inline_data:
1504 	case KEY_TYPE_indirect_inline_data:
1505 		new_val_u64s = (bkey_inline_data_offset(k.k) +
1506 				min(bkey_inline_data_bytes(k.k), k.k->size << 9)) >> 3;
1507 		break;
1508 	}
1509 
1510 	val_u64s_delta = bkey_val_u64s(k.k) - new_val_u64s;
1511 	BUG_ON(val_u64s_delta < 0);
1512 
1513 	set_bkey_val_u64s(k.k, new_val_u64s);
1514 	memset(bkey_val_end(k), 0, val_u64s_delta * sizeof(u64));
1515 	return -val_u64s_delta;
1516 }
1517