Merge branch 'for-linus/2640/i2c' of git://git.fluff.org/bjdooks/linux
[pandora-kernel.git] / fs / ubifs / recovery.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: Adrian Hunter
20  *          Artem Bityutskiy (Битюцкий Артём)
21  */
22
23 /*
24  * This file implements functions needed to recover from unclean un-mounts.
25  * When UBIFS is mounted, it checks a flag on the master node to determine if
26  * an un-mount was completed successfully. If not, the process of mounting
27  * incorporates additional checking and fixing of on-flash data structures.
28  * UBIFS always cleans away all remnants of an unclean un-mount, so that
29  * errors do not accumulate. However UBIFS defers recovery if it is mounted
30  * read-only, and the flash is not modified in that case.
31  *
32  * The general UBIFS approach to the recovery is that it recovers from
33  * corruptions which could be caused by power cuts, but it refuses to recover
34  * from corruption caused by other reasons. And UBIFS tries to distinguish
35  * between these 2 reasons of corruptions and silently recover in the former
36  * case and loudly complain in the latter case.
37  *
38  * UBIFS writes only to erased LEBs, so it writes only to the flash space
39  * containing only 0xFFs. UBIFS also always writes strictly from the beginning
40  * of the LEB to the end. And UBIFS assumes that the underlying flash media
41  * writes in @c->max_write_size bytes at a time.
42  *
43  * Hence, if UBIFS finds a corrupted node at offset X, it expects only the min.
44  * I/O unit corresponding to offset X to contain corrupted data, all the
45  * following min. I/O units have to contain empty space (all 0xFFs). If this is
46  * not true, the corruption cannot be the result of a power cut, and UBIFS
47  * refuses to mount.
48  */
49
50 #include <linux/crc32.h>
51 #include <linux/slab.h>
52 #include "ubifs.h"
53
54 /**
55  * is_empty - determine whether a buffer is empty (contains all 0xff).
56  * @buf: buffer to clean
57  * @len: length of buffer
58  *
59  * This function returns %1 if the buffer is empty (contains all 0xff) otherwise
60  * %0 is returned.
61  */
62 static int is_empty(void *buf, int len)
63 {
64         uint8_t *p = buf;
65         int i;
66
67         for (i = 0; i < len; i++)
68                 if (*p++ != 0xff)
69                         return 0;
70         return 1;
71 }
72
73 /**
74  * first_non_ff - find offset of the first non-0xff byte.
75  * @buf: buffer to search in
76  * @len: length of buffer
77  *
78  * This function returns offset of the first non-0xff byte in @buf or %-1 if
79  * the buffer contains only 0xff bytes.
80  */
81 static int first_non_ff(void *buf, int len)
82 {
83         uint8_t *p = buf;
84         int i;
85
86         for (i = 0; i < len; i++)
87                 if (*p++ != 0xff)
88                         return i;
89         return -1;
90 }
91
92 /**
93  * get_master_node - get the last valid master node allowing for corruption.
94  * @c: UBIFS file-system description object
95  * @lnum: LEB number
96  * @pbuf: buffer containing the LEB read, is returned here
97  * @mst: master node, if found, is returned here
98  * @cor: corruption, if found, is returned here
99  *
100  * This function allocates a buffer, reads the LEB into it, and finds and
101  * returns the last valid master node allowing for one area of corruption.
102  * The corrupt area, if there is one, must be consistent with the assumption
103  * that it is the result of an unclean unmount while the master node was being
104  * written. Under those circumstances, it is valid to use the previously written
105  * master node.
106  *
107  * This function returns %0 on success and a negative error code on failure.
108  */
109 static int get_master_node(const struct ubifs_info *c, int lnum, void **pbuf,
110                            struct ubifs_mst_node **mst, void **cor)
111 {
112         const int sz = c->mst_node_alsz;
113         int err, offs, len;
114         void *sbuf, *buf;
115
116         sbuf = vmalloc(c->leb_size);
117         if (!sbuf)
118                 return -ENOMEM;
119
120         err = ubi_read(c->ubi, lnum, sbuf, 0, c->leb_size);
121         if (err && err != -EBADMSG)
122                 goto out_free;
123
124         /* Find the first position that is definitely not a node */
125         offs = 0;
126         buf = sbuf;
127         len = c->leb_size;
128         while (offs + UBIFS_MST_NODE_SZ <= c->leb_size) {
129                 struct ubifs_ch *ch = buf;
130
131                 if (le32_to_cpu(ch->magic) != UBIFS_NODE_MAGIC)
132                         break;
133                 offs += sz;
134                 buf  += sz;
135                 len  -= sz;
136         }
137         /* See if there was a valid master node before that */
138         if (offs) {
139                 int ret;
140
141                 offs -= sz;
142                 buf  -= sz;
143                 len  += sz;
144                 ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
145                 if (ret != SCANNED_A_NODE && offs) {
146                         /* Could have been corruption so check one place back */
147                         offs -= sz;
148                         buf  -= sz;
149                         len  += sz;
150                         ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
151                         if (ret != SCANNED_A_NODE)
152                                 /*
153                                  * We accept only one area of corruption because
154                                  * we are assuming that it was caused while
155                                  * trying to write a master node.
156                                  */
157                                 goto out_err;
158                 }
159                 if (ret == SCANNED_A_NODE) {
160                         struct ubifs_ch *ch = buf;
161
162                         if (ch->node_type != UBIFS_MST_NODE)
163                                 goto out_err;
164                         dbg_rcvry("found a master node at %d:%d", lnum, offs);
165                         *mst = buf;
166                         offs += sz;
167                         buf  += sz;
168                         len  -= sz;
169                 }
170         }
171         /* Check for corruption */
172         if (offs < c->leb_size) {
173                 if (!is_empty(buf, min_t(int, len, sz))) {
174                         *cor = buf;
175                         dbg_rcvry("found corruption at %d:%d", lnum, offs);
176                 }
177                 offs += sz;
178                 buf  += sz;
179                 len  -= sz;
180         }
181         /* Check remaining empty space */
182         if (offs < c->leb_size)
183                 if (!is_empty(buf, len))
184                         goto out_err;
185         *pbuf = sbuf;
186         return 0;
187
188 out_err:
189         err = -EINVAL;
190 out_free:
191         vfree(sbuf);
192         *mst = NULL;
193         *cor = NULL;
194         return err;
195 }
196
197 /**
198  * write_rcvrd_mst_node - write recovered master node.
199  * @c: UBIFS file-system description object
200  * @mst: master node
201  *
202  * This function returns %0 on success and a negative error code on failure.
203  */
204 static int write_rcvrd_mst_node(struct ubifs_info *c,
205                                 struct ubifs_mst_node *mst)
206 {
207         int err = 0, lnum = UBIFS_MST_LNUM, sz = c->mst_node_alsz;
208         __le32 save_flags;
209
210         dbg_rcvry("recovery");
211
212         save_flags = mst->flags;
213         mst->flags |= cpu_to_le32(UBIFS_MST_RCVRY);
214
215         ubifs_prepare_node(c, mst, UBIFS_MST_NODE_SZ, 1);
216         err = ubi_leb_change(c->ubi, lnum, mst, sz, UBI_SHORTTERM);
217         if (err)
218                 goto out;
219         err = ubi_leb_change(c->ubi, lnum + 1, mst, sz, UBI_SHORTTERM);
220         if (err)
221                 goto out;
222 out:
223         mst->flags = save_flags;
224         return err;
225 }
226
227 /**
228  * ubifs_recover_master_node - recover the master node.
229  * @c: UBIFS file-system description object
230  *
231  * This function recovers the master node from corruption that may occur due to
232  * an unclean unmount.
233  *
234  * This function returns %0 on success and a negative error code on failure.
235  */
236 int ubifs_recover_master_node(struct ubifs_info *c)
237 {
238         void *buf1 = NULL, *buf2 = NULL, *cor1 = NULL, *cor2 = NULL;
239         struct ubifs_mst_node *mst1 = NULL, *mst2 = NULL, *mst;
240         const int sz = c->mst_node_alsz;
241         int err, offs1, offs2;
242
243         dbg_rcvry("recovery");
244
245         err = get_master_node(c, UBIFS_MST_LNUM, &buf1, &mst1, &cor1);
246         if (err)
247                 goto out_free;
248
249         err = get_master_node(c, UBIFS_MST_LNUM + 1, &buf2, &mst2, &cor2);
250         if (err)
251                 goto out_free;
252
253         if (mst1) {
254                 offs1 = (void *)mst1 - buf1;
255                 if ((le32_to_cpu(mst1->flags) & UBIFS_MST_RCVRY) &&
256                     (offs1 == 0 && !cor1)) {
257                         /*
258                          * mst1 was written by recovery at offset 0 with no
259                          * corruption.
260                          */
261                         dbg_rcvry("recovery recovery");
262                         mst = mst1;
263                 } else if (mst2) {
264                         offs2 = (void *)mst2 - buf2;
265                         if (offs1 == offs2) {
266                                 /* Same offset, so must be the same */
267                                 if (memcmp((void *)mst1 + UBIFS_CH_SZ,
268                                            (void *)mst2 + UBIFS_CH_SZ,
269                                            UBIFS_MST_NODE_SZ - UBIFS_CH_SZ))
270                                         goto out_err;
271                                 mst = mst1;
272                         } else if (offs2 + sz == offs1) {
273                                 /* 1st LEB was written, 2nd was not */
274                                 if (cor1)
275                                         goto out_err;
276                                 mst = mst1;
277                         } else if (offs1 == 0 && offs2 + sz >= c->leb_size) {
278                                 /* 1st LEB was unmapped and written, 2nd not */
279                                 if (cor1)
280                                         goto out_err;
281                                 mst = mst1;
282                         } else
283                                 goto out_err;
284                 } else {
285                         /*
286                          * 2nd LEB was unmapped and about to be written, so
287                          * there must be only one master node in the first LEB
288                          * and no corruption.
289                          */
290                         if (offs1 != 0 || cor1)
291                                 goto out_err;
292                         mst = mst1;
293                 }
294         } else {
295                 if (!mst2)
296                         goto out_err;
297                 /*
298                  * 1st LEB was unmapped and about to be written, so there must
299                  * be no room left in 2nd LEB.
300                  */
301                 offs2 = (void *)mst2 - buf2;
302                 if (offs2 + sz + sz <= c->leb_size)
303                         goto out_err;
304                 mst = mst2;
305         }
306
307         ubifs_msg("recovered master node from LEB %d",
308                   (mst == mst1 ? UBIFS_MST_LNUM : UBIFS_MST_LNUM + 1));
309
310         memcpy(c->mst_node, mst, UBIFS_MST_NODE_SZ);
311
312         if (c->ro_mount) {
313                 /* Read-only mode. Keep a copy for switching to rw mode */
314                 c->rcvrd_mst_node = kmalloc(sz, GFP_KERNEL);
315                 if (!c->rcvrd_mst_node) {
316                         err = -ENOMEM;
317                         goto out_free;
318                 }
319                 memcpy(c->rcvrd_mst_node, c->mst_node, UBIFS_MST_NODE_SZ);
320
321                 /*
322                  * We had to recover the master node, which means there was an
323                  * unclean reboot. However, it is possible that the master node
324                  * is clean at this point, i.e., %UBIFS_MST_DIRTY is not set.
325                  * E.g., consider the following chain of events:
326                  *
327                  * 1. UBIFS was cleanly unmounted, so the master node is clean
328                  * 2. UBIFS is being mounted R/W and starts changing the master
329                  *    node in the first (%UBIFS_MST_LNUM). A power cut happens,
330                  *    so this LEB ends up with some amount of garbage at the
331                  *    end.
332                  * 3. UBIFS is being mounted R/O. We reach this place and
333                  *    recover the master node from the second LEB
334                  *    (%UBIFS_MST_LNUM + 1). But we cannot update the media
335                  *    because we are being mounted R/O. We have to defer the
336                  *    operation.
337                  * 4. However, this master node (@c->mst_node) is marked as
338                  *    clean (since the step 1). And if we just return, the
339                  *    mount code will be confused and won't recover the master
340                  *    node when it is re-mounter R/W later.
341                  *
342                  *    Thus, to force the recovery by marking the master node as
343                  *    dirty.
344                  */
345                 c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
346         } else {
347                 /* Write the recovered master node */
348                 c->max_sqnum = le64_to_cpu(mst->ch.sqnum) - 1;
349                 err = write_rcvrd_mst_node(c, c->mst_node);
350                 if (err)
351                         goto out_free;
352         }
353
354         vfree(buf2);
355         vfree(buf1);
356
357         return 0;
358
359 out_err:
360         err = -EINVAL;
361 out_free:
362         ubifs_err("failed to recover master node");
363         if (mst1) {
364                 dbg_err("dumping first master node");
365                 dbg_dump_node(c, mst1);
366         }
367         if (mst2) {
368                 dbg_err("dumping second master node");
369                 dbg_dump_node(c, mst2);
370         }
371         vfree(buf2);
372         vfree(buf1);
373         return err;
374 }
375
376 /**
377  * ubifs_write_rcvrd_mst_node - write the recovered master node.
378  * @c: UBIFS file-system description object
379  *
380  * This function writes the master node that was recovered during mounting in
381  * read-only mode and must now be written because we are remounting rw.
382  *
383  * This function returns %0 on success and a negative error code on failure.
384  */
385 int ubifs_write_rcvrd_mst_node(struct ubifs_info *c)
386 {
387         int err;
388
389         if (!c->rcvrd_mst_node)
390                 return 0;
391         c->rcvrd_mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
392         c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
393         err = write_rcvrd_mst_node(c, c->rcvrd_mst_node);
394         if (err)
395                 return err;
396         kfree(c->rcvrd_mst_node);
397         c->rcvrd_mst_node = NULL;
398         return 0;
399 }
400
401 /**
402  * is_last_write - determine if an offset was in the last write to a LEB.
403  * @c: UBIFS file-system description object
404  * @buf: buffer to check
405  * @offs: offset to check
406  *
407  * This function returns %1 if @offs was in the last write to the LEB whose data
408  * is in @buf, otherwise %0 is returned. The determination is made by checking
409  * for subsequent empty space starting from the next @c->max_write_size
410  * boundary.
411  */
412 static int is_last_write(const struct ubifs_info *c, void *buf, int offs)
413 {
414         int empty_offs, check_len;
415         uint8_t *p;
416
417         /*
418          * Round up to the next @c->max_write_size boundary i.e. @offs is in
419          * the last wbuf written. After that should be empty space.
420          */
421         empty_offs = ALIGN(offs + 1, c->max_write_size);
422         check_len = c->leb_size - empty_offs;
423         p = buf + empty_offs - offs;
424         return is_empty(p, check_len);
425 }
426
427 /**
428  * clean_buf - clean the data from an LEB sitting in a buffer.
429  * @c: UBIFS file-system description object
430  * @buf: buffer to clean
431  * @lnum: LEB number to clean
432  * @offs: offset from which to clean
433  * @len: length of buffer
434  *
435  * This function pads up to the next min_io_size boundary (if there is one) and
436  * sets empty space to all 0xff. @buf, @offs and @len are updated to the next
437  * @c->min_io_size boundary.
438  */
439 static void clean_buf(const struct ubifs_info *c, void **buf, int lnum,
440                       int *offs, int *len)
441 {
442         int empty_offs, pad_len;
443
444         lnum = lnum;
445         dbg_rcvry("cleaning corruption at %d:%d", lnum, *offs);
446
447         ubifs_assert(!(*offs & 7));
448         empty_offs = ALIGN(*offs, c->min_io_size);
449         pad_len = empty_offs - *offs;
450         ubifs_pad(c, *buf, pad_len);
451         *offs += pad_len;
452         *buf += pad_len;
453         *len -= pad_len;
454         memset(*buf, 0xff, c->leb_size - empty_offs);
455 }
456
457 /**
458  * no_more_nodes - determine if there are no more nodes in a buffer.
459  * @c: UBIFS file-system description object
460  * @buf: buffer to check
461  * @len: length of buffer
462  * @lnum: LEB number of the LEB from which @buf was read
463  * @offs: offset from which @buf was read
464  *
465  * This function ensures that the corrupted node at @offs is the last thing
466  * written to a LEB. This function returns %1 if more data is not found and
467  * %0 if more data is found.
468  */
469 static int no_more_nodes(const struct ubifs_info *c, void *buf, int len,
470                         int lnum, int offs)
471 {
472         struct ubifs_ch *ch = buf;
473         int skip, dlen = le32_to_cpu(ch->len);
474
475         /* Check for empty space after the corrupt node's common header */
476         skip = ALIGN(offs + UBIFS_CH_SZ, c->max_write_size) - offs;
477         if (is_empty(buf + skip, len - skip))
478                 return 1;
479         /*
480          * The area after the common header size is not empty, so the common
481          * header must be intact. Check it.
482          */
483         if (ubifs_check_node(c, buf, lnum, offs, 1, 0) != -EUCLEAN) {
484                 dbg_rcvry("unexpected bad common header at %d:%d", lnum, offs);
485                 return 0;
486         }
487         /* Now we know the corrupt node's length we can skip over it */
488         skip = ALIGN(offs + dlen, c->max_write_size) - offs;
489         /* After which there should be empty space */
490         if (is_empty(buf + skip, len - skip))
491                 return 1;
492         dbg_rcvry("unexpected data at %d:%d", lnum, offs + skip);
493         return 0;
494 }
495
496 /**
497  * fix_unclean_leb - fix an unclean LEB.
498  * @c: UBIFS file-system description object
499  * @sleb: scanned LEB information
500  * @start: offset where scan started
501  */
502 static int fix_unclean_leb(struct ubifs_info *c, struct ubifs_scan_leb *sleb,
503                            int start)
504 {
505         int lnum = sleb->lnum, endpt = start;
506
507         /* Get the end offset of the last node we are keeping */
508         if (!list_empty(&sleb->nodes)) {
509                 struct ubifs_scan_node *snod;
510
511                 snod = list_entry(sleb->nodes.prev,
512                                   struct ubifs_scan_node, list);
513                 endpt = snod->offs + snod->len;
514         }
515
516         if (c->ro_mount && !c->remounting_rw) {
517                 /* Add to recovery list */
518                 struct ubifs_unclean_leb *ucleb;
519
520                 dbg_rcvry("need to fix LEB %d start %d endpt %d",
521                           lnum, start, sleb->endpt);
522                 ucleb = kzalloc(sizeof(struct ubifs_unclean_leb), GFP_NOFS);
523                 if (!ucleb)
524                         return -ENOMEM;
525                 ucleb->lnum = lnum;
526                 ucleb->endpt = endpt;
527                 list_add_tail(&ucleb->list, &c->unclean_leb_list);
528         } else {
529                 /* Write the fixed LEB back to flash */
530                 int err;
531
532                 dbg_rcvry("fixing LEB %d start %d endpt %d",
533                           lnum, start, sleb->endpt);
534                 if (endpt == 0) {
535                         err = ubifs_leb_unmap(c, lnum);
536                         if (err)
537                                 return err;
538                 } else {
539                         int len = ALIGN(endpt, c->min_io_size);
540
541                         if (start) {
542                                 err = ubi_read(c->ubi, lnum, sleb->buf, 0,
543                                                start);
544                                 if (err)
545                                         return err;
546                         }
547                         /* Pad to min_io_size */
548                         if (len > endpt) {
549                                 int pad_len = len - ALIGN(endpt, 8);
550
551                                 if (pad_len > 0) {
552                                         void *buf = sleb->buf + len - pad_len;
553
554                                         ubifs_pad(c, buf, pad_len);
555                                 }
556                         }
557                         err = ubi_leb_change(c->ubi, lnum, sleb->buf, len,
558                                              UBI_UNKNOWN);
559                         if (err)
560                                 return err;
561                 }
562         }
563         return 0;
564 }
565
566 /**
567  * drop_last_node - drop the last node or group of nodes.
568  * @sleb: scanned LEB information
569  * @offs: offset of dropped nodes is returned here
570  * @grouped: non-zero if whole group of nodes have to be dropped
571  *
572  * This is a helper function for 'ubifs_recover_leb()' which drops the last
573  * node of the scanned LEB or the last group of nodes if @grouped is not zero.
574  * This function returns %1 if a node was dropped and %0 otherwise.
575  */
576 static int drop_last_node(struct ubifs_scan_leb *sleb, int *offs, int grouped)
577 {
578         int dropped = 0;
579
580         while (!list_empty(&sleb->nodes)) {
581                 struct ubifs_scan_node *snod;
582                 struct ubifs_ch *ch;
583
584                 snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node,
585                                   list);
586                 ch = snod->node;
587                 if (ch->group_type != UBIFS_IN_NODE_GROUP)
588                         return dropped;
589                 dbg_rcvry("dropping node at %d:%d", sleb->lnum, snod->offs);
590                 *offs = snod->offs;
591                 list_del(&snod->list);
592                 kfree(snod);
593                 sleb->nodes_cnt -= 1;
594                 dropped = 1;
595                 if (!grouped)
596                         break;
597         }
598         return dropped;
599 }
600
601 /**
602  * ubifs_recover_leb - scan and recover a LEB.
603  * @c: UBIFS file-system description object
604  * @lnum: LEB number
605  * @offs: offset
606  * @sbuf: LEB-sized buffer to use
607  * @grouped: nodes may be grouped for recovery
608  *
609  * This function does a scan of a LEB, but caters for errors that might have
610  * been caused by the unclean unmount from which we are attempting to recover.
611  * Returns %0 in case of success, %-EUCLEAN if an unrecoverable corruption is
612  * found, and a negative error code in case of failure.
613  */
614 struct ubifs_scan_leb *ubifs_recover_leb(struct ubifs_info *c, int lnum,
615                                          int offs, void *sbuf, int grouped)
616 {
617         int ret = 0, err, len = c->leb_size - offs, start = offs, min_io_unit;
618         struct ubifs_scan_leb *sleb;
619         void *buf = sbuf + offs;
620
621         dbg_rcvry("%d:%d", lnum, offs);
622
623         sleb = ubifs_start_scan(c, lnum, offs, sbuf);
624         if (IS_ERR(sleb))
625                 return sleb;
626
627         ubifs_assert(len >= 8);
628         while (len >= 8) {
629                 dbg_scan("look at LEB %d:%d (%d bytes left)",
630                          lnum, offs, len);
631
632                 cond_resched();
633
634                 /*
635                  * Scan quietly until there is an error from which we cannot
636                  * recover
637                  */
638                 ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 0);
639                 if (ret == SCANNED_A_NODE) {
640                         /* A valid node, and not a padding node */
641                         struct ubifs_ch *ch = buf;
642                         int node_len;
643
644                         err = ubifs_add_snod(c, sleb, buf, offs);
645                         if (err)
646                                 goto error;
647                         node_len = ALIGN(le32_to_cpu(ch->len), 8);
648                         offs += node_len;
649                         buf += node_len;
650                         len -= node_len;
651                 } else if (ret > 0) {
652                         /* Padding bytes or a valid padding node */
653                         offs += ret;
654                         buf += ret;
655                         len -= ret;
656                 } else if (ret == SCANNED_EMPTY_SPACE ||
657                            ret == SCANNED_GARBAGE     ||
658                            ret == SCANNED_A_BAD_PAD_NODE ||
659                            ret == SCANNED_A_CORRUPT_NODE) {
660                         dbg_rcvry("found corruption - %d", ret);
661                         break;
662                 } else {
663                         dbg_err("unexpected return value %d", ret);
664                         err = -EINVAL;
665                         goto error;
666                 }
667         }
668
669         if (ret == SCANNED_GARBAGE || ret == SCANNED_A_BAD_PAD_NODE) {
670                 if (!is_last_write(c, buf, offs))
671                         goto corrupted_rescan;
672         } else if (ret == SCANNED_A_CORRUPT_NODE) {
673                 if (!no_more_nodes(c, buf, len, lnum, offs))
674                         goto corrupted_rescan;
675         } else if (!is_empty(buf, len)) {
676                 if (!is_last_write(c, buf, offs)) {
677                         int corruption = first_non_ff(buf, len);
678
679                         /*
680                          * See header comment for this file for more
681                          * explanations about the reasons we have this check.
682                          */
683                         ubifs_err("corrupt empty space LEB %d:%d, corruption "
684                                   "starts at %d", lnum, offs, corruption);
685                         /* Make sure we dump interesting non-0xFF data */
686                         offs += corruption;
687                         buf += corruption;
688                         goto corrupted;
689                 }
690         }
691
692         min_io_unit = round_down(offs, c->min_io_size);
693         if (grouped)
694                 /*
695                  * If nodes are grouped, always drop the incomplete group at
696                  * the end.
697                  */
698                 drop_last_node(sleb, &offs, 1);
699
700         /*
701          * While we are in the middle of the same min. I/O unit keep dropping
702          * nodes. So basically, what we want is to make sure that the last min.
703          * I/O unit where we saw the corruption is dropped completely with all
704          * the uncorrupted node which may possibly sit there.
705          *
706          * In other words, let's name the min. I/O unit where the corruption
707          * starts B, and the previous min. I/O unit A. The below code tries to
708          * deal with a situation when half of B contains valid nodes or the end
709          * of a valid node, and the second half of B contains corrupted data or
710          * garbage. This means that UBIFS had been writing to B just before the
711          * power cut happened. I do not know how realistic is this scenario
712          * that half of the min. I/O unit had been written successfully and the
713          * other half not, but this is possible in our 'failure mode emulation'
714          * infrastructure at least.
715          *
716          * So what is the problem, why we need to drop those nodes? Whey can't
717          * we just clean-up the second half of B by putting a padding node
718          * there? We can, and this works fine with one exception which was
719          * reproduced with power cut emulation testing and happens extremely
720          * rarely. The description follows, but it is worth noting that that is
721          * only about the GC head, so we could do this trick only if the bud
722          * belongs to the GC head, but it does not seem to be worth an
723          * additional "if" statement.
724          *
725          * So, imagine the file-system is full, we run GC which is moving valid
726          * nodes from LEB X to LEB Y (obviously, LEB Y is the current GC head
727          * LEB). The @c->gc_lnum is -1, which means that GC will retain LEB X
728          * and will try to continue. Imagine that LEB X is currently the
729          * dirtiest LEB, and the amount of used space in LEB Y is exactly the
730          * same as amount of free space in LEB X.
731          *
732          * And a power cut happens when nodes are moved from LEB X to LEB Y. We
733          * are here trying to recover LEB Y which is the GC head LEB. We find
734          * the min. I/O unit B as described above. Then we clean-up LEB Y by
735          * padding min. I/O unit. And later 'ubifs_rcvry_gc_commit()' function
736          * fails, because it cannot find a dirty LEB which could be GC'd into
737          * LEB Y! Even LEB X does not match because the amount of valid nodes
738          * there does not fit the free space in LEB Y any more! And this is
739          * because of the padding node which we added to LEB Y. The
740          * user-visible effect of this which I once observed and analysed is
741          * that we cannot mount the file-system with -ENOSPC error.
742          *
743          * So obviously, to make sure that situation does not happen we should
744          * free min. I/O unit B in LEB Y completely and the last used min. I/O
745          * unit in LEB Y should be A. This is basically what the below code
746          * tries to do.
747          */
748         while (min_io_unit == round_down(offs, c->min_io_size) &&
749                min_io_unit != offs &&
750                drop_last_node(sleb, &offs, grouped));
751
752         buf = sbuf + offs;
753         len = c->leb_size - offs;
754
755         clean_buf(c, &buf, lnum, &offs, &len);
756         ubifs_end_scan(c, sleb, lnum, offs);
757
758         err = fix_unclean_leb(c, sleb, start);
759         if (err)
760                 goto error;
761
762         return sleb;
763
764 corrupted_rescan:
765         /* Re-scan the corrupted data with verbose messages */
766         dbg_err("corruptio %d", ret);
767         ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
768 corrupted:
769         ubifs_scanned_corruption(c, lnum, offs, buf);
770         err = -EUCLEAN;
771 error:
772         ubifs_err("LEB %d scanning failed", lnum);
773         ubifs_scan_destroy(sleb);
774         return ERR_PTR(err);
775 }
776
777 /**
778  * get_cs_sqnum - get commit start sequence number.
779  * @c: UBIFS file-system description object
780  * @lnum: LEB number of commit start node
781  * @offs: offset of commit start node
782  * @cs_sqnum: commit start sequence number is returned here
783  *
784  * This function returns %0 on success and a negative error code on failure.
785  */
786 static int get_cs_sqnum(struct ubifs_info *c, int lnum, int offs,
787                         unsigned long long *cs_sqnum)
788 {
789         struct ubifs_cs_node *cs_node = NULL;
790         int err, ret;
791
792         dbg_rcvry("at %d:%d", lnum, offs);
793         cs_node = kmalloc(UBIFS_CS_NODE_SZ, GFP_KERNEL);
794         if (!cs_node)
795                 return -ENOMEM;
796         if (c->leb_size - offs < UBIFS_CS_NODE_SZ)
797                 goto out_err;
798         err = ubi_read(c->ubi, lnum, (void *)cs_node, offs, UBIFS_CS_NODE_SZ);
799         if (err && err != -EBADMSG)
800                 goto out_free;
801         ret = ubifs_scan_a_node(c, cs_node, UBIFS_CS_NODE_SZ, lnum, offs, 0);
802         if (ret != SCANNED_A_NODE) {
803                 dbg_err("Not a valid node");
804                 goto out_err;
805         }
806         if (cs_node->ch.node_type != UBIFS_CS_NODE) {
807                 dbg_err("Node a CS node, type is %d", cs_node->ch.node_type);
808                 goto out_err;
809         }
810         if (le64_to_cpu(cs_node->cmt_no) != c->cmt_no) {
811                 dbg_err("CS node cmt_no %llu != current cmt_no %llu",
812                         (unsigned long long)le64_to_cpu(cs_node->cmt_no),
813                         c->cmt_no);
814                 goto out_err;
815         }
816         *cs_sqnum = le64_to_cpu(cs_node->ch.sqnum);
817         dbg_rcvry("commit start sqnum %llu", *cs_sqnum);
818         kfree(cs_node);
819         return 0;
820
821 out_err:
822         err = -EINVAL;
823 out_free:
824         ubifs_err("failed to get CS sqnum");
825         kfree(cs_node);
826         return err;
827 }
828
829 /**
830  * ubifs_recover_log_leb - scan and recover a log LEB.
831  * @c: UBIFS file-system description object
832  * @lnum: LEB number
833  * @offs: offset
834  * @sbuf: LEB-sized buffer to use
835  *
836  * This function does a scan of a LEB, but caters for errors that might have
837  * been caused by unclean reboots from which we are attempting to recover
838  * (assume that only the last log LEB can be corrupted by an unclean reboot).
839  *
840  * This function returns %0 on success and a negative error code on failure.
841  */
842 struct ubifs_scan_leb *ubifs_recover_log_leb(struct ubifs_info *c, int lnum,
843                                              int offs, void *sbuf)
844 {
845         struct ubifs_scan_leb *sleb;
846         int next_lnum;
847
848         dbg_rcvry("LEB %d", lnum);
849         next_lnum = lnum + 1;
850         if (next_lnum >= UBIFS_LOG_LNUM + c->log_lebs)
851                 next_lnum = UBIFS_LOG_LNUM;
852         if (next_lnum != c->ltail_lnum) {
853                 /*
854                  * We can only recover at the end of the log, so check that the
855                  * next log LEB is empty or out of date.
856                  */
857                 sleb = ubifs_scan(c, next_lnum, 0, sbuf, 0);
858                 if (IS_ERR(sleb))
859                         return sleb;
860                 if (sleb->nodes_cnt) {
861                         struct ubifs_scan_node *snod;
862                         unsigned long long cs_sqnum = c->cs_sqnum;
863
864                         snod = list_entry(sleb->nodes.next,
865                                           struct ubifs_scan_node, list);
866                         if (cs_sqnum == 0) {
867                                 int err;
868
869                                 err = get_cs_sqnum(c, lnum, offs, &cs_sqnum);
870                                 if (err) {
871                                         ubifs_scan_destroy(sleb);
872                                         return ERR_PTR(err);
873                                 }
874                         }
875                         if (snod->sqnum > cs_sqnum) {
876                                 ubifs_err("unrecoverable log corruption "
877                                           "in LEB %d", lnum);
878                                 ubifs_scan_destroy(sleb);
879                                 return ERR_PTR(-EUCLEAN);
880                         }
881                 }
882                 ubifs_scan_destroy(sleb);
883         }
884         return ubifs_recover_leb(c, lnum, offs, sbuf, 0);
885 }
886
887 /**
888  * recover_head - recover a head.
889  * @c: UBIFS file-system description object
890  * @lnum: LEB number of head to recover
891  * @offs: offset of head to recover
892  * @sbuf: LEB-sized buffer to use
893  *
894  * This function ensures that there is no data on the flash at a head location.
895  *
896  * This function returns %0 on success and a negative error code on failure.
897  */
898 static int recover_head(const struct ubifs_info *c, int lnum, int offs,
899                         void *sbuf)
900 {
901         int len = c->max_write_size, err;
902
903         if (offs + len > c->leb_size)
904                 len = c->leb_size - offs;
905
906         if (!len)
907                 return 0;
908
909         /* Read at the head location and check it is empty flash */
910         err = ubi_read(c->ubi, lnum, sbuf, offs, len);
911         if (err || !is_empty(sbuf, len)) {
912                 dbg_rcvry("cleaning head at %d:%d", lnum, offs);
913                 if (offs == 0)
914                         return ubifs_leb_unmap(c, lnum);
915                 err = ubi_read(c->ubi, lnum, sbuf, 0, offs);
916                 if (err)
917                         return err;
918                 return ubi_leb_change(c->ubi, lnum, sbuf, offs, UBI_UNKNOWN);
919         }
920
921         return 0;
922 }
923
924 /**
925  * ubifs_recover_inl_heads - recover index and LPT heads.
926  * @c: UBIFS file-system description object
927  * @sbuf: LEB-sized buffer to use
928  *
929  * This function ensures that there is no data on the flash at the index and
930  * LPT head locations.
931  *
932  * This deals with the recovery of a half-completed journal commit. UBIFS is
933  * careful never to overwrite the last version of the index or the LPT. Because
934  * the index and LPT are wandering trees, data from a half-completed commit will
935  * not be referenced anywhere in UBIFS. The data will be either in LEBs that are
936  * assumed to be empty and will be unmapped anyway before use, or in the index
937  * and LPT heads.
938  *
939  * This function returns %0 on success and a negative error code on failure.
940  */
941 int ubifs_recover_inl_heads(const struct ubifs_info *c, void *sbuf)
942 {
943         int err;
944
945         ubifs_assert(!c->ro_mount || c->remounting_rw);
946
947         dbg_rcvry("checking index head at %d:%d", c->ihead_lnum, c->ihead_offs);
948         err = recover_head(c, c->ihead_lnum, c->ihead_offs, sbuf);
949         if (err)
950                 return err;
951
952         dbg_rcvry("checking LPT head at %d:%d", c->nhead_lnum, c->nhead_offs);
953         err = recover_head(c, c->nhead_lnum, c->nhead_offs, sbuf);
954         if (err)
955                 return err;
956
957         return 0;
958 }
959
960 /**
961  *  clean_an_unclean_leb - read and write a LEB to remove corruption.
962  * @c: UBIFS file-system description object
963  * @ucleb: unclean LEB information
964  * @sbuf: LEB-sized buffer to use
965  *
966  * This function reads a LEB up to a point pre-determined by the mount recovery,
967  * checks the nodes, and writes the result back to the flash, thereby cleaning
968  * off any following corruption, or non-fatal ECC errors.
969  *
970  * This function returns %0 on success and a negative error code on failure.
971  */
972 static int clean_an_unclean_leb(const struct ubifs_info *c,
973                                 struct ubifs_unclean_leb *ucleb, void *sbuf)
974 {
975         int err, lnum = ucleb->lnum, offs = 0, len = ucleb->endpt, quiet = 1;
976         void *buf = sbuf;
977
978         dbg_rcvry("LEB %d len %d", lnum, len);
979
980         if (len == 0) {
981                 /* Nothing to read, just unmap it */
982                 err = ubifs_leb_unmap(c, lnum);
983                 if (err)
984                         return err;
985                 return 0;
986         }
987
988         err = ubi_read(c->ubi, lnum, buf, offs, len);
989         if (err && err != -EBADMSG)
990                 return err;
991
992         while (len >= 8) {
993                 int ret;
994
995                 cond_resched();
996
997                 /* Scan quietly until there is an error */
998                 ret = ubifs_scan_a_node(c, buf, len, lnum, offs, quiet);
999
1000                 if (ret == SCANNED_A_NODE) {
1001                         /* A valid node, and not a padding node */
1002                         struct ubifs_ch *ch = buf;
1003                         int node_len;
1004
1005                         node_len = ALIGN(le32_to_cpu(ch->len), 8);
1006                         offs += node_len;
1007                         buf += node_len;
1008                         len -= node_len;
1009                         continue;
1010                 }
1011
1012                 if (ret > 0) {
1013                         /* Padding bytes or a valid padding node */
1014                         offs += ret;
1015                         buf += ret;
1016                         len -= ret;
1017                         continue;
1018                 }
1019
1020                 if (ret == SCANNED_EMPTY_SPACE) {
1021                         ubifs_err("unexpected empty space at %d:%d",
1022                                   lnum, offs);
1023                         return -EUCLEAN;
1024                 }
1025
1026                 if (quiet) {
1027                         /* Redo the last scan but noisily */
1028                         quiet = 0;
1029                         continue;
1030                 }
1031
1032                 ubifs_scanned_corruption(c, lnum, offs, buf);
1033                 return -EUCLEAN;
1034         }
1035
1036         /* Pad to min_io_size */
1037         len = ALIGN(ucleb->endpt, c->min_io_size);
1038         if (len > ucleb->endpt) {
1039                 int pad_len = len - ALIGN(ucleb->endpt, 8);
1040
1041                 if (pad_len > 0) {
1042                         buf = c->sbuf + len - pad_len;
1043                         ubifs_pad(c, buf, pad_len);
1044                 }
1045         }
1046
1047         /* Write back the LEB atomically */
1048         err = ubi_leb_change(c->ubi, lnum, sbuf, len, UBI_UNKNOWN);
1049         if (err)
1050                 return err;
1051
1052         dbg_rcvry("cleaned LEB %d", lnum);
1053
1054         return 0;
1055 }
1056
1057 /**
1058  * ubifs_clean_lebs - clean LEBs recovered during read-only mount.
1059  * @c: UBIFS file-system description object
1060  * @sbuf: LEB-sized buffer to use
1061  *
1062  * This function cleans a LEB identified during recovery that needs to be
1063  * written but was not because UBIFS was mounted read-only. This happens when
1064  * remounting to read-write mode.
1065  *
1066  * This function returns %0 on success and a negative error code on failure.
1067  */
1068 int ubifs_clean_lebs(const struct ubifs_info *c, void *sbuf)
1069 {
1070         dbg_rcvry("recovery");
1071         while (!list_empty(&c->unclean_leb_list)) {
1072                 struct ubifs_unclean_leb *ucleb;
1073                 int err;
1074
1075                 ucleb = list_entry(c->unclean_leb_list.next,
1076                                    struct ubifs_unclean_leb, list);
1077                 err = clean_an_unclean_leb(c, ucleb, sbuf);
1078                 if (err)
1079                         return err;
1080                 list_del(&ucleb->list);
1081                 kfree(ucleb);
1082         }
1083         return 0;
1084 }
1085
1086 /**
1087  * grab_empty_leb - grab an empty LEB to use as GC LEB and run commit.
1088  * @c: UBIFS file-system description object
1089  *
1090  * This is a helper function for 'ubifs_rcvry_gc_commit()' which grabs an empty
1091  * LEB to be used as GC LEB (@c->gc_lnum), and then runs the commit. Returns
1092  * zero in case of success and a negative error code in case of failure.
1093  */
1094 static int grab_empty_leb(struct ubifs_info *c)
1095 {
1096         int lnum, err;
1097
1098         /*
1099          * Note, it is very important to first search for an empty LEB and then
1100          * run the commit, not vice-versa. The reason is that there might be
1101          * only one empty LEB at the moment, the one which has been the
1102          * @c->gc_lnum just before the power cut happened. During the regular
1103          * UBIFS operation (not now) @c->gc_lnum is marked as "taken", so no
1104          * one but GC can grab it. But at this moment this single empty LEB is
1105          * not marked as taken, so if we run commit - what happens? Right, the
1106          * commit will grab it and write the index there. Remember that the
1107          * index always expands as long as there is free space, and it only
1108          * starts consolidating when we run out of space.
1109          *
1110          * IOW, if we run commit now, we might not be able to find a free LEB
1111          * after this.
1112          */
1113         lnum = ubifs_find_free_leb_for_idx(c);
1114         if (lnum < 0) {
1115                 dbg_err("could not find an empty LEB");
1116                 dbg_dump_lprops(c);
1117                 dbg_dump_budg(c, &c->bi);
1118                 return lnum;
1119         }
1120
1121         /* Reset the index flag */
1122         err = ubifs_change_one_lp(c, lnum, LPROPS_NC, LPROPS_NC, 0,
1123                                   LPROPS_INDEX, 0);
1124         if (err)
1125                 return err;
1126
1127         c->gc_lnum = lnum;
1128         dbg_rcvry("found empty LEB %d, run commit", lnum);
1129
1130         return ubifs_run_commit(c);
1131 }
1132
1133 /**
1134  * ubifs_rcvry_gc_commit - recover the GC LEB number and run the commit.
1135  * @c: UBIFS file-system description object
1136  *
1137  * Out-of-place garbage collection requires always one empty LEB with which to
1138  * start garbage collection. The LEB number is recorded in c->gc_lnum and is
1139  * written to the master node on unmounting. In the case of an unclean unmount
1140  * the value of gc_lnum recorded in the master node is out of date and cannot
1141  * be used. Instead, recovery must allocate an empty LEB for this purpose.
1142  * However, there may not be enough empty space, in which case it must be
1143  * possible to GC the dirtiest LEB into the GC head LEB.
1144  *
1145  * This function also runs the commit which causes the TNC updates from
1146  * size-recovery and orphans to be written to the flash. That is important to
1147  * ensure correct replay order for subsequent mounts.
1148  *
1149  * This function returns %0 on success and a negative error code on failure.
1150  */
1151 int ubifs_rcvry_gc_commit(struct ubifs_info *c)
1152 {
1153         struct ubifs_wbuf *wbuf = &c->jheads[GCHD].wbuf;
1154         struct ubifs_lprops lp;
1155         int err;
1156
1157         dbg_rcvry("GC head LEB %d, offs %d", wbuf->lnum, wbuf->offs);
1158
1159         c->gc_lnum = -1;
1160         if (wbuf->lnum == -1 || wbuf->offs == c->leb_size)
1161                 return grab_empty_leb(c);
1162
1163         err = ubifs_find_dirty_leb(c, &lp, wbuf->offs, 2);
1164         if (err) {
1165                 if (err != -ENOSPC)
1166                         return err;
1167
1168                 dbg_rcvry("could not find a dirty LEB");
1169                 return grab_empty_leb(c);
1170         }
1171
1172         ubifs_assert(!(lp.flags & LPROPS_INDEX));
1173         ubifs_assert(lp.free + lp.dirty >= wbuf->offs);
1174
1175         /*
1176          * We run the commit before garbage collection otherwise subsequent
1177          * mounts will see the GC and orphan deletion in a different order.
1178          */
1179         dbg_rcvry("committing");
1180         err = ubifs_run_commit(c);
1181         if (err)
1182                 return err;
1183
1184         dbg_rcvry("GC'ing LEB %d", lp.lnum);
1185         mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
1186         err = ubifs_garbage_collect_leb(c, &lp);
1187         if (err >= 0) {
1188                 int err2 = ubifs_wbuf_sync_nolock(wbuf);
1189
1190                 if (err2)
1191                         err = err2;
1192         }
1193         mutex_unlock(&wbuf->io_mutex);
1194         if (err < 0) {
1195                 dbg_err("GC failed, error %d", err);
1196                 if (err == -EAGAIN)
1197                         err = -EINVAL;
1198                 return err;
1199         }
1200
1201         ubifs_assert(err == LEB_RETAINED);
1202         if (err != LEB_RETAINED)
1203                 return -EINVAL;
1204
1205         err = ubifs_leb_unmap(c, c->gc_lnum);
1206         if (err)
1207                 return err;
1208
1209         dbg_rcvry("allocated LEB %d for GC", lp.lnum);
1210         return 0;
1211 }
1212
1213 /**
1214  * struct size_entry - inode size information for recovery.
1215  * @rb: link in the RB-tree of sizes
1216  * @inum: inode number
1217  * @i_size: size on inode
1218  * @d_size: maximum size based on data nodes
1219  * @exists: indicates whether the inode exists
1220  * @inode: inode if pinned in memory awaiting rw mode to fix it
1221  */
1222 struct size_entry {
1223         struct rb_node rb;
1224         ino_t inum;
1225         loff_t i_size;
1226         loff_t d_size;
1227         int exists;
1228         struct inode *inode;
1229 };
1230
1231 /**
1232  * add_ino - add an entry to the size tree.
1233  * @c: UBIFS file-system description object
1234  * @inum: inode number
1235  * @i_size: size on inode
1236  * @d_size: maximum size based on data nodes
1237  * @exists: indicates whether the inode exists
1238  */
1239 static int add_ino(struct ubifs_info *c, ino_t inum, loff_t i_size,
1240                    loff_t d_size, int exists)
1241 {
1242         struct rb_node **p = &c->size_tree.rb_node, *parent = NULL;
1243         struct size_entry *e;
1244
1245         while (*p) {
1246                 parent = *p;
1247                 e = rb_entry(parent, struct size_entry, rb);
1248                 if (inum < e->inum)
1249                         p = &(*p)->rb_left;
1250                 else
1251                         p = &(*p)->rb_right;
1252         }
1253
1254         e = kzalloc(sizeof(struct size_entry), GFP_KERNEL);
1255         if (!e)
1256                 return -ENOMEM;
1257
1258         e->inum = inum;
1259         e->i_size = i_size;
1260         e->d_size = d_size;
1261         e->exists = exists;
1262
1263         rb_link_node(&e->rb, parent, p);
1264         rb_insert_color(&e->rb, &c->size_tree);
1265
1266         return 0;
1267 }
1268
1269 /**
1270  * find_ino - find an entry on the size tree.
1271  * @c: UBIFS file-system description object
1272  * @inum: inode number
1273  */
1274 static struct size_entry *find_ino(struct ubifs_info *c, ino_t inum)
1275 {
1276         struct rb_node *p = c->size_tree.rb_node;
1277         struct size_entry *e;
1278
1279         while (p) {
1280                 e = rb_entry(p, struct size_entry, rb);
1281                 if (inum < e->inum)
1282                         p = p->rb_left;
1283                 else if (inum > e->inum)
1284                         p = p->rb_right;
1285                 else
1286                         return e;
1287         }
1288         return NULL;
1289 }
1290
1291 /**
1292  * remove_ino - remove an entry from the size tree.
1293  * @c: UBIFS file-system description object
1294  * @inum: inode number
1295  */
1296 static void remove_ino(struct ubifs_info *c, ino_t inum)
1297 {
1298         struct size_entry *e = find_ino(c, inum);
1299
1300         if (!e)
1301                 return;
1302         rb_erase(&e->rb, &c->size_tree);
1303         kfree(e);
1304 }
1305
1306 /**
1307  * ubifs_destroy_size_tree - free resources related to the size tree.
1308  * @c: UBIFS file-system description object
1309  */
1310 void ubifs_destroy_size_tree(struct ubifs_info *c)
1311 {
1312         struct rb_node *this = c->size_tree.rb_node;
1313         struct size_entry *e;
1314
1315         while (this) {
1316                 if (this->rb_left) {
1317                         this = this->rb_left;
1318                         continue;
1319                 } else if (this->rb_right) {
1320                         this = this->rb_right;
1321                         continue;
1322                 }
1323                 e = rb_entry(this, struct size_entry, rb);
1324                 if (e->inode)
1325                         iput(e->inode);
1326                 this = rb_parent(this);
1327                 if (this) {
1328                         if (this->rb_left == &e->rb)
1329                                 this->rb_left = NULL;
1330                         else
1331                                 this->rb_right = NULL;
1332                 }
1333                 kfree(e);
1334         }
1335         c->size_tree = RB_ROOT;
1336 }
1337
1338 /**
1339  * ubifs_recover_size_accum - accumulate inode sizes for recovery.
1340  * @c: UBIFS file-system description object
1341  * @key: node key
1342  * @deletion: node is for a deletion
1343  * @new_size: inode size
1344  *
1345  * This function has two purposes:
1346  *     1) to ensure there are no data nodes that fall outside the inode size
1347  *     2) to ensure there are no data nodes for inodes that do not exist
1348  * To accomplish those purposes, a rb-tree is constructed containing an entry
1349  * for each inode number in the journal that has not been deleted, and recording
1350  * the size from the inode node, the maximum size of any data node (also altered
1351  * by truncations) and a flag indicating a inode number for which no inode node
1352  * was present in the journal.
1353  *
1354  * Note that there is still the possibility that there are data nodes that have
1355  * been committed that are beyond the inode size, however the only way to find
1356  * them would be to scan the entire index. Alternatively, some provision could
1357  * be made to record the size of inodes at the start of commit, which would seem
1358  * very cumbersome for a scenario that is quite unlikely and the only negative
1359  * consequence of which is wasted space.
1360  *
1361  * This functions returns %0 on success and a negative error code on failure.
1362  */
1363 int ubifs_recover_size_accum(struct ubifs_info *c, union ubifs_key *key,
1364                              int deletion, loff_t new_size)
1365 {
1366         ino_t inum = key_inum(c, key);
1367         struct size_entry *e;
1368         int err;
1369
1370         switch (key_type(c, key)) {
1371         case UBIFS_INO_KEY:
1372                 if (deletion)
1373                         remove_ino(c, inum);
1374                 else {
1375                         e = find_ino(c, inum);
1376                         if (e) {
1377                                 e->i_size = new_size;
1378                                 e->exists = 1;
1379                         } else {
1380                                 err = add_ino(c, inum, new_size, 0, 1);
1381                                 if (err)
1382                                         return err;
1383                         }
1384                 }
1385                 break;
1386         case UBIFS_DATA_KEY:
1387                 e = find_ino(c, inum);
1388                 if (e) {
1389                         if (new_size > e->d_size)
1390                                 e->d_size = new_size;
1391                 } else {
1392                         err = add_ino(c, inum, 0, new_size, 0);
1393                         if (err)
1394                                 return err;
1395                 }
1396                 break;
1397         case UBIFS_TRUN_KEY:
1398                 e = find_ino(c, inum);
1399                 if (e)
1400                         e->d_size = new_size;
1401                 break;
1402         }
1403         return 0;
1404 }
1405
1406 /**
1407  * fix_size_in_place - fix inode size in place on flash.
1408  * @c: UBIFS file-system description object
1409  * @e: inode size information for recovery
1410  */
1411 static int fix_size_in_place(struct ubifs_info *c, struct size_entry *e)
1412 {
1413         struct ubifs_ino_node *ino = c->sbuf;
1414         unsigned char *p;
1415         union ubifs_key key;
1416         int err, lnum, offs, len;
1417         loff_t i_size;
1418         uint32_t crc;
1419
1420         /* Locate the inode node LEB number and offset */
1421         ino_key_init(c, &key, e->inum);
1422         err = ubifs_tnc_locate(c, &key, ino, &lnum, &offs);
1423         if (err)
1424                 goto out;
1425         /*
1426          * If the size recorded on the inode node is greater than the size that
1427          * was calculated from nodes in the journal then don't change the inode.
1428          */
1429         i_size = le64_to_cpu(ino->size);
1430         if (i_size >= e->d_size)
1431                 return 0;
1432         /* Read the LEB */
1433         err = ubi_read(c->ubi, lnum, c->sbuf, 0, c->leb_size);
1434         if (err)
1435                 goto out;
1436         /* Change the size field and recalculate the CRC */
1437         ino = c->sbuf + offs;
1438         ino->size = cpu_to_le64(e->d_size);
1439         len = le32_to_cpu(ino->ch.len);
1440         crc = crc32(UBIFS_CRC32_INIT, (void *)ino + 8, len - 8);
1441         ino->ch.crc = cpu_to_le32(crc);
1442         /* Work out where data in the LEB ends and free space begins */
1443         p = c->sbuf;
1444         len = c->leb_size - 1;
1445         while (p[len] == 0xff)
1446                 len -= 1;
1447         len = ALIGN(len + 1, c->min_io_size);
1448         /* Atomically write the fixed LEB back again */
1449         err = ubi_leb_change(c->ubi, lnum, c->sbuf, len, UBI_UNKNOWN);
1450         if (err)
1451                 goto out;
1452         dbg_rcvry("inode %lu at %d:%d size %lld -> %lld",
1453                   (unsigned long)e->inum, lnum, offs, i_size, e->d_size);
1454         return 0;
1455
1456 out:
1457         ubifs_warn("inode %lu failed to fix size %lld -> %lld error %d",
1458                    (unsigned long)e->inum, e->i_size, e->d_size, err);
1459         return err;
1460 }
1461
1462 /**
1463  * ubifs_recover_size - recover inode size.
1464  * @c: UBIFS file-system description object
1465  *
1466  * This function attempts to fix inode size discrepancies identified by the
1467  * 'ubifs_recover_size_accum()' function.
1468  *
1469  * This functions returns %0 on success and a negative error code on failure.
1470  */
1471 int ubifs_recover_size(struct ubifs_info *c)
1472 {
1473         struct rb_node *this = rb_first(&c->size_tree);
1474
1475         while (this) {
1476                 struct size_entry *e;
1477                 int err;
1478
1479                 e = rb_entry(this, struct size_entry, rb);
1480                 if (!e->exists) {
1481                         union ubifs_key key;
1482
1483                         ino_key_init(c, &key, e->inum);
1484                         err = ubifs_tnc_lookup(c, &key, c->sbuf);
1485                         if (err && err != -ENOENT)
1486                                 return err;
1487                         if (err == -ENOENT) {
1488                                 /* Remove data nodes that have no inode */
1489                                 dbg_rcvry("removing ino %lu",
1490                                           (unsigned long)e->inum);
1491                                 err = ubifs_tnc_remove_ino(c, e->inum);
1492                                 if (err)
1493                                         return err;
1494                         } else {
1495                                 struct ubifs_ino_node *ino = c->sbuf;
1496
1497                                 e->exists = 1;
1498                                 e->i_size = le64_to_cpu(ino->size);
1499                         }
1500                 }
1501
1502                 if (e->exists && e->i_size < e->d_size) {
1503                         if (c->ro_mount) {
1504                                 /* Fix the inode size and pin it in memory */
1505                                 struct inode *inode;
1506                                 struct ubifs_inode *ui;
1507
1508                                 ubifs_assert(!e->inode);
1509
1510                                 inode = ubifs_iget(c->vfs_sb, e->inum);
1511                                 if (IS_ERR(inode))
1512                                         return PTR_ERR(inode);
1513
1514                                 ui = ubifs_inode(inode);
1515                                 if (inode->i_size < e->d_size) {
1516                                         dbg_rcvry("ino %lu size %lld -> %lld",
1517                                                   (unsigned long)e->inum,
1518                                                   inode->i_size, e->d_size);
1519                                         inode->i_size = e->d_size;
1520                                         ui->ui_size = e->d_size;
1521                                         ui->synced_i_size = e->d_size;
1522                                         e->inode = inode;
1523                                         this = rb_next(this);
1524                                         continue;
1525                                 }
1526                                 iput(inode);
1527                         } else {
1528                                 /* Fix the size in place */
1529                                 err = fix_size_in_place(c, e);
1530                                 if (err)
1531                                         return err;
1532                                 if (e->inode)
1533                                         iput(e->inode);
1534                         }
1535                 }
1536
1537                 this = rb_next(this);
1538                 rb_erase(&e->rb, &c->size_tree);
1539                 kfree(e);
1540         }
1541
1542         return 0;
1543 }