libfstools: make mtd_volume_identify() less chatty
[project/fstools.git] / block.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #define _GNU_SOURCE
16 #include <getopt.h>
17 #include <stdio.h>
18 #include <unistd.h>
19 #include <syslog.h>
20 #include <libgen.h>
21 #include <glob.h>
22 #include <dirent.h>
23 #include <stdarg.h>
24 #include <string.h>
25
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/swap.h>
29 #include <sys/mount.h>
30 #include <sys/wait.h>
31
32 #include <uci.h>
33 #include <uci_blob.h>
34
35 #include <libubox/ulog.h>
36 #include <libubox/list.h>
37 #include <libubox/vlist.h>
38 #include <libubox/blobmsg_json.h>
39 #include <libubox/avl-cmp.h>
40
41 #include "libblkid-tiny/libblkid-tiny.h"
42
43 #ifdef UBIFS_EXTROOT
44 #include "libubi/libubi.h"
45 #endif
46
47 enum {
48         TYPE_MOUNT,
49         TYPE_SWAP,
50 };
51
52 struct mount {
53         struct vlist_node node;
54         int type;
55
56         char *target;
57         char *path;
58         char *options;
59         uint32_t flags;
60         char *uuid;
61         char *label;
62         char *device;
63         int extroot;
64         int overlay;
65         int disabled_fsck;
66         unsigned int prio;
67 };
68
69 static struct vlist_tree mounts;
70 static struct blob_buf b;
71 static LIST_HEAD(devices);
72 static int anon_mount, anon_swap, auto_mount, auto_swap, check_fs;
73 static unsigned int delay_root;
74
75 enum {
76         CFG_ANON_MOUNT,
77         CFG_ANON_SWAP,
78         CFG_AUTO_MOUNT,
79         CFG_AUTO_SWAP,
80         CFG_DELAY_ROOT,
81         CFG_CHECK_FS,
82         __CFG_MAX
83 };
84
85 static const struct blobmsg_policy config_policy[__CFG_MAX] = {
86         [CFG_ANON_SWAP] = { .name = "anon_swap", .type = BLOBMSG_TYPE_INT32 },
87         [CFG_ANON_MOUNT] = { .name = "anon_mount", .type = BLOBMSG_TYPE_INT32 },
88         [CFG_AUTO_SWAP] = { .name = "auto_swap", .type = BLOBMSG_TYPE_INT32 },
89         [CFG_AUTO_MOUNT] = { .name = "auto_mount", .type = BLOBMSG_TYPE_INT32 },
90         [CFG_DELAY_ROOT] = { .name = "delay_root", .type = BLOBMSG_TYPE_INT32 },
91         [CFG_CHECK_FS] = { .name = "check_fs", .type = BLOBMSG_TYPE_INT32 },
92 };
93
94 enum {
95         MOUNT_UUID,
96         MOUNT_LABEL,
97         MOUNT_ENABLE,
98         MOUNT_TARGET,
99         MOUNT_DEVICE,
100         MOUNT_OPTIONS,
101         __MOUNT_MAX
102 };
103
104 static const struct uci_blob_param_list config_attr_list = {
105         .n_params = __CFG_MAX,
106         .params = config_policy,
107 };
108
109 static const struct blobmsg_policy mount_policy[__MOUNT_MAX] = {
110         [MOUNT_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
111         [MOUNT_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
112         [MOUNT_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
113         [MOUNT_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
114         [MOUNT_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_STRING },
115         [MOUNT_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
116 };
117
118 static const struct uci_blob_param_list mount_attr_list = {
119         .n_params = __MOUNT_MAX,
120         .params = mount_policy,
121 };
122
123 enum {
124         SWAP_ENABLE,
125         SWAP_UUID,
126         SWAP_LABEL,
127         SWAP_DEVICE,
128         SWAP_PRIO,
129         __SWAP_MAX
130 };
131
132 static const struct blobmsg_policy swap_policy[__SWAP_MAX] = {
133         [SWAP_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
134         [SWAP_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
135         [SWAP_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
136         [SWAP_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
137         [SWAP_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
138 };
139
140 static const struct uci_blob_param_list swap_attr_list = {
141         .n_params = __SWAP_MAX,
142         .params = swap_policy,
143 };
144
145 struct mount_flag {
146         const char *name;
147         int32_t flag;
148 };
149
150 #ifndef MS_DIRSYNC
151 #       define MS_DIRSYNC               (1 << 7)
152 #endif
153
154 #ifndef MS_RELATIME
155 #       define MS_RELATIME              (1 << 21)
156 #endif
157
158 #ifndef MS_STRICTATIME
159 #       define MS_STRICTATIME   (1 << 24)
160 #endif
161
162 static const struct mount_flag mount_flags[] = {
163         { "sync",               MS_SYNCHRONOUS  },
164         { "async",              ~MS_SYNCHRONOUS },
165         { "dirsync",            MS_DIRSYNC      },
166         { "mand",               MS_MANDLOCK     },
167         { "nomand",             ~MS_MANDLOCK    },
168         { "atime",              ~MS_NOATIME     },
169         { "noatime",            MS_NOATIME      },
170         { "dev",                ~MS_NODEV       },
171         { "nodev",              MS_NODEV        },
172         { "diratime",           ~MS_NODIRATIME  },
173         { "nodiratime",         MS_NODIRATIME   },
174         { "exec",               ~MS_NOEXEC      },
175         { "noexec",             MS_NOEXEC       },
176         { "suid",               ~MS_NOSUID      },
177         { "nosuid",             MS_NOSUID       },
178         { "rw",                 ~MS_RDONLY      },
179         { "ro",                 MS_RDONLY       },
180         { "relatime",           MS_RELATIME     },
181         { "norelatime",         ~MS_RELATIME    },
182         { "strictatime",        MS_STRICTATIME  },
183 };
184
185 static char *blobmsg_get_strdup(struct blob_attr *attr)
186 {
187         if (!attr)
188                 return NULL;
189
190         return strdup(blobmsg_get_string(attr));
191 }
192
193 static char *blobmsg_get_basename(struct blob_attr *attr)
194 {
195         if (!attr)
196                 return NULL;
197
198         return strdup(basename(blobmsg_get_string(attr)));
199 }
200
201 static void parse_mount_options(struct mount *m, char *optstr)
202 {
203         int i;
204         bool is_flag;
205         char *p, *opts, *last;
206
207         m->flags = 0;
208         m->options = NULL;
209
210         if (!optstr || !*optstr)
211                 return;
212
213         m->options = opts = calloc(1, strlen(optstr) + 1);
214
215         if (!m->options)
216                 return;
217
218         p = last = optstr;
219
220         do {
221                 p = strchr(p, ',');
222
223                 if (p)
224                         *p++ = 0;
225
226                 for (i = 0, is_flag = false; i < ARRAY_SIZE(mount_flags); i++) {
227                         if (!strcmp(last, mount_flags[i].name)) {
228                                 if (mount_flags[i].flag < 0)
229                                         m->flags &= (uint32_t)mount_flags[i].flag;
230                                 else
231                                         m->flags |= (uint32_t)mount_flags[i].flag;
232                                 is_flag = true;
233                                 break;
234                         }
235                 }
236
237                 if (!is_flag)
238                         opts += sprintf(opts, "%s%s", (opts > m->options) ? "," : "", last);
239
240                 last = p;
241
242         } while (p);
243
244         free(optstr);
245 }
246
247 static int mount_add(struct uci_section *s)
248 {
249         struct blob_attr *tb[__MOUNT_MAX] = { 0 };
250         struct mount *m;
251
252         blob_buf_init(&b, 0);
253         uci_to_blob(&b, s, &mount_attr_list);
254         blobmsg_parse(mount_policy, __MOUNT_MAX, tb, blob_data(b.head), blob_len(b.head));
255
256         if (!tb[MOUNT_LABEL] && !tb[MOUNT_UUID] && !tb[MOUNT_DEVICE])
257                 return -1;
258
259         if (tb[MOUNT_ENABLE] && !blobmsg_get_u32(tb[MOUNT_ENABLE]))
260                 return -1;
261
262         m = malloc(sizeof(struct mount));
263         m->type = TYPE_MOUNT;
264         m->uuid = blobmsg_get_strdup(tb[MOUNT_UUID]);
265         m->label = blobmsg_get_strdup(tb[MOUNT_LABEL]);
266         m->target = blobmsg_get_strdup(tb[MOUNT_TARGET]);
267         m->device = blobmsg_get_basename(tb[MOUNT_DEVICE]);
268
269         parse_mount_options(m, blobmsg_get_strdup(tb[MOUNT_OPTIONS]));
270
271         m->overlay = m->extroot = 0;
272         if (m->target && !strcmp(m->target, "/"))
273                 m->extroot = 1;
274         if (m->target && !strcmp(m->target, "/overlay"))
275                 m->extroot = m->overlay = 1;
276
277         if (m->uuid)
278                 vlist_add(&mounts, &m->node, m->uuid);
279         else if (m->label)
280                 vlist_add(&mounts, &m->node, m->label);
281         else if (m->device)
282                 vlist_add(&mounts, &m->node, m->device);
283
284         return 0;
285 }
286
287 static int swap_add(struct uci_section *s)
288 {
289         struct blob_attr *tb[__SWAP_MAX] = { 0 };
290         struct mount *m;
291
292         blob_buf_init(&b, 0);
293         uci_to_blob(&b, s, &swap_attr_list);
294         blobmsg_parse(swap_policy, __SWAP_MAX, tb, blob_data(b.head), blob_len(b.head));
295
296         if (!tb[SWAP_UUID] && !tb[SWAP_LABEL] && !tb[SWAP_DEVICE])
297                 return -1;
298
299         m = malloc(sizeof(struct mount));
300         memset(m, 0, sizeof(struct mount));
301         m->type = TYPE_SWAP;
302         m->uuid = blobmsg_get_strdup(tb[SWAP_UUID]);
303         m->label = blobmsg_get_strdup(tb[SWAP_LABEL]);
304         m->device = blobmsg_get_basename(tb[SWAP_DEVICE]);
305         if (tb[SWAP_PRIO])
306                 m->prio = blobmsg_get_u32(tb[SWAP_PRIO]);
307         if (m->prio)
308                 m->prio = ((m->prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
309
310         if ((!tb[SWAP_ENABLE]) || blobmsg_get_u32(tb[SWAP_ENABLE])) {
311                 /* store complete swap path */
312                 if (tb[SWAP_DEVICE])
313                         m->target = blobmsg_get_strdup(tb[SWAP_DEVICE]);
314
315                 if (m->uuid)
316                         vlist_add(&mounts, &m->node, m->uuid);
317                 else if (m->label)
318                         vlist_add(&mounts, &m->node, m->label);
319                 else if (m->device)
320                         vlist_add(&mounts, &m->node, m->device);
321         }
322
323         return 0;
324 }
325
326 static int global_add(struct uci_section *s)
327 {
328         struct blob_attr *tb[__CFG_MAX] = { 0 };
329
330         blob_buf_init(&b, 0);
331         uci_to_blob(&b, s, &config_attr_list);
332         blobmsg_parse(config_policy, __CFG_MAX, tb, blob_data(b.head), blob_len(b.head));
333
334         if ((tb[CFG_ANON_MOUNT]) && blobmsg_get_u32(tb[CFG_ANON_MOUNT]))
335                 anon_mount = 1;
336         if ((tb[CFG_ANON_SWAP]) && blobmsg_get_u32(tb[CFG_ANON_SWAP]))
337                 anon_swap = 1;
338
339         if ((tb[CFG_AUTO_MOUNT]) && blobmsg_get_u32(tb[CFG_AUTO_MOUNT]))
340                 auto_mount = 1;
341         if ((tb[CFG_AUTO_SWAP]) && blobmsg_get_u32(tb[CFG_AUTO_SWAP]))
342                 auto_swap = 1;
343
344         if (tb[CFG_DELAY_ROOT])
345                 delay_root = blobmsg_get_u32(tb[CFG_DELAY_ROOT]);
346
347         if ((tb[CFG_CHECK_FS]) && blobmsg_get_u32(tb[CFG_CHECK_FS]))
348                 check_fs = 1;
349
350         return 0;
351 }
352
353 static struct mount* find_swap(const char *uuid, const char *label, const char *device)
354 {
355         struct mount *m;
356
357         vlist_for_each_element(&mounts, m, node) {
358                 if (m->type != TYPE_SWAP)
359                         continue;
360                 if (uuid && m->uuid && !strcasecmp(m->uuid, uuid))
361                         return m;
362                 if (label && m->label && !strcmp(m->label, label))
363                         return m;
364                 if (device && m->device && !strcmp(m->device, device))
365                         return m;
366         }
367
368         return NULL;
369 }
370
371 static struct mount* find_block(const char *uuid, const char *label, const char *device,
372                                 const char *target)
373 {
374         struct mount *m;
375
376         vlist_for_each_element(&mounts, m, node) {
377                 if (m->type != TYPE_MOUNT)
378                         continue;
379                 if (m->uuid && uuid && !strcasecmp(m->uuid, uuid))
380                         return m;
381                 if (m->label && label && !strcmp(m->label, label))
382                         return m;
383                 if (m->target && target && !strcmp(m->target, target))
384                         return m;
385                 if (m->device && device && !strcmp(m->device, device))
386                         return m;
387         }
388
389         return NULL;
390 }
391
392 static void mounts_update(struct vlist_tree *tree, struct vlist_node *node_new,
393                           struct vlist_node *node_old)
394 {
395 }
396
397 static struct uci_package * config_try_load(struct uci_context *ctx, char *path)
398 {
399         char *file = basename(path);
400         char *dir = dirname(path);
401         char *err;
402         struct uci_package *pkg;
403
404         uci_set_confdir(ctx, dir);
405         ULOG_INFO("attempting to load %s/%s\n", dir, file);
406
407         if (uci_load(ctx, file, &pkg)) {
408                 uci_get_errorstr(ctx, &err, file);
409                 ULOG_ERR("unable to load configuration (%s)\n", err);
410
411                 free(err);
412                 return NULL;
413         }
414
415         return pkg;
416 }
417
418 static int config_load(char *cfg)
419 {
420         struct uci_context *ctx = uci_alloc_context();
421         struct uci_package *pkg = NULL;
422         struct uci_element *e;
423         char path[64];
424
425         vlist_init(&mounts, avl_strcmp, mounts_update);
426
427         if (cfg) {
428                 snprintf(path, sizeof(path), "%s/upper/etc/config/fstab", cfg);
429                 pkg = config_try_load(ctx, path);
430
431                 if (!pkg) {
432                         snprintf(path, sizeof(path), "%s/etc/config/fstab", cfg);
433                         pkg = config_try_load(ctx, path);
434                 }
435         }
436
437         if (!pkg) {
438                 snprintf(path, sizeof(path), "/etc/config/fstab");
439                 pkg = config_try_load(ctx, path);
440         }
441
442         if (!pkg) {
443                 ULOG_ERR("no usable configuration\n");
444                 return -1;
445         }
446
447         vlist_update(&mounts);
448         uci_foreach_element(&pkg->sections, e) {
449                 struct uci_section *s = uci_to_section(e);
450
451                 if (!strcmp(s->type, "mount"))
452                         mount_add(s);
453                 if (!strcmp(s->type, "swap"))
454                         swap_add(s);
455                 if (!strcmp(s->type, "global"))
456                         global_add(s);
457         }
458         vlist_flush(&mounts);
459
460         return 0;
461 }
462
463 static struct blkid_struct_probe* _probe_path(char *path)
464 {
465         struct blkid_struct_probe *pr;
466
467         pr = malloc(sizeof(*pr));
468
469         if (!pr)
470                 return NULL;
471
472         memset(pr, 0, sizeof(*pr));
473         probe_block(path, pr);
474
475         if (pr->err || !pr->id) {
476                 free(pr);
477                 return NULL;
478         }
479
480         return pr;
481 }
482
483 static int _cache_load(const char *path)
484 {
485         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
486         int j;
487         glob_t gl;
488
489         if (glob(path, gl_flags, NULL, &gl) < 0)
490                 return -1;
491
492         for (j = 0; j < gl.gl_pathc; j++) {
493                 struct blkid_struct_probe *pr = _probe_path(gl.gl_pathv[j]);
494                 if (pr)
495                         list_add_tail(&pr->list, &devices);
496         }
497
498         globfree(&gl);
499
500         return 0;
501 }
502
503 static void cache_load(int mtd)
504 {
505         if (mtd) {
506                 _cache_load("/dev/mtdblock*");
507                 _cache_load("/dev/ubiblock*");
508                 _cache_load("/dev/ubi?*_?*");
509         }
510         _cache_load("/dev/mmcblk*");
511         _cache_load("/dev/sd*");
512         _cache_load("/dev/hd*");
513         _cache_load("/dev/md*");
514         _cache_load("/dev/vd*");
515         _cache_load("/dev/mapper/*");
516 }
517
518 static int print_block_info(struct blkid_struct_probe *pr)
519 {
520         printf("%s:", pr->dev);
521         if (pr->uuid[0])
522                 printf(" UUID=\"%s\"", pr->uuid);
523
524         if (pr->label[0])
525                 printf(" LABEL=\"%s\"", pr->label);
526
527         if (pr->name[0])
528                 printf(" NAME=\"%s\"", pr->name);
529
530         if (pr->version[0])
531                 printf(" VERSION=\"%s\"", pr->version);
532
533         printf(" TYPE=\"%s\"\n", pr->id->name);
534
535         return 0;
536 }
537
538 static int print_block_uci(struct blkid_struct_probe *pr)
539 {
540         if (!strcmp(pr->id->name, "swap")) {
541                 printf("config 'swap'\n");
542         } else {
543                 printf("config 'mount'\n");
544                 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
545         }
546         if (pr->uuid[0])
547                 printf("\toption\tuuid\t'%s'\n", pr->uuid);
548         else
549                 printf("\toption\tdevice\t'%s'\n", pr->dev);
550         printf("\toption\tenabled\t'0'\n\n");
551
552         return 0;
553 }
554
555 static struct blkid_struct_probe* find_block_info(char *uuid, char *label, char *path)
556 {
557         struct blkid_struct_probe *pr = NULL;
558
559         if (uuid)
560                 list_for_each_entry(pr, &devices, list)
561                         if (!strcasecmp(pr->uuid, uuid))
562                                 return pr;
563
564         if (label)
565                 list_for_each_entry(pr, &devices, list)
566                         if (!strcmp(pr->label, label))
567                                 return pr;
568
569         if (path)
570                 list_for_each_entry(pr, &devices, list)
571                         if (!strcmp(basename(pr->dev), basename(path)))
572                                 return pr;
573
574         return NULL;
575 }
576
577 static char* find_mount_point(char *block)
578 {
579         FILE *fp = fopen("/proc/mounts", "r");
580         static char line[256];
581         int len = strlen(block);
582         char *point = NULL;
583
584         if(!fp)
585                 return NULL;
586
587         while (fgets(line, sizeof(line), fp)) {
588                 if (!strncmp(line, block, len)) {
589                         char *p = &line[len + 1];
590                         char *t = strstr(p, " ");
591
592                         if (!t) {
593                                 fclose(fp);
594                                 return NULL;
595                         }
596                         *t = '\0';
597                         point = p;
598                         break;
599                 }
600         }
601
602         fclose(fp);
603
604         return point;
605 }
606
607 static void mkdir_p(char *dir)
608 {
609         char *l = strrchr(dir, '/');
610
611         if (l) {
612                 *l = '\0';
613                 mkdir_p(dir);
614                 *l = '/';
615                 mkdir(dir, 0755);
616         }
617 }
618
619 static void check_filesystem(struct blkid_struct_probe *pr)
620 {
621         pid_t pid;
622         struct stat statbuf;
623         char *e2fsck = "/usr/sbin/e2fsck";
624
625         /* UBIFS does not need stuff like fsck */
626         if (!strncmp(pr->id->name, "ubifs", 5))
627                 return;
628
629         if (strncmp(pr->id->name, "ext", 3)) {
630                 ULOG_ERR("check_filesystem: %s is not supported\n", pr->id->name);
631                 return;
632         }
633
634         if (stat(e2fsck, &statbuf) < 0) {
635                 ULOG_ERR("check_filesystem: %s not found\n", e2fsck);
636                 return;
637         }
638
639         pid = fork();
640         if (!pid) {
641                 execl(e2fsck, e2fsck, "-p", pr->dev, NULL);
642                 exit(-1);
643         } else if (pid > 0) {
644                 int status;
645
646                 waitpid(pid, &status, 0);
647                 if (WEXITSTATUS(status))
648                         ULOG_ERR("check_filesystem: %s returned %d\n", e2fsck, WEXITSTATUS(status));
649         }
650 }
651
652 static void handle_swapfiles(bool on)
653 {
654         struct stat s;
655         struct mount *m;
656         struct blkid_struct_probe *pr;
657
658         vlist_for_each_element(&mounts, m, node)
659         {
660                 if (m->type != TYPE_SWAP || !m->target)
661                         continue;
662
663                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
664                         continue;
665
666                 pr = _probe_path(m->target);
667
668                 if (!pr)
669                         continue;
670
671                 if (!strcmp(pr->id->name, "swap")) {
672                         if (on)
673                                 swapon(pr->dev, m->prio);
674                         else
675                                 swapoff(pr->dev);
676                 }
677
678                 free(pr);
679         }
680 }
681
682 static int mount_device(struct blkid_struct_probe *pr, int hotplug)
683 {
684         struct mount *m;
685         char *device;
686
687         if (!pr)
688                 return -1;
689
690         device = basename(pr->dev);
691
692         if (!strcmp(pr->id->name, "swap")) {
693                 if (hotplug && !auto_swap)
694                         return -1;
695                 m = find_swap(pr->uuid, pr->label, device);
696                 if (m || anon_swap)
697                         swapon(pr->dev, (m) ? (m->prio) : (0));
698
699                 return 0;
700         }
701
702         if (hotplug && !auto_mount)
703                 return -1;
704
705         if (find_mount_point(pr->dev)) {
706                 ULOG_ERR("%s is already mounted\n", pr->dev);
707                 return -1;
708         }
709
710         m = find_block(pr->uuid, pr->label, device, NULL);
711         if (m && m->extroot)
712                 return -1;
713
714         if (m) {
715                 char *target = m->target;
716                 char _target[32];
717                 int err = 0;
718
719                 if (!target) {
720                         snprintf(_target, sizeof(_target), "/mnt/%s", device);
721                         target = _target;
722                 }
723                 mkdir_p(target);
724
725                 if (check_fs)
726                         check_filesystem(pr);
727
728                 err = mount(pr->dev, target, pr->id->name, m->flags,
729                             (m->options) ? (m->options) : (""));
730                 if (err)
731                         ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
732                                  pr->dev, pr->id->name, target, err, strerror(err));
733                 else
734                         handle_swapfiles(true);
735                 return err;
736         }
737
738         if (anon_mount) {
739                 char target[] = "/mnt/mmcblk123";
740                 int err = 0;
741
742                 snprintf(target, sizeof(target), "/mnt/%s", device);
743                 mkdir_p(target);
744
745                 if (check_fs)
746                         check_filesystem(pr);
747
748                 err = mount(pr->dev, target, pr->id->name, 0, "");
749                 if (err)
750                         ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
751                                  pr->dev, pr->id->name, target, err, strerror(err));
752                 else
753                         handle_swapfiles(true);
754                 return err;
755         }
756
757         return 0;
758 }
759
760 static int umount_device(struct blkid_struct_probe *pr)
761 {
762         struct mount *m;
763         char *device = basename(pr->dev);
764         char *mp;
765         int err;
766
767         if (!pr)
768                 return -1;
769
770         if (!strcmp(pr->id->name, "swap"))
771                 return -1;
772
773         mp = find_mount_point(pr->dev);
774         if (!mp)
775                 return -1;
776
777         m = find_block(pr->uuid, pr->label, device, NULL);
778         if (m && m->extroot)
779                 return -1;
780
781         err = umount2(mp, MNT_DETACH);
782         if (err)
783                 ULOG_ERR("unmounting %s (%s)  failed (%d) - %s\n",
784                          pr->dev, mp, err, strerror(err));
785         else
786                 ULOG_INFO("unmounted %s (%s)\n",
787                           pr->dev, mp);
788
789         return err;
790 }
791
792 static int main_hotplug(int argc, char **argv)
793 {
794         char path[32];
795         char *action, *device, *mount_point;
796
797         action = getenv("ACTION");
798         device = getenv("DEVNAME");
799
800         if (!action || !device)
801                 return -1;
802         snprintf(path, sizeof(path), "/dev/%s", device);
803
804         if (!strcmp(action, "remove")) {
805                 int err = 0;
806                 mount_point = find_mount_point(path);
807                 if (mount_point)
808                         err = umount2(mount_point, MNT_DETACH);
809
810                 if (err)
811                         ULOG_ERR("umount of %s failed (%d) - %s\n",
812                                  mount_point, err, strerror(err));
813
814                 return 0;
815         } else if (strcmp(action, "add")) {
816                 ULOG_ERR("Unkown action %s\n", action);
817
818                 return -1;
819         }
820
821         if (config_load(NULL))
822                 return -1;
823         cache_load(0);
824
825         return mount_device(find_block_info(NULL, NULL, path), 1);
826 }
827
828 static int find_block_mtd(char *name, char *part, int plen)
829 {
830         FILE *fp = fopen("/proc/mtd", "r");
831         static char line[256];
832         char *index = NULL;
833
834         if(!fp)
835                 return -1;
836
837         while (!index && fgets(line, sizeof(line), fp)) {
838                 if (strstr(line, name)) {
839                         char *eol = strstr(line, ":");
840
841                         if (!eol)
842                                 continue;
843
844                         *eol = '\0';
845                         index = &line[3];
846                 }
847         }
848
849         fclose(fp);
850
851         if (!index)
852                 return -1;
853
854         snprintf(part, plen, "/dev/mtdblock%s", index);
855
856         return 0;
857 }
858
859 #ifdef UBIFS_EXTROOT
860 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
861 {
862         int dev = 0;
863
864         while (ubi_dev_present(libubi, dev))
865         {
866                 struct ubi_dev_info dev_info;
867                 struct ubi_vol_info vol_info;
868
869                 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
870                         continue;
871                 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
872                         continue;
873
874                 *dev_num = dev_info.dev_num;
875                 *vol_id = vol_info.vol_id;
876
877                 return 0;
878         }
879
880         return -1;
881 }
882
883 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
884 {
885         int dev_num;
886         int vol_id;
887         int err = -1;
888
889         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
890         if (!err)
891                 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
892
893         return err;
894 }
895
896 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
897 {
898         int dev_num;
899         int vol_id;
900         int err = -1;
901
902         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
903         if (!err)
904                 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
905
906         return err;
907 }
908
909 #else
910
911 static int find_root_dev(char *buf, int len)
912 {
913         DIR *d;
914         dev_t root;
915         struct stat s;
916         struct dirent *e;
917
918         if (stat("/", &s))
919                 return -1;
920
921         if (!(d = opendir("/dev")))
922                 return -1;
923
924         root = s.st_dev;
925
926         while ((e = readdir(d)) != NULL) {
927                 snprintf(buf, len, "/dev/%s", e->d_name);
928
929                 if (stat(buf, &s) || s.st_rdev != root)
930                         continue;
931
932                 closedir(d);
933                 return 0;
934         }
935
936         closedir(d);
937         return -1;
938 }
939
940 #endif
941
942 static int test_fs_support(const char *name)
943 {
944         char line[128], *p;
945         int rv = -1;
946         FILE *f;
947
948         if ((f = fopen("/proc/filesystems", "r")) != NULL) {
949                 while (fgets(line, sizeof(line), f)) {
950                         p = strtok(line, "\t\n");
951
952                         if (p && !strcmp(p, "nodev"))
953                                 p = strtok(NULL, "\t\n");
954
955                         if (p && !strcmp(p, name)) {
956                                 rv = 0;
957                                 break;
958                         }
959                 }
960                 fclose(f);
961         }
962
963         return rv;
964 }
965
966 static int check_extroot(char *path)
967 {
968         struct blkid_struct_probe *pr = NULL;
969         char devpath[32];
970
971 #ifdef UBIFS_EXTROOT
972         if (find_block_mtd("rootfs", devpath, sizeof(devpath))) {
973                 int err = -1;
974                 libubi_t libubi;
975
976                 libubi = libubi_open();
977                 err = find_block_ubi_RO(libubi, "rootfs", devpath, sizeof(devpath));
978                 libubi_close(libubi);
979                 if (err)
980                         return -1;
981         }
982 #else
983         if (find_block_mtd("rootfs", devpath, sizeof(devpath))) {
984                 if (find_root_dev(devpath, sizeof(devpath))) {
985                         ULOG_ERR("extroot: unable to determine root device\n");
986                         return -1;
987                 }
988         }
989 #endif
990
991         list_for_each_entry(pr, &devices, list) {
992                 if (!strcmp(pr->dev, devpath)) {
993                         struct stat s;
994                         FILE *fp = NULL;
995                         char tag[64];
996                         char uuid[64] = { 0 };
997
998                         snprintf(tag, sizeof(tag), "%s/etc", path);
999                         if (stat(tag, &s))
1000                                 mkdir_p(tag);
1001
1002                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
1003                         if (stat(tag, &s)) {
1004                                 fp = fopen(tag, "w+");
1005                                 if (!fp) {
1006                                         ULOG_ERR("extroot: failed to write UUID to %s: %d (%s)\n",
1007                                                  tag, errno, strerror(errno));
1008                                         /* return 0 to continue boot regardless of error */
1009                                         return 0;
1010                                 }
1011                                 fputs(pr->uuid, fp);
1012                                 fclose(fp);
1013                                 return 0;
1014                         }
1015
1016                         fp = fopen(tag, "r");
1017                         if (!fp) {
1018                                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1019                                          tag, errno, strerror(errno));
1020                                 return -1;
1021                         }
1022
1023                         fgets(uuid, sizeof(uuid), fp);
1024                         fclose(fp);
1025
1026                         if (!strcasecmp(uuid, pr->uuid))
1027                                 return 0;
1028
1029                         ULOG_ERR("extroot: UUID mismatch (root: %s, %s: %s)\n",
1030                                  pr->uuid, basename(path), uuid);
1031                         return -1;
1032                 }
1033         }
1034
1035         ULOG_ERR("extroot: unable to lookup root device %s\n", devpath);
1036         return -1;
1037 }
1038
1039 /*
1040  * Read info about extroot from UCI (using prefix) and mount it.
1041  */
1042 static int mount_extroot(char *cfg)
1043 {
1044         char overlay[] = "/tmp/extroot/overlay";
1045         char mnt[] = "/tmp/extroot/mnt";
1046         char *path = mnt;
1047         struct blkid_struct_probe *pr;
1048         struct mount *m;
1049         int err = -1;
1050
1051         /* Load @cfg/etc/config/fstab */
1052         if (config_load(cfg))
1053                 return -2;
1054
1055         /* See if there is extroot-specific mount config */
1056         m = find_block(NULL, NULL, NULL, "/");
1057         if (!m)
1058                 m = find_block(NULL, NULL, NULL, "/overlay");
1059
1060         if (!m || !m->extroot)
1061         {
1062                 ULOG_INFO("extroot: not configured\n");
1063                 return -1;
1064         }
1065
1066         /* Find block device pointed by the mount config */
1067         pr = find_block_info(m->uuid, m->label, m->device);
1068
1069         if (!pr && delay_root){
1070                 ULOG_INFO("extroot: device not present, retrying in %u seconds\n", delay_root);
1071                 sleep(delay_root);
1072                 mkblkdev();
1073                 cache_load(0);
1074                 pr = find_block_info(m->uuid, m->label, m->device);
1075         }
1076         if (pr) {
1077                 if (strncmp(pr->id->name, "ext", 3) &&
1078                     strncmp(pr->id->name, "ubifs", 5)) {
1079                         ULOG_ERR("extroot: unsupported filesystem %s, try ext4\n", pr->id->name);
1080                         return -1;
1081                 }
1082
1083                 if (test_fs_support(pr->id->name)) {
1084                         ULOG_ERR("extroot: filesystem %s not supported by kernel\n", pr->id->name);
1085                         return -1;
1086                 }
1087
1088                 if (m->overlay)
1089                         path = overlay;
1090                 mkdir_p(path);
1091
1092                 if (check_fs)
1093                         check_filesystem(pr);
1094
1095                 err = mount(pr->dev, path, pr->id->name, 0, (m->options) ? (m->options) : (""));
1096
1097                 if (err) {
1098                         ULOG_ERR("extroot: mounting %s (%s) on %s failed: %d (%s)\n",
1099                                  pr->dev, pr->id->name, path, err, strerror(err));
1100                 } else if (m->overlay) {
1101                         err = check_extroot(path);
1102                         if (err)
1103                                 umount(path);
1104                 }
1105         } else {
1106                 ULOG_ERR("extroot: cannot find device %s%s\n",
1107                          (m->uuid ? "with UUID " : (m->label ? "with label " : "")),
1108                          (m->uuid ? m->uuid : (m->label ? m->label : m->device)));
1109         }
1110
1111         return err;
1112 }
1113
1114 static int main_extroot(int argc, char **argv)
1115 {
1116         struct blkid_struct_probe *pr;
1117         char blkdev_path[32] = { 0 };
1118         int err = -1;
1119 #ifdef UBIFS_EXTROOT
1120         libubi_t libubi;
1121 #endif
1122
1123         if (!getenv("PREINIT"))
1124                 return -1;
1125
1126         if (argc != 2) {
1127                 ULOG_ERR("Usage: block extroot\n");
1128                 return -1;
1129         }
1130
1131         mkblkdev();
1132         cache_load(1);
1133
1134         /* enable LOG_INFO messages */
1135         ulog_threshold(LOG_INFO);
1136
1137         /*
1138          * Look for "rootfs_data". We will want to mount it and check for
1139          * extroot configuration.
1140          */
1141
1142         /* Start with looking for MTD partition */
1143         find_block_mtd("rootfs_data", blkdev_path, sizeof(blkdev_path));
1144         if (blkdev_path[0]) {
1145                 pr = find_block_info(NULL, NULL, blkdev_path);
1146                 if (pr && !strcmp(pr->id->name, "jffs2")) {
1147                         char cfg[] = "/tmp/jffs_cfg";
1148
1149                         /*
1150                          * Mount MTD part and try extroot (using
1151                          * /etc/config/fstab from that partition)
1152                          */
1153                         mkdir_p(cfg);
1154                         if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1155                                 err = mount_extroot(cfg);
1156                                 umount2(cfg, MNT_DETACH);
1157                         }
1158                         if (err < 0)
1159                                 rmdir("/tmp/overlay");
1160                         rmdir(cfg);
1161                         return err;
1162                 }
1163         }
1164
1165 #ifdef UBIFS_EXTROOT
1166         /* ... but it also could be an UBI volume */
1167         memset(blkdev_path, 0, sizeof(blkdev_path));
1168         libubi = libubi_open();
1169         find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1170         libubi_close(libubi);
1171         if (blkdev_path[0]) {
1172                 char cfg[] = "/tmp/ubifs_cfg";
1173
1174                 /* Mount volume and try extroot (using fstab from that vol) */
1175                 mkdir_p(cfg);
1176                 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1177                         err = mount_extroot(cfg);
1178                         umount2(cfg, MNT_DETACH);
1179                 }
1180                 if (err < 0)
1181                         rmdir("/tmp/overlay");
1182                 rmdir(cfg);
1183                 return err;
1184        }
1185 #endif
1186
1187         return mount_extroot(NULL);
1188 }
1189
1190 static int main_mount(int argc, char **argv)
1191 {
1192         struct blkid_struct_probe *pr;
1193
1194         if (config_load(NULL))
1195                 return -1;
1196
1197         cache_load(1);
1198         list_for_each_entry(pr, &devices, list)
1199                 mount_device(pr, 0);
1200
1201         handle_swapfiles(true);
1202
1203         return 0;
1204 }
1205
1206 static int main_umount(int argc, char **argv)
1207 {
1208         struct blkid_struct_probe *pr;
1209
1210         if (config_load(NULL))
1211                 return -1;
1212
1213         handle_swapfiles(false);
1214
1215         cache_load(0);
1216         list_for_each_entry(pr, &devices, list)
1217                 umount_device(pr);
1218
1219         return 0;
1220 }
1221
1222 static int main_detect(int argc, char **argv)
1223 {
1224         struct blkid_struct_probe *pr;
1225
1226         cache_load(0);
1227         printf("config 'global'\n");
1228         printf("\toption\tanon_swap\t'0'\n");
1229         printf("\toption\tanon_mount\t'0'\n");
1230         printf("\toption\tauto_swap\t'1'\n");
1231         printf("\toption\tauto_mount\t'1'\n");
1232         printf("\toption\tdelay_root\t'5'\n");
1233         printf("\toption\tcheck_fs\t'0'\n\n");
1234         list_for_each_entry(pr, &devices, list)
1235                 print_block_uci(pr);
1236
1237         return 0;
1238 }
1239
1240 static int main_info(int argc, char **argv)
1241 {
1242         int i;
1243         struct blkid_struct_probe *pr;
1244
1245         cache_load(1);
1246         if (argc == 2) {
1247                 list_for_each_entry(pr, &devices, list)
1248                         print_block_info(pr);
1249
1250                 return 0;
1251         };
1252
1253         for (i = 2; i < argc; i++) {
1254                 struct stat s;
1255
1256                 if (stat(argv[i], &s)) {
1257                         ULOG_ERR("failed to stat %s\n", argv[i]);
1258                         continue;
1259                 }
1260                 if (!S_ISBLK(s.st_mode)) {
1261                         ULOG_ERR("%s is not a block device\n", argv[i]);
1262                         continue;
1263                 }
1264                 pr = find_block_info(NULL, NULL, argv[i]);
1265                 if (pr)
1266                         print_block_info(pr);
1267         }
1268
1269         return 0;
1270 }
1271
1272 static int swapon_usage(void)
1273 {
1274         fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1275                 "\tStart swapping on [DEVICE]\n"
1276                 " -a\tStart swapping on all swap devices\n"
1277                 " -p pri\tSet priority of swap device\n"
1278                 " -s\tShow summary\n");
1279         return -1;
1280 }
1281
1282 static int main_swapon(int argc, char **argv)
1283 {
1284         int ch;
1285         FILE *fp;
1286         char *lineptr;
1287         size_t s;
1288         struct blkid_struct_probe *pr;
1289         int flags = 0;
1290         int pri;
1291         struct stat st;
1292         int err;
1293
1294         while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1295                 switch(ch) {
1296                 case 's':
1297                         fp = fopen("/proc/swaps", "r");
1298                         lineptr = NULL;
1299
1300                         if (!fp) {
1301                                 ULOG_ERR("failed to open /proc/swaps\n");
1302                                 return -1;
1303                         }
1304                         while (getline(&lineptr, &s, fp) > 0)
1305                                 printf(lineptr);
1306                         if (lineptr)
1307                                 free(lineptr);
1308                         fclose(fp);
1309                         return 0;
1310                 case 'a':
1311                         cache_load(0);
1312                         list_for_each_entry(pr, &devices, list) {
1313                                 if (strcmp(pr->id->name, "swap"))
1314                                         continue;
1315                                 if (swapon(pr->dev, 0))
1316                                         ULOG_ERR("failed to swapon %s\n", pr->dev);
1317                         }
1318                         return 0;
1319                 case 'p':
1320                         pri = atoi(optarg);
1321                         if (pri >= 0)
1322                                 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1323                         break;
1324                 default:
1325                         return swapon_usage();
1326                 }
1327
1328         }
1329
1330         if (optind != (argc - 1))
1331                 return swapon_usage();
1332
1333         if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1334                 ULOG_ERR("%s is not a block device or file\n", argv[optind]);
1335                 return -1;
1336         }
1337         err = swapon(argv[optind], flags);
1338         if (err) {
1339                 ULOG_ERR("failed to swapon %s (%d)\n", argv[optind], err);
1340                 return err;
1341         }
1342
1343         return 0;
1344 }
1345
1346 static int main_swapoff(int argc, char **argv)
1347 {
1348         if (argc != 2) {
1349                 ULOG_ERR("Usage: swapoff [-a] [DEVICE]\n\n"
1350                         "\tStop swapping on DEVICE\n"
1351                         " -a\tStop swapping on all swap devices\n");
1352                 return -1;
1353         }
1354
1355         if (!strcmp(argv[1], "-a")) {
1356                 FILE *fp = fopen("/proc/swaps", "r");
1357                 char line[256];
1358
1359                 if (!fp) {
1360                         ULOG_ERR("failed to open /proc/swaps\n");
1361                         return -1;
1362                 }
1363                 fgets(line, sizeof(line), fp);
1364                 while (fgets(line, sizeof(line), fp)) {
1365                         char *end = strchr(line, ' ');
1366                         int err;
1367
1368                         if (!end)
1369                                 continue;
1370                         *end = '\0';
1371                         err = swapoff(line);
1372                         if (err)
1373                                 ULOG_ERR("failed to swapoff %s (%d)\n", line, err);
1374                 }
1375                 fclose(fp);
1376         } else {
1377                 struct stat s;
1378                 int err;
1379
1380                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1381                         ULOG_ERR("%s is not a block device or file\n", argv[1]);
1382                         return -1;
1383                 }
1384                 err = swapoff(argv[1]);
1385                 if (err) {
1386                         ULOG_ERR("failed to swapoff %s (%d)\n", argv[1], err);
1387                         return err;
1388                 }
1389         }
1390
1391         return 0;
1392 }
1393
1394 int main(int argc, char **argv)
1395 {
1396         char *base = basename(*argv);
1397
1398         umask(0);
1399
1400         ulog_open(-1, -1, "block");
1401         ulog_threshold(LOG_NOTICE);
1402
1403         if (!strcmp(base, "swapon"))
1404                 return main_swapon(argc, argv);
1405
1406         if (!strcmp(base, "swapoff"))
1407                 return main_swapoff(argc, argv);
1408
1409         if ((argc > 1) && !strcmp(base, "block")) {
1410                 if (!strcmp(argv[1], "info"))
1411                         return main_info(argc, argv);
1412
1413                 if (!strcmp(argv[1], "detect"))
1414                         return main_detect(argc, argv);
1415
1416                 if (!strcmp(argv[1], "hotplug"))
1417                         return main_hotplug(argc, argv);
1418
1419                 if (!strcmp(argv[1], "extroot"))
1420                         return main_extroot(argc, argv);
1421
1422                 if (!strcmp(argv[1], "mount"))
1423                         return main_mount(argc, argv);
1424
1425                 if (!strcmp(argv[1], "umount"))
1426                         return main_umount(argc, argv);
1427         }
1428
1429         ULOG_ERR("Usage: block <info|mount|umount|detect>\n");
1430
1431         return -1;
1432 }