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