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