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