xref: /openbmc/linux/fs/ubifs/replay.c (revision 3213486f)
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 	hash_desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
580 
581 	ubifs_shash_copy_state(c, log_hash, hash_desc);
582 	return crypto_shash_final(hash_desc, hash);
583 }
584 
585 static int authenticate_sleb_hmac(struct ubifs_info *c, u8 *hash, u8 *hmac)
586 {
587 	SHASH_DESC_ON_STACK(hmac_desc, c->hmac_tfm);
588 
589 	hmac_desc->tfm = c->hmac_tfm;
590 	hmac_desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
591 
592 	return crypto_shash_digest(hmac_desc, hash, c->hash_len, hmac);
593 }
594 
595 /**
596  * authenticate_sleb - authenticate one scan LEB
597  * @c: UBIFS file-system description object
598  * @sleb: the scan LEB to authenticate
599  * @log_hash:
600  * @is_last: if true, this is is the last LEB
601  *
602  * This function iterates over the buds of a single LEB authenticating all buds
603  * with the authentication nodes on this LEB. Authentication nodes are written
604  * after some buds and contain a HMAC covering the authentication node itself
605  * and the buds between the last authentication node and the current
606  * authentication node. It can happen that the last buds cannot be authenticated
607  * because a powercut happened when some nodes were written but not the
608  * corresponding authentication node. This function returns the number of nodes
609  * that could be authenticated or a negative error code.
610  */
611 static int authenticate_sleb(struct ubifs_info *c, struct ubifs_scan_leb *sleb,
612 			     struct shash_desc *log_hash, int is_last)
613 {
614 	int n_not_auth = 0;
615 	struct ubifs_scan_node *snod;
616 	int n_nodes = 0;
617 	int err;
618 	u8 *hash, *hmac;
619 
620 	if (!ubifs_authenticated(c))
621 		return sleb->nodes_cnt;
622 
623 	hash = kmalloc(crypto_shash_descsize(c->hash_tfm), GFP_NOFS);
624 	hmac = kmalloc(c->hmac_desc_len, GFP_NOFS);
625 	if (!hash || !hmac) {
626 		err = -ENOMEM;
627 		goto out;
628 	}
629 
630 	list_for_each_entry(snod, &sleb->nodes, list) {
631 
632 		n_nodes++;
633 
634 		if (snod->type == UBIFS_AUTH_NODE) {
635 			struct ubifs_auth_node *auth = snod->node;
636 
637 			err = authenticate_sleb_hash(c, log_hash, hash);
638 			if (err)
639 				goto out;
640 
641 			err = authenticate_sleb_hmac(c, hash, hmac);
642 			if (err)
643 				goto out;
644 
645 			err = ubifs_check_hmac(c, auth->hmac, hmac);
646 			if (err) {
647 				err = -EPERM;
648 				goto out;
649 			}
650 			n_not_auth = 0;
651 		} else {
652 			err = crypto_shash_update(log_hash, snod->node,
653 						  snod->len);
654 			if (err)
655 				goto out;
656 			n_not_auth++;
657 		}
658 	}
659 
660 	/*
661 	 * A powercut can happen when some nodes were written, but not yet
662 	 * the corresponding authentication node. This may only happen on
663 	 * the last bud though.
664 	 */
665 	if (n_not_auth) {
666 		if (is_last) {
667 			dbg_mnt("%d unauthenticated nodes found on LEB %d, Ignoring them",
668 				n_not_auth, sleb->lnum);
669 			err = 0;
670 		} else {
671 			dbg_mnt("%d unauthenticated nodes found on non-last LEB %d",
672 				n_not_auth, sleb->lnum);
673 			err = -EPERM;
674 		}
675 	} else {
676 		err = 0;
677 	}
678 out:
679 	kfree(hash);
680 	kfree(hmac);
681 
682 	return err ? err : n_nodes - n_not_auth;
683 }
684 
685 /**
686  * replay_bud - replay a bud logical eraseblock.
687  * @c: UBIFS file-system description object
688  * @b: bud entry which describes the bud
689  *
690  * This function replays bud @bud, recovers it if needed, and adds all nodes
691  * from this bud to the replay list. Returns zero in case of success and a
692  * negative error code in case of failure.
693  */
694 static int replay_bud(struct ubifs_info *c, struct bud_entry *b)
695 {
696 	int is_last = is_last_bud(c, b->bud);
697 	int err = 0, used = 0, lnum = b->bud->lnum, offs = b->bud->start;
698 	int n_nodes, n = 0;
699 	struct ubifs_scan_leb *sleb;
700 	struct ubifs_scan_node *snod;
701 
702 	dbg_mnt("replay bud LEB %d, head %d, offs %d, is_last %d",
703 		lnum, b->bud->jhead, offs, is_last);
704 
705 	if (c->need_recovery && is_last)
706 		/*
707 		 * Recover only last LEBs in the journal heads, because power
708 		 * cuts may cause corruptions only in these LEBs, because only
709 		 * these LEBs could possibly be written to at the power cut
710 		 * time.
711 		 */
712 		sleb = ubifs_recover_leb(c, lnum, offs, c->sbuf, b->bud->jhead);
713 	else
714 		sleb = ubifs_scan(c, lnum, offs, c->sbuf, 0);
715 	if (IS_ERR(sleb))
716 		return PTR_ERR(sleb);
717 
718 	n_nodes = authenticate_sleb(c, sleb, b->bud->log_hash, is_last);
719 	if (n_nodes < 0) {
720 		err = n_nodes;
721 		goto out;
722 	}
723 
724 	ubifs_shash_copy_state(c, b->bud->log_hash,
725 			       c->jheads[b->bud->jhead].log_hash);
726 
727 	/*
728 	 * The bud does not have to start from offset zero - the beginning of
729 	 * the 'lnum' LEB may contain previously committed data. One of the
730 	 * things we have to do in replay is to correctly update lprops with
731 	 * newer information about this LEB.
732 	 *
733 	 * At this point lprops thinks that this LEB has 'c->leb_size - offs'
734 	 * bytes of free space because it only contain information about
735 	 * committed data.
736 	 *
737 	 * But we know that real amount of free space is 'c->leb_size -
738 	 * sleb->endpt', and the space in the 'lnum' LEB between 'offs' and
739 	 * 'sleb->endpt' is used by bud data. We have to correctly calculate
740 	 * how much of these data are dirty and update lprops with this
741 	 * information.
742 	 *
743 	 * The dirt in that LEB region is comprised of padding nodes, deletion
744 	 * nodes, truncation nodes and nodes which are obsoleted by subsequent
745 	 * nodes in this LEB. So instead of calculating clean space, we
746 	 * calculate used space ('used' variable).
747 	 */
748 
749 	list_for_each_entry(snod, &sleb->nodes, list) {
750 		u8 hash[UBIFS_HASH_ARR_SZ];
751 		int deletion = 0;
752 
753 		cond_resched();
754 
755 		if (snod->sqnum >= SQNUM_WATERMARK) {
756 			ubifs_err(c, "file system's life ended");
757 			goto out_dump;
758 		}
759 
760 		ubifs_node_calc_hash(c, snod->node, hash);
761 
762 		if (snod->sqnum > c->max_sqnum)
763 			c->max_sqnum = snod->sqnum;
764 
765 		switch (snod->type) {
766 		case UBIFS_INO_NODE:
767 		{
768 			struct ubifs_ino_node *ino = snod->node;
769 			loff_t new_size = le64_to_cpu(ino->size);
770 
771 			if (le32_to_cpu(ino->nlink) == 0)
772 				deletion = 1;
773 			err = insert_node(c, lnum, snod->offs, snod->len, hash,
774 					  &snod->key, snod->sqnum, deletion,
775 					  &used, 0, new_size);
776 			break;
777 		}
778 		case UBIFS_DATA_NODE:
779 		{
780 			struct ubifs_data_node *dn = snod->node;
781 			loff_t new_size = le32_to_cpu(dn->size) +
782 					  key_block(c, &snod->key) *
783 					  UBIFS_BLOCK_SIZE;
784 
785 			err = insert_node(c, lnum, snod->offs, snod->len, hash,
786 					  &snod->key, snod->sqnum, deletion,
787 					  &used, 0, new_size);
788 			break;
789 		}
790 		case UBIFS_DENT_NODE:
791 		case UBIFS_XENT_NODE:
792 		{
793 			struct ubifs_dent_node *dent = snod->node;
794 
795 			err = ubifs_validate_entry(c, dent);
796 			if (err)
797 				goto out_dump;
798 
799 			err = insert_dent(c, lnum, snod->offs, snod->len, hash,
800 					  &snod->key, dent->name,
801 					  le16_to_cpu(dent->nlen), snod->sqnum,
802 					  !le64_to_cpu(dent->inum), &used);
803 			break;
804 		}
805 		case UBIFS_TRUN_NODE:
806 		{
807 			struct ubifs_trun_node *trun = snod->node;
808 			loff_t old_size = le64_to_cpu(trun->old_size);
809 			loff_t new_size = le64_to_cpu(trun->new_size);
810 			union ubifs_key key;
811 
812 			/* Validate truncation node */
813 			if (old_size < 0 || old_size > c->max_inode_sz ||
814 			    new_size < 0 || new_size > c->max_inode_sz ||
815 			    old_size <= new_size) {
816 				ubifs_err(c, "bad truncation node");
817 				goto out_dump;
818 			}
819 
820 			/*
821 			 * Create a fake truncation key just to use the same
822 			 * functions which expect nodes to have keys.
823 			 */
824 			trun_key_init(c, &key, le32_to_cpu(trun->inum));
825 			err = insert_node(c, lnum, snod->offs, snod->len, hash,
826 					  &key, snod->sqnum, 1, &used,
827 					  old_size, new_size);
828 			break;
829 		}
830 		case UBIFS_AUTH_NODE:
831 			break;
832 		default:
833 			ubifs_err(c, "unexpected node type %d in bud LEB %d:%d",
834 				  snod->type, lnum, snod->offs);
835 			err = -EINVAL;
836 			goto out_dump;
837 		}
838 		if (err)
839 			goto out;
840 
841 		n++;
842 		if (n == n_nodes)
843 			break;
844 	}
845 
846 	ubifs_assert(c, ubifs_search_bud(c, lnum));
847 	ubifs_assert(c, sleb->endpt - offs >= used);
848 	ubifs_assert(c, sleb->endpt % c->min_io_size == 0);
849 
850 	b->dirty = sleb->endpt - offs - used;
851 	b->free = c->leb_size - sleb->endpt;
852 	dbg_mnt("bud LEB %d replied: dirty %d, free %d",
853 		lnum, b->dirty, b->free);
854 
855 out:
856 	ubifs_scan_destroy(sleb);
857 	return err;
858 
859 out_dump:
860 	ubifs_err(c, "bad node is at LEB %d:%d", lnum, snod->offs);
861 	ubifs_dump_node(c, snod->node);
862 	ubifs_scan_destroy(sleb);
863 	return -EINVAL;
864 }
865 
866 /**
867  * replay_buds - replay all buds.
868  * @c: UBIFS file-system description object
869  *
870  * This function returns zero in case of success and a negative error code in
871  * case of failure.
872  */
873 static int replay_buds(struct ubifs_info *c)
874 {
875 	struct bud_entry *b;
876 	int err;
877 	unsigned long long prev_sqnum = 0;
878 
879 	list_for_each_entry(b, &c->replay_buds, list) {
880 		err = replay_bud(c, b);
881 		if (err)
882 			return err;
883 
884 		ubifs_assert(c, b->sqnum > prev_sqnum);
885 		prev_sqnum = b->sqnum;
886 	}
887 
888 	return 0;
889 }
890 
891 /**
892  * destroy_bud_list - destroy the list of buds to replay.
893  * @c: UBIFS file-system description object
894  */
895 static void destroy_bud_list(struct ubifs_info *c)
896 {
897 	struct bud_entry *b;
898 
899 	while (!list_empty(&c->replay_buds)) {
900 		b = list_entry(c->replay_buds.next, struct bud_entry, list);
901 		list_del(&b->list);
902 		kfree(b);
903 	}
904 }
905 
906 /**
907  * add_replay_bud - add a bud to the list of buds to replay.
908  * @c: UBIFS file-system description object
909  * @lnum: bud logical eraseblock number to replay
910  * @offs: bud start offset
911  * @jhead: journal head to which this bud belongs
912  * @sqnum: reference node sequence number
913  *
914  * This function returns zero in case of success and a negative error code in
915  * case of failure.
916  */
917 static int add_replay_bud(struct ubifs_info *c, int lnum, int offs, int jhead,
918 			  unsigned long long sqnum)
919 {
920 	struct ubifs_bud *bud;
921 	struct bud_entry *b;
922 	int err;
923 
924 	dbg_mnt("add replay bud LEB %d:%d, head %d", lnum, offs, jhead);
925 
926 	bud = kmalloc(sizeof(struct ubifs_bud), GFP_KERNEL);
927 	if (!bud)
928 		return -ENOMEM;
929 
930 	b = kmalloc(sizeof(struct bud_entry), GFP_KERNEL);
931 	if (!b) {
932 		err = -ENOMEM;
933 		goto out;
934 	}
935 
936 	bud->lnum = lnum;
937 	bud->start = offs;
938 	bud->jhead = jhead;
939 	bud->log_hash = ubifs_hash_get_desc(c);
940 	if (IS_ERR(bud->log_hash)) {
941 		err = PTR_ERR(bud->log_hash);
942 		goto out;
943 	}
944 
945 	ubifs_shash_copy_state(c, c->log_hash, bud->log_hash);
946 
947 	ubifs_add_bud(c, bud);
948 
949 	b->bud = bud;
950 	b->sqnum = sqnum;
951 	list_add_tail(&b->list, &c->replay_buds);
952 
953 	return 0;
954 out:
955 	kfree(bud);
956 	kfree(b);
957 
958 	return err;
959 }
960 
961 /**
962  * validate_ref - validate a reference node.
963  * @c: UBIFS file-system description object
964  * @ref: the reference node to validate
965  * @ref_lnum: LEB number of the reference node
966  * @ref_offs: reference node offset
967  *
968  * This function returns %1 if a bud reference already exists for the LEB. %0 is
969  * returned if the reference node is new, otherwise %-EINVAL is returned if
970  * validation failed.
971  */
972 static int validate_ref(struct ubifs_info *c, const struct ubifs_ref_node *ref)
973 {
974 	struct ubifs_bud *bud;
975 	int lnum = le32_to_cpu(ref->lnum);
976 	unsigned int offs = le32_to_cpu(ref->offs);
977 	unsigned int jhead = le32_to_cpu(ref->jhead);
978 
979 	/*
980 	 * ref->offs may point to the end of LEB when the journal head points
981 	 * to the end of LEB and we write reference node for it during commit.
982 	 * So this is why we require 'offs > c->leb_size'.
983 	 */
984 	if (jhead >= c->jhead_cnt || lnum >= c->leb_cnt ||
985 	    lnum < c->main_first || offs > c->leb_size ||
986 	    offs & (c->min_io_size - 1))
987 		return -EINVAL;
988 
989 	/* Make sure we have not already looked at this bud */
990 	bud = ubifs_search_bud(c, lnum);
991 	if (bud) {
992 		if (bud->jhead == jhead && bud->start <= offs)
993 			return 1;
994 		ubifs_err(c, "bud at LEB %d:%d was already referred", lnum, offs);
995 		return -EINVAL;
996 	}
997 
998 	return 0;
999 }
1000 
1001 /**
1002  * replay_log_leb - replay a log logical eraseblock.
1003  * @c: UBIFS file-system description object
1004  * @lnum: log logical eraseblock to replay
1005  * @offs: offset to start replaying from
1006  * @sbuf: scan buffer
1007  *
1008  * This function replays a log LEB and returns zero in case of success, %1 if
1009  * this is the last LEB in the log, and a negative error code in case of
1010  * failure.
1011  */
1012 static int replay_log_leb(struct ubifs_info *c, int lnum, int offs, void *sbuf)
1013 {
1014 	int err;
1015 	struct ubifs_scan_leb *sleb;
1016 	struct ubifs_scan_node *snod;
1017 	const struct ubifs_cs_node *node;
1018 
1019 	dbg_mnt("replay log LEB %d:%d", lnum, offs);
1020 	sleb = ubifs_scan(c, lnum, offs, sbuf, c->need_recovery);
1021 	if (IS_ERR(sleb)) {
1022 		if (PTR_ERR(sleb) != -EUCLEAN || !c->need_recovery)
1023 			return PTR_ERR(sleb);
1024 		/*
1025 		 * Note, the below function will recover this log LEB only if
1026 		 * it is the last, because unclean reboots can possibly corrupt
1027 		 * only the tail of the log.
1028 		 */
1029 		sleb = ubifs_recover_log_leb(c, lnum, offs, sbuf);
1030 		if (IS_ERR(sleb))
1031 			return PTR_ERR(sleb);
1032 	}
1033 
1034 	if (sleb->nodes_cnt == 0) {
1035 		err = 1;
1036 		goto out;
1037 	}
1038 
1039 	node = sleb->buf;
1040 	snod = list_entry(sleb->nodes.next, struct ubifs_scan_node, list);
1041 	if (c->cs_sqnum == 0) {
1042 		/*
1043 		 * This is the first log LEB we are looking at, make sure that
1044 		 * the first node is a commit start node. Also record its
1045 		 * sequence number so that UBIFS can determine where the log
1046 		 * ends, because all nodes which were have higher sequence
1047 		 * numbers.
1048 		 */
1049 		if (snod->type != UBIFS_CS_NODE) {
1050 			ubifs_err(c, "first log node at LEB %d:%d is not CS node",
1051 				  lnum, offs);
1052 			goto out_dump;
1053 		}
1054 		if (le64_to_cpu(node->cmt_no) != c->cmt_no) {
1055 			ubifs_err(c, "first CS node at LEB %d:%d has wrong commit number %llu expected %llu",
1056 				  lnum, offs,
1057 				  (unsigned long long)le64_to_cpu(node->cmt_no),
1058 				  c->cmt_no);
1059 			goto out_dump;
1060 		}
1061 
1062 		c->cs_sqnum = le64_to_cpu(node->ch.sqnum);
1063 		dbg_mnt("commit start sqnum %llu", c->cs_sqnum);
1064 
1065 		err = ubifs_shash_init(c, c->log_hash);
1066 		if (err)
1067 			goto out;
1068 
1069 		err = ubifs_shash_update(c, c->log_hash, node, UBIFS_CS_NODE_SZ);
1070 		if (err < 0)
1071 			goto out;
1072 	}
1073 
1074 	if (snod->sqnum < c->cs_sqnum) {
1075 		/*
1076 		 * This means that we reached end of log and now
1077 		 * look to the older log data, which was already
1078 		 * committed but the eraseblock was not erased (UBIFS
1079 		 * only un-maps it). So this basically means we have to
1080 		 * exit with "end of log" code.
1081 		 */
1082 		err = 1;
1083 		goto out;
1084 	}
1085 
1086 	/* Make sure the first node sits at offset zero of the LEB */
1087 	if (snod->offs != 0) {
1088 		ubifs_err(c, "first node is not at zero offset");
1089 		goto out_dump;
1090 	}
1091 
1092 	list_for_each_entry(snod, &sleb->nodes, list) {
1093 		cond_resched();
1094 
1095 		if (snod->sqnum >= SQNUM_WATERMARK) {
1096 			ubifs_err(c, "file system's life ended");
1097 			goto out_dump;
1098 		}
1099 
1100 		if (snod->sqnum < c->cs_sqnum) {
1101 			ubifs_err(c, "bad sqnum %llu, commit sqnum %llu",
1102 				  snod->sqnum, c->cs_sqnum);
1103 			goto out_dump;
1104 		}
1105 
1106 		if (snod->sqnum > c->max_sqnum)
1107 			c->max_sqnum = snod->sqnum;
1108 
1109 		switch (snod->type) {
1110 		case UBIFS_REF_NODE: {
1111 			const struct ubifs_ref_node *ref = snod->node;
1112 
1113 			err = validate_ref(c, ref);
1114 			if (err == 1)
1115 				break; /* Already have this bud */
1116 			if (err)
1117 				goto out_dump;
1118 
1119 			err = ubifs_shash_update(c, c->log_hash, ref,
1120 						 UBIFS_REF_NODE_SZ);
1121 			if (err)
1122 				goto out;
1123 
1124 			err = add_replay_bud(c, le32_to_cpu(ref->lnum),
1125 					     le32_to_cpu(ref->offs),
1126 					     le32_to_cpu(ref->jhead),
1127 					     snod->sqnum);
1128 			if (err)
1129 				goto out;
1130 
1131 			break;
1132 		}
1133 		case UBIFS_CS_NODE:
1134 			/* Make sure it sits at the beginning of LEB */
1135 			if (snod->offs != 0) {
1136 				ubifs_err(c, "unexpected node in log");
1137 				goto out_dump;
1138 			}
1139 			break;
1140 		default:
1141 			ubifs_err(c, "unexpected node in log");
1142 			goto out_dump;
1143 		}
1144 	}
1145 
1146 	if (sleb->endpt || c->lhead_offs >= c->leb_size) {
1147 		c->lhead_lnum = lnum;
1148 		c->lhead_offs = sleb->endpt;
1149 	}
1150 
1151 	err = !sleb->endpt;
1152 out:
1153 	ubifs_scan_destroy(sleb);
1154 	return err;
1155 
1156 out_dump:
1157 	ubifs_err(c, "log error detected while replaying the log at LEB %d:%d",
1158 		  lnum, offs + snod->offs);
1159 	ubifs_dump_node(c, snod->node);
1160 	ubifs_scan_destroy(sleb);
1161 	return -EINVAL;
1162 }
1163 
1164 /**
1165  * take_ihead - update the status of the index head in lprops to 'taken'.
1166  * @c: UBIFS file-system description object
1167  *
1168  * This function returns the amount of free space in the index head LEB or a
1169  * negative error code.
1170  */
1171 static int take_ihead(struct ubifs_info *c)
1172 {
1173 	const struct ubifs_lprops *lp;
1174 	int err, free;
1175 
1176 	ubifs_get_lprops(c);
1177 
1178 	lp = ubifs_lpt_lookup_dirty(c, c->ihead_lnum);
1179 	if (IS_ERR(lp)) {
1180 		err = PTR_ERR(lp);
1181 		goto out;
1182 	}
1183 
1184 	free = lp->free;
1185 
1186 	lp = ubifs_change_lp(c, lp, LPROPS_NC, LPROPS_NC,
1187 			     lp->flags | LPROPS_TAKEN, 0);
1188 	if (IS_ERR(lp)) {
1189 		err = PTR_ERR(lp);
1190 		goto out;
1191 	}
1192 
1193 	err = free;
1194 out:
1195 	ubifs_release_lprops(c);
1196 	return err;
1197 }
1198 
1199 /**
1200  * ubifs_replay_journal - replay journal.
1201  * @c: UBIFS file-system description object
1202  *
1203  * This function scans the journal, replays and cleans it up. It makes sure all
1204  * memory data structures related to uncommitted journal are built (dirty TNC
1205  * tree, tree of buds, modified lprops, etc).
1206  */
1207 int ubifs_replay_journal(struct ubifs_info *c)
1208 {
1209 	int err, lnum, free;
1210 
1211 	BUILD_BUG_ON(UBIFS_TRUN_KEY > 5);
1212 
1213 	/* Update the status of the index head in lprops to 'taken' */
1214 	free = take_ihead(c);
1215 	if (free < 0)
1216 		return free; /* Error code */
1217 
1218 	if (c->ihead_offs != c->leb_size - free) {
1219 		ubifs_err(c, "bad index head LEB %d:%d", c->ihead_lnum,
1220 			  c->ihead_offs);
1221 		return -EINVAL;
1222 	}
1223 
1224 	dbg_mnt("start replaying the journal");
1225 	c->replaying = 1;
1226 	lnum = c->ltail_lnum = c->lhead_lnum;
1227 
1228 	do {
1229 		err = replay_log_leb(c, lnum, 0, c->sbuf);
1230 		if (err == 1) {
1231 			if (lnum != c->lhead_lnum)
1232 				/* We hit the end of the log */
1233 				break;
1234 
1235 			/*
1236 			 * The head of the log must always start with the
1237 			 * "commit start" node on a properly formatted UBIFS.
1238 			 * But we found no nodes at all, which means that
1239 			 * something went wrong and we cannot proceed mounting
1240 			 * the file-system.
1241 			 */
1242 			ubifs_err(c, "no UBIFS nodes found at the log head LEB %d:%d, possibly corrupted",
1243 				  lnum, 0);
1244 			err = -EINVAL;
1245 		}
1246 		if (err)
1247 			goto out;
1248 		lnum = ubifs_next_log_lnum(c, lnum);
1249 	} while (lnum != c->ltail_lnum);
1250 
1251 	err = replay_buds(c);
1252 	if (err)
1253 		goto out;
1254 
1255 	err = apply_replay_list(c);
1256 	if (err)
1257 		goto out;
1258 
1259 	err = set_buds_lprops(c);
1260 	if (err)
1261 		goto out;
1262 
1263 	/*
1264 	 * UBIFS budgeting calculations use @c->bi.uncommitted_idx variable
1265 	 * to roughly estimate index growth. Things like @c->bi.min_idx_lebs
1266 	 * depend on it. This means we have to initialize it to make sure
1267 	 * budgeting works properly.
1268 	 */
1269 	c->bi.uncommitted_idx = atomic_long_read(&c->dirty_zn_cnt);
1270 	c->bi.uncommitted_idx *= c->max_idx_node_sz;
1271 
1272 	ubifs_assert(c, c->bud_bytes <= c->max_bud_bytes || c->need_recovery);
1273 	dbg_mnt("finished, log head LEB %d:%d, max_sqnum %llu, highest_inum %lu",
1274 		c->lhead_lnum, c->lhead_offs, c->max_sqnum,
1275 		(unsigned long)c->highest_inum);
1276 out:
1277 	destroy_replay_list(c);
1278 	destroy_bud_list(c);
1279 	c->replaying = 0;
1280 	return err;
1281 }
1282