b.liu | e958203 | 2025-04-17 19:18:16 +0800 | [diff] [blame^] | 1 | // SPDX-License-Identifier: GPL-2.0-only |
| 2 | /* |
| 3 | * Copyright (C) 2021 Rafał Miłecki <rafal@milecki.pl> |
| 4 | */ |
| 5 | |
| 6 | #include <linux/init.h> |
| 7 | #include <linux/jffs2.h> |
| 8 | #include <linux/kernel.h> |
| 9 | #include <linux/module.h> |
| 10 | #include <linux/mtd/mtd.h> |
| 11 | #include <linux/mtd/partitions.h> |
| 12 | #include <linux/of.h> |
| 13 | #include <linux/slab.h> |
| 14 | |
| 15 | #include "mtdsplit.h" |
| 16 | |
| 17 | #define je16_to_cpu(x) ((x).v16) |
| 18 | #define je32_to_cpu(x) ((x).v32) |
| 19 | |
| 20 | #define NR_PARTS 2 |
| 21 | |
| 22 | static int mtdsplit_cfe_bootfs_parse(struct mtd_info *mtd, |
| 23 | const struct mtd_partition **pparts, |
| 24 | struct mtd_part_parser_data *data) |
| 25 | { |
| 26 | struct jffs2_raw_dirent node; |
| 27 | enum mtdsplit_part_type type; |
| 28 | struct mtd_partition *parts; |
| 29 | size_t rootfs_offset; |
| 30 | size_t retlen; |
| 31 | size_t offset; |
| 32 | int err; |
| 33 | |
| 34 | /* Don't parse backup partitions */ |
| 35 | if (strcmp(mtd->name, "firmware")) |
| 36 | return -EINVAL; |
| 37 | |
| 38 | /* Find the end of JFFS2 bootfs partition */ |
| 39 | offset = 0; |
| 40 | do { |
| 41 | err = mtd_read(mtd, offset, sizeof(node), &retlen, (void *)&node); |
| 42 | if (err || retlen != sizeof(node)) |
| 43 | break; |
| 44 | |
| 45 | if (je16_to_cpu(node.magic) != JFFS2_MAGIC_BITMASK) |
| 46 | break; |
| 47 | |
| 48 | offset += je32_to_cpu(node.totlen); |
| 49 | offset = (offset + 0x3) & ~0x3; |
| 50 | } while (offset < mtd->size); |
| 51 | |
| 52 | /* Find rootfs partition that follows the bootfs */ |
| 53 | err = mtd_find_rootfs_from(mtd, mtd->erasesize, mtd->size, &rootfs_offset, &type); |
| 54 | if (err) |
| 55 | return err; |
| 56 | |
| 57 | parts = kzalloc(NR_PARTS * sizeof(*parts), GFP_KERNEL); |
| 58 | if (!parts) |
| 59 | return -ENOMEM; |
| 60 | |
| 61 | parts[0].name = "bootfs"; |
| 62 | parts[0].offset = 0; |
| 63 | parts[0].size = rootfs_offset; |
| 64 | |
| 65 | if (type == MTDSPLIT_PART_TYPE_UBI) |
| 66 | parts[1].name = UBI_PART_NAME; |
| 67 | else |
| 68 | parts[1].name = ROOTFS_PART_NAME; |
| 69 | parts[1].offset = rootfs_offset; |
| 70 | parts[1].size = mtd->size - rootfs_offset; |
| 71 | |
| 72 | *pparts = parts; |
| 73 | |
| 74 | return NR_PARTS; |
| 75 | } |
| 76 | |
| 77 | static const struct of_device_id mtdsplit_cfe_bootfs_of_match_table[] = { |
| 78 | { .compatible = "brcm,bcm4908-firmware" }, |
| 79 | {}, |
| 80 | }; |
| 81 | MODULE_DEVICE_TABLE(of, mtdsplit_cfe_bootfs_of_match_table); |
| 82 | |
| 83 | static struct mtd_part_parser mtdsplit_cfe_bootfs_parser = { |
| 84 | .owner = THIS_MODULE, |
| 85 | .name = "cfe-bootfs", |
| 86 | .of_match_table = mtdsplit_cfe_bootfs_of_match_table, |
| 87 | .parse_fn = mtdsplit_cfe_bootfs_parse, |
| 88 | }; |
| 89 | |
| 90 | module_mtd_part_parser(mtdsplit_cfe_bootfs_parser); |