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