66da310e84b61494fec209f0d557f682c1fb3c87
[openwrt/openwrt.git] / target / linux / generic / pending-4.14 / 490-ubi-auto-attach-mtd-device-named-ubi-or-data-on-boot.patch
1 From: Daniel Golle <daniel@makrotopia.org>
2 Subject: ubi: auto-attach mtd device named "ubi" or "data" on boot
3
4 Signed-off-by: Daniel Golle <daniel@makrotopia.org>
5 ---
6 drivers/mtd/ubi/build.c | 36 ++++++++++++++++++++++++++++++++++++
7 1 file changed, 36 insertions(+)
8
9 --- a/drivers/mtd/ubi/build.c
10 +++ b/drivers/mtd/ubi/build.c
11 @@ -1171,6 +1171,68 @@ static struct mtd_info * __init open_mtd
12 return mtd;
13 }
14
15 +/*
16 + * This function tries attaching mtd partitions named either "ubi" or "data"
17 + * during boot.
18 + */
19 +static void __init ubi_auto_attach(void)
20 +{
21 + int err;
22 + struct mtd_info *mtd;
23 + loff_t offset = 0;
24 + size_t len;
25 + char magic[4];
26 +
27 + /* try attaching mtd device named "ubi" or "data" */
28 + mtd = open_mtd_device("ubi");
29 + if (IS_ERR(mtd))
30 + mtd = open_mtd_device("data");
31 +
32 + if (IS_ERR(mtd))
33 + return;
34 +
35 + /* get the first not bad block */
36 + if (mtd_can_have_bb(mtd))
37 + while (mtd_block_isbad(mtd, offset)) {
38 + offset += mtd->erasesize;
39 +
40 + if (offset > mtd->size) {
41 + pr_err("UBI error: Failed to find a non-bad "
42 + "block on mtd%d\n", mtd->index);
43 + goto cleanup;
44 + }
45 + }
46 +
47 + /* check for a valid ubi magic if read from flash was successful */
48 + err = mtd_read(mtd, offset, 4, &len, (void *) magic);
49 + if ((!err || mtd_is_bitflip(err)) &&
50 + len == 4 && strncmp(magic, "UBI#", 4)) {
51 + pr_err("UBI error: no valid UBI magic found inside mtd%d\n", mtd->index);
52 + goto cleanup;
53 + }
54 +
55 + /* don't auto-add media types where UBI doesn't makes sense */
56 + if (mtd->type != MTD_NANDFLASH &&
57 + mtd->type != MTD_NORFLASH &&
58 + mtd->type != MTD_DATAFLASH &&
59 + mtd->type != MTD_MLCNANDFLASH)
60 + goto cleanup;
61 +
62 + mutex_lock(&ubi_devices_mutex);
63 + pr_notice("UBI: auto-attach mtd%d\n", mtd->index);
64 + err = ubi_attach_mtd_dev(mtd, UBI_DEV_NUM_AUTO, 0, 0);
65 + mutex_unlock(&ubi_devices_mutex);
66 + if (err < 0) {
67 + pr_err("UBI error: cannot attach mtd%d\n", mtd->index);
68 + goto cleanup;
69 + }
70 +
71 + return;
72 +
73 +cleanup:
74 + put_mtd_device(mtd);
75 +}
76 +
77 static int __init ubi_init(void)
78 {
79 int err, i, k;
80 @@ -1254,6 +1316,12 @@ static int __init ubi_init(void)
81 }
82 }
83
84 + /* auto-attach mtd devices only if built-in to the kernel and no ubi.mtd
85 + * parameter was given */
86 + if (IS_ENABLED(CONFIG_MTD_ROOTFS_ROOT_DEV) &&
87 + !ubi_is_module() && !mtd_devs)
88 + ubi_auto_attach();
89 +
90 err = ubiblock_init();
91 if (err) {
92 pr_err("UBI error: block: cannot initialize, error %d\n", err);