Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * This file is part of UBIFS.
0004  *
0005  * Copyright (C) 2006-2008 Nokia Corporation.
0006  *
0007  * Authors: Adrian Hunter
0008  *          Artem Bityutskiy (Битюцкий Артём)
0009  */
0010 
0011 /*
0012  * This file contains journal replay code. It runs when the file-system is being
0013  * mounted and requires no locking.
0014  *
0015  * The larger is the journal, the longer it takes to scan it, so the longer it
0016  * takes to mount UBIFS. This is why the journal has limited size which may be
0017  * changed depending on the system requirements. But a larger journal gives
0018  * faster I/O speed because it writes the index less frequently. So this is a
0019  * trade-off. Also, the journal is indexed by the in-memory index (TNC), so the
0020  * larger is the journal, the more memory its index may consume.
0021  */
0022 
0023 #include "ubifs.h"
0024 #include <linux/list_sort.h>
0025 #include <crypto/hash.h>
0026 #include <crypto/algapi.h>
0027 
0028 /**
0029  * struct replay_entry - replay list entry.
0030  * @lnum: logical eraseblock number of the node
0031  * @offs: node offset
0032  * @len: node length
0033  * @deletion: non-zero if this entry corresponds to a node deletion
0034  * @sqnum: node sequence number
0035  * @list: links the replay list
0036  * @key: node key
0037  * @nm: directory entry name
0038  * @old_size: truncation old size
0039  * @new_size: truncation new size
0040  *
0041  * The replay process first scans all buds and builds the replay list, then
0042  * sorts the replay list in nodes sequence number order, and then inserts all
0043  * the replay entries to the TNC.
0044  */
0045 struct replay_entry {
0046     int lnum;
0047     int offs;
0048     int len;
0049     u8 hash[UBIFS_HASH_ARR_SZ];
0050     unsigned int deletion:1;
0051     unsigned long long sqnum;
0052     struct list_head list;
0053     union ubifs_key key;
0054     union {
0055         struct fscrypt_name nm;
0056         struct {
0057             loff_t old_size;
0058             loff_t new_size;
0059         };
0060     };
0061 };
0062 
0063 /**
0064  * struct bud_entry - entry in the list of buds to replay.
0065  * @list: next bud in the list
0066  * @bud: bud description object
0067  * @sqnum: reference node sequence number
0068  * @free: free bytes in the bud
0069  * @dirty: dirty bytes in the bud
0070  */
0071 struct bud_entry {
0072     struct list_head list;
0073     struct ubifs_bud *bud;
0074     unsigned long long sqnum;
0075     int free;
0076     int dirty;
0077 };
0078 
0079 /**
0080  * set_bud_lprops - set free and dirty space used by a bud.
0081  * @c: UBIFS file-system description object
0082  * @b: bud entry which describes the bud
0083  *
0084  * This function makes sure the LEB properties of bud @b are set correctly
0085  * after the replay. Returns zero in case of success and a negative error code
0086  * in case of failure.
0087  */
0088 static int set_bud_lprops(struct ubifs_info *c, struct bud_entry *b)
0089 {
0090     const struct ubifs_lprops *lp;
0091     int err = 0, dirty;
0092 
0093     ubifs_get_lprops(c);
0094 
0095     lp = ubifs_lpt_lookup_dirty(c, b->bud->lnum);
0096     if (IS_ERR(lp)) {
0097         err = PTR_ERR(lp);
0098         goto out;
0099     }
0100 
0101     dirty = lp->dirty;
0102     if (b->bud->start == 0 && (lp->free != c->leb_size || lp->dirty != 0)) {
0103         /*
0104          * The LEB was added to the journal with a starting offset of
0105          * zero which means the LEB must have been empty. The LEB
0106          * property values should be @lp->free == @c->leb_size and
0107          * @lp->dirty == 0, but that is not the case. The reason is that
0108          * the LEB had been garbage collected before it became the bud,
0109          * and there was no commit in between. The garbage collector
0110          * resets the free and dirty space without recording it
0111          * anywhere except lprops, so if there was no commit then
0112          * lprops does not have that information.
0113          *
0114          * We do not need to adjust free space because the scan has told
0115          * us the exact value which is recorded in the replay entry as
0116          * @b->free.
0117          *
0118          * However we do need to subtract from the dirty space the
0119          * amount of space that the garbage collector reclaimed, which
0120          * is the whole LEB minus the amount of space that was free.
0121          */
0122         dbg_mnt("bud LEB %d was GC'd (%d free, %d dirty)", b->bud->lnum,
0123             lp->free, lp->dirty);
0124         dbg_gc("bud LEB %d was GC'd (%d free, %d dirty)", b->bud->lnum,
0125             lp->free, lp->dirty);
0126         dirty -= c->leb_size - lp->free;
0127         /*
0128          * If the replay order was perfect the dirty space would now be
0129          * zero. The order is not perfect because the journal heads
0130          * race with each other. This is not a problem but is does mean
0131          * that the dirty space may temporarily exceed c->leb_size
0132          * during the replay.
0133          */
0134         if (dirty != 0)
0135             dbg_mnt("LEB %d lp: %d free %d dirty replay: %d free %d dirty",
0136                 b->bud->lnum, lp->free, lp->dirty, b->free,
0137                 b->dirty);
0138     }
0139     lp = ubifs_change_lp(c, lp, b->free, dirty + b->dirty,
0140                  lp->flags | LPROPS_TAKEN, 0);
0141     if (IS_ERR(lp)) {
0142         err = PTR_ERR(lp);
0143         goto out;
0144     }
0145 
0146     /* Make sure the journal head points to the latest bud */
0147     err = ubifs_wbuf_seek_nolock(&c->jheads[b->bud->jhead].wbuf,
0148                      b->bud->lnum, c->leb_size - b->free);
0149 
0150 out:
0151     ubifs_release_lprops(c);
0152     return err;
0153 }
0154 
0155 /**
0156  * set_buds_lprops - set free and dirty space for all replayed buds.
0157  * @c: UBIFS file-system description object
0158  *
0159  * This function sets LEB properties for all replayed buds. Returns zero in
0160  * case of success and a negative error code in case of failure.
0161  */
0162 static int set_buds_lprops(struct ubifs_info *c)
0163 {
0164     struct bud_entry *b;
0165     int err;
0166 
0167     list_for_each_entry(b, &c->replay_buds, list) {
0168         err = set_bud_lprops(c, b);
0169         if (err)
0170             return err;
0171     }
0172 
0173     return 0;
0174 }
0175 
0176 /**
0177  * trun_remove_range - apply a replay entry for a truncation to the TNC.
0178  * @c: UBIFS file-system description object
0179  * @r: replay entry of truncation
0180  */
0181 static int trun_remove_range(struct ubifs_info *c, struct replay_entry *r)
0182 {
0183     unsigned min_blk, max_blk;
0184     union ubifs_key min_key, max_key;
0185     ino_t ino;
0186 
0187     min_blk = r->new_size / UBIFS_BLOCK_SIZE;
0188     if (r->new_size & (UBIFS_BLOCK_SIZE - 1))
0189         min_blk += 1;
0190 
0191     max_blk = r->old_size / UBIFS_BLOCK_SIZE;
0192     if ((r->old_size & (UBIFS_BLOCK_SIZE - 1)) == 0)
0193         max_blk -= 1;
0194 
0195     ino = key_inum(c, &r->key);
0196 
0197     data_key_init(c, &min_key, ino, min_blk);
0198     data_key_init(c, &max_key, ino, max_blk);
0199 
0200     return ubifs_tnc_remove_range(c, &min_key, &max_key);
0201 }
0202 
0203 /**
0204  * inode_still_linked - check whether inode in question will be re-linked.
0205  * @c: UBIFS file-system description object
0206  * @rino: replay entry to test
0207  *
0208  * O_TMPFILE files can be re-linked, this means link count goes from 0 to 1.
0209  * This case needs special care, otherwise all references to the inode will
0210  * be removed upon the first replay entry of an inode with link count 0
0211  * is found.
0212  */
0213 static bool inode_still_linked(struct ubifs_info *c, struct replay_entry *rino)
0214 {
0215     struct replay_entry *r;
0216 
0217     ubifs_assert(c, rino->deletion);
0218     ubifs_assert(c, key_type(c, &rino->key) == UBIFS_INO_KEY);
0219 
0220     /*
0221      * Find the most recent entry for the inode behind @rino and check
0222      * whether it is a deletion.
0223      */
0224     list_for_each_entry_reverse(r, &c->replay_list, list) {
0225         ubifs_assert(c, r->sqnum >= rino->sqnum);
0226         if (key_inum(c, &r->key) == key_inum(c, &rino->key) &&
0227             key_type(c, &r->key) == UBIFS_INO_KEY)
0228             return r->deletion == 0;
0229 
0230     }
0231 
0232     ubifs_assert(c, 0);
0233     return false;
0234 }
0235 
0236 /**
0237  * apply_replay_entry - apply a replay entry to the TNC.
0238  * @c: UBIFS file-system description object
0239  * @r: replay entry to apply
0240  *
0241  * Apply a replay entry to the TNC.
0242  */
0243 static int apply_replay_entry(struct ubifs_info *c, struct replay_entry *r)
0244 {
0245     int err;
0246 
0247     dbg_mntk(&r->key, "LEB %d:%d len %d deletion %d sqnum %llu key ",
0248          r->lnum, r->offs, r->len, r->deletion, r->sqnum);
0249 
0250     if (is_hash_key(c, &r->key)) {
0251         if (r->deletion)
0252             err = ubifs_tnc_remove_nm(c, &r->key, &r->nm);
0253         else
0254             err = ubifs_tnc_add_nm(c, &r->key, r->lnum, r->offs,
0255                            r->len, r->hash, &r->nm);
0256     } else {
0257         if (r->deletion)
0258             switch (key_type(c, &r->key)) {
0259             case UBIFS_INO_KEY:
0260             {
0261                 ino_t inum = key_inum(c, &r->key);
0262 
0263                 if (inode_still_linked(c, r)) {
0264                     err = 0;
0265                     break;
0266                 }
0267 
0268                 err = ubifs_tnc_remove_ino(c, inum);
0269                 break;
0270             }
0271             case UBIFS_TRUN_KEY:
0272                 err = trun_remove_range(c, r);
0273                 break;
0274             default:
0275                 err = ubifs_tnc_remove(c, &r->key);
0276                 break;
0277             }
0278         else
0279             err = ubifs_tnc_add(c, &r->key, r->lnum, r->offs,
0280                         r->len, r->hash);
0281         if (err)
0282             return err;
0283 
0284         if (c->need_recovery)
0285             err = ubifs_recover_size_accum(c, &r->key, r->deletion,
0286                                r->new_size);
0287     }
0288 
0289     return err;
0290 }
0291 
0292 /**
0293  * replay_entries_cmp - compare 2 replay entries.
0294  * @priv: UBIFS file-system description object
0295  * @a: first replay entry
0296  * @b: second replay entry
0297  *
0298  * This is a comparios function for 'list_sort()' which compares 2 replay
0299  * entries @a and @b by comparing their sequence number.  Returns %1 if @a has
0300  * greater sequence number and %-1 otherwise.
0301  */
0302 static int replay_entries_cmp(void *priv, const struct list_head *a,
0303                   const struct list_head *b)
0304 {
0305     struct ubifs_info *c = priv;
0306     struct replay_entry *ra, *rb;
0307 
0308     cond_resched();
0309     if (a == b)
0310         return 0;
0311 
0312     ra = list_entry(a, struct replay_entry, list);
0313     rb = list_entry(b, struct replay_entry, list);
0314     ubifs_assert(c, ra->sqnum != rb->sqnum);
0315     if (ra->sqnum > rb->sqnum)
0316         return 1;
0317     return -1;
0318 }
0319 
0320 /**
0321  * apply_replay_list - apply the replay list to the TNC.
0322  * @c: UBIFS file-system description object
0323  *
0324  * Apply all entries in the replay list to the TNC. Returns zero in case of
0325  * success and a negative error code in case of failure.
0326  */
0327 static int apply_replay_list(struct ubifs_info *c)
0328 {
0329     struct replay_entry *r;
0330     int err;
0331 
0332     list_sort(c, &c->replay_list, &replay_entries_cmp);
0333 
0334     list_for_each_entry(r, &c->replay_list, list) {
0335         cond_resched();
0336 
0337         err = apply_replay_entry(c, r);
0338         if (err)
0339             return err;
0340     }
0341 
0342     return 0;
0343 }
0344 
0345 /**
0346  * destroy_replay_list - destroy the replay.
0347  * @c: UBIFS file-system description object
0348  *
0349  * Destroy the replay list.
0350  */
0351 static void destroy_replay_list(struct ubifs_info *c)
0352 {
0353     struct replay_entry *r, *tmp;
0354 
0355     list_for_each_entry_safe(r, tmp, &c->replay_list, list) {
0356         if (is_hash_key(c, &r->key))
0357             kfree(fname_name(&r->nm));
0358         list_del(&r->list);
0359         kfree(r);
0360     }
0361 }
0362 
0363 /**
0364  * insert_node - insert a node to the replay list
0365  * @c: UBIFS file-system description object
0366  * @lnum: node logical eraseblock number
0367  * @offs: node offset
0368  * @len: node length
0369  * @key: node key
0370  * @sqnum: sequence number
0371  * @deletion: non-zero if this is a deletion
0372  * @used: number of bytes in use in a LEB
0373  * @old_size: truncation old size
0374  * @new_size: truncation new size
0375  *
0376  * This function inserts a scanned non-direntry node to the replay list. The
0377  * replay list contains @struct replay_entry elements, and we sort this list in
0378  * sequence number order before applying it. The replay list is applied at the
0379  * very end of the replay process. Since the list is sorted in sequence number
0380  * order, the older modifications are applied first. This function returns zero
0381  * in case of success and a negative error code in case of failure.
0382  */
0383 static int insert_node(struct ubifs_info *c, int lnum, int offs, int len,
0384                const u8 *hash, union ubifs_key *key,
0385                unsigned long long sqnum, int deletion, int *used,
0386                loff_t old_size, loff_t new_size)
0387 {
0388     struct replay_entry *r;
0389 
0390     dbg_mntk(key, "add LEB %d:%d, key ", lnum, offs);
0391 
0392     if (key_inum(c, key) >= c->highest_inum)
0393         c->highest_inum = key_inum(c, key);
0394 
0395     r = kzalloc(sizeof(struct replay_entry), GFP_KERNEL);
0396     if (!r)
0397         return -ENOMEM;
0398 
0399     if (!deletion)
0400         *used += ALIGN(len, 8);
0401     r->lnum = lnum;
0402     r->offs = offs;
0403     r->len = len;
0404     ubifs_copy_hash(c, hash, r->hash);
0405     r->deletion = !!deletion;
0406     r->sqnum = sqnum;
0407     key_copy(c, key, &r->key);
0408     r->old_size = old_size;
0409     r->new_size = new_size;
0410 
0411     list_add_tail(&r->list, &c->replay_list);
0412     return 0;
0413 }
0414 
0415 /**
0416  * insert_dent - insert a directory entry node into the replay list.
0417  * @c: UBIFS file-system description object
0418  * @lnum: node logical eraseblock number
0419  * @offs: node offset
0420  * @len: node length
0421  * @key: node key
0422  * @name: directory entry name
0423  * @nlen: directory entry name length
0424  * @sqnum: sequence number
0425  * @deletion: non-zero if this is a deletion
0426  * @used: number of bytes in use in a LEB
0427  *
0428  * This function inserts a scanned directory entry node or an extended
0429  * attribute entry to the replay list. Returns zero in case of success and a
0430  * negative error code in case of failure.
0431  */
0432 static int insert_dent(struct ubifs_info *c, int lnum, int offs, int len,
0433                const u8 *hash, union ubifs_key *key,
0434                const char *name, int nlen, unsigned long long sqnum,
0435                int deletion, int *used)
0436 {
0437     struct replay_entry *r;
0438     char *nbuf;
0439 
0440     dbg_mntk(key, "add LEB %d:%d, key ", lnum, offs);
0441     if (key_inum(c, key) >= c->highest_inum)
0442         c->highest_inum = key_inum(c, key);
0443 
0444     r = kzalloc(sizeof(struct replay_entry), GFP_KERNEL);
0445     if (!r)
0446         return -ENOMEM;
0447 
0448     nbuf = kmalloc(nlen + 1, GFP_KERNEL);
0449     if (!nbuf) {
0450         kfree(r);
0451         return -ENOMEM;
0452     }
0453 
0454     if (!deletion)
0455         *used += ALIGN(len, 8);
0456     r->lnum = lnum;
0457     r->offs = offs;
0458     r->len = len;
0459     ubifs_copy_hash(c, hash, r->hash);
0460     r->deletion = !!deletion;
0461     r->sqnum = sqnum;
0462     key_copy(c, key, &r->key);
0463     fname_len(&r->nm) = nlen;
0464     memcpy(nbuf, name, nlen);
0465     nbuf[nlen] = '\0';
0466     fname_name(&r->nm) = nbuf;
0467 
0468     list_add_tail(&r->list, &c->replay_list);
0469     return 0;
0470 }
0471 
0472 /**
0473  * ubifs_validate_entry - validate directory or extended attribute entry node.
0474  * @c: UBIFS file-system description object
0475  * @dent: the node to validate
0476  *
0477  * This function validates directory or extended attribute entry node @dent.
0478  * Returns zero if the node is all right and a %-EINVAL if not.
0479  */
0480 int ubifs_validate_entry(struct ubifs_info *c,
0481              const struct ubifs_dent_node *dent)
0482 {
0483     int key_type = key_type_flash(c, dent->key);
0484     int nlen = le16_to_cpu(dent->nlen);
0485 
0486     if (le32_to_cpu(dent->ch.len) != nlen + UBIFS_DENT_NODE_SZ + 1 ||
0487         dent->type >= UBIFS_ITYPES_CNT ||
0488         nlen > UBIFS_MAX_NLEN || dent->name[nlen] != 0 ||
0489         (key_type == UBIFS_XENT_KEY && strnlen(dent->name, nlen) != nlen) ||
0490         le64_to_cpu(dent->inum) > MAX_INUM) {
0491         ubifs_err(c, "bad %s node", key_type == UBIFS_DENT_KEY ?
0492               "directory entry" : "extended attribute entry");
0493         return -EINVAL;
0494     }
0495 
0496     if (key_type != UBIFS_DENT_KEY && key_type != UBIFS_XENT_KEY) {
0497         ubifs_err(c, "bad key type %d", key_type);
0498         return -EINVAL;
0499     }
0500 
0501     return 0;
0502 }
0503 
0504 /**
0505  * is_last_bud - check if the bud is the last in the journal head.
0506  * @c: UBIFS file-system description object
0507  * @bud: bud description object
0508  *
0509  * This function checks if bud @bud is the last bud in its journal head. This
0510  * information is then used by 'replay_bud()' to decide whether the bud can
0511  * have corruptions or not. Indeed, only last buds can be corrupted by power
0512  * cuts. Returns %1 if this is the last bud, and %0 if not.
0513  */
0514 static int is_last_bud(struct ubifs_info *c, struct ubifs_bud *bud)
0515 {
0516     struct ubifs_jhead *jh = &c->jheads[bud->jhead];
0517     struct ubifs_bud *next;
0518     uint32_t data;
0519     int err;
0520 
0521     if (list_is_last(&bud->list, &jh->buds_list))
0522         return 1;
0523 
0524     /*
0525      * The following is a quirk to make sure we work correctly with UBIFS
0526      * images used with older UBIFS.
0527      *
0528      * Normally, the last bud will be the last in the journal head's list
0529      * of bud. However, there is one exception if the UBIFS image belongs
0530      * to older UBIFS. This is fairly unlikely: one would need to use old
0531      * UBIFS, then have a power cut exactly at the right point, and then
0532      * try to mount this image with new UBIFS.
0533      *
0534      * The exception is: it is possible to have 2 buds A and B, A goes
0535      * before B, and B is the last, bud B is contains no data, and bud A is
0536      * corrupted at the end. The reason is that in older versions when the
0537      * journal code switched the next bud (from A to B), it first added a
0538      * log reference node for the new bud (B), and only after this it
0539      * synchronized the write-buffer of current bud (A). But later this was
0540      * changed and UBIFS started to always synchronize the write-buffer of
0541      * the bud (A) before writing the log reference for the new bud (B).
0542      *
0543      * But because older UBIFS always synchronized A's write-buffer before
0544      * writing to B, we can recognize this exceptional situation but
0545      * checking the contents of bud B - if it is empty, then A can be
0546      * treated as the last and we can recover it.
0547      *
0548      * TODO: remove this piece of code in a couple of years (today it is
0549      * 16.05.2011).
0550      */
0551     next = list_entry(bud->list.next, struct ubifs_bud, list);
0552     if (!list_is_last(&next->list, &jh->buds_list))
0553         return 0;
0554 
0555     err = ubifs_leb_read(c, next->lnum, (char *)&data, next->start, 4, 1);
0556     if (err)
0557         return 0;
0558 
0559     return data == 0xFFFFFFFF;
0560 }
0561 
0562 /* authenticate_sleb_hash is split out for stack usage */
0563 static int noinline_for_stack
0564 authenticate_sleb_hash(struct ubifs_info *c,
0565                struct shash_desc *log_hash, u8 *hash)
0566 {
0567     SHASH_DESC_ON_STACK(hash_desc, c->hash_tfm);
0568 
0569     hash_desc->tfm = c->hash_tfm;
0570 
0571     ubifs_shash_copy_state(c, log_hash, hash_desc);
0572     return crypto_shash_final(hash_desc, hash);
0573 }
0574 
0575 /**
0576  * authenticate_sleb - authenticate one scan LEB
0577  * @c: UBIFS file-system description object
0578  * @sleb: the scan LEB to authenticate
0579  * @log_hash:
0580  * @is_last: if true, this is the last LEB
0581  *
0582  * This function iterates over the buds of a single LEB authenticating all buds
0583  * with the authentication nodes on this LEB. Authentication nodes are written
0584  * after some buds and contain a HMAC covering the authentication node itself
0585  * and the buds between the last authentication node and the current
0586  * authentication node. It can happen that the last buds cannot be authenticated
0587  * because a powercut happened when some nodes were written but not the
0588  * corresponding authentication node. This function returns the number of nodes
0589  * that could be authenticated or a negative error code.
0590  */
0591 static int authenticate_sleb(struct ubifs_info *c, struct ubifs_scan_leb *sleb,
0592                  struct shash_desc *log_hash, int is_last)
0593 {
0594     int n_not_auth = 0;
0595     struct ubifs_scan_node *snod;
0596     int n_nodes = 0;
0597     int err;
0598     u8 hash[UBIFS_HASH_ARR_SZ];
0599     u8 hmac[UBIFS_HMAC_ARR_SZ];
0600 
0601     if (!ubifs_authenticated(c))
0602         return sleb->nodes_cnt;
0603 
0604     list_for_each_entry(snod, &sleb->nodes, list) {
0605 
0606         n_nodes++;
0607 
0608         if (snod->type == UBIFS_AUTH_NODE) {
0609             struct ubifs_auth_node *auth = snod->node;
0610 
0611             err = authenticate_sleb_hash(c, log_hash, hash);
0612             if (err)
0613                 goto out;
0614 
0615             err = crypto_shash_tfm_digest(c->hmac_tfm, hash,
0616                               c->hash_len, hmac);
0617             if (err)
0618                 goto out;
0619 
0620             err = ubifs_check_hmac(c, auth->hmac, hmac);
0621             if (err) {
0622                 err = -EPERM;
0623                 goto out;
0624             }
0625             n_not_auth = 0;
0626         } else {
0627             err = crypto_shash_update(log_hash, snod->node,
0628                           snod->len);
0629             if (err)
0630                 goto out;
0631             n_not_auth++;
0632         }
0633     }
0634 
0635     /*
0636      * A powercut can happen when some nodes were written, but not yet
0637      * the corresponding authentication node. This may only happen on
0638      * the last bud though.
0639      */
0640     if (n_not_auth) {
0641         if (is_last) {
0642             dbg_mnt("%d unauthenticated nodes found on LEB %d, Ignoring them",
0643                 n_not_auth, sleb->lnum);
0644             err = 0;
0645         } else {
0646             dbg_mnt("%d unauthenticated nodes found on non-last LEB %d",
0647                 n_not_auth, sleb->lnum);
0648             err = -EPERM;
0649         }
0650     } else {
0651         err = 0;
0652     }
0653 out:
0654     return err ? err : n_nodes - n_not_auth;
0655 }
0656 
0657 /**
0658  * replay_bud - replay a bud logical eraseblock.
0659  * @c: UBIFS file-system description object
0660  * @b: bud entry which describes the bud
0661  *
0662  * This function replays bud @bud, recovers it if needed, and adds all nodes
0663  * from this bud to the replay list. Returns zero in case of success and a
0664  * negative error code in case of failure.
0665  */
0666 static int replay_bud(struct ubifs_info *c, struct bud_entry *b)
0667 {
0668     int is_last = is_last_bud(c, b->bud);
0669     int err = 0, used = 0, lnum = b->bud->lnum, offs = b->bud->start;
0670     int n_nodes, n = 0;
0671     struct ubifs_scan_leb *sleb;
0672     struct ubifs_scan_node *snod;
0673 
0674     dbg_mnt("replay bud LEB %d, head %d, offs %d, is_last %d",
0675         lnum, b->bud->jhead, offs, is_last);
0676 
0677     if (c->need_recovery && is_last)
0678         /*
0679          * Recover only last LEBs in the journal heads, because power
0680          * cuts may cause corruptions only in these LEBs, because only
0681          * these LEBs could possibly be written to at the power cut
0682          * time.
0683          */
0684         sleb = ubifs_recover_leb(c, lnum, offs, c->sbuf, b->bud->jhead);
0685     else
0686         sleb = ubifs_scan(c, lnum, offs, c->sbuf, 0);
0687     if (IS_ERR(sleb))
0688         return PTR_ERR(sleb);
0689 
0690     n_nodes = authenticate_sleb(c, sleb, b->bud->log_hash, is_last);
0691     if (n_nodes < 0) {
0692         err = n_nodes;
0693         goto out;
0694     }
0695 
0696     ubifs_shash_copy_state(c, b->bud->log_hash,
0697                    c->jheads[b->bud->jhead].log_hash);
0698 
0699     /*
0700      * The bud does not have to start from offset zero - the beginning of
0701      * the 'lnum' LEB may contain previously committed data. One of the
0702      * things we have to do in replay is to correctly update lprops with
0703      * newer information about this LEB.
0704      *
0705      * At this point lprops thinks that this LEB has 'c->leb_size - offs'
0706      * bytes of free space because it only contain information about
0707      * committed data.
0708      *
0709      * But we know that real amount of free space is 'c->leb_size -
0710      * sleb->endpt', and the space in the 'lnum' LEB between 'offs' and
0711      * 'sleb->endpt' is used by bud data. We have to correctly calculate
0712      * how much of these data are dirty and update lprops with this
0713      * information.
0714      *
0715      * The dirt in that LEB region is comprised of padding nodes, deletion
0716      * nodes, truncation nodes and nodes which are obsoleted by subsequent
0717      * nodes in this LEB. So instead of calculating clean space, we
0718      * calculate used space ('used' variable).
0719      */
0720 
0721     list_for_each_entry(snod, &sleb->nodes, list) {
0722         u8 hash[UBIFS_HASH_ARR_SZ];
0723         int deletion = 0;
0724 
0725         cond_resched();
0726 
0727         if (snod->sqnum >= SQNUM_WATERMARK) {
0728             ubifs_err(c, "file system's life ended");
0729             goto out_dump;
0730         }
0731 
0732         ubifs_node_calc_hash(c, snod->node, hash);
0733 
0734         if (snod->sqnum > c->max_sqnum)
0735             c->max_sqnum = snod->sqnum;
0736 
0737         switch (snod->type) {
0738         case UBIFS_INO_NODE:
0739         {
0740             struct ubifs_ino_node *ino = snod->node;
0741             loff_t new_size = le64_to_cpu(ino->size);
0742 
0743             if (le32_to_cpu(ino->nlink) == 0)
0744                 deletion = 1;
0745             err = insert_node(c, lnum, snod->offs, snod->len, hash,
0746                       &snod->key, snod->sqnum, deletion,
0747                       &used, 0, new_size);
0748             break;
0749         }
0750         case UBIFS_DATA_NODE:
0751         {
0752             struct ubifs_data_node *dn = snod->node;
0753             loff_t new_size = le32_to_cpu(dn->size) +
0754                       key_block(c, &snod->key) *
0755                       UBIFS_BLOCK_SIZE;
0756 
0757             err = insert_node(c, lnum, snod->offs, snod->len, hash,
0758                       &snod->key, snod->sqnum, deletion,
0759                       &used, 0, new_size);
0760             break;
0761         }
0762         case UBIFS_DENT_NODE:
0763         case UBIFS_XENT_NODE:
0764         {
0765             struct ubifs_dent_node *dent = snod->node;
0766 
0767             err = ubifs_validate_entry(c, dent);
0768             if (err)
0769                 goto out_dump;
0770 
0771             err = insert_dent(c, lnum, snod->offs, snod->len, hash,
0772                       &snod->key, dent->name,
0773                       le16_to_cpu(dent->nlen), snod->sqnum,
0774                       !le64_to_cpu(dent->inum), &used);
0775             break;
0776         }
0777         case UBIFS_TRUN_NODE:
0778         {
0779             struct ubifs_trun_node *trun = snod->node;
0780             loff_t old_size = le64_to_cpu(trun->old_size);
0781             loff_t new_size = le64_to_cpu(trun->new_size);
0782             union ubifs_key key;
0783 
0784             /* Validate truncation node */
0785             if (old_size < 0 || old_size > c->max_inode_sz ||
0786                 new_size < 0 || new_size > c->max_inode_sz ||
0787                 old_size <= new_size) {
0788                 ubifs_err(c, "bad truncation node");
0789                 goto out_dump;
0790             }
0791 
0792             /*
0793              * Create a fake truncation key just to use the same
0794              * functions which expect nodes to have keys.
0795              */
0796             trun_key_init(c, &key, le32_to_cpu(trun->inum));
0797             err = insert_node(c, lnum, snod->offs, snod->len, hash,
0798                       &key, snod->sqnum, 1, &used,
0799                       old_size, new_size);
0800             break;
0801         }
0802         case UBIFS_AUTH_NODE:
0803             break;
0804         default:
0805             ubifs_err(c, "unexpected node type %d in bud LEB %d:%d",
0806                   snod->type, lnum, snod->offs);
0807             err = -EINVAL;
0808             goto out_dump;
0809         }
0810         if (err)
0811             goto out;
0812 
0813         n++;
0814         if (n == n_nodes)
0815             break;
0816     }
0817 
0818     ubifs_assert(c, ubifs_search_bud(c, lnum));
0819     ubifs_assert(c, sleb->endpt - offs >= used);
0820     ubifs_assert(c, sleb->endpt % c->min_io_size == 0);
0821 
0822     b->dirty = sleb->endpt - offs - used;
0823     b->free = c->leb_size - sleb->endpt;
0824     dbg_mnt("bud LEB %d replied: dirty %d, free %d",
0825         lnum, b->dirty, b->free);
0826 
0827 out:
0828     ubifs_scan_destroy(sleb);
0829     return err;
0830 
0831 out_dump:
0832     ubifs_err(c, "bad node is at LEB %d:%d", lnum, snod->offs);
0833     ubifs_dump_node(c, snod->node, c->leb_size - snod->offs);
0834     ubifs_scan_destroy(sleb);
0835     return -EINVAL;
0836 }
0837 
0838 /**
0839  * replay_buds - replay all buds.
0840  * @c: UBIFS file-system description object
0841  *
0842  * This function returns zero in case of success and a negative error code in
0843  * case of failure.
0844  */
0845 static int replay_buds(struct ubifs_info *c)
0846 {
0847     struct bud_entry *b;
0848     int err;
0849     unsigned long long prev_sqnum = 0;
0850 
0851     list_for_each_entry(b, &c->replay_buds, list) {
0852         err = replay_bud(c, b);
0853         if (err)
0854             return err;
0855 
0856         ubifs_assert(c, b->sqnum > prev_sqnum);
0857         prev_sqnum = b->sqnum;
0858     }
0859 
0860     return 0;
0861 }
0862 
0863 /**
0864  * destroy_bud_list - destroy the list of buds to replay.
0865  * @c: UBIFS file-system description object
0866  */
0867 static void destroy_bud_list(struct ubifs_info *c)
0868 {
0869     struct bud_entry *b;
0870 
0871     while (!list_empty(&c->replay_buds)) {
0872         b = list_entry(c->replay_buds.next, struct bud_entry, list);
0873         list_del(&b->list);
0874         kfree(b);
0875     }
0876 }
0877 
0878 /**
0879  * add_replay_bud - add a bud to the list of buds to replay.
0880  * @c: UBIFS file-system description object
0881  * @lnum: bud logical eraseblock number to replay
0882  * @offs: bud start offset
0883  * @jhead: journal head to which this bud belongs
0884  * @sqnum: reference node sequence number
0885  *
0886  * This function returns zero in case of success and a negative error code in
0887  * case of failure.
0888  */
0889 static int add_replay_bud(struct ubifs_info *c, int lnum, int offs, int jhead,
0890               unsigned long long sqnum)
0891 {
0892     struct ubifs_bud *bud;
0893     struct bud_entry *b;
0894     int err;
0895 
0896     dbg_mnt("add replay bud LEB %d:%d, head %d", lnum, offs, jhead);
0897 
0898     bud = kmalloc(sizeof(struct ubifs_bud), GFP_KERNEL);
0899     if (!bud)
0900         return -ENOMEM;
0901 
0902     b = kmalloc(sizeof(struct bud_entry), GFP_KERNEL);
0903     if (!b) {
0904         err = -ENOMEM;
0905         goto out;
0906     }
0907 
0908     bud->lnum = lnum;
0909     bud->start = offs;
0910     bud->jhead = jhead;
0911     bud->log_hash = ubifs_hash_get_desc(c);
0912     if (IS_ERR(bud->log_hash)) {
0913         err = PTR_ERR(bud->log_hash);
0914         goto out;
0915     }
0916 
0917     ubifs_shash_copy_state(c, c->log_hash, bud->log_hash);
0918 
0919     ubifs_add_bud(c, bud);
0920 
0921     b->bud = bud;
0922     b->sqnum = sqnum;
0923     list_add_tail(&b->list, &c->replay_buds);
0924 
0925     return 0;
0926 out:
0927     kfree(bud);
0928     kfree(b);
0929 
0930     return err;
0931 }
0932 
0933 /**
0934  * validate_ref - validate a reference node.
0935  * @c: UBIFS file-system description object
0936  * @ref: the reference node to validate
0937  *
0938  * This function returns %1 if a bud reference already exists for the LEB. %0 is
0939  * returned if the reference node is new, otherwise %-EINVAL is returned if
0940  * validation failed.
0941  */
0942 static int validate_ref(struct ubifs_info *c, const struct ubifs_ref_node *ref)
0943 {
0944     struct ubifs_bud *bud;
0945     int lnum = le32_to_cpu(ref->lnum);
0946     unsigned int offs = le32_to_cpu(ref->offs);
0947     unsigned int jhead = le32_to_cpu(ref->jhead);
0948 
0949     /*
0950      * ref->offs may point to the end of LEB when the journal head points
0951      * to the end of LEB and we write reference node for it during commit.
0952      * So this is why we require 'offs > c->leb_size'.
0953      */
0954     if (jhead >= c->jhead_cnt || lnum >= c->leb_cnt ||
0955         lnum < c->main_first || offs > c->leb_size ||
0956         offs & (c->min_io_size - 1))
0957         return -EINVAL;
0958 
0959     /* Make sure we have not already looked at this bud */
0960     bud = ubifs_search_bud(c, lnum);
0961     if (bud) {
0962         if (bud->jhead == jhead && bud->start <= offs)
0963             return 1;
0964         ubifs_err(c, "bud at LEB %d:%d was already referred", lnum, offs);
0965         return -EINVAL;
0966     }
0967 
0968     return 0;
0969 }
0970 
0971 /**
0972  * replay_log_leb - replay a log logical eraseblock.
0973  * @c: UBIFS file-system description object
0974  * @lnum: log logical eraseblock to replay
0975  * @offs: offset to start replaying from
0976  * @sbuf: scan buffer
0977  *
0978  * This function replays a log LEB and returns zero in case of success, %1 if
0979  * this is the last LEB in the log, and a negative error code in case of
0980  * failure.
0981  */
0982 static int replay_log_leb(struct ubifs_info *c, int lnum, int offs, void *sbuf)
0983 {
0984     int err;
0985     struct ubifs_scan_leb *sleb;
0986     struct ubifs_scan_node *snod;
0987     const struct ubifs_cs_node *node;
0988 
0989     dbg_mnt("replay log LEB %d:%d", lnum, offs);
0990     sleb = ubifs_scan(c, lnum, offs, sbuf, c->need_recovery);
0991     if (IS_ERR(sleb)) {
0992         if (PTR_ERR(sleb) != -EUCLEAN || !c->need_recovery)
0993             return PTR_ERR(sleb);
0994         /*
0995          * Note, the below function will recover this log LEB only if
0996          * it is the last, because unclean reboots can possibly corrupt
0997          * only the tail of the log.
0998          */
0999         sleb = ubifs_recover_log_leb(c, lnum, offs, sbuf);
1000         if (IS_ERR(sleb))
1001             return PTR_ERR(sleb);
1002     }
1003 
1004     if (sleb->nodes_cnt == 0) {
1005         err = 1;
1006         goto out;
1007     }
1008 
1009     node = sleb->buf;
1010     snod = list_entry(sleb->nodes.next, struct ubifs_scan_node, list);
1011     if (c->cs_sqnum == 0) {
1012         /*
1013          * This is the first log LEB we are looking at, make sure that
1014          * the first node is a commit start node. Also record its
1015          * sequence number so that UBIFS can determine where the log
1016          * ends, because all nodes which were have higher sequence
1017          * numbers.
1018          */
1019         if (snod->type != UBIFS_CS_NODE) {
1020             ubifs_err(c, "first log node at LEB %d:%d is not CS node",
1021                   lnum, offs);
1022             goto out_dump;
1023         }
1024         if (le64_to_cpu(node->cmt_no) != c->cmt_no) {
1025             ubifs_err(c, "first CS node at LEB %d:%d has wrong commit number %llu expected %llu",
1026                   lnum, offs,
1027                   (unsigned long long)le64_to_cpu(node->cmt_no),
1028                   c->cmt_no);
1029             goto out_dump;
1030         }
1031 
1032         c->cs_sqnum = le64_to_cpu(node->ch.sqnum);
1033         dbg_mnt("commit start sqnum %llu", c->cs_sqnum);
1034 
1035         err = ubifs_shash_init(c, c->log_hash);
1036         if (err)
1037             goto out;
1038 
1039         err = ubifs_shash_update(c, c->log_hash, node, UBIFS_CS_NODE_SZ);
1040         if (err < 0)
1041             goto out;
1042     }
1043 
1044     if (snod->sqnum < c->cs_sqnum) {
1045         /*
1046          * This means that we reached end of log and now
1047          * look to the older log data, which was already
1048          * committed but the eraseblock was not erased (UBIFS
1049          * only un-maps it). So this basically means we have to
1050          * exit with "end of log" code.
1051          */
1052         err = 1;
1053         goto out;
1054     }
1055 
1056     /* Make sure the first node sits at offset zero of the LEB */
1057     if (snod->offs != 0) {
1058         ubifs_err(c, "first node is not at zero offset");
1059         goto out_dump;
1060     }
1061 
1062     list_for_each_entry(snod, &sleb->nodes, list) {
1063         cond_resched();
1064 
1065         if (snod->sqnum >= SQNUM_WATERMARK) {
1066             ubifs_err(c, "file system's life ended");
1067             goto out_dump;
1068         }
1069 
1070         if (snod->sqnum < c->cs_sqnum) {
1071             ubifs_err(c, "bad sqnum %llu, commit sqnum %llu",
1072                   snod->sqnum, c->cs_sqnum);
1073             goto out_dump;
1074         }
1075 
1076         if (snod->sqnum > c->max_sqnum)
1077             c->max_sqnum = snod->sqnum;
1078 
1079         switch (snod->type) {
1080         case UBIFS_REF_NODE: {
1081             const struct ubifs_ref_node *ref = snod->node;
1082 
1083             err = validate_ref(c, ref);
1084             if (err == 1)
1085                 break; /* Already have this bud */
1086             if (err)
1087                 goto out_dump;
1088 
1089             err = ubifs_shash_update(c, c->log_hash, ref,
1090                          UBIFS_REF_NODE_SZ);
1091             if (err)
1092                 goto out;
1093 
1094             err = add_replay_bud(c, le32_to_cpu(ref->lnum),
1095                          le32_to_cpu(ref->offs),
1096                          le32_to_cpu(ref->jhead),
1097                          snod->sqnum);
1098             if (err)
1099                 goto out;
1100 
1101             break;
1102         }
1103         case UBIFS_CS_NODE:
1104             /* Make sure it sits at the beginning of LEB */
1105             if (snod->offs != 0) {
1106                 ubifs_err(c, "unexpected node in log");
1107                 goto out_dump;
1108             }
1109             break;
1110         default:
1111             ubifs_err(c, "unexpected node in log");
1112             goto out_dump;
1113         }
1114     }
1115 
1116     if (sleb->endpt || c->lhead_offs >= c->leb_size) {
1117         c->lhead_lnum = lnum;
1118         c->lhead_offs = sleb->endpt;
1119     }
1120 
1121     err = !sleb->endpt;
1122 out:
1123     ubifs_scan_destroy(sleb);
1124     return err;
1125 
1126 out_dump:
1127     ubifs_err(c, "log error detected while replaying the log at LEB %d:%d",
1128           lnum, offs + snod->offs);
1129     ubifs_dump_node(c, snod->node, c->leb_size - snod->offs);
1130     ubifs_scan_destroy(sleb);
1131     return -EINVAL;
1132 }
1133 
1134 /**
1135  * take_ihead - update the status of the index head in lprops to 'taken'.
1136  * @c: UBIFS file-system description object
1137  *
1138  * This function returns the amount of free space in the index head LEB or a
1139  * negative error code.
1140  */
1141 static int take_ihead(struct ubifs_info *c)
1142 {
1143     const struct ubifs_lprops *lp;
1144     int err, free;
1145 
1146     ubifs_get_lprops(c);
1147 
1148     lp = ubifs_lpt_lookup_dirty(c, c->ihead_lnum);
1149     if (IS_ERR(lp)) {
1150         err = PTR_ERR(lp);
1151         goto out;
1152     }
1153 
1154     free = lp->free;
1155 
1156     lp = ubifs_change_lp(c, lp, LPROPS_NC, LPROPS_NC,
1157                  lp->flags | LPROPS_TAKEN, 0);
1158     if (IS_ERR(lp)) {
1159         err = PTR_ERR(lp);
1160         goto out;
1161     }
1162 
1163     err = free;
1164 out:
1165     ubifs_release_lprops(c);
1166     return err;
1167 }
1168 
1169 /**
1170  * ubifs_replay_journal - replay journal.
1171  * @c: UBIFS file-system description object
1172  *
1173  * This function scans the journal, replays and cleans it up. It makes sure all
1174  * memory data structures related to uncommitted journal are built (dirty TNC
1175  * tree, tree of buds, modified lprops, etc).
1176  */
1177 int ubifs_replay_journal(struct ubifs_info *c)
1178 {
1179     int err, lnum, free;
1180 
1181     BUILD_BUG_ON(UBIFS_TRUN_KEY > 5);
1182 
1183     /* Update the status of the index head in lprops to 'taken' */
1184     free = take_ihead(c);
1185     if (free < 0)
1186         return free; /* Error code */
1187 
1188     if (c->ihead_offs != c->leb_size - free) {
1189         ubifs_err(c, "bad index head LEB %d:%d", c->ihead_lnum,
1190               c->ihead_offs);
1191         return -EINVAL;
1192     }
1193 
1194     dbg_mnt("start replaying the journal");
1195     c->replaying = 1;
1196     lnum = c->ltail_lnum = c->lhead_lnum;
1197 
1198     do {
1199         err = replay_log_leb(c, lnum, 0, c->sbuf);
1200         if (err == 1) {
1201             if (lnum != c->lhead_lnum)
1202                 /* We hit the end of the log */
1203                 break;
1204 
1205             /*
1206              * The head of the log must always start with the
1207              * "commit start" node on a properly formatted UBIFS.
1208              * But we found no nodes at all, which means that
1209              * something went wrong and we cannot proceed mounting
1210              * the file-system.
1211              */
1212             ubifs_err(c, "no UBIFS nodes found at the log head LEB %d:%d, possibly corrupted",
1213                   lnum, 0);
1214             err = -EINVAL;
1215         }
1216         if (err)
1217             goto out;
1218         lnum = ubifs_next_log_lnum(c, lnum);
1219     } while (lnum != c->ltail_lnum);
1220 
1221     err = replay_buds(c);
1222     if (err)
1223         goto out;
1224 
1225     err = apply_replay_list(c);
1226     if (err)
1227         goto out;
1228 
1229     err = set_buds_lprops(c);
1230     if (err)
1231         goto out;
1232 
1233     /*
1234      * UBIFS budgeting calculations use @c->bi.uncommitted_idx variable
1235      * to roughly estimate index growth. Things like @c->bi.min_idx_lebs
1236      * depend on it. This means we have to initialize it to make sure
1237      * budgeting works properly.
1238      */
1239     c->bi.uncommitted_idx = atomic_long_read(&c->dirty_zn_cnt);
1240     c->bi.uncommitted_idx *= c->max_idx_node_sz;
1241 
1242     ubifs_assert(c, c->bud_bytes <= c->max_bud_bytes || c->need_recovery);
1243     dbg_mnt("finished, log head LEB %d:%d, max_sqnum %llu, highest_inum %lu",
1244         c->lhead_lnum, c->lhead_offs, c->max_sqnum,
1245         (unsigned long)c->highest_inum);
1246 out:
1247     destroy_replay_list(c);
1248     destroy_bud_list(c);
1249     c->replaying = 0;
1250     return err;
1251 }