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