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