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