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