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