kernel: update mtdsplit for linux 4.9
[openwrt/staging/dedeckeh.git] / target / linux / generic / files / drivers / mtd / mtdsplit / mtdsplit_brnimage.c
1 /*
2 * Copyright (C) 2012 John Crispin <blogic@openwrt.org>
3 * Copyright (C) 2015 Martin Blumenstingl <martin.blumenstingl@googlemail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 as published
7 * by the Free Software Foundation.
8 *
9 */
10
11 #include <linux/module.h>
12 #include <linux/init.h>
13 #include <linux/kernel.h>
14 #include <linux/slab.h>
15 #include <linux/mtd/mtd.h>
16 #include <linux/mtd/partitions.h>
17 #include <linux/byteorder/generic.h>
18
19 #include "mtdsplit.h"
20
21 #define BRNIMAGE_NR_PARTS 2
22
23 #define BRNIMAGE_ALIGN_BYTES 0x400
24 #define BRNIMAGE_FOOTER_SIZE 12
25
26 #define BRNIMAGE_MIN_OVERHEAD (BRNIMAGE_FOOTER_SIZE)
27 #define BRNIMAGE_MAX_OVERHEAD (BRNIMAGE_ALIGN_BYTES + BRNIMAGE_FOOTER_SIZE)
28
29 static int mtdsplit_parse_brnimage(struct mtd_info *master,
30 const struct mtd_partition **pparts,
31 struct mtd_part_parser_data *data)
32 {
33 struct mtd_partition *parts;
34 uint32_t buf;
35 unsigned long rootfs_offset, rootfs_size, kernel_size;
36 size_t len;
37 int ret = 0;
38
39 for (rootfs_offset = 0; rootfs_offset < master->size;
40 rootfs_offset += BRNIMAGE_ALIGN_BYTES) {
41 ret = mtd_check_rootfs_magic(master, rootfs_offset, NULL);
42 if (!ret)
43 break;
44 }
45
46 if (ret)
47 return ret;
48
49 if (rootfs_offset >= master->size)
50 return -EINVAL;
51
52 ret = mtd_read(master, rootfs_offset - BRNIMAGE_FOOTER_SIZE, 4, &len,
53 (void *)&buf);
54 if (ret)
55 return ret;
56
57 if (len != 4)
58 return -EIO;
59
60 kernel_size = le32_to_cpu(buf);
61
62 if (kernel_size > (rootfs_offset - BRNIMAGE_MIN_OVERHEAD))
63 return -EINVAL;
64
65 if (kernel_size < (rootfs_offset - BRNIMAGE_MAX_OVERHEAD))
66 return -EINVAL;
67
68 /*
69 * The footer must be untouched as it contains the checksum of the
70 * original brnImage (kernel + squashfs)!
71 */
72 rootfs_size = master->size - rootfs_offset - BRNIMAGE_FOOTER_SIZE;
73
74 parts = kzalloc(BRNIMAGE_NR_PARTS * sizeof(*parts), GFP_KERNEL);
75 if (!parts)
76 return -ENOMEM;
77
78 parts[0].name = KERNEL_PART_NAME;
79 parts[0].offset = 0;
80 parts[0].size = kernel_size;
81
82 parts[1].name = ROOTFS_PART_NAME;
83 parts[1].offset = rootfs_offset;
84 parts[1].size = rootfs_size;
85
86 *pparts = parts;
87 return BRNIMAGE_NR_PARTS;
88 }
89
90 static struct mtd_part_parser mtdsplit_brnimage_parser = {
91 .owner = THIS_MODULE,
92 .name = "brnimage-fw",
93 .parse_fn = mtdsplit_parse_brnimage,
94 .type = MTD_PARSER_TYPE_FIRMWARE,
95 };
96
97 static int __init mtdsplit_brnimage_init(void)
98 {
99 register_mtd_parser(&mtdsplit_brnimage_parser);
100
101 return 0;
102 }
103
104 subsys_initcall(mtdsplit_brnimage_init);