xref: /linux/fs/bcachefs/snapshot.c (revision 24168c5e6dfbdd5b414f048f47f75d64533296ca)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "bkey_buf.h"
5 #include "btree_key_cache.h"
6 #include "btree_update.h"
7 #include "buckets.h"
8 #include "errcode.h"
9 #include "error.h"
10 #include "fs.h"
11 #include "recovery_passes.h"
12 #include "snapshot.h"
13 
14 #include <linux/random.h>
15 
16 /*
17  * Snapshot trees:
18  *
19  * Keys in BTREE_ID_snapshot_trees identify a whole tree of snapshot nodes; they
20  * exist to provide a stable identifier for the whole lifetime of a snapshot
21  * tree.
22  */
23 
24 void bch2_snapshot_tree_to_text(struct printbuf *out, struct bch_fs *c,
25 				struct bkey_s_c k)
26 {
27 	struct bkey_s_c_snapshot_tree t = bkey_s_c_to_snapshot_tree(k);
28 
29 	prt_printf(out, "subvol %u root snapshot %u",
30 		   le32_to_cpu(t.v->master_subvol),
31 		   le32_to_cpu(t.v->root_snapshot));
32 }
33 
34 int bch2_snapshot_tree_invalid(struct bch_fs *c, struct bkey_s_c k,
35 			       enum bch_validate_flags flags,
36 			       struct printbuf *err)
37 {
38 	int ret = 0;
39 
40 	bkey_fsck_err_on(bkey_gt(k.k->p, POS(0, U32_MAX)) ||
41 			 bkey_lt(k.k->p, POS(0, 1)), c, err,
42 			 snapshot_tree_pos_bad,
43 			 "bad pos");
44 fsck_err:
45 	return ret;
46 }
47 
48 int bch2_snapshot_tree_lookup(struct btree_trans *trans, u32 id,
49 			      struct bch_snapshot_tree *s)
50 {
51 	int ret = bch2_bkey_get_val_typed(trans, BTREE_ID_snapshot_trees, POS(0, id),
52 					  BTREE_ITER_with_updates, snapshot_tree, s);
53 
54 	if (bch2_err_matches(ret, ENOENT))
55 		ret = -BCH_ERR_ENOENT_snapshot_tree;
56 	return ret;
57 }
58 
59 struct bkey_i_snapshot_tree *
60 __bch2_snapshot_tree_create(struct btree_trans *trans)
61 {
62 	struct btree_iter iter;
63 	int ret = bch2_bkey_get_empty_slot(trans, &iter,
64 			BTREE_ID_snapshot_trees, POS(0, U32_MAX));
65 	struct bkey_i_snapshot_tree *s_t;
66 
67 	if (ret == -BCH_ERR_ENOSPC_btree_slot)
68 		ret = -BCH_ERR_ENOSPC_snapshot_tree;
69 	if (ret)
70 		return ERR_PTR(ret);
71 
72 	s_t = bch2_bkey_alloc(trans, &iter, 0, snapshot_tree);
73 	ret = PTR_ERR_OR_ZERO(s_t);
74 	bch2_trans_iter_exit(trans, &iter);
75 	return ret ? ERR_PTR(ret) : s_t;
76 }
77 
78 static int bch2_snapshot_tree_create(struct btree_trans *trans,
79 				u32 root_id, u32 subvol_id, u32 *tree_id)
80 {
81 	struct bkey_i_snapshot_tree *n_tree =
82 		__bch2_snapshot_tree_create(trans);
83 
84 	if (IS_ERR(n_tree))
85 		return PTR_ERR(n_tree);
86 
87 	n_tree->v.master_subvol	= cpu_to_le32(subvol_id);
88 	n_tree->v.root_snapshot	= cpu_to_le32(root_id);
89 	*tree_id = n_tree->k.p.offset;
90 	return 0;
91 }
92 
93 /* Snapshot nodes: */
94 
95 static bool __bch2_snapshot_is_ancestor_early(struct snapshot_table *t, u32 id, u32 ancestor)
96 {
97 	while (id && id < ancestor) {
98 		const struct snapshot_t *s = __snapshot_t(t, id);
99 		id = s ? s->parent : 0;
100 	}
101 	return id == ancestor;
102 }
103 
104 static bool bch2_snapshot_is_ancestor_early(struct bch_fs *c, u32 id, u32 ancestor)
105 {
106 	rcu_read_lock();
107 	bool ret = __bch2_snapshot_is_ancestor_early(rcu_dereference(c->snapshots), id, ancestor);
108 	rcu_read_unlock();
109 
110 	return ret;
111 }
112 
113 static inline u32 get_ancestor_below(struct snapshot_table *t, u32 id, u32 ancestor)
114 {
115 	const struct snapshot_t *s = __snapshot_t(t, id);
116 	if (!s)
117 		return 0;
118 
119 	if (s->skip[2] <= ancestor)
120 		return s->skip[2];
121 	if (s->skip[1] <= ancestor)
122 		return s->skip[1];
123 	if (s->skip[0] <= ancestor)
124 		return s->skip[0];
125 	return s->parent;
126 }
127 
128 static bool test_ancestor_bitmap(struct snapshot_table *t, u32 id, u32 ancestor)
129 {
130 	const struct snapshot_t *s = __snapshot_t(t, id);
131 	if (!s)
132 		return false;
133 
134 	return test_bit(ancestor - id - 1, s->is_ancestor);
135 }
136 
137 bool __bch2_snapshot_is_ancestor(struct bch_fs *c, u32 id, u32 ancestor)
138 {
139 	bool ret;
140 
141 	rcu_read_lock();
142 	struct snapshot_table *t = rcu_dereference(c->snapshots);
143 
144 	if (unlikely(c->recovery_pass_done < BCH_RECOVERY_PASS_check_snapshots)) {
145 		ret = __bch2_snapshot_is_ancestor_early(t, id, ancestor);
146 		goto out;
147 	}
148 
149 	while (id && id < ancestor - IS_ANCESTOR_BITMAP)
150 		id = get_ancestor_below(t, id, ancestor);
151 
152 	ret = id && id < ancestor
153 		? test_ancestor_bitmap(t, id, ancestor)
154 		: id == ancestor;
155 
156 	EBUG_ON(ret != __bch2_snapshot_is_ancestor_early(t, id, ancestor));
157 out:
158 	rcu_read_unlock();
159 
160 	return ret;
161 }
162 
163 static noinline struct snapshot_t *__snapshot_t_mut(struct bch_fs *c, u32 id)
164 {
165 	size_t idx = U32_MAX - id;
166 	struct snapshot_table *new, *old;
167 
168 	size_t new_bytes = kmalloc_size_roundup(struct_size(new, s, idx + 1));
169 	size_t new_size = (new_bytes - sizeof(*new)) / sizeof(new->s[0]);
170 
171 	new = kvzalloc(new_bytes, GFP_KERNEL);
172 	if (!new)
173 		return NULL;
174 
175 	new->nr = new_size;
176 
177 	old = rcu_dereference_protected(c->snapshots, true);
178 	if (old)
179 		memcpy(new->s, old->s, sizeof(old->s[0]) * old->nr);
180 
181 	rcu_assign_pointer(c->snapshots, new);
182 	kvfree_rcu(old, rcu);
183 
184 	return &rcu_dereference_protected(c->snapshots,
185 				lockdep_is_held(&c->snapshot_table_lock))->s[idx];
186 }
187 
188 static inline struct snapshot_t *snapshot_t_mut(struct bch_fs *c, u32 id)
189 {
190 	size_t idx = U32_MAX - id;
191 	struct snapshot_table *table =
192 		rcu_dereference_protected(c->snapshots,
193 				lockdep_is_held(&c->snapshot_table_lock));
194 
195 	lockdep_assert_held(&c->snapshot_table_lock);
196 
197 	if (likely(table && idx < table->nr))
198 		return &table->s[idx];
199 
200 	return __snapshot_t_mut(c, id);
201 }
202 
203 void bch2_snapshot_to_text(struct printbuf *out, struct bch_fs *c,
204 			   struct bkey_s_c k)
205 {
206 	struct bkey_s_c_snapshot s = bkey_s_c_to_snapshot(k);
207 
208 	prt_printf(out, "is_subvol %llu deleted %llu parent %10u children %10u %10u subvol %u tree %u",
209 	       BCH_SNAPSHOT_SUBVOL(s.v),
210 	       BCH_SNAPSHOT_DELETED(s.v),
211 	       le32_to_cpu(s.v->parent),
212 	       le32_to_cpu(s.v->children[0]),
213 	       le32_to_cpu(s.v->children[1]),
214 	       le32_to_cpu(s.v->subvol),
215 	       le32_to_cpu(s.v->tree));
216 
217 	if (bkey_val_bytes(k.k) > offsetof(struct bch_snapshot, depth))
218 		prt_printf(out, " depth %u skiplist %u %u %u",
219 			   le32_to_cpu(s.v->depth),
220 			   le32_to_cpu(s.v->skip[0]),
221 			   le32_to_cpu(s.v->skip[1]),
222 			   le32_to_cpu(s.v->skip[2]));
223 }
224 
225 int bch2_snapshot_invalid(struct bch_fs *c, struct bkey_s_c k,
226 			  enum bch_validate_flags flags,
227 			  struct printbuf *err)
228 {
229 	struct bkey_s_c_snapshot s;
230 	u32 i, id;
231 	int ret = 0;
232 
233 	bkey_fsck_err_on(bkey_gt(k.k->p, POS(0, U32_MAX)) ||
234 			 bkey_lt(k.k->p, POS(0, 1)), c, err,
235 			 snapshot_pos_bad,
236 			 "bad pos");
237 
238 	s = bkey_s_c_to_snapshot(k);
239 
240 	id = le32_to_cpu(s.v->parent);
241 	bkey_fsck_err_on(id && id <= k.k->p.offset, c, err,
242 			 snapshot_parent_bad,
243 			 "bad parent node (%u <= %llu)",
244 			 id, k.k->p.offset);
245 
246 	bkey_fsck_err_on(le32_to_cpu(s.v->children[0]) < le32_to_cpu(s.v->children[1]), c, err,
247 			 snapshot_children_not_normalized,
248 			 "children not normalized");
249 
250 	bkey_fsck_err_on(s.v->children[0] && s.v->children[0] == s.v->children[1], c, err,
251 			 snapshot_child_duplicate,
252 			 "duplicate child nodes");
253 
254 	for (i = 0; i < 2; i++) {
255 		id = le32_to_cpu(s.v->children[i]);
256 
257 		bkey_fsck_err_on(id >= k.k->p.offset, c, err,
258 				 snapshot_child_bad,
259 				 "bad child node (%u >= %llu)",
260 				 id, k.k->p.offset);
261 	}
262 
263 	if (bkey_val_bytes(k.k) > offsetof(struct bch_snapshot, skip)) {
264 		bkey_fsck_err_on(le32_to_cpu(s.v->skip[0]) > le32_to_cpu(s.v->skip[1]) ||
265 				 le32_to_cpu(s.v->skip[1]) > le32_to_cpu(s.v->skip[2]), c, err,
266 				 snapshot_skiplist_not_normalized,
267 				 "skiplist not normalized");
268 
269 		for (i = 0; i < ARRAY_SIZE(s.v->skip); i++) {
270 			id = le32_to_cpu(s.v->skip[i]);
271 
272 			bkey_fsck_err_on(id && id < le32_to_cpu(s.v->parent), c, err,
273 					 snapshot_skiplist_bad,
274 					 "bad skiplist node %u", id);
275 		}
276 	}
277 fsck_err:
278 	return ret;
279 }
280 
281 static void __set_is_ancestor_bitmap(struct bch_fs *c, u32 id)
282 {
283 	struct snapshot_t *t = snapshot_t_mut(c, id);
284 	u32 parent = id;
285 
286 	while ((parent = bch2_snapshot_parent_early(c, parent)) &&
287 	       parent - id - 1 < IS_ANCESTOR_BITMAP)
288 		__set_bit(parent - id - 1, t->is_ancestor);
289 }
290 
291 static void set_is_ancestor_bitmap(struct bch_fs *c, u32 id)
292 {
293 	mutex_lock(&c->snapshot_table_lock);
294 	__set_is_ancestor_bitmap(c, id);
295 	mutex_unlock(&c->snapshot_table_lock);
296 }
297 
298 static int __bch2_mark_snapshot(struct btree_trans *trans,
299 		       enum btree_id btree, unsigned level,
300 		       struct bkey_s_c old, struct bkey_s_c new,
301 		       enum btree_iter_update_trigger_flags flags)
302 {
303 	struct bch_fs *c = trans->c;
304 	struct snapshot_t *t;
305 	u32 id = new.k->p.offset;
306 	int ret = 0;
307 
308 	mutex_lock(&c->snapshot_table_lock);
309 
310 	t = snapshot_t_mut(c, id);
311 	if (!t) {
312 		ret = -BCH_ERR_ENOMEM_mark_snapshot;
313 		goto err;
314 	}
315 
316 	if (new.k->type == KEY_TYPE_snapshot) {
317 		struct bkey_s_c_snapshot s = bkey_s_c_to_snapshot(new);
318 
319 		t->parent	= le32_to_cpu(s.v->parent);
320 		t->children[0]	= le32_to_cpu(s.v->children[0]);
321 		t->children[1]	= le32_to_cpu(s.v->children[1]);
322 		t->subvol	= BCH_SNAPSHOT_SUBVOL(s.v) ? le32_to_cpu(s.v->subvol) : 0;
323 		t->tree		= le32_to_cpu(s.v->tree);
324 
325 		if (bkey_val_bytes(s.k) > offsetof(struct bch_snapshot, depth)) {
326 			t->depth	= le32_to_cpu(s.v->depth);
327 			t->skip[0]	= le32_to_cpu(s.v->skip[0]);
328 			t->skip[1]	= le32_to_cpu(s.v->skip[1]);
329 			t->skip[2]	= le32_to_cpu(s.v->skip[2]);
330 		} else {
331 			t->depth	= 0;
332 			t->skip[0]	= 0;
333 			t->skip[1]	= 0;
334 			t->skip[2]	= 0;
335 		}
336 
337 		__set_is_ancestor_bitmap(c, id);
338 
339 		if (BCH_SNAPSHOT_DELETED(s.v)) {
340 			set_bit(BCH_FS_need_delete_dead_snapshots, &c->flags);
341 			if (c->curr_recovery_pass > BCH_RECOVERY_PASS_delete_dead_snapshots)
342 				bch2_delete_dead_snapshots_async(c);
343 		}
344 	} else {
345 		memset(t, 0, sizeof(*t));
346 	}
347 err:
348 	mutex_unlock(&c->snapshot_table_lock);
349 	return ret;
350 }
351 
352 int bch2_mark_snapshot(struct btree_trans *trans,
353 		       enum btree_id btree, unsigned level,
354 		       struct bkey_s_c old, struct bkey_s new,
355 		       enum btree_iter_update_trigger_flags flags)
356 {
357 	return __bch2_mark_snapshot(trans, btree, level, old, new.s_c, flags);
358 }
359 
360 int bch2_snapshot_lookup(struct btree_trans *trans, u32 id,
361 			 struct bch_snapshot *s)
362 {
363 	return bch2_bkey_get_val_typed(trans, BTREE_ID_snapshots, POS(0, id),
364 				       BTREE_ITER_with_updates, snapshot, s);
365 }
366 
367 static int bch2_snapshot_live(struct btree_trans *trans, u32 id)
368 {
369 	struct bch_snapshot v;
370 	int ret;
371 
372 	if (!id)
373 		return 0;
374 
375 	ret = bch2_snapshot_lookup(trans, id, &v);
376 	if (bch2_err_matches(ret, ENOENT))
377 		bch_err(trans->c, "snapshot node %u not found", id);
378 	if (ret)
379 		return ret;
380 
381 	return !BCH_SNAPSHOT_DELETED(&v);
382 }
383 
384 /*
385  * If @k is a snapshot with just one live child, it's part of a linear chain,
386  * which we consider to be an equivalence class: and then after snapshot
387  * deletion cleanup, there should only be a single key at a given position in
388  * this equivalence class.
389  *
390  * This sets the equivalence class of @k to be the child's equivalence class, if
391  * it's part of such a linear chain: this correctly sets equivalence classes on
392  * startup if we run leaf to root (i.e. in natural key order).
393  */
394 static int bch2_snapshot_set_equiv(struct btree_trans *trans, struct bkey_s_c k)
395 {
396 	struct bch_fs *c = trans->c;
397 	unsigned i, nr_live = 0, live_idx = 0;
398 	struct bkey_s_c_snapshot snap;
399 	u32 id = k.k->p.offset, child[2];
400 
401 	if (k.k->type != KEY_TYPE_snapshot)
402 		return 0;
403 
404 	snap = bkey_s_c_to_snapshot(k);
405 
406 	child[0] = le32_to_cpu(snap.v->children[0]);
407 	child[1] = le32_to_cpu(snap.v->children[1]);
408 
409 	for (i = 0; i < 2; i++) {
410 		int ret = bch2_snapshot_live(trans, child[i]);
411 
412 		if (ret < 0)
413 			return ret;
414 
415 		if (ret)
416 			live_idx = i;
417 		nr_live += ret;
418 	}
419 
420 	mutex_lock(&c->snapshot_table_lock);
421 
422 	snapshot_t_mut(c, id)->equiv = nr_live == 1
423 		? snapshot_t_mut(c, child[live_idx])->equiv
424 		: id;
425 
426 	mutex_unlock(&c->snapshot_table_lock);
427 
428 	return 0;
429 }
430 
431 /* fsck: */
432 
433 static u32 bch2_snapshot_child(struct bch_fs *c, u32 id, unsigned child)
434 {
435 	return snapshot_t(c, id)->children[child];
436 }
437 
438 static u32 bch2_snapshot_left_child(struct bch_fs *c, u32 id)
439 {
440 	return bch2_snapshot_child(c, id, 0);
441 }
442 
443 static u32 bch2_snapshot_right_child(struct bch_fs *c, u32 id)
444 {
445 	return bch2_snapshot_child(c, id, 1);
446 }
447 
448 static u32 bch2_snapshot_tree_next(struct bch_fs *c, u32 id)
449 {
450 	u32 n, parent;
451 
452 	n = bch2_snapshot_left_child(c, id);
453 	if (n)
454 		return n;
455 
456 	while ((parent = bch2_snapshot_parent(c, id))) {
457 		n = bch2_snapshot_right_child(c, parent);
458 		if (n && n != id)
459 			return n;
460 		id = parent;
461 	}
462 
463 	return 0;
464 }
465 
466 static u32 bch2_snapshot_tree_oldest_subvol(struct bch_fs *c, u32 snapshot_root)
467 {
468 	u32 id = snapshot_root;
469 	u32 subvol = 0, s;
470 
471 	while (id) {
472 		s = snapshot_t(c, id)->subvol;
473 
474 		if (s && (!subvol || s < subvol))
475 			subvol = s;
476 
477 		id = bch2_snapshot_tree_next(c, id);
478 	}
479 
480 	return subvol;
481 }
482 
483 static int bch2_snapshot_tree_master_subvol(struct btree_trans *trans,
484 					    u32 snapshot_root, u32 *subvol_id)
485 {
486 	struct bch_fs *c = trans->c;
487 	struct btree_iter iter;
488 	struct bkey_s_c k;
489 	bool found = false;
490 	int ret;
491 
492 	for_each_btree_key_norestart(trans, iter, BTREE_ID_subvolumes, POS_MIN,
493 				     0, k, ret) {
494 		if (k.k->type != KEY_TYPE_subvolume)
495 			continue;
496 
497 		struct bkey_s_c_subvolume s = bkey_s_c_to_subvolume(k);
498 		if (!bch2_snapshot_is_ancestor(c, le32_to_cpu(s.v->snapshot), snapshot_root))
499 			continue;
500 		if (!BCH_SUBVOLUME_SNAP(s.v)) {
501 			*subvol_id = s.k->p.offset;
502 			found = true;
503 			break;
504 		}
505 	}
506 
507 	bch2_trans_iter_exit(trans, &iter);
508 
509 	if (!ret && !found) {
510 		struct bkey_i_subvolume *u;
511 
512 		*subvol_id = bch2_snapshot_tree_oldest_subvol(c, snapshot_root);
513 
514 		u = bch2_bkey_get_mut_typed(trans, &iter,
515 					    BTREE_ID_subvolumes, POS(0, *subvol_id),
516 					    0, subvolume);
517 		ret = PTR_ERR_OR_ZERO(u);
518 		if (ret)
519 			return ret;
520 
521 		SET_BCH_SUBVOLUME_SNAP(&u->v, false);
522 	}
523 
524 	return ret;
525 }
526 
527 static int check_snapshot_tree(struct btree_trans *trans,
528 			       struct btree_iter *iter,
529 			       struct bkey_s_c k)
530 {
531 	struct bch_fs *c = trans->c;
532 	struct bkey_s_c_snapshot_tree st;
533 	struct bch_snapshot s;
534 	struct bch_subvolume subvol;
535 	struct printbuf buf = PRINTBUF;
536 	u32 root_id;
537 	int ret;
538 
539 	if (k.k->type != KEY_TYPE_snapshot_tree)
540 		return 0;
541 
542 	st = bkey_s_c_to_snapshot_tree(k);
543 	root_id = le32_to_cpu(st.v->root_snapshot);
544 
545 	ret = bch2_snapshot_lookup(trans, root_id, &s);
546 	if (ret && !bch2_err_matches(ret, ENOENT))
547 		goto err;
548 
549 	if (fsck_err_on(ret ||
550 			root_id != bch2_snapshot_root(c, root_id) ||
551 			st.k->p.offset != le32_to_cpu(s.tree),
552 			c, snapshot_tree_to_missing_snapshot,
553 			"snapshot tree points to missing/incorrect snapshot:\n  %s",
554 			(bch2_bkey_val_to_text(&buf, c, st.s_c), buf.buf))) {
555 		ret = bch2_btree_delete_at(trans, iter, 0);
556 		goto err;
557 	}
558 
559 	ret = bch2_subvolume_get(trans, le32_to_cpu(st.v->master_subvol),
560 				 false, 0, &subvol);
561 	if (ret && !bch2_err_matches(ret, ENOENT))
562 		goto err;
563 
564 	if (fsck_err_on(ret,
565 			c, snapshot_tree_to_missing_subvol,
566 			"snapshot tree points to missing subvolume:\n  %s",
567 			(printbuf_reset(&buf),
568 			 bch2_bkey_val_to_text(&buf, c, st.s_c), buf.buf)) ||
569 	    fsck_err_on(!bch2_snapshot_is_ancestor(c,
570 						le32_to_cpu(subvol.snapshot),
571 						root_id),
572 			c, snapshot_tree_to_wrong_subvol,
573 			"snapshot tree points to subvolume that does not point to snapshot in this tree:\n  %s",
574 			(printbuf_reset(&buf),
575 			 bch2_bkey_val_to_text(&buf, c, st.s_c), buf.buf)) ||
576 	    fsck_err_on(BCH_SUBVOLUME_SNAP(&subvol),
577 			c, snapshot_tree_to_snapshot_subvol,
578 			"snapshot tree points to snapshot subvolume:\n  %s",
579 			(printbuf_reset(&buf),
580 			 bch2_bkey_val_to_text(&buf, c, st.s_c), buf.buf))) {
581 		struct bkey_i_snapshot_tree *u;
582 		u32 subvol_id;
583 
584 		ret = bch2_snapshot_tree_master_subvol(trans, root_id, &subvol_id);
585 		bch_err_fn(c, ret);
586 
587 		if (bch2_err_matches(ret, ENOENT)) { /* nothing to be done here */
588 			ret = 0;
589 			goto err;
590 		}
591 
592 		if (ret)
593 			goto err;
594 
595 		u = bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot_tree);
596 		ret = PTR_ERR_OR_ZERO(u);
597 		if (ret)
598 			goto err;
599 
600 		u->v.master_subvol = cpu_to_le32(subvol_id);
601 		st = snapshot_tree_i_to_s_c(u);
602 	}
603 err:
604 fsck_err:
605 	printbuf_exit(&buf);
606 	return ret;
607 }
608 
609 /*
610  * For each snapshot_tree, make sure it points to the root of a snapshot tree
611  * and that snapshot entry points back to it, or delete it.
612  *
613  * And, make sure it points to a subvolume within that snapshot tree, or correct
614  * it to point to the oldest subvolume within that snapshot tree.
615  */
616 int bch2_check_snapshot_trees(struct bch_fs *c)
617 {
618 	int ret = bch2_trans_run(c,
619 		for_each_btree_key_commit(trans, iter,
620 			BTREE_ID_snapshot_trees, POS_MIN,
621 			BTREE_ITER_prefetch, k,
622 			NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
623 		check_snapshot_tree(trans, &iter, k)));
624 	bch_err_fn(c, ret);
625 	return ret;
626 }
627 
628 /*
629  * Look up snapshot tree for @tree_id and find root,
630  * make sure @snap_id is a descendent:
631  */
632 static int snapshot_tree_ptr_good(struct btree_trans *trans,
633 				  u32 snap_id, u32 tree_id)
634 {
635 	struct bch_snapshot_tree s_t;
636 	int ret = bch2_snapshot_tree_lookup(trans, tree_id, &s_t);
637 
638 	if (bch2_err_matches(ret, ENOENT))
639 		return 0;
640 	if (ret)
641 		return ret;
642 
643 	return bch2_snapshot_is_ancestor_early(trans->c, snap_id, le32_to_cpu(s_t.root_snapshot));
644 }
645 
646 u32 bch2_snapshot_skiplist_get(struct bch_fs *c, u32 id)
647 {
648 	const struct snapshot_t *s;
649 
650 	if (!id)
651 		return 0;
652 
653 	rcu_read_lock();
654 	s = snapshot_t(c, id);
655 	if (s->parent)
656 		id = bch2_snapshot_nth_parent(c, id, get_random_u32_below(s->depth));
657 	rcu_read_unlock();
658 
659 	return id;
660 }
661 
662 static int snapshot_skiplist_good(struct btree_trans *trans, u32 id, struct bch_snapshot s)
663 {
664 	unsigned i;
665 
666 	for (i = 0; i < 3; i++)
667 		if (!s.parent) {
668 			if (s.skip[i])
669 				return false;
670 		} else {
671 			if (!bch2_snapshot_is_ancestor_early(trans->c, id, le32_to_cpu(s.skip[i])))
672 				return false;
673 		}
674 
675 	return true;
676 }
677 
678 /*
679  * snapshot_tree pointer was incorrect: look up root snapshot node, make sure
680  * its snapshot_tree pointer is correct (allocate new one if necessary), then
681  * update this node's pointer to root node's pointer:
682  */
683 static int snapshot_tree_ptr_repair(struct btree_trans *trans,
684 				    struct btree_iter *iter,
685 				    struct bkey_s_c k,
686 				    struct bch_snapshot *s)
687 {
688 	struct bch_fs *c = trans->c;
689 	struct btree_iter root_iter;
690 	struct bch_snapshot_tree s_t;
691 	struct bkey_s_c_snapshot root;
692 	struct bkey_i_snapshot *u;
693 	u32 root_id = bch2_snapshot_root(c, k.k->p.offset), tree_id;
694 	int ret;
695 
696 	root = bch2_bkey_get_iter_typed(trans, &root_iter,
697 			       BTREE_ID_snapshots, POS(0, root_id),
698 			       BTREE_ITER_with_updates, snapshot);
699 	ret = bkey_err(root);
700 	if (ret)
701 		goto err;
702 
703 	tree_id = le32_to_cpu(root.v->tree);
704 
705 	ret = bch2_snapshot_tree_lookup(trans, tree_id, &s_t);
706 	if (ret && !bch2_err_matches(ret, ENOENT))
707 		return ret;
708 
709 	if (ret || le32_to_cpu(s_t.root_snapshot) != root_id) {
710 		u = bch2_bkey_make_mut_typed(trans, &root_iter, &root.s_c, 0, snapshot);
711 		ret =   PTR_ERR_OR_ZERO(u) ?:
712 			bch2_snapshot_tree_create(trans, root_id,
713 				bch2_snapshot_tree_oldest_subvol(c, root_id),
714 				&tree_id);
715 		if (ret)
716 			goto err;
717 
718 		u->v.tree = cpu_to_le32(tree_id);
719 		if (k.k->p.offset == root_id)
720 			*s = u->v;
721 	}
722 
723 	if (k.k->p.offset != root_id) {
724 		u = bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot);
725 		ret = PTR_ERR_OR_ZERO(u);
726 		if (ret)
727 			goto err;
728 
729 		u->v.tree = cpu_to_le32(tree_id);
730 		*s = u->v;
731 	}
732 err:
733 	bch2_trans_iter_exit(trans, &root_iter);
734 	return ret;
735 }
736 
737 static int check_snapshot(struct btree_trans *trans,
738 			  struct btree_iter *iter,
739 			  struct bkey_s_c k)
740 {
741 	struct bch_fs *c = trans->c;
742 	struct bch_snapshot s;
743 	struct bch_subvolume subvol;
744 	struct bch_snapshot v;
745 	struct bkey_i_snapshot *u;
746 	u32 parent_id = bch2_snapshot_parent_early(c, k.k->p.offset);
747 	u32 real_depth;
748 	struct printbuf buf = PRINTBUF;
749 	u32 i, id;
750 	int ret = 0;
751 
752 	if (k.k->type != KEY_TYPE_snapshot)
753 		return 0;
754 
755 	memset(&s, 0, sizeof(s));
756 	memcpy(&s, k.v, min(sizeof(s), bkey_val_bytes(k.k)));
757 
758 	id = le32_to_cpu(s.parent);
759 	if (id) {
760 		ret = bch2_snapshot_lookup(trans, id, &v);
761 		if (bch2_err_matches(ret, ENOENT))
762 			bch_err(c, "snapshot with nonexistent parent:\n  %s",
763 				(bch2_bkey_val_to_text(&buf, c, k), buf.buf));
764 		if (ret)
765 			goto err;
766 
767 		if (le32_to_cpu(v.children[0]) != k.k->p.offset &&
768 		    le32_to_cpu(v.children[1]) != k.k->p.offset) {
769 			bch_err(c, "snapshot parent %u missing pointer to child %llu",
770 				id, k.k->p.offset);
771 			ret = -EINVAL;
772 			goto err;
773 		}
774 	}
775 
776 	for (i = 0; i < 2 && s.children[i]; i++) {
777 		id = le32_to_cpu(s.children[i]);
778 
779 		ret = bch2_snapshot_lookup(trans, id, &v);
780 		if (bch2_err_matches(ret, ENOENT))
781 			bch_err(c, "snapshot node %llu has nonexistent child %u",
782 				k.k->p.offset, id);
783 		if (ret)
784 			goto err;
785 
786 		if (le32_to_cpu(v.parent) != k.k->p.offset) {
787 			bch_err(c, "snapshot child %u has wrong parent (got %u should be %llu)",
788 				id, le32_to_cpu(v.parent), k.k->p.offset);
789 			ret = -EINVAL;
790 			goto err;
791 		}
792 	}
793 
794 	bool should_have_subvol = BCH_SNAPSHOT_SUBVOL(&s) &&
795 		!BCH_SNAPSHOT_DELETED(&s);
796 
797 	if (should_have_subvol) {
798 		id = le32_to_cpu(s.subvol);
799 		ret = bch2_subvolume_get(trans, id, 0, false, &subvol);
800 		if (bch2_err_matches(ret, ENOENT))
801 			bch_err(c, "snapshot points to nonexistent subvolume:\n  %s",
802 				(bch2_bkey_val_to_text(&buf, c, k), buf.buf));
803 		if (ret)
804 			goto err;
805 
806 		if (BCH_SNAPSHOT_SUBVOL(&s) != (le32_to_cpu(subvol.snapshot) == k.k->p.offset)) {
807 			bch_err(c, "snapshot node %llu has wrong BCH_SNAPSHOT_SUBVOL",
808 				k.k->p.offset);
809 			ret = -EINVAL;
810 			goto err;
811 		}
812 	} else {
813 		if (fsck_err_on(s.subvol,
814 				c, snapshot_should_not_have_subvol,
815 				"snapshot should not point to subvol:\n  %s",
816 				(bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
817 			u = bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot);
818 			ret = PTR_ERR_OR_ZERO(u);
819 			if (ret)
820 				goto err;
821 
822 			u->v.subvol = 0;
823 			s = u->v;
824 		}
825 	}
826 
827 	ret = snapshot_tree_ptr_good(trans, k.k->p.offset, le32_to_cpu(s.tree));
828 	if (ret < 0)
829 		goto err;
830 
831 	if (fsck_err_on(!ret, c, snapshot_to_bad_snapshot_tree,
832 			"snapshot points to missing/incorrect tree:\n  %s",
833 			(bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
834 		ret = snapshot_tree_ptr_repair(trans, iter, k, &s);
835 		if (ret)
836 			goto err;
837 	}
838 	ret = 0;
839 
840 	real_depth = bch2_snapshot_depth(c, parent_id);
841 
842 	if (fsck_err_on(le32_to_cpu(s.depth) != real_depth,
843 			c, snapshot_bad_depth,
844 			"snapshot with incorrect depth field, should be %u:\n  %s",
845 			real_depth, (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
846 		u = bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot);
847 		ret = PTR_ERR_OR_ZERO(u);
848 		if (ret)
849 			goto err;
850 
851 		u->v.depth = cpu_to_le32(real_depth);
852 		s = u->v;
853 	}
854 
855 	ret = snapshot_skiplist_good(trans, k.k->p.offset, s);
856 	if (ret < 0)
857 		goto err;
858 
859 	if (fsck_err_on(!ret, c, snapshot_bad_skiplist,
860 			"snapshot with bad skiplist field:\n  %s",
861 			(bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
862 		u = bch2_bkey_make_mut_typed(trans, iter, &k, 0, snapshot);
863 		ret = PTR_ERR_OR_ZERO(u);
864 		if (ret)
865 			goto err;
866 
867 		for (i = 0; i < ARRAY_SIZE(u->v.skip); i++)
868 			u->v.skip[i] = cpu_to_le32(bch2_snapshot_skiplist_get(c, parent_id));
869 
870 		bubble_sort(u->v.skip, ARRAY_SIZE(u->v.skip), cmp_le32);
871 		s = u->v;
872 	}
873 	ret = 0;
874 err:
875 fsck_err:
876 	printbuf_exit(&buf);
877 	return ret;
878 }
879 
880 int bch2_check_snapshots(struct bch_fs *c)
881 {
882 	/*
883 	 * We iterate backwards as checking/fixing the depth field requires that
884 	 * the parent's depth already be correct:
885 	 */
886 	int ret = bch2_trans_run(c,
887 		for_each_btree_key_reverse_commit(trans, iter,
888 				BTREE_ID_snapshots, POS_MAX,
889 				BTREE_ITER_prefetch, k,
890 				NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
891 			check_snapshot(trans, &iter, k)));
892 	bch_err_fn(c, ret);
893 	return ret;
894 }
895 
896 static int check_snapshot_exists(struct btree_trans *trans, u32 id)
897 {
898 	struct bch_fs *c = trans->c;
899 
900 	if (bch2_snapshot_equiv(c, id))
901 		return 0;
902 
903 	/* 0 is an invalid tree ID */
904 	u32 tree_id = 0;
905 	int ret = bch2_snapshot_tree_create(trans, id, 0, &tree_id);
906 	if (ret)
907 		return ret;
908 
909 	struct bkey_i_snapshot *snapshot = bch2_trans_kmalloc(trans, sizeof(*snapshot));
910 	ret = PTR_ERR_OR_ZERO(snapshot);
911 	if (ret)
912 		return ret;
913 
914 	bkey_snapshot_init(&snapshot->k_i);
915 	snapshot->k.p		= POS(0, id);
916 	snapshot->v.tree	= cpu_to_le32(tree_id);
917 	snapshot->v.btime.lo	= cpu_to_le64(bch2_current_time(c));
918 
919 	return  bch2_btree_insert_trans(trans, BTREE_ID_snapshots, &snapshot->k_i, 0) ?:
920 		bch2_mark_snapshot(trans, BTREE_ID_snapshots, 0,
921 				   bkey_s_c_null, bkey_i_to_s(&snapshot->k_i), 0) ?:
922 		bch2_snapshot_set_equiv(trans, bkey_i_to_s_c(&snapshot->k_i));
923 }
924 
925 /* Figure out which snapshot nodes belong in the same tree: */
926 struct snapshot_tree_reconstruct {
927 	enum btree_id			btree;
928 	struct bpos			cur_pos;
929 	snapshot_id_list		cur_ids;
930 	DARRAY(snapshot_id_list)	trees;
931 };
932 
933 static void snapshot_tree_reconstruct_exit(struct snapshot_tree_reconstruct *r)
934 {
935 	darray_for_each(r->trees, i)
936 		darray_exit(i);
937 	darray_exit(&r->trees);
938 	darray_exit(&r->cur_ids);
939 }
940 
941 static inline bool same_snapshot(struct snapshot_tree_reconstruct *r, struct bpos pos)
942 {
943 	return r->btree == BTREE_ID_inodes
944 		? r->cur_pos.offset == pos.offset
945 		: r->cur_pos.inode == pos.inode;
946 }
947 
948 static inline bool snapshot_id_lists_have_common(snapshot_id_list *l, snapshot_id_list *r)
949 {
950 	darray_for_each(*l, i)
951 		if (snapshot_list_has_id(r, *i))
952 			return true;
953 	return false;
954 }
955 
956 static void snapshot_id_list_to_text(struct printbuf *out, snapshot_id_list *s)
957 {
958 	bool first = true;
959 	darray_for_each(*s, i) {
960 		if (!first)
961 			prt_char(out, ' ');
962 		first = false;
963 		prt_printf(out, "%u", *i);
964 	}
965 }
966 
967 static int snapshot_tree_reconstruct_next(struct bch_fs *c, struct snapshot_tree_reconstruct *r)
968 {
969 	if (r->cur_ids.nr) {
970 		darray_for_each(r->trees, i)
971 			if (snapshot_id_lists_have_common(i, &r->cur_ids)) {
972 				int ret = snapshot_list_merge(c, i, &r->cur_ids);
973 				if (ret)
974 					return ret;
975 				goto out;
976 			}
977 		darray_push(&r->trees, r->cur_ids);
978 		darray_init(&r->cur_ids);
979 	}
980 out:
981 	r->cur_ids.nr = 0;
982 	return 0;
983 }
984 
985 static int get_snapshot_trees(struct bch_fs *c, struct snapshot_tree_reconstruct *r, struct bpos pos)
986 {
987 	if (!same_snapshot(r, pos))
988 		snapshot_tree_reconstruct_next(c, r);
989 	r->cur_pos = pos;
990 	return snapshot_list_add_nodup(c, &r->cur_ids, pos.snapshot);
991 }
992 
993 int bch2_reconstruct_snapshots(struct bch_fs *c)
994 {
995 	struct btree_trans *trans = bch2_trans_get(c);
996 	struct printbuf buf = PRINTBUF;
997 	struct snapshot_tree_reconstruct r = {};
998 	int ret = 0;
999 
1000 	for (unsigned btree = 0; btree < BTREE_ID_NR; btree++) {
1001 		if (btree_type_has_snapshots(btree)) {
1002 			r.btree = btree;
1003 
1004 			ret = for_each_btree_key(trans, iter, btree, POS_MIN,
1005 					BTREE_ITER_all_snapshots|BTREE_ITER_prefetch, k, ({
1006 				get_snapshot_trees(c, &r, k.k->p);
1007 			}));
1008 			if (ret)
1009 				goto err;
1010 
1011 			snapshot_tree_reconstruct_next(c, &r);
1012 		}
1013 	}
1014 
1015 	darray_for_each(r.trees, t) {
1016 		printbuf_reset(&buf);
1017 		snapshot_id_list_to_text(&buf, t);
1018 
1019 		darray_for_each(*t, id) {
1020 			if (fsck_err_on(!bch2_snapshot_equiv(c, *id),
1021 					c, snapshot_node_missing,
1022 					"snapshot node %u from tree %s missing, recreate?", *id, buf.buf)) {
1023 				if (t->nr > 1) {
1024 					bch_err(c, "cannot reconstruct snapshot trees with multiple nodes");
1025 					ret = -BCH_ERR_fsck_repair_unimplemented;
1026 					goto err;
1027 				}
1028 
1029 				ret = commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
1030 						check_snapshot_exists(trans, *id));
1031 				if (ret)
1032 					goto err;
1033 			}
1034 		}
1035 	}
1036 fsck_err:
1037 err:
1038 	bch2_trans_put(trans);
1039 	snapshot_tree_reconstruct_exit(&r);
1040 	printbuf_exit(&buf);
1041 	bch_err_fn(c, ret);
1042 	return ret;
1043 }
1044 
1045 /*
1046  * Mark a snapshot as deleted, for future cleanup:
1047  */
1048 int bch2_snapshot_node_set_deleted(struct btree_trans *trans, u32 id)
1049 {
1050 	struct btree_iter iter;
1051 	struct bkey_i_snapshot *s;
1052 	int ret = 0;
1053 
1054 	s = bch2_bkey_get_mut_typed(trans, &iter,
1055 				    BTREE_ID_snapshots, POS(0, id),
1056 				    0, snapshot);
1057 	ret = PTR_ERR_OR_ZERO(s);
1058 	if (unlikely(ret)) {
1059 		bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOENT),
1060 					trans->c, "missing snapshot %u", id);
1061 		return ret;
1062 	}
1063 
1064 	/* already deleted? */
1065 	if (BCH_SNAPSHOT_DELETED(&s->v))
1066 		goto err;
1067 
1068 	SET_BCH_SNAPSHOT_DELETED(&s->v, true);
1069 	SET_BCH_SNAPSHOT_SUBVOL(&s->v, false);
1070 	s->v.subvol = 0;
1071 err:
1072 	bch2_trans_iter_exit(trans, &iter);
1073 	return ret;
1074 }
1075 
1076 static inline void normalize_snapshot_child_pointers(struct bch_snapshot *s)
1077 {
1078 	if (le32_to_cpu(s->children[0]) < le32_to_cpu(s->children[1]))
1079 		swap(s->children[0], s->children[1]);
1080 }
1081 
1082 static int bch2_snapshot_node_delete(struct btree_trans *trans, u32 id)
1083 {
1084 	struct bch_fs *c = trans->c;
1085 	struct btree_iter iter, p_iter = (struct btree_iter) { NULL };
1086 	struct btree_iter c_iter = (struct btree_iter) { NULL };
1087 	struct btree_iter tree_iter = (struct btree_iter) { NULL };
1088 	struct bkey_s_c_snapshot s;
1089 	u32 parent_id, child_id;
1090 	unsigned i;
1091 	int ret = 0;
1092 
1093 	s = bch2_bkey_get_iter_typed(trans, &iter, BTREE_ID_snapshots, POS(0, id),
1094 				     BTREE_ITER_intent, snapshot);
1095 	ret = bkey_err(s);
1096 	bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOENT), c,
1097 				"missing snapshot %u", id);
1098 
1099 	if (ret)
1100 		goto err;
1101 
1102 	BUG_ON(s.v->children[1]);
1103 
1104 	parent_id = le32_to_cpu(s.v->parent);
1105 	child_id = le32_to_cpu(s.v->children[0]);
1106 
1107 	if (parent_id) {
1108 		struct bkey_i_snapshot *parent;
1109 
1110 		parent = bch2_bkey_get_mut_typed(trans, &p_iter,
1111 				     BTREE_ID_snapshots, POS(0, parent_id),
1112 				     0, snapshot);
1113 		ret = PTR_ERR_OR_ZERO(parent);
1114 		bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOENT), c,
1115 					"missing snapshot %u", parent_id);
1116 		if (unlikely(ret))
1117 			goto err;
1118 
1119 		/* find entry in parent->children for node being deleted */
1120 		for (i = 0; i < 2; i++)
1121 			if (le32_to_cpu(parent->v.children[i]) == id)
1122 				break;
1123 
1124 		if (bch2_fs_inconsistent_on(i == 2, c,
1125 					"snapshot %u missing child pointer to %u",
1126 					parent_id, id))
1127 			goto err;
1128 
1129 		parent->v.children[i] = cpu_to_le32(child_id);
1130 
1131 		normalize_snapshot_child_pointers(&parent->v);
1132 	}
1133 
1134 	if (child_id) {
1135 		struct bkey_i_snapshot *child;
1136 
1137 		child = bch2_bkey_get_mut_typed(trans, &c_iter,
1138 				     BTREE_ID_snapshots, POS(0, child_id),
1139 				     0, snapshot);
1140 		ret = PTR_ERR_OR_ZERO(child);
1141 		bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOENT), c,
1142 					"missing snapshot %u", child_id);
1143 		if (unlikely(ret))
1144 			goto err;
1145 
1146 		child->v.parent = cpu_to_le32(parent_id);
1147 
1148 		if (!child->v.parent) {
1149 			child->v.skip[0] = 0;
1150 			child->v.skip[1] = 0;
1151 			child->v.skip[2] = 0;
1152 		}
1153 	}
1154 
1155 	if (!parent_id) {
1156 		/*
1157 		 * We're deleting the root of a snapshot tree: update the
1158 		 * snapshot_tree entry to point to the new root, or delete it if
1159 		 * this is the last snapshot ID in this tree:
1160 		 */
1161 		struct bkey_i_snapshot_tree *s_t;
1162 
1163 		BUG_ON(s.v->children[1]);
1164 
1165 		s_t = bch2_bkey_get_mut_typed(trans, &tree_iter,
1166 				BTREE_ID_snapshot_trees, POS(0, le32_to_cpu(s.v->tree)),
1167 				0, snapshot_tree);
1168 		ret = PTR_ERR_OR_ZERO(s_t);
1169 		if (ret)
1170 			goto err;
1171 
1172 		if (s.v->children[0]) {
1173 			s_t->v.root_snapshot = s.v->children[0];
1174 		} else {
1175 			s_t->k.type = KEY_TYPE_deleted;
1176 			set_bkey_val_u64s(&s_t->k, 0);
1177 		}
1178 	}
1179 
1180 	ret = bch2_btree_delete_at(trans, &iter, 0);
1181 err:
1182 	bch2_trans_iter_exit(trans, &tree_iter);
1183 	bch2_trans_iter_exit(trans, &p_iter);
1184 	bch2_trans_iter_exit(trans, &c_iter);
1185 	bch2_trans_iter_exit(trans, &iter);
1186 	return ret;
1187 }
1188 
1189 static int create_snapids(struct btree_trans *trans, u32 parent, u32 tree,
1190 			  u32 *new_snapids,
1191 			  u32 *snapshot_subvols,
1192 			  unsigned nr_snapids)
1193 {
1194 	struct bch_fs *c = trans->c;
1195 	struct btree_iter iter;
1196 	struct bkey_i_snapshot *n;
1197 	struct bkey_s_c k;
1198 	unsigned i, j;
1199 	u32 depth = bch2_snapshot_depth(c, parent);
1200 	int ret;
1201 
1202 	bch2_trans_iter_init(trans, &iter, BTREE_ID_snapshots,
1203 			     POS_MIN, BTREE_ITER_intent);
1204 	k = bch2_btree_iter_peek(&iter);
1205 	ret = bkey_err(k);
1206 	if (ret)
1207 		goto err;
1208 
1209 	for (i = 0; i < nr_snapids; i++) {
1210 		k = bch2_btree_iter_prev_slot(&iter);
1211 		ret = bkey_err(k);
1212 		if (ret)
1213 			goto err;
1214 
1215 		if (!k.k || !k.k->p.offset) {
1216 			ret = -BCH_ERR_ENOSPC_snapshot_create;
1217 			goto err;
1218 		}
1219 
1220 		n = bch2_bkey_alloc(trans, &iter, 0, snapshot);
1221 		ret = PTR_ERR_OR_ZERO(n);
1222 		if (ret)
1223 			goto err;
1224 
1225 		n->v.flags	= 0;
1226 		n->v.parent	= cpu_to_le32(parent);
1227 		n->v.subvol	= cpu_to_le32(snapshot_subvols[i]);
1228 		n->v.tree	= cpu_to_le32(tree);
1229 		n->v.depth	= cpu_to_le32(depth);
1230 		n->v.btime.lo	= cpu_to_le64(bch2_current_time(c));
1231 		n->v.btime.hi	= 0;
1232 
1233 		for (j = 0; j < ARRAY_SIZE(n->v.skip); j++)
1234 			n->v.skip[j] = cpu_to_le32(bch2_snapshot_skiplist_get(c, parent));
1235 
1236 		bubble_sort(n->v.skip, ARRAY_SIZE(n->v.skip), cmp_le32);
1237 		SET_BCH_SNAPSHOT_SUBVOL(&n->v, true);
1238 
1239 		ret = __bch2_mark_snapshot(trans, BTREE_ID_snapshots, 0,
1240 					 bkey_s_c_null, bkey_i_to_s_c(&n->k_i), 0);
1241 		if (ret)
1242 			goto err;
1243 
1244 		new_snapids[i]	= iter.pos.offset;
1245 
1246 		mutex_lock(&c->snapshot_table_lock);
1247 		snapshot_t_mut(c, new_snapids[i])->equiv = new_snapids[i];
1248 		mutex_unlock(&c->snapshot_table_lock);
1249 	}
1250 err:
1251 	bch2_trans_iter_exit(trans, &iter);
1252 	return ret;
1253 }
1254 
1255 /*
1256  * Create new snapshot IDs as children of an existing snapshot ID:
1257  */
1258 static int bch2_snapshot_node_create_children(struct btree_trans *trans, u32 parent,
1259 			      u32 *new_snapids,
1260 			      u32 *snapshot_subvols,
1261 			      unsigned nr_snapids)
1262 {
1263 	struct btree_iter iter;
1264 	struct bkey_i_snapshot *n_parent;
1265 	int ret = 0;
1266 
1267 	n_parent = bch2_bkey_get_mut_typed(trans, &iter,
1268 			BTREE_ID_snapshots, POS(0, parent),
1269 			0, snapshot);
1270 	ret = PTR_ERR_OR_ZERO(n_parent);
1271 	if (unlikely(ret)) {
1272 		if (bch2_err_matches(ret, ENOENT))
1273 			bch_err(trans->c, "snapshot %u not found", parent);
1274 		return ret;
1275 	}
1276 
1277 	if (n_parent->v.children[0] || n_parent->v.children[1]) {
1278 		bch_err(trans->c, "Trying to add child snapshot nodes to parent that already has children");
1279 		ret = -EINVAL;
1280 		goto err;
1281 	}
1282 
1283 	ret = create_snapids(trans, parent, le32_to_cpu(n_parent->v.tree),
1284 			     new_snapids, snapshot_subvols, nr_snapids);
1285 	if (ret)
1286 		goto err;
1287 
1288 	n_parent->v.children[0] = cpu_to_le32(new_snapids[0]);
1289 	n_parent->v.children[1] = cpu_to_le32(new_snapids[1]);
1290 	n_parent->v.subvol = 0;
1291 	SET_BCH_SNAPSHOT_SUBVOL(&n_parent->v, false);
1292 err:
1293 	bch2_trans_iter_exit(trans, &iter);
1294 	return ret;
1295 }
1296 
1297 /*
1298  * Create a snapshot node that is the root of a new tree:
1299  */
1300 static int bch2_snapshot_node_create_tree(struct btree_trans *trans,
1301 			      u32 *new_snapids,
1302 			      u32 *snapshot_subvols,
1303 			      unsigned nr_snapids)
1304 {
1305 	struct bkey_i_snapshot_tree *n_tree;
1306 	int ret;
1307 
1308 	n_tree = __bch2_snapshot_tree_create(trans);
1309 	ret =   PTR_ERR_OR_ZERO(n_tree) ?:
1310 		create_snapids(trans, 0, n_tree->k.p.offset,
1311 			     new_snapids, snapshot_subvols, nr_snapids);
1312 	if (ret)
1313 		return ret;
1314 
1315 	n_tree->v.master_subvol	= cpu_to_le32(snapshot_subvols[0]);
1316 	n_tree->v.root_snapshot	= cpu_to_le32(new_snapids[0]);
1317 	return 0;
1318 }
1319 
1320 int bch2_snapshot_node_create(struct btree_trans *trans, u32 parent,
1321 			      u32 *new_snapids,
1322 			      u32 *snapshot_subvols,
1323 			      unsigned nr_snapids)
1324 {
1325 	BUG_ON((parent == 0) != (nr_snapids == 1));
1326 	BUG_ON((parent != 0) != (nr_snapids == 2));
1327 
1328 	return parent
1329 		? bch2_snapshot_node_create_children(trans, parent,
1330 				new_snapids, snapshot_subvols, nr_snapids)
1331 		: bch2_snapshot_node_create_tree(trans,
1332 				new_snapids, snapshot_subvols, nr_snapids);
1333 
1334 }
1335 
1336 /*
1337  * If we have an unlinked inode in an internal snapshot node, and the inode
1338  * really has been deleted in all child snapshots, how does this get cleaned up?
1339  *
1340  * first there is the problem of how keys that have been overwritten in all
1341  * child snapshots get deleted (unimplemented?), but inodes may perhaps be
1342  * special?
1343  *
1344  * also: unlinked inode in internal snapshot appears to not be getting deleted
1345  * correctly if inode doesn't exist in leaf snapshots
1346  *
1347  * solution:
1348  *
1349  * for a key in an interior snapshot node that needs work to be done that
1350  * requires it to be mutated: iterate over all descendent leaf nodes and copy
1351  * that key to snapshot leaf nodes, where we can mutate it
1352  */
1353 
1354 static int snapshot_delete_key(struct btree_trans *trans,
1355 			       struct btree_iter *iter,
1356 			       struct bkey_s_c k,
1357 			       snapshot_id_list *deleted,
1358 			       snapshot_id_list *equiv_seen,
1359 			       struct bpos *last_pos)
1360 {
1361 	struct bch_fs *c = trans->c;
1362 	u32 equiv = bch2_snapshot_equiv(c, k.k->p.snapshot);
1363 
1364 	if (!bkey_eq(k.k->p, *last_pos))
1365 		equiv_seen->nr = 0;
1366 	*last_pos = k.k->p;
1367 
1368 	if (snapshot_list_has_id(deleted, k.k->p.snapshot) ||
1369 	    snapshot_list_has_id(equiv_seen, equiv)) {
1370 		return bch2_btree_delete_at(trans, iter,
1371 					    BTREE_UPDATE_internal_snapshot_node);
1372 	} else {
1373 		return snapshot_list_add(c, equiv_seen, equiv);
1374 	}
1375 }
1376 
1377 static int move_key_to_correct_snapshot(struct btree_trans *trans,
1378 			       struct btree_iter *iter,
1379 			       struct bkey_s_c k)
1380 {
1381 	struct bch_fs *c = trans->c;
1382 	u32 equiv = bch2_snapshot_equiv(c, k.k->p.snapshot);
1383 
1384 	/*
1385 	 * When we have a linear chain of snapshot nodes, we consider
1386 	 * those to form an equivalence class: we're going to collapse
1387 	 * them all down to a single node, and keep the leaf-most node -
1388 	 * which has the same id as the equivalence class id.
1389 	 *
1390 	 * If there are multiple keys in different snapshots at the same
1391 	 * position, we're only going to keep the one in the newest
1392 	 * snapshot - the rest have been overwritten and are redundant,
1393 	 * and for the key we're going to keep we need to move it to the
1394 	 * equivalance class ID if it's not there already.
1395 	 */
1396 	if (equiv != k.k->p.snapshot) {
1397 		struct bkey_i *new = bch2_bkey_make_mut_noupdate(trans, k);
1398 		struct btree_iter new_iter;
1399 		int ret;
1400 
1401 		ret = PTR_ERR_OR_ZERO(new);
1402 		if (ret)
1403 			return ret;
1404 
1405 		new->k.p.snapshot = equiv;
1406 
1407 		bch2_trans_iter_init(trans, &new_iter, iter->btree_id, new->k.p,
1408 				     BTREE_ITER_all_snapshots|
1409 				     BTREE_ITER_cached|
1410 				     BTREE_ITER_intent);
1411 
1412 		ret =   bch2_btree_iter_traverse(&new_iter) ?:
1413 			bch2_trans_update(trans, &new_iter, new,
1414 					BTREE_UPDATE_internal_snapshot_node) ?:
1415 			bch2_btree_delete_at(trans, iter,
1416 					BTREE_UPDATE_internal_snapshot_node);
1417 		bch2_trans_iter_exit(trans, &new_iter);
1418 		if (ret)
1419 			return ret;
1420 	}
1421 
1422 	return 0;
1423 }
1424 
1425 static int bch2_snapshot_needs_delete(struct btree_trans *trans, struct bkey_s_c k)
1426 {
1427 	struct bkey_s_c_snapshot snap;
1428 	u32 children[2];
1429 	int ret;
1430 
1431 	if (k.k->type != KEY_TYPE_snapshot)
1432 		return 0;
1433 
1434 	snap = bkey_s_c_to_snapshot(k);
1435 	if (BCH_SNAPSHOT_DELETED(snap.v) ||
1436 	    BCH_SNAPSHOT_SUBVOL(snap.v))
1437 		return 0;
1438 
1439 	children[0] = le32_to_cpu(snap.v->children[0]);
1440 	children[1] = le32_to_cpu(snap.v->children[1]);
1441 
1442 	ret   = bch2_snapshot_live(trans, children[0]) ?:
1443 		bch2_snapshot_live(trans, children[1]);
1444 	if (ret < 0)
1445 		return ret;
1446 	return !ret;
1447 }
1448 
1449 /*
1450  * For a given snapshot, if it doesn't have a subvolume that points to it, and
1451  * it doesn't have child snapshot nodes - it's now redundant and we can mark it
1452  * as deleted.
1453  */
1454 static int bch2_delete_redundant_snapshot(struct btree_trans *trans, struct bkey_s_c k)
1455 {
1456 	int ret = bch2_snapshot_needs_delete(trans, k);
1457 
1458 	return ret <= 0
1459 		? ret
1460 		: bch2_snapshot_node_set_deleted(trans, k.k->p.offset);
1461 }
1462 
1463 static inline u32 bch2_snapshot_nth_parent_skip(struct bch_fs *c, u32 id, u32 n,
1464 						snapshot_id_list *skip)
1465 {
1466 	rcu_read_lock();
1467 	while (snapshot_list_has_id(skip, id))
1468 		id = __bch2_snapshot_parent(c, id);
1469 
1470 	while (n--) {
1471 		do {
1472 			id = __bch2_snapshot_parent(c, id);
1473 		} while (snapshot_list_has_id(skip, id));
1474 	}
1475 	rcu_read_unlock();
1476 
1477 	return id;
1478 }
1479 
1480 static int bch2_fix_child_of_deleted_snapshot(struct btree_trans *trans,
1481 					      struct btree_iter *iter, struct bkey_s_c k,
1482 					      snapshot_id_list *deleted)
1483 {
1484 	struct bch_fs *c = trans->c;
1485 	u32 nr_deleted_ancestors = 0;
1486 	struct bkey_i_snapshot *s;
1487 	int ret;
1488 
1489 	if (k.k->type != KEY_TYPE_snapshot)
1490 		return 0;
1491 
1492 	if (snapshot_list_has_id(deleted, k.k->p.offset))
1493 		return 0;
1494 
1495 	s = bch2_bkey_make_mut_noupdate_typed(trans, k, snapshot);
1496 	ret = PTR_ERR_OR_ZERO(s);
1497 	if (ret)
1498 		return ret;
1499 
1500 	darray_for_each(*deleted, i)
1501 		nr_deleted_ancestors += bch2_snapshot_is_ancestor(c, s->k.p.offset, *i);
1502 
1503 	if (!nr_deleted_ancestors)
1504 		return 0;
1505 
1506 	le32_add_cpu(&s->v.depth, -nr_deleted_ancestors);
1507 
1508 	if (!s->v.depth) {
1509 		s->v.skip[0] = 0;
1510 		s->v.skip[1] = 0;
1511 		s->v.skip[2] = 0;
1512 	} else {
1513 		u32 depth = le32_to_cpu(s->v.depth);
1514 		u32 parent = bch2_snapshot_parent(c, s->k.p.offset);
1515 
1516 		for (unsigned j = 0; j < ARRAY_SIZE(s->v.skip); j++) {
1517 			u32 id = le32_to_cpu(s->v.skip[j]);
1518 
1519 			if (snapshot_list_has_id(deleted, id)) {
1520 				id = bch2_snapshot_nth_parent_skip(c,
1521 							parent,
1522 							depth > 1
1523 							? get_random_u32_below(depth - 1)
1524 							: 0,
1525 							deleted);
1526 				s->v.skip[j] = cpu_to_le32(id);
1527 			}
1528 		}
1529 
1530 		bubble_sort(s->v.skip, ARRAY_SIZE(s->v.skip), cmp_le32);
1531 	}
1532 
1533 	return bch2_trans_update(trans, iter, &s->k_i, 0);
1534 }
1535 
1536 int bch2_delete_dead_snapshots(struct bch_fs *c)
1537 {
1538 	struct btree_trans *trans;
1539 	snapshot_id_list deleted = { 0 };
1540 	snapshot_id_list deleted_interior = { 0 };
1541 	u32 id;
1542 	int ret = 0;
1543 
1544 	if (!test_and_clear_bit(BCH_FS_need_delete_dead_snapshots, &c->flags))
1545 		return 0;
1546 
1547 	if (!test_bit(BCH_FS_started, &c->flags)) {
1548 		ret = bch2_fs_read_write_early(c);
1549 		bch_err_msg(c, ret, "deleting dead snapshots: error going rw");
1550 		if (ret)
1551 			return ret;
1552 	}
1553 
1554 	trans = bch2_trans_get(c);
1555 
1556 	/*
1557 	 * For every snapshot node: If we have no live children and it's not
1558 	 * pointed to by a subvolume, delete it:
1559 	 */
1560 	ret = for_each_btree_key_commit(trans, iter, BTREE_ID_snapshots,
1561 			POS_MIN, 0, k,
1562 			NULL, NULL, 0,
1563 		bch2_delete_redundant_snapshot(trans, k));
1564 	bch_err_msg(c, ret, "deleting redundant snapshots");
1565 	if (ret)
1566 		goto err;
1567 
1568 	ret = for_each_btree_key(trans, iter, BTREE_ID_snapshots,
1569 				 POS_MIN, 0, k,
1570 		bch2_snapshot_set_equiv(trans, k));
1571 	bch_err_msg(c, ret, "in bch2_snapshots_set_equiv");
1572 	if (ret)
1573 		goto err;
1574 
1575 	ret = for_each_btree_key(trans, iter, BTREE_ID_snapshots,
1576 				 POS_MIN, 0, k, ({
1577 		if (k.k->type != KEY_TYPE_snapshot)
1578 			continue;
1579 
1580 		BCH_SNAPSHOT_DELETED(bkey_s_c_to_snapshot(k).v)
1581 			? snapshot_list_add(c, &deleted, k.k->p.offset)
1582 			: 0;
1583 	}));
1584 	bch_err_msg(c, ret, "walking snapshots");
1585 	if (ret)
1586 		goto err;
1587 
1588 	for (id = 0; id < BTREE_ID_NR; id++) {
1589 		struct bpos last_pos = POS_MIN;
1590 		snapshot_id_list equiv_seen = { 0 };
1591 		struct disk_reservation res = { 0 };
1592 
1593 		if (!btree_type_has_snapshots(id))
1594 			continue;
1595 
1596 		/*
1597 		 * deleted inodes btree is maintained by a trigger on the inodes
1598 		 * btree - no work for us to do here, and it's not safe to scan
1599 		 * it because we'll see out of date keys due to the btree write
1600 		 * buffer:
1601 		 */
1602 		if (id == BTREE_ID_deleted_inodes)
1603 			continue;
1604 
1605 		ret = for_each_btree_key_commit(trans, iter,
1606 				id, POS_MIN,
1607 				BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k,
1608 				&res, NULL, BCH_TRANS_COMMIT_no_enospc,
1609 			snapshot_delete_key(trans, &iter, k, &deleted, &equiv_seen, &last_pos)) ?:
1610 		      for_each_btree_key_commit(trans, iter,
1611 				id, POS_MIN,
1612 				BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k,
1613 				&res, NULL, BCH_TRANS_COMMIT_no_enospc,
1614 			move_key_to_correct_snapshot(trans, &iter, k));
1615 
1616 		bch2_disk_reservation_put(c, &res);
1617 		darray_exit(&equiv_seen);
1618 
1619 		bch_err_msg(c, ret, "deleting keys from dying snapshots");
1620 		if (ret)
1621 			goto err;
1622 	}
1623 
1624 	bch2_trans_unlock(trans);
1625 	down_write(&c->snapshot_create_lock);
1626 
1627 	ret = for_each_btree_key(trans, iter, BTREE_ID_snapshots,
1628 				 POS_MIN, 0, k, ({
1629 		u32 snapshot = k.k->p.offset;
1630 		u32 equiv = bch2_snapshot_equiv(c, snapshot);
1631 
1632 		equiv != snapshot
1633 			? snapshot_list_add(c, &deleted_interior, snapshot)
1634 			: 0;
1635 	}));
1636 
1637 	bch_err_msg(c, ret, "walking snapshots");
1638 	if (ret)
1639 		goto err_create_lock;
1640 
1641 	/*
1642 	 * Fixing children of deleted snapshots can't be done completely
1643 	 * atomically, if we crash between here and when we delete the interior
1644 	 * nodes some depth fields will be off:
1645 	 */
1646 	ret = for_each_btree_key_commit(trans, iter, BTREE_ID_snapshots, POS_MIN,
1647 				  BTREE_ITER_intent, k,
1648 				  NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
1649 		bch2_fix_child_of_deleted_snapshot(trans, &iter, k, &deleted_interior));
1650 	if (ret)
1651 		goto err_create_lock;
1652 
1653 	darray_for_each(deleted, i) {
1654 		ret = commit_do(trans, NULL, NULL, 0,
1655 			bch2_snapshot_node_delete(trans, *i));
1656 		bch_err_msg(c, ret, "deleting snapshot %u", *i);
1657 		if (ret)
1658 			goto err_create_lock;
1659 	}
1660 
1661 	darray_for_each(deleted_interior, i) {
1662 		ret = commit_do(trans, NULL, NULL, 0,
1663 			bch2_snapshot_node_delete(trans, *i));
1664 		bch_err_msg(c, ret, "deleting snapshot %u", *i);
1665 		if (ret)
1666 			goto err_create_lock;
1667 	}
1668 err_create_lock:
1669 	up_write(&c->snapshot_create_lock);
1670 err:
1671 	darray_exit(&deleted_interior);
1672 	darray_exit(&deleted);
1673 	bch2_trans_put(trans);
1674 	bch_err_fn(c, ret);
1675 	return ret;
1676 }
1677 
1678 void bch2_delete_dead_snapshots_work(struct work_struct *work)
1679 {
1680 	struct bch_fs *c = container_of(work, struct bch_fs, snapshot_delete_work);
1681 
1682 	bch2_delete_dead_snapshots(c);
1683 	bch2_write_ref_put(c, BCH_WRITE_REF_delete_dead_snapshots);
1684 }
1685 
1686 void bch2_delete_dead_snapshots_async(struct bch_fs *c)
1687 {
1688 	if (bch2_write_ref_tryget(c, BCH_WRITE_REF_delete_dead_snapshots) &&
1689 	    !queue_work(c->write_ref_wq, &c->snapshot_delete_work))
1690 		bch2_write_ref_put(c, BCH_WRITE_REF_delete_dead_snapshots);
1691 }
1692 
1693 int __bch2_key_has_snapshot_overwrites(struct btree_trans *trans,
1694 				       enum btree_id id,
1695 				       struct bpos pos)
1696 {
1697 	struct bch_fs *c = trans->c;
1698 	struct btree_iter iter;
1699 	struct bkey_s_c k;
1700 	int ret;
1701 
1702 	bch2_trans_iter_init(trans, &iter, id, pos,
1703 			     BTREE_ITER_not_extents|
1704 			     BTREE_ITER_all_snapshots);
1705 	while (1) {
1706 		k = bch2_btree_iter_prev(&iter);
1707 		ret = bkey_err(k);
1708 		if (ret)
1709 			break;
1710 
1711 		if (!k.k)
1712 			break;
1713 
1714 		if (!bkey_eq(pos, k.k->p))
1715 			break;
1716 
1717 		if (bch2_snapshot_is_ancestor(c, k.k->p.snapshot, pos.snapshot)) {
1718 			ret = 1;
1719 			break;
1720 		}
1721 	}
1722 	bch2_trans_iter_exit(trans, &iter);
1723 
1724 	return ret;
1725 }
1726 
1727 static u32 bch2_snapshot_smallest_child(struct bch_fs *c, u32 id)
1728 {
1729 	const struct snapshot_t *s = snapshot_t(c, id);
1730 
1731 	return s->children[1] ?: s->children[0];
1732 }
1733 
1734 static u32 bch2_snapshot_smallest_descendent(struct bch_fs *c, u32 id)
1735 {
1736 	u32 child;
1737 
1738 	while ((child = bch2_snapshot_smallest_child(c, id)))
1739 		id = child;
1740 	return id;
1741 }
1742 
1743 static int bch2_propagate_key_to_snapshot_leaf(struct btree_trans *trans,
1744 					       enum btree_id btree,
1745 					       struct bkey_s_c interior_k,
1746 					       u32 leaf_id, struct bpos *new_min_pos)
1747 {
1748 	struct btree_iter iter;
1749 	struct bpos pos = interior_k.k->p;
1750 	struct bkey_s_c k;
1751 	struct bkey_i *new;
1752 	int ret;
1753 
1754 	pos.snapshot = leaf_id;
1755 
1756 	bch2_trans_iter_init(trans, &iter, btree, pos, BTREE_ITER_intent);
1757 	k = bch2_btree_iter_peek_slot(&iter);
1758 	ret = bkey_err(k);
1759 	if (ret)
1760 		goto out;
1761 
1762 	/* key already overwritten in this snapshot? */
1763 	if (k.k->p.snapshot != interior_k.k->p.snapshot)
1764 		goto out;
1765 
1766 	if (bpos_eq(*new_min_pos, POS_MIN)) {
1767 		*new_min_pos = k.k->p;
1768 		new_min_pos->snapshot = leaf_id;
1769 	}
1770 
1771 	new = bch2_bkey_make_mut_noupdate(trans, interior_k);
1772 	ret = PTR_ERR_OR_ZERO(new);
1773 	if (ret)
1774 		goto out;
1775 
1776 	new->k.p.snapshot = leaf_id;
1777 	ret = bch2_trans_update(trans, &iter, new, 0);
1778 out:
1779 	bch2_trans_iter_exit(trans, &iter);
1780 	return ret;
1781 }
1782 
1783 int bch2_propagate_key_to_snapshot_leaves(struct btree_trans *trans,
1784 					  enum btree_id btree,
1785 					  struct bkey_s_c k,
1786 					  struct bpos *new_min_pos)
1787 {
1788 	struct bch_fs *c = trans->c;
1789 	struct bkey_buf sk;
1790 	u32 restart_count = trans->restart_count;
1791 	int ret = 0;
1792 
1793 	bch2_bkey_buf_init(&sk);
1794 	bch2_bkey_buf_reassemble(&sk, c, k);
1795 	k = bkey_i_to_s_c(sk.k);
1796 
1797 	*new_min_pos = POS_MIN;
1798 
1799 	for (u32 id = bch2_snapshot_smallest_descendent(c, k.k->p.snapshot);
1800 	     id < k.k->p.snapshot;
1801 	     id++) {
1802 		if (!bch2_snapshot_is_ancestor(c, id, k.k->p.snapshot) ||
1803 		    !bch2_snapshot_is_leaf(c, id))
1804 			continue;
1805 again:
1806 		ret =   btree_trans_too_many_iters(trans) ?:
1807 			bch2_propagate_key_to_snapshot_leaf(trans, btree, k, id, new_min_pos) ?:
1808 			bch2_trans_commit(trans, NULL, NULL, 0);
1809 		if (ret && bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
1810 			bch2_trans_begin(trans);
1811 			goto again;
1812 		}
1813 
1814 		if (ret)
1815 			break;
1816 	}
1817 
1818 	bch2_bkey_buf_exit(&sk, c);
1819 
1820 	return ret ?: trans_was_restarted(trans, restart_count);
1821 }
1822 
1823 static int bch2_check_snapshot_needs_deletion(struct btree_trans *trans, struct bkey_s_c k)
1824 {
1825 	struct bch_fs *c = trans->c;
1826 	struct bkey_s_c_snapshot snap;
1827 	int ret = 0;
1828 
1829 	if (k.k->type != KEY_TYPE_snapshot)
1830 		return 0;
1831 
1832 	snap = bkey_s_c_to_snapshot(k);
1833 	if (BCH_SNAPSHOT_DELETED(snap.v) ||
1834 	    bch2_snapshot_equiv(c, k.k->p.offset) != k.k->p.offset ||
1835 	    (ret = bch2_snapshot_needs_delete(trans, k)) > 0) {
1836 		set_bit(BCH_FS_need_delete_dead_snapshots, &c->flags);
1837 		return 0;
1838 	}
1839 
1840 	return ret;
1841 }
1842 
1843 int bch2_snapshots_read(struct bch_fs *c)
1844 {
1845 	int ret = bch2_trans_run(c,
1846 		for_each_btree_key(trans, iter, BTREE_ID_snapshots,
1847 				   POS_MIN, 0, k,
1848 			__bch2_mark_snapshot(trans, BTREE_ID_snapshots, 0, bkey_s_c_null, k, 0) ?:
1849 			bch2_snapshot_set_equiv(trans, k) ?:
1850 			bch2_check_snapshot_needs_deletion(trans, k)) ?:
1851 		for_each_btree_key(trans, iter, BTREE_ID_snapshots,
1852 				   POS_MIN, 0, k,
1853 			   (set_is_ancestor_bitmap(c, k.k->p.offset), 0)));
1854 	bch_err_fn(c, ret);
1855 
1856 	/*
1857 	 * It's important that we check if we need to reconstruct snapshots
1858 	 * before going RW, so we mark that pass as required in the superblock -
1859 	 * otherwise, we could end up deleting keys with missing snapshot nodes
1860 	 * instead
1861 	 */
1862 	BUG_ON(!test_bit(BCH_FS_new_fs, &c->flags) &&
1863 	       test_bit(BCH_FS_may_go_rw, &c->flags));
1864 
1865 	if (bch2_err_matches(ret, EIO) ||
1866 	    (c->sb.btrees_lost_data & BIT_ULL(BTREE_ID_snapshots)))
1867 		ret = bch2_run_explicit_recovery_pass_persistent(c, BCH_RECOVERY_PASS_reconstruct_snapshots);
1868 
1869 	return ret;
1870 }
1871 
1872 void bch2_fs_snapshots_exit(struct bch_fs *c)
1873 {
1874 	kvfree(rcu_dereference_protected(c->snapshots, true));
1875 }
1876