3e4cfb5fb66d7b2716e5c1683093ba5ae83ab745
[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 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/swap.h>
32 #include <sys/mount.h>
33 #include <sys/wait.h>
34 #include <sys/sysmacros.h>
35
36 #include <linux/fs.h>
37
38 #include <uci.h>
39 #include <uci_blob.h>
40
41 #include <libubox/ulog.h>
42 #include <libubox/list.h>
43 #include <libubox/vlist.h>
44 #include <libubox/blobmsg_json.h>
45 #include <libubox/avl-cmp.h>
46 #include <libubus.h>
47
48 #include "probe.h"
49
50 #define AUTOFS_MOUNT_PATH       "/tmp/run/blockd/"
51
52 #ifdef UBIFS_EXTROOT
53 #include "libubi/libubi.h"
54 #endif
55
56 enum {
57         TYPE_MOUNT,
58         TYPE_SWAP,
59 };
60
61 enum {
62         TYPE_DEV,
63         TYPE_HOTPLUG,
64         TYPE_AUTOFS,
65 };
66
67 struct mount {
68         struct vlist_node node;
69         int type;
70
71         char *target;
72         char *path;
73         char *options;
74         uint32_t flags;
75         char *uuid;
76         char *label;
77         char *device;
78         int extroot;
79         int autofs;
80         int overlay;
81         int disabled_fsck;
82         unsigned int prio;
83 };
84
85 static struct vlist_tree mounts;
86 static struct blob_buf b;
87 static LIST_HEAD(devices);
88 static int anon_mount, anon_swap, auto_mount, auto_swap, check_fs;
89 static unsigned int delay_root;
90
91 enum {
92         CFG_ANON_MOUNT,
93         CFG_ANON_SWAP,
94         CFG_AUTO_MOUNT,
95         CFG_AUTO_SWAP,
96         CFG_DELAY_ROOT,
97         CFG_CHECK_FS,
98         __CFG_MAX
99 };
100
101 static const struct blobmsg_policy config_policy[__CFG_MAX] = {
102         [CFG_ANON_SWAP] = { .name = "anon_swap", .type = BLOBMSG_TYPE_INT32 },
103         [CFG_ANON_MOUNT] = { .name = "anon_mount", .type = BLOBMSG_TYPE_INT32 },
104         [CFG_AUTO_SWAP] = { .name = "auto_swap", .type = BLOBMSG_TYPE_INT32 },
105         [CFG_AUTO_MOUNT] = { .name = "auto_mount", .type = BLOBMSG_TYPE_INT32 },
106         [CFG_DELAY_ROOT] = { .name = "delay_root", .type = BLOBMSG_TYPE_INT32 },
107         [CFG_CHECK_FS] = { .name = "check_fs", .type = BLOBMSG_TYPE_INT32 },
108 };
109
110 enum {
111         MOUNT_UUID,
112         MOUNT_LABEL,
113         MOUNT_ENABLE,
114         MOUNT_TARGET,
115         MOUNT_DEVICE,
116         MOUNT_OPTIONS,
117         MOUNT_AUTOFS,
118         __MOUNT_MAX
119 };
120
121 static const struct uci_blob_param_list config_attr_list = {
122         .n_params = __CFG_MAX,
123         .params = config_policy,
124 };
125
126 static const struct blobmsg_policy mount_policy[__MOUNT_MAX] = {
127         [MOUNT_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
128         [MOUNT_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
129         [MOUNT_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
130         [MOUNT_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
131         [MOUNT_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_STRING },
132         [MOUNT_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
133         [MOUNT_AUTOFS] = { .name = "autofs", .type = BLOBMSG_TYPE_INT32 },
134 };
135
136 static const struct uci_blob_param_list mount_attr_list = {
137         .n_params = __MOUNT_MAX,
138         .params = mount_policy,
139 };
140
141 enum {
142         SWAP_ENABLE,
143         SWAP_UUID,
144         SWAP_LABEL,
145         SWAP_DEVICE,
146         SWAP_PRIO,
147         __SWAP_MAX
148 };
149
150 static const struct blobmsg_policy swap_policy[__SWAP_MAX] = {
151         [SWAP_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
152         [SWAP_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
153         [SWAP_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
154         [SWAP_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
155         [SWAP_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
156 };
157
158 static const struct uci_blob_param_list swap_attr_list = {
159         .n_params = __SWAP_MAX,
160         .params = swap_policy,
161 };
162
163 struct mount_flag {
164         const char *name;
165         int32_t flag;
166 };
167
168 static const struct mount_flag mount_flags[] = {
169         { "sync",               MS_SYNCHRONOUS  },
170         { "async",              ~MS_SYNCHRONOUS },
171         { "dirsync",            MS_DIRSYNC      },
172         { "mand",               MS_MANDLOCK     },
173         { "nomand",             ~MS_MANDLOCK    },
174         { "atime",              ~MS_NOATIME     },
175         { "noatime",            MS_NOATIME      },
176         { "dev",                ~MS_NODEV       },
177         { "nodev",              MS_NODEV        },
178         { "diratime",           ~MS_NODIRATIME  },
179         { "nodiratime",         MS_NODIRATIME   },
180         { "exec",               ~MS_NOEXEC      },
181         { "noexec",             MS_NOEXEC       },
182         { "suid",               ~MS_NOSUID      },
183         { "nosuid",             MS_NOSUID       },
184         { "rw",                 ~MS_RDONLY      },
185         { "ro",                 MS_RDONLY       },
186         { "relatime",           MS_RELATIME     },
187         { "norelatime",         ~MS_RELATIME    },
188         { "strictatime",        MS_STRICTATIME  },
189         { "acl",                MS_POSIXACL     },
190         { "noacl",              ~MS_POSIXACL    },
191         { "nouser_xattr",       MS_NOUSER       },
192         { "user_xattr",         ~MS_NOUSER      },
193 };
194
195 static char *blobmsg_get_strdup(struct blob_attr *attr)
196 {
197         if (!attr)
198                 return NULL;
199
200         return strdup(blobmsg_get_string(attr));
201 }
202
203 static char *blobmsg_get_basename(struct blob_attr *attr)
204 {
205         if (!attr)
206                 return NULL;
207
208         return strdup(basename(blobmsg_get_string(attr)));
209 }
210
211 static void parse_mount_options(struct mount *m, char *optstr)
212 {
213         int i;
214         bool is_flag;
215         char *p, *opts, *last;
216
217         m->flags = 0;
218         m->options = NULL;
219
220         if (!optstr || !*optstr)
221                 return;
222
223         m->options = opts = calloc(1, strlen(optstr) + 1);
224
225         if (!m->options)
226                 return;
227
228         p = last = optstr;
229
230         do {
231                 p = strchr(p, ',');
232
233                 if (p)
234                         *p++ = 0;
235
236                 for (i = 0, is_flag = false; i < ARRAY_SIZE(mount_flags); i++) {
237                         if (!strcmp(last, mount_flags[i].name)) {
238                                 if (mount_flags[i].flag < 0)
239                                         m->flags &= (uint32_t)mount_flags[i].flag;
240                                 else
241                                         m->flags |= (uint32_t)mount_flags[i].flag;
242                                 is_flag = true;
243                                 break;
244                         }
245                 }
246
247                 if (!is_flag)
248                         opts += sprintf(opts, "%s%s", (opts > m->options) ? "," : "", last);
249
250                 last = p;
251
252         } while (p);
253
254         free(optstr);
255 }
256
257 static int mount_add(struct uci_section *s)
258 {
259         struct blob_attr *tb[__MOUNT_MAX] = { 0 };
260         struct mount *m;
261
262         blob_buf_init(&b, 0);
263         uci_to_blob(&b, s, &mount_attr_list);
264         blobmsg_parse(mount_policy, __MOUNT_MAX, tb, blob_data(b.head), blob_len(b.head));
265
266         if (!tb[MOUNT_LABEL] && !tb[MOUNT_UUID] && !tb[MOUNT_DEVICE])
267                 return -1;
268
269         if (tb[MOUNT_ENABLE] && !blobmsg_get_u32(tb[MOUNT_ENABLE]))
270                 return -1;
271
272         m = malloc(sizeof(struct mount));
273         m->type = TYPE_MOUNT;
274         m->uuid = blobmsg_get_strdup(tb[MOUNT_UUID]);
275         m->label = blobmsg_get_strdup(tb[MOUNT_LABEL]);
276         m->target = blobmsg_get_strdup(tb[MOUNT_TARGET]);
277         m->device = blobmsg_get_basename(tb[MOUNT_DEVICE]);
278         if (tb[MOUNT_AUTOFS])
279                 m->autofs = blobmsg_get_u32(tb[MOUNT_AUTOFS]);
280         else
281                 m->autofs = 0;
282         parse_mount_options(m, blobmsg_get_strdup(tb[MOUNT_OPTIONS]));
283
284         m->overlay = m->extroot = 0;
285         if (m->target && !strcmp(m->target, "/"))
286                 m->extroot = 1;
287         if (m->target && !strcmp(m->target, "/overlay"))
288                 m->extroot = m->overlay = 1;
289
290         if (m->target && *m->target != '/') {
291                 ULOG_WARN("ignoring mount section %s due to invalid target '%s'\n",
292                           s->e.name, m->target);
293                 free(m);
294                 return -1;
295         }
296
297         if (m->uuid)
298                 vlist_add(&mounts, &m->node, m->uuid);
299         else if (m->label)
300                 vlist_add(&mounts, &m->node, m->label);
301         else if (m->device)
302                 vlist_add(&mounts, &m->node, m->device);
303
304         return 0;
305 }
306
307 static int swap_add(struct uci_section *s)
308 {
309         struct blob_attr *tb[__SWAP_MAX] = { 0 };
310         struct mount *m;
311
312         blob_buf_init(&b, 0);
313         uci_to_blob(&b, s, &swap_attr_list);
314         blobmsg_parse(swap_policy, __SWAP_MAX, tb, blob_data(b.head), blob_len(b.head));
315
316         if (!tb[SWAP_UUID] && !tb[SWAP_LABEL] && !tb[SWAP_DEVICE])
317                 return -1;
318
319         m = malloc(sizeof(struct mount));
320         memset(m, 0, sizeof(struct mount));
321         m->type = TYPE_SWAP;
322         m->uuid = blobmsg_get_strdup(tb[SWAP_UUID]);
323         m->label = blobmsg_get_strdup(tb[SWAP_LABEL]);
324         m->device = blobmsg_get_basename(tb[SWAP_DEVICE]);
325         if (tb[SWAP_PRIO])
326                 m->prio = blobmsg_get_u32(tb[SWAP_PRIO]);
327         if (m->prio)
328                 m->prio = ((m->prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
329
330         if ((!tb[SWAP_ENABLE]) || blobmsg_get_u32(tb[SWAP_ENABLE])) {
331                 /* store complete swap path */
332                 if (tb[SWAP_DEVICE])
333                         m->target = blobmsg_get_strdup(tb[SWAP_DEVICE]);
334
335                 if (m->uuid)
336                         vlist_add(&mounts, &m->node, m->uuid);
337                 else if (m->label)
338                         vlist_add(&mounts, &m->node, m->label);
339                 else if (m->device)
340                         vlist_add(&mounts, &m->node, m->device);
341         }
342
343         return 0;
344 }
345
346 static int global_add(struct uci_section *s)
347 {
348         struct blob_attr *tb[__CFG_MAX] = { 0 };
349
350         blob_buf_init(&b, 0);
351         uci_to_blob(&b, s, &config_attr_list);
352         blobmsg_parse(config_policy, __CFG_MAX, tb, blob_data(b.head), blob_len(b.head));
353
354         if ((tb[CFG_ANON_MOUNT]) && blobmsg_get_u32(tb[CFG_ANON_MOUNT]))
355                 anon_mount = 1;
356         if ((tb[CFG_ANON_SWAP]) && blobmsg_get_u32(tb[CFG_ANON_SWAP]))
357                 anon_swap = 1;
358
359         if ((tb[CFG_AUTO_MOUNT]) && blobmsg_get_u32(tb[CFG_AUTO_MOUNT]))
360                 auto_mount = 1;
361         if ((tb[CFG_AUTO_SWAP]) && blobmsg_get_u32(tb[CFG_AUTO_SWAP]))
362                 auto_swap = 1;
363
364         if (tb[CFG_DELAY_ROOT])
365                 delay_root = blobmsg_get_u32(tb[CFG_DELAY_ROOT]);
366
367         if ((tb[CFG_CHECK_FS]) && blobmsg_get_u32(tb[CFG_CHECK_FS]))
368                 check_fs = 1;
369
370         return 0;
371 }
372
373 static struct mount* find_swap(const char *uuid, const char *label, const char *device)
374 {
375         struct mount *m;
376
377         vlist_for_each_element(&mounts, m, node) {
378                 if (m->type != TYPE_SWAP)
379                         continue;
380                 if (uuid && m->uuid && !strcasecmp(m->uuid, uuid))
381                         return m;
382                 if (label && m->label && !strcmp(m->label, label))
383                         return m;
384                 if (device && m->device && !strcmp(m->device, device))
385                         return m;
386         }
387
388         return NULL;
389 }
390
391 static struct mount* find_block(const char *uuid, const char *label, const char *device,
392                                 const char *target)
393 {
394         struct mount *m;
395
396         vlist_for_each_element(&mounts, m, node) {
397                 if (m->type != TYPE_MOUNT)
398                         continue;
399                 if (m->uuid && uuid && !strcasecmp(m->uuid, uuid))
400                         return m;
401                 if (m->label && label && !strcmp(m->label, label))
402                         return m;
403                 if (m->target && target && !strcmp(m->target, target))
404                         return m;
405                 if (m->device && device && !strcmp(m->device, device))
406                         return m;
407         }
408
409         return NULL;
410 }
411
412 static void mounts_update(struct vlist_tree *tree, struct vlist_node *node_new,
413                           struct vlist_node *node_old)
414 {
415 }
416
417 static struct uci_package * config_try_load(struct uci_context *ctx, char *path)
418 {
419         char *file = basename(path);
420         char *dir = dirname(path);
421         char *err;
422         struct uci_package *pkg;
423
424         uci_set_confdir(ctx, dir);
425         ULOG_INFO("attempting to load %s/%s\n", dir, file);
426
427         if (uci_load(ctx, file, &pkg)) {
428                 uci_get_errorstr(ctx, &err, file);
429                 ULOG_ERR("unable to load configuration (%s)\n", err);
430
431                 free(err);
432                 return NULL;
433         }
434
435         return pkg;
436 }
437
438 static int config_load(char *cfg)
439 {
440         struct uci_context *ctx = uci_alloc_context();
441         struct uci_package *pkg = NULL;
442         struct uci_element *e;
443         char path[64];
444
445         vlist_init(&mounts, avl_strcmp, mounts_update);
446
447         if (cfg) {
448                 snprintf(path, sizeof(path), "%s/upper/etc/config/fstab", cfg);
449                 pkg = config_try_load(ctx, path);
450
451                 if (!pkg) {
452                         snprintf(path, sizeof(path), "%s/etc/config/fstab", cfg);
453                         pkg = config_try_load(ctx, path);
454                 }
455         }
456
457         if (!pkg) {
458                 snprintf(path, sizeof(path), "/etc/config/fstab");
459                 pkg = config_try_load(ctx, path);
460         }
461
462         if (!pkg) {
463                 ULOG_ERR("no usable configuration\n");
464                 return -1;
465         }
466
467         vlist_update(&mounts);
468         uci_foreach_element(&pkg->sections, e) {
469                 struct uci_section *s = uci_to_section(e);
470
471                 if (!strcmp(s->type, "mount"))
472                         mount_add(s);
473                 if (!strcmp(s->type, "swap"))
474                         swap_add(s);
475                 if (!strcmp(s->type, "global"))
476                         global_add(s);
477         }
478         vlist_flush(&mounts);
479
480         return 0;
481 }
482
483 static struct probe_info* _probe_path(char *path)
484 {
485         struct probe_info *pr;
486         char tmppath[64];
487
488         /* skip ubi device if ubiblock device is present */
489         if (path[5] == 'u' && path[6] == 'b' && path[7] == 'i' &&
490             path[8] >= '0' && path[8] <= '9' ) {
491                 snprintf(tmppath, sizeof(tmppath), "/dev/ubiblock%s", path + 8);
492                 list_for_each_entry(pr, &devices, list)
493                         if (!strcasecmp(pr->dev, tmppath))
494                                 return NULL;
495         }
496
497         return probe_path(path);
498 }
499
500 static int _cache_load(const char *path)
501 {
502         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
503         int j;
504         glob_t gl;
505
506         if (glob(path, gl_flags, NULL, &gl) < 0)
507                 return -1;
508
509         for (j = 0; j < gl.gl_pathc; j++) {
510                 struct probe_info *pr = _probe_path(gl.gl_pathv[j]);
511                 if (pr)
512                         list_add_tail(&pr->list, &devices);
513         }
514
515         globfree(&gl);
516
517         return 0;
518 }
519
520 static void cache_load(int mtd)
521 {
522         if (mtd) {
523                 _cache_load("/dev/mtdblock*");
524                 _cache_load("/dev/ubiblock*");
525                 _cache_load("/dev/ubi[0-9]*");
526         }
527         _cache_load("/dev/loop*");
528         _cache_load("/dev/mmcblk*");
529         _cache_load("/dev/sd*");
530         _cache_load("/dev/hd*");
531         _cache_load("/dev/md*");
532         _cache_load("/dev/vd*");
533         _cache_load("/dev/xvd*");
534         _cache_load("/dev/mapper/*");
535 }
536
537
538 static int print_block_uci(struct probe_info *pr)
539 {
540         if (!strcmp(pr->type, "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)
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 probe_info* find_block_info(char *uuid, char *label, char *path)
556 {
557         struct probe_info *pr = NULL;
558
559         if (uuid)
560                 list_for_each_entry(pr, &devices, list)
561                         if (pr->uuid && !strcasecmp(pr->uuid, uuid))
562                                 return pr;
563
564         if (label)
565                 list_for_each_entry(pr, &devices, list)
566                         if (pr->label && !strcmp(pr->label, label))
567                                 return pr;
568
569         if (path)
570                 list_for_each_entry(pr, &devices, list)
571                         if (pr->dev && !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/self/mountinfo", "r");
580         static char line[256];
581         int len = strlen(block);
582         char *point = NULL, *pos, *tmp, *cpoint, *devname;
583         struct stat s;
584         int rstat;
585         unsigned int minor, major;
586
587         if (!fp)
588                 return NULL;
589
590         rstat = stat(block, &s);
591
592         while (fgets(line, sizeof(line), fp)) {
593                 pos = strchr(line, ' ');
594                 if (!pos)
595                         continue;
596
597                 pos = strchr(pos + 1, ' ');
598                 if (!pos)
599                         continue;
600
601                 tmp = ++pos;
602                 pos = strchr(pos, ':');
603                 if (!pos)
604                         continue;
605
606                 *pos = '\0';
607                 major = atoi(tmp);
608                 tmp = ++pos;
609                 pos = strchr(pos, ' ');
610                 if (!pos)
611                         continue;
612
613                 *pos = '\0';
614                 minor = atoi(tmp);
615                 pos = strchr(pos + 1, ' ');
616                 if (!pos)
617                         continue;
618                 tmp = ++pos;
619
620                 pos = strchr(pos, ' ');
621                 if (!pos)
622                         continue;
623                 *pos = '\0';
624                 cpoint = tmp;
625
626                 pos = strchr(pos + 1, ' ');
627                 if (!pos)
628                         continue;
629
630                 pos = strchr(pos + 1, ' ');
631                 if (!pos)
632                         continue;
633
634                 pos = strchr(pos + 1, ' ');
635                 if (!pos)
636                         continue;
637
638                 tmp = ++pos;
639                 pos = strchr(pos, ' ');
640                 if (!pos)
641                         continue;
642
643                 *pos = '\0';
644                 devname = tmp;
645                 if (!strncmp(block, devname, len)) {
646                         point = strdup(cpoint);
647                         break;
648                 }
649
650                 if (rstat)
651                         continue;
652
653                 if (!S_ISBLK(s.st_mode))
654                         continue;
655
656                 if (major == major(s.st_rdev) &&
657                     minor == minor(s.st_rdev)) {
658                         point = strdup(cpoint);
659                         break;
660                 }
661         }
662
663         fclose(fp);
664
665         return point;
666 }
667
668 static int print_block_info(struct probe_info *pr)
669 {
670         static char *mp;
671
672         mp = find_mount_point(pr->dev);
673         printf("%s:", pr->dev);
674         if (pr->uuid)
675                 printf(" UUID=\"%s\"", pr->uuid);
676
677         if (pr->label)
678                 printf(" LABEL=\"%s\"", pr->label);
679
680         if (pr->version)
681                 printf(" VERSION=\"%s\"", pr->version);
682
683         if (mp) {
684                 printf(" MOUNT=\"%s\"", mp);
685                 free(mp);
686         }
687
688         printf(" TYPE=\"%s\"\n", pr->type);
689
690         return 0;
691 }
692
693 static void mkdir_p(char *dir)
694 {
695         char *l = strrchr(dir, '/');
696
697         if (l) {
698                 *l = '\0';
699                 mkdir_p(dir);
700                 *l = '/';
701                 mkdir(dir, 0755);
702         }
703 }
704
705 static void check_filesystem(struct probe_info *pr)
706 {
707         pid_t pid;
708         struct stat statbuf;
709         const char *e2fsck = "/usr/sbin/e2fsck";
710         const char *f2fsck = "/usr/sbin/fsck.f2fs";
711         const char *dosfsck = "/usr/sbin/dosfsck";
712         const char *ckfs;
713
714         /* UBIFS does not need stuff like fsck */
715         if (!strncmp(pr->type, "ubifs", 5))
716                 return;
717
718         if (!strncmp(pr->type, "vfat", 4)) {
719                 ckfs = dosfsck;
720         } else if (!strncmp(pr->type, "f2fs", 4)) {
721                 ckfs = f2fsck;
722         } else if (!strncmp(pr->type, "ext", 3)) {
723                 ckfs = e2fsck;
724         } else {
725                 ULOG_ERR("check_filesystem: %s is not supported\n", pr->type);
726                 return;
727         }
728
729         if (stat(ckfs, &statbuf) < 0) {
730                 ULOG_ERR("check_filesystem: %s not found\n", ckfs);
731                 return;
732         }
733
734         pid = fork();
735         if (!pid) {
736                 if(!strncmp(pr->type, "f2fs", 4)) {
737                         execl(ckfs, ckfs, "-f", pr->dev, NULL);
738                         exit(-1);
739                 } else {
740                         execl(ckfs, ckfs, "-p", pr->dev, NULL);
741                         exit(-1);
742                 }
743         } else if (pid > 0) {
744                 int status;
745
746                 waitpid(pid, &status, 0);
747                 if (WEXITSTATUS(status))
748                         ULOG_ERR("check_filesystem: %s returned %d\n", ckfs, WEXITSTATUS(status));
749         }
750 }
751
752 static void handle_swapfiles(bool on)
753 {
754         struct stat s;
755         struct mount *m;
756         struct probe_info *pr;
757
758         vlist_for_each_element(&mounts, m, node)
759         {
760                 if (m->type != TYPE_SWAP || !m->target)
761                         continue;
762
763                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
764                         continue;
765
766                 pr = _probe_path(m->target);
767
768                 if (!pr)
769                         continue;
770
771                 if (!strcmp(pr->type, "swap")) {
772                         if (on)
773                                 swapon(pr->dev, m->prio);
774                         else
775                                 swapoff(pr->dev);
776                 }
777
778                 free(pr);
779         }
780 }
781
782 static void to_devnull(int fd)
783 {
784         int devnull = open("/dev/null", fd ? O_WRONLY : O_RDONLY);
785
786         if (devnull >= 0)
787                 dup2(devnull, fd);
788
789         if (devnull > STDERR_FILENO)
790                 close(devnull);
791 }
792
793 static int exec_mount(const char *source, const char *target,
794                       const char *fstype, const char *options)
795 {
796         pid_t pid;
797         struct stat s;
798         FILE *mount_fd;
799         int err, status, pfds[2];
800         char errmsg[128], cmd[sizeof("/sbin/mount.XXXXXXXXXXXXXXXX\0")];
801
802         snprintf(cmd, sizeof(cmd), "/sbin/mount.%s", fstype);
803
804         if (stat(cmd, &s) < 0 || !S_ISREG(s.st_mode) || !(s.st_mode & S_IXUSR)) {
805                 ULOG_ERR("No \"mount.%s\" utility available\n", fstype);
806                 return -1;
807         }
808
809         if (pipe(pfds) < 0)
810                 return -1;
811
812         fcntl(pfds[0], F_SETFD, fcntl(pfds[0], F_GETFD) | FD_CLOEXEC);
813         fcntl(pfds[1], F_SETFD, fcntl(pfds[1], F_GETFD) | FD_CLOEXEC);
814
815         pid = vfork();
816
817         switch (pid) {
818         case -1:
819                 close(pfds[0]);
820                 close(pfds[1]);
821
822                 return -1;
823
824         case 0:
825                 to_devnull(STDIN_FILENO);
826                 to_devnull(STDOUT_FILENO);
827
828                 dup2(pfds[1], STDERR_FILENO);
829                 close(pfds[0]);
830                 close(pfds[1]);
831
832                 if (options && *options)
833                         execl(cmd, cmd, "-o", options, source, target, NULL);
834                 else
835                         execl(cmd, cmd, source, target, NULL);
836
837                 return -1;
838
839         default:
840                 close(pfds[1]);
841
842                 mount_fd = fdopen(pfds[0], "r");
843
844                 while (fgets(errmsg, sizeof(errmsg), mount_fd))
845                         ULOG_ERR("mount.%s: %s", fstype, errmsg);
846
847                 fclose(mount_fd);
848
849                 err = waitpid(pid, &status, 0);
850
851                 if (err != -1) {
852                         if (status != 0) {
853                                 ULOG_ERR("mount.%s: failed with status %d\n", fstype, status);
854                                 errno = EINVAL;
855                                 err = -1;
856                         } else {
857                                 errno = 0;
858                                 err = 0;
859                         }
860                 }
861
862                 break;
863         }
864
865         return err;
866 }
867
868 static int handle_mount(const char *source, const char *target,
869                         const char *fstype, struct mount *m)
870 {
871         int i, err;
872         size_t mount_opts_len;
873         char *mount_opts = NULL, *ptr;
874
875         err = mount(source, target, fstype, m ? m->flags : 0,
876                     (m && m->options) ? m->options : "");
877
878         /* Requested file system type is not available in kernel,
879            attempt to call mount helper. */
880         if (err == -1 && errno == ENODEV) {
881                 if (m) {
882                         /* Convert mount flags back into string representation,
883                            first calculate needed length of string buffer... */
884                         mount_opts_len = 1 + (m->options ? strlen(m->options) : 0);
885
886                         for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
887                                 if ((mount_flags[i].flag > 0) &&
888                                     (mount_flags[i].flag < INT_MAX) &&
889                                     (m->flags & (uint32_t)mount_flags[i].flag))
890                                         mount_opts_len += strlen(mount_flags[i].name) + 1;
891
892                         /* ... then now allocate and fill it ... */
893                         ptr = mount_opts = calloc(1, mount_opts_len);
894
895                         if (!ptr) {
896                                 errno = ENOMEM;
897                                 return -1;
898                         }
899
900                         if (m->options)
901                                 ptr += sprintf(ptr, "%s,", m->options);
902
903                         for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
904                                 if ((mount_flags[i].flag > 0) &&
905                                     (mount_flags[i].flag < INT_MAX) &&
906                                     (m->flags & (uint32_t)mount_flags[i].flag))
907                                         ptr += sprintf(ptr, "%s,", mount_flags[i].name);
908
909                         mount_opts[mount_opts_len - 1] = 0;
910                 }
911
912                 /* ... and now finally invoke the external mount program */
913                 err = exec_mount(source, target, fstype, mount_opts);
914         }
915
916         return err;
917 }
918
919 static void blockd_notify(char *device, struct mount *m, struct probe_info *pr)
920 {
921         struct ubus_context *ctx = ubus_connect(NULL);
922         uint32_t id;
923
924         if (!ctx)
925                 return;
926
927         if (!ubus_lookup_id(ctx, "block", &id)) {
928                 struct blob_buf buf = { 0 };
929                 char *d = strrchr(device, '/');
930
931                 if (d)
932                         d++;
933                 else
934                         d = device;
935
936                 blob_buf_init(&buf, 0);
937
938                 if (m) {
939
940                         blobmsg_add_string(&buf, "device", d);
941                         if (m->uuid)
942                                 blobmsg_add_string(&buf, "uuid", m->uuid);
943                         if (m->label)
944                                 blobmsg_add_string(&buf, "label", m->label);
945                         if (m->target)
946                                 blobmsg_add_string(&buf, "target", m->target);
947                         if (m->options)
948                                 blobmsg_add_string(&buf, "options", m->options);
949                         if (m->autofs)
950                                 blobmsg_add_u32(&buf, "autofs", m->autofs);
951                         if (pr->type)
952                                 blobmsg_add_string(&buf, "type", pr->type);
953                         if (pr->version)
954                                 blobmsg_add_string(&buf, "version", pr->version);
955                 } else if (pr) {
956                         blobmsg_add_string(&buf, "device", d);
957                         if (pr->uuid)
958                                 blobmsg_add_string(&buf, "uuid", pr->uuid);
959                         if (pr->label)
960                                 blobmsg_add_string(&buf, "label", pr->label);
961                         if (pr->type)
962                                 blobmsg_add_string(&buf, "type", pr->type);
963                         if (pr->version)
964                                 blobmsg_add_string(&buf, "version", pr->version);
965                         blobmsg_add_u32(&buf, "anon", 1);
966                 } else {
967                         blobmsg_add_string(&buf, "device", d);
968                         blobmsg_add_u32(&buf, "remove", 1);
969                 }
970
971                 ubus_invoke(ctx, id, "hotplug", buf.head, NULL, NULL, 3000);
972         }
973
974         ubus_free(ctx);
975 }
976
977 static int mount_device(struct probe_info *pr, int type)
978 {
979         struct mount *m;
980         char *device;
981         char *mp;
982
983         if (!pr)
984                 return -1;
985
986         device = basename(pr->dev);
987
988         if (!strcmp(pr->type, "swap")) {
989                 if ((type == TYPE_HOTPLUG) && !auto_swap)
990                         return -1;
991                 m = find_swap(pr->uuid, pr->label, device);
992                 if (m || anon_swap)
993                         swapon(pr->dev, (m) ? (m->prio) : (0));
994
995                 return 0;
996         }
997
998         mp = find_mount_point(pr->dev);
999         if (mp && (type != TYPE_HOTPLUG)) {
1000                 ULOG_ERR("%s is already mounted on %s\n", pr->dev, mp);
1001                 free(mp);
1002                 return -1;
1003         }
1004
1005         m = find_block(pr->uuid, pr->label, device, NULL);
1006         if (m && m->extroot)
1007                 return -1;
1008
1009         if (m) switch (type) {
1010         case TYPE_HOTPLUG:
1011                 blockd_notify(device, m, pr);
1012                 if (m->autofs)
1013                         return 0;
1014                 if (!auto_mount)
1015                         return -1;
1016                 break;
1017         case TYPE_AUTOFS:
1018                 if (!m->autofs)
1019                         return -1;
1020                 break;
1021         case TYPE_DEV:
1022                 if (m->autofs)
1023                         return -1;
1024                 break;
1025         } else if (type == TYPE_HOTPLUG) {
1026                 blockd_notify(device, NULL, pr);
1027         }
1028
1029         if (m) {
1030                 char *target = m->target;
1031                 char _target[32];
1032                 int err = 0;
1033
1034                 if (m->autofs) {
1035                         snprintf(_target, sizeof(_target), "/tmp/run/blockd/%s", device);
1036                         target = _target;
1037                 }
1038                 if (!target) {
1039                         snprintf(_target, sizeof(_target), "/mnt/%s", device);
1040                         target = _target;
1041                 }
1042                 mkdir_p(target);
1043
1044                 if (check_fs)
1045                         check_filesystem(pr);
1046
1047                 err = handle_mount(pr->dev, target, pr->type, m);
1048                 if (err)
1049                         ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
1050                                  pr->dev, pr->type, target, errno, strerror(errno));
1051                 else
1052                         handle_swapfiles(true);
1053                 return err;
1054         }
1055
1056         if (anon_mount) {
1057                 char target[32];
1058                 int err = 0;
1059
1060                 snprintf(target, sizeof(target), "/mnt/%s", device);
1061                 mkdir_p(target);
1062
1063                 if (check_fs)
1064                         check_filesystem(pr);
1065
1066                 err = handle_mount(pr->dev, target, pr->type, NULL);
1067                 if (err)
1068                         ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
1069                                  pr->dev, pr->type, target, errno, strerror(errno));
1070                 else
1071                         handle_swapfiles(true);
1072                 return err;
1073         }
1074
1075         return 0;
1076 }
1077
1078 static int umount_device(struct probe_info *pr)
1079 {
1080         struct mount *m;
1081         char *device = basename(pr->dev);
1082         char *mp;
1083         int err;
1084
1085         if (!pr)
1086                 return -1;
1087
1088         if (!strcmp(pr->type, "swap"))
1089                 return -1;
1090
1091         mp = find_mount_point(pr->dev);
1092         if (!mp)
1093                 return -1;
1094
1095         m = find_block(pr->uuid, pr->label, device, NULL);
1096         if (m && m->extroot)
1097                 return -1;
1098
1099         err = umount2(mp, MNT_DETACH);
1100         if (err)
1101                 ULOG_ERR("unmounting %s (%s)  failed (%d) - %s\n",
1102                          pr->dev, mp, errno, strerror(errno));
1103         else
1104                 ULOG_INFO("unmounted %s (%s)\n",
1105                           pr->dev, mp);
1106
1107         free(mp);
1108         return err;
1109 }
1110
1111 static int mount_action(char *action, char *device, int type)
1112 {
1113         char path[32];
1114         char *mount_point;
1115
1116         if (!action || !device)
1117                 return -1;
1118         snprintf(path, sizeof(path), "/dev/%s", device);
1119
1120         if (!strcmp(action, "remove")) {
1121                 int err = 0;
1122
1123                 if (type == TYPE_HOTPLUG)
1124                         blockd_notify(device, NULL, NULL);
1125
1126                 mount_point = find_mount_point(path);
1127                 if (mount_point)
1128                         err = umount2(mount_point, MNT_DETACH);
1129
1130                 if (err)
1131                         ULOG_ERR("umount of %s failed (%d) - %s\n",
1132                                  mount_point, errno, strerror(errno));
1133
1134                 free(mount_point);
1135                 return 0;
1136         } else if (strcmp(action, "add")) {
1137                 ULOG_ERR("Unkown action %s\n", action);
1138
1139                 return -1;
1140         }
1141
1142         if (config_load(NULL))
1143                 return -1;
1144         cache_load(0);
1145
1146         return mount_device(find_block_info(NULL, NULL, path), type);
1147 }
1148
1149 static int main_hotplug(int argc, char **argv)
1150 {
1151         return mount_action(getenv("ACTION"), getenv("DEVNAME"), TYPE_HOTPLUG);
1152 }
1153
1154 static int main_autofs(int argc, char **argv)
1155 {
1156         if (argc < 3)
1157                 return -1;
1158
1159         if (!strcmp(argv[2], "start")) {
1160                 struct probe_info *pr;
1161
1162                 if (config_load(NULL))
1163                         return -1;
1164
1165                 cache_load(0);
1166                 list_for_each_entry(pr, &devices, list) {
1167                         struct mount *m = find_block(pr->uuid, pr->label, NULL, NULL);
1168
1169                         if (m && m->autofs)
1170                                 mount_device(pr, TYPE_HOTPLUG);
1171                         else
1172                                 blockd_notify(pr->dev, m, pr);
1173                 }
1174                 return 0;
1175         }
1176         return mount_action(argv[2], argv[3], TYPE_AUTOFS);
1177 }
1178
1179 static int find_block_mtd(char *name, char *part, int plen)
1180 {
1181         FILE *fp = fopen("/proc/mtd", "r");
1182         static char line[256];
1183         char *index = NULL;
1184
1185         if(!fp)
1186                 return -1;
1187
1188         while (!index && fgets(line, sizeof(line), fp)) {
1189                 if (strstr(line, name)) {
1190                         char *eol = strstr(line, ":");
1191
1192                         if (!eol)
1193                                 continue;
1194
1195                         *eol = '\0';
1196                         index = &line[3];
1197                 }
1198         }
1199
1200         fclose(fp);
1201
1202         if (!index)
1203                 return -1;
1204
1205         snprintf(part, plen, "/dev/mtdblock%s", index);
1206
1207         return 0;
1208 }
1209
1210 #ifdef UBIFS_EXTROOT
1211 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
1212 {
1213         int dev = 0;
1214
1215         while (ubi_dev_present(libubi, dev))
1216         {
1217                 struct ubi_dev_info dev_info;
1218                 struct ubi_vol_info vol_info;
1219
1220                 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
1221                         continue;
1222                 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
1223                         continue;
1224
1225                 *dev_num = dev_info.dev_num;
1226                 *vol_id = vol_info.vol_id;
1227
1228                 return 0;
1229         }
1230
1231         return -1;
1232 }
1233
1234 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
1235 {
1236         int dev_num;
1237         int vol_id;
1238         int err = -1;
1239
1240         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1241         if (!err)
1242                 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
1243
1244         return err;
1245 }
1246
1247 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
1248 {
1249         int dev_num;
1250         int vol_id;
1251         int err = -1;
1252
1253         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1254         if (!err)
1255                 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
1256
1257         return err;
1258 }
1259
1260 #else
1261
1262 static int find_root_dev(char *buf, int len)
1263 {
1264         DIR *d;
1265         dev_t root;
1266         struct stat s;
1267         struct dirent *e;
1268
1269         if (stat("/", &s))
1270                 return -1;
1271
1272         if (!(d = opendir("/dev")))
1273                 return -1;
1274
1275         root = s.st_dev;
1276
1277         while ((e = readdir(d)) != NULL) {
1278                 snprintf(buf, len, "/dev/%s", e->d_name);
1279
1280                 if (stat(buf, &s) || s.st_rdev != root)
1281                         continue;
1282
1283                 closedir(d);
1284                 return 0;
1285         }
1286
1287         closedir(d);
1288         return -1;
1289 }
1290
1291 #endif
1292
1293 static int test_fs_support(const char *name)
1294 {
1295         char line[128], *p;
1296         int rv = -1;
1297         FILE *f;
1298
1299         if ((f = fopen("/proc/filesystems", "r")) != NULL) {
1300                 while (fgets(line, sizeof(line), f)) {
1301                         p = strtok(line, "\t\n");
1302
1303                         if (p && !strcmp(p, "nodev"))
1304                                 p = strtok(NULL, "\t\n");
1305
1306                         if (p && !strcmp(p, name)) {
1307                                 rv = 0;
1308                                 break;
1309                         }
1310                 }
1311                 fclose(f);
1312         }
1313
1314         return rv;
1315 }
1316
1317 static int check_extroot(char *path)
1318 {
1319         struct probe_info *pr = NULL;
1320         char devpath[32];
1321
1322 #ifdef UBIFS_EXTROOT
1323         if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
1324                 int err = -1;
1325                 libubi_t libubi;
1326
1327                 libubi = libubi_open();
1328                 err = find_block_ubi_RO(libubi, "rootfs", devpath, sizeof(devpath));
1329                 libubi_close(libubi);
1330                 if (err)
1331                         return -1;
1332         }
1333 #else
1334         if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
1335                 if (find_root_dev(devpath, sizeof(devpath))) {
1336                         ULOG_ERR("extroot: unable to determine root device\n");
1337                         return -1;
1338                 }
1339         }
1340 #endif
1341
1342         list_for_each_entry(pr, &devices, list) {
1343                 if (!strcmp(pr->dev, devpath)) {
1344                         struct stat s;
1345                         FILE *fp = NULL;
1346                         char tag[64];
1347                         char uuid[64] = { 0 };
1348
1349                         snprintf(tag, sizeof(tag), "%s/etc", path);
1350                         if (stat(tag, &s))
1351                                 mkdir_p(tag);
1352
1353                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
1354                         if (stat(tag, &s)) {
1355                                 fp = fopen(tag, "w+");
1356                                 if (!fp) {
1357                                         ULOG_ERR("extroot: failed to write UUID to %s: %d (%s)\n",
1358                                                  tag, errno, strerror(errno));
1359                                         /* return 0 to continue boot regardless of error */
1360                                         return 0;
1361                                 }
1362                                 fputs(pr->uuid, fp);
1363                                 fclose(fp);
1364                                 return 0;
1365                         }
1366
1367                         fp = fopen(tag, "r");
1368                         if (!fp) {
1369                                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1370                                          tag, errno, strerror(errno));
1371                                 return -1;
1372                         }
1373
1374                         if (!fgets(uuid, sizeof(uuid), fp))
1375                                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1376                                          tag, errno, strerror(errno));
1377                         fclose(fp);
1378
1379                         if (*uuid && !strcasecmp(uuid, pr->uuid))
1380                                 return 0;
1381
1382                         ULOG_ERR("extroot: UUID mismatch (root: %s, %s: %s)\n",
1383                                  pr->uuid, basename(path), uuid);
1384                         return -1;
1385                 }
1386         }
1387
1388         ULOG_ERR("extroot: unable to lookup root device %s\n", devpath);
1389         return -1;
1390 }
1391
1392 /*
1393  * Read info about extroot from UCI (using prefix) and mount it.
1394  */
1395 static int mount_extroot(char *cfg)
1396 {
1397         char overlay[] = "/tmp/extroot/overlay";
1398         char mnt[] = "/tmp/extroot/mnt";
1399         char *path = mnt;
1400         struct probe_info *pr;
1401         struct mount *m;
1402         int err = -1;
1403
1404         /* Load @cfg/etc/config/fstab */
1405         if (config_load(cfg))
1406                 return -2;
1407
1408         /* See if there is extroot-specific mount config */
1409         m = find_block(NULL, NULL, NULL, "/");
1410         if (!m)
1411                 m = find_block(NULL, NULL, NULL, "/overlay");
1412
1413         if (!m || !m->extroot)
1414         {
1415                 ULOG_INFO("extroot: not configured\n");
1416                 return -1;
1417         }
1418
1419         /* Find block device pointed by the mount config */
1420         pr = find_block_info(m->uuid, m->label, m->device);
1421
1422         if (!pr && delay_root){
1423                 ULOG_INFO("extroot: device not present, retrying in %u seconds\n", delay_root);
1424                 sleep(delay_root);
1425                 make_devs();
1426                 cache_load(0);
1427                 pr = find_block_info(m->uuid, m->label, m->device);
1428         }
1429         if (pr) {
1430                 if (strncmp(pr->type, "ext", 3) &&
1431                     strncmp(pr->type, "f2fs", 4) &&
1432                     strncmp(pr->type, "ubifs", 5)) {
1433                         ULOG_ERR("extroot: unsupported filesystem %s, try ext4, f2fs or ubifs\n", pr->type);
1434                         return -1;
1435                 }
1436
1437                 if (test_fs_support(pr->type)) {
1438                         ULOG_ERR("extroot: filesystem %s not supported by kernel\n", pr->type);
1439                         return -1;
1440                 }
1441
1442                 if (m->overlay)
1443                         path = overlay;
1444                 mkdir_p(path);
1445
1446                 if (check_fs)
1447                         check_filesystem(pr);
1448
1449                 err = mount(pr->dev, path, pr->type, m->flags,
1450                             (m->options) ? (m->options) : (""));
1451
1452                 if (err) {
1453                         ULOG_ERR("extroot: mounting %s (%s) on %s failed: %d (%s)\n",
1454                                  pr->dev, pr->type, path, errno, strerror(errno));
1455                 } else if (m->overlay) {
1456                         err = check_extroot(path);
1457                         if (err)
1458                                 umount(path);
1459                 }
1460         } else {
1461                 ULOG_ERR("extroot: cannot find device %s%s\n",
1462                          (m->uuid ? "with UUID " : (m->label ? "with label " : "")),
1463                          (m->uuid ? m->uuid : (m->label ? m->label : m->device)));
1464         }
1465
1466         return err;
1467 }
1468
1469 static int main_extroot(int argc, char **argv)
1470 {
1471         struct probe_info *pr;
1472         char blkdev_path[32] = { 0 };
1473         int err = -1;
1474 #ifdef UBIFS_EXTROOT
1475         libubi_t libubi;
1476 #endif
1477
1478         if (!getenv("PREINIT"))
1479                 return -1;
1480
1481         if (argc != 2) {
1482                 ULOG_ERR("Usage: block extroot\n");
1483                 return -1;
1484         }
1485
1486         make_devs();
1487         cache_load(1);
1488
1489         /* enable LOG_INFO messages */
1490         ulog_threshold(LOG_INFO);
1491
1492         /*
1493          * Look for "rootfs_data". We will want to mount it and check for
1494          * extroot configuration.
1495          */
1496
1497         /* Start with looking for MTD partition */
1498         find_block_mtd("\"rootfs_data\"", blkdev_path, sizeof(blkdev_path));
1499         if (blkdev_path[0]) {
1500                 pr = find_block_info(NULL, NULL, blkdev_path);
1501                 if (pr && !strcmp(pr->type, "jffs2")) {
1502                         char cfg[] = "/tmp/jffs_cfg";
1503
1504                         /*
1505                          * Mount MTD part and try extroot (using
1506                          * /etc/config/fstab from that partition)
1507                          */
1508                         mkdir_p(cfg);
1509                         if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1510                                 err = mount_extroot(cfg);
1511                                 umount2(cfg, MNT_DETACH);
1512                         }
1513                         if (err < 0)
1514                                 rmdir("/tmp/overlay");
1515                         rmdir(cfg);
1516                         return err;
1517                 }
1518         }
1519
1520 #ifdef UBIFS_EXTROOT
1521         /* ... but it also could be an UBI volume */
1522         memset(blkdev_path, 0, sizeof(blkdev_path));
1523         libubi = libubi_open();
1524         find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1525         libubi_close(libubi);
1526         if (blkdev_path[0]) {
1527                 char cfg[] = "/tmp/ubifs_cfg";
1528
1529                 /* Mount volume and try extroot (using fstab from that vol) */
1530                 mkdir_p(cfg);
1531                 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1532                         err = mount_extroot(cfg);
1533                         umount2(cfg, MNT_DETACH);
1534                 }
1535                 if (err < 0)
1536                         rmdir("/tmp/overlay");
1537                 rmdir(cfg);
1538                 return err;
1539        }
1540 #endif
1541
1542         return mount_extroot(NULL);
1543 }
1544
1545 static int main_mount(int argc, char **argv)
1546 {
1547         struct probe_info *pr;
1548
1549         if (config_load(NULL))
1550                 return -1;
1551
1552         cache_load(1);
1553         list_for_each_entry(pr, &devices, list)
1554                 mount_device(pr, TYPE_DEV);
1555
1556         handle_swapfiles(true);
1557
1558         return 0;
1559 }
1560
1561 static int main_umount(int argc, char **argv)
1562 {
1563         struct probe_info *pr;
1564
1565         if (config_load(NULL))
1566                 return -1;
1567
1568         handle_swapfiles(false);
1569
1570         cache_load(0);
1571         list_for_each_entry(pr, &devices, list)
1572                 umount_device(pr);
1573
1574         return 0;
1575 }
1576
1577 static int main_detect(int argc, char **argv)
1578 {
1579         struct probe_info *pr;
1580
1581         cache_load(0);
1582         printf("config 'global'\n");
1583         printf("\toption\tanon_swap\t'0'\n");
1584         printf("\toption\tanon_mount\t'0'\n");
1585         printf("\toption\tauto_swap\t'1'\n");
1586         printf("\toption\tauto_mount\t'1'\n");
1587         printf("\toption\tdelay_root\t'5'\n");
1588         printf("\toption\tcheck_fs\t'0'\n\n");
1589         list_for_each_entry(pr, &devices, list)
1590                 print_block_uci(pr);
1591
1592         return 0;
1593 }
1594
1595 static int main_info(int argc, char **argv)
1596 {
1597         int i;
1598         struct probe_info *pr;
1599
1600         cache_load(1);
1601         if (argc == 2) {
1602                 list_for_each_entry(pr, &devices, list)
1603                         print_block_info(pr);
1604
1605                 return 0;
1606         };
1607
1608         for (i = 2; i < argc; i++) {
1609                 struct stat s;
1610
1611                 if (stat(argv[i], &s)) {
1612                         ULOG_ERR("failed to stat %s\n", argv[i]);
1613                         continue;
1614                 }
1615                 if (!S_ISBLK(s.st_mode) && !(S_ISCHR(s.st_mode) && major(s.st_rdev) == 250)) {
1616                         ULOG_ERR("%s is not a block device\n", argv[i]);
1617                         continue;
1618                 }
1619                 pr = find_block_info(NULL, NULL, argv[i]);
1620                 if (pr)
1621                         print_block_info(pr);
1622         }
1623
1624         return 0;
1625 }
1626
1627 static int swapon_usage(void)
1628 {
1629         fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1630                 "\tStart swapping on [DEVICE]\n"
1631                 " -a\tStart swapping on all swap devices\n"
1632                 " -p pri\tSet priority of swap device\n"
1633                 " -s\tShow summary\n");
1634         return -1;
1635 }
1636
1637 static int main_swapon(int argc, char **argv)
1638 {
1639         int ch;
1640         FILE *fp;
1641         char *lineptr;
1642         size_t s;
1643         struct probe_info *pr;
1644         int flags = 0;
1645         int pri;
1646         struct stat st;
1647         int err;
1648
1649         while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1650                 switch(ch) {
1651                 case 's':
1652                         fp = fopen("/proc/swaps", "r");
1653                         lineptr = NULL;
1654
1655                         if (!fp) {
1656                                 ULOG_ERR("failed to open /proc/swaps\n");
1657                                 return -1;
1658                         }
1659                         while (getline(&lineptr, &s, fp) > 0)
1660                                 printf("%s", lineptr);
1661                         if (lineptr)
1662                                 free(lineptr);
1663                         fclose(fp);
1664                         return 0;
1665                 case 'a':
1666                         cache_load(0);
1667                         list_for_each_entry(pr, &devices, list) {
1668                                 if (strcmp(pr->type, "swap"))
1669                                         continue;
1670                                 if (swapon(pr->dev, 0))
1671                                         ULOG_ERR("failed to swapon %s\n", pr->dev);
1672                         }
1673                         return 0;
1674                 case 'p':
1675                         pri = atoi(optarg);
1676                         if (pri >= 0)
1677                                 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1678                         break;
1679                 default:
1680                         return swapon_usage();
1681                 }
1682
1683         }
1684
1685         if (optind != (argc - 1))
1686                 return swapon_usage();
1687
1688         if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1689                 ULOG_ERR("%s is not a block device or file\n", argv[optind]);
1690                 return -1;
1691         }
1692         err = swapon(argv[optind], flags);
1693         if (err) {
1694                 ULOG_ERR("failed to swapon %s (%d)\n", argv[optind], err);
1695                 return err;
1696         }
1697
1698         return 0;
1699 }
1700
1701 static int main_swapoff(int argc, char **argv)
1702 {
1703         if (argc != 2) {
1704                 ULOG_ERR("Usage: swapoff [-a] [DEVICE]\n\n"
1705                         "\tStop swapping on DEVICE\n"
1706                         " -a\tStop swapping on all swap devices\n");
1707                 return -1;
1708         }
1709
1710         if (!strcmp(argv[1], "-a")) {
1711                 FILE *fp = fopen("/proc/swaps", "r");
1712                 char line[256];
1713
1714                 if (!fp) {
1715                         ULOG_ERR("failed to open /proc/swaps\n");
1716                         return -1;
1717                 }
1718                 if (fgets(line, sizeof(line), fp))
1719                         while (fgets(line, sizeof(line), fp)) {
1720                                 char *end = strchr(line, ' ');
1721                                 int err;
1722
1723                                 if (!end)
1724                                         continue;
1725                                 *end = '\0';
1726                                 err = swapoff(line);
1727                                 if (err)
1728                                         ULOG_ERR("failed to swapoff %s (%d)\n", line, err);
1729                         }
1730                 fclose(fp);
1731         } else {
1732                 struct stat s;
1733                 int err;
1734
1735                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1736                         ULOG_ERR("%s is not a block device or file\n", argv[1]);
1737                         return -1;
1738                 }
1739                 err = swapoff(argv[1]);
1740                 if (err) {
1741                         ULOG_ERR("failed to swapoff %s (%d)\n", argv[1], err);
1742                         return err;
1743                 }
1744         }
1745
1746         return 0;
1747 }
1748
1749 int main(int argc, char **argv)
1750 {
1751         char *base = basename(*argv);
1752
1753         umask(0);
1754
1755         ulog_open(-1, -1, "block");
1756         ulog_threshold(LOG_NOTICE);
1757
1758         if (!strcmp(base, "swapon"))
1759                 return main_swapon(argc, argv);
1760
1761         if (!strcmp(base, "swapoff"))
1762                 return main_swapoff(argc, argv);
1763
1764         if ((argc > 1) && !strcmp(base, "block")) {
1765                 if (!strcmp(argv[1], "info"))
1766                         return main_info(argc, argv);
1767
1768                 if (!strcmp(argv[1], "detect"))
1769                         return main_detect(argc, argv);
1770
1771                 if (!strcmp(argv[1], "hotplug"))
1772                         return main_hotplug(argc, argv);
1773
1774                 if (!strcmp(argv[1], "autofs"))
1775                         return main_autofs(argc, argv);
1776
1777                 if (!strcmp(argv[1], "extroot"))
1778                         return main_extroot(argc, argv);
1779
1780                 if (!strcmp(argv[1], "mount"))
1781                         return main_mount(argc, argv);
1782
1783                 if (!strcmp(argv[1], "umount"))
1784                         return main_umount(argc, argv);
1785
1786                 if (!strcmp(argv[1], "remount")) {
1787                         int ret = main_umount(argc, argv);
1788
1789                         if (!ret)
1790                                 ret = main_mount(argc, argv);
1791                         return ret;
1792                 }
1793         }
1794
1795         ULOG_ERR("Usage: block <info|mount|umount|detect>\n");
1796
1797         return -1;
1798 }