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