31acebf50fb566f77c5257118706f1c3d4e49bf8
[openwrt/openwrt.git] / target / linux / generic / patches-4.4 / 141-mtd-bcm47xxpart-improve-handling-TRX-partition-size.patch
1 From: =?UTF-8?q?Rafa=C5=82=20Mi=C5=82ecki?= <rafal@milecki.pl>
2 Subject: [PATCH] mtd: bcm47xxpart: improve handling TRX partition size
3 MIME-Version: 1.0
4 Content-Type: text/plain; charset=UTF-8
5 Content-Transfer-Encoding: 8bit
6
7 When bcm47xxpart finds a TRX partition (container) it's supposed to jump
8 to the end of it and keep looking for more partitions. TRX and its
9 subpartitions are handled be a separated parser.
10
11 The problem with old code was relying on the length specified in a TRX
12 header. That isn't reliable as TRX is commonly modified to have checksum
13 cover only non-changing subpartitions. Otherwise modifying e.g. a rootfs
14 would result in CRC32 mismatch and bootloader refusing to boot a
15 firmware.
16
17 Fix it by trying better to figure out a real TRX size. We can securely
18 assume that TRX has to cover all subpartitions and the last one is at
19 least of a block size in size. Then compare it with a length field.
20
21 This makes code more optimal & reliable thanks to skipping data that
22 shouldn't be parsed.
23
24 Signed-off-by: Rafał Miłecki <rafal@milecki.pl>
25 ---
26
27 --- a/drivers/mtd/bcm47xxpart.c
28 +++ b/drivers/mtd/bcm47xxpart.c
29 @@ -268,6 +268,8 @@ static int bcm47xxpart_parse(struct mtd_
30 /* TRX */
31 if (buf[0x000 / 4] == TRX_MAGIC) {
32 struct trx_header *trx;
33 + uint32_t last_subpart;
34 + uint32_t trx_size;
35
36 if (trx_num >= ARRAY_SIZE(trx_parts))
37 pr_warn("No enough space to store another TRX found at 0x%X\n",
38 @@ -277,11 +279,23 @@ static int bcm47xxpart_parse(struct mtd_
39 bcm47xxpart_add_part(&parts[curr_part++], "firmware",
40 offset, 0);
41
42 - /* Jump to the end of TRX */
43 + /*
44 + * Try to find TRX size. The "length" field isn't fully
45 + * reliable as it could be decreased to make CRC32 cover
46 + * only part of TRX data. It's commonly used as checksum
47 + * can't cover e.g. ever-changing rootfs partition.
48 + * Use offsets as helpers for assuming min TRX size.
49 + */
50 trx = (struct trx_header *)buf;
51 - offset = roundup(offset + trx->length, blocksize);
52 - /* Next loop iteration will increase the offset */
53 - offset -= blocksize;
54 + last_subpart = max3(trx->offset[0], trx->offset[1],
55 + trx->offset[2]);
56 + trx_size = max(trx->length, last_subpart + blocksize);
57 +
58 + /*
59 + * Skip the TRX data. Decrease offset by block size as
60 + * the next loop iteration will increase it.
61 + */
62 + offset += roundup(trx_size, blocksize) - blocksize;
63 continue;
64 }
65