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