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