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