kernel: move mtdsplit files to drivers/mtd/mtdsplit/ to simplify maintenance, unify...
[openwrt/openwrt.git] / target / linux / generic / files / drivers / mtd / mtdsplit / mtdsplit.c
1 /*
2 * Copyright (C) 2009-2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2009-2013 Gabor Juhos <juhosg@openwrt.org>
4 * Copyright (C) 2012 Jonas Gorski <jogo@openwrt.org>
5 * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License version 2 as published
9 * by the Free Software Foundation.
10 *
11 */
12
13 #define pr_fmt(fmt) "mtdsplit: " fmt
14
15 #include <linux/export.h>
16 #include <linux/init.h>
17 #include <linux/kernel.h>
18 #include <linux/magic.h>
19 #include <linux/mtd/mtd.h>
20 #include <linux/mtd/partitions.h>
21 #include <linux/byteorder/generic.h>
22
23 #include "mtdsplit.h"
24
25 struct squashfs_super_block {
26 __le32 s_magic;
27 __le32 pad0[9];
28 __le64 bytes_used;
29 };
30
31 int mtd_get_squashfs_len(struct mtd_info *master,
32 size_t offset,
33 size_t *squashfs_len)
34 {
35 struct squashfs_super_block sb;
36 size_t retlen;
37 int err;
38
39 err = mtd_read(master, offset, sizeof(sb), &retlen, (void *)&sb);
40 if (err || (retlen != sizeof(sb))) {
41 pr_alert("error occured while reading from \"%s\"\n",
42 master->name);
43 return -EIO;
44 }
45
46 if (le32_to_cpu(sb.s_magic) != SQUASHFS_MAGIC) {
47 pr_alert("no squashfs found in \"%s\"\n", master->name);
48 return -EINVAL;
49 }
50
51 retlen = le64_to_cpu(sb.bytes_used);
52 if (retlen <= 0) {
53 pr_alert("squashfs is empty in \"%s\"\n", master->name);
54 return -ENODEV;
55 }
56
57 if (offset + retlen > master->size) {
58 pr_alert("squashfs has invalid size in \"%s\"\n",
59 master->name);
60 return -EINVAL;
61 }
62
63 *squashfs_len = retlen;
64 return 0;
65 }
66 EXPORT_SYMBOL_GPL(mtd_get_squashfs_len);
67
68 static ssize_t mtd_next_eb(struct mtd_info *mtd, size_t offset)
69 {
70 return mtd_rounddown_to_eb(offset, mtd) + mtd->erasesize;
71 }
72
73 int mtd_check_rootfs_magic(struct mtd_info *mtd, size_t offset)
74 {
75 u32 magic;
76 size_t retlen;
77 int ret;
78
79 ret = mtd_read(mtd, offset, sizeof(magic), &retlen,
80 (unsigned char *) &magic);
81 if (ret)
82 return ret;
83
84 if (retlen != sizeof(magic))
85 return -EIO;
86
87 if (le32_to_cpu(magic) != SQUASHFS_MAGIC &&
88 magic != 0x19852003)
89 return -EINVAL;
90
91 return 0;
92 }
93 EXPORT_SYMBOL_GPL(mtd_check_rootfs_magic);
94
95 int mtd_find_rootfs_from(struct mtd_info *mtd,
96 size_t from,
97 size_t limit,
98 size_t *ret_offset)
99 {
100 size_t offset;
101 int err;
102
103 for (offset = from; offset < limit;
104 offset = mtd_next_eb(mtd, offset)) {
105 err = mtd_check_rootfs_magic(mtd, offset);
106 if (err)
107 continue;
108
109 *ret_offset = offset;
110 return 0;
111 }
112
113 return -ENODEV;
114 }
115 EXPORT_SYMBOL_GPL(mtd_find_rootfs_from);
116