kernel: improve ubi auto attach code readability
[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,54 @@ 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 + size_t len;
24 + char magic[4];
25 +
26 + /* try attaching mtd device named "ubi" or "data" */
27 + mtd = open_mtd_device("ubi");
28 + if (IS_ERR(mtd))
29 + mtd = open_mtd_device("data");
30 +
31 + if (IS_ERR(mtd))
32 + return;
33 +
34 + /* check for a valid ubi magic if read from flash was successful */
35 + err = mtd_read(mtd, 0, 4, &len, (void *) magic);
36 + if (!err && len == 4 && strncmp(magic, "UBI#", 4)) {
37 + pr_err("UBI error: no valid UBI magic found inside mtd%d\n", mtd->index);
38 + goto cleanup;
39 + }
40 +
41 + /* don't auto-add media types where UBI doesn't makes sense */
42 + if (mtd->type != MTD_NANDFLASH &&
43 + mtd->type != MTD_NORFLASH &&
44 + mtd->type != MTD_DATAFLASH &&
45 + mtd->type != MTD_MLCNANDFLASH)
46 + goto cleanup;
47 +
48 + mutex_lock(&ubi_devices_mutex);
49 + pr_notice("UBI: auto-attach mtd%d\n", mtd->index);
50 + err = ubi_attach_mtd_dev(mtd, UBI_DEV_NUM_AUTO, 0, 0);
51 + mutex_unlock(&ubi_devices_mutex);
52 + if (err < 0) {
53 + pr_err("UBI error: cannot attach mtd%d\n", mtd->index);
54 + goto cleanup;
55 + }
56 +
57 + return;
58 +
59 +cleanup:
60 + put_mtd_device(mtd);
61 +}
62 +
63 static int __init ubi_init(void)
64 {
65 int err, i, k;
66 @@ -1254,6 +1302,12 @@ static int __init ubi_init(void)
67 }
68 }
69
70 + /* auto-attach mtd devices only if built-in to the kernel and no ubi.mtd
71 + * parameter was given */
72 + if (IS_ENABLED(CONFIG_MTD_ROOTFS_ROOT_DEV) &&
73 + !ubi_is_module() && !mtd_devs)
74 + ubi_auto_attach();
75 +
76 err = ubiblock_init();
77 if (err) {
78 pr_err("UBI error: block: cannot initialize, error %d\n", err);