fsck.c 34 KB
Newer Older
Kent Overstreet's avatar
Kent Overstreet committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// SPDX-License-Identifier: GPL-2.0

#include "bcachefs.h"
#include "btree_update.h"
#include "dirent.h"
#include "error.h"
#include "fs.h"
#include "fsck.h"
#include "inode.h"
#include "keylist.h"
#include "super.h"
#include "xattr.h"

#include <linux/dcache.h> /* struct qstr */
#include <linux/generic-radix-tree.h>

#define QSTR(n) { { { .len = strlen(n) } }, .name = n }

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
static s64 bch2_count_inode_sectors(struct btree_trans *trans, u64 inum)
{
	struct btree_iter *iter;
	struct bkey_s_c k;
	u64 sectors = 0;

	for_each_btree_key(trans, iter, BTREE_ID_EXTENTS, POS(inum, 0), 0, k) {
		if (k.k->p.inode != inum)
			break;

		if (bkey_extent_is_allocation(k.k))
			sectors += k.k->size;
	}

	return bch2_trans_iter_free(trans, iter) ?: sectors;
}

36
static int remove_dirent(struct btree_trans *trans,
Kent Overstreet's avatar
Kent Overstreet committed
37 38
			 struct bkey_s_c_dirent dirent)
{
39
	struct bch_fs *c = trans->c;
Kent Overstreet's avatar
Kent Overstreet committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
	struct qstr name;
	struct bch_inode_unpacked dir_inode;
	struct bch_hash_info dir_hash_info;
	u64 dir_inum = dirent.k->p.inode;
	int ret;
	char *buf;

	name.len = bch2_dirent_name_bytes(dirent);
	buf = kmalloc(name.len + 1, GFP_KERNEL);
	if (!buf)
		return -ENOMEM;

	memcpy(buf, dirent.v->d_name, name.len);
	buf[name.len] = '\0';
	name.name = buf;

56 57
	/* Unlock so we don't deadlock, after copying name: */
	bch2_btree_trans_unlock(trans);
Kent Overstreet's avatar
Kent Overstreet committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

	ret = bch2_inode_find_by_inum(c, dir_inum, &dir_inode);
	if (ret) {
		bch_err(c, "remove_dirent: err %i looking up directory inode", ret);
		goto err;
	}

	dir_hash_info = bch2_hash_info_init(c, &dir_inode);

	ret = bch2_dirent_delete(c, dir_inum, &dir_hash_info, &name, NULL);
	if (ret)
		bch_err(c, "remove_dirent: err %i deleting dirent", ret);
err:
	kfree(buf);
	return ret;
}

static int reattach_inode(struct bch_fs *c,
			  struct bch_inode_unpacked *lostfound_inode,
			  u64 inum)
{
	struct bch_hash_info lostfound_hash_info =
		bch2_hash_info_init(c, lostfound_inode);
	struct bkey_inode_buf packed;
	char name_buf[20];
	struct qstr name;
	int ret;

	snprintf(name_buf, sizeof(name_buf), "%llu", inum);
	name = (struct qstr) QSTR(name_buf);

	lostfound_inode->bi_nlink++;

	bch2_inode_pack(&packed, lostfound_inode);

	ret = bch2_btree_insert(c, BTREE_ID_INODES, &packed.inode.k_i,
94 95 96
				NULL, NULL,
				BTREE_INSERT_NOFAIL|
				BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
97 98 99 100 101 102 103 104 105
	if (ret) {
		bch_err(c, "error %i reattaching inode %llu while updating lost+found",
			ret, inum);
		return ret;
	}

	ret = bch2_dirent_create(c, lostfound_inode->bi_inum,
				 &lostfound_hash_info,
				 DT_DIR, &name, inum, NULL,
106 107
				 BTREE_INSERT_NOFAIL|
				 BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
	if (ret) {
		bch_err(c, "error %i reattaching inode %llu while creating new dirent",
			ret, inum);
		return ret;
	}
	return ret;
}

struct inode_walker {
	bool			first_this_inode;
	bool			have_inode;
	u64			cur_inum;
	struct bch_inode_unpacked inode;
};

static struct inode_walker inode_walker_init(void)
{
	return (struct inode_walker) {
		.cur_inum	= -1,
		.have_inode	= false,
	};
}

static int walk_inode(struct bch_fs *c, struct inode_walker *w, u64 inum)
{
	w->first_this_inode	= inum != w->cur_inum;
	w->cur_inum		= inum;

	if (w->first_this_inode) {
		int ret = bch2_inode_find_by_inum(c, inum, &w->inode);

		if (ret && ret != -ENOENT)
			return ret;

		w->have_inode = !ret;
	}

	return 0;
}

struct hash_check {
	struct bch_hash_info	info;
150 151 152 153 154

	/* start of current chain of hash collisions: */
	struct btree_iter	*chain;

	/* next offset in current chain of hash collisions: */
155
	u64			chain_end;
Kent Overstreet's avatar
Kent Overstreet committed
156 157
};

158 159 160 161 162 163
static void hash_check_init(struct hash_check *h)
{
	h->chain = NULL;
}

static void hash_stop_chain(struct btree_trans *trans,
164
			    struct hash_check *h)
Kent Overstreet's avatar
Kent Overstreet committed
165
{
166 167 168
	if (h->chain)
		bch2_trans_iter_free(trans, h->chain);
	h->chain = NULL;
Kent Overstreet's avatar
Kent Overstreet committed
169 170
}

171 172
static void hash_check_set_inode(struct btree_trans *trans,
				 struct hash_check *h,
Kent Overstreet's avatar
Kent Overstreet committed
173 174
				 const struct bch_inode_unpacked *bi)
{
175 176
	h->info = bch2_hash_info_init(trans->c, bi);
	hash_stop_chain(trans, h);
Kent Overstreet's avatar
Kent Overstreet committed
177 178 179
}

static int hash_redo_key(const struct bch_hash_desc desc,
180
			 struct btree_trans *trans, struct hash_check *h,
Kent Overstreet's avatar
Kent Overstreet committed
181 182 183 184 185 186 187 188 189 190 191 192
			 struct btree_iter *k_iter, struct bkey_s_c k,
			 u64 hashed)
{
	struct bkey_i *tmp;
	int ret = 0;

	tmp = kmalloc(bkey_bytes(k.k), GFP_KERNEL);
	if (!tmp)
		return -ENOMEM;

	bkey_reassemble(tmp, k);

193
	ret = bch2_btree_delete_at(trans, k_iter, 0);
Kent Overstreet's avatar
Kent Overstreet committed
194 195 196
	if (ret)
		goto err;

197 198 199
	bch2_hash_set(trans, desc, &h->info, k_iter->pos.inode,
		      tmp, BCH_HASH_SET_MUST_CREATE);
	ret = bch2_trans_commit(trans, NULL, NULL,
Kent Overstreet's avatar
Kent Overstreet committed
200 201
				BTREE_INSERT_NOFAIL|
				BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
202 203 204 205 206
err:
	kfree(tmp);
	return ret;
}

207 208
static int fsck_hash_delete_at(struct btree_trans *trans,
			       const struct bch_hash_desc desc,
Kent Overstreet's avatar
Kent Overstreet committed
209
			       struct bch_hash_info *info,
210
			       struct btree_iter *iter)
Kent Overstreet's avatar
Kent Overstreet committed
211 212 213
{
	int ret;
retry:
214 215
	ret   = bch2_hash_delete_at(trans, desc, info, iter) ?:
		bch2_trans_commit(trans, NULL, NULL,
Kent Overstreet's avatar
Kent Overstreet committed
216
				  BTREE_INSERT_ATOMIC|
Kent Overstreet's avatar
Kent Overstreet committed
217 218
				  BTREE_INSERT_NOFAIL|
				  BTREE_INSERT_LAZY_RW);
219 220 221 222 223
	if (ret == -EINTR) {
		ret = bch2_btree_iter_traverse(iter);
		if (!ret)
			goto retry;
	}
Kent Overstreet's avatar
Kent Overstreet committed
224 225 226 227

	return ret;
}

228 229 230
static int hash_check_duplicates(struct btree_trans *trans,
			const struct bch_hash_desc desc, struct hash_check *h,
			struct btree_iter *k_iter, struct bkey_s_c k)
231
{
232
	struct bch_fs *c = trans->c;
233 234 235 236 237 238 239 240
	struct btree_iter *iter;
	struct bkey_s_c k2;
	char buf[200];
	int ret = 0;

	if (!bkey_cmp(h->chain->pos, k_iter->pos))
		return 0;

241
	iter = bch2_trans_copy_iter(trans, h->chain);
242 243 244 245 246 247 248 249 250
	BUG_ON(IS_ERR(iter));

	for_each_btree_key_continue(iter, 0, k2) {
		if (bkey_cmp(k2.k->p, k.k->p) >= 0)
			break;

		if (fsck_err_on(k2.k->type == desc.key_type &&
				!desc.cmp_bkey(k, k2), c,
				"duplicate hash table keys:\n%s",
251 252
				(bch2_bkey_val_to_text(&PBUF(buf), c,
						       k), buf))) {
253
			ret = fsck_hash_delete_at(trans, desc, &h->info, k_iter);
254 255 256 257 258 259 260
			if (ret)
				return ret;
			ret = 1;
			break;
		}
	}
fsck_err:
261
	bch2_trans_iter_free(trans, iter);
262 263 264
	return ret;
}

265 266 267 268
static void hash_set_chain_start(struct btree_trans *trans,
			const struct bch_hash_desc desc,
			struct hash_check *h,
			struct btree_iter *k_iter, struct bkey_s_c k)
269
{
270 271
	bool hole = (k.k->type != KEY_TYPE_whiteout &&
		     k.k->type != desc.key_type);
272

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
	if (hole || k.k->p.offset > h->chain_end + 1)
		hash_stop_chain(trans, h);

	if (!hole) {
		if (!h->chain) {
			h->chain = bch2_trans_copy_iter(trans, k_iter);
			BUG_ON(IS_ERR(h->chain));
		}

		h->chain_end = k.k->p.offset;
	}
}

static bool key_has_correct_hash(struct btree_trans *trans,
			const struct bch_hash_desc desc,
			struct hash_check *h,
			struct btree_iter *k_iter, struct bkey_s_c k)
{
	u64 hash;
292

293
	hash_set_chain_start(trans, desc, h, k_iter, k);
294 295 296 297 298 299 300 301 302 303

	if (k.k->type != desc.key_type)
		return true;

	hash = desc.hash_bkey(&h->info, k);

	return hash >= h->chain->pos.offset &&
		hash <= k.k->p.offset;
}

304 305 306
static int hash_check_key(struct btree_trans *trans,
			const struct bch_hash_desc desc, struct hash_check *h,
			struct btree_iter *k_iter, struct bkey_s_c k)
Kent Overstreet's avatar
Kent Overstreet committed
307
{
308
	struct bch_fs *c = trans->c;
Kent Overstreet's avatar
Kent Overstreet committed
309 310 311 312
	char buf[200];
	u64 hashed;
	int ret = 0;

313
	hash_set_chain_start(trans, desc, h, k_iter, k);
Kent Overstreet's avatar
Kent Overstreet committed
314 315 316 317 318 319

	if (k.k->type != desc.key_type)
		return 0;

	hashed = desc.hash_bkey(&h->info, k);

320
	if (fsck_err_on(hashed < h->chain->pos.offset ||
Kent Overstreet's avatar
Kent Overstreet committed
321
			hashed > k.k->p.offset, c,
322
			"hash table key at wrong offset: btree %u, %llu, "
Kent Overstreet's avatar
Kent Overstreet committed
323
			"hashed to %llu chain starts at %llu\n%s",
324 325
			desc.btree_id, k.k->p.offset,
			hashed, h->chain->pos.offset,
326 327
			(bch2_bkey_val_to_text(&PBUF(buf), c,
					       k), buf))) {
328
		ret = hash_redo_key(desc, trans, h, k_iter, k, hashed);
Kent Overstreet's avatar
Kent Overstreet committed
329 330 331 332 333 334 335
		if (ret) {
			bch_err(c, "hash_redo_key err %i", ret);
			return ret;
		}
		return 1;
	}

336
	ret = hash_check_duplicates(trans, desc, h, k_iter, k);
Kent Overstreet's avatar
Kent Overstreet committed
337 338 339 340
fsck_err:
	return ret;
}

341
static int check_dirent_hash(struct btree_trans *trans, struct hash_check *h,
342 343
			     struct btree_iter *iter, struct bkey_s_c *k)
{
344
	struct bch_fs *c = trans->c;
345 346 347 348 349 350
	struct bkey_i_dirent *d = NULL;
	int ret = -EINVAL;
	char buf[200];
	unsigned len;
	u64 hash;

351
	if (key_has_correct_hash(trans, bch2_dirent_hash_desc, h, iter, *k))
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
		return 0;

	len = bch2_dirent_name_bytes(bkey_s_c_to_dirent(*k));
	BUG_ON(!len);

	memcpy(buf, bkey_s_c_to_dirent(*k).v->d_name, len);
	buf[len] = '\0';

	d = kmalloc(bkey_bytes(k->k), GFP_KERNEL);
	if (!d) {
		bch_err(c, "memory allocation failure");
		return -ENOMEM;
	}

	bkey_reassemble(&d->k_i, *k);

	do {
		--len;
		if (!len)
			goto err_redo;

		d->k.u64s = BKEY_U64s + dirent_val_u64s(len);

		BUG_ON(bkey_val_bytes(&d->k) <
		       offsetof(struct bch_dirent, d_name) + len);

		memset(d->v.d_name + len, 0,
		       bkey_val_bytes(&d->k) -
		       offsetof(struct bch_dirent, d_name) - len);

		hash = bch2_dirent_hash_desc.hash_bkey(&h->info,
						bkey_i_to_s_c(&d->k_i));
	} while (hash < h->chain->pos.offset ||
		 hash > k->k->p.offset);

	if (fsck_err(c, "dirent with junk at end, was %s (%zu) now %s (%u)",
		     buf, strlen(buf), d->v.d_name, len)) {
389 390
		bch2_trans_update(trans, BTREE_INSERT_ENTRY(iter, &d->k_i));

Kent Overstreet's avatar
Kent Overstreet committed
391 392 393
		ret = bch2_trans_commit(trans, NULL, NULL,
					BTREE_INSERT_NOFAIL|
					BTREE_INSERT_LAZY_RW);
394 395 396 397 398
		if (ret)
			goto err;

		*k = bch2_btree_iter_peek(iter);

399
		BUG_ON(k->k->type != KEY_TYPE_dirent);
400 401 402 403 404 405 406 407
	}
err:
fsck_err:
	kfree(d);
	return ret;
err_redo:
	hash = bch2_dirent_hash_desc.hash_bkey(&h->info, *k);

408 409 410 411 412
	if (fsck_err(c, "cannot fix dirent by removing trailing garbage %s (%zu)\n"
		     "hash table key at wrong offset: btree %u, offset %llu, "
		     "hashed to %llu chain starts at %llu\n%s",
		     buf, strlen(buf), BTREE_ID_DIRENTS,
		     k->k->p.offset, hash, h->chain->pos.offset,
413 414
		     (bch2_bkey_val_to_text(&PBUF(buf), c,
					    *k), buf))) {
415 416
		ret = hash_redo_key(bch2_dirent_hash_desc, trans,
				    h, iter, *k, hash);
417 418 419 420 421 422 423 424 425
		if (ret)
			bch_err(c, "hash_redo_key err %i", ret);
		else
			ret = 1;
	}

	goto err;
}

426 427 428 429 430 431 432
static int bch2_inode_truncate(struct bch_fs *c, u64 inode_nr, u64 new_size)
{
	return bch2_btree_delete_range(c, BTREE_ID_EXTENTS,
			POS(inode_nr, round_up(new_size, block_bytes(c)) >> 9),
			POS(inode_nr + 1, 0), NULL);
}

Kent Overstreet's avatar
Kent Overstreet committed
433 434 435 436 437 438 439 440
/*
 * Walk extents: verify that extents have a corresponding S_ISREG inode, and
 * that i_size an i_sectors are consistent
 */
noinline_for_stack
static int check_extents(struct bch_fs *c)
{
	struct inode_walker w = inode_walker_init();
441 442
	struct btree_trans trans;
	struct btree_iter *iter;
Kent Overstreet's avatar
Kent Overstreet committed
443 444 445 446
	struct bkey_s_c k;
	u64 i_sectors;
	int ret = 0;

447 448
	bch2_trans_init(&trans, c);

Kent Overstreet's avatar
Kent Overstreet committed
449 450
	bch_verbose(c, "checking extents");

451
	for_each_btree_key(&trans, iter, BTREE_ID_EXTENTS,
Kent Overstreet's avatar
Kent Overstreet committed
452 453 454 455 456 457 458 459 460 461 462 463
			   POS(BCACHEFS_ROOT_INO, 0), 0, k) {
		ret = walk_inode(c, &w, k.k->p.inode);
		if (ret)
			break;

		if (fsck_err_on(!w.have_inode, c,
			"extent type %u for missing inode %llu",
			k.k->type, k.k->p.inode) ||
		    fsck_err_on(w.have_inode &&
			!S_ISREG(w.inode.bi_mode) && !S_ISLNK(w.inode.bi_mode), c,
			"extent type %u for non regular file, inode %llu mode %o",
			k.k->type, k.k->p.inode, w.inode.bi_mode)) {
464
			bch2_trans_unlock(&trans);
Kent Overstreet's avatar
Kent Overstreet committed
465

466
			ret = bch2_inode_truncate(c, k.k->p.inode, 0);
Kent Overstreet's avatar
Kent Overstreet committed
467 468 469 470 471 472 473 474 475
			if (ret)
				goto err;
			continue;
		}

		if (fsck_err_on(w.first_this_inode &&
			w.have_inode &&
			!(w.inode.bi_flags & BCH_INODE_I_SECTORS_DIRTY) &&
			w.inode.bi_sectors !=
476
			(i_sectors = bch2_count_inode_sectors(&trans, w.cur_inum)),
Kent Overstreet's avatar
Kent Overstreet committed
477 478 479 480 481 482
			c, "i_sectors wrong: got %llu, should be %llu",
			w.inode.bi_sectors, i_sectors)) {
			struct bkey_inode_buf p;

			w.inode.bi_sectors = i_sectors;

483
			bch2_trans_unlock(&trans);
Kent Overstreet's avatar
Kent Overstreet committed
484 485 486 487

			bch2_inode_pack(&p, &w.inode);

			ret = bch2_btree_insert(c, BTREE_ID_INODES,
488
						&p.inode.k_i, NULL, NULL,
489 490
						BTREE_INSERT_NOFAIL|
						BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
491 492 493 494 495 496 497
			if (ret) {
				bch_err(c, "error in fs gc: error %i "
					"updating inode", ret);
				goto err;
			}

			/* revalidate iterator: */
498
			k = bch2_btree_iter_peek(iter);
Kent Overstreet's avatar
Kent Overstreet committed
499 500 501 502
		}

		if (fsck_err_on(w.have_inode &&
			!(w.inode.bi_flags & BCH_INODE_I_SIZE_DIRTY) &&
503
			k.k->type != KEY_TYPE_reservation &&
Kent Overstreet's avatar
Kent Overstreet committed
504 505 506
			k.k->p.offset > round_up(w.inode.bi_size, PAGE_SIZE) >> 9, c,
			"extent type %u offset %llu past end of inode %llu, i_size %llu",
			k.k->type, k.k->p.offset, k.k->p.inode, w.inode.bi_size)) {
507
			bch2_trans_unlock(&trans);
Kent Overstreet's avatar
Kent Overstreet committed
508 509

			ret = bch2_inode_truncate(c, k.k->p.inode,
510
						  w.inode.bi_size);
Kent Overstreet's avatar
Kent Overstreet committed
511 512 513 514 515 516 517
			if (ret)
				goto err;
			continue;
		}
	}
err:
fsck_err:
518
	return bch2_trans_exit(&trans) ?: ret;
Kent Overstreet's avatar
Kent Overstreet committed
519 520 521 522 523 524 525 526 527 528 529
}

/*
 * Walk dirents: verify that they all have a corresponding S_ISDIR inode,
 * validate d_type
 */
noinline_for_stack
static int check_dirents(struct bch_fs *c)
{
	struct inode_walker w = inode_walker_init();
	struct hash_check h;
530 531
	struct btree_trans trans;
	struct btree_iter *iter;
Kent Overstreet's avatar
Kent Overstreet committed
532 533 534 535 536 537 538
	struct bkey_s_c k;
	unsigned name_len;
	char buf[200];
	int ret = 0;

	bch_verbose(c, "checking dirents");

539
	bch2_trans_init(&trans, c);
Kent Overstreet's avatar
Kent Overstreet committed
540

541
	bch2_trans_preload_iters(&trans);
542 543 544 545

	iter = bch2_trans_get_iter(&trans, BTREE_ID_DIRENTS,
				   POS(BCACHEFS_ROOT_INO, 0), 0);

546
	hash_check_init(&h);
547 548

	for_each_btree_key_continue(iter, 0, k) {
Kent Overstreet's avatar
Kent Overstreet committed
549 550 551 552 553 554 555 556 557 558 559
		struct bkey_s_c_dirent d;
		struct bch_inode_unpacked target;
		bool have_target;
		u64 d_inum;

		ret = walk_inode(c, &w, k.k->p.inode);
		if (ret)
			break;

		if (fsck_err_on(!w.have_inode, c,
				"dirent in nonexisting directory:\n%s",
560 561
				(bch2_bkey_val_to_text(&PBUF(buf), c,
						       k), buf)) ||
Kent Overstreet's avatar
Kent Overstreet committed
562 563 564
		    fsck_err_on(!S_ISDIR(w.inode.bi_mode), c,
				"dirent in non directory inode type %u:\n%s",
				mode_to_type(w.inode.bi_mode),
565 566
				(bch2_bkey_val_to_text(&PBUF(buf), c,
						       k), buf))) {
567
			ret = bch2_btree_delete_at(&trans, iter, 0);
Kent Overstreet's avatar
Kent Overstreet committed
568 569 570 571 572 573
			if (ret)
				goto err;
			continue;
		}

		if (w.first_this_inode && w.have_inode)
574
			hash_check_set_inode(&trans, &h, &w.inode);
Kent Overstreet's avatar
Kent Overstreet committed
575

576
		ret = check_dirent_hash(&trans, &h, iter, &k);
Kent Overstreet's avatar
Kent Overstreet committed
577 578 579 580
		if (ret > 0) {
			ret = 0;
			continue;
		}
581 582
		if (ret)
			goto fsck_err;
Kent Overstreet's avatar
Kent Overstreet committed
583 584 585 586

		if (ret)
			goto fsck_err;

587
		if (k.k->type != KEY_TYPE_dirent)
Kent Overstreet's avatar
Kent Overstreet committed
588 589 590 591 592 593 594 595 596 597 598 599 600
			continue;

		d = bkey_s_c_to_dirent(k);
		d_inum = le64_to_cpu(d.v->d_inum);

		name_len = bch2_dirent_name_bytes(d);

		if (fsck_err_on(!name_len, c, "empty dirent") ||
		    fsck_err_on(name_len == 1 &&
				!memcmp(d.v->d_name, ".", 1), c,
				". dirent") ||
		    fsck_err_on(name_len == 2 &&
				!memcmp(d.v->d_name, "..", 2), c,
601 602 603 604 605 606
				".. dirent") ||
		    fsck_err_on(name_len == 2 &&
				!memcmp(d.v->d_name, "..", 2), c,
				".. dirent") ||
		    fsck_err_on(memchr(d.v->d_name, '/', name_len), c,
				"dirent name has invalid chars")) {
607
			ret = remove_dirent(&trans, d);
Kent Overstreet's avatar
Kent Overstreet committed
608 609 610 611 612 613 614
			if (ret)
				goto err;
			continue;
		}

		if (fsck_err_on(d_inum == d.k->p.inode, c,
				"dirent points to own directory:\n%s",
615 616
				(bch2_bkey_val_to_text(&PBUF(buf), c,
						       k), buf))) {
617
			ret = remove_dirent(&trans, d);
Kent Overstreet's avatar
Kent Overstreet committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631
			if (ret)
				goto err;
			continue;
		}

		ret = bch2_inode_find_by_inum(c, d_inum, &target);
		if (ret && ret != -ENOENT)
			break;

		have_target = !ret;
		ret = 0;

		if (fsck_err_on(!have_target, c,
				"dirent points to missing inode:\n%s",
632 633
				(bch2_bkey_val_to_text(&PBUF(buf), c,
						       k), buf))) {
634
			ret = remove_dirent(&trans, d);
Kent Overstreet's avatar
Kent Overstreet committed
635 636 637 638 639 640 641 642 643 644
			if (ret)
				goto err;
			continue;
		}

		if (fsck_err_on(have_target &&
				d.v->d_type !=
				mode_to_type(target.bi_mode), c,
				"incorrect d_type: should be %u:\n%s",
				mode_to_type(target.bi_mode),
645 646
				(bch2_bkey_val_to_text(&PBUF(buf), c,
						       k), buf))) {
Kent Overstreet's avatar
Kent Overstreet committed
647 648 649 650 651 652 653 654 655 656 657
			struct bkey_i_dirent *n;

			n = kmalloc(bkey_bytes(d.k), GFP_KERNEL);
			if (!n) {
				ret = -ENOMEM;
				goto err;
			}

			bkey_reassemble(&n->k_i, d.s_c);
			n->v.d_type = mode_to_type(target.bi_mode);

658 659 660 661
			bch2_trans_update(&trans,
				BTREE_INSERT_ENTRY(iter, &n->k_i));

			ret = bch2_trans_commit(&trans, NULL, NULL,
Kent Overstreet's avatar
Kent Overstreet committed
662 663
						BTREE_INSERT_NOFAIL|
						BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
664 665 666 667 668 669
			kfree(n);
			if (ret)
				goto err;

		}
	}
670 671

	hash_stop_chain(&trans, &h);
Kent Overstreet's avatar
Kent Overstreet committed
672 673
err:
fsck_err:
674
	return bch2_trans_exit(&trans) ?: ret;
Kent Overstreet's avatar
Kent Overstreet committed
675 676 677 678 679 680 681 682 683 684
}

/*
 * Walk xattrs: verify that they all have a corresponding inode
 */
noinline_for_stack
static int check_xattrs(struct bch_fs *c)
{
	struct inode_walker w = inode_walker_init();
	struct hash_check h;
685 686
	struct btree_trans trans;
	struct btree_iter *iter;
Kent Overstreet's avatar
Kent Overstreet committed
687 688 689 690 691
	struct bkey_s_c k;
	int ret = 0;

	bch_verbose(c, "checking xattrs");

692
	bch2_trans_init(&trans, c);
Kent Overstreet's avatar
Kent Overstreet committed
693

694
	bch2_trans_preload_iters(&trans);
695 696 697 698

	iter = bch2_trans_get_iter(&trans, BTREE_ID_XATTRS,
				   POS(BCACHEFS_ROOT_INO, 0), 0);

699
	hash_check_init(&h);
700 701

	for_each_btree_key_continue(iter, 0, k) {
Kent Overstreet's avatar
Kent Overstreet committed
702 703 704 705 706 707 708
		ret = walk_inode(c, &w, k.k->p.inode);
		if (ret)
			break;

		if (fsck_err_on(!w.have_inode, c,
				"xattr for missing inode %llu",
				k.k->p.inode)) {
709
			ret = bch2_btree_delete_at(&trans, iter, 0);
Kent Overstreet's avatar
Kent Overstreet committed
710 711 712 713 714 715
			if (ret)
				goto err;
			continue;
		}

		if (w.first_this_inode && w.have_inode)
716
			hash_check_set_inode(&trans, &h, &w.inode);
Kent Overstreet's avatar
Kent Overstreet committed
717

718 719
		ret = hash_check_key(&trans, bch2_xattr_hash_desc,
				     &h, iter, k);
Kent Overstreet's avatar
Kent Overstreet committed
720 721 722 723 724
		if (ret)
			goto fsck_err;
	}
err:
fsck_err:
725
	return bch2_trans_exit(&trans) ?: ret;
Kent Overstreet's avatar
Kent Overstreet committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
}

/* Get root directory, create if it doesn't exist: */
static int check_root(struct bch_fs *c, struct bch_inode_unpacked *root_inode)
{
	struct bkey_inode_buf packed;
	int ret;

	bch_verbose(c, "checking root directory");

	ret = bch2_inode_find_by_inum(c, BCACHEFS_ROOT_INO, root_inode);
	if (ret && ret != -ENOENT)
		return ret;

	if (fsck_err_on(ret, c, "root directory missing"))
		goto create_root;

	if (fsck_err_on(!S_ISDIR(root_inode->bi_mode), c,
			"root inode not a directory"))
		goto create_root;

	return 0;
fsck_err:
	return ret;
create_root:
	bch2_inode_init(c, root_inode, 0, 0, S_IFDIR|S_IRWXU|S_IRUGO|S_IXUGO,
			0, NULL);
	root_inode->bi_inum = BCACHEFS_ROOT_INO;

	bch2_inode_pack(&packed, root_inode);

	return bch2_btree_insert(c, BTREE_ID_INODES, &packed.inode.k_i,
758 759 760
				 NULL, NULL,
				 BTREE_INSERT_NOFAIL|
				 BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
}

/* Get lost+found, create if it doesn't exist: */
static int check_lostfound(struct bch_fs *c,
			   struct bch_inode_unpacked *root_inode,
			   struct bch_inode_unpacked *lostfound_inode)
{
	struct qstr lostfound = QSTR("lost+found");
	struct bch_hash_info root_hash_info =
		bch2_hash_info_init(c, root_inode);
	struct bkey_inode_buf packed;
	u64 inum;
	int ret;

	bch_verbose(c, "checking lost+found");

	inum = bch2_dirent_lookup(c, BCACHEFS_ROOT_INO, &root_hash_info,
				 &lostfound);
	if (!inum) {
		bch_notice(c, "creating lost+found");
		goto create_lostfound;
	}

	ret = bch2_inode_find_by_inum(c, inum, lostfound_inode);
	if (ret && ret != -ENOENT)
		return ret;

	if (fsck_err_on(ret, c, "lost+found missing"))
		goto create_lostfound;

	if (fsck_err_on(!S_ISDIR(lostfound_inode->bi_mode), c,
			"lost+found inode not a directory"))
		goto create_lostfound;

	return 0;
fsck_err:
	return ret;
create_lostfound:
	root_inode->bi_nlink++;

	bch2_inode_pack(&packed, root_inode);

	ret = bch2_btree_insert(c, BTREE_ID_INODES, &packed.inode.k_i,
804 805 806
				NULL, NULL,
				BTREE_INSERT_NOFAIL|
				BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
807 808 809 810 811 812 813 814 815 816 817 818 819
	if (ret)
		return ret;

	bch2_inode_init(c, lostfound_inode, 0, 0, S_IFDIR|S_IRWXU|S_IRUGO|S_IXUGO,
			0, root_inode);

	ret = bch2_inode_create(c, lostfound_inode, BLOCKDEV_INODE_MAX, 0,
			       &c->unused_inode_hint);
	if (ret)
		return ret;

	ret = bch2_dirent_create(c, BCACHEFS_ROOT_INO, &root_hash_info, DT_DIR,
				 &lostfound, lostfound_inode->bi_inum, NULL,
820 821
				 BTREE_INSERT_NOFAIL|
				 BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
	if (ret)
		return ret;

	return 0;
}

struct inode_bitmap {
	unsigned long	*bits;
	size_t		size;
};

static inline bool inode_bitmap_test(struct inode_bitmap *b, size_t nr)
{
	return nr < b->size ? test_bit(nr, b->bits) : false;
}

static inline int inode_bitmap_set(struct inode_bitmap *b, size_t nr)
{
	if (nr >= b->size) {
		size_t new_size = max_t(size_t, max_t(size_t,
					PAGE_SIZE * 8,
					b->size * 2),
					nr + 1);
		void *n;

		new_size = roundup_pow_of_two(new_size);
		n = krealloc(b->bits, new_size / 8, GFP_KERNEL|__GFP_ZERO);
		if (!n) {
			return -ENOMEM;
		}

		b->bits = n;
		b->size = new_size;
	}

	__set_bit(nr, b->bits);
	return 0;
}

struct pathbuf {
	size_t		nr;
	size_t		size;

	struct pathbuf_entry {
		u64	inum;
		u64	offset;
	}		*entries;
};

static int path_down(struct pathbuf *p, u64 inum)
{
	if (p->nr == p->size) {
		size_t new_size = max_t(size_t, 256UL, p->size * 2);
		void *n = krealloc(p->entries,
				   new_size * sizeof(p->entries[0]),
				   GFP_KERNEL);
		if (!n)
			return -ENOMEM;

		p->entries = n;
		p->size = new_size;
	};

	p->entries[p->nr++] = (struct pathbuf_entry) {
		.inum = inum,
		.offset = 0,
	};
	return 0;
}

noinline_for_stack
static int check_directory_structure(struct bch_fs *c,
				     struct bch_inode_unpacked *lostfound_inode)
{
	struct inode_bitmap dirs_done = { NULL, 0 };
	struct pathbuf path = { 0, 0, NULL };
	struct pathbuf_entry *e;
899 900
	struct btree_trans trans;
	struct btree_iter *iter;
Kent Overstreet's avatar
Kent Overstreet committed
901 902 903 904 905 906
	struct bkey_s_c k;
	struct bkey_s_c_dirent dirent;
	bool had_unreachable;
	u64 d_inum;
	int ret = 0;

907 908
	bch2_trans_init(&trans, c);

Kent Overstreet's avatar
Kent Overstreet committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
	bch_verbose(c, "checking directory structure");

	/* DFS: */
restart_dfs:
	had_unreachable = false;

	ret = inode_bitmap_set(&dirs_done, BCACHEFS_ROOT_INO);
	if (ret) {
		bch_err(c, "memory allocation failure in inode_bitmap_set()");
		goto err;
	}

	ret = path_down(&path, BCACHEFS_ROOT_INO);
	if (ret) {
		return ret;
	}

	while (path.nr) {
next:
		e = &path.entries[path.nr - 1];

		if (e->offset == U64_MAX)
			goto up;

933
		for_each_btree_key(&trans, iter, BTREE_ID_DIRENTS,
Kent Overstreet's avatar
Kent Overstreet committed
934 935 936 937 938 939
				   POS(e->inum, e->offset + 1), 0, k) {
			if (k.k->p.inode != e->inum)
				break;

			e->offset = k.k->p.offset;

940
			if (k.k->type != KEY_TYPE_dirent)
Kent Overstreet's avatar
Kent Overstreet committed
941 942 943 944 945 946 947 948 949 950 951 952
				continue;

			dirent = bkey_s_c_to_dirent(k);

			if (dirent.v->d_type != DT_DIR)
				continue;

			d_inum = le64_to_cpu(dirent.v->d_inum);

			if (fsck_err_on(inode_bitmap_test(&dirs_done, d_inum), c,
					"directory %llu has multiple hardlinks",
					d_inum)) {
953
				ret = remove_dirent(&trans, dirent);
Kent Overstreet's avatar
Kent Overstreet committed
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
				if (ret)
					goto err;
				continue;
			}

			ret = inode_bitmap_set(&dirs_done, d_inum);
			if (ret) {
				bch_err(c, "memory allocation failure in inode_bitmap_set()");
				goto err;
			}

			ret = path_down(&path, d_inum);
			if (ret) {
				goto err;
			}

970 971 972 973 974
			ret = bch2_trans_iter_free(&trans, iter);
			if (ret) {
				bch_err(c, "btree error %i in fsck", ret);
				goto err;
			}
Kent Overstreet's avatar
Kent Overstreet committed
975 976
			goto next;
		}
977
		ret = bch2_trans_iter_free(&trans, iter);
Kent Overstreet's avatar
Kent Overstreet committed
978 979 980 981 982 983 984 985
		if (ret) {
			bch_err(c, "btree error %i in fsck", ret);
			goto err;
		}
up:
		path.nr--;
	}

986
	for_each_btree_key(&trans, iter, BTREE_ID_INODES, POS_MIN, 0, k) {
987
		if (k.k->type != KEY_TYPE_inode)
Kent Overstreet's avatar
Kent Overstreet committed
988 989 990 991 992 993 994 995 996 997 998
			continue;

		if (!S_ISDIR(le16_to_cpu(bkey_s_c_to_inode(k).v->bi_mode)))
			continue;

		if (!bch2_empty_dir(c, k.k->p.inode))
			continue;

		if (fsck_err_on(!inode_bitmap_test(&dirs_done, k.k->p.inode), c,
				"unreachable directory found (inum %llu)",
				k.k->p.inode)) {
999
			bch2_btree_trans_unlock(&trans);
Kent Overstreet's avatar
Kent Overstreet committed
1000 1001 1002 1003 1004 1005 1006 1007 1008

			ret = reattach_inode(c, lostfound_inode, k.k->p.inode);
			if (ret) {
				goto err;
			}

			had_unreachable = true;
		}
	}
1009
	ret = bch2_trans_iter_free(&trans, iter);
Kent Overstreet's avatar
Kent Overstreet committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
	if (ret)
		goto err;

	if (had_unreachable) {
		bch_info(c, "reattached unreachable directories, restarting pass to check for loops");
		kfree(dirs_done.bits);
		kfree(path.entries);
		memset(&dirs_done, 0, sizeof(dirs_done));
		memset(&path, 0, sizeof(path));
		goto restart_dfs;
	}

out:
	kfree(dirs_done.bits);
	kfree(path.entries);
	return ret;
err:
fsck_err:
1028
	ret = bch2_trans_exit(&trans) ?: ret;
Kent Overstreet's avatar
Kent Overstreet committed
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
	goto out;
}

struct nlink {
	u32	count;
	u32	dir_count;
};

typedef GENRADIX(struct nlink) nlink_table;

static void inc_link(struct bch_fs *c, nlink_table *links,
		     u64 range_start, u64 *range_end,
		     u64 inum, bool dir)
{
	struct nlink *link;

	if (inum < range_start || inum >= *range_end)
		return;

	link = genradix_ptr_alloc(links, inum - range_start, GFP_KERNEL);
	if (!link) {
		bch_verbose(c, "allocation failed during fs gc - will need another pass");
		*range_end = inum;
		return;
	}

	if (dir)
		link->dir_count++;
	else
		link->count++;
}

noinline_for_stack
static int bch2_gc_walk_dirents(struct bch_fs *c, nlink_table *links,
			       u64 range_start, u64 *range_end)
{
1065 1066
	struct btree_trans trans;
	struct btree_iter *iter;
Kent Overstreet's avatar
Kent Overstreet committed
1067 1068 1069 1070 1071
	struct bkey_s_c k;
	struct bkey_s_c_dirent d;
	u64 d_inum;
	int ret;

1072 1073
	bch2_trans_init(&trans, c);

Kent Overstreet's avatar
Kent Overstreet committed
1074 1075
	inc_link(c, links, range_start, range_end, BCACHEFS_ROOT_INO, false);

1076
	for_each_btree_key(&trans, iter, BTREE_ID_DIRENTS, POS_MIN, 0, k) {
Kent Overstreet's avatar
Kent Overstreet committed
1077
		switch (k.k->type) {
1078
		case KEY_TYPE_dirent:
Kent Overstreet's avatar
Kent Overstreet committed
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
			d = bkey_s_c_to_dirent(k);
			d_inum = le64_to_cpu(d.v->d_inum);

			if (d.v->d_type == DT_DIR)
				inc_link(c, links, range_start, range_end,
					 d.k->p.inode, true);

			inc_link(c, links, range_start, range_end,
				 d_inum, false);

			break;
		}

1092
		bch2_trans_cond_resched(&trans);
Kent Overstreet's avatar
Kent Overstreet committed
1093
	}
1094
	ret = bch2_trans_exit(&trans);
Kent Overstreet's avatar
Kent Overstreet committed
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
	if (ret)
		bch_err(c, "error in fs gc: btree error %i while walking dirents", ret);

	return ret;
}

static int check_inode_nlink(struct bch_fs *c,
			     struct bch_inode_unpacked *lostfound_inode,
			     struct bch_inode_unpacked *u,
			     struct nlink *link,
			     bool *do_update)
{
	u32 i_nlink = u->bi_flags & BCH_INODE_UNLINKED
		? 0
		: u->bi_nlink + nlink_bias(u->bi_mode);
	u32 real_i_nlink =
		link->count * nlink_bias(u->bi_mode) +
		link->dir_count;
	int ret = 0;

	/*
	 * These should have been caught/fixed by earlier passes, we don't
	 * repair them here:
	 */
	if (S_ISDIR(u->bi_mode) && link->count > 1) {
		need_fsck_err(c, "directory %llu with multiple hardlinks: %u",
			      u->bi_inum, link->count);
		return 0;
	}

	if (S_ISDIR(u->bi_mode) && !link->count) {
		need_fsck_err(c, "unreachable directory found (inum %llu)",
			      u->bi_inum);
		return 0;
	}

	if (!S_ISDIR(u->bi_mode) && link->dir_count) {
		need_fsck_err(c, "non directory with subdirectories",
			      u->bi_inum);
		return 0;
	}

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	if (!link->count &&
	    !(u->bi_flags & BCH_INODE_UNLINKED) &&
	    (c->sb.features & (1 << BCH_FEATURE_ATOMIC_NLINK))) {
		if (fsck_err(c, "unreachable inode %llu not marked as unlinked (type %u)",
			     u->bi_inum, mode_to_type(u->bi_mode)) ==
		    FSCK_ERR_IGNORE)
			return 0;

		ret = reattach_inode(c, lostfound_inode, u->bi_inum);
		if (ret)
			return ret;

		link->count = 1;
		real_i_nlink = nlink_bias(u->bi_mode) + link->dir_count;
		goto set_i_nlink;
	}

Kent Overstreet's avatar
Kent Overstreet committed
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
	if (i_nlink < link->count) {
		if (fsck_err(c, "inode %llu i_link too small (%u < %u, type %i)",
			     u->bi_inum, i_nlink, link->count,
			     mode_to_type(u->bi_mode)) == FSCK_ERR_IGNORE)
			return 0;
		goto set_i_nlink;
	}

	if (i_nlink != real_i_nlink &&
	    c->sb.clean) {
		if (fsck_err(c, "filesystem marked clean, "
			     "but inode %llu has wrong i_nlink "
			     "(type %u i_nlink %u, should be %u)",
			     u->bi_inum, mode_to_type(u->bi_mode),
			     i_nlink, real_i_nlink) == FSCK_ERR_IGNORE)
			return 0;
		goto set_i_nlink;
	}

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
	if (i_nlink != real_i_nlink &&
	    (c->sb.features & (1 << BCH_FEATURE_ATOMIC_NLINK))) {
		if (fsck_err(c, "inode %llu has wrong i_nlink "
			     "(type %u i_nlink %u, should be %u)",
			     u->bi_inum, mode_to_type(u->bi_mode),
			     i_nlink, real_i_nlink) == FSCK_ERR_IGNORE)
			return 0;
		goto set_i_nlink;
	}

Kent Overstreet's avatar
Kent Overstreet committed
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
	if (real_i_nlink && i_nlink != real_i_nlink)
		bch_verbose(c, "setting inode %llu nlink from %u to %u",
			    u->bi_inum, i_nlink, real_i_nlink);
set_i_nlink:
	if (i_nlink != real_i_nlink) {
		if (real_i_nlink) {
			u->bi_nlink = real_i_nlink - nlink_bias(u->bi_mode);
			u->bi_flags &= ~BCH_INODE_UNLINKED;
		} else {
			u->bi_nlink = 0;
			u->bi_flags |= BCH_INODE_UNLINKED;
		}

		*do_update = true;
	}
fsck_err:
	return ret;
}

1202
static int check_inode(struct btree_trans *trans,
Kent Overstreet's avatar
Kent Overstreet committed
1203 1204 1205 1206 1207
		       struct bch_inode_unpacked *lostfound_inode,
		       struct btree_iter *iter,
		       struct bkey_s_c_inode inode,
		       struct nlink *link)
{
1208
	struct bch_fs *c = trans->c;
Kent Overstreet's avatar
Kent Overstreet committed
1209 1210 1211 1212 1213
	struct bch_inode_unpacked u;
	bool do_update = false;
	int ret = 0;

	ret = bch2_inode_unpack(inode, &u);
1214 1215 1216

	bch2_btree_trans_unlock(trans);

Kent Overstreet's avatar
Kent Overstreet committed
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
	if (bch2_fs_inconsistent_on(ret, c,
			 "error unpacking inode %llu in fsck",
			 inode.k->p.inode))
		return ret;

	if (link) {
		ret = check_inode_nlink(c, lostfound_inode, &u, link,
					&do_update);
		if (ret)
			return ret;
	}

	if (u.bi_flags & BCH_INODE_UNLINKED) {
1230 1231 1232 1233 1234
		fsck_err_on(c->sb.clean, c,
			    "filesystem marked clean, "
			    "but inode %llu unlinked",
			    u.bi_inum);

Kent Overstreet's avatar
Kent Overstreet committed
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
		bch_verbose(c, "deleting inode %llu", u.bi_inum);

		ret = bch2_inode_rm(c, u.bi_inum);
		if (ret)
			bch_err(c, "error in fs gc: error %i "
				"while deleting inode", ret);
		return ret;
	}

	if (u.bi_flags & BCH_INODE_I_SIZE_DIRTY) {
		fsck_err_on(c->sb.clean, c,
			    "filesystem marked clean, "
			    "but inode %llu has i_size dirty",
			    u.bi_inum);

		bch_verbose(c, "truncating inode %llu", u.bi_inum);

		/*
		 * XXX: need to truncate partial blocks too here - or ideally
		 * just switch units to bytes and that issue goes away
		 */

1257
		ret = bch2_inode_truncate(c, u.bi_inum, u.bi_size);
Kent Overstreet's avatar
Kent Overstreet committed
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
		if (ret) {
			bch_err(c, "error in fs gc: error %i "
				"truncating inode", ret);
			return ret;
		}

		/*
		 * We truncated without our normal sector accounting hook, just
		 * make sure we recalculate it:
		 */
		u.bi_flags |= BCH_INODE_I_SECTORS_DIRTY;

		u.bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
		do_update = true;
	}

	if (u.bi_flags & BCH_INODE_I_SECTORS_DIRTY) {
		s64 sectors;

		fsck_err_on(c->sb.clean, c,
			    "filesystem marked clean, "
			    "but inode %llu has i_sectors dirty",
			    u.bi_inum);

		bch_verbose(c, "recounting sectors for inode %llu",
			    u.bi_inum);

1285
		sectors = bch2_count_inode_sectors(trans, u.bi_inum);
Kent Overstreet's avatar
Kent Overstreet committed
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
		if (sectors < 0) {
			bch_err(c, "error in fs gc: error %i "
				"recounting inode sectors",
				(int) sectors);
			return sectors;
		}

		u.bi_sectors = sectors;
		u.bi_flags &= ~BCH_INODE_I_SECTORS_DIRTY;
		do_update = true;
	}

	if (do_update) {
		struct bkey_inode_buf p;

		bch2_inode_pack(&p, &u);
1302
		bch2_trans_update(trans, BTREE_INSERT_ENTRY(iter, &p.inode.k_i));
Kent Overstreet's avatar
Kent Overstreet committed
1303

1304
		ret = bch2_trans_commit(trans, NULL, NULL,
Kent Overstreet's avatar
Kent Overstreet committed
1305 1306
					BTREE_INSERT_NOFAIL|
					BTREE_INSERT_LAZY_RW);
Kent Overstreet's avatar
Kent Overstreet committed
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
		if (ret && ret != -EINTR)
			bch_err(c, "error in fs gc: error %i "
				"updating inode", ret);
	}
fsck_err:
	return ret;
}

noinline_for_stack
static int bch2_gc_walk_inodes(struct bch_fs *c,
			       struct bch_inode_unpacked *lostfound_inode,
			       nlink_table *links,
			       u64 range_start, u64 range_end)
{
1321 1322
	struct btree_trans trans;
	struct btree_iter *iter;
Kent Overstreet's avatar
Kent Overstreet committed
1323 1324 1325 1326 1327 1328
	struct bkey_s_c k;
	struct nlink *link, zero_links = { 0, 0 };
	struct genradix_iter nlinks_iter;
	int ret = 0, ret2 = 0;
	u64 nlinks_pos;

1329 1330 1331 1332
	bch2_trans_init(&trans, c);

	iter = bch2_trans_get_iter(&trans, BTREE_ID_INODES,
				   POS(range_start, 0), 0);
Kent Overstreet's avatar
Kent Overstreet committed
1333 1334
	nlinks_iter = genradix_iter_init(links, 0);

1335
	while ((k = bch2_btree_iter_peek(iter)).k &&
1336
	       !(ret2 = bkey_err(k))) {
Kent Overstreet's avatar
Kent Overstreet committed
1337 1338
peek_nlinks:	link = genradix_iter_peek(&nlinks_iter, links);

1339
		if (!link && (!k.k || iter->pos.inode >= range_end))
Kent Overstreet's avatar
Kent Overstreet committed
1340 1341 1342
			break;

		nlinks_pos = range_start + nlinks_iter.pos;
1343
		if (iter->pos.inode > nlinks_pos) {
Kent Overstreet's avatar
Kent Overstreet committed
1344 1345 1346 1347 1348 1349 1350 1351
			/* Should have been caught by dirents pass: */
			need_fsck_err_on(link && link->count, c,
				"missing inode %llu (nlink %u)",
				nlinks_pos, link->count);
			genradix_iter_advance(&nlinks_iter, links);
			goto peek_nlinks;
		}

1352
		if (iter->pos.inode < nlinks_pos || !link)
Kent Overstreet's avatar
Kent Overstreet committed
1353 1354
			link = &zero_links;

1355
		if (k.k && k.k->type == KEY_TYPE_inode) {
1356
			ret = check_inode(&trans, lostfound_inode, iter,
Kent Overstreet's avatar
Kent Overstreet committed
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
					  bkey_s_c_to_inode(k), link);
			BUG_ON(ret == -EINTR);
			if (ret)
				break;
		} else {
			/* Should have been caught by dirents pass: */
			need_fsck_err_on(link->count, c,
				"missing inode %llu (nlink %u)",
				nlinks_pos, link->count);
		}

1368
		if (nlinks_pos == iter->pos.inode)
Kent Overstreet's avatar
Kent Overstreet committed
1369 1370
			genradix_iter_advance(&nlinks_iter, links);

1371
		bch2_btree_iter_next(iter);
1372
		bch2_trans_cond_resched(&trans);
Kent Overstreet's avatar
Kent Overstreet committed
1373 1374
	}
fsck_err:
1375 1376
	bch2_trans_exit(&trans);

Kent Overstreet's avatar
Kent Overstreet committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
	if (ret2)
		bch_err(c, "error in fs gc: btree error %i while walking inodes", ret2);

	return ret ?: ret2;
}

noinline_for_stack
static int check_inode_nlinks(struct bch_fs *c,
			      struct bch_inode_unpacked *lostfound_inode)
{
	nlink_table links;
	u64 this_iter_range_start, next_iter_range_start = 0;
	int ret = 0;

	bch_verbose(c, "checking inode nlinks");

	genradix_init(&links);

	do {
		this_iter_range_start = next_iter_range_start;
		next_iter_range_start = U64_MAX;

		ret = bch2_gc_walk_dirents(c, &links,
					  this_iter_range_start,
					  &next_iter_range_start);
		if (ret)
			break;

		ret = bch2_gc_walk_inodes(c, lostfound_inode, &links,
					 this_iter_range_start,
					 next_iter_range_start);
		if (ret)
			break;

		genradix_free(&links);
	} while (next_iter_range_start != U64_MAX);

	genradix_free(&links);

	return ret;
}

noinline_for_stack
static int check_inodes_fast(struct bch_fs *c)
{
1422 1423
	struct btree_trans trans;
	struct btree_iter *iter;
Kent Overstreet's avatar
Kent Overstreet committed
1424 1425
	struct bkey_s_c k;
	struct bkey_s_c_inode inode;
1426
	int ret = 0, ret2;
Kent Overstreet's avatar
Kent Overstreet committed
1427

1428 1429 1430 1431 1432 1433
	bch2_trans_init(&trans, c);

	iter = bch2_trans_get_iter(&trans, BTREE_ID_INODES,
				   POS_MIN, 0);

	for_each_btree_key_continue(iter, 0, k) {
1434
		if (k.k->type != KEY_TYPE_inode)
Kent Overstreet's avatar
Kent Overstreet committed
1435 1436 1437 1438 1439 1440 1441 1442
			continue;

		inode = bkey_s_c_to_inode(k);

		if (inode.v->bi_flags &
		    (BCH_INODE_I_SIZE_DIRTY|
		     BCH_INODE_I_SECTORS_DIRTY|
		     BCH_INODE_UNLINKED)) {
1443
			ret = check_inode(&trans, NULL, iter, inode, NULL);
Kent Overstreet's avatar
Kent Overstreet committed
1444 1445 1446 1447 1448
			BUG_ON(ret == -EINTR);
			if (ret)
				break;
		}
	}
1449

1450
	ret2 = bch2_trans_exit(&trans);
1451

1452
	return ret ?: ret2;
Kent Overstreet's avatar
Kent Overstreet committed
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
}

/*
 * Checks for inconsistencies that shouldn't happen, unless we have a bug.
 * Doesn't fix them yet, mainly because they haven't yet been observed:
 */
static int bch2_fsck_full(struct bch_fs *c)
{
	struct bch_inode_unpacked root_inode, lostfound_inode;
	int ret;

	bch_verbose(c, "starting fsck:");
	ret =   check_extents(c) ?:
		check_dirents(c) ?:
		check_xattrs(c) ?:
		check_root(c, &root_inode) ?:
		check_lostfound(c, &root_inode, &lostfound_inode) ?:
		check_directory_structure(c, &lostfound_inode) ?:
		check_inode_nlinks(c, &lostfound_inode);

	bch2_flush_fsck_errs(c);
	bch_verbose(c, "fsck done");

	return ret;
}

static int bch2_fsck_inode_nlink(struct bch_fs *c)
{
	struct bch_inode_unpacked root_inode, lostfound_inode;
	int ret;

	bch_verbose(c, "checking inode link counts:");
	ret =   check_root(c, &root_inode) ?:
		check_lostfound(c, &root_inode, &lostfound_inode) ?:
		check_inode_nlinks(c, &lostfound_inode);

	bch2_flush_fsck_errs(c);
	bch_verbose(c, "done");

	return ret;
}

static int bch2_fsck_walk_inodes_only(struct bch_fs *c)
{
	int ret;

	bch_verbose(c, "walking inodes:");
	ret = check_inodes_fast(c);

	bch2_flush_fsck_errs(c);
	bch_verbose(c, "done");

	return ret;
}

int bch2_fsck(struct bch_fs *c)
{
1510
	if (c->opts.fsck)
Kent Overstreet's avatar
Kent Overstreet committed
1511 1512
		return bch2_fsck_full(c);

1513 1514
	if (c->sb.clean)
		return 0;
Kent Overstreet's avatar
Kent Overstreet committed
1515

1516 1517 1518
	return c->sb.features & (1 << BCH_FEATURE_ATOMIC_NLINK)
		? bch2_fsck_walk_inodes_only(c)
		: bch2_fsck_inode_nlink(c);
Kent Overstreet's avatar
Kent Overstreet committed
1519
}