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