/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _BCACHEFS_SNAPSHOT_H
#define _BCACHEFS_SNAPSHOT_H

void bch2_snapshot_tree_to_text(struct printbuf *, struct bch_fs *, struct bkey_s_c);
int bch2_snapshot_tree_validate(struct bch_fs *, struct bkey_s_c,
				const struct bkey_validate_context *);

#define bch2_bkey_ops_snapshot_tree ((struct bkey_ops) {	\
	.key_validate	= bch2_snapshot_tree_validate,		\
	.val_to_text	= bch2_snapshot_tree_to_text,		\
	.min_val_size	= 8,					\
})

struct bkey_i_snapshot_tree *__bch2_snapshot_tree_create(struct btree_trans *);

int bch2_snapshot_tree_lookup(struct btree_trans *, u32, struct bch_snapshot_tree *);

void bch2_snapshot_to_text(struct printbuf *, const struct bch_snapshot *);
void bch2_snapshot_key_to_text(struct printbuf *, struct bch_fs *, struct bkey_s_c);
int bch2_snapshot_validate(struct bch_fs *, struct bkey_s_c,
			   const struct bkey_validate_context *);
int bch2_snapshot_trigger(struct btree_trans *, struct btree_trigger_op);

int bch2_snapshot_tree_keys_to_text(struct printbuf *, struct btree_trans *, u32);

int bch2_check_snapshot_needs_deletion(struct btree_trans *, struct bkey_s_c, u32 *);

#define bch2_bkey_ops_snapshot ((struct bkey_ops) {		\
	.key_validate	= bch2_snapshot_validate,		\
	.val_to_text	= bch2_snapshot_key_to_text,		\
	.trigger	= bch2_snapshot_trigger,		\
	.min_val_size	= 24,					\
})

static inline enum bch_snapshot_state bch2_snapshot_state(const struct bch_snapshot *s)
{
	return le32_to_cpu(s->state);
}

static inline enum bch_snapshot_state bch2_snapshot_state_from_flags(const struct bch_snapshot *s)
{
	if (BCH_SNAPSHOT_DELETED_OBSOLETE(s))
		return SNAPSHOT_STATE_deleted;
	if (BCH_SNAPSHOT_NO_KEYS_OBSOLETE(s))
		return SNAPSHOT_STATE_no_keys;
	if (BCH_SNAPSHOT_WILL_DELETE_OBSOLETE(s))
		return SNAPSHOT_STATE_will_delete;
	return SNAPSHOT_STATE_live;
}

static inline enum bch_snapshot_state bch2_snapshot_state_compat(const struct bch_snapshot *s)
{
	return s->state
		? bch2_snapshot_state(s)
		: bch2_snapshot_state_from_flags(s);
}

static inline bool bch2_snapshot_state_valid(enum bch_snapshot_state state)
{
	switch (state) {
#define x(n, v) case SNAPSHOT_STATE_##n:
	BCH_SNAPSHOT_STATES()
#undef x
		return true;
	default:
		return false;
	}
}

/*
 * Nearest-codeword decode for a corrupted state field: the state codewords
 * are >= 14 bits apart, so a corruption of <= 6 bits lands strictly nearest
 * its original and >= 8 from every other - a uniquely decodable bitflip.
 * Returns the nearest state; @dist is its Hamming distance from @v (0 iff @v
 * is already a valid codeword). The caller corrects only within the
 * uniquely-decodable radius.
 */
static inline enum bch_snapshot_state
bch2_snapshot_state_nearest(u32 v, unsigned *dist)
{
	enum bch_snapshot_state best = SNAPSHOT_STATE_live;
	unsigned best_dist = 33;

#define x(n, val)						\
	if (hweight32(v ^ (val)) < best_dist) {			\
		best_dist = hweight32(v ^ (val));		\
		best = SNAPSHOT_STATE_##n;			\
	}
	BCH_SNAPSHOT_STATES()
#undef x
	*dist = best_dist;
	return best;
}

const char *bch2_snapshot_state_str(enum bch_snapshot_state);
void bch2_snapshot_state_set(struct bch_snapshot *, enum bch_snapshot_state);

static inline struct snapshot_t *__snapshot_t(struct snapshot_table *t, u32 id)
{
	u32 idx = U32_MAX - id;

	return likely(t && idx < t->nr)
		? &t->s[idx]
		: NULL;
}

static inline const struct snapshot_t *snapshot_t(struct bch_fs *c, u32 id)
{
	return __snapshot_t(rcu_dereference(c->snapshots.table), id);
}

struct snapshot_t *bch2_snapshot_t_mut(struct bch_fs *, u32);

static inline u32 bch2_snapshot_tree(struct bch_fs *c, u32 id)
{
	guard(rcu)();
	const struct snapshot_t *s = snapshot_t(c, id);
	return s ? s->tree : 0;
}

static inline bool bch2_snapshots_same_tree(struct bch_fs *c, u32 id1, u32 id2)
{
	if (id1 == id2)
		return true;

	guard(rcu)();
	const struct snapshot_t *s1 = snapshot_t(c, id1);
	const struct snapshot_t *s2 = snapshot_t(c, id2);
	return s1 && s2 && s1->tree == s2->tree;
}

static inline u32 __bch2_snapshot_parent_early(struct bch_fs *c, u32 id)
{
	const struct snapshot_t *s = snapshot_t(c, id);
	return s ? s->parent : 0;
}

static inline u32 bch2_snapshot_parent_early(struct bch_fs *c, u32 id)
{
	guard(rcu)();
	return __bch2_snapshot_parent_early(c, id);
}

/*
 * No depth consistency check here: depth == parent's depth + 1 is not an
 * invariant this can rely on. delete_dead_interior_snapshots() writes every
 * surviving child's new depth in one loop and only splices the deleted nodes
 * out in the next, so for that whole span - and on disk, if we crash in it - a
 * child carries its new depth and its old parent pointer. fsck owns the check
 * instead: snapshot_bad_depth in check_snapshot(), which has a transaction, is
 * FSCK_AUTOFIX, and re-derives depth from the parent rather than just
 * complaining about it.
 */
static inline u32 __bch2_snapshot_parent(struct snapshot_table *t, u32 id)
{
	const struct snapshot_t *s = __snapshot_t(t, id);
	return s ? s->parent : 0;
}

static inline u32 bch2_snapshot_parent(struct bch_fs *c, u32 id)
{
	guard(rcu)();
	return __bch2_snapshot_parent(rcu_dereference(c->snapshots.table), id);
}

static inline u32 bch2_snapshot_nth_parent(struct bch_fs *c, u32 id, u32 n)
{
	guard(rcu)();
	struct snapshot_table *t = rcu_dereference(c->snapshots.table);

	while (n--)
		id = __bch2_snapshot_parent(t, id);
	return id;
}

u32 bch2_snapshot_skiplist_get(struct bch_fs *, u32);

static inline u32 bch2_snapshot_root(struct bch_fs *c, u32 id)
{
	guard(rcu)();
	struct snapshot_table *t = rcu_dereference(c->snapshots.table);

	u32 parent;
	while ((parent = __bch2_snapshot_parent(t, id)))
		id = parent;
	return id;
}

static inline enum snapshot_id_state __bch2_snapshot_id_state(struct snapshot_table *t, u32 id)
{
	const struct snapshot_t *s = __snapshot_t(t, id);
	return s ? s->state : SNAPSHOT_ID_empty;
}

static inline enum snapshot_id_state bch2_snapshot_id_state(struct bch_fs *c, u32 id)
{
	guard(rcu)();
	return __bch2_snapshot_id_state(rcu_dereference(c->snapshots.table), id);
}

static inline bool __bch2_snapshot_exists(struct snapshot_table *t, u32 id)
{
	return __bch2_snapshot_id_state(t, id) == SNAPSHOT_ID_live;
}

static inline bool bch2_snapshot_exists(struct bch_fs *c, u32 id)
{
	return bch2_snapshot_id_state(c, id) == SNAPSHOT_ID_live;
}

u32 bch2_snapshot_redundant_interior(struct bch_fs *, u32);

static inline int bch2_snapshot_is_internal_node(struct bch_fs *c, u32 id)
{
	guard(rcu)();
	const struct snapshot_t *s = snapshot_t(c, id);
	return s ? s->children[0] != 0 : bch_err_throw(c, invalid_snapshot_node);
}

static inline int bch2_snapshot_is_leaf(struct bch_fs *c, u32 id)
{
	int ret = bch2_snapshot_is_internal_node(c, id);
	if (ret < 0)
		return ret;
	return !ret;
}

static inline u32 bch2_snapshot_depth(struct bch_fs *c, u32 parent)
{
	guard(rcu)();
	return parent ? snapshot_t(c, parent)->depth + 1 : 0;
}

/*
 * We can have partially deleted snapshot nodes in the NO_KEYS state: they're
 * part of the tree of snapshots - we can't remove them from the tree of
 * snapshots at runtime - but all keys with that snapshot ID have been removed
 * and we can't create new ones. Walk to the single live descendant we can use
 * instead.
 *
 * Returns 0, with *live set to the live descendant - or *live == 0 if the
 * subtree has been fully deleted and there is none (a stray key in such a node
 * has no live home and should just be dropped).
 *
 * A missing node mid-walk means a deleted interior node's child pointer is
 * dangling - the tree is damaged - and is returned as an error rather than
 * conflated with "no live descendant", so the caller doesn't drop a key a live
 * descendant should still see.
 */
static inline int bch2_snapshot_live_descendent(struct bch_fs *c, u32 id, u32 *live)
{
	*live = 0;

	guard(rcu)();
	struct snapshot_table *t = rcu_dereference(c->snapshots.table);

	while (true) {
		const struct snapshot_t *s = __snapshot_t(t, id);
		if (!s)
			return bch_err_throw(c, invalid_snapshot_node);
		if (s->state == SNAPSHOT_ID_live) {
			*live = id;
			return 0;
		}

		if (s->children[1])	/* deleted nodes are single-child */
			return bch_err_throw(c, snapshot_multiple_descendents);
		if (!s->children[0])
			return 0;
		id = s->children[0];
	}
}

bool __bch2_snapshot_is_ancestor(struct btree_trans *, u32, u32);

static inline bool bch2_snapshot_is_ancestor(struct btree_trans *trans, u32 id, u32 ancestor)
{
	EBUG_ON(!id);
	EBUG_ON(!ancestor);

	return id == ancestor
		? true
		: __bch2_snapshot_is_ancestor(trans, id, ancestor);
}

bool bch2_snapshot_is_ancestor_early(struct bch_fs *, u32, u32);

static inline bool bch2_snapshot_has_children(struct bch_fs *c, u32 id)
{
	guard(rcu)();
	const struct snapshot_t *t = snapshot_t(c, id);
	return t && (t->children[0]|t->children[1]) != 0;
}

static inline bool snapshot_list_has_id(snapshot_id_list *s, u32 id)
{
	return darray_find(*s, id) != NULL;
}

static inline bool snapshot_list_has_ancestor(struct btree_trans *trans, snapshot_id_list *s, u32 id)
{
	return darray_find_p(*s, i, bch2_snapshot_is_ancestor(trans, id, *i)) != NULL;
}

static inline int snapshot_list_add(struct bch_fs *c, snapshot_id_list *s, u32 id)
{
	BUG_ON(snapshot_list_has_id(s, id));
	int ret = darray_push(s, id);
	if (ret)
		bch_err(c, "error reallocating snapshot_id_list (size %zu)", s->size);
	return ret;
}

static inline int snapshot_list_add_nodup(struct bch_fs *c, snapshot_id_list *s, u32 id)
{
	int ret = snapshot_list_has_id(s, id)
		? 0
		: darray_push(s, id);
	if (ret)
		bch_err(c, "error reallocating snapshot_id_list (size %zu)", s->size);
	return ret;
}

static inline int snapshot_list_merge(struct bch_fs *c, snapshot_id_list *dst, snapshot_id_list *src)
{
	darray_for_each(*src, i) {
		int ret = snapshot_list_add_nodup(c, dst, *i);
		if (ret)
			return ret;
	}

	return 0;
}

void bch2_snapshot_id_list_to_text(struct printbuf *, snapshot_id_list *);

u32 __bch2_snapshot_tree_next(struct bch_fs *, struct snapshot_table *, u32, unsigned *);
u32 bch2_snapshot_tree_next(struct bch_fs *, u32, unsigned *);

#define __for_each_snapshot_child(_c, _t, _start, _depth, _id)		\
	for (u32 _id = _start;						\
	     _id && _id <= _start;					\
	     _id = __bch2_snapshot_tree_next(_c, _t, _id, _depth))

#define for_each_snapshot_child(_c, _start, _depth, _id)		\
	for (u32 _id = _start;						\
	     _id && _id <= _start;					\
	     _id = bch2_snapshot_tree_next(_c, _id, _depth))

int bch2_snapshot_lookup(struct btree_trans *trans, u32 id,
			 struct bch_snapshot *s);
int bch2_snapshot_lookup_key(struct btree_trans *trans, u32 id,
			     struct bkey_i_snapshot *k);

/* only exported for tests: */
int bch2_snapshot_node_create(struct btree_trans *, u32,
			      u32 *, u32 *, unsigned);

int bch2_check_snapshot_trees(struct bch_fs *);
int bch2_check_snapshots_trans(struct btree_trans *);
int bch2_check_snapshots(struct bch_fs *);
int bch2_reconstruct_snapshots(struct bch_fs *);

int __bch2_check_key_has_snapshot(struct btree_trans *, struct btree_iter *, struct bkey_s_c);

static inline int bch2_check_key_has_snapshot(struct btree_trans *trans,
					      struct btree_iter *iter,
					      struct bkey_s_c k)
{
	return likely(bch2_snapshot_exists(trans->c, k.k->p.snapshot))
		? 0
		: __bch2_check_key_has_snapshot(trans, iter, k);
}

int __bch2_get_snapshot_overwrites(struct btree_trans *,
				   enum btree_id, struct bpos,
				   snapshot_id_list *);

/*
 * Get a list of snapshot IDs that have overwritten a given key:
 */
static inline int bch2_get_snapshot_overwrites(struct btree_trans *trans,
					       enum btree_id btree, struct bpos pos,
					       snapshot_id_list *s)
{
	return bch2_snapshot_has_children(trans->c, pos.snapshot)
		? __bch2_get_snapshot_overwrites(trans, btree, pos, s)
		: 0;

}

int bch2_snapshot_node_set_deleted(struct btree_trans *, u32);
int bch2_snapshot_node_delete(struct btree_trans *, u32);
int bch2_snapshot_node_undelete(struct btree_trans *, struct bkey_i_snapshot *);
int bch2_snapshot_accounting_totals(struct bch_fs *, u32, u64 *, u64 *,
				    u64 *, struct printbuf *);

int __bch2_key_has_snapshot_overwrites(struct btree_trans *, enum btree_id, struct bpos);

static inline int bch2_key_has_snapshot_overwrites(struct btree_trans *trans,
					  enum btree_id id,
					  struct bpos pos)
{
	if (!btree_type_has_snapshots(id) ||
	    bch2_snapshot_is_leaf(trans->c, pos.snapshot) > 0)
		return 0;

	return __bch2_key_has_snapshot_overwrites(trans, id, pos);
}

int bch2_delete_dead_snapshot_key(struct btree_trans *, struct btree_iter *,
				  struct bkey_s_c, u32);

int __bch2_delete_dead_snapshots(struct bch_fs *);
int bch2_delete_dead_snapshots(struct bch_fs *);
void bch2_snapshot_delete_status_to_text(struct printbuf *, struct bch_fs *);

int bch2_delete_dead_interior_snapshots(struct bch_fs *);
int bch2_snapshot_table_rebuild(struct btree_trans *);
int bch2_snapshots_read(struct bch_fs *);
void bch2_fs_snapshots_exit(struct bch_fs *);
void bch2_fs_snapshots_init_early(struct bch_fs *);
int bch2_fs_snapshots_init(struct bch_fs *);

#endif /* _BCACHEFS_SNAPSHOT_H */
