xref: /linux/fs/ubifs/debug.c (revision bd628c1bed7902ec1f24ba0fe70758949146abbe)
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 			zbr->znode = child;
1607 		}
1608 
1609 		znode = child;
1610 	}
1611 
1612 	/* Iterate over all indexing nodes */
1613 	while (1) {
1614 		int idx;
1615 
1616 		cond_resched();
1617 
1618 		if (znode_cb) {
1619 			err = znode_cb(c, znode, priv);
1620 			if (err) {
1621 				ubifs_err(c, "znode checking function returned error %d",
1622 					  err);
1623 				ubifs_dump_znode(c, znode);
1624 				goto out_dump;
1625 			}
1626 		}
1627 		if (leaf_cb && znode->level == 0) {
1628 			for (idx = 0; idx < znode->child_cnt; idx++) {
1629 				zbr = &znode->zbranch[idx];
1630 				err = leaf_cb(c, zbr, priv);
1631 				if (err) {
1632 					ubifs_err(c, "leaf checking function returned error %d, for leaf at LEB %d:%d",
1633 						  err, zbr->lnum, zbr->offs);
1634 					goto out_dump;
1635 				}
1636 			}
1637 		}
1638 
1639 		if (!znode->parent)
1640 			break;
1641 
1642 		idx = znode->iip + 1;
1643 		znode = znode->parent;
1644 		if (idx < znode->child_cnt) {
1645 			/* Switch to the next index in the parent */
1646 			zbr = &znode->zbranch[idx];
1647 			child = zbr->znode;
1648 			if (!child) {
1649 				child = ubifs_load_znode(c, zbr, znode, idx);
1650 				if (IS_ERR(child)) {
1651 					err = PTR_ERR(child);
1652 					goto out_unlock;
1653 				}
1654 				zbr->znode = child;
1655 			}
1656 			znode = child;
1657 		} else
1658 			/*
1659 			 * This is the last child, switch to the parent and
1660 			 * continue.
1661 			 */
1662 			continue;
1663 
1664 		/* Go to the lowest leftmost znode in the new sub-tree */
1665 		while (znode->level > 0) {
1666 			zbr = &znode->zbranch[0];
1667 			child = zbr->znode;
1668 			if (!child) {
1669 				child = ubifs_load_znode(c, zbr, znode, 0);
1670 				if (IS_ERR(child)) {
1671 					err = PTR_ERR(child);
1672 					goto out_unlock;
1673 				}
1674 				zbr->znode = child;
1675 			}
1676 			znode = child;
1677 		}
1678 	}
1679 
1680 	mutex_unlock(&c->tnc_mutex);
1681 	return 0;
1682 
1683 out_dump:
1684 	if (znode->parent)
1685 		zbr = &znode->parent->zbranch[znode->iip];
1686 	else
1687 		zbr = &c->zroot;
1688 	ubifs_msg(c, "dump of znode at LEB %d:%d", zbr->lnum, zbr->offs);
1689 	ubifs_dump_znode(c, znode);
1690 out_unlock:
1691 	mutex_unlock(&c->tnc_mutex);
1692 	return err;
1693 }
1694 
1695 /**
1696  * add_size - add znode size to partially calculated index size.
1697  * @c: UBIFS file-system description object
1698  * @znode: znode to add size for
1699  * @priv: partially calculated index size
1700  *
1701  * This is a helper function for 'dbg_check_idx_size()' which is called for
1702  * every indexing node and adds its size to the 'long long' variable pointed to
1703  * by @priv.
1704  */
1705 static int add_size(struct ubifs_info *c, struct ubifs_znode *znode, void *priv)
1706 {
1707 	long long *idx_size = priv;
1708 	int add;
1709 
1710 	add = ubifs_idx_node_sz(c, znode->child_cnt);
1711 	add = ALIGN(add, 8);
1712 	*idx_size += add;
1713 	return 0;
1714 }
1715 
1716 /**
1717  * dbg_check_idx_size - check index size.
1718  * @c: UBIFS file-system description object
1719  * @idx_size: size to check
1720  *
1721  * This function walks the UBIFS index, calculates its size and checks that the
1722  * size is equivalent to @idx_size. Returns zero in case of success and a
1723  * negative error code in case of failure.
1724  */
1725 int dbg_check_idx_size(struct ubifs_info *c, long long idx_size)
1726 {
1727 	int err;
1728 	long long calc = 0;
1729 
1730 	if (!dbg_is_chk_index(c))
1731 		return 0;
1732 
1733 	err = dbg_walk_index(c, NULL, add_size, &calc);
1734 	if (err) {
1735 		ubifs_err(c, "error %d while walking the index", err);
1736 		return err;
1737 	}
1738 
1739 	if (calc != idx_size) {
1740 		ubifs_err(c, "index size check failed: calculated size is %lld, should be %lld",
1741 			  calc, idx_size);
1742 		dump_stack();
1743 		return -EINVAL;
1744 	}
1745 
1746 	return 0;
1747 }
1748 
1749 /**
1750  * struct fsck_inode - information about an inode used when checking the file-system.
1751  * @rb: link in the RB-tree of inodes
1752  * @inum: inode number
1753  * @mode: inode type, permissions, etc
1754  * @nlink: inode link count
1755  * @xattr_cnt: count of extended attributes
1756  * @references: how many directory/xattr entries refer this inode (calculated
1757  *              while walking the index)
1758  * @calc_cnt: for directory inode count of child directories
1759  * @size: inode size (read from on-flash inode)
1760  * @xattr_sz: summary size of all extended attributes (read from on-flash
1761  *            inode)
1762  * @calc_sz: for directories calculated directory size
1763  * @calc_xcnt: count of extended attributes
1764  * @calc_xsz: calculated summary size of all extended attributes
1765  * @xattr_nms: sum of lengths of all extended attribute names belonging to this
1766  *             inode (read from on-flash inode)
1767  * @calc_xnms: calculated sum of lengths of all extended attribute names
1768  */
1769 struct fsck_inode {
1770 	struct rb_node rb;
1771 	ino_t inum;
1772 	umode_t mode;
1773 	unsigned int nlink;
1774 	unsigned int xattr_cnt;
1775 	int references;
1776 	int calc_cnt;
1777 	long long size;
1778 	unsigned int xattr_sz;
1779 	long long calc_sz;
1780 	long long calc_xcnt;
1781 	long long calc_xsz;
1782 	unsigned int xattr_nms;
1783 	long long calc_xnms;
1784 };
1785 
1786 /**
1787  * struct fsck_data - private FS checking information.
1788  * @inodes: RB-tree of all inodes (contains @struct fsck_inode objects)
1789  */
1790 struct fsck_data {
1791 	struct rb_root inodes;
1792 };
1793 
1794 /**
1795  * add_inode - add inode information to RB-tree of inodes.
1796  * @c: UBIFS file-system description object
1797  * @fsckd: FS checking information
1798  * @ino: raw UBIFS inode to add
1799  *
1800  * This is a helper function for 'check_leaf()' which adds information about
1801  * inode @ino to the RB-tree of inodes. Returns inode information pointer in
1802  * case of success and a negative error code in case of failure.
1803  */
1804 static struct fsck_inode *add_inode(struct ubifs_info *c,
1805 				    struct fsck_data *fsckd,
1806 				    struct ubifs_ino_node *ino)
1807 {
1808 	struct rb_node **p, *parent = NULL;
1809 	struct fsck_inode *fscki;
1810 	ino_t inum = key_inum_flash(c, &ino->key);
1811 	struct inode *inode;
1812 	struct ubifs_inode *ui;
1813 
1814 	p = &fsckd->inodes.rb_node;
1815 	while (*p) {
1816 		parent = *p;
1817 		fscki = rb_entry(parent, struct fsck_inode, rb);
1818 		if (inum < fscki->inum)
1819 			p = &(*p)->rb_left;
1820 		else if (inum > fscki->inum)
1821 			p = &(*p)->rb_right;
1822 		else
1823 			return fscki;
1824 	}
1825 
1826 	if (inum > c->highest_inum) {
1827 		ubifs_err(c, "too high inode number, max. is %lu",
1828 			  (unsigned long)c->highest_inum);
1829 		return ERR_PTR(-EINVAL);
1830 	}
1831 
1832 	fscki = kzalloc(sizeof(struct fsck_inode), GFP_NOFS);
1833 	if (!fscki)
1834 		return ERR_PTR(-ENOMEM);
1835 
1836 	inode = ilookup(c->vfs_sb, inum);
1837 
1838 	fscki->inum = inum;
1839 	/*
1840 	 * If the inode is present in the VFS inode cache, use it instead of
1841 	 * the on-flash inode which might be out-of-date. E.g., the size might
1842 	 * be out-of-date. If we do not do this, the following may happen, for
1843 	 * example:
1844 	 *   1. A power cut happens
1845 	 *   2. We mount the file-system R/O, the replay process fixes up the
1846 	 *      inode size in the VFS cache, but on on-flash.
1847 	 *   3. 'check_leaf()' fails because it hits a data node beyond inode
1848 	 *      size.
1849 	 */
1850 	if (!inode) {
1851 		fscki->nlink = le32_to_cpu(ino->nlink);
1852 		fscki->size = le64_to_cpu(ino->size);
1853 		fscki->xattr_cnt = le32_to_cpu(ino->xattr_cnt);
1854 		fscki->xattr_sz = le32_to_cpu(ino->xattr_size);
1855 		fscki->xattr_nms = le32_to_cpu(ino->xattr_names);
1856 		fscki->mode = le32_to_cpu(ino->mode);
1857 	} else {
1858 		ui = ubifs_inode(inode);
1859 		fscki->nlink = inode->i_nlink;
1860 		fscki->size = inode->i_size;
1861 		fscki->xattr_cnt = ui->xattr_cnt;
1862 		fscki->xattr_sz = ui->xattr_size;
1863 		fscki->xattr_nms = ui->xattr_names;
1864 		fscki->mode = inode->i_mode;
1865 		iput(inode);
1866 	}
1867 
1868 	if (S_ISDIR(fscki->mode)) {
1869 		fscki->calc_sz = UBIFS_INO_NODE_SZ;
1870 		fscki->calc_cnt = 2;
1871 	}
1872 
1873 	rb_link_node(&fscki->rb, parent, p);
1874 	rb_insert_color(&fscki->rb, &fsckd->inodes);
1875 
1876 	return fscki;
1877 }
1878 
1879 /**
1880  * search_inode - search inode in the RB-tree of inodes.
1881  * @fsckd: FS checking information
1882  * @inum: inode number to search
1883  *
1884  * This is a helper function for 'check_leaf()' which searches inode @inum in
1885  * the RB-tree of inodes and returns an inode information pointer or %NULL if
1886  * the inode was not found.
1887  */
1888 static struct fsck_inode *search_inode(struct fsck_data *fsckd, ino_t inum)
1889 {
1890 	struct rb_node *p;
1891 	struct fsck_inode *fscki;
1892 
1893 	p = fsckd->inodes.rb_node;
1894 	while (p) {
1895 		fscki = rb_entry(p, struct fsck_inode, rb);
1896 		if (inum < fscki->inum)
1897 			p = p->rb_left;
1898 		else if (inum > fscki->inum)
1899 			p = p->rb_right;
1900 		else
1901 			return fscki;
1902 	}
1903 	return NULL;
1904 }
1905 
1906 /**
1907  * read_add_inode - read inode node and add it to RB-tree of inodes.
1908  * @c: UBIFS file-system description object
1909  * @fsckd: FS checking information
1910  * @inum: inode number to read
1911  *
1912  * This is a helper function for 'check_leaf()' which finds inode node @inum in
1913  * the index, reads it, and adds it to the RB-tree of inodes. Returns inode
1914  * information pointer in case of success and a negative error code in case of
1915  * failure.
1916  */
1917 static struct fsck_inode *read_add_inode(struct ubifs_info *c,
1918 					 struct fsck_data *fsckd, ino_t inum)
1919 {
1920 	int n, err;
1921 	union ubifs_key key;
1922 	struct ubifs_znode *znode;
1923 	struct ubifs_zbranch *zbr;
1924 	struct ubifs_ino_node *ino;
1925 	struct fsck_inode *fscki;
1926 
1927 	fscki = search_inode(fsckd, inum);
1928 	if (fscki)
1929 		return fscki;
1930 
1931 	ino_key_init(c, &key, inum);
1932 	err = ubifs_lookup_level0(c, &key, &znode, &n);
1933 	if (!err) {
1934 		ubifs_err(c, "inode %lu not found in index", (unsigned long)inum);
1935 		return ERR_PTR(-ENOENT);
1936 	} else if (err < 0) {
1937 		ubifs_err(c, "error %d while looking up inode %lu",
1938 			  err, (unsigned long)inum);
1939 		return ERR_PTR(err);
1940 	}
1941 
1942 	zbr = &znode->zbranch[n];
1943 	if (zbr->len < UBIFS_INO_NODE_SZ) {
1944 		ubifs_err(c, "bad node %lu node length %d",
1945 			  (unsigned long)inum, zbr->len);
1946 		return ERR_PTR(-EINVAL);
1947 	}
1948 
1949 	ino = kmalloc(zbr->len, GFP_NOFS);
1950 	if (!ino)
1951 		return ERR_PTR(-ENOMEM);
1952 
1953 	err = ubifs_tnc_read_node(c, zbr, ino);
1954 	if (err) {
1955 		ubifs_err(c, "cannot read inode node at LEB %d:%d, error %d",
1956 			  zbr->lnum, zbr->offs, err);
1957 		kfree(ino);
1958 		return ERR_PTR(err);
1959 	}
1960 
1961 	fscki = add_inode(c, fsckd, ino);
1962 	kfree(ino);
1963 	if (IS_ERR(fscki)) {
1964 		ubifs_err(c, "error %ld while adding inode %lu node",
1965 			  PTR_ERR(fscki), (unsigned long)inum);
1966 		return fscki;
1967 	}
1968 
1969 	return fscki;
1970 }
1971 
1972 /**
1973  * check_leaf - check leaf node.
1974  * @c: UBIFS file-system description object
1975  * @zbr: zbranch of the leaf node to check
1976  * @priv: FS checking information
1977  *
1978  * This is a helper function for 'dbg_check_filesystem()' which is called for
1979  * every single leaf node while walking the indexing tree. It checks that the
1980  * leaf node referred from the indexing tree exists, has correct CRC, and does
1981  * some other basic validation. This function is also responsible for building
1982  * an RB-tree of inodes - it adds all inodes into the RB-tree. It also
1983  * calculates reference count, size, etc for each inode in order to later
1984  * compare them to the information stored inside the inodes and detect possible
1985  * inconsistencies. Returns zero in case of success and a negative error code
1986  * in case of failure.
1987  */
1988 static int check_leaf(struct ubifs_info *c, struct ubifs_zbranch *zbr,
1989 		      void *priv)
1990 {
1991 	ino_t inum;
1992 	void *node;
1993 	struct ubifs_ch *ch;
1994 	int err, type = key_type(c, &zbr->key);
1995 	struct fsck_inode *fscki;
1996 
1997 	if (zbr->len < UBIFS_CH_SZ) {
1998 		ubifs_err(c, "bad leaf length %d (LEB %d:%d)",
1999 			  zbr->len, zbr->lnum, zbr->offs);
2000 		return -EINVAL;
2001 	}
2002 
2003 	node = kmalloc(zbr->len, GFP_NOFS);
2004 	if (!node)
2005 		return -ENOMEM;
2006 
2007 	err = ubifs_tnc_read_node(c, zbr, node);
2008 	if (err) {
2009 		ubifs_err(c, "cannot read leaf node at LEB %d:%d, error %d",
2010 			  zbr->lnum, zbr->offs, err);
2011 		goto out_free;
2012 	}
2013 
2014 	/* If this is an inode node, add it to RB-tree of inodes */
2015 	if (type == UBIFS_INO_KEY) {
2016 		fscki = add_inode(c, priv, node);
2017 		if (IS_ERR(fscki)) {
2018 			err = PTR_ERR(fscki);
2019 			ubifs_err(c, "error %d while adding inode node", err);
2020 			goto out_dump;
2021 		}
2022 		goto out;
2023 	}
2024 
2025 	if (type != UBIFS_DENT_KEY && type != UBIFS_XENT_KEY &&
2026 	    type != UBIFS_DATA_KEY) {
2027 		ubifs_err(c, "unexpected node type %d at LEB %d:%d",
2028 			  type, zbr->lnum, zbr->offs);
2029 		err = -EINVAL;
2030 		goto out_free;
2031 	}
2032 
2033 	ch = node;
2034 	if (le64_to_cpu(ch->sqnum) > c->max_sqnum) {
2035 		ubifs_err(c, "too high sequence number, max. is %llu",
2036 			  c->max_sqnum);
2037 		err = -EINVAL;
2038 		goto out_dump;
2039 	}
2040 
2041 	if (type == UBIFS_DATA_KEY) {
2042 		long long blk_offs;
2043 		struct ubifs_data_node *dn = node;
2044 
2045 		ubifs_assert(c, zbr->len >= UBIFS_DATA_NODE_SZ);
2046 
2047 		/*
2048 		 * Search the inode node this data node belongs to and insert
2049 		 * it to the RB-tree of inodes.
2050 		 */
2051 		inum = key_inum_flash(c, &dn->key);
2052 		fscki = read_add_inode(c, priv, inum);
2053 		if (IS_ERR(fscki)) {
2054 			err = PTR_ERR(fscki);
2055 			ubifs_err(c, "error %d while processing data node and trying to find inode node %lu",
2056 				  err, (unsigned long)inum);
2057 			goto out_dump;
2058 		}
2059 
2060 		/* Make sure the data node is within inode size */
2061 		blk_offs = key_block_flash(c, &dn->key);
2062 		blk_offs <<= UBIFS_BLOCK_SHIFT;
2063 		blk_offs += le32_to_cpu(dn->size);
2064 		if (blk_offs > fscki->size) {
2065 			ubifs_err(c, "data node at LEB %d:%d is not within inode size %lld",
2066 				  zbr->lnum, zbr->offs, fscki->size);
2067 			err = -EINVAL;
2068 			goto out_dump;
2069 		}
2070 	} else {
2071 		int nlen;
2072 		struct ubifs_dent_node *dent = node;
2073 		struct fsck_inode *fscki1;
2074 
2075 		ubifs_assert(c, zbr->len >= UBIFS_DENT_NODE_SZ);
2076 
2077 		err = ubifs_validate_entry(c, dent);
2078 		if (err)
2079 			goto out_dump;
2080 
2081 		/*
2082 		 * Search the inode node this entry refers to and the parent
2083 		 * inode node and insert them to the RB-tree of inodes.
2084 		 */
2085 		inum = le64_to_cpu(dent->inum);
2086 		fscki = read_add_inode(c, priv, inum);
2087 		if (IS_ERR(fscki)) {
2088 			err = PTR_ERR(fscki);
2089 			ubifs_err(c, "error %d while processing entry node and trying to find inode node %lu",
2090 				  err, (unsigned long)inum);
2091 			goto out_dump;
2092 		}
2093 
2094 		/* Count how many direntries or xentries refers this inode */
2095 		fscki->references += 1;
2096 
2097 		inum = key_inum_flash(c, &dent->key);
2098 		fscki1 = read_add_inode(c, priv, inum);
2099 		if (IS_ERR(fscki1)) {
2100 			err = PTR_ERR(fscki1);
2101 			ubifs_err(c, "error %d while processing entry node and trying to find parent inode node %lu",
2102 				  err, (unsigned long)inum);
2103 			goto out_dump;
2104 		}
2105 
2106 		nlen = le16_to_cpu(dent->nlen);
2107 		if (type == UBIFS_XENT_KEY) {
2108 			fscki1->calc_xcnt += 1;
2109 			fscki1->calc_xsz += CALC_DENT_SIZE(nlen);
2110 			fscki1->calc_xsz += CALC_XATTR_BYTES(fscki->size);
2111 			fscki1->calc_xnms += nlen;
2112 		} else {
2113 			fscki1->calc_sz += CALC_DENT_SIZE(nlen);
2114 			if (dent->type == UBIFS_ITYPE_DIR)
2115 				fscki1->calc_cnt += 1;
2116 		}
2117 	}
2118 
2119 out:
2120 	kfree(node);
2121 	return 0;
2122 
2123 out_dump:
2124 	ubifs_msg(c, "dump of node at LEB %d:%d", zbr->lnum, zbr->offs);
2125 	ubifs_dump_node(c, node);
2126 out_free:
2127 	kfree(node);
2128 	return err;
2129 }
2130 
2131 /**
2132  * free_inodes - free RB-tree of inodes.
2133  * @fsckd: FS checking information
2134  */
2135 static void free_inodes(struct fsck_data *fsckd)
2136 {
2137 	struct fsck_inode *fscki, *n;
2138 
2139 	rbtree_postorder_for_each_entry_safe(fscki, n, &fsckd->inodes, rb)
2140 		kfree(fscki);
2141 }
2142 
2143 /**
2144  * check_inodes - checks all inodes.
2145  * @c: UBIFS file-system description object
2146  * @fsckd: FS checking information
2147  *
2148  * This is a helper function for 'dbg_check_filesystem()' which walks the
2149  * RB-tree of inodes after the index scan has been finished, and checks that
2150  * inode nlink, size, etc are correct. Returns zero if inodes are fine,
2151  * %-EINVAL if not, and a negative error code in case of failure.
2152  */
2153 static int check_inodes(struct ubifs_info *c, struct fsck_data *fsckd)
2154 {
2155 	int n, err;
2156 	union ubifs_key key;
2157 	struct ubifs_znode *znode;
2158 	struct ubifs_zbranch *zbr;
2159 	struct ubifs_ino_node *ino;
2160 	struct fsck_inode *fscki;
2161 	struct rb_node *this = rb_first(&fsckd->inodes);
2162 
2163 	while (this) {
2164 		fscki = rb_entry(this, struct fsck_inode, rb);
2165 		this = rb_next(this);
2166 
2167 		if (S_ISDIR(fscki->mode)) {
2168 			/*
2169 			 * Directories have to have exactly one reference (they
2170 			 * cannot have hardlinks), although root inode is an
2171 			 * exception.
2172 			 */
2173 			if (fscki->inum != UBIFS_ROOT_INO &&
2174 			    fscki->references != 1) {
2175 				ubifs_err(c, "directory inode %lu has %d direntries which refer it, but should be 1",
2176 					  (unsigned long)fscki->inum,
2177 					  fscki->references);
2178 				goto out_dump;
2179 			}
2180 			if (fscki->inum == UBIFS_ROOT_INO &&
2181 			    fscki->references != 0) {
2182 				ubifs_err(c, "root inode %lu has non-zero (%d) direntries which refer it",
2183 					  (unsigned long)fscki->inum,
2184 					  fscki->references);
2185 				goto out_dump;
2186 			}
2187 			if (fscki->calc_sz != fscki->size) {
2188 				ubifs_err(c, "directory inode %lu size is %lld, but calculated size is %lld",
2189 					  (unsigned long)fscki->inum,
2190 					  fscki->size, fscki->calc_sz);
2191 				goto out_dump;
2192 			}
2193 			if (fscki->calc_cnt != fscki->nlink) {
2194 				ubifs_err(c, "directory inode %lu nlink is %d, but calculated nlink is %d",
2195 					  (unsigned long)fscki->inum,
2196 					  fscki->nlink, fscki->calc_cnt);
2197 				goto out_dump;
2198 			}
2199 		} else {
2200 			if (fscki->references != fscki->nlink) {
2201 				ubifs_err(c, "inode %lu nlink is %d, but calculated nlink is %d",
2202 					  (unsigned long)fscki->inum,
2203 					  fscki->nlink, fscki->references);
2204 				goto out_dump;
2205 			}
2206 		}
2207 		if (fscki->xattr_sz != fscki->calc_xsz) {
2208 			ubifs_err(c, "inode %lu has xattr size %u, but calculated size is %lld",
2209 				  (unsigned long)fscki->inum, fscki->xattr_sz,
2210 				  fscki->calc_xsz);
2211 			goto out_dump;
2212 		}
2213 		if (fscki->xattr_cnt != fscki->calc_xcnt) {
2214 			ubifs_err(c, "inode %lu has %u xattrs, but calculated count is %lld",
2215 				  (unsigned long)fscki->inum,
2216 				  fscki->xattr_cnt, fscki->calc_xcnt);
2217 			goto out_dump;
2218 		}
2219 		if (fscki->xattr_nms != fscki->calc_xnms) {
2220 			ubifs_err(c, "inode %lu has xattr names' size %u, but calculated names' size is %lld",
2221 				  (unsigned long)fscki->inum, fscki->xattr_nms,
2222 				  fscki->calc_xnms);
2223 			goto out_dump;
2224 		}
2225 	}
2226 
2227 	return 0;
2228 
2229 out_dump:
2230 	/* Read the bad inode and dump it */
2231 	ino_key_init(c, &key, fscki->inum);
2232 	err = ubifs_lookup_level0(c, &key, &znode, &n);
2233 	if (!err) {
2234 		ubifs_err(c, "inode %lu not found in index",
2235 			  (unsigned long)fscki->inum);
2236 		return -ENOENT;
2237 	} else if (err < 0) {
2238 		ubifs_err(c, "error %d while looking up inode %lu",
2239 			  err, (unsigned long)fscki->inum);
2240 		return err;
2241 	}
2242 
2243 	zbr = &znode->zbranch[n];
2244 	ino = kmalloc(zbr->len, GFP_NOFS);
2245 	if (!ino)
2246 		return -ENOMEM;
2247 
2248 	err = ubifs_tnc_read_node(c, zbr, ino);
2249 	if (err) {
2250 		ubifs_err(c, "cannot read inode node at LEB %d:%d, error %d",
2251 			  zbr->lnum, zbr->offs, err);
2252 		kfree(ino);
2253 		return err;
2254 	}
2255 
2256 	ubifs_msg(c, "dump of the inode %lu sitting in LEB %d:%d",
2257 		  (unsigned long)fscki->inum, zbr->lnum, zbr->offs);
2258 	ubifs_dump_node(c, ino);
2259 	kfree(ino);
2260 	return -EINVAL;
2261 }
2262 
2263 /**
2264  * dbg_check_filesystem - check the file-system.
2265  * @c: UBIFS file-system description object
2266  *
2267  * This function checks the file system, namely:
2268  * o makes sure that all leaf nodes exist and their CRCs are correct;
2269  * o makes sure inode nlink, size, xattr size/count are correct (for all
2270  *   inodes).
2271  *
2272  * The function reads whole indexing tree and all nodes, so it is pretty
2273  * heavy-weight. Returns zero if the file-system is consistent, %-EINVAL if
2274  * not, and a negative error code in case of failure.
2275  */
2276 int dbg_check_filesystem(struct ubifs_info *c)
2277 {
2278 	int err;
2279 	struct fsck_data fsckd;
2280 
2281 	if (!dbg_is_chk_fs(c))
2282 		return 0;
2283 
2284 	fsckd.inodes = RB_ROOT;
2285 	err = dbg_walk_index(c, check_leaf, NULL, &fsckd);
2286 	if (err)
2287 		goto out_free;
2288 
2289 	err = check_inodes(c, &fsckd);
2290 	if (err)
2291 		goto out_free;
2292 
2293 	free_inodes(&fsckd);
2294 	return 0;
2295 
2296 out_free:
2297 	ubifs_err(c, "file-system check failed with error %d", err);
2298 	dump_stack();
2299 	free_inodes(&fsckd);
2300 	return err;
2301 }
2302 
2303 /**
2304  * dbg_check_data_nodes_order - check that list of data nodes is sorted.
2305  * @c: UBIFS file-system description object
2306  * @head: the list of nodes ('struct ubifs_scan_node' objects)
2307  *
2308  * This function returns zero if the list of data nodes is sorted correctly,
2309  * and %-EINVAL if not.
2310  */
2311 int dbg_check_data_nodes_order(struct ubifs_info *c, struct list_head *head)
2312 {
2313 	struct list_head *cur;
2314 	struct ubifs_scan_node *sa, *sb;
2315 
2316 	if (!dbg_is_chk_gen(c))
2317 		return 0;
2318 
2319 	for (cur = head->next; cur->next != head; cur = cur->next) {
2320 		ino_t inuma, inumb;
2321 		uint32_t blka, blkb;
2322 
2323 		cond_resched();
2324 		sa = container_of(cur, struct ubifs_scan_node, list);
2325 		sb = container_of(cur->next, struct ubifs_scan_node, list);
2326 
2327 		if (sa->type != UBIFS_DATA_NODE) {
2328 			ubifs_err(c, "bad node type %d", sa->type);
2329 			ubifs_dump_node(c, sa->node);
2330 			return -EINVAL;
2331 		}
2332 		if (sb->type != UBIFS_DATA_NODE) {
2333 			ubifs_err(c, "bad node type %d", sb->type);
2334 			ubifs_dump_node(c, sb->node);
2335 			return -EINVAL;
2336 		}
2337 
2338 		inuma = key_inum(c, &sa->key);
2339 		inumb = key_inum(c, &sb->key);
2340 
2341 		if (inuma < inumb)
2342 			continue;
2343 		if (inuma > inumb) {
2344 			ubifs_err(c, "larger inum %lu goes before inum %lu",
2345 				  (unsigned long)inuma, (unsigned long)inumb);
2346 			goto error_dump;
2347 		}
2348 
2349 		blka = key_block(c, &sa->key);
2350 		blkb = key_block(c, &sb->key);
2351 
2352 		if (blka > blkb) {
2353 			ubifs_err(c, "larger block %u goes before %u", blka, blkb);
2354 			goto error_dump;
2355 		}
2356 		if (blka == blkb) {
2357 			ubifs_err(c, "two data nodes for the same block");
2358 			goto error_dump;
2359 		}
2360 	}
2361 
2362 	return 0;
2363 
2364 error_dump:
2365 	ubifs_dump_node(c, sa->node);
2366 	ubifs_dump_node(c, sb->node);
2367 	return -EINVAL;
2368 }
2369 
2370 /**
2371  * dbg_check_nondata_nodes_order - check that list of data nodes is sorted.
2372  * @c: UBIFS file-system description object
2373  * @head: the list of nodes ('struct ubifs_scan_node' objects)
2374  *
2375  * This function returns zero if the list of non-data nodes is sorted correctly,
2376  * and %-EINVAL if not.
2377  */
2378 int dbg_check_nondata_nodes_order(struct ubifs_info *c, struct list_head *head)
2379 {
2380 	struct list_head *cur;
2381 	struct ubifs_scan_node *sa, *sb;
2382 
2383 	if (!dbg_is_chk_gen(c))
2384 		return 0;
2385 
2386 	for (cur = head->next; cur->next != head; cur = cur->next) {
2387 		ino_t inuma, inumb;
2388 		uint32_t hasha, hashb;
2389 
2390 		cond_resched();
2391 		sa = container_of(cur, struct ubifs_scan_node, list);
2392 		sb = container_of(cur->next, struct ubifs_scan_node, list);
2393 
2394 		if (sa->type != UBIFS_INO_NODE && sa->type != UBIFS_DENT_NODE &&
2395 		    sa->type != UBIFS_XENT_NODE) {
2396 			ubifs_err(c, "bad node type %d", sa->type);
2397 			ubifs_dump_node(c, sa->node);
2398 			return -EINVAL;
2399 		}
2400 		if (sb->type != UBIFS_INO_NODE && sb->type != UBIFS_DENT_NODE &&
2401 		    sb->type != UBIFS_XENT_NODE) {
2402 			ubifs_err(c, "bad node type %d", sb->type);
2403 			ubifs_dump_node(c, sb->node);
2404 			return -EINVAL;
2405 		}
2406 
2407 		if (sa->type != UBIFS_INO_NODE && sb->type == UBIFS_INO_NODE) {
2408 			ubifs_err(c, "non-inode node goes before inode node");
2409 			goto error_dump;
2410 		}
2411 
2412 		if (sa->type == UBIFS_INO_NODE && sb->type != UBIFS_INO_NODE)
2413 			continue;
2414 
2415 		if (sa->type == UBIFS_INO_NODE && sb->type == UBIFS_INO_NODE) {
2416 			/* Inode nodes are sorted in descending size order */
2417 			if (sa->len < sb->len) {
2418 				ubifs_err(c, "smaller inode node goes first");
2419 				goto error_dump;
2420 			}
2421 			continue;
2422 		}
2423 
2424 		/*
2425 		 * This is either a dentry or xentry, which should be sorted in
2426 		 * ascending (parent ino, hash) order.
2427 		 */
2428 		inuma = key_inum(c, &sa->key);
2429 		inumb = key_inum(c, &sb->key);
2430 
2431 		if (inuma < inumb)
2432 			continue;
2433 		if (inuma > inumb) {
2434 			ubifs_err(c, "larger inum %lu goes before inum %lu",
2435 				  (unsigned long)inuma, (unsigned long)inumb);
2436 			goto error_dump;
2437 		}
2438 
2439 		hasha = key_block(c, &sa->key);
2440 		hashb = key_block(c, &sb->key);
2441 
2442 		if (hasha > hashb) {
2443 			ubifs_err(c, "larger hash %u goes before %u",
2444 				  hasha, hashb);
2445 			goto error_dump;
2446 		}
2447 	}
2448 
2449 	return 0;
2450 
2451 error_dump:
2452 	ubifs_msg(c, "dumping first node");
2453 	ubifs_dump_node(c, sa->node);
2454 	ubifs_msg(c, "dumping second node");
2455 	ubifs_dump_node(c, sb->node);
2456 	return -EINVAL;
2457 	return 0;
2458 }
2459 
2460 static inline int chance(unsigned int n, unsigned int out_of)
2461 {
2462 	return !!((prandom_u32() % out_of) + 1 <= n);
2463 
2464 }
2465 
2466 static int power_cut_emulated(struct ubifs_info *c, int lnum, int write)
2467 {
2468 	struct ubifs_debug_info *d = c->dbg;
2469 
2470 	ubifs_assert(c, dbg_is_tst_rcvry(c));
2471 
2472 	if (!d->pc_cnt) {
2473 		/* First call - decide delay to the power cut */
2474 		if (chance(1, 2)) {
2475 			unsigned long delay;
2476 
2477 			if (chance(1, 2)) {
2478 				d->pc_delay = 1;
2479 				/* Fail within 1 minute */
2480 				delay = prandom_u32() % 60000;
2481 				d->pc_timeout = jiffies;
2482 				d->pc_timeout += msecs_to_jiffies(delay);
2483 				ubifs_warn(c, "failing after %lums", delay);
2484 			} else {
2485 				d->pc_delay = 2;
2486 				delay = prandom_u32() % 10000;
2487 				/* Fail within 10000 operations */
2488 				d->pc_cnt_max = delay;
2489 				ubifs_warn(c, "failing after %lu calls", delay);
2490 			}
2491 		}
2492 
2493 		d->pc_cnt += 1;
2494 	}
2495 
2496 	/* Determine if failure delay has expired */
2497 	if (d->pc_delay == 1 && time_before(jiffies, d->pc_timeout))
2498 			return 0;
2499 	if (d->pc_delay == 2 && d->pc_cnt++ < d->pc_cnt_max)
2500 			return 0;
2501 
2502 	if (lnum == UBIFS_SB_LNUM) {
2503 		if (write && chance(1, 2))
2504 			return 0;
2505 		if (chance(19, 20))
2506 			return 0;
2507 		ubifs_warn(c, "failing in super block LEB %d", lnum);
2508 	} else if (lnum == UBIFS_MST_LNUM || lnum == UBIFS_MST_LNUM + 1) {
2509 		if (chance(19, 20))
2510 			return 0;
2511 		ubifs_warn(c, "failing in master LEB %d", lnum);
2512 	} else if (lnum >= UBIFS_LOG_LNUM && lnum <= c->log_last) {
2513 		if (write && chance(99, 100))
2514 			return 0;
2515 		if (chance(399, 400))
2516 			return 0;
2517 		ubifs_warn(c, "failing in log LEB %d", lnum);
2518 	} else if (lnum >= c->lpt_first && lnum <= c->lpt_last) {
2519 		if (write && chance(7, 8))
2520 			return 0;
2521 		if (chance(19, 20))
2522 			return 0;
2523 		ubifs_warn(c, "failing in LPT LEB %d", lnum);
2524 	} else if (lnum >= c->orph_first && lnum <= c->orph_last) {
2525 		if (write && chance(1, 2))
2526 			return 0;
2527 		if (chance(9, 10))
2528 			return 0;
2529 		ubifs_warn(c, "failing in orphan LEB %d", lnum);
2530 	} else if (lnum == c->ihead_lnum) {
2531 		if (chance(99, 100))
2532 			return 0;
2533 		ubifs_warn(c, "failing in index head LEB %d", lnum);
2534 	} else if (c->jheads && lnum == c->jheads[GCHD].wbuf.lnum) {
2535 		if (chance(9, 10))
2536 			return 0;
2537 		ubifs_warn(c, "failing in GC head LEB %d", lnum);
2538 	} else if (write && !RB_EMPTY_ROOT(&c->buds) &&
2539 		   !ubifs_search_bud(c, lnum)) {
2540 		if (chance(19, 20))
2541 			return 0;
2542 		ubifs_warn(c, "failing in non-bud LEB %d", lnum);
2543 	} else if (c->cmt_state == COMMIT_RUNNING_BACKGROUND ||
2544 		   c->cmt_state == COMMIT_RUNNING_REQUIRED) {
2545 		if (chance(999, 1000))
2546 			return 0;
2547 		ubifs_warn(c, "failing in bud LEB %d commit running", lnum);
2548 	} else {
2549 		if (chance(9999, 10000))
2550 			return 0;
2551 		ubifs_warn(c, "failing in bud LEB %d commit not running", lnum);
2552 	}
2553 
2554 	d->pc_happened = 1;
2555 	ubifs_warn(c, "========== Power cut emulated ==========");
2556 	dump_stack();
2557 	return 1;
2558 }
2559 
2560 static int corrupt_data(const struct ubifs_info *c, const void *buf,
2561 			unsigned int len)
2562 {
2563 	unsigned int from, to, ffs = chance(1, 2);
2564 	unsigned char *p = (void *)buf;
2565 
2566 	from = prandom_u32() % len;
2567 	/* Corruption span max to end of write unit */
2568 	to = min(len, ALIGN(from + 1, c->max_write_size));
2569 
2570 	ubifs_warn(c, "filled bytes %u-%u with %s", from, to - 1,
2571 		   ffs ? "0xFFs" : "random data");
2572 
2573 	if (ffs)
2574 		memset(p + from, 0xFF, to - from);
2575 	else
2576 		prandom_bytes(p + from, to - from);
2577 
2578 	return to;
2579 }
2580 
2581 int dbg_leb_write(struct ubifs_info *c, int lnum, const void *buf,
2582 		  int offs, int len)
2583 {
2584 	int err, failing;
2585 
2586 	if (dbg_is_power_cut(c))
2587 		return -EROFS;
2588 
2589 	failing = power_cut_emulated(c, lnum, 1);
2590 	if (failing) {
2591 		len = corrupt_data(c, buf, len);
2592 		ubifs_warn(c, "actually write %d bytes to LEB %d:%d (the buffer was corrupted)",
2593 			   len, lnum, offs);
2594 	}
2595 	err = ubi_leb_write(c->ubi, lnum, buf, offs, len);
2596 	if (err)
2597 		return err;
2598 	if (failing)
2599 		return -EROFS;
2600 	return 0;
2601 }
2602 
2603 int dbg_leb_change(struct ubifs_info *c, int lnum, const void *buf,
2604 		   int len)
2605 {
2606 	int err;
2607 
2608 	if (dbg_is_power_cut(c))
2609 		return -EROFS;
2610 	if (power_cut_emulated(c, lnum, 1))
2611 		return -EROFS;
2612 	err = ubi_leb_change(c->ubi, lnum, buf, len);
2613 	if (err)
2614 		return err;
2615 	if (power_cut_emulated(c, lnum, 1))
2616 		return -EROFS;
2617 	return 0;
2618 }
2619 
2620 int dbg_leb_unmap(struct ubifs_info *c, int lnum)
2621 {
2622 	int err;
2623 
2624 	if (dbg_is_power_cut(c))
2625 		return -EROFS;
2626 	if (power_cut_emulated(c, lnum, 0))
2627 		return -EROFS;
2628 	err = ubi_leb_unmap(c->ubi, lnum);
2629 	if (err)
2630 		return err;
2631 	if (power_cut_emulated(c, lnum, 0))
2632 		return -EROFS;
2633 	return 0;
2634 }
2635 
2636 int dbg_leb_map(struct ubifs_info *c, int lnum)
2637 {
2638 	int err;
2639 
2640 	if (dbg_is_power_cut(c))
2641 		return -EROFS;
2642 	if (power_cut_emulated(c, lnum, 0))
2643 		return -EROFS;
2644 	err = ubi_leb_map(c->ubi, lnum);
2645 	if (err)
2646 		return err;
2647 	if (power_cut_emulated(c, lnum, 0))
2648 		return -EROFS;
2649 	return 0;
2650 }
2651 
2652 /*
2653  * Root directory for UBIFS stuff in debugfs. Contains sub-directories which
2654  * contain the stuff specific to particular file-system mounts.
2655  */
2656 static struct dentry *dfs_rootdir;
2657 
2658 static int dfs_file_open(struct inode *inode, struct file *file)
2659 {
2660 	file->private_data = inode->i_private;
2661 	return nonseekable_open(inode, file);
2662 }
2663 
2664 /**
2665  * provide_user_output - provide output to the user reading a debugfs file.
2666  * @val: boolean value for the answer
2667  * @u: the buffer to store the answer at
2668  * @count: size of the buffer
2669  * @ppos: position in the @u output buffer
2670  *
2671  * This is a simple helper function which stores @val boolean value in the user
2672  * buffer when the user reads one of UBIFS debugfs files. Returns amount of
2673  * bytes written to @u in case of success and a negative error code in case of
2674  * failure.
2675  */
2676 static int provide_user_output(int val, char __user *u, size_t count,
2677 			       loff_t *ppos)
2678 {
2679 	char buf[3];
2680 
2681 	if (val)
2682 		buf[0] = '1';
2683 	else
2684 		buf[0] = '0';
2685 	buf[1] = '\n';
2686 	buf[2] = 0x00;
2687 
2688 	return simple_read_from_buffer(u, count, ppos, buf, 2);
2689 }
2690 
2691 static ssize_t dfs_file_read(struct file *file, char __user *u, size_t count,
2692 			     loff_t *ppos)
2693 {
2694 	struct dentry *dent = file->f_path.dentry;
2695 	struct ubifs_info *c = file->private_data;
2696 	struct ubifs_debug_info *d = c->dbg;
2697 	int val;
2698 
2699 	if (dent == d->dfs_chk_gen)
2700 		val = d->chk_gen;
2701 	else if (dent == d->dfs_chk_index)
2702 		val = d->chk_index;
2703 	else if (dent == d->dfs_chk_orph)
2704 		val = d->chk_orph;
2705 	else if (dent == d->dfs_chk_lprops)
2706 		val = d->chk_lprops;
2707 	else if (dent == d->dfs_chk_fs)
2708 		val = d->chk_fs;
2709 	else if (dent == d->dfs_tst_rcvry)
2710 		val = d->tst_rcvry;
2711 	else if (dent == d->dfs_ro_error)
2712 		val = c->ro_error;
2713 	else
2714 		return -EINVAL;
2715 
2716 	return provide_user_output(val, u, count, ppos);
2717 }
2718 
2719 /**
2720  * interpret_user_input - interpret user debugfs file input.
2721  * @u: user-provided buffer with the input
2722  * @count: buffer size
2723  *
2724  * This is a helper function which interpret user input to a boolean UBIFS
2725  * debugfs file. Returns %0 or %1 in case of success and a negative error code
2726  * in case of failure.
2727  */
2728 static int interpret_user_input(const char __user *u, size_t count)
2729 {
2730 	size_t buf_size;
2731 	char buf[8];
2732 
2733 	buf_size = min_t(size_t, count, (sizeof(buf) - 1));
2734 	if (copy_from_user(buf, u, buf_size))
2735 		return -EFAULT;
2736 
2737 	if (buf[0] == '1')
2738 		return 1;
2739 	else if (buf[0] == '0')
2740 		return 0;
2741 
2742 	return -EINVAL;
2743 }
2744 
2745 static ssize_t dfs_file_write(struct file *file, const char __user *u,
2746 			      size_t count, loff_t *ppos)
2747 {
2748 	struct ubifs_info *c = file->private_data;
2749 	struct ubifs_debug_info *d = c->dbg;
2750 	struct dentry *dent = file->f_path.dentry;
2751 	int val;
2752 
2753 	/*
2754 	 * TODO: this is racy - the file-system might have already been
2755 	 * unmounted and we'd oops in this case. The plan is to fix it with
2756 	 * help of 'iterate_supers_type()' which we should have in v3.0: when
2757 	 * a debugfs opened, we rember FS's UUID in file->private_data. Then
2758 	 * whenever we access the FS via a debugfs file, we iterate all UBIFS
2759 	 * superblocks and fine the one with the same UUID, and take the
2760 	 * locking right.
2761 	 *
2762 	 * The other way to go suggested by Al Viro is to create a separate
2763 	 * 'ubifs-debug' file-system instead.
2764 	 */
2765 	if (file->f_path.dentry == d->dfs_dump_lprops) {
2766 		ubifs_dump_lprops(c);
2767 		return count;
2768 	}
2769 	if (file->f_path.dentry == d->dfs_dump_budg) {
2770 		ubifs_dump_budg(c, &c->bi);
2771 		return count;
2772 	}
2773 	if (file->f_path.dentry == d->dfs_dump_tnc) {
2774 		mutex_lock(&c->tnc_mutex);
2775 		ubifs_dump_tnc(c);
2776 		mutex_unlock(&c->tnc_mutex);
2777 		return count;
2778 	}
2779 
2780 	val = interpret_user_input(u, count);
2781 	if (val < 0)
2782 		return val;
2783 
2784 	if (dent == d->dfs_chk_gen)
2785 		d->chk_gen = val;
2786 	else if (dent == d->dfs_chk_index)
2787 		d->chk_index = val;
2788 	else if (dent == d->dfs_chk_orph)
2789 		d->chk_orph = val;
2790 	else if (dent == d->dfs_chk_lprops)
2791 		d->chk_lprops = val;
2792 	else if (dent == d->dfs_chk_fs)
2793 		d->chk_fs = val;
2794 	else if (dent == d->dfs_tst_rcvry)
2795 		d->tst_rcvry = val;
2796 	else if (dent == d->dfs_ro_error)
2797 		c->ro_error = !!val;
2798 	else
2799 		return -EINVAL;
2800 
2801 	return count;
2802 }
2803 
2804 static const struct file_operations dfs_fops = {
2805 	.open = dfs_file_open,
2806 	.read = dfs_file_read,
2807 	.write = dfs_file_write,
2808 	.owner = THIS_MODULE,
2809 	.llseek = no_llseek,
2810 };
2811 
2812 /**
2813  * dbg_debugfs_init_fs - initialize debugfs for UBIFS instance.
2814  * @c: UBIFS file-system description object
2815  *
2816  * This function creates all debugfs files for this instance of UBIFS. Returns
2817  * zero in case of success and a negative error code in case of failure.
2818  *
2819  * Note, the only reason we have not merged this function with the
2820  * 'ubifs_debugging_init()' function is because it is better to initialize
2821  * debugfs interfaces at the very end of the mount process, and remove them at
2822  * the very beginning of the mount process.
2823  */
2824 int dbg_debugfs_init_fs(struct ubifs_info *c)
2825 {
2826 	int err, n;
2827 	const char *fname;
2828 	struct dentry *dent;
2829 	struct ubifs_debug_info *d = c->dbg;
2830 
2831 	if (!IS_ENABLED(CONFIG_DEBUG_FS))
2832 		return 0;
2833 
2834 	n = snprintf(d->dfs_dir_name, UBIFS_DFS_DIR_LEN + 1, UBIFS_DFS_DIR_NAME,
2835 		     c->vi.ubi_num, c->vi.vol_id);
2836 	if (n == UBIFS_DFS_DIR_LEN) {
2837 		/* The array size is too small */
2838 		fname = UBIFS_DFS_DIR_NAME;
2839 		dent = ERR_PTR(-EINVAL);
2840 		goto out;
2841 	}
2842 
2843 	fname = d->dfs_dir_name;
2844 	dent = debugfs_create_dir(fname, dfs_rootdir);
2845 	if (IS_ERR_OR_NULL(dent))
2846 		goto out;
2847 	d->dfs_dir = dent;
2848 
2849 	fname = "dump_lprops";
2850 	dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
2851 	if (IS_ERR_OR_NULL(dent))
2852 		goto out_remove;
2853 	d->dfs_dump_lprops = dent;
2854 
2855 	fname = "dump_budg";
2856 	dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
2857 	if (IS_ERR_OR_NULL(dent))
2858 		goto out_remove;
2859 	d->dfs_dump_budg = dent;
2860 
2861 	fname = "dump_tnc";
2862 	dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
2863 	if (IS_ERR_OR_NULL(dent))
2864 		goto out_remove;
2865 	d->dfs_dump_tnc = dent;
2866 
2867 	fname = "chk_general";
2868 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2869 				   &dfs_fops);
2870 	if (IS_ERR_OR_NULL(dent))
2871 		goto out_remove;
2872 	d->dfs_chk_gen = dent;
2873 
2874 	fname = "chk_index";
2875 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2876 				   &dfs_fops);
2877 	if (IS_ERR_OR_NULL(dent))
2878 		goto out_remove;
2879 	d->dfs_chk_index = dent;
2880 
2881 	fname = "chk_orphans";
2882 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2883 				   &dfs_fops);
2884 	if (IS_ERR_OR_NULL(dent))
2885 		goto out_remove;
2886 	d->dfs_chk_orph = dent;
2887 
2888 	fname = "chk_lprops";
2889 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2890 				   &dfs_fops);
2891 	if (IS_ERR_OR_NULL(dent))
2892 		goto out_remove;
2893 	d->dfs_chk_lprops = dent;
2894 
2895 	fname = "chk_fs";
2896 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2897 				   &dfs_fops);
2898 	if (IS_ERR_OR_NULL(dent))
2899 		goto out_remove;
2900 	d->dfs_chk_fs = dent;
2901 
2902 	fname = "tst_recovery";
2903 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2904 				   &dfs_fops);
2905 	if (IS_ERR_OR_NULL(dent))
2906 		goto out_remove;
2907 	d->dfs_tst_rcvry = dent;
2908 
2909 	fname = "ro_error";
2910 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, d->dfs_dir, c,
2911 				   &dfs_fops);
2912 	if (IS_ERR_OR_NULL(dent))
2913 		goto out_remove;
2914 	d->dfs_ro_error = dent;
2915 
2916 	return 0;
2917 
2918 out_remove:
2919 	debugfs_remove_recursive(d->dfs_dir);
2920 out:
2921 	err = dent ? PTR_ERR(dent) : -ENODEV;
2922 	ubifs_err(c, "cannot create \"%s\" debugfs file or directory, error %d\n",
2923 		  fname, err);
2924 	return err;
2925 }
2926 
2927 /**
2928  * dbg_debugfs_exit_fs - remove all debugfs files.
2929  * @c: UBIFS file-system description object
2930  */
2931 void dbg_debugfs_exit_fs(struct ubifs_info *c)
2932 {
2933 	if (IS_ENABLED(CONFIG_DEBUG_FS))
2934 		debugfs_remove_recursive(c->dbg->dfs_dir);
2935 }
2936 
2937 struct ubifs_global_debug_info ubifs_dbg;
2938 
2939 static struct dentry *dfs_chk_gen;
2940 static struct dentry *dfs_chk_index;
2941 static struct dentry *dfs_chk_orph;
2942 static struct dentry *dfs_chk_lprops;
2943 static struct dentry *dfs_chk_fs;
2944 static struct dentry *dfs_tst_rcvry;
2945 
2946 static ssize_t dfs_global_file_read(struct file *file, char __user *u,
2947 				    size_t count, loff_t *ppos)
2948 {
2949 	struct dentry *dent = file->f_path.dentry;
2950 	int val;
2951 
2952 	if (dent == dfs_chk_gen)
2953 		val = ubifs_dbg.chk_gen;
2954 	else if (dent == dfs_chk_index)
2955 		val = ubifs_dbg.chk_index;
2956 	else if (dent == dfs_chk_orph)
2957 		val = ubifs_dbg.chk_orph;
2958 	else if (dent == dfs_chk_lprops)
2959 		val = ubifs_dbg.chk_lprops;
2960 	else if (dent == dfs_chk_fs)
2961 		val = ubifs_dbg.chk_fs;
2962 	else if (dent == dfs_tst_rcvry)
2963 		val = ubifs_dbg.tst_rcvry;
2964 	else
2965 		return -EINVAL;
2966 
2967 	return provide_user_output(val, u, count, ppos);
2968 }
2969 
2970 static ssize_t dfs_global_file_write(struct file *file, const char __user *u,
2971 				     size_t count, loff_t *ppos)
2972 {
2973 	struct dentry *dent = file->f_path.dentry;
2974 	int val;
2975 
2976 	val = interpret_user_input(u, count);
2977 	if (val < 0)
2978 		return val;
2979 
2980 	if (dent == dfs_chk_gen)
2981 		ubifs_dbg.chk_gen = val;
2982 	else if (dent == dfs_chk_index)
2983 		ubifs_dbg.chk_index = val;
2984 	else if (dent == dfs_chk_orph)
2985 		ubifs_dbg.chk_orph = val;
2986 	else if (dent == dfs_chk_lprops)
2987 		ubifs_dbg.chk_lprops = val;
2988 	else if (dent == dfs_chk_fs)
2989 		ubifs_dbg.chk_fs = val;
2990 	else if (dent == dfs_tst_rcvry)
2991 		ubifs_dbg.tst_rcvry = val;
2992 	else
2993 		return -EINVAL;
2994 
2995 	return count;
2996 }
2997 
2998 static const struct file_operations dfs_global_fops = {
2999 	.read = dfs_global_file_read,
3000 	.write = dfs_global_file_write,
3001 	.owner = THIS_MODULE,
3002 	.llseek = no_llseek,
3003 };
3004 
3005 /**
3006  * dbg_debugfs_init - initialize debugfs file-system.
3007  *
3008  * UBIFS uses debugfs file-system to expose various debugging knobs to
3009  * user-space. This function creates "ubifs" directory in the debugfs
3010  * file-system. Returns zero in case of success and a negative error code in
3011  * case of failure.
3012  */
3013 int dbg_debugfs_init(void)
3014 {
3015 	int err;
3016 	const char *fname;
3017 	struct dentry *dent;
3018 
3019 	if (!IS_ENABLED(CONFIG_DEBUG_FS))
3020 		return 0;
3021 
3022 	fname = "ubifs";
3023 	dent = debugfs_create_dir(fname, NULL);
3024 	if (IS_ERR_OR_NULL(dent))
3025 		goto out;
3026 	dfs_rootdir = dent;
3027 
3028 	fname = "chk_general";
3029 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3030 				   &dfs_global_fops);
3031 	if (IS_ERR_OR_NULL(dent))
3032 		goto out_remove;
3033 	dfs_chk_gen = dent;
3034 
3035 	fname = "chk_index";
3036 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3037 				   &dfs_global_fops);
3038 	if (IS_ERR_OR_NULL(dent))
3039 		goto out_remove;
3040 	dfs_chk_index = dent;
3041 
3042 	fname = "chk_orphans";
3043 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3044 				   &dfs_global_fops);
3045 	if (IS_ERR_OR_NULL(dent))
3046 		goto out_remove;
3047 	dfs_chk_orph = dent;
3048 
3049 	fname = "chk_lprops";
3050 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3051 				   &dfs_global_fops);
3052 	if (IS_ERR_OR_NULL(dent))
3053 		goto out_remove;
3054 	dfs_chk_lprops = dent;
3055 
3056 	fname = "chk_fs";
3057 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3058 				   &dfs_global_fops);
3059 	if (IS_ERR_OR_NULL(dent))
3060 		goto out_remove;
3061 	dfs_chk_fs = dent;
3062 
3063 	fname = "tst_recovery";
3064 	dent = debugfs_create_file(fname, S_IRUSR | S_IWUSR, dfs_rootdir, NULL,
3065 				   &dfs_global_fops);
3066 	if (IS_ERR_OR_NULL(dent))
3067 		goto out_remove;
3068 	dfs_tst_rcvry = dent;
3069 
3070 	return 0;
3071 
3072 out_remove:
3073 	debugfs_remove_recursive(dfs_rootdir);
3074 out:
3075 	err = dent ? PTR_ERR(dent) : -ENODEV;
3076 	pr_err("UBIFS error (pid %d): cannot create \"%s\" debugfs file or directory, error %d\n",
3077 	       current->pid, fname, err);
3078 	return err;
3079 }
3080 
3081 /**
3082  * dbg_debugfs_exit - remove the "ubifs" directory from debugfs file-system.
3083  */
3084 void dbg_debugfs_exit(void)
3085 {
3086 	if (IS_ENABLED(CONFIG_DEBUG_FS))
3087 		debugfs_remove_recursive(dfs_rootdir);
3088 }
3089 
3090 void ubifs_assert_failed(struct ubifs_info *c, const char *expr,
3091 			 const char *file, int line)
3092 {
3093 	ubifs_err(c, "UBIFS assert failed: %s, in %s:%u", expr, file, line);
3094 
3095 	switch (c->assert_action) {
3096 		case ASSACT_PANIC:
3097 		BUG();
3098 		break;
3099 
3100 		case ASSACT_RO:
3101 		ubifs_ro_mode(c, -EINVAL);
3102 		break;
3103 
3104 		case ASSACT_REPORT:
3105 		default:
3106 		dump_stack();
3107 		break;
3108 
3109 	}
3110 }
3111 
3112 /**
3113  * ubifs_debugging_init - initialize UBIFS debugging.
3114  * @c: UBIFS file-system description object
3115  *
3116  * This function initializes debugging-related data for the file system.
3117  * Returns zero in case of success and a negative error code in case of
3118  * failure.
3119  */
3120 int ubifs_debugging_init(struct ubifs_info *c)
3121 {
3122 	c->dbg = kzalloc(sizeof(struct ubifs_debug_info), GFP_KERNEL);
3123 	if (!c->dbg)
3124 		return -ENOMEM;
3125 
3126 	return 0;
3127 }
3128 
3129 /**
3130  * ubifs_debugging_exit - free debugging data.
3131  * @c: UBIFS file-system description object
3132  */
3133 void ubifs_debugging_exit(struct ubifs_info *c)
3134 {
3135 	kfree(c->dbg);
3136 }
3137