xref: /openbmc/u-boot/fs/ubifs/debug.c (revision 90c08fa0)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * This file is part of UBIFS.
4  *
5  * Copyright (C) 2006-2008 Nokia Corporation
6  *
7  * Authors: Artem Bityutskiy (Битюцкий Артём)
8  *          Adrian Hunter
9  */
10 
11 /*
12  * This file implements most of the debugging stuff which is compiled in only
13  * when it is enabled. But some debugging check functions are implemented in
14  * corresponding subsystem, just because they are closely related and utilize
15  * various local functions of those subsystems.
16  */
17 
18 #include <hexdump.h>
19 
20 #ifndef __UBOOT__
21 #include <linux/module.h>
22 #include <linux/debugfs.h>
23 #include <linux/math64.h>
24 #include <linux/uaccess.h>
25 #include <linux/random.h>
26 #else
27 #include <linux/compat.h>
28 #include <linux/err.h>
29 #endif
30 #include "ubifs.h"
31 
32 #ifndef __UBOOT__
33 static DEFINE_SPINLOCK(dbg_lock);
34 #endif
35 
36 static const char *get_key_fmt(int fmt)
37 {
38 	switch (fmt) {
39 	case UBIFS_SIMPLE_KEY_FMT:
40 		return "simple";
41 	default:
42 		return "unknown/invalid format";
43 	}
44 }
45 
46 static const char *get_key_hash(int hash)
47 {
48 	switch (hash) {
49 	case UBIFS_KEY_HASH_R5:
50 		return "R5";
51 	case UBIFS_KEY_HASH_TEST:
52 		return "test";
53 	default:
54 		return "unknown/invalid name hash";
55 	}
56 }
57 
58 static const char *get_key_type(int type)
59 {
60 	switch (type) {
61 	case UBIFS_INO_KEY:
62 		return "inode";
63 	case UBIFS_DENT_KEY:
64 		return "direntry";
65 	case UBIFS_XENT_KEY:
66 		return "xentry";
67 	case UBIFS_DATA_KEY:
68 		return "data";
69 	case UBIFS_TRUN_KEY:
70 		return "truncate";
71 	default:
72 		return "unknown/invalid key";
73 	}
74 }
75 
76 #ifndef __UBOOT__
77 static const char *get_dent_type(int type)
78 {
79 	switch (type) {
80 	case UBIFS_ITYPE_REG:
81 		return "file";
82 	case UBIFS_ITYPE_DIR:
83 		return "dir";
84 	case UBIFS_ITYPE_LNK:
85 		return "symlink";
86 	case UBIFS_ITYPE_BLK:
87 		return "blkdev";
88 	case UBIFS_ITYPE_CHR:
89 		return "char dev";
90 	case UBIFS_ITYPE_FIFO:
91 		return "fifo";
92 	case UBIFS_ITYPE_SOCK:
93 		return "socket";
94 	default:
95 		return "unknown/invalid type";
96 	}
97 }
98 #endif
99 
100 const char *dbg_snprintf_key(const struct ubifs_info *c,
101 			     const union ubifs_key *key, char *buffer, int len)
102 {
103 	char *p = buffer;
104 	int type = key_type(c, key);
105 
106 	if (c->key_fmt == UBIFS_SIMPLE_KEY_FMT) {
107 		switch (type) {
108 		case UBIFS_INO_KEY:
109 			len -= snprintf(p, len, "(%lu, %s)",
110 					(unsigned long)key_inum(c, key),
111 					get_key_type(type));
112 			break;
113 		case UBIFS_DENT_KEY:
114 		case UBIFS_XENT_KEY:
115 			len -= snprintf(p, len, "(%lu, %s, %#08x)",
116 					(unsigned long)key_inum(c, key),
117 					get_key_type(type), key_hash(c, key));
118 			break;
119 		case UBIFS_DATA_KEY:
120 			len -= snprintf(p, len, "(%lu, %s, %u)",
121 					(unsigned long)key_inum(c, key),
122 					get_key_type(type), key_block(c, key));
123 			break;
124 		case UBIFS_TRUN_KEY:
125 			len -= snprintf(p, len, "(%lu, %s)",
126 					(unsigned long)key_inum(c, key),
127 					get_key_type(type));
128 			break;
129 		default:
130 			len -= snprintf(p, len, "(bad key type: %#08x, %#08x)",
131 					key->u32[0], key->u32[1]);
132 		}
133 	} else
134 		len -= snprintf(p, len, "bad key format %d", c->key_fmt);
135 	ubifs_assert(len > 0);
136 	return p;
137 }
138 
139 const char *dbg_ntype(int type)
140 {
141 	switch (type) {
142 	case UBIFS_PAD_NODE:
143 		return "padding node";
144 	case UBIFS_SB_NODE:
145 		return "superblock node";
146 	case UBIFS_MST_NODE:
147 		return "master node";
148 	case UBIFS_REF_NODE:
149 		return "reference node";
150 	case UBIFS_INO_NODE:
151 		return "inode node";
152 	case UBIFS_DENT_NODE:
153 		return "direntry node";
154 	case UBIFS_XENT_NODE:
155 		return "xentry node";
156 	case UBIFS_DATA_NODE:
157 		return "data node";
158 	case UBIFS_TRUN_NODE:
159 		return "truncate node";
160 	case UBIFS_IDX_NODE:
161 		return "indexing node";
162 	case UBIFS_CS_NODE:
163 		return "commit start node";
164 	case UBIFS_ORPH_NODE:
165 		return "orphan node";
166 	default:
167 		return "unknown node";
168 	}
169 }
170 
171 static const char *dbg_gtype(int type)
172 {
173 	switch (type) {
174 	case UBIFS_NO_NODE_GROUP:
175 		return "no node group";
176 	case UBIFS_IN_NODE_GROUP:
177 		return "in node group";
178 	case UBIFS_LAST_OF_NODE_GROUP:
179 		return "last of node group";
180 	default:
181 		return "unknown";
182 	}
183 }
184 
185 const char *dbg_cstate(int cmt_state)
186 {
187 	switch (cmt_state) {
188 	case COMMIT_RESTING:
189 		return "commit resting";
190 	case COMMIT_BACKGROUND:
191 		return "background commit requested";
192 	case COMMIT_REQUIRED:
193 		return "commit required";
194 	case COMMIT_RUNNING_BACKGROUND:
195 		return "BACKGROUND commit running";
196 	case COMMIT_RUNNING_REQUIRED:
197 		return "commit running and required";
198 	case COMMIT_BROKEN:
199 		return "broken commit";
200 	default:
201 		return "unknown commit state";
202 	}
203 }
204 
205 const char *dbg_jhead(int jhead)
206 {
207 	switch (jhead) {
208 	case GCHD:
209 		return "0 (GC)";
210 	case BASEHD:
211 		return "1 (base)";
212 	case DATAHD:
213 		return "2 (data)";
214 	default:
215 		return "unknown journal head";
216 	}
217 }
218 
219 static void dump_ch(const struct ubifs_ch *ch)
220 {
221 	pr_err("\tmagic          %#x\n", le32_to_cpu(ch->magic));
222 	pr_err("\tcrc            %#x\n", le32_to_cpu(ch->crc));
223 	pr_err("\tnode_type      %d (%s)\n", ch->node_type,
224 	       dbg_ntype(ch->node_type));
225 	pr_err("\tgroup_type     %d (%s)\n", ch->group_type,
226 	       dbg_gtype(ch->group_type));
227 	pr_err("\tsqnum          %llu\n",
228 	       (unsigned long long)le64_to_cpu(ch->sqnum));
229 	pr_err("\tlen            %u\n", le32_to_cpu(ch->len));
230 }
231 
232 void ubifs_dump_inode(struct ubifs_info *c, const struct inode *inode)
233 {
234 #ifndef __UBOOT__
235 	const struct ubifs_inode *ui = ubifs_inode(inode);
236 	struct qstr nm = { .name = NULL };
237 	union ubifs_key key;
238 	struct ubifs_dent_node *dent, *pdent = NULL;
239 	int count = 2;
240 
241 	pr_err("Dump in-memory inode:");
242 	pr_err("\tinode          %lu\n", inode->i_ino);
243 	pr_err("\tsize           %llu\n",
244 	       (unsigned long long)i_size_read(inode));
245 	pr_err("\tnlink          %u\n", inode->i_nlink);
246 	pr_err("\tuid            %u\n", (unsigned int)i_uid_read(inode));
247 	pr_err("\tgid            %u\n", (unsigned int)i_gid_read(inode));
248 	pr_err("\tatime          %u.%u\n",
249 	       (unsigned int)inode->i_atime.tv_sec,
250 	       (unsigned int)inode->i_atime.tv_nsec);
251 	pr_err("\tmtime          %u.%u\n",
252 	       (unsigned int)inode->i_mtime.tv_sec,
253 	       (unsigned int)inode->i_mtime.tv_nsec);
254 	pr_err("\tctime          %u.%u\n",
255 	       (unsigned int)inode->i_ctime.tv_sec,
256 	       (unsigned int)inode->i_ctime.tv_nsec);
257 	pr_err("\tcreat_sqnum    %llu\n", ui->creat_sqnum);
258 	pr_err("\txattr_size     %u\n", ui->xattr_size);
259 	pr_err("\txattr_cnt      %u\n", ui->xattr_cnt);
260 	pr_err("\txattr_names    %u\n", ui->xattr_names);
261 	pr_err("\tdirty          %u\n", ui->dirty);
262 	pr_err("\txattr          %u\n", ui->xattr);
263 	pr_err("\tbulk_read      %u\n", ui->xattr);
264 	pr_err("\tsynced_i_size  %llu\n",
265 	       (unsigned long long)ui->synced_i_size);
266 	pr_err("\tui_size        %llu\n",
267 	       (unsigned long long)ui->ui_size);
268 	pr_err("\tflags          %d\n", ui->flags);
269 	pr_err("\tcompr_type     %d\n", ui->compr_type);
270 	pr_err("\tlast_page_read %lu\n", ui->last_page_read);
271 	pr_err("\tread_in_a_row  %lu\n", ui->read_in_a_row);
272 	pr_err("\tdata_len       %d\n", ui->data_len);
273 
274 	if (!S_ISDIR(inode->i_mode))
275 		return;
276 
277 	pr_err("List of directory entries:\n");
278 	ubifs_assert(!mutex_is_locked(&c->tnc_mutex));
279 
280 	lowest_dent_key(c, &key, inode->i_ino);
281 	while (1) {
282 		dent = ubifs_tnc_next_ent(c, &key, &nm);
283 		if (IS_ERR(dent)) {
284 			if (PTR_ERR(dent) != -ENOENT)
285 				pr_err("error %ld\n", PTR_ERR(dent));
286 			break;
287 		}
288 
289 		pr_err("\t%d: %s (%s)\n",
290 		       count++, dent->name, get_dent_type(dent->type));
291 
292 		nm.name = dent->name;
293 		nm.len = le16_to_cpu(dent->nlen);
294 		kfree(pdent);
295 		pdent = dent;
296 		key_read(c, &dent->key, &key);
297 	}
298 	kfree(pdent);
299 #endif
300 }
301 
302 void ubifs_dump_node(const struct ubifs_info *c, const void *node)
303 {
304 	int i, n;
305 	union ubifs_key key;
306 	const struct ubifs_ch *ch = node;
307 	char key_buf[DBG_KEY_BUF_LEN];
308 
309 	/* If the magic is incorrect, just hexdump the first bytes */
310 	if (le32_to_cpu(ch->magic) != UBIFS_NODE_MAGIC) {
311 		pr_err("Not a node, first %zu bytes:", UBIFS_CH_SZ);
312 		print_hex_dump("", DUMP_PREFIX_OFFSET, 32, 1,
313 			       (void *)node, UBIFS_CH_SZ, 1);
314 		return;
315 	}
316 
317 	spin_lock(&dbg_lock);
318 	dump_ch(node);
319 
320 	switch (ch->node_type) {
321 	case UBIFS_PAD_NODE:
322 	{
323 		const struct ubifs_pad_node *pad = node;
324 
325 		pr_err("\tpad_len        %u\n", le32_to_cpu(pad->pad_len));
326 		break;
327 	}
328 	case UBIFS_SB_NODE:
329 	{
330 		const struct ubifs_sb_node *sup = node;
331 		unsigned int sup_flags = le32_to_cpu(sup->flags);
332 
333 		pr_err("\tkey_hash       %d (%s)\n",
334 		       (int)sup->key_hash, get_key_hash(sup->key_hash));
335 		pr_err("\tkey_fmt        %d (%s)\n",
336 		       (int)sup->key_fmt, get_key_fmt(sup->key_fmt));
337 		pr_err("\tflags          %#x\n", sup_flags);
338 		pr_err("\tbig_lpt        %u\n",
339 		       !!(sup_flags & UBIFS_FLG_BIGLPT));
340 		pr_err("\tspace_fixup    %u\n",
341 		       !!(sup_flags & UBIFS_FLG_SPACE_FIXUP));
342 		pr_err("\tmin_io_size    %u\n", le32_to_cpu(sup->min_io_size));
343 		pr_err("\tleb_size       %u\n", le32_to_cpu(sup->leb_size));
344 		pr_err("\tleb_cnt        %u\n", le32_to_cpu(sup->leb_cnt));
345 		pr_err("\tmax_leb_cnt    %u\n", le32_to_cpu(sup->max_leb_cnt));
346 		pr_err("\tmax_bud_bytes  %llu\n",
347 		       (unsigned long long)le64_to_cpu(sup->max_bud_bytes));
348 		pr_err("\tlog_lebs       %u\n", le32_to_cpu(sup->log_lebs));
349 		pr_err("\tlpt_lebs       %u\n", le32_to_cpu(sup->lpt_lebs));
350 		pr_err("\torph_lebs      %u\n", le32_to_cpu(sup->orph_lebs));
351 		pr_err("\tjhead_cnt      %u\n", le32_to_cpu(sup->jhead_cnt));
352 		pr_err("\tfanout         %u\n", le32_to_cpu(sup->fanout));
353 		pr_err("\tlsave_cnt      %u\n", le32_to_cpu(sup->lsave_cnt));
354 		pr_err("\tdefault_compr  %u\n",
355 		       (int)le16_to_cpu(sup->default_compr));
356 		pr_err("\trp_size        %llu\n",
357 		       (unsigned long long)le64_to_cpu(sup->rp_size));
358 		pr_err("\trp_uid         %u\n", le32_to_cpu(sup->rp_uid));
359 		pr_err("\trp_gid         %u\n", le32_to_cpu(sup->rp_gid));
360 		pr_err("\tfmt_version    %u\n", le32_to_cpu(sup->fmt_version));
361 		pr_err("\ttime_gran      %u\n", le32_to_cpu(sup->time_gran));
362 		pr_err("\tUUID           %pUB\n", sup->uuid);
363 		break;
364 	}
365 	case UBIFS_MST_NODE:
366 	{
367 		const struct ubifs_mst_node *mst = node;
368 
369 		pr_err("\thighest_inum   %llu\n",
370 		       (unsigned long long)le64_to_cpu(mst->highest_inum));
371 		pr_err("\tcommit number  %llu\n",
372 		       (unsigned long long)le64_to_cpu(mst->cmt_no));
373 		pr_err("\tflags          %#x\n", le32_to_cpu(mst->flags));
374 		pr_err("\tlog_lnum       %u\n", le32_to_cpu(mst->log_lnum));
375 		pr_err("\troot_lnum      %u\n", le32_to_cpu(mst->root_lnum));
376 		pr_err("\troot_offs      %u\n", le32_to_cpu(mst->root_offs));
377 		pr_err("\troot_len       %u\n", le32_to_cpu(mst->root_len));
378 		pr_err("\tgc_lnum        %u\n", le32_to_cpu(mst->gc_lnum));
379 		pr_err("\tihead_lnum     %u\n", le32_to_cpu(mst->ihead_lnum));
380 		pr_err("\tihead_offs     %u\n", le32_to_cpu(mst->ihead_offs));
381 		pr_err("\tindex_size     %llu\n",
382 		       (unsigned long long)le64_to_cpu(mst->index_size));
383 		pr_err("\tlpt_lnum       %u\n", le32_to_cpu(mst->lpt_lnum));
384 		pr_err("\tlpt_offs       %u\n", le32_to_cpu(mst->lpt_offs));
385 		pr_err("\tnhead_lnum     %u\n", le32_to_cpu(mst->nhead_lnum));
386 		pr_err("\tnhead_offs     %u\n", le32_to_cpu(mst->nhead_offs));
387 		pr_err("\tltab_lnum      %u\n", le32_to_cpu(mst->ltab_lnum));
388 		pr_err("\tltab_offs      %u\n", le32_to_cpu(mst->ltab_offs));
389 		pr_err("\tlsave_lnum     %u\n", le32_to_cpu(mst->lsave_lnum));
390 		pr_err("\tlsave_offs     %u\n", le32_to_cpu(mst->lsave_offs));
391 		pr_err("\tlscan_lnum     %u\n", le32_to_cpu(mst->lscan_lnum));
392 		pr_err("\tleb_cnt        %u\n", le32_to_cpu(mst->leb_cnt));
393 		pr_err("\tempty_lebs     %u\n", le32_to_cpu(mst->empty_lebs));
394 		pr_err("\tidx_lebs       %u\n", le32_to_cpu(mst->idx_lebs));
395 		pr_err("\ttotal_free     %llu\n",
396 		       (unsigned long long)le64_to_cpu(mst->total_free));
397 		pr_err("\ttotal_dirty    %llu\n",
398 		       (unsigned long long)le64_to_cpu(mst->total_dirty));
399 		pr_err("\ttotal_used     %llu\n",
400 		       (unsigned long long)le64_to_cpu(mst->total_used));
401 		pr_err("\ttotal_dead     %llu\n",
402 		       (unsigned long long)le64_to_cpu(mst->total_dead));
403 		pr_err("\ttotal_dark     %llu\n",
404 		       (unsigned long long)le64_to_cpu(mst->total_dark));
405 		break;
406 	}
407 	case UBIFS_REF_NODE:
408 	{
409 		const struct ubifs_ref_node *ref = node;
410 
411 		pr_err("\tlnum           %u\n", le32_to_cpu(ref->lnum));
412 		pr_err("\toffs           %u\n", le32_to_cpu(ref->offs));
413 		pr_err("\tjhead          %u\n", le32_to_cpu(ref->jhead));
414 		break;
415 	}
416 	case UBIFS_INO_NODE:
417 	{
418 		const struct ubifs_ino_node *ino = node;
419 
420 		key_read(c, &ino->key, &key);
421 		pr_err("\tkey            %s\n",
422 		       dbg_snprintf_key(c, &key, key_buf, DBG_KEY_BUF_LEN));
423 		pr_err("\tcreat_sqnum    %llu\n",
424 		       (unsigned long long)le64_to_cpu(ino->creat_sqnum));
425 		pr_err("\tsize           %llu\n",
426 		       (unsigned long long)le64_to_cpu(ino->size));
427 		pr_err("\tnlink          %u\n", le32_to_cpu(ino->nlink));
428 		pr_err("\tatime          %lld.%u\n",
429 		       (long long)le64_to_cpu(ino->atime_sec),
430 		       le32_to_cpu(ino->atime_nsec));
431 		pr_err("\tmtime          %lld.%u\n",
432 		       (long long)le64_to_cpu(ino->mtime_sec),
433 		       le32_to_cpu(ino->mtime_nsec));
434 		pr_err("\tctime          %lld.%u\n",
435 		       (long long)le64_to_cpu(ino->ctime_sec),
436 		       le32_to_cpu(ino->ctime_nsec));
437 		pr_err("\tuid            %u\n", le32_to_cpu(ino->uid));
438 		pr_err("\tgid            %u\n", le32_to_cpu(ino->gid));
439 		pr_err("\tmode           %u\n", le32_to_cpu(ino->mode));
440 		pr_err("\tflags          %#x\n", le32_to_cpu(ino->flags));
441 		pr_err("\txattr_cnt      %u\n", le32_to_cpu(ino->xattr_cnt));
442 		pr_err("\txattr_size     %u\n", le32_to_cpu(ino->xattr_size));
443 		pr_err("\txattr_names    %u\n", le32_to_cpu(ino->xattr_names));
444 		pr_err("\tcompr_type     %#x\n",
445 		       (int)le16_to_cpu(ino->compr_type));
446 		pr_err("\tdata len       %u\n", le32_to_cpu(ino->data_len));
447 		break;
448 	}
449 	case UBIFS_DENT_NODE:
450 	case UBIFS_XENT_NODE:
451 	{
452 		const struct ubifs_dent_node *dent = node;
453 		int nlen = le16_to_cpu(dent->nlen);
454 
455 		key_read(c, &dent->key, &key);
456 		pr_err("\tkey            %s\n",
457 		       dbg_snprintf_key(c, &key, key_buf, DBG_KEY_BUF_LEN));
458 		pr_err("\tinum           %llu\n",
459 		       (unsigned long long)le64_to_cpu(dent->inum));
460 		pr_err("\ttype           %d\n", (int)dent->type);
461 		pr_err("\tnlen           %d\n", nlen);
462 		pr_err("\tname           ");
463 
464 		if (nlen > UBIFS_MAX_NLEN)
465 			pr_err("(bad name length, not printing, bad or corrupted node)");
466 		else {
467 			for (i = 0; i < nlen && dent->name[i]; i++)
468 				pr_cont("%c", dent->name[i]);
469 		}
470 		pr_cont("\n");
471 
472 		break;
473 	}
474 	case UBIFS_DATA_NODE:
475 	{
476 		const struct ubifs_data_node *dn = node;
477 		int dlen = le32_to_cpu(ch->len) - UBIFS_DATA_NODE_SZ;
478 
479 		key_read(c, &dn->key, &key);
480 		pr_err("\tkey            %s\n",
481 		       dbg_snprintf_key(c, &key, key_buf, DBG_KEY_BUF_LEN));
482 		pr_err("\tsize           %u\n", le32_to_cpu(dn->size));
483 		pr_err("\tcompr_typ      %d\n",
484 		       (int)le16_to_cpu(dn->compr_type));
485 		pr_err("\tdata size      %d\n", dlen);
486 		pr_err("\tdata:\n");
487 		print_hex_dump("\t", DUMP_PREFIX_OFFSET, 32, 1,
488 			       (void *)&dn->data, dlen, 0);
489 		break;
490 	}
491 	case UBIFS_TRUN_NODE:
492 	{
493 		const struct ubifs_trun_node *trun = node;
494 
495 		pr_err("\tinum           %u\n", le32_to_cpu(trun->inum));
496 		pr_err("\told_size       %llu\n",
497 		       (unsigned long long)le64_to_cpu(trun->old_size));
498 		pr_err("\tnew_size       %llu\n",
499 		       (unsigned long long)le64_to_cpu(trun->new_size));
500 		break;
501 	}
502 	case UBIFS_IDX_NODE:
503 	{
504 		const struct ubifs_idx_node *idx = node;
505 
506 		n = le16_to_cpu(idx->child_cnt);
507 		pr_err("\tchild_cnt      %d\n", n);
508 		pr_err("\tlevel          %d\n", (int)le16_to_cpu(idx->level));
509 		pr_err("\tBranches:\n");
510 
511 		for (i = 0; i < n && i < c->fanout - 1; i++) {
512 			const struct ubifs_branch *br;
513 
514 			br = ubifs_idx_branch(c, idx, i);
515 			key_read(c, &br->key, &key);
516 			pr_err("\t%d: LEB %d:%d len %d key %s\n",
517 			       i, le32_to_cpu(br->lnum), le32_to_cpu(br->offs),
518 			       le32_to_cpu(br->len),
519 			       dbg_snprintf_key(c, &key, key_buf,
520 						DBG_KEY_BUF_LEN));
521 		}
522 		break;
523 	}
524 	case UBIFS_CS_NODE:
525 		break;
526 	case UBIFS_ORPH_NODE:
527 	{
528 		const struct ubifs_orph_node *orph = node;
529 
530 		pr_err("\tcommit number  %llu\n",
531 		       (unsigned long long)
532 				le64_to_cpu(orph->cmt_no) & LLONG_MAX);
533 		pr_err("\tlast node flag %llu\n",
534 		       (unsigned long long)(le64_to_cpu(orph->cmt_no)) >> 63);
535 		n = (le32_to_cpu(ch->len) - UBIFS_ORPH_NODE_SZ) >> 3;
536 		pr_err("\t%d orphan inode numbers:\n", n);
537 		for (i = 0; i < n; i++)
538 			pr_err("\t  ino %llu\n",
539 			       (unsigned long long)le64_to_cpu(orph->inos[i]));
540 		break;
541 	}
542 	default:
543 		pr_err("node type %d was not recognized\n",
544 		       (int)ch->node_type);
545 	}
546 	spin_unlock(&dbg_lock);
547 }
548 
549 void ubifs_dump_budget_req(const struct ubifs_budget_req *req)
550 {
551 	spin_lock(&dbg_lock);
552 	pr_err("Budgeting request: new_ino %d, dirtied_ino %d\n",
553 	       req->new_ino, req->dirtied_ino);
554 	pr_err("\tnew_ino_d   %d, dirtied_ino_d %d\n",
555 	       req->new_ino_d, req->dirtied_ino_d);
556 	pr_err("\tnew_page    %d, dirtied_page %d\n",
557 	       req->new_page, req->dirtied_page);
558 	pr_err("\tnew_dent    %d, mod_dent     %d\n",
559 	       req->new_dent, req->mod_dent);
560 	pr_err("\tidx_growth  %d\n", req->idx_growth);
561 	pr_err("\tdata_growth %d dd_growth     %d\n",
562 	       req->data_growth, req->dd_growth);
563 	spin_unlock(&dbg_lock);
564 }
565 
566 void ubifs_dump_lstats(const struct ubifs_lp_stats *lst)
567 {
568 	spin_lock(&dbg_lock);
569 	pr_err("(pid %d) Lprops statistics: empty_lebs %d, idx_lebs  %d\n",
570 	       current->pid, lst->empty_lebs, lst->idx_lebs);
571 	pr_err("\ttaken_empty_lebs %d, total_free %lld, total_dirty %lld\n",
572 	       lst->taken_empty_lebs, lst->total_free, lst->total_dirty);
573 	pr_err("\ttotal_used %lld, total_dark %lld, total_dead %lld\n",
574 	       lst->total_used, lst->total_dark, lst->total_dead);
575 	spin_unlock(&dbg_lock);
576 }
577 
578 #ifndef __UBOOT__
579 void ubifs_dump_budg(struct ubifs_info *c, const struct ubifs_budg_info *bi)
580 {
581 	int i;
582 	struct rb_node *rb;
583 	struct ubifs_bud *bud;
584 	struct ubifs_gced_idx_leb *idx_gc;
585 	long long available, outstanding, free;
586 
587 	spin_lock(&c->space_lock);
588 	spin_lock(&dbg_lock);
589 	pr_err("(pid %d) Budgeting info: data budget sum %lld, total budget sum %lld\n",
590 	       current->pid, bi->data_growth + bi->dd_growth,
591 	       bi->data_growth + bi->dd_growth + bi->idx_growth);
592 	pr_err("\tbudg_data_growth %lld, budg_dd_growth %lld, budg_idx_growth %lld\n",
593 	       bi->data_growth, bi->dd_growth, bi->idx_growth);
594 	pr_err("\tmin_idx_lebs %d, old_idx_sz %llu, uncommitted_idx %lld\n",
595 	       bi->min_idx_lebs, bi->old_idx_sz, bi->uncommitted_idx);
596 	pr_err("\tpage_budget %d, inode_budget %d, dent_budget %d\n",
597 	       bi->page_budget, bi->inode_budget, bi->dent_budget);
598 	pr_err("\tnospace %u, nospace_rp %u\n", bi->nospace, bi->nospace_rp);
599 	pr_err("\tdark_wm %d, dead_wm %d, max_idx_node_sz %d\n",
600 	       c->dark_wm, c->dead_wm, c->max_idx_node_sz);
601 
602 	if (bi != &c->bi)
603 		/*
604 		 * If we are dumping saved budgeting data, do not print
605 		 * additional information which is about the current state, not
606 		 * the old one which corresponded to the saved budgeting data.
607 		 */
608 		goto out_unlock;
609 
610 	pr_err("\tfreeable_cnt %d, calc_idx_sz %lld, idx_gc_cnt %d\n",
611 	       c->freeable_cnt, c->calc_idx_sz, c->idx_gc_cnt);
612 	pr_err("\tdirty_pg_cnt %ld, dirty_zn_cnt %ld, clean_zn_cnt %ld\n",
613 	       atomic_long_read(&c->dirty_pg_cnt),
614 	       atomic_long_read(&c->dirty_zn_cnt),
615 	       atomic_long_read(&c->clean_zn_cnt));
616 	pr_err("\tgc_lnum %d, ihead_lnum %d\n", c->gc_lnum, c->ihead_lnum);
617 
618 	/* If we are in R/O mode, journal heads do not exist */
619 	if (c->jheads)
620 		for (i = 0; i < c->jhead_cnt; i++)
621 			pr_err("\tjhead %s\t LEB %d\n",
622 			       dbg_jhead(c->jheads[i].wbuf.jhead),
623 			       c->jheads[i].wbuf.lnum);
624 	for (rb = rb_first(&c->buds); rb; rb = rb_next(rb)) {
625 		bud = rb_entry(rb, struct ubifs_bud, rb);
626 		pr_err("\tbud LEB %d\n", bud->lnum);
627 	}
628 	list_for_each_entry(bud, &c->old_buds, list)
629 		pr_err("\told bud LEB %d\n", bud->lnum);
630 	list_for_each_entry(idx_gc, &c->idx_gc, list)
631 		pr_err("\tGC'ed idx LEB %d unmap %d\n",
632 		       idx_gc->lnum, idx_gc->unmap);
633 	pr_err("\tcommit state %d\n", c->cmt_state);
634 
635 	/* Print budgeting predictions */
636 	available = ubifs_calc_available(c, c->bi.min_idx_lebs);
637 	outstanding = c->bi.data_growth + c->bi.dd_growth;
638 	free = ubifs_get_free_space_nolock(c);
639 	pr_err("Budgeting predictions:\n");
640 	pr_err("\tavailable: %lld, outstanding %lld, free %lld\n",
641 	       available, outstanding, free);
642 out_unlock:
643 	spin_unlock(&dbg_lock);
644 	spin_unlock(&c->space_lock);
645 }
646 #else
647 void ubifs_dump_budg(struct ubifs_info *c, const struct ubifs_budg_info *bi)
648 {
649 }
650 #endif
651 
652 void ubifs_dump_lprop(const struct ubifs_info *c, const struct ubifs_lprops *lp)
653 {
654 	int i, spc, dark = 0, dead = 0;
655 	struct rb_node *rb;
656 	struct ubifs_bud *bud;
657 
658 	spc = lp->free + lp->dirty;
659 	if (spc < c->dead_wm)
660 		dead = spc;
661 	else
662 		dark = ubifs_calc_dark(c, spc);
663 
664 	if (lp->flags & LPROPS_INDEX)
665 		pr_err("LEB %-7d free %-8d dirty %-8d used %-8d free + dirty %-8d flags %#x (",
666 		       lp->lnum, lp->free, lp->dirty, c->leb_size - spc, spc,
667 		       lp->flags);
668 	else
669 		pr_err("LEB %-7d free %-8d dirty %-8d used %-8d free + dirty %-8d dark %-4d dead %-4d nodes fit %-3d flags %#-4x (",
670 		       lp->lnum, lp->free, lp->dirty, c->leb_size - spc, spc,
671 		       dark, dead, (int)(spc / UBIFS_MAX_NODE_SZ), lp->flags);
672 
673 	if (lp->flags & LPROPS_TAKEN) {
674 		if (lp->flags & LPROPS_INDEX)
675 			pr_cont("index, taken");
676 		else
677 			pr_cont("taken");
678 	} else {
679 		const char *s;
680 
681 		if (lp->flags & LPROPS_INDEX) {
682 			switch (lp->flags & LPROPS_CAT_MASK) {
683 			case LPROPS_DIRTY_IDX:
684 				s = "dirty index";
685 				break;
686 			case LPROPS_FRDI_IDX:
687 				s = "freeable index";
688 				break;
689 			default:
690 				s = "index";
691 			}
692 		} else {
693 			switch (lp->flags & LPROPS_CAT_MASK) {
694 			case LPROPS_UNCAT:
695 				s = "not categorized";
696 				break;
697 			case LPROPS_DIRTY:
698 				s = "dirty";
699 				break;
700 			case LPROPS_FREE:
701 				s = "free";
702 				break;
703 			case LPROPS_EMPTY:
704 				s = "empty";
705 				break;
706 			case LPROPS_FREEABLE:
707 				s = "freeable";
708 				break;
709 			default:
710 				s = NULL;
711 				break;
712 			}
713 		}
714 		pr_cont("%s", s);
715 	}
716 
717 	for (rb = rb_first((struct rb_root *)&c->buds); rb; rb = rb_next(rb)) {
718 		bud = rb_entry(rb, struct ubifs_bud, rb);
719 		if (bud->lnum == lp->lnum) {
720 			int head = 0;
721 			for (i = 0; i < c->jhead_cnt; i++) {
722 				/*
723 				 * Note, if we are in R/O mode or in the middle
724 				 * of mounting/re-mounting, the write-buffers do
725 				 * not exist.
726 				 */
727 				if (c->jheads &&
728 				    lp->lnum == c->jheads[i].wbuf.lnum) {
729 					pr_cont(", jhead %s", dbg_jhead(i));
730 					head = 1;
731 				}
732 			}
733 			if (!head)
734 				pr_cont(", bud of jhead %s",
735 				       dbg_jhead(bud->jhead));
736 		}
737 	}
738 	if (lp->lnum == c->gc_lnum)
739 		pr_cont(", GC LEB");
740 	pr_cont(")\n");
741 }
742 
743 void ubifs_dump_lprops(struct ubifs_info *c)
744 {
745 	int lnum, err;
746 	struct ubifs_lprops lp;
747 	struct ubifs_lp_stats lst;
748 
749 	pr_err("(pid %d) start dumping LEB properties\n", current->pid);
750 	ubifs_get_lp_stats(c, &lst);
751 	ubifs_dump_lstats(&lst);
752 
753 	for (lnum = c->main_first; lnum < c->leb_cnt; lnum++) {
754 		err = ubifs_read_one_lp(c, lnum, &lp);
755 		if (err) {
756 			ubifs_err(c, "cannot read lprops for LEB %d", lnum);
757 			continue;
758 		}
759 
760 		ubifs_dump_lprop(c, &lp);
761 	}
762 	pr_err("(pid %d) finish dumping LEB properties\n", current->pid);
763 }
764 
765 void ubifs_dump_lpt_info(struct ubifs_info *c)
766 {
767 	int i;
768 
769 	spin_lock(&dbg_lock);
770 	pr_err("(pid %d) dumping LPT information\n", current->pid);
771 	pr_err("\tlpt_sz:        %lld\n", c->lpt_sz);
772 	pr_err("\tpnode_sz:      %d\n", c->pnode_sz);
773 	pr_err("\tnnode_sz:      %d\n", c->nnode_sz);
774 	pr_err("\tltab_sz:       %d\n", c->ltab_sz);
775 	pr_err("\tlsave_sz:      %d\n", c->lsave_sz);
776 	pr_err("\tbig_lpt:       %d\n", c->big_lpt);
777 	pr_err("\tlpt_hght:      %d\n", c->lpt_hght);
778 	pr_err("\tpnode_cnt:     %d\n", c->pnode_cnt);
779 	pr_err("\tnnode_cnt:     %d\n", c->nnode_cnt);
780 	pr_err("\tdirty_pn_cnt:  %d\n", c->dirty_pn_cnt);
781 	pr_err("\tdirty_nn_cnt:  %d\n", c->dirty_nn_cnt);
782 	pr_err("\tlsave_cnt:     %d\n", c->lsave_cnt);
783 	pr_err("\tspace_bits:    %d\n", c->space_bits);
784 	pr_err("\tlpt_lnum_bits: %d\n", c->lpt_lnum_bits);
785 	pr_err("\tlpt_offs_bits: %d\n", c->lpt_offs_bits);
786 	pr_err("\tlpt_spc_bits:  %d\n", c->lpt_spc_bits);
787 	pr_err("\tpcnt_bits:     %d\n", c->pcnt_bits);
788 	pr_err("\tlnum_bits:     %d\n", c->lnum_bits);
789 	pr_err("\tLPT root is at %d:%d\n", c->lpt_lnum, c->lpt_offs);
790 	pr_err("\tLPT head is at %d:%d\n",
791 	       c->nhead_lnum, c->nhead_offs);
792 	pr_err("\tLPT ltab is at %d:%d\n", c->ltab_lnum, c->ltab_offs);
793 	if (c->big_lpt)
794 		pr_err("\tLPT lsave is at %d:%d\n",
795 		       c->lsave_lnum, c->lsave_offs);
796 	for (i = 0; i < c->lpt_lebs; i++)
797 		pr_err("\tLPT LEB %d free %d dirty %d tgc %d cmt %d\n",
798 		       i + c->lpt_first, c->ltab[i].free, c->ltab[i].dirty,
799 		       c->ltab[i].tgc, c->ltab[i].cmt);
800 	spin_unlock(&dbg_lock);
801 }
802 
803 void ubifs_dump_sleb(const struct ubifs_info *c,
804 		     const struct ubifs_scan_leb *sleb, int offs)
805 {
806 	struct ubifs_scan_node *snod;
807 
808 	pr_err("(pid %d) start dumping scanned data from LEB %d:%d\n",
809 	       current->pid, sleb->lnum, offs);
810 
811 	list_for_each_entry(snod, &sleb->nodes, list) {
812 		cond_resched();
813 		pr_err("Dumping node at LEB %d:%d len %d\n",
814 		       sleb->lnum, snod->offs, snod->len);
815 		ubifs_dump_node(c, snod->node);
816 	}
817 }
818 
819 void ubifs_dump_leb(const struct ubifs_info *c, int lnum)
820 {
821 	struct ubifs_scan_leb *sleb;
822 	struct ubifs_scan_node *snod;
823 	void *buf;
824 
825 	pr_err("(pid %d) start dumping LEB %d\n", current->pid, lnum);
826 
827 	buf = __vmalloc(c->leb_size, GFP_NOFS, PAGE_KERNEL);
828 	if (!buf) {
829 		ubifs_err(c, "cannot allocate memory for dumping LEB %d", lnum);
830 		return;
831 	}
832 
833 	sleb = ubifs_scan(c, lnum, 0, buf, 0);
834 	if (IS_ERR(sleb)) {
835 		ubifs_err(c, "scan error %d", (int)PTR_ERR(sleb));
836 		goto out;
837 	}
838 
839 	pr_err("LEB %d has %d nodes ending at %d\n", lnum,
840 	       sleb->nodes_cnt, sleb->endpt);
841 
842 	list_for_each_entry(snod, &sleb->nodes, list) {
843 		cond_resched();
844 		pr_err("Dumping node at LEB %d:%d len %d\n", lnum,
845 		       snod->offs, snod->len);
846 		ubifs_dump_node(c, snod->node);
847 	}
848 
849 	pr_err("(pid %d) finish dumping LEB %d\n", current->pid, lnum);
850 	ubifs_scan_destroy(sleb);
851 
852 out:
853 	vfree(buf);
854 	return;
855 }
856 
857 void ubifs_dump_znode(const struct ubifs_info *c,
858 		      const struct ubifs_znode *znode)
859 {
860 	int n;
861 	const struct ubifs_zbranch *zbr;
862 	char key_buf[DBG_KEY_BUF_LEN];
863 
864 	spin_lock(&dbg_lock);
865 	if (znode->parent)
866 		zbr = &znode->parent->zbranch[znode->iip];
867 	else
868 		zbr = &c->zroot;
869 
870 	pr_err("znode %p, LEB %d:%d len %d parent %p iip %d level %d child_cnt %d flags %lx\n",
871 	       znode, zbr->lnum, zbr->offs, zbr->len, znode->parent, znode->iip,
872 	       znode->level, znode->child_cnt, znode->flags);
873 
874 	if (znode->child_cnt <= 0 || znode->child_cnt > c->fanout) {
875 		spin_unlock(&dbg_lock);
876 		return;
877 	}
878 
879 	pr_err("zbranches:\n");
880 	for (n = 0; n < znode->child_cnt; n++) {
881 		zbr = &znode->zbranch[n];
882 		if (znode->level > 0)
883 			pr_err("\t%d: znode %p LEB %d:%d len %d key %s\n",
884 			       n, zbr->znode, zbr->lnum, zbr->offs, zbr->len,
885 			       dbg_snprintf_key(c, &zbr->key, key_buf,
886 						DBG_KEY_BUF_LEN));
887 		else
888 			pr_err("\t%d: LNC %p LEB %d:%d len %d key %s\n",
889 			       n, zbr->znode, zbr->lnum, zbr->offs, zbr->len,
890 			       dbg_snprintf_key(c, &zbr->key, key_buf,
891 						DBG_KEY_BUF_LEN));
892 	}
893 	spin_unlock(&dbg_lock);
894 }
895 
896 void ubifs_dump_heap(struct ubifs_info *c, struct ubifs_lpt_heap *heap, int cat)
897 {
898 	int i;
899 
900 	pr_err("(pid %d) start dumping heap cat %d (%d elements)\n",
901 	       current->pid, cat, heap->cnt);
902 	for (i = 0; i < heap->cnt; i++) {
903 		struct ubifs_lprops *lprops = heap->arr[i];
904 
905 		pr_err("\t%d. LEB %d hpos %d free %d dirty %d flags %d\n",
906 		       i, lprops->lnum, lprops->hpos, lprops->free,
907 		       lprops->dirty, lprops->flags);
908 	}
909 	pr_err("(pid %d) finish dumping heap\n", current->pid);
910 }
911 
912 void ubifs_dump_pnode(struct ubifs_info *c, struct ubifs_pnode *pnode,
913 		      struct ubifs_nnode *parent, int iip)
914 {
915 	int i;
916 
917 	pr_err("(pid %d) dumping pnode:\n", current->pid);
918 	pr_err("\taddress %zx parent %zx cnext %zx\n",
919 	       (size_t)pnode, (size_t)parent, (size_t)pnode->cnext);
920 	pr_err("\tflags %lu iip %d level %d num %d\n",
921 	       pnode->flags, iip, pnode->level, pnode->num);
922 	for (i = 0; i < UBIFS_LPT_FANOUT; i++) {
923 		struct ubifs_lprops *lp = &pnode->lprops[i];
924 
925 		pr_err("\t%d: free %d dirty %d flags %d lnum %d\n",
926 		       i, lp->free, lp->dirty, lp->flags, lp->lnum);
927 	}
928 }
929 
930 void ubifs_dump_tnc(struct ubifs_info *c)
931 {
932 	struct ubifs_znode *znode;
933 	int level;
934 
935 	pr_err("\n");
936 	pr_err("(pid %d) start dumping TNC tree\n", current->pid);
937 	znode = ubifs_tnc_levelorder_next(c->zroot.znode, NULL);
938 	level = znode->level;
939 	pr_err("== Level %d ==\n", level);
940 	while (znode) {
941 		if (level != znode->level) {
942 			level = znode->level;
943 			pr_err("== Level %d ==\n", level);
944 		}
945 		ubifs_dump_znode(c, znode);
946 		znode = ubifs_tnc_levelorder_next(c->zroot.znode, znode);
947 	}
948 	pr_err("(pid %d) finish dumping TNC tree\n", current->pid);
949 }
950 
951 static int dump_znode(struct ubifs_info *c, struct ubifs_znode *znode,
952 		      void *priv)
953 {
954 	ubifs_dump_znode(c, znode);
955 	return 0;
956 }
957 
958 /**
959  * ubifs_dump_index - dump the on-flash index.
960  * @c: UBIFS file-system description object
961  *
962  * This function dumps whole UBIFS indexing B-tree, unlike 'ubifs_dump_tnc()'
963  * which dumps only in-memory znodes and does not read znodes which from flash.
964  */
965 void ubifs_dump_index(struct ubifs_info *c)
966 {
967 	dbg_walk_index(c, NULL, dump_znode, NULL);
968 }
969 
970 #ifndef __UBOOT__
971 /**
972  * dbg_save_space_info - save information about flash space.
973  * @c: UBIFS file-system description object
974  *
975  * This function saves information about UBIFS free space, dirty space, etc, in
976  * order to check it later.
977  */
978 void dbg_save_space_info(struct ubifs_info *c)
979 {
980 	struct ubifs_debug_info *d = c->dbg;
981 	int freeable_cnt;
982 
983 	spin_lock(&c->space_lock);
984 	memcpy(&d->saved_lst, &c->lst, sizeof(struct ubifs_lp_stats));
985 	memcpy(&d->saved_bi, &c->bi, sizeof(struct ubifs_budg_info));
986 	d->saved_idx_gc_cnt = c->idx_gc_cnt;
987 
988 	/*
989 	 * We use a dirty hack here and zero out @c->freeable_cnt, because it
990 	 * affects the free space calculations, and UBIFS might not know about
991 	 * all freeable eraseblocks. Indeed, we know about freeable eraseblocks
992 	 * only when we read their lprops, and we do this only lazily, upon the
993 	 * need. So at any given point of time @c->freeable_cnt might be not
994 	 * exactly accurate.
995 	 *
996 	 * Just one example about the issue we hit when we did not zero
997 	 * @c->freeable_cnt.
998 	 * 1. The file-system is mounted R/O, c->freeable_cnt is %0. We save the
999 	 *    amount of free space in @d->saved_free
1000 	 * 2. We re-mount R/W, which makes UBIFS to read the "lsave"
1001 	 *    information from flash, where we cache LEBs from various
1002 	 *    categories ('ubifs_remount_fs()' -> 'ubifs_lpt_init()'
1003 	 *    -> 'lpt_init_wr()' -> 'read_lsave()' -> 'ubifs_lpt_lookup()'
1004 	 *    -> 'ubifs_get_pnode()' -> 'update_cats()'
1005 	 *    -> 'ubifs_add_to_cat()').
1006 	 * 3. Lsave contains a freeable eraseblock, and @c->freeable_cnt
1007 	 *    becomes %1.
1008 	 * 4. We calculate the amount of free space when the re-mount is
1009 	 *    finished in 'dbg_check_space_info()' and it does not match
1010 	 *    @d->saved_free.
1011 	 */
1012 	freeable_cnt = c->freeable_cnt;
1013 	c->freeable_cnt = 0;
1014 	d->saved_free = ubifs_get_free_space_nolock(c);
1015 	c->freeable_cnt = freeable_cnt;
1016 	spin_unlock(&c->space_lock);
1017 }
1018 
1019 /**
1020  * dbg_check_space_info - check flash space information.
1021  * @c: UBIFS file-system description object
1022  *
1023  * This function compares current flash space information with the information
1024  * which was saved when the 'dbg_save_space_info()' function was called.
1025  * Returns zero if the information has not changed, and %-EINVAL it it has
1026  * changed.
1027  */
1028 int dbg_check_space_info(struct ubifs_info *c)
1029 {
1030 	struct ubifs_debug_info *d = c->dbg;
1031 	struct ubifs_lp_stats lst;
1032 	long long free;
1033 	int freeable_cnt;
1034 
1035 	spin_lock(&c->space_lock);
1036 	freeable_cnt = c->freeable_cnt;
1037 	c->freeable_cnt = 0;
1038 	free = ubifs_get_free_space_nolock(c);
1039 	c->freeable_cnt = freeable_cnt;
1040 	spin_unlock(&c->space_lock);
1041 
1042 	if (free != d->saved_free) {
1043 		ubifs_err(c, "free space changed from %lld to %lld",
1044 			  d->saved_free, free);
1045 		goto out;
1046 	}
1047 
1048 	return 0;
1049 
1050 out:
1051 	ubifs_msg(c, "saved lprops statistics dump");
1052 	ubifs_dump_lstats(&d->saved_lst);
1053 	ubifs_msg(c, "saved budgeting info dump");
1054 	ubifs_dump_budg(c, &d->saved_bi);
1055 	ubifs_msg(c, "saved idx_gc_cnt %d", d->saved_idx_gc_cnt);
1056 	ubifs_msg(c, "current lprops statistics dump");
1057 	ubifs_get_lp_stats(c, &lst);
1058 	ubifs_dump_lstats(&lst);
1059 	ubifs_msg(c, "current budgeting info dump");
1060 	ubifs_dump_budg(c, &c->bi);
1061 	dump_stack();
1062 	return -EINVAL;
1063 }
1064 
1065 /**
1066  * dbg_check_synced_i_size - check synchronized inode size.
1067  * @c: UBIFS file-system description object
1068  * @inode: inode to check
1069  *
1070  * If inode is clean, synchronized inode size has to be equivalent to current
1071  * inode size. This function has to be called only for locked inodes (@i_mutex
1072  * has to be locked). Returns %0 if synchronized inode size if correct, and
1073  * %-EINVAL if not.
1074  */
1075 int dbg_check_synced_i_size(const struct ubifs_info *c, struct inode *inode)
1076 {
1077 	int err = 0;
1078 	struct ubifs_inode *ui = ubifs_inode(inode);
1079 
1080 	if (!dbg_is_chk_gen(c))
1081 		return 0;
1082 	if (!S_ISREG(inode->i_mode))
1083 		return 0;
1084 
1085 	mutex_lock(&ui->ui_mutex);
1086 	spin_lock(&ui->ui_lock);
1087 	if (ui->ui_size != ui->synced_i_size && !ui->dirty) {
1088 		ubifs_err(c, "ui_size is %lld, synced_i_size is %lld, but inode is clean",
1089 			  ui->ui_size, ui->synced_i_size);
1090 		ubifs_err(c, "i_ino %lu, i_mode %#x, i_size %lld", inode->i_ino,
1091 			  inode->i_mode, i_size_read(inode));
1092 		dump_stack();
1093 		err = -EINVAL;
1094 	}
1095 	spin_unlock(&ui->ui_lock);
1096 	mutex_unlock(&ui->ui_mutex);
1097 	return err;
1098 }
1099 
1100 /*
1101  * dbg_check_dir - check directory inode size and link count.
1102  * @c: UBIFS file-system description object
1103  * @dir: the directory to calculate size for
1104  * @size: the result is returned here
1105  *
1106  * This function makes sure that directory size and link count are correct.
1107  * Returns zero in case of success and a negative error code in case of
1108  * failure.
1109  *
1110  * Note, it is good idea to make sure the @dir->i_mutex is locked before
1111  * calling this function.
1112  */
1113 int dbg_check_dir(struct ubifs_info *c, const struct inode *dir)
1114 {
1115 	unsigned int nlink = 2;
1116 	union ubifs_key key;
1117 	struct ubifs_dent_node *dent, *pdent = NULL;
1118 	struct qstr nm = { .name = NULL };
1119 	loff_t size = UBIFS_INO_NODE_SZ;
1120 
1121 	if (!dbg_is_chk_gen(c))
1122 		return 0;
1123 
1124 	if (!S_ISDIR(dir->i_mode))
1125 		return 0;
1126 
1127 	lowest_dent_key(c, &key, dir->i_ino);
1128 	while (1) {
1129 		int err;
1130 
1131 		dent = ubifs_tnc_next_ent(c, &key, &nm);
1132 		if (IS_ERR(dent)) {
1133 			err = PTR_ERR(dent);
1134 			if (err == -ENOENT)
1135 				break;
1136 			return err;
1137 		}
1138 
1139 		nm.name = dent->name;
1140 		nm.len = le16_to_cpu(dent->nlen);
1141 		size += CALC_DENT_SIZE(nm.len);
1142 		if (dent->type == UBIFS_ITYPE_DIR)
1143 			nlink += 1;
1144 		kfree(pdent);
1145 		pdent = dent;
1146 		key_read(c, &dent->key, &key);
1147 	}
1148 	kfree(pdent);
1149 
1150 	if (i_size_read(dir) != size) {
1151 		ubifs_err(c, "directory inode %lu has size %llu, but calculated size is %llu",
1152 			  dir->i_ino, (unsigned long long)i_size_read(dir),
1153 			  (unsigned long long)size);
1154 		ubifs_dump_inode(c, dir);
1155 		dump_stack();
1156 		return -EINVAL;
1157 	}
1158 	if (dir->i_nlink != nlink) {
1159 		ubifs_err(c, "directory inode %lu has nlink %u, but calculated nlink is %u",
1160 			  dir->i_ino, dir->i_nlink, nlink);
1161 		ubifs_dump_inode(c, dir);
1162 		dump_stack();
1163 		return -EINVAL;
1164 	}
1165 
1166 	return 0;
1167 }
1168 
1169 /**
1170  * dbg_check_key_order - make sure that colliding keys are properly ordered.
1171  * @c: UBIFS file-system description object
1172  * @zbr1: first zbranch
1173  * @zbr2: following zbranch
1174  *
1175  * In UBIFS indexing B-tree colliding keys has to be sorted in binary order of
1176  * names of the direntries/xentries which are referred by the keys. This
1177  * function reads direntries/xentries referred by @zbr1 and @zbr2 and makes
1178  * sure the name of direntry/xentry referred by @zbr1 is less than
1179  * direntry/xentry referred by @zbr2. Returns zero if this is true, %1 if not,
1180  * and a negative error code in case of failure.
1181  */
1182 static int dbg_check_key_order(struct ubifs_info *c, struct ubifs_zbranch *zbr1,
1183 			       struct ubifs_zbranch *zbr2)
1184 {
1185 	int err, nlen1, nlen2, cmp;
1186 	struct ubifs_dent_node *dent1, *dent2;
1187 	union ubifs_key key;
1188 	char key_buf[DBG_KEY_BUF_LEN];
1189 
1190 	ubifs_assert(!keys_cmp(c, &zbr1->key, &zbr2->key));
1191 	dent1 = kmalloc(UBIFS_MAX_DENT_NODE_SZ, GFP_NOFS);
1192 	if (!dent1)
1193 		return -ENOMEM;
1194 	dent2 = kmalloc(UBIFS_MAX_DENT_NODE_SZ, GFP_NOFS);
1195 	if (!dent2) {
1196 		err = -ENOMEM;
1197 		goto out_free;
1198 	}
1199 
1200 	err = ubifs_tnc_read_node(c, zbr1, dent1);
1201 	if (err)
1202 		goto out_free;
1203 	err = ubifs_validate_entry(c, dent1);
1204 	if (err)
1205 		goto out_free;
1206 
1207 	err = ubifs_tnc_read_node(c, zbr2, dent2);
1208 	if (err)
1209 		goto out_free;
1210 	err = ubifs_validate_entry(c, dent2);
1211 	if (err)
1212 		goto out_free;
1213 
1214 	/* Make sure node keys are the same as in zbranch */
1215 	err = 1;
1216 	key_read(c, &dent1->key, &key);
1217 	if (keys_cmp(c, &zbr1->key, &key)) {
1218 		ubifs_err(c, "1st entry at %d:%d has key %s", zbr1->lnum,
1219 			  zbr1->offs, dbg_snprintf_key(c, &key, key_buf,
1220 						       DBG_KEY_BUF_LEN));
1221 		ubifs_err(c, "but it should have key %s according to tnc",
1222 			  dbg_snprintf_key(c, &zbr1->key, key_buf,
1223 					   DBG_KEY_BUF_LEN));
1224 		ubifs_dump_node(c, dent1);
1225 		goto out_free;
1226 	}
1227 
1228 	key_read(c, &dent2->key, &key);
1229 	if (keys_cmp(c, &zbr2->key, &key)) {
1230 		ubifs_err(c, "2nd entry at %d:%d has key %s", zbr1->lnum,
1231 			  zbr1->offs, dbg_snprintf_key(c, &key, key_buf,
1232 						       DBG_KEY_BUF_LEN));
1233 		ubifs_err(c, "but it should have key %s according to tnc",
1234 			  dbg_snprintf_key(c, &zbr2->key, key_buf,
1235 					   DBG_KEY_BUF_LEN));
1236 		ubifs_dump_node(c, dent2);
1237 		goto out_free;
1238 	}
1239 
1240 	nlen1 = le16_to_cpu(dent1->nlen);
1241 	nlen2 = le16_to_cpu(dent2->nlen);
1242 
1243 	cmp = memcmp(dent1->name, dent2->name, min_t(int, nlen1, nlen2));
1244 	if (cmp < 0 || (cmp == 0 && nlen1 < nlen2)) {
1245 		err = 0;
1246 		goto out_free;
1247 	}
1248 	if (cmp == 0 && nlen1 == nlen2)
1249 		ubifs_err(c, "2 xent/dent nodes with the same name");
1250 	else
1251 		ubifs_err(c, "bad order of colliding key %s",
1252 			  dbg_snprintf_key(c, &key, key_buf, DBG_KEY_BUF_LEN));
1253 
1254 	ubifs_msg(c, "first node at %d:%d\n", zbr1->lnum, zbr1->offs);
1255 	ubifs_dump_node(c, dent1);
1256 	ubifs_msg(c, "second node at %d:%d\n", zbr2->lnum, zbr2->offs);
1257 	ubifs_dump_node(c, dent2);
1258 
1259 out_free:
1260 	kfree(dent2);
1261 	kfree(dent1);
1262 	return err;
1263 }
1264 
1265 /**
1266  * dbg_check_znode - check if znode is all right.
1267  * @c: UBIFS file-system description object
1268  * @zbr: zbranch which points to this znode
1269  *
1270  * This function makes sure that znode referred to by @zbr is all right.
1271  * Returns zero if it is, and %-EINVAL if it is not.
1272  */
1273 static int dbg_check_znode(struct ubifs_info *c, struct ubifs_zbranch *zbr)
1274 {
1275 	struct ubifs_znode *znode = zbr->znode;
1276 	struct ubifs_znode *zp = znode->parent;
1277 	int n, err, cmp;
1278 
1279 	if (znode->child_cnt <= 0 || znode->child_cnt > c->fanout) {
1280 		err = 1;
1281 		goto out;
1282 	}
1283 	if (znode->level < 0) {
1284 		err = 2;
1285 		goto out;
1286 	}
1287 	if (znode->iip < 0 || znode->iip >= c->fanout) {
1288 		err = 3;
1289 		goto out;
1290 	}
1291 
1292 	if (zbr->len == 0)
1293 		/* Only dirty zbranch may have no on-flash nodes */
1294 		if (!ubifs_zn_dirty(znode)) {
1295 			err = 4;
1296 			goto out;
1297 		}
1298 
1299 	if (ubifs_zn_dirty(znode)) {
1300 		/*
1301 		 * If znode is dirty, its parent has to be dirty as well. The
1302 		 * order of the operation is important, so we have to have
1303 		 * memory barriers.
1304 		 */
1305 		smp_mb();
1306 		if (zp && !ubifs_zn_dirty(zp)) {
1307 			/*
1308 			 * The dirty flag is atomic and is cleared outside the
1309 			 * TNC mutex, so znode's dirty flag may now have
1310 			 * been cleared. The child is always cleared before the
1311 			 * parent, so we just need to check again.
1312 			 */
1313 			smp_mb();
1314 			if (ubifs_zn_dirty(znode)) {
1315 				err = 5;
1316 				goto out;
1317 			}
1318 		}
1319 	}
1320 
1321 	if (zp) {
1322 		const union ubifs_key *min, *max;
1323 
1324 		if (znode->level != zp->level - 1) {
1325 			err = 6;
1326 			goto out;
1327 		}
1328 
1329 		/* Make sure the 'parent' pointer in our znode is correct */
1330 		err = ubifs_search_zbranch(c, zp, &zbr->key, &n);
1331 		if (!err) {
1332 			/* This zbranch does not exist in the parent */
1333 			err = 7;
1334 			goto out;
1335 		}
1336 
1337 		if (znode->iip >= zp->child_cnt) {
1338 			err = 8;
1339 			goto out;
1340 		}
1341 
1342 		if (znode->iip != n) {
1343 			/* This may happen only in case of collisions */
1344 			if (keys_cmp(c, &zp->zbranch[n].key,
1345 				     &zp->zbranch[znode->iip].key)) {
1346 				err = 9;
1347 				goto out;
1348 			}
1349 			n = znode->iip;
1350 		}
1351 
1352 		/*
1353 		 * Make sure that the first key in our znode is greater than or
1354 		 * equal to the key in the pointing zbranch.
1355 		 */
1356 		min = &zbr->key;
1357 		cmp = keys_cmp(c, min, &znode->zbranch[0].key);
1358 		if (cmp == 1) {
1359 			err = 10;
1360 			goto out;
1361 		}
1362 
1363 		if (n + 1 < zp->child_cnt) {
1364 			max = &zp->zbranch[n + 1].key;
1365 
1366 			/*
1367 			 * Make sure the last key in our znode is less or
1368 			 * equivalent than the key in the zbranch which goes
1369 			 * after our pointing zbranch.
1370 			 */
1371 			cmp = keys_cmp(c, max,
1372 				&znode->zbranch[znode->child_cnt - 1].key);
1373 			if (cmp == -1) {
1374 				err = 11;
1375 				goto out;
1376 			}
1377 		}
1378 	} else {
1379 		/* This may only be root znode */
1380 		if (zbr != &c->zroot) {
1381 			err = 12;
1382 			goto out;
1383 		}
1384 	}
1385 
1386 	/*
1387 	 * Make sure that next key is greater or equivalent then the previous
1388 	 * one.
1389 	 */
1390 	for (n = 1; n < znode->child_cnt; n++) {
1391 		cmp = keys_cmp(c, &znode->zbranch[n - 1].key,
1392 			       &znode->zbranch[n].key);
1393 		if (cmp > 0) {
1394 			err = 13;
1395 			goto out;
1396 		}
1397 		if (cmp == 0) {
1398 			/* This can only be keys with colliding hash */
1399 			if (!is_hash_key(c, &znode->zbranch[n].key)) {
1400 				err = 14;
1401 				goto out;
1402 			}
1403 
1404 			if (znode->level != 0 || c->replaying)
1405 				continue;
1406 
1407 			/*
1408 			 * Colliding keys should follow binary order of
1409 			 * corresponding xentry/dentry names.
1410 			 */
1411 			err = dbg_check_key_order(c, &znode->zbranch[n - 1],
1412 						  &znode->zbranch[n]);
1413 			if (err < 0)
1414 				return err;
1415 			if (err) {
1416 				err = 15;
1417 				goto out;
1418 			}
1419 		}
1420 	}
1421 
1422 	for (n = 0; n < znode->child_cnt; n++) {
1423 		if (!znode->zbranch[n].znode &&
1424 		    (znode->zbranch[n].lnum == 0 ||
1425 		     znode->zbranch[n].len == 0)) {
1426 			err = 16;
1427 			goto out;
1428 		}
1429 
1430 		if (znode->zbranch[n].lnum != 0 &&
1431 		    znode->zbranch[n].len == 0) {
1432 			err = 17;
1433 			goto out;
1434 		}
1435 
1436 		if (znode->zbranch[n].lnum == 0 &&
1437 		    znode->zbranch[n].len != 0) {
1438 			err = 18;
1439 			goto out;
1440 		}
1441 
1442 		if (znode->zbranch[n].lnum == 0 &&
1443 		    znode->zbranch[n].offs != 0) {
1444 			err = 19;
1445 			goto out;
1446 		}
1447 
1448 		if (znode->level != 0 && znode->zbranch[n].znode)
1449 			if (znode->zbranch[n].znode->parent != znode) {
1450 				err = 20;
1451 				goto out;
1452 			}
1453 	}
1454 
1455 	return 0;
1456 
1457 out:
1458 	ubifs_err(c, "failed, error %d", err);
1459 	ubifs_msg(c, "dump of the znode");
1460 	ubifs_dump_znode(c, znode);
1461 	if (zp) {
1462 		ubifs_msg(c, "dump of the parent znode");
1463 		ubifs_dump_znode(c, zp);
1464 	}
1465 	dump_stack();
1466 	return -EINVAL;
1467 }
1468 #else
1469 
1470 int dbg_check_dir(struct ubifs_info *c, const struct inode *dir)
1471 {
1472 	return 0;
1473 }
1474 
1475 void dbg_debugfs_exit_fs(struct ubifs_info *c)
1476 {
1477 	return;
1478 }
1479 
1480 int ubifs_debugging_init(struct ubifs_info *c)
1481 {
1482 	return 0;
1483 }
1484 void ubifs_debugging_exit(struct ubifs_info *c)
1485 {
1486 }
1487 int dbg_check_filesystem(struct ubifs_info *c)
1488 {
1489 	return 0;
1490 }
1491 int dbg_debugfs_init_fs(struct ubifs_info *c)
1492 {
1493 	return 0;
1494 }
1495 #endif
1496 
1497 #ifndef __UBOOT__
1498 /**
1499  * dbg_check_tnc - check TNC tree.
1500  * @c: UBIFS file-system description object
1501  * @extra: do extra checks that are possible at start commit
1502  *
1503  * This function traverses whole TNC tree and checks every znode. Returns zero
1504  * if everything is all right and %-EINVAL if something is wrong with TNC.
1505  */
1506 int dbg_check_tnc(struct ubifs_info *c, int extra)
1507 {
1508 	struct ubifs_znode *znode;
1509 	long clean_cnt = 0, dirty_cnt = 0;
1510 	int err, last;
1511 
1512 	if (!dbg_is_chk_index(c))
1513 		return 0;
1514 
1515 	ubifs_assert(mutex_is_locked(&c->tnc_mutex));
1516 	if (!c->zroot.znode)
1517 		return 0;
1518 
1519 	znode = ubifs_tnc_postorder_first(c->zroot.znode);
1520 	while (1) {
1521 		struct ubifs_znode *prev;
1522 		struct ubifs_zbranch *zbr;
1523 
1524 		if (!znode->parent)
1525 			zbr = &c->zroot;
1526 		else
1527 			zbr = &znode->parent->zbranch[znode->iip];
1528 
1529 		err = dbg_check_znode(c, zbr);
1530 		if (err)
1531 			return err;
1532 
1533 		if (extra) {
1534 			if (ubifs_zn_dirty(znode))
1535 				dirty_cnt += 1;
1536 			else
1537 				clean_cnt += 1;
1538 		}
1539 
1540 		prev = znode;
1541 		znode = ubifs_tnc_postorder_next(znode);
1542 		if (!znode)
1543 			break;
1544 
1545 		/*
1546 		 * If the last key of this znode is equivalent to the first key
1547 		 * of the next znode (collision), then check order of the keys.
1548 		 */
1549 		last = prev->child_cnt - 1;
1550 		if (prev->level == 0 && znode->level == 0 && !c->replaying &&
1551 		    !keys_cmp(c, &prev->zbranch[last].key,
1552 			      &znode->zbranch[0].key)) {
1553 			err = dbg_check_key_order(c, &prev->zbranch[last],
1554 						  &znode->zbranch[0]);
1555 			if (err < 0)
1556 				return err;
1557 			if (err) {
1558 				ubifs_msg(c, "first znode");
1559 				ubifs_dump_znode(c, prev);
1560 				ubifs_msg(c, "second znode");
1561 				ubifs_dump_znode(c, znode);
1562 				return -EINVAL;
1563 			}
1564 		}
1565 	}
1566 
1567 	if (extra) {
1568 		if (clean_cnt != atomic_long_read(&c->clean_zn_cnt)) {
1569 			ubifs_err(c, "incorrect clean_zn_cnt %ld, calculated %ld",
1570 				  atomic_long_read(&c->clean_zn_cnt),
1571 				  clean_cnt);
1572 			return -EINVAL;
1573 		}
1574 		if (dirty_cnt != atomic_long_read(&c->dirty_zn_cnt)) {
1575 			ubifs_err(c, "incorrect dirty_zn_cnt %ld, calculated %ld",
1576 				  atomic_long_read(&c->dirty_zn_cnt),
1577 				  dirty_cnt);
1578 			return -EINVAL;
1579 		}
1580 	}
1581 
1582 	return 0;
1583 }
1584 #else
1585 int dbg_check_tnc(struct ubifs_info *c, int extra)
1586 {
1587 	return 0;
1588 }
1589 #endif
1590 
1591 /**
1592  * dbg_walk_index - walk the on-flash index.
1593  * @c: UBIFS file-system description object
1594  * @leaf_cb: called for each leaf node
1595  * @znode_cb: called for each indexing node
1596  * @priv: private data which is passed to callbacks
1597  *
1598  * This function walks the UBIFS index and calls the @leaf_cb for each leaf
1599  * node and @znode_cb for each indexing node. Returns zero in case of success
1600  * and a negative error code in case of failure.
1601  *
1602  * It would be better if this function removed every znode it pulled to into
1603  * the TNC, so that the behavior more closely matched the non-debugging
1604  * behavior.
1605  */
1606 int dbg_walk_index(struct ubifs_info *c, dbg_leaf_callback leaf_cb,
1607 		   dbg_znode_callback znode_cb, void *priv)
1608 {
1609 	int err;
1610 	struct ubifs_zbranch *zbr;
1611 	struct ubifs_znode *znode, *child;
1612 
1613 	mutex_lock(&c->tnc_mutex);
1614 	/* If the root indexing node is not in TNC - pull it */
1615 	if (!c->zroot.znode) {
1616 		c->zroot.znode = ubifs_load_znode(c, &c->zroot, NULL, 0);
1617 		if (IS_ERR(c->zroot.znode)) {
1618 			err = PTR_ERR(c->zroot.znode);
1619 			c->zroot.znode = NULL;
1620 			goto out_unlock;
1621 		}
1622 	}
1623 
1624 	/*
1625 	 * We are going to traverse the indexing tree in the postorder manner.
1626 	 * Go down and find the leftmost indexing node where we are going to
1627 	 * start from.
1628 	 */
1629 	znode = c->zroot.znode;
1630 	while (znode->level > 0) {
1631 		zbr = &znode->zbranch[0];
1632 		child = zbr->znode;
1633 		if (!child) {
1634 			child = ubifs_load_znode(c, zbr, znode, 0);
1635 			if (IS_ERR(child)) {
1636 				err = PTR_ERR(child);
1637 				goto out_unlock;
1638 			}
1639 			zbr->znode = child;
1640 		}
1641 
1642 		znode = child;
1643 	}
1644 
1645 	/* Iterate over all indexing nodes */
1646 	while (1) {
1647 		int idx;
1648 
1649 		cond_resched();
1650 
1651 		if (znode_cb) {
1652 			err = znode_cb(c, znode, priv);
1653 			if (err) {
1654 				ubifs_err(c, "znode checking function returned error %d",
1655 					  err);
1656 				ubifs_dump_znode(c, znode);
1657 				goto out_dump;
1658 			}
1659 		}
1660 		if (leaf_cb && znode->level == 0) {
1661 			for (idx = 0; idx < znode->child_cnt; idx++) {
1662 				zbr = &znode->zbranch[idx];
1663 				err = leaf_cb(c, zbr, priv);
1664 				if (err) {
1665 					ubifs_err(c, "leaf checking function returned error %d, for leaf at LEB %d:%d",
1666 						  err, zbr->lnum, zbr->offs);
1667 					goto out_dump;
1668 				}
1669 			}
1670 		}
1671 
1672 		if (!znode->parent)
1673 			break;
1674 
1675 		idx = znode->iip + 1;
1676 		znode = znode->parent;
1677 		if (idx < znode->child_cnt) {
1678 			/* Switch to the next index in the parent */
1679 			zbr = &znode->zbranch[idx];
1680 			child = zbr->znode;
1681 			if (!child) {
1682 				child = ubifs_load_znode(c, zbr, znode, idx);
1683 				if (IS_ERR(child)) {
1684 					err = PTR_ERR(child);
1685 					goto out_unlock;
1686 				}
1687 				zbr->znode = child;
1688 			}
1689 			znode = child;
1690 		} else
1691 			/*
1692 			 * This is the last child, switch to the parent and
1693 			 * continue.
1694 			 */
1695 			continue;
1696 
1697 		/* Go to the lowest leftmost znode in the new sub-tree */
1698 		while (znode->level > 0) {
1699 			zbr = &znode->zbranch[0];
1700 			child = zbr->znode;
1701 			if (!child) {
1702 				child = ubifs_load_znode(c, zbr, znode, 0);
1703 				if (IS_ERR(child)) {
1704 					err = PTR_ERR(child);
1705 					goto out_unlock;
1706 				}
1707 				zbr->znode = child;
1708 			}
1709 			znode = child;
1710 		}
1711 	}
1712 
1713 	mutex_unlock(&c->tnc_mutex);
1714 	return 0;
1715 
1716 out_dump:
1717 	if (znode->parent)
1718 		zbr = &znode->parent->zbranch[znode->iip];
1719 	else
1720 		zbr = &c->zroot;
1721 	ubifs_msg(c, "dump of znode at LEB %d:%d", zbr->lnum, zbr->offs);
1722 	ubifs_dump_znode(c, znode);
1723 out_unlock:
1724 	mutex_unlock(&c->tnc_mutex);
1725 	return err;
1726 }
1727 
1728 /**
1729  * add_size - add znode size to partially calculated index size.
1730  * @c: UBIFS file-system description object
1731  * @znode: znode to add size for
1732  * @priv: partially calculated index size
1733  *
1734  * This is a helper function for 'dbg_check_idx_size()' which is called for
1735  * every indexing node and adds its size to the 'long long' variable pointed to
1736  * by @priv.
1737  */
1738 static int add_size(struct ubifs_info *c, struct ubifs_znode *znode, void *priv)
1739 {
1740 	long long *idx_size = priv;
1741 	int add;
1742 
1743 	add = ubifs_idx_node_sz(c, znode->child_cnt);
1744 	add = ALIGN(add, 8);
1745 	*idx_size += add;
1746 	return 0;
1747 }
1748 
1749 /**
1750  * dbg_check_idx_size - check index size.
1751  * @c: UBIFS file-system description object
1752  * @idx_size: size to check
1753  *
1754  * This function walks the UBIFS index, calculates its size and checks that the
1755  * size is equivalent to @idx_size. Returns zero in case of success and a
1756  * negative error code in case of failure.
1757  */
1758 int dbg_check_idx_size(struct ubifs_info *c, long long idx_size)
1759 {
1760 	int err;
1761 	long long calc = 0;
1762 
1763 	if (!dbg_is_chk_index(c))
1764 		return 0;
1765 
1766 	err = dbg_walk_index(c, NULL, add_size, &calc);
1767 	if (err) {
1768 		ubifs_err(c, "error %d while walking the index", err);
1769 		return err;
1770 	}
1771 
1772 	if (calc != idx_size) {
1773 		ubifs_err(c, "index size check failed: calculated size is %lld, should be %lld",
1774 			  calc, idx_size);
1775 		dump_stack();
1776 		return -EINVAL;
1777 	}
1778 
1779 	return 0;
1780 }
1781 
1782 #ifndef __UBOOT__
1783 /**
1784  * struct fsck_inode - information about an inode used when checking the file-system.
1785  * @rb: link in the RB-tree of inodes
1786  * @inum: inode number
1787  * @mode: inode type, permissions, etc
1788  * @nlink: inode link count
1789  * @xattr_cnt: count of extended attributes
1790  * @references: how many directory/xattr entries refer this inode (calculated
1791  *              while walking the index)
1792  * @calc_cnt: for directory inode count of child directories
1793  * @size: inode size (read from on-flash inode)
1794  * @xattr_sz: summary size of all extended attributes (read from on-flash
1795  *            inode)
1796  * @calc_sz: for directories calculated directory size
1797  * @calc_xcnt: count of extended attributes
1798  * @calc_xsz: calculated summary size of all extended attributes
1799  * @xattr_nms: sum of lengths of all extended attribute names belonging to this
1800  *             inode (read from on-flash inode)
1801  * @calc_xnms: calculated sum of lengths of all extended attribute names
1802  */
1803 struct fsck_inode {
1804 	struct rb_node rb;
1805 	ino_t inum;
1806 	umode_t mode;
1807 	unsigned int nlink;
1808 	unsigned int xattr_cnt;
1809 	int references;
1810 	int calc_cnt;
1811 	long long size;
1812 	unsigned int xattr_sz;
1813 	long long calc_sz;
1814 	long long calc_xcnt;
1815 	long long calc_xsz;
1816 	unsigned int xattr_nms;
1817 	long long calc_xnms;
1818 };
1819 
1820 /**
1821  * struct fsck_data - private FS checking information.
1822  * @inodes: RB-tree of all inodes (contains @struct fsck_inode objects)
1823  */
1824 struct fsck_data {
1825 	struct rb_root inodes;
1826 };
1827 
1828 /**
1829  * add_inode - add inode information to RB-tree of inodes.
1830  * @c: UBIFS file-system description object
1831  * @fsckd: FS checking information
1832  * @ino: raw UBIFS inode to add
1833  *
1834  * This is a helper function for 'check_leaf()' which adds information about
1835  * inode @ino to the RB-tree of inodes. Returns inode information pointer in
1836  * case of success and a negative error code in case of failure.
1837  */
1838 static struct fsck_inode *add_inode(struct ubifs_info *c,
1839 				    struct fsck_data *fsckd,
1840 				    struct ubifs_ino_node *ino)
1841 {
1842 	struct rb_node **p, *parent = NULL;
1843 	struct fsck_inode *fscki;
1844 	ino_t inum = key_inum_flash(c, &ino->key);
1845 	struct inode *inode;
1846 	struct ubifs_inode *ui;
1847 
1848 	p = &fsckd->inodes.rb_node;
1849 	while (*p) {
1850 		parent = *p;
1851 		fscki = rb_entry(parent, struct fsck_inode, rb);
1852 		if (inum < fscki->inum)
1853 			p = &(*p)->rb_left;
1854 		else if (inum > fscki->inum)
1855 			p = &(*p)->rb_right;
1856 		else
1857 			return fscki;
1858 	}
1859 
1860 	if (inum > c->highest_inum) {
1861 		ubifs_err(c, "too high inode number, max. is %lu",
1862 			  (unsigned long)c->highest_inum);
1863 		return ERR_PTR(-EINVAL);
1864 	}
1865 
1866 	fscki = kzalloc(sizeof(struct fsck_inode), GFP_NOFS);
1867 	if (!fscki)
1868 		return ERR_PTR(-ENOMEM);
1869 
1870 	inode = ilookup(c->vfs_sb, inum);
1871 
1872 	fscki->inum = inum;
1873 	/*
1874 	 * If the inode is present in the VFS inode cache, use it instead of
1875 	 * the on-flash inode which might be out-of-date. E.g., the size might
1876 	 * be out-of-date. If we do not do this, the following may happen, for
1877 	 * example:
1878 	 *   1. A power cut happens
1879 	 *   2. We mount the file-system R/O, the replay process fixes up the
1880 	 *      inode size in the VFS cache, but on on-flash.
1881 	 *   3. 'check_leaf()' fails because it hits a data node beyond inode
1882 	 *      size.
1883 	 */
1884 	if (!inode) {
1885 		fscki->nlink = le32_to_cpu(ino->nlink);
1886 		fscki->size = le64_to_cpu(ino->size);
1887 		fscki->xattr_cnt = le32_to_cpu(ino->xattr_cnt);
1888 		fscki->xattr_sz = le32_to_cpu(ino->xattr_size);
1889 		fscki->xattr_nms = le32_to_cpu(ino->xattr_names);
1890 		fscki->mode = le32_to_cpu(ino->mode);
1891 	} else {
1892 		ui = ubifs_inode(inode);
1893 		fscki->nlink = inode->i_nlink;
1894 		fscki->size = inode->i_size;
1895 		fscki->xattr_cnt = ui->xattr_cnt;
1896 		fscki->xattr_sz = ui->xattr_size;
1897 		fscki->xattr_nms = ui->xattr_names;
1898 		fscki->mode = inode->i_mode;
1899 		iput(inode);
1900 	}
1901 
1902 	if (S_ISDIR(fscki->mode)) {
1903 		fscki->calc_sz = UBIFS_INO_NODE_SZ;
1904 		fscki->calc_cnt = 2;
1905 	}
1906 
1907 	rb_link_node(&fscki->rb, parent, p);
1908 	rb_insert_color(&fscki->rb, &fsckd->inodes);
1909 
1910 	return fscki;
1911 }
1912 
1913 /**
1914  * search_inode - search inode in the RB-tree of inodes.
1915  * @fsckd: FS checking information
1916  * @inum: inode number to search
1917  *
1918  * This is a helper function for 'check_leaf()' which searches inode @inum in
1919  * the RB-tree of inodes and returns an inode information pointer or %NULL if
1920  * the inode was not found.
1921  */
1922 static struct fsck_inode *search_inode(struct fsck_data *fsckd, ino_t inum)
1923 {
1924 	struct rb_node *p;
1925 	struct fsck_inode *fscki;
1926 
1927 	p = fsckd->inodes.rb_node;
1928 	while (p) {
1929 		fscki = rb_entry(p, struct fsck_inode, rb);
1930 		if (inum < fscki->inum)
1931 			p = p->rb_left;
1932 		else if (inum > fscki->inum)
1933 			p = p->rb_right;
1934 		else
1935 			return fscki;
1936 	}
1937 	return NULL;
1938 }
1939 
1940 /**
1941  * read_add_inode - read inode node and add it to RB-tree of inodes.
1942  * @c: UBIFS file-system description object
1943  * @fsckd: FS checking information
1944  * @inum: inode number to read
1945  *
1946  * This is a helper function for 'check_leaf()' which finds inode node @inum in
1947  * the index, reads it, and adds it to the RB-tree of inodes. Returns inode
1948  * information pointer in case of success and a negative error code in case of
1949  * failure.
1950  */
1951 static struct fsck_inode *read_add_inode(struct ubifs_info *c,
1952 					 struct fsck_data *fsckd, ino_t inum)
1953 {
1954 	int n, err;
1955 	union ubifs_key key;
1956 	struct ubifs_znode *znode;
1957 	struct ubifs_zbranch *zbr;
1958 	struct ubifs_ino_node *ino;
1959 	struct fsck_inode *fscki;
1960 
1961 	fscki = search_inode(fsckd, inum);
1962 	if (fscki)
1963 		return fscki;
1964 
1965 	ino_key_init(c, &key, inum);
1966 	err = ubifs_lookup_level0(c, &key, &znode, &n);
1967 	if (!err) {
1968 		ubifs_err(c, "inode %lu not found in index", (unsigned long)inum);
1969 		return ERR_PTR(-ENOENT);
1970 	} else if (err < 0) {
1971 		ubifs_err(c, "error %d while looking up inode %lu",
1972 			  err, (unsigned long)inum);
1973 		return ERR_PTR(err);
1974 	}
1975 
1976 	zbr = &znode->zbranch[n];
1977 	if (zbr->len < UBIFS_INO_NODE_SZ) {
1978 		ubifs_err(c, "bad node %lu node length %d",
1979 			  (unsigned long)inum, zbr->len);
1980 		return ERR_PTR(-EINVAL);
1981 	}
1982 
1983 	ino = kmalloc(zbr->len, GFP_NOFS);
1984 	if (!ino)
1985 		return ERR_PTR(-ENOMEM);
1986 
1987 	err = ubifs_tnc_read_node(c, zbr, ino);
1988 	if (err) {
1989 		ubifs_err(c, "cannot read inode node at LEB %d:%d, error %d",
1990 			  zbr->lnum, zbr->offs, err);
1991 		kfree(ino);
1992 		return ERR_PTR(err);
1993 	}
1994 
1995 	fscki = add_inode(c, fsckd, ino);
1996 	kfree(ino);
1997 	if (IS_ERR(fscki)) {
1998 		ubifs_err(c, "error %ld while adding inode %lu node",
1999 			  PTR_ERR(fscki), (unsigned long)inum);
2000 		return fscki;
2001 	}
2002 
2003 	return fscki;
2004 }
2005 
2006 /**
2007  * check_leaf - check leaf node.
2008  * @c: UBIFS file-system description object
2009  * @zbr: zbranch of the leaf node to check
2010  * @priv: FS checking information
2011  *
2012  * This is a helper function for 'dbg_check_filesystem()' which is called for
2013  * every single leaf node while walking the indexing tree. It checks that the
2014  * leaf node referred from the indexing tree exists, has correct CRC, and does
2015  * some other basic validation. This function is also responsible for building
2016  * an RB-tree of inodes - it adds all inodes into the RB-tree. It also
2017  * calculates reference count, size, etc for each inode in order to later
2018  * compare them to the information stored inside the inodes and detect possible
2019  * inconsistencies. Returns zero in case of success and a negative error code
2020  * in case of failure.
2021  */
2022 static int check_leaf(struct ubifs_info *c, struct ubifs_zbranch *zbr,
2023 		      void *priv)
2024 {
2025 	ino_t inum;
2026 	void *node;
2027 	struct ubifs_ch *ch;
2028 	int err, type = key_type(c, &zbr->key);
2029 	struct fsck_inode *fscki;
2030 
2031 	if (zbr->len < UBIFS_CH_SZ) {
2032 		ubifs_err(c, "bad leaf length %d (LEB %d:%d)",
2033 			  zbr->len, zbr->lnum, zbr->offs);
2034 		return -EINVAL;
2035 	}
2036 
2037 	node = kmalloc(zbr->len, GFP_NOFS);
2038 	if (!node)
2039 		return -ENOMEM;
2040 
2041 	err = ubifs_tnc_read_node(c, zbr, node);
2042 	if (err) {
2043 		ubifs_err(c, "cannot read leaf node at LEB %d:%d, error %d",
2044 			  zbr->lnum, zbr->offs, err);
2045 		goto out_free;
2046 	}
2047 
2048 	/* If this is an inode node, add it to RB-tree of inodes */
2049 	if (type == UBIFS_INO_KEY) {
2050 		fscki = add_inode(c, priv, node);
2051 		if (IS_ERR(fscki)) {
2052 			err = PTR_ERR(fscki);
2053 			ubifs_err(c, "error %d while adding inode node", err);
2054 			goto out_dump;
2055 		}
2056 		goto out;
2057 	}
2058 
2059 	if (type != UBIFS_DENT_KEY && type != UBIFS_XENT_KEY &&
2060 	    type != UBIFS_DATA_KEY) {
2061 		ubifs_err(c, "unexpected node type %d at LEB %d:%d",
2062 			  type, zbr->lnum, zbr->offs);
2063 		err = -EINVAL;
2064 		goto out_free;
2065 	}
2066 
2067 	ch = node;
2068 	if (le64_to_cpu(ch->sqnum) > c->max_sqnum) {
2069 		ubifs_err(c, "too high sequence number, max. is %llu",
2070 			  c->max_sqnum);
2071 		err = -EINVAL;
2072 		goto out_dump;
2073 	}
2074 
2075 	if (type == UBIFS_DATA_KEY) {
2076 		long long blk_offs;
2077 		struct ubifs_data_node *dn = node;
2078 
2079 		ubifs_assert(zbr->len >= UBIFS_DATA_NODE_SZ);
2080 
2081 		/*
2082 		 * Search the inode node this data node belongs to and insert
2083 		 * it to the RB-tree of inodes.
2084 		 */
2085 		inum = key_inum_flash(c, &dn->key);
2086 		fscki = read_add_inode(c, priv, inum);
2087 		if (IS_ERR(fscki)) {
2088 			err = PTR_ERR(fscki);
2089 			ubifs_err(c, "error %d while processing data node and trying to find inode node %lu",
2090 				  err, (unsigned long)inum);
2091 			goto out_dump;
2092 		}
2093 
2094 		/* Make sure the data node is within inode size */
2095 		blk_offs = key_block_flash(c, &dn->key);
2096 		blk_offs <<= UBIFS_BLOCK_SHIFT;
2097 		blk_offs += le32_to_cpu(dn->size);
2098 		if (blk_offs > fscki->size) {
2099 			ubifs_err(c, "data node at LEB %d:%d is not within inode size %lld",
2100 				  zbr->lnum, zbr->offs, fscki->size);
2101 			err = -EINVAL;
2102 			goto out_dump;
2103 		}
2104 	} else {
2105 		int nlen;
2106 		struct ubifs_dent_node *dent = node;
2107 		struct fsck_inode *fscki1;
2108 
2109 		ubifs_assert(zbr->len >= UBIFS_DENT_NODE_SZ);
2110 
2111 		err = ubifs_validate_entry(c, dent);
2112 		if (err)
2113 			goto out_dump;
2114 
2115 		/*
2116 		 * Search the inode node this entry refers to and the parent
2117 		 * inode node and insert them to the RB-tree of inodes.
2118 		 */
2119 		inum = le64_to_cpu(dent->inum);
2120 		fscki = read_add_inode(c, priv, inum);
2121 		if (IS_ERR(fscki)) {
2122 			err = PTR_ERR(fscki);
2123 			ubifs_err(c, "error %d while processing entry node and trying to find inode node %lu",
2124 				  err, (unsigned long)inum);
2125 			goto out_dump;
2126 		}
2127 
2128 		/* Count how many direntries or xentries refers this inode */
2129 		fscki->references += 1;
2130 
2131 		inum = key_inum_flash(c, &dent->key);
2132 		fscki1 = read_add_inode(c, priv, inum);
2133 		if (IS_ERR(fscki1)) {
2134 			err = PTR_ERR(fscki1);
2135 			ubifs_err(c, "error %d while processing entry node and trying to find parent inode node %lu",
2136 				  err, (unsigned long)inum);
2137 			goto out_dump;
2138 		}
2139 
2140 		nlen = le16_to_cpu(dent->nlen);
2141 		if (type == UBIFS_XENT_KEY) {
2142 			fscki1->calc_xcnt += 1;
2143 			fscki1->calc_xsz += CALC_DENT_SIZE(nlen);
2144 			fscki1->calc_xsz += CALC_XATTR_BYTES(fscki->size);
2145 			fscki1->calc_xnms += nlen;
2146 		} else {
2147 			fscki1->calc_sz += CALC_DENT_SIZE(nlen);
2148 			if (dent->type == UBIFS_ITYPE_DIR)
2149 				fscki1->calc_cnt += 1;
2150 		}
2151 	}
2152 
2153 out:
2154 	kfree(node);
2155 	return 0;
2156 
2157 out_dump:
2158 	ubifs_msg(c, "dump of node at LEB %d:%d", zbr->lnum, zbr->offs);
2159 	ubifs_dump_node(c, node);
2160 out_free:
2161 	kfree(node);
2162 	return err;
2163 }
2164 
2165 /**
2166  * free_inodes - free RB-tree of inodes.
2167  * @fsckd: FS checking information
2168  */
2169 static void free_inodes(struct fsck_data *fsckd)
2170 {
2171 	struct fsck_inode *fscki, *n;
2172 
2173 	rbtree_postorder_for_each_entry_safe(fscki, n, &fsckd->inodes, rb)
2174 		kfree(fscki);
2175 }
2176 
2177 /**
2178  * check_inodes - checks all inodes.
2179  * @c: UBIFS file-system description object
2180  * @fsckd: FS checking information
2181  *
2182  * This is a helper function for 'dbg_check_filesystem()' which walks the
2183  * RB-tree of inodes after the index scan has been finished, and checks that
2184  * inode nlink, size, etc are correct. Returns zero if inodes are fine,
2185  * %-EINVAL if not, and a negative error code in case of failure.
2186  */
2187 static int check_inodes(struct ubifs_info *c, struct fsck_data *fsckd)
2188 {
2189 	int n, err;
2190 	union ubifs_key key;
2191 	struct ubifs_znode *znode;
2192 	struct ubifs_zbranch *zbr;
2193 	struct ubifs_ino_node *ino;
2194 	struct fsck_inode *fscki;
2195 	struct rb_node *this = rb_first(&fsckd->inodes);
2196 
2197 	while (this) {
2198 		fscki = rb_entry(this, struct fsck_inode, rb);
2199 		this = rb_next(this);
2200 
2201 		if (S_ISDIR(fscki->mode)) {
2202 			/*
2203 			 * Directories have to have exactly one reference (they
2204 			 * cannot have hardlinks), although root inode is an
2205 			 * exception.
2206 			 */
2207 			if (fscki->inum != UBIFS_ROOT_INO &&
2208 			    fscki->references != 1) {
2209 				ubifs_err(c, "directory inode %lu has %d direntries which refer it, but should be 1",
2210 					  (unsigned long)fscki->inum,
2211 					  fscki->references);
2212 				goto out_dump;
2213 			}
2214 			if (fscki->inum == UBIFS_ROOT_INO &&
2215 			    fscki->references != 0) {
2216 				ubifs_err(c, "root inode %lu has non-zero (%d) direntries which refer it",
2217 					  (unsigned long)fscki->inum,
2218 					  fscki->references);
2219 				goto out_dump;
2220 			}
2221 			if (fscki->calc_sz != fscki->size) {
2222 				ubifs_err(c, "directory inode %lu size is %lld, but calculated size is %lld",
2223 					  (unsigned long)fscki->inum,
2224 					  fscki->size, fscki->calc_sz);
2225 				goto out_dump;
2226 			}
2227 			if (fscki->calc_cnt != fscki->nlink) {
2228 				ubifs_err(c, "directory inode %lu nlink is %d, but calculated nlink is %d",
2229 					  (unsigned long)fscki->inum,
2230 					  fscki->nlink, fscki->calc_cnt);
2231 				goto out_dump;
2232 			}
2233 		} else {
2234 			if (fscki->references != fscki->nlink) {
2235 				ubifs_err(c, "inode %lu nlink is %d, but calculated nlink is %d",
2236 					  (unsigned long)fscki->inum,
2237 					  fscki->nlink, fscki->references);
2238 				goto out_dump;
2239 			}
2240 		}
2241 		if (fscki->xattr_sz != fscki->calc_xsz) {
2242 			ubifs_err(c, "inode %lu has xattr size %u, but calculated size is %lld",
2243 				  (unsigned long)fscki->inum, fscki->xattr_sz,
2244 				  fscki->calc_xsz);
2245 			goto out_dump;
2246 		}
2247 		if (fscki->xattr_cnt != fscki->calc_xcnt) {
2248 			ubifs_err(c, "inode %lu has %u xattrs, but calculated count is %lld",
2249 				  (unsigned long)fscki->inum,
2250 				  fscki->xattr_cnt, fscki->calc_xcnt);
2251 			goto out_dump;
2252 		}
2253 		if (fscki->xattr_nms != fscki->calc_xnms) {
2254 			ubifs_err(c, "inode %lu has xattr names' size %u, but calculated names' size is %lld",
2255 				  (unsigned long)fscki->inum, fscki->xattr_nms,
2256 				  fscki->calc_xnms);
2257 			goto out_dump;
2258 		}
2259 	}
2260 
2261 	return 0;
2262 
2263 out_dump:
2264 	/* Read the bad inode and dump it */
2265 	ino_key_init(c, &key, fscki->inum);
2266 	err = ubifs_lookup_level0(c, &key, &znode, &n);
2267 	if (!err) {
2268 		ubifs_err(c, "inode %lu not found in index",
2269 			  (unsigned long)fscki->inum);
2270 		return -ENOENT;
2271 	} else if (err < 0) {
2272 		ubifs_err(c, "error %d while looking up inode %lu",
2273 			  err, (unsigned long)fscki->inum);
2274 		return err;
2275 	}
2276 
2277 	zbr = &znode->zbranch[n];
2278 	ino = kmalloc(zbr->len, GFP_NOFS);
2279 	if (!ino)
2280 		return -ENOMEM;
2281 
2282 	err = ubifs_tnc_read_node(c, zbr, ino);
2283 	if (err) {
2284 		ubifs_err(c, "cannot read inode node at LEB %d:%d, error %d",
2285 			  zbr->lnum, zbr->offs, err);
2286 		kfree(ino);
2287 		return err;
2288 	}
2289 
2290 	ubifs_msg(c, "dump of the inode %lu sitting in LEB %d:%d",
2291 		  (unsigned long)fscki->inum, zbr->lnum, zbr->offs);
2292 	ubifs_dump_node(c, ino);
2293 	kfree(ino);
2294 	return -EINVAL;
2295 }
2296 
2297 /**
2298  * dbg_check_filesystem - check the file-system.
2299  * @c: UBIFS file-system description object
2300  *
2301  * This function checks the file system, namely:
2302  * o makes sure that all leaf nodes exist and their CRCs are correct;
2303  * o makes sure inode nlink, size, xattr size/count are correct (for all
2304  *   inodes).
2305  *
2306  * The function reads whole indexing tree and all nodes, so it is pretty
2307  * heavy-weight. Returns zero if the file-system is consistent, %-EINVAL if
2308  * not, and a negative error code in case of failure.
2309  */
2310 int dbg_check_filesystem(struct ubifs_info *c)
2311 {
2312 	int err;
2313 	struct fsck_data fsckd;
2314 
2315 	if (!dbg_is_chk_fs(c))
2316 		return 0;
2317 
2318 	fsckd.inodes = RB_ROOT;
2319 	err = dbg_walk_index(c, check_leaf, NULL, &fsckd);
2320 	if (err)
2321 		goto out_free;
2322 
2323 	err = check_inodes(c, &fsckd);
2324 	if (err)
2325 		goto out_free;
2326 
2327 	free_inodes(&fsckd);
2328 	return 0;
2329 
2330 out_free:
2331 	ubifs_err(c, "file-system check failed with error %d", err);
2332 	dump_stack();
2333 	free_inodes(&fsckd);
2334 	return err;
2335 }
2336 
2337 /**
2338  * dbg_check_data_nodes_order - check that list of data nodes is sorted.
2339  * @c: UBIFS file-system description object
2340  * @head: the list of nodes ('struct ubifs_scan_node' objects)
2341  *
2342  * This function returns zero if the list of data nodes is sorted correctly,
2343  * and %-EINVAL if not.
2344  */
2345 int dbg_check_data_nodes_order(struct ubifs_info *c, struct list_head *head)
2346 {
2347 	struct list_head *cur;
2348 	struct ubifs_scan_node *sa, *sb;
2349 
2350 	if (!dbg_is_chk_gen(c))
2351 		return 0;
2352 
2353 	for (cur = head->next; cur->next != head; cur = cur->next) {
2354 		ino_t inuma, inumb;
2355 		uint32_t blka, blkb;
2356 
2357 		cond_resched();
2358 		sa = container_of(cur, struct ubifs_scan_node, list);
2359 		sb = container_of(cur->next, struct ubifs_scan_node, list);
2360 
2361 		if (sa->type != UBIFS_DATA_NODE) {
2362 			ubifs_err(c, "bad node type %d", sa->type);
2363 			ubifs_dump_node(c, sa->node);
2364 			return -EINVAL;
2365 		}
2366 		if (sb->type != UBIFS_DATA_NODE) {
2367 			ubifs_err(c, "bad node type %d", sb->type);
2368 			ubifs_dump_node(c, sb->node);
2369 			return -EINVAL;
2370 		}
2371 
2372 		inuma = key_inum(c, &sa->key);
2373 		inumb = key_inum(c, &sb->key);
2374 
2375 		if (inuma < inumb)
2376 			continue;
2377 		if (inuma > inumb) {
2378 			ubifs_err(c, "larger inum %lu goes before inum %lu",
2379 				  (unsigned long)inuma, (unsigned long)inumb);
2380 			goto error_dump;
2381 		}
2382 
2383 		blka = key_block(c, &sa->key);
2384 		blkb = key_block(c, &sb->key);
2385 
2386 		if (blka > blkb) {
2387 			ubifs_err(c, "larger block %u goes before %u", blka, blkb);
2388 			goto error_dump;
2389 		}
2390 		if (blka == blkb) {
2391 			ubifs_err(c, "two data nodes for the same block");
2392 			goto error_dump;
2393 		}
2394 	}
2395 
2396 	return 0;
2397 
2398 error_dump:
2399 	ubifs_dump_node(c, sa->node);
2400 	ubifs_dump_node(c, sb->node);
2401 	return -EINVAL;
2402 }
2403 
2404 /**
2405  * dbg_check_nondata_nodes_order - check that list of data nodes is sorted.
2406  * @c: UBIFS file-system description object
2407  * @head: the list of nodes ('struct ubifs_scan_node' objects)
2408  *
2409  * This function returns zero if the list of non-data nodes is sorted correctly,
2410  * and %-EINVAL if not.
2411  */
2412 int dbg_check_nondata_nodes_order(struct ubifs_info *c, struct list_head *head)
2413 {
2414 	struct list_head *cur;
2415 	struct ubifs_scan_node *sa, *sb;
2416 
2417 	if (!dbg_is_chk_gen(c))
2418 		return 0;
2419 
2420 	for (cur = head->next; cur->next != head; cur = cur->next) {
2421 		ino_t inuma, inumb;
2422 		uint32_t hasha, hashb;
2423 
2424 		cond_resched();
2425 		sa = container_of(cur, struct ubifs_scan_node, list);
2426 		sb = container_of(cur->next, struct ubifs_scan_node, list);
2427 
2428 		if (sa->type != UBIFS_INO_NODE && sa->type != UBIFS_DENT_NODE &&
2429 		    sa->type != UBIFS_XENT_NODE) {
2430 			ubifs_err(c, "bad node type %d", sa->type);
2431 			ubifs_dump_node(c, sa->node);
2432 			return -EINVAL;
2433 		}
2434 		if (sa->type != UBIFS_INO_NODE && sa->type != UBIFS_DENT_NODE &&
2435 		    sa->type != UBIFS_XENT_NODE) {
2436 			ubifs_err(c, "bad node type %d", sb->type);
2437 			ubifs_dump_node(c, sb->node);
2438 			return -EINVAL;
2439 		}
2440 
2441 		if (sa->type != UBIFS_INO_NODE && sb->type == UBIFS_INO_NODE) {
2442 			ubifs_err(c, "non-inode node goes before inode node");
2443 			goto error_dump;
2444 		}
2445 
2446 		if (sa->type == UBIFS_INO_NODE && sb->type != UBIFS_INO_NODE)
2447 			continue;
2448 
2449 		if (sa->type == UBIFS_INO_NODE && sb->type == UBIFS_INO_NODE) {
2450 			/* Inode nodes are sorted in descending size order */
2451 			if (sa->len < sb->len) {
2452 				ubifs_err(c, "smaller inode node goes first");
2453 				goto error_dump;
2454 			}
2455 			continue;
2456 		}
2457 
2458 		/*
2459 		 * This is either a dentry or xentry, which should be sorted in
2460 		 * ascending (parent ino, hash) order.
2461 		 */
2462 		inuma = key_inum(c, &sa->key);
2463 		inumb = key_inum(c, &sb->key);
2464 
2465 		if (inuma < inumb)
2466 			continue;
2467 		if (inuma > inumb) {
2468 			ubifs_err(c, "larger inum %lu goes before inum %lu",
2469 				  (unsigned long)inuma, (unsigned long)inumb);
2470 			goto error_dump;
2471 		}
2472 
2473 		hasha = key_block(c, &sa->key);
2474 		hashb = key_block(c, &sb->key);
2475 
2476 		if (hasha > hashb) {
2477 			ubifs_err(c, "larger hash %u goes before %u",
2478 				  hasha, hashb);
2479 			goto error_dump;
2480 		}
2481 	}
2482 
2483 	return 0;
2484 
2485 error_dump:
2486 	ubifs_msg(c, "dumping first node");
2487 	ubifs_dump_node(c, sa->node);
2488 	ubifs_msg(c, "dumping second node");
2489 	ubifs_dump_node(c, sb->node);
2490 	return -EINVAL;
2491 	return 0;
2492 }
2493 
2494 static inline int chance(unsigned int n, unsigned int out_of)
2495 {
2496 	return !!((prandom_u32() % out_of) + 1 <= n);
2497 
2498 }
2499 
2500 static int power_cut_emulated(struct ubifs_info *c, int lnum, int write)
2501 {
2502 	struct ubifs_debug_info *d = c->dbg;
2503 
2504 	ubifs_assert(dbg_is_tst_rcvry(c));
2505 
2506 	if (!d->pc_cnt) {
2507 		/* First call - decide delay to the power cut */
2508 		if (chance(1, 2)) {
2509 			unsigned long delay;
2510 
2511 			if (chance(1, 2)) {
2512 				d->pc_delay = 1;
2513 				/* Fail within 1 minute */
2514 				delay = prandom_u32() % 60000;
2515 				d->pc_timeout = jiffies;
2516 				d->pc_timeout += msecs_to_jiffies(delay);
2517 				ubifs_warn(c, "failing after %lums", delay);
2518 			} else {
2519 				d->pc_delay = 2;
2520 				delay = prandom_u32() % 10000;
2521 				/* Fail within 10000 operations */
2522 				d->pc_cnt_max = delay;
2523 				ubifs_warn(c, "failing after %lu calls", delay);
2524 			}
2525 		}
2526 
2527 		d->pc_cnt += 1;
2528 	}
2529 
2530 	/* Determine if failure delay has expired */
2531 	if (d->pc_delay == 1 && time_before(jiffies, d->pc_timeout))
2532 			return 0;
2533 	if (d->pc_delay == 2 && d->pc_cnt++ < d->pc_cnt_max)
2534 			return 0;
2535 
2536 	if (lnum == UBIFS_SB_LNUM) {
2537 		if (write && chance(1, 2))
2538 			return 0;
2539 		if (chance(19, 20))
2540 			return 0;
2541 		ubifs_warn(c, "failing in super block LEB %d", lnum);
2542 	} else if (lnum == UBIFS_MST_LNUM || lnum == UBIFS_MST_LNUM + 1) {
2543 		if (chance(19, 20))
2544 			return 0;
2545 		ubifs_warn(c, "failing in master LEB %d", lnum);
2546 	} else if (lnum >= UBIFS_LOG_LNUM && lnum <= c->log_last) {
2547 		if (write && chance(99, 100))
2548 			return 0;
2549 		if (chance(399, 400))
2550 			return 0;
2551 		ubifs_warn(c, "failing in log LEB %d", lnum);
2552 	} else if (lnum >= c->lpt_first && lnum <= c->lpt_last) {
2553 		if (write && chance(7, 8))
2554 			return 0;
2555 		if (chance(19, 20))
2556 			return 0;
2557 		ubifs_warn(c, "failing in LPT LEB %d", lnum);
2558 	} else if (lnum >= c->orph_first && lnum <= c->orph_last) {
2559 		if (write && chance(1, 2))
2560 			return 0;
2561 		if (chance(9, 10))
2562 			return 0;
2563 		ubifs_warn(c, "failing in orphan LEB %d", lnum);
2564 	} else if (lnum == c->ihead_lnum) {
2565 		if (chance(99, 100))
2566 			return 0;
2567 		ubifs_warn(c, "failing in index head LEB %d", lnum);
2568 	} else if (c->jheads && lnum == c->jheads[GCHD].wbuf.lnum) {
2569 		if (chance(9, 10))
2570 			return 0;
2571 		ubifs_warn(c, "failing in GC head LEB %d", lnum);
2572 	} else if (write && !RB_EMPTY_ROOT(&c->buds) &&
2573 		   !ubifs_search_bud(c, lnum)) {
2574 		if (chance(19, 20))
2575 			return 0;
2576 		ubifs_warn(c, "failing in non-bud LEB %d", lnum);
2577 	} else if (c->cmt_state == COMMIT_RUNNING_BACKGROUND ||
2578 		   c->cmt_state == COMMIT_RUNNING_REQUIRED) {
2579 		if (chance(999, 1000))
2580 			return 0;
2581 		ubifs_warn(c, "failing in bud LEB %d commit running", lnum);
2582 	} else {
2583 		if (chance(9999, 10000))
2584 			return 0;
2585 		ubifs_warn(c, "failing in bud LEB %d commit not running", lnum);
2586 	}
2587 
2588 	d->pc_happened = 1;
2589 	ubifs_warn(c, "========== Power cut emulated ==========");
2590 	dump_stack();
2591 	return 1;
2592 }
2593 
2594 static int corrupt_data(const struct ubifs_info *c, const void *buf,
2595 			unsigned int len)
2596 {
2597 	unsigned int from, to, ffs = chance(1, 2);
2598 	unsigned char *p = (void *)buf;
2599 
2600 	from = prandom_u32() % len;
2601 	/* Corruption span max to end of write unit */
2602 	to = min(len, ALIGN(from + 1, c->max_write_size));
2603 
2604 	ubifs_warn(c, "filled bytes %u-%u with %s", from, to - 1,
2605 		   ffs ? "0xFFs" : "random data");
2606 
2607 	if (ffs)
2608 		memset(p + from, 0xFF, to - from);
2609 	else
2610 		prandom_bytes(p + from, to - from);
2611 
2612 	return to;
2613 }
2614 
2615 int dbg_leb_write(struct ubifs_info *c, int lnum, const void *buf,
2616 		  int offs, int len)
2617 {
2618 	int err, failing;
2619 
2620 	if (c->dbg->pc_happened)
2621 		return -EROFS;
2622 
2623 	failing = power_cut_emulated(c, lnum, 1);
2624 	if (failing) {
2625 		len = corrupt_data(c, buf, len);
2626 		ubifs_warn(c, "actually write %d bytes to LEB %d:%d (the buffer was corrupted)",
2627 			   len, lnum, offs);
2628 	}
2629 	err = ubi_leb_write(c->ubi, lnum, buf, offs, len);
2630 	if (err)
2631 		return err;
2632 	if (failing)
2633 		return -EROFS;
2634 	return 0;
2635 }
2636 
2637 int dbg_leb_change(struct ubifs_info *c, int lnum, const void *buf,
2638 		   int len)
2639 {
2640 	int err;
2641 
2642 	if (c->dbg->pc_happened)
2643 		return -EROFS;
2644 	if (power_cut_emulated(c, lnum, 1))
2645 		return -EROFS;
2646 	err = ubi_leb_change(c->ubi, lnum, buf, len);
2647 	if (err)
2648 		return err;
2649 	if (power_cut_emulated(c, lnum, 1))
2650 		return -EROFS;
2651 	return 0;
2652 }
2653 
2654 int dbg_leb_unmap(struct ubifs_info *c, int lnum)
2655 {
2656 	int err;
2657 
2658 	if (c->dbg->pc_happened)
2659 		return -EROFS;
2660 	if (power_cut_emulated(c, lnum, 0))
2661 		return -EROFS;
2662 	err = ubi_leb_unmap(c->ubi, lnum);
2663 	if (err)
2664 		return err;
2665 	if (power_cut_emulated(c, lnum, 0))
2666 		return -EROFS;
2667 	return 0;
2668 }
2669 
2670 int dbg_leb_map(struct ubifs_info *c, int lnum)
2671 {
2672 	int err;
2673 
2674 	if (c->dbg->pc_happened)
2675 		return -EROFS;
2676 	if (power_cut_emulated(c, lnum, 0))
2677 		return -EROFS;
2678 	err = ubi_leb_map(c->ubi, lnum);
2679 	if (err)
2680 		return err;
2681 	if (power_cut_emulated(c, lnum, 0))
2682 		return -EROFS;
2683 	return 0;
2684 }
2685 
2686 /*
2687  * Root directory for UBIFS stuff in debugfs. Contains sub-directories which
2688  * contain the stuff specific to particular file-system mounts.
2689  */
2690 static struct dentry *dfs_rootdir;
2691 
2692 static int dfs_file_open(struct inode *inode, struct file *file)
2693 {
2694 	file->private_data = inode->i_private;
2695 	return nonseekable_open(inode, file);
2696 }
2697 
2698 /**
2699  * provide_user_output - provide output to the user reading a debugfs file.
2700  * @val: boolean value for the answer
2701  * @u: the buffer to store the answer at
2702  * @count: size of the buffer
2703  * @ppos: position in the @u output buffer
2704  *
2705  * This is a simple helper function which stores @val boolean value in the user
2706  * buffer when the user reads one of UBIFS debugfs files. Returns amount of
2707  * bytes written to @u in case of success and a negative error code in case of
2708  * failure.
2709  */
2710 static int provide_user_output(int val, char __user *u, size_t count,
2711 			       loff_t *ppos)
2712 {
2713 	char buf[3];
2714 
2715 	if (val)
2716 		buf[0] = '1';
2717 	else
2718 		buf[0] = '0';
2719 	buf[1] = '\n';
2720 	buf[2] = 0x00;
2721 
2722 	return simple_read_from_buffer(u, count, ppos, buf, 2);
2723 }
2724 
2725 static ssize_t dfs_file_read(struct file *file, char __user *u, size_t count,
2726 			     loff_t *ppos)
2727 {
2728 	struct dentry *dent = file->f_path.dentry;
2729 	struct ubifs_info *c = file->private_data;
2730 	struct ubifs_debug_info *d = c->dbg;
2731 	int val;
2732 
2733 	if (dent == d->dfs_chk_gen)
2734 		val = d->chk_gen;
2735 	else if (dent == d->dfs_chk_index)
2736 		val = d->chk_index;
2737 	else if (dent == d->dfs_chk_orph)
2738 		val = d->chk_orph;
2739 	else if (dent == d->dfs_chk_lprops)
2740 		val = d->chk_lprops;
2741 	else if (dent == d->dfs_chk_fs)
2742 		val = d->chk_fs;
2743 	else if (dent == d->dfs_tst_rcvry)
2744 		val = d->tst_rcvry;
2745 	else if (dent == d->dfs_ro_error)
2746 		val = c->ro_error;
2747 	else
2748 		return -EINVAL;
2749 
2750 	return provide_user_output(val, u, count, ppos);
2751 }
2752 
2753 /**
2754  * interpret_user_input - interpret user debugfs file input.
2755  * @u: user-provided buffer with the input
2756  * @count: buffer size
2757  *
2758  * This is a helper function which interpret user input to a boolean UBIFS
2759  * debugfs file. Returns %0 or %1 in case of success and a negative error code
2760  * in case of failure.
2761  */
2762 static int interpret_user_input(const char __user *u, size_t count)
2763 {
2764 	size_t buf_size;
2765 	char buf[8];
2766 
2767 	buf_size = min_t(size_t, count, (sizeof(buf) - 1));
2768 	if (copy_from_user(buf, u, buf_size))
2769 		return -EFAULT;
2770 
2771 	if (buf[0] == '1')
2772 		return 1;
2773 	else if (buf[0] == '0')
2774 		return 0;
2775 
2776 	return -EINVAL;
2777 }
2778 
2779 static ssize_t dfs_file_write(struct file *file, const char __user *u,
2780 			      size_t count, loff_t *ppos)
2781 {
2782 	struct ubifs_info *c = file->private_data;
2783 	struct ubifs_debug_info *d = c->dbg;
2784 	struct dentry *dent = file->f_path.dentry;
2785 	int val;
2786 
2787 	/*
2788 	 * TODO: this is racy - the file-system might have already been
2789 	 * unmounted and we'd oops in this case. The plan is to fix it with
2790 	 * help of 'iterate_supers_type()' which we should have in v3.0: when
2791 	 * a debugfs opened, we rember FS's UUID in file->private_data. Then
2792 	 * whenever we access the FS via a debugfs file, we iterate all UBIFS
2793 	 * superblocks and fine the one with the same UUID, and take the
2794 	 * locking right.
2795 	 *
2796 	 * The other way to go suggested by Al Viro is to create a separate
2797 	 * 'ubifs-debug' file-system instead.
2798 	 */
2799 	if (file->f_path.dentry == d->dfs_dump_lprops) {
2800 		ubifs_dump_lprops(c);
2801 		return count;
2802 	}
2803 	if (file->f_path.dentry == d->dfs_dump_budg) {
2804 		ubifs_dump_budg(c, &c->bi);
2805 		return count;
2806 	}
2807 	if (file->f_path.dentry == d->dfs_dump_tnc) {
2808 		mutex_lock(&c->tnc_mutex);
2809 		ubifs_dump_tnc(c);
2810 		mutex_unlock(&c->tnc_mutex);
2811 		return count;
2812 	}
2813 
2814 	val = interpret_user_input(u, count);
2815 	if (val < 0)
2816 		return val;
2817 
2818 	if (dent == d->dfs_chk_gen)
2819 		d->chk_gen = val;
2820 	else if (dent == d->dfs_chk_index)
2821 		d->chk_index = val;
2822 	else if (dent == d->dfs_chk_orph)
2823 		d->chk_orph = val;
2824 	else if (dent == d->dfs_chk_lprops)
2825 		d->chk_lprops = val;
2826 	else if (dent == d->dfs_chk_fs)
2827 		d->chk_fs = val;
2828 	else if (dent == d->dfs_tst_rcvry)
2829 		d->tst_rcvry = val;
2830 	else if (dent == d->dfs_ro_error)
2831 		c->ro_error = !!val;
2832 	else
2833 		return -EINVAL;
2834 
2835 	return count;
2836 }
2837 
2838 static const struct file_operations dfs_fops = {
2839 	.open = dfs_file_open,
2840 	.read = dfs_file_read,
2841 	.write = dfs_file_write,
2842 	.owner = THIS_MODULE,
2843 	.llseek = no_llseek,
2844 };
2845 
2846 /**
2847  * dbg_debugfs_init_fs - initialize debugfs for UBIFS instance.
2848  * @c: UBIFS file-system description object
2849  *
2850  * This function creates all debugfs files for this instance of UBIFS. Returns
2851  * zero in case of success and a negative error code in case of failure.
2852  *
2853  * Note, the only reason we have not merged this function with the
2854  * 'ubifs_debugging_init()' function is because it is better to initialize
2855  * debugfs interfaces at the very end of the mount process, and remove them at
2856  * the very beginning of the mount process.
2857  */
2858 int dbg_debugfs_init_fs(struct ubifs_info *c)
2859 {
2860 	int err, n;
2861 	const char *fname;
2862 	struct dentry *dent;
2863 	struct ubifs_debug_info *d = c->dbg;
2864 
2865 	if (!IS_ENABLED(CONFIG_DEBUG_FS))
2866 		return 0;
2867 
2868 	n = snprintf(d->dfs_dir_name, UBIFS_DFS_DIR_LEN + 1, UBIFS_DFS_DIR_NAME,
2869 		     c->vi.ubi_num, c->vi.vol_id);
2870 	if (n == UBIFS_DFS_DIR_LEN) {
2871 		/* The array size is too small */
2872 		fname = UBIFS_DFS_DIR_NAME;
2873 		dent = ERR_PTR(-EINVAL);
2874 		goto out;
2875 	}
2876 
2877 	fname = d->dfs_dir_name;
2878 	dent = debugfs_create_dir(fname, dfs_rootdir);
2879 	if (IS_ERR_OR_NULL(dent))
2880 		goto out;
2881 	d->dfs_dir = dent;
2882 
2883 	fname = "dump_lprops";
2884 	dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
2885 	if (IS_ERR_OR_NULL(dent))
2886 		goto out_remove;
2887 	d->dfs_dump_lprops = dent;
2888 
2889 	fname = "dump_budg";
2890 	dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
2891 	if (IS_ERR_OR_NULL(dent))
2892 		goto out_remove;
2893 	d->dfs_dump_budg = dent;
2894 
2895 	fname = "dump_tnc";
2896 	dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
2897 	if (IS_ERR_OR_NULL(dent))
2898 		goto out_remove;
2899 	d->dfs_dump_tnc = dent;
2900 
2901 	fname = "chk_general";
2902 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2903 				   &dfs_fops);
2904 	if (IS_ERR_OR_NULL(dent))
2905 		goto out_remove;
2906 	d->dfs_chk_gen = dent;
2907 
2908 	fname = "chk_index";
2909 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2910 				   &dfs_fops);
2911 	if (IS_ERR_OR_NULL(dent))
2912 		goto out_remove;
2913 	d->dfs_chk_index = dent;
2914 
2915 	fname = "chk_orphans";
2916 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2917 				   &dfs_fops);
2918 	if (IS_ERR_OR_NULL(dent))
2919 		goto out_remove;
2920 	d->dfs_chk_orph = dent;
2921 
2922 	fname = "chk_lprops";
2923 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2924 				   &dfs_fops);
2925 	if (IS_ERR_OR_NULL(dent))
2926 		goto out_remove;
2927 	d->dfs_chk_lprops = dent;
2928 
2929 	fname = "chk_fs";
2930 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2931 				   &dfs_fops);
2932 	if (IS_ERR_OR_NULL(dent))
2933 		goto out_remove;
2934 	d->dfs_chk_fs = dent;
2935 
2936 	fname = "tst_recovery";
2937 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2938 				   &dfs_fops);
2939 	if (IS_ERR_OR_NULL(dent))
2940 		goto out_remove;
2941 	d->dfs_tst_rcvry = dent;
2942 
2943 	fname = "ro_error";
2944 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2945 				   &dfs_fops);
2946 	if (IS_ERR_OR_NULL(dent))
2947 		goto out_remove;
2948 	d->dfs_ro_error = dent;
2949 
2950 	return 0;
2951 
2952 out_remove:
2953 	debugfs_remove_recursive(d->dfs_dir);
2954 out:
2955 	err = dent ? PTR_ERR(dent) : -ENODEV;
2956 	ubifs_err(c, "cannot create \"%s\" debugfs file or directory, error %d\n",
2957 		  fname, err);
2958 	return err;
2959 }
2960 
2961 /**
2962  * dbg_debugfs_exit_fs - remove all debugfs files.
2963  * @c: UBIFS file-system description object
2964  */
2965 void dbg_debugfs_exit_fs(struct ubifs_info *c)
2966 {
2967 	if (IS_ENABLED(CONFIG_DEBUG_FS))
2968 		debugfs_remove_recursive(c->dbg->dfs_dir);
2969 }
2970 
2971 struct ubifs_global_debug_info ubifs_dbg;
2972 
2973 static struct dentry *dfs_chk_gen;
2974 static struct dentry *dfs_chk_index;
2975 static struct dentry *dfs_chk_orph;
2976 static struct dentry *dfs_chk_lprops;
2977 static struct dentry *dfs_chk_fs;
2978 static struct dentry *dfs_tst_rcvry;
2979 
2980 static ssize_t dfs_global_file_read(struct file *file, char __user *u,
2981 				    size_t count, loff_t *ppos)
2982 {
2983 	struct dentry *dent = file->f_path.dentry;
2984 	int val;
2985 
2986 	if (dent == dfs_chk_gen)
2987 		val = ubifs_dbg.chk_gen;
2988 	else if (dent == dfs_chk_index)
2989 		val = ubifs_dbg.chk_index;
2990 	else if (dent == dfs_chk_orph)
2991 		val = ubifs_dbg.chk_orph;
2992 	else if (dent == dfs_chk_lprops)
2993 		val = ubifs_dbg.chk_lprops;
2994 	else if (dent == dfs_chk_fs)
2995 		val = ubifs_dbg.chk_fs;
2996 	else if (dent == dfs_tst_rcvry)
2997 		val = ubifs_dbg.tst_rcvry;
2998 	else
2999 		return -EINVAL;
3000 
3001 	return provide_user_output(val, u, count, ppos);
3002 }
3003 
3004 static ssize_t dfs_global_file_write(struct file *file, const char __user *u,
3005 				     size_t count, loff_t *ppos)
3006 {
3007 	struct dentry *dent = file->f_path.dentry;
3008 	int val;
3009 
3010 	val = interpret_user_input(u, count);
3011 	if (val < 0)
3012 		return val;
3013 
3014 	if (dent == dfs_chk_gen)
3015 		ubifs_dbg.chk_gen = val;
3016 	else if (dent == dfs_chk_index)
3017 		ubifs_dbg.chk_index = val;
3018 	else if (dent == dfs_chk_orph)
3019 		ubifs_dbg.chk_orph = val;
3020 	else if (dent == dfs_chk_lprops)
3021 		ubifs_dbg.chk_lprops = val;
3022 	else if (dent == dfs_chk_fs)
3023 		ubifs_dbg.chk_fs = val;
3024 	else if (dent == dfs_tst_rcvry)
3025 		ubifs_dbg.tst_rcvry = val;
3026 	else
3027 		return -EINVAL;
3028 
3029 	return count;
3030 }
3031 
3032 static const struct file_operations dfs_global_fops = {
3033 	.read = dfs_global_file_read,
3034 	.write = dfs_global_file_write,
3035 	.owner = THIS_MODULE,
3036 	.llseek = no_llseek,
3037 };
3038 
3039 /**
3040  * dbg_debugfs_init - initialize debugfs file-system.
3041  *
3042  * UBIFS uses debugfs file-system to expose various debugging knobs to
3043  * user-space. This function creates "ubifs" directory in the debugfs
3044  * file-system. Returns zero in case of success and a negative error code in
3045  * case of failure.
3046  */
3047 int dbg_debugfs_init(void)
3048 {
3049 	int err;
3050 	const char *fname;
3051 	struct dentry *dent;
3052 
3053 	if (!IS_ENABLED(CONFIG_DEBUG_FS))
3054 		return 0;
3055 
3056 	fname = "ubifs";
3057 	dent = debugfs_create_dir(fname, NULL);
3058 	if (IS_ERR_OR_NULL(dent))
3059 		goto out;
3060 	dfs_rootdir = dent;
3061 
3062 	fname = "chk_general";
3063 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3064 				   &dfs_global_fops);
3065 	if (IS_ERR_OR_NULL(dent))
3066 		goto out_remove;
3067 	dfs_chk_gen = dent;
3068 
3069 	fname = "chk_index";
3070 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3071 				   &dfs_global_fops);
3072 	if (IS_ERR_OR_NULL(dent))
3073 		goto out_remove;
3074 	dfs_chk_index = dent;
3075 
3076 	fname = "chk_orphans";
3077 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3078 				   &dfs_global_fops);
3079 	if (IS_ERR_OR_NULL(dent))
3080 		goto out_remove;
3081 	dfs_chk_orph = dent;
3082 
3083 	fname = "chk_lprops";
3084 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3085 				   &dfs_global_fops);
3086 	if (IS_ERR_OR_NULL(dent))
3087 		goto out_remove;
3088 	dfs_chk_lprops = dent;
3089 
3090 	fname = "chk_fs";
3091 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3092 				   &dfs_global_fops);
3093 	if (IS_ERR_OR_NULL(dent))
3094 		goto out_remove;
3095 	dfs_chk_fs = dent;
3096 
3097 	fname = "tst_recovery";
3098 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3099 				   &dfs_global_fops);
3100 	if (IS_ERR_OR_NULL(dent))
3101 		goto out_remove;
3102 	dfs_tst_rcvry = dent;
3103 
3104 	return 0;
3105 
3106 out_remove:
3107 	debugfs_remove_recursive(dfs_rootdir);
3108 out:
3109 	err = dent ? PTR_ERR(dent) : -ENODEV;
3110 	pr_err("UBIFS error (pid %d): cannot create \"%s\" debugfs file or directory, error %d\n",
3111 	       current->pid, fname, err);
3112 	return err;
3113 }
3114 
3115 /**
3116  * dbg_debugfs_exit - remove the "ubifs" directory from debugfs file-system.
3117  */
3118 void dbg_debugfs_exit(void)
3119 {
3120 	if (IS_ENABLED(CONFIG_DEBUG_FS))
3121 		debugfs_remove_recursive(dfs_rootdir);
3122 }
3123 
3124 /**
3125  * ubifs_debugging_init - initialize UBIFS debugging.
3126  * @c: UBIFS file-system description object
3127  *
3128  * This function initializes debugging-related data for the file system.
3129  * Returns zero in case of success and a negative error code in case of
3130  * failure.
3131  */
3132 int ubifs_debugging_init(struct ubifs_info *c)
3133 {
3134 	c->dbg = kzalloc(sizeof(struct ubifs_debug_info), GFP_KERNEL);
3135 	if (!c->dbg)
3136 		return -ENOMEM;
3137 
3138 	return 0;
3139 }
3140 
3141 /**
3142  * ubifs_debugging_exit - free debugging data.
3143  * @c: UBIFS file-system description object
3144  */
3145 void ubifs_debugging_exit(struct ubifs_info *c)
3146 {
3147 	kfree(c->dbg);
3148 }
3149 #endif
3150