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