xref: /openbmc/linux/fs/ubifs/replay.c (revision 6a98bc4614de8fac8c6d520a6b20b194e23c9936)
1 /*
2  * This file is part of UBIFS.
3  *
4  * Copyright (C) 2006-2008 Nokia Corporation.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 as published by
8  * the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51
17  * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18  *
19  * Authors: Adrian Hunter
20  *          Artem Bityutskiy (Битюцкий Артём)
21  */
22 
23 /*
24  * This file contains journal replay code. It runs when the file-system is being
25  * mounted and requires no locking.
26  *
27  * The larger is the journal, the longer it takes to scan it, so the longer it
28  * takes to mount UBIFS. This is why the journal has limited size which may be
29  * changed depending on the system requirements. But a larger journal gives
30  * faster I/O speed because it writes the index less frequently. So this is a
31  * trade-off. Also, the journal is indexed by the in-memory index (TNC), so the
32  * larger is the journal, the more memory its index may consume.
33  */
34 
35 #include "ubifs.h"
36 #include <linux/list_sort.h>
37 
38 /**
39  * struct replay_entry - replay list entry.
40  * @lnum: logical eraseblock number of the node
41  * @offs: node offset
42  * @len: node length
43  * @deletion: non-zero if this entry corresponds to a node deletion
44  * @sqnum: node sequence number
45  * @list: links the replay list
46  * @key: node key
47  * @nm: directory entry name
48  * @old_size: truncation old size
49  * @new_size: truncation new size
50  *
51  * The replay process first scans all buds and builds the replay list, then
52  * sorts the replay list in nodes sequence number order, and then inserts all
53  * the replay entries to the TNC.
54  */
55 struct replay_entry {
56 	int lnum;
57 	int offs;
58 	int len;
59 	u8 hash[UBIFS_HASH_ARR_SZ];
60 	unsigned int deletion:1;
61 	unsigned long long sqnum;
62 	struct list_head list;
63 	union ubifs_key key;
64 	union {
65 		struct fscrypt_name nm;
66 		struct {
67 			loff_t old_size;
68 			loff_t new_size;
69 		};
70 	};
71 };
72 
73 /**
74  * struct bud_entry - entry in the list of buds to replay.
75  * @list: next bud in the list
76  * @bud: bud description object
77  * @sqnum: reference node sequence number
78  * @free: free bytes in the bud
79  * @dirty: dirty bytes in the bud
80  */
81 struct bud_entry {
82 	struct list_head list;
83 	struct ubifs_bud *bud;
84 	unsigned long long sqnum;
85 	int free;
86 	int dirty;
87 };
88 
89 /**
90  * set_bud_lprops - set free and dirty space used by a bud.
91  * @c: UBIFS file-system description object
92  * @b: bud entry which describes the bud
93  *
94  * This function makes sure the LEB properties of bud @b are set correctly
95  * after the replay. Returns zero in case of success and a negative error code
96  * in case of failure.
97  */
98 static int set_bud_lprops(struct ubifs_info *c, struct bud_entry *b)
99 {
100 	const struct ubifs_lprops *lp;
101 	int err = 0, dirty;
102 
103 	ubifs_get_lprops(c);
104 
105 	lp = ubifs_lpt_lookup_dirty(c, b->bud->lnum);
106 	if (IS_ERR(lp)) {
107 		err = PTR_ERR(lp);
108 		goto out;
109 	}
110 
111 	dirty = lp->dirty;
112 	if (b->bud->start == 0 && (lp->free != c->leb_size || lp->dirty != 0)) {
113 		/*
114 		 * The LEB was added to the journal with a starting offset of
115 		 * zero which means the LEB must have been empty. The LEB
116 		 * property values should be @lp->free == @c->leb_size and
117 		 * @lp->dirty == 0, but that is not the case. The reason is that
118 		 * the LEB had been garbage collected before it became the bud,
119 		 * and there was not commit inbetween. The garbage collector
120 		 * resets the free and dirty space without recording it
121 		 * anywhere except lprops, so if there was no commit then
122 		 * lprops does not have that information.
123 		 *
124 		 * We do not need to adjust free space because the scan has told
125 		 * us the exact value which is recorded in the replay entry as
126 		 * @b->free.
127 		 *
128 		 * However we do need to subtract from the dirty space the
129 		 * amount of space that the garbage collector reclaimed, which
130 		 * is the whole LEB minus the amount of space that was free.
131 		 */
132 		dbg_mnt("bud LEB %d was GC'd (%d free, %d dirty)", b->bud->lnum,
133 			lp->free, lp->dirty);
134 		dbg_gc("bud LEB %d was GC'd (%d free, %d dirty)", b->bud->lnum,
135 			lp->free, lp->dirty);
136 		dirty -= c->leb_size - lp->free;
137 		/*
138 		 * If the replay order was perfect the dirty space would now be
139 		 * zero. The order is not perfect because the journal heads
140 		 * race with each other. This is not a problem but is does mean
141 		 * that the dirty space may temporarily exceed c->leb_size
142 		 * during the replay.
143 		 */
144 		if (dirty != 0)
145 			dbg_mnt("LEB %d lp: %d free %d dirty replay: %d free %d dirty",
146 				b->bud->lnum, lp->free, lp->dirty, b->free,
147 				b->dirty);
148 	}
149 	lp = ubifs_change_lp(c, lp, b->free, dirty + b->dirty,
150 			     lp->flags | LPROPS_TAKEN, 0);
151 	if (IS_ERR(lp)) {
152 		err = PTR_ERR(lp);
153 		goto out;
154 	}
155 
156 	/* Make sure the journal head points to the latest bud */
157 	err = ubifs_wbuf_seek_nolock(&c->jheads[b->bud->jhead].wbuf,
158 				     b->bud->lnum, c->leb_size - b->free);
159 
160 out:
161 	ubifs_release_lprops(c);
162 	return err;
163 }
164 
165 /**
166  * set_buds_lprops - set free and dirty space for all replayed buds.
167  * @c: UBIFS file-system description object
168  *
169  * This function sets LEB properties for all replayed buds. Returns zero in
170  * case of success and a negative error code in case of failure.
171  */
172 static int set_buds_lprops(struct ubifs_info *c)
173 {
174 	struct bud_entry *b;
175 	int err;
176 
177 	list_for_each_entry(b, &c->replay_buds, list) {
178 		err = set_bud_lprops(c, b);
179 		if (err)
180 			return err;
181 	}
182 
183 	return 0;
184 }
185 
186 /**
187  * trun_remove_range - apply a replay entry for a truncation to the TNC.
188  * @c: UBIFS file-system description object
189  * @r: replay entry of truncation
190  */
191 static int trun_remove_range(struct ubifs_info *c, struct replay_entry *r)
192 {
193 	unsigned min_blk, max_blk;
194 	union ubifs_key min_key, max_key;
195 	ino_t ino;
196 
197 	min_blk = r->new_size / UBIFS_BLOCK_SIZE;
198 	if (r->new_size & (UBIFS_BLOCK_SIZE - 1))
199 		min_blk += 1;
200 
201 	max_blk = r->old_size / UBIFS_BLOCK_SIZE;
202 	if ((r->old_size & (UBIFS_BLOCK_SIZE - 1)) == 0)
203 		max_blk -= 1;
204 
205 	ino = key_inum(c, &r->key);
206 
207 	data_key_init(c, &min_key, ino, min_blk);
208 	data_key_init(c, &max_key, ino, max_blk);
209 
210 	return ubifs_tnc_remove_range(c, &min_key, &max_key);
211 }
212 
213 /**
214  * apply_replay_entry - apply a replay entry to the TNC.
215  * @c: UBIFS file-system description object
216  * @r: replay entry to apply
217  *
218  * Apply a replay entry to the TNC.
219  */
220 static int apply_replay_entry(struct ubifs_info *c, struct replay_entry *r)
221 {
222 	int err;
223 
224 	dbg_mntk(&r->key, "LEB %d:%d len %d deletion %d sqnum %llu key ",
225 		 r->lnum, r->offs, r->len, r->deletion, r->sqnum);
226 
227 	if (is_hash_key(c, &r->key)) {
228 		if (r->deletion)
229 			err = ubifs_tnc_remove_nm(c, &r->key, &r->nm);
230 		else
231 			err = ubifs_tnc_add_nm(c, &r->key, r->lnum, r->offs,
232 					       r->len, r->hash, &r->nm);
233 	} else {
234 		if (r->deletion)
235 			switch (key_type(c, &r->key)) {
236 			case UBIFS_INO_KEY:
237 			{
238 				ino_t inum = key_inum(c, &r->key);
239 
240 				err = ubifs_tnc_remove_ino(c, inum);
241 				break;
242 			}
243 			case UBIFS_TRUN_KEY:
244 				err = trun_remove_range(c, r);
245 				break;
246 			default:
247 				err = ubifs_tnc_remove(c, &r->key);
248 				break;
249 			}
250 		else
251 			err = ubifs_tnc_add(c, &r->key, r->lnum, r->offs,
252 					    r->len, r->hash);
253 		if (err)
254 			return err;
255 
256 		if (c->need_recovery)
257 			err = ubifs_recover_size_accum(c, &r->key, r->deletion,
258 						       r->new_size);
259 	}
260 
261 	return err;
262 }
263 
264 /**
265  * replay_entries_cmp - compare 2 replay entries.
266  * @priv: UBIFS file-system description object
267  * @a: first replay entry
268  * @b: second replay entry
269  *
270  * This is a comparios function for 'list_sort()' which compares 2 replay
271  * entries @a and @b by comparing their sequence numer.  Returns %1 if @a has
272  * greater sequence number and %-1 otherwise.
273  */
274 static int replay_entries_cmp(void *priv, struct list_head *a,
275 			      struct list_head *b)
276 {
277 	struct ubifs_info *c = priv;
278 	struct replay_entry *ra, *rb;
279 
280 	cond_resched();
281 	if (a == b)
282 		return 0;
283 
284 	ra = list_entry(a, struct replay_entry, list);
285 	rb = list_entry(b, struct replay_entry, list);
286 	ubifs_assert(c, ra->sqnum != rb->sqnum);
287 	if (ra->sqnum > rb->sqnum)
288 		return 1;
289 	return -1;
290 }
291 
292 /**
293  * apply_replay_list - apply the replay list to the TNC.
294  * @c: UBIFS file-system description object
295  *
296  * Apply all entries in the replay list to the TNC. Returns zero in case of
297  * success and a negative error code in case of failure.
298  */
299 static int apply_replay_list(struct ubifs_info *c)
300 {
301 	struct replay_entry *r;
302 	int err;
303 
304 	list_sort(c, &c->replay_list, &replay_entries_cmp);
305 
306 	list_for_each_entry(r, &c->replay_list, list) {
307 		cond_resched();
308 
309 		err = apply_replay_entry(c, r);
310 		if (err)
311 			return err;
312 	}
313 
314 	return 0;
315 }
316 
317 /**
318  * destroy_replay_list - destroy the replay.
319  * @c: UBIFS file-system description object
320  *
321  * Destroy the replay list.
322  */
323 static void destroy_replay_list(struct ubifs_info *c)
324 {
325 	struct replay_entry *r, *tmp;
326 
327 	list_for_each_entry_safe(r, tmp, &c->replay_list, list) {
328 		if (is_hash_key(c, &r->key))
329 			kfree(fname_name(&r->nm));
330 		list_del(&r->list);
331 		kfree(r);
332 	}
333 }
334 
335 /**
336  * insert_node - insert a node to the replay list
337  * @c: UBIFS file-system description object
338  * @lnum: node logical eraseblock number
339  * @offs: node offset
340  * @len: node length
341  * @key: node key
342  * @sqnum: sequence number
343  * @deletion: non-zero if this is a deletion
344  * @used: number of bytes in use in a LEB
345  * @old_size: truncation old size
346  * @new_size: truncation new size
347  *
348  * This function inserts a scanned non-direntry node to the replay list. The
349  * replay list contains @struct replay_entry elements, and we sort this list in
350  * sequence number order before applying it. The replay list is applied at the
351  * very end of the replay process. Since the list is sorted in sequence number
352  * order, the older modifications are applied first. This function returns zero
353  * in case of success and a negative error code in case of failure.
354  */
355 static int insert_node(struct ubifs_info *c, int lnum, int offs, int len,
356 		       const u8 *hash, union ubifs_key *key,
357 		       unsigned long long sqnum, int deletion, int *used,
358 		       loff_t old_size, loff_t new_size)
359 {
360 	struct replay_entry *r;
361 
362 	dbg_mntk(key, "add LEB %d:%d, key ", lnum, offs);
363 
364 	if (key_inum(c, key) >= c->highest_inum)
365 		c->highest_inum = key_inum(c, key);
366 
367 	r = kzalloc(sizeof(struct replay_entry), GFP_KERNEL);
368 	if (!r)
369 		return -ENOMEM;
370 
371 	if (!deletion)
372 		*used += ALIGN(len, 8);
373 	r->lnum = lnum;
374 	r->offs = offs;
375 	r->len = len;
376 	ubifs_copy_hash(c, hash, r->hash);
377 	r->deletion = !!deletion;
378 	r->sqnum = sqnum;
379 	key_copy(c, key, &r->key);
380 	r->old_size = old_size;
381 	r->new_size = new_size;
382 
383 	list_add_tail(&r->list, &c->replay_list);
384 	return 0;
385 }
386 
387 /**
388  * insert_dent - insert a directory entry node into the replay list.
389  * @c: UBIFS file-system description object
390  * @lnum: node logical eraseblock number
391  * @offs: node offset
392  * @len: node length
393  * @key: node key
394  * @name: directory entry name
395  * @nlen: directory entry name length
396  * @sqnum: sequence number
397  * @deletion: non-zero if this is a deletion
398  * @used: number of bytes in use in a LEB
399  *
400  * This function inserts a scanned directory entry node or an extended
401  * attribute entry to the replay list. Returns zero in case of success and a
402  * negative error code in case of failure.
403  */
404 static int insert_dent(struct ubifs_info *c, int lnum, int offs, int len,
405 		       const u8 *hash, union ubifs_key *key,
406 		       const char *name, int nlen, unsigned long long sqnum,
407 		       int deletion, int *used)
408 {
409 	struct replay_entry *r;
410 	char *nbuf;
411 
412 	dbg_mntk(key, "add LEB %d:%d, key ", lnum, offs);
413 	if (key_inum(c, key) >= c->highest_inum)
414 		c->highest_inum = key_inum(c, key);
415 
416 	r = kzalloc(sizeof(struct replay_entry), GFP_KERNEL);
417 	if (!r)
418 		return -ENOMEM;
419 
420 	nbuf = kmalloc(nlen + 1, GFP_KERNEL);
421 	if (!nbuf) {
422 		kfree(r);
423 		return -ENOMEM;
424 	}
425 
426 	if (!deletion)
427 		*used += ALIGN(len, 8);
428 	r->lnum = lnum;
429 	r->offs = offs;
430 	r->len = len;
431 	ubifs_copy_hash(c, hash, r->hash);
432 	r->deletion = !!deletion;
433 	r->sqnum = sqnum;
434 	key_copy(c, key, &r->key);
435 	fname_len(&r->nm) = nlen;
436 	memcpy(nbuf, name, nlen);
437 	nbuf[nlen] = '\0';
438 	fname_name(&r->nm) = nbuf;
439 
440 	list_add_tail(&r->list, &c->replay_list);
441 	return 0;
442 }
443 
444 /**
445  * ubifs_validate_entry - validate directory or extended attribute entry node.
446  * @c: UBIFS file-system description object
447  * @dent: the node to validate
448  *
449  * This function validates directory or extended attribute entry node @dent.
450  * Returns zero if the node is all right and a %-EINVAL if not.
451  */
452 int ubifs_validate_entry(struct ubifs_info *c,
453 			 const struct ubifs_dent_node *dent)
454 {
455 	int key_type = key_type_flash(c, dent->key);
456 	int nlen = le16_to_cpu(dent->nlen);
457 
458 	if (le32_to_cpu(dent->ch.len) != nlen + UBIFS_DENT_NODE_SZ + 1 ||
459 	    dent->type >= UBIFS_ITYPES_CNT ||
460 	    nlen > UBIFS_MAX_NLEN || dent->name[nlen] != 0 ||
461 	    (key_type == UBIFS_XENT_KEY && strnlen(dent->name, nlen) != nlen) ||
462 	    le64_to_cpu(dent->inum) > MAX_INUM) {
463 		ubifs_err(c, "bad %s node", key_type == UBIFS_DENT_KEY ?
464 			  "directory entry" : "extended attribute entry");
465 		return -EINVAL;
466 	}
467 
468 	if (key_type != UBIFS_DENT_KEY && key_type != UBIFS_XENT_KEY) {
469 		ubifs_err(c, "bad key type %d", key_type);
470 		return -EINVAL;
471 	}
472 
473 	return 0;
474 }
475 
476 /**
477  * is_last_bud - check if the bud is the last in the journal head.
478  * @c: UBIFS file-system description object
479  * @bud: bud description object
480  *
481  * This function checks if bud @bud is the last bud in its journal head. This
482  * information is then used by 'replay_bud()' to decide whether the bud can
483  * have corruptions or not. Indeed, only last buds can be corrupted by power
484  * cuts. Returns %1 if this is the last bud, and %0 if not.
485  */
486 static int is_last_bud(struct ubifs_info *c, struct ubifs_bud *bud)
487 {
488 	struct ubifs_jhead *jh = &c->jheads[bud->jhead];
489 	struct ubifs_bud *next;
490 	uint32_t data;
491 	int err;
492 
493 	if (list_is_last(&bud->list, &jh->buds_list))
494 		return 1;
495 
496 	/*
497 	 * The following is a quirk to make sure we work correctly with UBIFS
498 	 * images used with older UBIFS.
499 	 *
500 	 * Normally, the last bud will be the last in the journal head's list
501 	 * of bud. However, there is one exception if the UBIFS image belongs
502 	 * to older UBIFS. This is fairly unlikely: one would need to use old
503 	 * UBIFS, then have a power cut exactly at the right point, and then
504 	 * try to mount this image with new UBIFS.
505 	 *
506 	 * The exception is: it is possible to have 2 buds A and B, A goes
507 	 * before B, and B is the last, bud B is contains no data, and bud A is
508 	 * corrupted at the end. The reason is that in older versions when the
509 	 * journal code switched the next bud (from A to B), it first added a
510 	 * log reference node for the new bud (B), and only after this it
511 	 * synchronized the write-buffer of current bud (A). But later this was
512 	 * changed and UBIFS started to always synchronize the write-buffer of
513 	 * the bud (A) before writing the log reference for the new bud (B).
514 	 *
515 	 * But because older UBIFS always synchronized A's write-buffer before
516 	 * writing to B, we can recognize this exceptional situation but
517 	 * checking the contents of bud B - if it is empty, then A can be
518 	 * treated as the last and we can recover it.
519 	 *
520 	 * TODO: remove this piece of code in a couple of years (today it is
521 	 * 16.05.2011).
522 	 */
523 	next = list_entry(bud->list.next, struct ubifs_bud, list);
524 	if (!list_is_last(&next->list, &jh->buds_list))
525 		return 0;
526 
527 	err = ubifs_leb_read(c, next->lnum, (char *)&data, next->start, 4, 1);
528 	if (err)
529 		return 0;
530 
531 	return data == 0xFFFFFFFF;
532 }
533 
534 /**
535  * replay_bud - replay a bud logical eraseblock.
536  * @c: UBIFS file-system description object
537  * @b: bud entry which describes the bud
538  *
539  * This function replays bud @bud, recovers it if needed, and adds all nodes
540  * from this bud to the replay list. Returns zero in case of success and a
541  * negative error code in case of failure.
542  */
543 static int replay_bud(struct ubifs_info *c, struct bud_entry *b)
544 {
545 	int is_last = is_last_bud(c, b->bud);
546 	int err = 0, used = 0, lnum = b->bud->lnum, offs = b->bud->start;
547 	struct ubifs_scan_leb *sleb;
548 	struct ubifs_scan_node *snod;
549 
550 	dbg_mnt("replay bud LEB %d, head %d, offs %d, is_last %d",
551 		lnum, b->bud->jhead, offs, is_last);
552 
553 	if (c->need_recovery && is_last)
554 		/*
555 		 * Recover only last LEBs in the journal heads, because power
556 		 * cuts may cause corruptions only in these LEBs, because only
557 		 * these LEBs could possibly be written to at the power cut
558 		 * time.
559 		 */
560 		sleb = ubifs_recover_leb(c, lnum, offs, c->sbuf, b->bud->jhead);
561 	else
562 		sleb = ubifs_scan(c, lnum, offs, c->sbuf, 0);
563 	if (IS_ERR(sleb))
564 		return PTR_ERR(sleb);
565 
566 	/*
567 	 * The bud does not have to start from offset zero - the beginning of
568 	 * the 'lnum' LEB may contain previously committed data. One of the
569 	 * things we have to do in replay is to correctly update lprops with
570 	 * newer information about this LEB.
571 	 *
572 	 * At this point lprops thinks that this LEB has 'c->leb_size - offs'
573 	 * bytes of free space because it only contain information about
574 	 * committed data.
575 	 *
576 	 * But we know that real amount of free space is 'c->leb_size -
577 	 * sleb->endpt', and the space in the 'lnum' LEB between 'offs' and
578 	 * 'sleb->endpt' is used by bud data. We have to correctly calculate
579 	 * how much of these data are dirty and update lprops with this
580 	 * information.
581 	 *
582 	 * The dirt in that LEB region is comprised of padding nodes, deletion
583 	 * nodes, truncation nodes and nodes which are obsoleted by subsequent
584 	 * nodes in this LEB. So instead of calculating clean space, we
585 	 * calculate used space ('used' variable).
586 	 */
587 
588 	list_for_each_entry(snod, &sleb->nodes, list) {
589 		u8 hash[UBIFS_HASH_ARR_SZ];
590 		int deletion = 0;
591 
592 		cond_resched();
593 
594 		if (snod->sqnum >= SQNUM_WATERMARK) {
595 			ubifs_err(c, "file system's life ended");
596 			goto out_dump;
597 		}
598 
599 		ubifs_node_calc_hash(c, snod->node, hash);
600 
601 		if (snod->sqnum > c->max_sqnum)
602 			c->max_sqnum = snod->sqnum;
603 
604 		switch (snod->type) {
605 		case UBIFS_INO_NODE:
606 		{
607 			struct ubifs_ino_node *ino = snod->node;
608 			loff_t new_size = le64_to_cpu(ino->size);
609 
610 			if (le32_to_cpu(ino->nlink) == 0)
611 				deletion = 1;
612 			err = insert_node(c, lnum, snod->offs, snod->len, hash,
613 					  &snod->key, snod->sqnum, deletion,
614 					  &used, 0, new_size);
615 			break;
616 		}
617 		case UBIFS_DATA_NODE:
618 		{
619 			struct ubifs_data_node *dn = snod->node;
620 			loff_t new_size = le32_to_cpu(dn->size) +
621 					  key_block(c, &snod->key) *
622 					  UBIFS_BLOCK_SIZE;
623 
624 			err = insert_node(c, lnum, snod->offs, snod->len, hash,
625 					  &snod->key, snod->sqnum, deletion,
626 					  &used, 0, new_size);
627 			break;
628 		}
629 		case UBIFS_DENT_NODE:
630 		case UBIFS_XENT_NODE:
631 		{
632 			struct ubifs_dent_node *dent = snod->node;
633 
634 			err = ubifs_validate_entry(c, dent);
635 			if (err)
636 				goto out_dump;
637 
638 			err = insert_dent(c, lnum, snod->offs, snod->len, hash,
639 					  &snod->key, dent->name,
640 					  le16_to_cpu(dent->nlen), snod->sqnum,
641 					  !le64_to_cpu(dent->inum), &used);
642 			break;
643 		}
644 		case UBIFS_TRUN_NODE:
645 		{
646 			struct ubifs_trun_node *trun = snod->node;
647 			loff_t old_size = le64_to_cpu(trun->old_size);
648 			loff_t new_size = le64_to_cpu(trun->new_size);
649 			union ubifs_key key;
650 
651 			/* Validate truncation node */
652 			if (old_size < 0 || old_size > c->max_inode_sz ||
653 			    new_size < 0 || new_size > c->max_inode_sz ||
654 			    old_size <= new_size) {
655 				ubifs_err(c, "bad truncation node");
656 				goto out_dump;
657 			}
658 
659 			/*
660 			 * Create a fake truncation key just to use the same
661 			 * functions which expect nodes to have keys.
662 			 */
663 			trun_key_init(c, &key, le32_to_cpu(trun->inum));
664 			err = insert_node(c, lnum, snod->offs, snod->len, hash,
665 					  &key, snod->sqnum, 1, &used,
666 					  old_size, new_size);
667 			break;
668 		}
669 		case UBIFS_AUTH_NODE:
670 			break;
671 		default:
672 			ubifs_err(c, "unexpected node type %d in bud LEB %d:%d",
673 				  snod->type, lnum, snod->offs);
674 			err = -EINVAL;
675 			goto out_dump;
676 		}
677 		if (err)
678 			goto out;
679 	}
680 
681 	ubifs_assert(c, ubifs_search_bud(c, lnum));
682 	ubifs_assert(c, sleb->endpt - offs >= used);
683 	ubifs_assert(c, sleb->endpt % c->min_io_size == 0);
684 
685 	b->dirty = sleb->endpt - offs - used;
686 	b->free = c->leb_size - sleb->endpt;
687 	dbg_mnt("bud LEB %d replied: dirty %d, free %d",
688 		lnum, b->dirty, b->free);
689 
690 out:
691 	ubifs_scan_destroy(sleb);
692 	return err;
693 
694 out_dump:
695 	ubifs_err(c, "bad node is at LEB %d:%d", lnum, snod->offs);
696 	ubifs_dump_node(c, snod->node);
697 	ubifs_scan_destroy(sleb);
698 	return -EINVAL;
699 }
700 
701 /**
702  * replay_buds - replay all buds.
703  * @c: UBIFS file-system description object
704  *
705  * This function returns zero in case of success and a negative error code in
706  * case of failure.
707  */
708 static int replay_buds(struct ubifs_info *c)
709 {
710 	struct bud_entry *b;
711 	int err;
712 	unsigned long long prev_sqnum = 0;
713 
714 	list_for_each_entry(b, &c->replay_buds, list) {
715 		err = replay_bud(c, b);
716 		if (err)
717 			return err;
718 
719 		ubifs_assert(c, b->sqnum > prev_sqnum);
720 		prev_sqnum = b->sqnum;
721 	}
722 
723 	return 0;
724 }
725 
726 /**
727  * destroy_bud_list - destroy the list of buds to replay.
728  * @c: UBIFS file-system description object
729  */
730 static void destroy_bud_list(struct ubifs_info *c)
731 {
732 	struct bud_entry *b;
733 
734 	while (!list_empty(&c->replay_buds)) {
735 		b = list_entry(c->replay_buds.next, struct bud_entry, list);
736 		list_del(&b->list);
737 		kfree(b);
738 	}
739 }
740 
741 /**
742  * add_replay_bud - add a bud to the list of buds to replay.
743  * @c: UBIFS file-system description object
744  * @lnum: bud logical eraseblock number to replay
745  * @offs: bud start offset
746  * @jhead: journal head to which this bud belongs
747  * @sqnum: reference node sequence number
748  *
749  * This function returns zero in case of success and a negative error code in
750  * case of failure.
751  */
752 static int add_replay_bud(struct ubifs_info *c, int lnum, int offs, int jhead,
753 			  unsigned long long sqnum)
754 {
755 	struct ubifs_bud *bud;
756 	struct bud_entry *b;
757 
758 	dbg_mnt("add replay bud LEB %d:%d, head %d", lnum, offs, jhead);
759 
760 	bud = kmalloc(sizeof(struct ubifs_bud), GFP_KERNEL);
761 	if (!bud)
762 		return -ENOMEM;
763 
764 	b = kmalloc(sizeof(struct bud_entry), GFP_KERNEL);
765 	if (!b) {
766 		kfree(bud);
767 		return -ENOMEM;
768 	}
769 
770 	bud->lnum = lnum;
771 	bud->start = offs;
772 	bud->jhead = jhead;
773 	ubifs_add_bud(c, bud);
774 
775 	b->bud = bud;
776 	b->sqnum = sqnum;
777 	list_add_tail(&b->list, &c->replay_buds);
778 
779 	return 0;
780 }
781 
782 /**
783  * validate_ref - validate a reference node.
784  * @c: UBIFS file-system description object
785  * @ref: the reference node to validate
786  * @ref_lnum: LEB number of the reference node
787  * @ref_offs: reference node offset
788  *
789  * This function returns %1 if a bud reference already exists for the LEB. %0 is
790  * returned if the reference node is new, otherwise %-EINVAL is returned if
791  * validation failed.
792  */
793 static int validate_ref(struct ubifs_info *c, const struct ubifs_ref_node *ref)
794 {
795 	struct ubifs_bud *bud;
796 	int lnum = le32_to_cpu(ref->lnum);
797 	unsigned int offs = le32_to_cpu(ref->offs);
798 	unsigned int jhead = le32_to_cpu(ref->jhead);
799 
800 	/*
801 	 * ref->offs may point to the end of LEB when the journal head points
802 	 * to the end of LEB and we write reference node for it during commit.
803 	 * So this is why we require 'offs > c->leb_size'.
804 	 */
805 	if (jhead >= c->jhead_cnt || lnum >= c->leb_cnt ||
806 	    lnum < c->main_first || offs > c->leb_size ||
807 	    offs & (c->min_io_size - 1))
808 		return -EINVAL;
809 
810 	/* Make sure we have not already looked at this bud */
811 	bud = ubifs_search_bud(c, lnum);
812 	if (bud) {
813 		if (bud->jhead == jhead && bud->start <= offs)
814 			return 1;
815 		ubifs_err(c, "bud at LEB %d:%d was already referred", lnum, offs);
816 		return -EINVAL;
817 	}
818 
819 	return 0;
820 }
821 
822 /**
823  * replay_log_leb - replay a log logical eraseblock.
824  * @c: UBIFS file-system description object
825  * @lnum: log logical eraseblock to replay
826  * @offs: offset to start replaying from
827  * @sbuf: scan buffer
828  *
829  * This function replays a log LEB and returns zero in case of success, %1 if
830  * this is the last LEB in the log, and a negative error code in case of
831  * failure.
832  */
833 static int replay_log_leb(struct ubifs_info *c, int lnum, int offs, void *sbuf)
834 {
835 	int err;
836 	struct ubifs_scan_leb *sleb;
837 	struct ubifs_scan_node *snod;
838 	const struct ubifs_cs_node *node;
839 
840 	dbg_mnt("replay log LEB %d:%d", lnum, offs);
841 	sleb = ubifs_scan(c, lnum, offs, sbuf, c->need_recovery);
842 	if (IS_ERR(sleb)) {
843 		if (PTR_ERR(sleb) != -EUCLEAN || !c->need_recovery)
844 			return PTR_ERR(sleb);
845 		/*
846 		 * Note, the below function will recover this log LEB only if
847 		 * it is the last, because unclean reboots can possibly corrupt
848 		 * only the tail of the log.
849 		 */
850 		sleb = ubifs_recover_log_leb(c, lnum, offs, sbuf);
851 		if (IS_ERR(sleb))
852 			return PTR_ERR(sleb);
853 	}
854 
855 	if (sleb->nodes_cnt == 0) {
856 		err = 1;
857 		goto out;
858 	}
859 
860 	node = sleb->buf;
861 	snod = list_entry(sleb->nodes.next, struct ubifs_scan_node, list);
862 	if (c->cs_sqnum == 0) {
863 		/*
864 		 * This is the first log LEB we are looking at, make sure that
865 		 * the first node is a commit start node. Also record its
866 		 * sequence number so that UBIFS can determine where the log
867 		 * ends, because all nodes which were have higher sequence
868 		 * numbers.
869 		 */
870 		if (snod->type != UBIFS_CS_NODE) {
871 			ubifs_err(c, "first log node at LEB %d:%d is not CS node",
872 				  lnum, offs);
873 			goto out_dump;
874 		}
875 		if (le64_to_cpu(node->cmt_no) != c->cmt_no) {
876 			ubifs_err(c, "first CS node at LEB %d:%d has wrong commit number %llu expected %llu",
877 				  lnum, offs,
878 				  (unsigned long long)le64_to_cpu(node->cmt_no),
879 				  c->cmt_no);
880 			goto out_dump;
881 		}
882 
883 		c->cs_sqnum = le64_to_cpu(node->ch.sqnum);
884 		dbg_mnt("commit start sqnum %llu", c->cs_sqnum);
885 	}
886 
887 	if (snod->sqnum < c->cs_sqnum) {
888 		/*
889 		 * This means that we reached end of log and now
890 		 * look to the older log data, which was already
891 		 * committed but the eraseblock was not erased (UBIFS
892 		 * only un-maps it). So this basically means we have to
893 		 * exit with "end of log" code.
894 		 */
895 		err = 1;
896 		goto out;
897 	}
898 
899 	/* Make sure the first node sits at offset zero of the LEB */
900 	if (snod->offs != 0) {
901 		ubifs_err(c, "first node is not at zero offset");
902 		goto out_dump;
903 	}
904 
905 	list_for_each_entry(snod, &sleb->nodes, list) {
906 		cond_resched();
907 
908 		if (snod->sqnum >= SQNUM_WATERMARK) {
909 			ubifs_err(c, "file system's life ended");
910 			goto out_dump;
911 		}
912 
913 		if (snod->sqnum < c->cs_sqnum) {
914 			ubifs_err(c, "bad sqnum %llu, commit sqnum %llu",
915 				  snod->sqnum, c->cs_sqnum);
916 			goto out_dump;
917 		}
918 
919 		if (snod->sqnum > c->max_sqnum)
920 			c->max_sqnum = snod->sqnum;
921 
922 		switch (snod->type) {
923 		case UBIFS_REF_NODE: {
924 			const struct ubifs_ref_node *ref = snod->node;
925 
926 			err = validate_ref(c, ref);
927 			if (err == 1)
928 				break; /* Already have this bud */
929 			if (err)
930 				goto out_dump;
931 
932 			err = add_replay_bud(c, le32_to_cpu(ref->lnum),
933 					     le32_to_cpu(ref->offs),
934 					     le32_to_cpu(ref->jhead),
935 					     snod->sqnum);
936 			if (err)
937 				goto out;
938 
939 			break;
940 		}
941 		case UBIFS_CS_NODE:
942 			/* Make sure it sits at the beginning of LEB */
943 			if (snod->offs != 0) {
944 				ubifs_err(c, "unexpected node in log");
945 				goto out_dump;
946 			}
947 			break;
948 		default:
949 			ubifs_err(c, "unexpected node in log");
950 			goto out_dump;
951 		}
952 	}
953 
954 	if (sleb->endpt || c->lhead_offs >= c->leb_size) {
955 		c->lhead_lnum = lnum;
956 		c->lhead_offs = sleb->endpt;
957 	}
958 
959 	err = !sleb->endpt;
960 out:
961 	ubifs_scan_destroy(sleb);
962 	return err;
963 
964 out_dump:
965 	ubifs_err(c, "log error detected while replaying the log at LEB %d:%d",
966 		  lnum, offs + snod->offs);
967 	ubifs_dump_node(c, snod->node);
968 	ubifs_scan_destroy(sleb);
969 	return -EINVAL;
970 }
971 
972 /**
973  * take_ihead - update the status of the index head in lprops to 'taken'.
974  * @c: UBIFS file-system description object
975  *
976  * This function returns the amount of free space in the index head LEB or a
977  * negative error code.
978  */
979 static int take_ihead(struct ubifs_info *c)
980 {
981 	const struct ubifs_lprops *lp;
982 	int err, free;
983 
984 	ubifs_get_lprops(c);
985 
986 	lp = ubifs_lpt_lookup_dirty(c, c->ihead_lnum);
987 	if (IS_ERR(lp)) {
988 		err = PTR_ERR(lp);
989 		goto out;
990 	}
991 
992 	free = lp->free;
993 
994 	lp = ubifs_change_lp(c, lp, LPROPS_NC, LPROPS_NC,
995 			     lp->flags | LPROPS_TAKEN, 0);
996 	if (IS_ERR(lp)) {
997 		err = PTR_ERR(lp);
998 		goto out;
999 	}
1000 
1001 	err = free;
1002 out:
1003 	ubifs_release_lprops(c);
1004 	return err;
1005 }
1006 
1007 /**
1008  * ubifs_replay_journal - replay journal.
1009  * @c: UBIFS file-system description object
1010  *
1011  * This function scans the journal, replays and cleans it up. It makes sure all
1012  * memory data structures related to uncommitted journal are built (dirty TNC
1013  * tree, tree of buds, modified lprops, etc).
1014  */
1015 int ubifs_replay_journal(struct ubifs_info *c)
1016 {
1017 	int err, lnum, free;
1018 
1019 	BUILD_BUG_ON(UBIFS_TRUN_KEY > 5);
1020 
1021 	/* Update the status of the index head in lprops to 'taken' */
1022 	free = take_ihead(c);
1023 	if (free < 0)
1024 		return free; /* Error code */
1025 
1026 	if (c->ihead_offs != c->leb_size - free) {
1027 		ubifs_err(c, "bad index head LEB %d:%d", c->ihead_lnum,
1028 			  c->ihead_offs);
1029 		return -EINVAL;
1030 	}
1031 
1032 	dbg_mnt("start replaying the journal");
1033 	c->replaying = 1;
1034 	lnum = c->ltail_lnum = c->lhead_lnum;
1035 
1036 	do {
1037 		err = replay_log_leb(c, lnum, 0, c->sbuf);
1038 		if (err == 1) {
1039 			if (lnum != c->lhead_lnum)
1040 				/* We hit the end of the log */
1041 				break;
1042 
1043 			/*
1044 			 * The head of the log must always start with the
1045 			 * "commit start" node on a properly formatted UBIFS.
1046 			 * But we found no nodes at all, which means that
1047 			 * something went wrong and we cannot proceed mounting
1048 			 * the file-system.
1049 			 */
1050 			ubifs_err(c, "no UBIFS nodes found at the log head LEB %d:%d, possibly corrupted",
1051 				  lnum, 0);
1052 			err = -EINVAL;
1053 		}
1054 		if (err)
1055 			goto out;
1056 		lnum = ubifs_next_log_lnum(c, lnum);
1057 	} while (lnum != c->ltail_lnum);
1058 
1059 	err = replay_buds(c);
1060 	if (err)
1061 		goto out;
1062 
1063 	err = apply_replay_list(c);
1064 	if (err)
1065 		goto out;
1066 
1067 	err = set_buds_lprops(c);
1068 	if (err)
1069 		goto out;
1070 
1071 	/*
1072 	 * UBIFS budgeting calculations use @c->bi.uncommitted_idx variable
1073 	 * to roughly estimate index growth. Things like @c->bi.min_idx_lebs
1074 	 * depend on it. This means we have to initialize it to make sure
1075 	 * budgeting works properly.
1076 	 */
1077 	c->bi.uncommitted_idx = atomic_long_read(&c->dirty_zn_cnt);
1078 	c->bi.uncommitted_idx *= c->max_idx_node_sz;
1079 
1080 	ubifs_assert(c, c->bud_bytes <= c->max_bud_bytes || c->need_recovery);
1081 	dbg_mnt("finished, log head LEB %d:%d, max_sqnum %llu, highest_inum %lu",
1082 		c->lhead_lnum, c->lhead_offs, c->max_sqnum,
1083 		(unsigned long)c->highest_inum);
1084 out:
1085 	destroy_replay_list(c);
1086 	destroy_bud_list(c);
1087 	c->replaying = 0;
1088 	return err;
1089 }
1090