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