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