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