xref: /linux/fs/bcachefs/inode.c (revision 1c0ee43b2c9057473e551e2464f24f717accabf6)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "btree_key_cache.h"
5 #include "btree_write_buffer.h"
6 #include "bkey_methods.h"
7 #include "btree_update.h"
8 #include "buckets.h"
9 #include "compress.h"
10 #include "dirent.h"
11 #include "disk_accounting.h"
12 #include "error.h"
13 #include "extents.h"
14 #include "extent_update.h"
15 #include "inode.h"
16 #include "str_hash.h"
17 #include "snapshot.h"
18 #include "subvolume.h"
19 #include "varint.h"
20 
21 #include <linux/random.h>
22 
23 #include <asm/unaligned.h>
24 
25 #define x(name, ...)	#name,
26 const char * const bch2_inode_opts[] = {
27 	BCH_INODE_OPTS()
28 	NULL,
29 };
30 
31 static const char * const bch2_inode_flag_strs[] = {
32 	BCH_INODE_FLAGS()
33 	NULL
34 };
35 #undef  x
36 
37 static const u8 byte_table[8] = { 1, 2, 3, 4, 6, 8, 10, 13 };
38 
39 static int inode_decode_field(const u8 *in, const u8 *end,
40 			      u64 out[2], unsigned *out_bits)
41 {
42 	__be64 be[2] = { 0, 0 };
43 	unsigned bytes, shift;
44 	u8 *p;
45 
46 	if (in >= end)
47 		return -1;
48 
49 	if (!*in)
50 		return -1;
51 
52 	/*
53 	 * position of highest set bit indicates number of bytes:
54 	 * shift = number of bits to remove in high byte:
55 	 */
56 	shift	= 8 - __fls(*in); /* 1 <= shift <= 8 */
57 	bytes	= byte_table[shift - 1];
58 
59 	if (in + bytes > end)
60 		return -1;
61 
62 	p = (u8 *) be + 16 - bytes;
63 	memcpy(p, in, bytes);
64 	*p ^= (1 << 8) >> shift;
65 
66 	out[0] = be64_to_cpu(be[0]);
67 	out[1] = be64_to_cpu(be[1]);
68 	*out_bits = out[0] ? 64 + fls64(out[0]) : fls64(out[1]);
69 
70 	return bytes;
71 }
72 
73 static inline void bch2_inode_pack_inlined(struct bkey_inode_buf *packed,
74 					   const struct bch_inode_unpacked *inode)
75 {
76 	struct bkey_i_inode_v3 *k = &packed->inode;
77 	u8 *out = k->v.fields;
78 	u8 *end = (void *) &packed[1];
79 	u8 *last_nonzero_field = out;
80 	unsigned nr_fields = 0, last_nonzero_fieldnr = 0;
81 	unsigned bytes;
82 	int ret;
83 
84 	bkey_inode_v3_init(&packed->inode.k_i);
85 	packed->inode.k.p.offset	= inode->bi_inum;
86 	packed->inode.v.bi_journal_seq	= cpu_to_le64(inode->bi_journal_seq);
87 	packed->inode.v.bi_hash_seed	= inode->bi_hash_seed;
88 	packed->inode.v.bi_flags	= cpu_to_le64(inode->bi_flags);
89 	packed->inode.v.bi_sectors	= cpu_to_le64(inode->bi_sectors);
90 	packed->inode.v.bi_size		= cpu_to_le64(inode->bi_size);
91 	packed->inode.v.bi_version	= cpu_to_le64(inode->bi_version);
92 	SET_INODEv3_MODE(&packed->inode.v, inode->bi_mode);
93 	SET_INODEv3_FIELDS_START(&packed->inode.v, INODEv3_FIELDS_START_CUR);
94 
95 
96 #define x(_name, _bits)							\
97 	nr_fields++;							\
98 									\
99 	if (inode->_name) {						\
100 		ret = bch2_varint_encode_fast(out, inode->_name);	\
101 		out += ret;						\
102 									\
103 		if (_bits > 64)						\
104 			*out++ = 0;					\
105 									\
106 		last_nonzero_field = out;				\
107 		last_nonzero_fieldnr = nr_fields;			\
108 	} else {							\
109 		*out++ = 0;						\
110 									\
111 		if (_bits > 64)						\
112 			*out++ = 0;					\
113 	}
114 
115 	BCH_INODE_FIELDS_v3()
116 #undef  x
117 	BUG_ON(out > end);
118 
119 	out = last_nonzero_field;
120 	nr_fields = last_nonzero_fieldnr;
121 
122 	bytes = out - (u8 *) &packed->inode.v;
123 	set_bkey_val_bytes(&packed->inode.k, bytes);
124 	memset_u64s_tail(&packed->inode.v, 0, bytes);
125 
126 	SET_INODEv3_NR_FIELDS(&k->v, nr_fields);
127 
128 	if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG)) {
129 		struct bch_inode_unpacked unpacked;
130 
131 		ret = bch2_inode_unpack(bkey_i_to_s_c(&packed->inode.k_i), &unpacked);
132 		BUG_ON(ret);
133 		BUG_ON(unpacked.bi_inum		!= inode->bi_inum);
134 		BUG_ON(unpacked.bi_hash_seed	!= inode->bi_hash_seed);
135 		BUG_ON(unpacked.bi_sectors	!= inode->bi_sectors);
136 		BUG_ON(unpacked.bi_size		!= inode->bi_size);
137 		BUG_ON(unpacked.bi_version	!= inode->bi_version);
138 		BUG_ON(unpacked.bi_mode		!= inode->bi_mode);
139 
140 #define x(_name, _bits)	if (unpacked._name != inode->_name)		\
141 			panic("unpacked %llu should be %llu",		\
142 			      (u64) unpacked._name, (u64) inode->_name);
143 		BCH_INODE_FIELDS_v3()
144 #undef  x
145 	}
146 }
147 
148 void bch2_inode_pack(struct bkey_inode_buf *packed,
149 		     const struct bch_inode_unpacked *inode)
150 {
151 	bch2_inode_pack_inlined(packed, inode);
152 }
153 
154 static noinline int bch2_inode_unpack_v1(struct bkey_s_c_inode inode,
155 				struct bch_inode_unpacked *unpacked)
156 {
157 	const u8 *in = inode.v->fields;
158 	const u8 *end = bkey_val_end(inode);
159 	u64 field[2];
160 	unsigned fieldnr = 0, field_bits;
161 	int ret;
162 
163 #define x(_name, _bits)					\
164 	if (fieldnr++ == INODE_NR_FIELDS(inode.v)) {			\
165 		unsigned offset = offsetof(struct bch_inode_unpacked, _name);\
166 		memset((void *) unpacked + offset, 0,			\
167 		       sizeof(*unpacked) - offset);			\
168 		return 0;						\
169 	}								\
170 									\
171 	ret = inode_decode_field(in, end, field, &field_bits);		\
172 	if (ret < 0)							\
173 		return ret;						\
174 									\
175 	if (field_bits > sizeof(unpacked->_name) * 8)			\
176 		return -1;						\
177 									\
178 	unpacked->_name = field[1];					\
179 	in += ret;
180 
181 	BCH_INODE_FIELDS_v2()
182 #undef  x
183 
184 	/* XXX: signal if there were more fields than expected? */
185 	return 0;
186 }
187 
188 static int bch2_inode_unpack_v2(struct bch_inode_unpacked *unpacked,
189 				const u8 *in, const u8 *end,
190 				unsigned nr_fields)
191 {
192 	unsigned fieldnr = 0;
193 	int ret;
194 	u64 v[2];
195 
196 #define x(_name, _bits)							\
197 	if (fieldnr < nr_fields) {					\
198 		ret = bch2_varint_decode_fast(in, end, &v[0]);		\
199 		if (ret < 0)						\
200 			return ret;					\
201 		in += ret;						\
202 									\
203 		if (_bits > 64) {					\
204 			ret = bch2_varint_decode_fast(in, end, &v[1]);	\
205 			if (ret < 0)					\
206 				return ret;				\
207 			in += ret;					\
208 		} else {						\
209 			v[1] = 0;					\
210 		}							\
211 	} else {							\
212 		v[0] = v[1] = 0;					\
213 	}								\
214 									\
215 	unpacked->_name = v[0];						\
216 	if (v[1] || v[0] != unpacked->_name)				\
217 		return -1;						\
218 	fieldnr++;
219 
220 	BCH_INODE_FIELDS_v2()
221 #undef  x
222 
223 	/* XXX: signal if there were more fields than expected? */
224 	return 0;
225 }
226 
227 static int bch2_inode_unpack_v3(struct bkey_s_c k,
228 				struct bch_inode_unpacked *unpacked)
229 {
230 	struct bkey_s_c_inode_v3 inode = bkey_s_c_to_inode_v3(k);
231 	const u8 *in = inode.v->fields;
232 	const u8 *end = bkey_val_end(inode);
233 	unsigned nr_fields = INODEv3_NR_FIELDS(inode.v);
234 	unsigned fieldnr = 0;
235 	int ret;
236 	u64 v[2];
237 
238 	unpacked->bi_inum	= inode.k->p.offset;
239 	unpacked->bi_journal_seq= le64_to_cpu(inode.v->bi_journal_seq);
240 	unpacked->bi_hash_seed	= inode.v->bi_hash_seed;
241 	unpacked->bi_flags	= le64_to_cpu(inode.v->bi_flags);
242 	unpacked->bi_sectors	= le64_to_cpu(inode.v->bi_sectors);
243 	unpacked->bi_size	= le64_to_cpu(inode.v->bi_size);
244 	unpacked->bi_version	= le64_to_cpu(inode.v->bi_version);
245 	unpacked->bi_mode	= INODEv3_MODE(inode.v);
246 
247 #define x(_name, _bits)							\
248 	if (fieldnr < nr_fields) {					\
249 		ret = bch2_varint_decode_fast(in, end, &v[0]);		\
250 		if (ret < 0)						\
251 			return ret;					\
252 		in += ret;						\
253 									\
254 		if (_bits > 64) {					\
255 			ret = bch2_varint_decode_fast(in, end, &v[1]);	\
256 			if (ret < 0)					\
257 				return ret;				\
258 			in += ret;					\
259 		} else {						\
260 			v[1] = 0;					\
261 		}							\
262 	} else {							\
263 		v[0] = v[1] = 0;					\
264 	}								\
265 									\
266 	unpacked->_name = v[0];						\
267 	if (v[1] || v[0] != unpacked->_name)				\
268 		return -1;						\
269 	fieldnr++;
270 
271 	BCH_INODE_FIELDS_v3()
272 #undef  x
273 
274 	/* XXX: signal if there were more fields than expected? */
275 	return 0;
276 }
277 
278 static noinline int bch2_inode_unpack_slowpath(struct bkey_s_c k,
279 					       struct bch_inode_unpacked *unpacked)
280 {
281 	memset(unpacked, 0, sizeof(*unpacked));
282 
283 	switch (k.k->type) {
284 	case KEY_TYPE_inode: {
285 		struct bkey_s_c_inode inode = bkey_s_c_to_inode(k);
286 
287 		unpacked->bi_inum	= inode.k->p.offset;
288 		unpacked->bi_journal_seq= 0;
289 		unpacked->bi_hash_seed	= inode.v->bi_hash_seed;
290 		unpacked->bi_flags	= le32_to_cpu(inode.v->bi_flags);
291 		unpacked->bi_mode	= le16_to_cpu(inode.v->bi_mode);
292 
293 		if (INODE_NEW_VARINT(inode.v)) {
294 			return bch2_inode_unpack_v2(unpacked, inode.v->fields,
295 						    bkey_val_end(inode),
296 						    INODE_NR_FIELDS(inode.v));
297 		} else {
298 			return bch2_inode_unpack_v1(inode, unpacked);
299 		}
300 		break;
301 	}
302 	case KEY_TYPE_inode_v2: {
303 		struct bkey_s_c_inode_v2 inode = bkey_s_c_to_inode_v2(k);
304 
305 		unpacked->bi_inum	= inode.k->p.offset;
306 		unpacked->bi_journal_seq= le64_to_cpu(inode.v->bi_journal_seq);
307 		unpacked->bi_hash_seed	= inode.v->bi_hash_seed;
308 		unpacked->bi_flags	= le64_to_cpu(inode.v->bi_flags);
309 		unpacked->bi_mode	= le16_to_cpu(inode.v->bi_mode);
310 
311 		return bch2_inode_unpack_v2(unpacked, inode.v->fields,
312 					    bkey_val_end(inode),
313 					    INODEv2_NR_FIELDS(inode.v));
314 	}
315 	default:
316 		BUG();
317 	}
318 }
319 
320 int bch2_inode_unpack(struct bkey_s_c k,
321 		      struct bch_inode_unpacked *unpacked)
322 {
323 	unpacked->bi_snapshot = k.k->p.snapshot;
324 
325 	return likely(k.k->type == KEY_TYPE_inode_v3)
326 		? bch2_inode_unpack_v3(k, unpacked)
327 		: bch2_inode_unpack_slowpath(k, unpacked);
328 }
329 
330 int bch2_inode_peek_nowarn(struct btree_trans *trans,
331 		    struct btree_iter *iter,
332 		    struct bch_inode_unpacked *inode,
333 		    subvol_inum inum, unsigned flags)
334 {
335 	struct bkey_s_c k;
336 	u32 snapshot;
337 	int ret;
338 
339 	ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
340 	if (ret)
341 		return ret;
342 
343 	k = bch2_bkey_get_iter(trans, iter, BTREE_ID_inodes,
344 			       SPOS(0, inum.inum, snapshot),
345 			       flags|BTREE_ITER_cached);
346 	ret = bkey_err(k);
347 	if (ret)
348 		return ret;
349 
350 	ret = bkey_is_inode(k.k) ? 0 : -BCH_ERR_ENOENT_inode;
351 	if (ret)
352 		goto err;
353 
354 	ret = bch2_inode_unpack(k, inode);
355 	if (ret)
356 		goto err;
357 
358 	return 0;
359 err:
360 	bch2_trans_iter_exit(trans, iter);
361 	return ret;
362 }
363 
364 int bch2_inode_peek(struct btree_trans *trans,
365 		    struct btree_iter *iter,
366 		    struct bch_inode_unpacked *inode,
367 		    subvol_inum inum, unsigned flags)
368 {
369 	int ret = bch2_inode_peek_nowarn(trans, iter, inode, inum, flags);
370 	bch_err_msg(trans->c, ret, "looking up inum %llu:%llu:", inum.subvol, inum.inum);
371 	return ret;
372 }
373 
374 int bch2_inode_write_flags(struct btree_trans *trans,
375 		     struct btree_iter *iter,
376 		     struct bch_inode_unpacked *inode,
377 		     enum btree_iter_update_trigger_flags flags)
378 {
379 	struct bkey_inode_buf *inode_p;
380 
381 	inode_p = bch2_trans_kmalloc(trans, sizeof(*inode_p));
382 	if (IS_ERR(inode_p))
383 		return PTR_ERR(inode_p);
384 
385 	bch2_inode_pack_inlined(inode_p, inode);
386 	inode_p->inode.k.p.snapshot = iter->snapshot;
387 	return bch2_trans_update(trans, iter, &inode_p->inode.k_i, flags);
388 }
389 
390 int __bch2_fsck_write_inode(struct btree_trans *trans,
391 			 struct bch_inode_unpacked *inode,
392 			 u32 snapshot)
393 {
394 	struct bkey_inode_buf *inode_p =
395 		bch2_trans_kmalloc(trans, sizeof(*inode_p));
396 
397 	if (IS_ERR(inode_p))
398 		return PTR_ERR(inode_p);
399 
400 	bch2_inode_pack(inode_p, inode);
401 	inode_p->inode.k.p.snapshot = snapshot;
402 
403 	return bch2_btree_insert_nonextent(trans, BTREE_ID_inodes,
404 				&inode_p->inode.k_i,
405 				BTREE_UPDATE_internal_snapshot_node);
406 }
407 
408 int bch2_fsck_write_inode(struct btree_trans *trans,
409 			    struct bch_inode_unpacked *inode,
410 			    u32 snapshot)
411 {
412 	int ret = commit_do(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc,
413 			    __bch2_fsck_write_inode(trans, inode, snapshot));
414 	bch_err_fn(trans->c, ret);
415 	return ret;
416 }
417 
418 struct bkey_i *bch2_inode_to_v3(struct btree_trans *trans, struct bkey_i *k)
419 {
420 	struct bch_inode_unpacked u;
421 	struct bkey_inode_buf *inode_p;
422 	int ret;
423 
424 	if (!bkey_is_inode(&k->k))
425 		return ERR_PTR(-ENOENT);
426 
427 	inode_p = bch2_trans_kmalloc(trans, sizeof(*inode_p));
428 	if (IS_ERR(inode_p))
429 		return ERR_CAST(inode_p);
430 
431 	ret = bch2_inode_unpack(bkey_i_to_s_c(k), &u);
432 	if (ret)
433 		return ERR_PTR(ret);
434 
435 	bch2_inode_pack(inode_p, &u);
436 	return &inode_p->inode.k_i;
437 }
438 
439 static int __bch2_inode_validate(struct bch_fs *c, struct bkey_s_c k,
440 				 enum bch_validate_flags flags)
441 {
442 	struct bch_inode_unpacked unpacked;
443 	int ret = 0;
444 
445 	bkey_fsck_err_on(k.k->p.inode,
446 			 c, inode_pos_inode_nonzero,
447 			 "nonzero k.p.inode");
448 
449 	bkey_fsck_err_on(k.k->p.offset < BLOCKDEV_INODE_MAX,
450 			 c, inode_pos_blockdev_range,
451 			 "fs inode in blockdev range");
452 
453 	bkey_fsck_err_on(bch2_inode_unpack(k, &unpacked),
454 			 c, inode_unpack_error,
455 			 "invalid variable length fields");
456 
457 	bkey_fsck_err_on(unpacked.bi_data_checksum >= BCH_CSUM_OPT_NR + 1,
458 			 c, inode_checksum_type_invalid,
459 			 "invalid data checksum type (%u >= %u",
460 			 unpacked.bi_data_checksum, BCH_CSUM_OPT_NR + 1);
461 
462 	bkey_fsck_err_on(unpacked.bi_compression &&
463 			 !bch2_compression_opt_valid(unpacked.bi_compression - 1),
464 			 c, inode_compression_type_invalid,
465 			 "invalid compression opt %u", unpacked.bi_compression - 1);
466 
467 	bkey_fsck_err_on((unpacked.bi_flags & BCH_INODE_unlinked) &&
468 			 unpacked.bi_nlink != 0,
469 			 c, inode_unlinked_but_nlink_nonzero,
470 			 "flagged as unlinked but bi_nlink != 0");
471 
472 	bkey_fsck_err_on(unpacked.bi_subvol && !S_ISDIR(unpacked.bi_mode),
473 			 c, inode_subvol_root_but_not_dir,
474 			 "subvolume root but not a directory");
475 fsck_err:
476 	return ret;
477 }
478 
479 int bch2_inode_validate(struct bch_fs *c, struct bkey_s_c k,
480 			enum bch_validate_flags flags)
481 {
482 	struct bkey_s_c_inode inode = bkey_s_c_to_inode(k);
483 	int ret = 0;
484 
485 	bkey_fsck_err_on(INODE_STR_HASH(inode.v) >= BCH_STR_HASH_NR,
486 			 c, inode_str_hash_invalid,
487 			 "invalid str hash type (%llu >= %u)",
488 			 INODE_STR_HASH(inode.v), BCH_STR_HASH_NR);
489 
490 	ret = __bch2_inode_validate(c, k, flags);
491 fsck_err:
492 	return ret;
493 }
494 
495 int bch2_inode_v2_validate(struct bch_fs *c, struct bkey_s_c k,
496 			   enum bch_validate_flags flags)
497 {
498 	struct bkey_s_c_inode_v2 inode = bkey_s_c_to_inode_v2(k);
499 	int ret = 0;
500 
501 	bkey_fsck_err_on(INODEv2_STR_HASH(inode.v) >= BCH_STR_HASH_NR,
502 			 c, inode_str_hash_invalid,
503 			 "invalid str hash type (%llu >= %u)",
504 			 INODEv2_STR_HASH(inode.v), BCH_STR_HASH_NR);
505 
506 	ret = __bch2_inode_validate(c, k, flags);
507 fsck_err:
508 	return ret;
509 }
510 
511 int bch2_inode_v3_validate(struct bch_fs *c, struct bkey_s_c k,
512 			   enum bch_validate_flags flags)
513 {
514 	struct bkey_s_c_inode_v3 inode = bkey_s_c_to_inode_v3(k);
515 	int ret = 0;
516 
517 	bkey_fsck_err_on(INODEv3_FIELDS_START(inode.v) < INODEv3_FIELDS_START_INITIAL ||
518 			 INODEv3_FIELDS_START(inode.v) > bkey_val_u64s(inode.k),
519 			 c, inode_v3_fields_start_bad,
520 			 "invalid fields_start (got %llu, min %u max %zu)",
521 			 INODEv3_FIELDS_START(inode.v),
522 			 INODEv3_FIELDS_START_INITIAL,
523 			 bkey_val_u64s(inode.k));
524 
525 	bkey_fsck_err_on(INODEv3_STR_HASH(inode.v) >= BCH_STR_HASH_NR,
526 			 c, inode_str_hash_invalid,
527 			 "invalid str hash type (%llu >= %u)",
528 			 INODEv3_STR_HASH(inode.v), BCH_STR_HASH_NR);
529 
530 	ret = __bch2_inode_validate(c, k, flags);
531 fsck_err:
532 	return ret;
533 }
534 
535 static void __bch2_inode_unpacked_to_text(struct printbuf *out,
536 					  struct bch_inode_unpacked *inode)
537 {
538 	prt_printf(out, "\n");
539 	printbuf_indent_add(out, 2);
540 	prt_printf(out, "mode=%o\n", inode->bi_mode);
541 
542 	prt_str(out, "flags=");
543 	prt_bitflags(out, bch2_inode_flag_strs, inode->bi_flags & ((1U << 20) - 1));
544 	prt_printf(out, "(%x)\n", inode->bi_flags);
545 
546 	prt_printf(out, "journal_seq=%llu\n",	inode->bi_journal_seq);
547 	prt_printf(out, "bi_size=%llu\n",	inode->bi_size);
548 	prt_printf(out, "bi_sectors=%llu\n",	inode->bi_sectors);
549 	prt_printf(out, "bi_version=%llu\n",	inode->bi_version);
550 
551 #define x(_name, _bits)						\
552 	prt_printf(out, #_name "=%llu\n", (u64) inode->_name);
553 	BCH_INODE_FIELDS_v3()
554 #undef  x
555 
556 	bch2_printbuf_strip_trailing_newline(out);
557 	printbuf_indent_sub(out, 2);
558 }
559 
560 void bch2_inode_unpacked_to_text(struct printbuf *out, struct bch_inode_unpacked *inode)
561 {
562 	prt_printf(out, "inum: %llu:%u ", inode->bi_inum, inode->bi_snapshot);
563 	__bch2_inode_unpacked_to_text(out, inode);
564 }
565 
566 void bch2_inode_to_text(struct printbuf *out, struct bch_fs *c, struct bkey_s_c k)
567 {
568 	struct bch_inode_unpacked inode;
569 
570 	if (bch2_inode_unpack(k, &inode)) {
571 		prt_printf(out, "(unpack error)");
572 		return;
573 	}
574 
575 	__bch2_inode_unpacked_to_text(out, &inode);
576 }
577 
578 static inline u64 bkey_inode_flags(struct bkey_s_c k)
579 {
580 	switch (k.k->type) {
581 	case KEY_TYPE_inode:
582 		return le32_to_cpu(bkey_s_c_to_inode(k).v->bi_flags);
583 	case KEY_TYPE_inode_v2:
584 		return le64_to_cpu(bkey_s_c_to_inode_v2(k).v->bi_flags);
585 	case KEY_TYPE_inode_v3:
586 		return le64_to_cpu(bkey_s_c_to_inode_v3(k).v->bi_flags);
587 	default:
588 		return 0;
589 	}
590 }
591 
592 static inline bool bkey_is_deleted_inode(struct bkey_s_c k)
593 {
594 	return bkey_inode_flags(k) & BCH_INODE_unlinked;
595 }
596 
597 int bch2_trigger_inode(struct btree_trans *trans,
598 		       enum btree_id btree_id, unsigned level,
599 		       struct bkey_s_c old,
600 		       struct bkey_s new,
601 		       enum btree_iter_update_trigger_flags flags)
602 {
603 	if ((flags & BTREE_TRIGGER_atomic) && (flags & BTREE_TRIGGER_insert)) {
604 		BUG_ON(!trans->journal_res.seq);
605 		bkey_s_to_inode_v3(new).v->bi_journal_seq = cpu_to_le64(trans->journal_res.seq);
606 	}
607 
608 	s64 nr = bkey_is_inode(new.k) - bkey_is_inode(old.k);
609 	if ((flags & (BTREE_TRIGGER_transactional|BTREE_TRIGGER_gc)) && nr) {
610 		struct disk_accounting_pos acc = { .type = BCH_DISK_ACCOUNTING_nr_inodes };
611 		int ret = bch2_disk_accounting_mod(trans, &acc, &nr, 1, flags & BTREE_TRIGGER_gc);
612 		if (ret)
613 			return ret;
614 	}
615 
616 	int deleted_delta =	(int) bkey_is_deleted_inode(new.s_c) -
617 				(int) bkey_is_deleted_inode(old);
618 	if ((flags & BTREE_TRIGGER_transactional) && deleted_delta) {
619 		int ret = bch2_btree_bit_mod_buffered(trans, BTREE_ID_deleted_inodes,
620 						      new.k->p, deleted_delta > 0);
621 		if (ret)
622 			return ret;
623 	}
624 
625 	return 0;
626 }
627 
628 int bch2_inode_generation_validate(struct bch_fs *c, struct bkey_s_c k,
629 				   enum bch_validate_flags flags)
630 {
631 	int ret = 0;
632 
633 	bkey_fsck_err_on(k.k->p.inode,
634 			 c, inode_pos_inode_nonzero,
635 			 "nonzero k.p.inode");
636 fsck_err:
637 	return ret;
638 }
639 
640 void bch2_inode_generation_to_text(struct printbuf *out, struct bch_fs *c,
641 				   struct bkey_s_c k)
642 {
643 	struct bkey_s_c_inode_generation gen = bkey_s_c_to_inode_generation(k);
644 
645 	prt_printf(out, "generation: %u", le32_to_cpu(gen.v->bi_generation));
646 }
647 
648 void bch2_inode_init_early(struct bch_fs *c,
649 			   struct bch_inode_unpacked *inode_u)
650 {
651 	enum bch_str_hash_type str_hash =
652 		bch2_str_hash_opt_to_type(c, c->opts.str_hash);
653 
654 	memset(inode_u, 0, sizeof(*inode_u));
655 
656 	/* ick */
657 	inode_u->bi_flags |= str_hash << INODE_STR_HASH_OFFSET;
658 	get_random_bytes(&inode_u->bi_hash_seed,
659 			 sizeof(inode_u->bi_hash_seed));
660 }
661 
662 void bch2_inode_init_late(struct bch_inode_unpacked *inode_u, u64 now,
663 			  uid_t uid, gid_t gid, umode_t mode, dev_t rdev,
664 			  struct bch_inode_unpacked *parent)
665 {
666 	inode_u->bi_mode	= mode;
667 	inode_u->bi_uid		= uid;
668 	inode_u->bi_gid		= gid;
669 	inode_u->bi_dev		= rdev;
670 	inode_u->bi_atime	= now;
671 	inode_u->bi_mtime	= now;
672 	inode_u->bi_ctime	= now;
673 	inode_u->bi_otime	= now;
674 
675 	if (parent && parent->bi_mode & S_ISGID) {
676 		inode_u->bi_gid = parent->bi_gid;
677 		if (S_ISDIR(mode))
678 			inode_u->bi_mode |= S_ISGID;
679 	}
680 
681 	if (parent) {
682 #define x(_name, ...)	inode_u->bi_##_name = parent->bi_##_name;
683 		BCH_INODE_OPTS()
684 #undef x
685 	}
686 }
687 
688 void bch2_inode_init(struct bch_fs *c, struct bch_inode_unpacked *inode_u,
689 		     uid_t uid, gid_t gid, umode_t mode, dev_t rdev,
690 		     struct bch_inode_unpacked *parent)
691 {
692 	bch2_inode_init_early(c, inode_u);
693 	bch2_inode_init_late(inode_u, bch2_current_time(c),
694 			     uid, gid, mode, rdev, parent);
695 }
696 
697 static inline u32 bkey_generation(struct bkey_s_c k)
698 {
699 	switch (k.k->type) {
700 	case KEY_TYPE_inode:
701 	case KEY_TYPE_inode_v2:
702 		BUG();
703 	case KEY_TYPE_inode_generation:
704 		return le32_to_cpu(bkey_s_c_to_inode_generation(k).v->bi_generation);
705 	default:
706 		return 0;
707 	}
708 }
709 
710 /*
711  * This just finds an empty slot:
712  */
713 int bch2_inode_create(struct btree_trans *trans,
714 		      struct btree_iter *iter,
715 		      struct bch_inode_unpacked *inode_u,
716 		      u32 snapshot, u64 cpu)
717 {
718 	struct bch_fs *c = trans->c;
719 	struct bkey_s_c k;
720 	u64 min, max, start, pos, *hint;
721 	int ret = 0;
722 	unsigned bits = (c->opts.inodes_32bit ? 31 : 63);
723 
724 	if (c->opts.shard_inode_numbers) {
725 		bits -= c->inode_shard_bits;
726 
727 		min = (cpu << bits);
728 		max = (cpu << bits) | ~(ULLONG_MAX << bits);
729 
730 		min = max_t(u64, min, BLOCKDEV_INODE_MAX);
731 		hint = c->unused_inode_hints + cpu;
732 	} else {
733 		min = BLOCKDEV_INODE_MAX;
734 		max = ~(ULLONG_MAX << bits);
735 		hint = c->unused_inode_hints;
736 	}
737 
738 	start = READ_ONCE(*hint);
739 
740 	if (start >= max || start < min)
741 		start = min;
742 
743 	pos = start;
744 	bch2_trans_iter_init(trans, iter, BTREE_ID_inodes, POS(0, pos),
745 			     BTREE_ITER_all_snapshots|
746 			     BTREE_ITER_intent);
747 again:
748 	while ((k = bch2_btree_iter_peek(iter)).k &&
749 	       !(ret = bkey_err(k)) &&
750 	       bkey_lt(k.k->p, POS(0, max))) {
751 		if (pos < iter->pos.offset)
752 			goto found_slot;
753 
754 		/*
755 		 * We don't need to iterate over keys in every snapshot once
756 		 * we've found just one:
757 		 */
758 		pos = iter->pos.offset + 1;
759 		bch2_btree_iter_set_pos(iter, POS(0, pos));
760 	}
761 
762 	if (!ret && pos < max)
763 		goto found_slot;
764 
765 	if (!ret && start == min)
766 		ret = -BCH_ERR_ENOSPC_inode_create;
767 
768 	if (ret) {
769 		bch2_trans_iter_exit(trans, iter);
770 		return ret;
771 	}
772 
773 	/* Retry from start */
774 	pos = start = min;
775 	bch2_btree_iter_set_pos(iter, POS(0, pos));
776 	goto again;
777 found_slot:
778 	bch2_btree_iter_set_pos(iter, SPOS(0, pos, snapshot));
779 	k = bch2_btree_iter_peek_slot(iter);
780 	ret = bkey_err(k);
781 	if (ret) {
782 		bch2_trans_iter_exit(trans, iter);
783 		return ret;
784 	}
785 
786 	*hint			= k.k->p.offset;
787 	inode_u->bi_inum	= k.k->p.offset;
788 	inode_u->bi_generation	= bkey_generation(k);
789 	return 0;
790 }
791 
792 static int bch2_inode_delete_keys(struct btree_trans *trans,
793 				  subvol_inum inum, enum btree_id id)
794 {
795 	struct btree_iter iter;
796 	struct bkey_s_c k;
797 	struct bkey_i delete;
798 	struct bpos end = POS(inum.inum, U64_MAX);
799 	u32 snapshot;
800 	int ret = 0;
801 
802 	/*
803 	 * We're never going to be deleting partial extents, no need to use an
804 	 * extent iterator:
805 	 */
806 	bch2_trans_iter_init(trans, &iter, id, POS(inum.inum, 0),
807 			     BTREE_ITER_intent);
808 
809 	while (1) {
810 		bch2_trans_begin(trans);
811 
812 		ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
813 		if (ret)
814 			goto err;
815 
816 		bch2_btree_iter_set_snapshot(&iter, snapshot);
817 
818 		k = bch2_btree_iter_peek_upto(&iter, end);
819 		ret = bkey_err(k);
820 		if (ret)
821 			goto err;
822 
823 		if (!k.k)
824 			break;
825 
826 		bkey_init(&delete.k);
827 		delete.k.p = iter.pos;
828 
829 		if (iter.flags & BTREE_ITER_is_extents)
830 			bch2_key_resize(&delete.k,
831 					bpos_min(end, k.k->p).offset -
832 					iter.pos.offset);
833 
834 		ret = bch2_trans_update(trans, &iter, &delete, 0) ?:
835 		      bch2_trans_commit(trans, NULL, NULL,
836 					BCH_TRANS_COMMIT_no_enospc);
837 err:
838 		if (ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart))
839 			break;
840 	}
841 
842 	bch2_trans_iter_exit(trans, &iter);
843 	return ret;
844 }
845 
846 int bch2_inode_rm(struct bch_fs *c, subvol_inum inum)
847 {
848 	struct btree_trans *trans = bch2_trans_get(c);
849 	struct btree_iter iter = { NULL };
850 	struct bkey_i_inode_generation delete;
851 	struct bch_inode_unpacked inode_u;
852 	struct bkey_s_c k;
853 	u32 snapshot;
854 	int ret;
855 
856 	/*
857 	 * If this was a directory, there shouldn't be any real dirents left -
858 	 * but there could be whiteouts (from hash collisions) that we should
859 	 * delete:
860 	 *
861 	 * XXX: the dirent could ideally would delete whiteouts when they're no
862 	 * longer needed
863 	 */
864 	ret   = bch2_inode_delete_keys(trans, inum, BTREE_ID_extents) ?:
865 		bch2_inode_delete_keys(trans, inum, BTREE_ID_xattrs) ?:
866 		bch2_inode_delete_keys(trans, inum, BTREE_ID_dirents);
867 	if (ret)
868 		goto err;
869 retry:
870 	bch2_trans_begin(trans);
871 
872 	ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
873 	if (ret)
874 		goto err;
875 
876 	k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_inodes,
877 			       SPOS(0, inum.inum, snapshot),
878 			       BTREE_ITER_intent|BTREE_ITER_cached);
879 	ret = bkey_err(k);
880 	if (ret)
881 		goto err;
882 
883 	if (!bkey_is_inode(k.k)) {
884 		bch2_fs_inconsistent(c,
885 				     "inode %llu:%u not found when deleting",
886 				     inum.inum, snapshot);
887 		ret = -EIO;
888 		goto err;
889 	}
890 
891 	bch2_inode_unpack(k, &inode_u);
892 
893 	bkey_inode_generation_init(&delete.k_i);
894 	delete.k.p = iter.pos;
895 	delete.v.bi_generation = cpu_to_le32(inode_u.bi_generation + 1);
896 
897 	ret   = bch2_trans_update(trans, &iter, &delete.k_i, 0) ?:
898 		bch2_trans_commit(trans, NULL, NULL,
899 				BCH_TRANS_COMMIT_no_enospc);
900 err:
901 	bch2_trans_iter_exit(trans, &iter);
902 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
903 		goto retry;
904 
905 	bch2_trans_put(trans);
906 	return ret;
907 }
908 
909 int bch2_inode_find_by_inum_nowarn_trans(struct btree_trans *trans,
910 				  subvol_inum inum,
911 				  struct bch_inode_unpacked *inode)
912 {
913 	struct btree_iter iter;
914 	int ret;
915 
916 	ret = bch2_inode_peek_nowarn(trans, &iter, inode, inum, 0);
917 	if (!ret)
918 		bch2_trans_iter_exit(trans, &iter);
919 	return ret;
920 }
921 
922 int bch2_inode_find_by_inum_trans(struct btree_trans *trans,
923 				  subvol_inum inum,
924 				  struct bch_inode_unpacked *inode)
925 {
926 	struct btree_iter iter;
927 	int ret;
928 
929 	ret = bch2_inode_peek(trans, &iter, inode, inum, 0);
930 	if (!ret)
931 		bch2_trans_iter_exit(trans, &iter);
932 	return ret;
933 }
934 
935 int bch2_inode_find_by_inum(struct bch_fs *c, subvol_inum inum,
936 			    struct bch_inode_unpacked *inode)
937 {
938 	return bch2_trans_do(c, NULL, NULL, 0,
939 		bch2_inode_find_by_inum_trans(trans, inum, inode));
940 }
941 
942 int bch2_inode_nlink_inc(struct bch_inode_unpacked *bi)
943 {
944 	if (bi->bi_flags & BCH_INODE_unlinked)
945 		bi->bi_flags &= ~BCH_INODE_unlinked;
946 	else {
947 		if (bi->bi_nlink == U32_MAX)
948 			return -EINVAL;
949 
950 		bi->bi_nlink++;
951 	}
952 
953 	return 0;
954 }
955 
956 void bch2_inode_nlink_dec(struct btree_trans *trans, struct bch_inode_unpacked *bi)
957 {
958 	if (bi->bi_nlink && (bi->bi_flags & BCH_INODE_unlinked)) {
959 		bch2_trans_inconsistent(trans, "inode %llu unlinked but link count nonzero",
960 					bi->bi_inum);
961 		return;
962 	}
963 
964 	if (bi->bi_flags & BCH_INODE_unlinked) {
965 		bch2_trans_inconsistent(trans, "inode %llu link count underflow", bi->bi_inum);
966 		return;
967 	}
968 
969 	if (bi->bi_nlink)
970 		bi->bi_nlink--;
971 	else
972 		bi->bi_flags |= BCH_INODE_unlinked;
973 }
974 
975 struct bch_opts bch2_inode_opts_to_opts(struct bch_inode_unpacked *inode)
976 {
977 	struct bch_opts ret = { 0 };
978 #define x(_name, _bits)							\
979 	if (inode->bi_##_name)						\
980 		opt_set(ret, _name, inode->bi_##_name - 1);
981 	BCH_INODE_OPTS()
982 #undef x
983 	return ret;
984 }
985 
986 void bch2_inode_opts_get(struct bch_io_opts *opts, struct bch_fs *c,
987 			 struct bch_inode_unpacked *inode)
988 {
989 #define x(_name, _bits)		opts->_name = inode_opt_get(c, inode, _name);
990 	BCH_INODE_OPTS()
991 #undef x
992 
993 	if (opts->nocow)
994 		opts->compression = opts->background_compression = opts->data_checksum = opts->erasure_code = 0;
995 }
996 
997 int bch2_inum_opts_get(struct btree_trans *trans, subvol_inum inum, struct bch_io_opts *opts)
998 {
999 	struct bch_inode_unpacked inode;
1000 	int ret = lockrestart_do(trans, bch2_inode_find_by_inum_trans(trans, inum, &inode));
1001 
1002 	if (ret)
1003 		return ret;
1004 
1005 	bch2_inode_opts_get(opts, trans->c, &inode);
1006 	return 0;
1007 }
1008 
1009 int bch2_inode_rm_snapshot(struct btree_trans *trans, u64 inum, u32 snapshot)
1010 {
1011 	struct bch_fs *c = trans->c;
1012 	struct btree_iter iter = { NULL };
1013 	struct bkey_i_inode_generation delete;
1014 	struct bch_inode_unpacked inode_u;
1015 	struct bkey_s_c k;
1016 	int ret;
1017 
1018 	do {
1019 		ret   = bch2_btree_delete_range_trans(trans, BTREE_ID_extents,
1020 						      SPOS(inum, 0, snapshot),
1021 						      SPOS(inum, U64_MAX, snapshot),
1022 						      0, NULL) ?:
1023 			bch2_btree_delete_range_trans(trans, BTREE_ID_dirents,
1024 						      SPOS(inum, 0, snapshot),
1025 						      SPOS(inum, U64_MAX, snapshot),
1026 						      0, NULL) ?:
1027 			bch2_btree_delete_range_trans(trans, BTREE_ID_xattrs,
1028 						      SPOS(inum, 0, snapshot),
1029 						      SPOS(inum, U64_MAX, snapshot),
1030 						      0, NULL);
1031 	} while (ret == -BCH_ERR_transaction_restart_nested);
1032 	if (ret)
1033 		goto err;
1034 retry:
1035 	bch2_trans_begin(trans);
1036 
1037 	k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_inodes,
1038 			       SPOS(0, inum, snapshot), BTREE_ITER_intent);
1039 	ret = bkey_err(k);
1040 	if (ret)
1041 		goto err;
1042 
1043 	if (!bkey_is_inode(k.k)) {
1044 		bch2_fs_inconsistent(c,
1045 				     "inode %llu:%u not found when deleting",
1046 				     inum, snapshot);
1047 		ret = -EIO;
1048 		goto err;
1049 	}
1050 
1051 	bch2_inode_unpack(k, &inode_u);
1052 
1053 	/* Subvolume root? */
1054 	if (inode_u.bi_subvol)
1055 		bch_warn(c, "deleting inode %llu marked as unlinked, but also a subvolume root!?", inode_u.bi_inum);
1056 
1057 	bkey_inode_generation_init(&delete.k_i);
1058 	delete.k.p = iter.pos;
1059 	delete.v.bi_generation = cpu_to_le32(inode_u.bi_generation + 1);
1060 
1061 	ret   = bch2_trans_update(trans, &iter, &delete.k_i, 0) ?:
1062 		bch2_trans_commit(trans, NULL, NULL,
1063 				BCH_TRANS_COMMIT_no_enospc);
1064 err:
1065 	bch2_trans_iter_exit(trans, &iter);
1066 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1067 		goto retry;
1068 
1069 	return ret ?: -BCH_ERR_transaction_restart_nested;
1070 }
1071 
1072 static int may_delete_deleted_inode(struct btree_trans *trans,
1073 				    struct btree_iter *iter,
1074 				    struct bpos pos,
1075 				    bool *need_another_pass)
1076 {
1077 	struct bch_fs *c = trans->c;
1078 	struct btree_iter inode_iter;
1079 	struct bkey_s_c k;
1080 	struct bch_inode_unpacked inode;
1081 	int ret;
1082 
1083 	k = bch2_bkey_get_iter(trans, &inode_iter, BTREE_ID_inodes, pos, BTREE_ITER_cached);
1084 	ret = bkey_err(k);
1085 	if (ret)
1086 		return ret;
1087 
1088 	ret = bkey_is_inode(k.k) ? 0 : -BCH_ERR_ENOENT_inode;
1089 	if (fsck_err_on(!bkey_is_inode(k.k),
1090 			trans, deleted_inode_missing,
1091 			"nonexistent inode %llu:%u in deleted_inodes btree",
1092 			pos.offset, pos.snapshot))
1093 		goto delete;
1094 
1095 	ret = bch2_inode_unpack(k, &inode);
1096 	if (ret)
1097 		goto out;
1098 
1099 	if (S_ISDIR(inode.bi_mode)) {
1100 		ret = bch2_empty_dir_snapshot(trans, pos.offset, 0, pos.snapshot);
1101 		if (fsck_err_on(bch2_err_matches(ret, ENOTEMPTY),
1102 				trans, deleted_inode_is_dir,
1103 				"non empty directory %llu:%u in deleted_inodes btree",
1104 				pos.offset, pos.snapshot))
1105 			goto delete;
1106 		if (ret)
1107 			goto out;
1108 	}
1109 
1110 	if (fsck_err_on(!(inode.bi_flags & BCH_INODE_unlinked),
1111 			trans, deleted_inode_not_unlinked,
1112 			"non-deleted inode %llu:%u in deleted_inodes btree",
1113 			pos.offset, pos.snapshot))
1114 		goto delete;
1115 
1116 	if (test_bit(BCH_FS_clean_recovery, &c->flags) &&
1117 	    !fsck_err(trans, deleted_inode_but_clean,
1118 		      "filesystem marked as clean but have deleted inode %llu:%u",
1119 		      pos.offset, pos.snapshot)) {
1120 		ret = 0;
1121 		goto out;
1122 	}
1123 
1124 	if (bch2_snapshot_is_internal_node(c, pos.snapshot)) {
1125 		struct bpos new_min_pos;
1126 
1127 		ret = bch2_propagate_key_to_snapshot_leaves(trans, inode_iter.btree_id, k, &new_min_pos);
1128 		if (ret)
1129 			goto out;
1130 
1131 		inode.bi_flags &= ~BCH_INODE_unlinked;
1132 
1133 		ret = bch2_inode_write_flags(trans, &inode_iter, &inode,
1134 					     BTREE_UPDATE_internal_snapshot_node);
1135 		bch_err_msg(c, ret, "clearing inode unlinked flag");
1136 		if (ret)
1137 			goto out;
1138 
1139 		/*
1140 		 * We'll need another write buffer flush to pick up the new
1141 		 * unlinked inodes in the snapshot leaves:
1142 		 */
1143 		*need_another_pass = true;
1144 		goto out;
1145 	}
1146 
1147 	ret = 1;
1148 out:
1149 fsck_err:
1150 	bch2_trans_iter_exit(trans, &inode_iter);
1151 	return ret;
1152 delete:
1153 	ret = bch2_btree_bit_mod_buffered(trans, BTREE_ID_deleted_inodes, pos, false);
1154 	goto out;
1155 }
1156 
1157 int bch2_delete_dead_inodes(struct bch_fs *c)
1158 {
1159 	struct btree_trans *trans = bch2_trans_get(c);
1160 	bool need_another_pass;
1161 	int ret;
1162 again:
1163 	/*
1164 	 * if we ran check_inodes() unlinked inodes will have already been
1165 	 * cleaned up but the write buffer will be out of sync; therefore we
1166 	 * alway need a write buffer flush
1167 	 */
1168 	ret = bch2_btree_write_buffer_flush_sync(trans);
1169 	if (ret)
1170 		goto err;
1171 
1172 	need_another_pass = false;
1173 
1174 	/*
1175 	 * Weird transaction restart handling here because on successful delete,
1176 	 * bch2_inode_rm_snapshot() will return a nested transaction restart,
1177 	 * but we can't retry because the btree write buffer won't have been
1178 	 * flushed and we'd spin:
1179 	 */
1180 	ret = for_each_btree_key_commit(trans, iter, BTREE_ID_deleted_inodes, POS_MIN,
1181 					BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k,
1182 					NULL, NULL, BCH_TRANS_COMMIT_no_enospc, ({
1183 		ret = may_delete_deleted_inode(trans, &iter, k.k->p, &need_another_pass);
1184 		if (ret > 0) {
1185 			bch_verbose(c, "deleting unlinked inode %llu:%u", k.k->p.offset, k.k->p.snapshot);
1186 
1187 			ret = bch2_inode_rm_snapshot(trans, k.k->p.offset, k.k->p.snapshot);
1188 			/*
1189 			 * We don't want to loop here: a transaction restart
1190 			 * error here means we handled a transaction restart and
1191 			 * we're actually done, but if we loop we'll retry the
1192 			 * same key because the write buffer hasn't been flushed
1193 			 * yet
1194 			 */
1195 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
1196 				ret = 0;
1197 				continue;
1198 			}
1199 		}
1200 
1201 		ret;
1202 	}));
1203 
1204 	if (!ret && need_another_pass)
1205 		goto again;
1206 err:
1207 	bch2_trans_put(trans);
1208 	return ret;
1209 }
1210