68cfd5a5a89207a7e03b438dff4ae0cfbd242521
[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         {
415                 char *err;
416                 uci_get_errorstr(ctx, &err, "fstab");
417                 ERROR("extroot: failed to load %s/etc/config/%s\n",
418                       cfg ? cfg : "", err);
419                 free(err);
420                 return -1;
421         }
422
423         vlist_update(&mounts);
424         uci_foreach_element(&pkg->sections, e) {
425                 struct uci_section *s = uci_to_section(e);
426
427                 if (!strcmp(s->type, "mount"))
428                         mount_add(s);
429                 if (!strcmp(s->type, "swap"))
430                         swap_add(s);
431                 if (!strcmp(s->type, "global"))
432                         global_add(s);
433         }
434         vlist_flush(&mounts);
435
436         return 0;
437 }
438
439 static struct blkid_struct_probe* _probe_path(char *path)
440 {
441         struct blkid_struct_probe *pr;
442
443         pr = malloc(sizeof(*pr));
444
445         if (!pr)
446                 return NULL;
447
448         memset(pr, 0, sizeof(*pr));
449         probe_block(path, pr);
450
451         if (pr->err || !pr->id) {
452                 free(pr);
453                 return NULL;
454         }
455
456         return pr;
457 }
458
459 static int _cache_load(const char *path)
460 {
461         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
462         int j;
463         glob_t gl;
464
465         if (glob(path, gl_flags, NULL, &gl) < 0)
466                 return -1;
467
468         for (j = 0; j < gl.gl_pathc; j++) {
469                 struct blkid_struct_probe *pr = _probe_path(gl.gl_pathv[j]);
470                 if (pr)
471                         list_add_tail(&pr->list, &devices);
472         }
473
474         globfree(&gl);
475
476         return 0;
477 }
478
479 static void cache_load(int mtd)
480 {
481         if (mtd) {
482                 _cache_load("/dev/mtdblock*");
483                 _cache_load("/dev/ubiblock*");
484                 _cache_load("/dev/ubi?*_?*");
485         }
486         _cache_load("/dev/mmcblk*");
487         _cache_load("/dev/sd*");
488         _cache_load("/dev/hd*");
489         _cache_load("/dev/md*");
490         _cache_load("/dev/vd*");
491         _cache_load("/dev/mapper/*");
492 }
493
494 static int print_block_info(struct blkid_struct_probe *pr)
495 {
496         printf("%s:", pr->dev);
497         if (pr->uuid[0])
498                 printf(" UUID=\"%s\"", pr->uuid);
499
500         if (pr->label[0])
501                 printf(" LABEL=\"%s\"", pr->label);
502
503         if (pr->name[0])
504                 printf(" NAME=\"%s\"", pr->name);
505
506         if (pr->version[0])
507                 printf(" VERSION=\"%s\"", pr->version);
508
509         printf(" TYPE=\"%s\"\n", pr->id->name);
510
511         return 0;
512 }
513
514 static int print_block_uci(struct blkid_struct_probe *pr)
515 {
516         if (!strcmp(pr->id->name, "swap")) {
517                 printf("config 'swap'\n");
518         } else {
519                 printf("config 'mount'\n");
520                 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
521         }
522         if (pr->uuid[0])
523                 printf("\toption\tuuid\t'%s'\n", pr->uuid);
524         else
525                 printf("\toption\tdevice\t'%s'\n", pr->dev);
526         printf("\toption\tenabled\t'0'\n\n");
527
528         return 0;
529 }
530
531 static struct blkid_struct_probe* find_block_info(char *uuid, char *label, char *path)
532 {
533         struct blkid_struct_probe *pr = NULL;
534
535         if (uuid)
536                 list_for_each_entry(pr, &devices, list)
537                         if (!strcasecmp(pr->uuid, uuid))
538                                 return pr;
539
540         if (label)
541                 list_for_each_entry(pr, &devices, list)
542                         if (!strcmp(pr->label, label))
543                                 return pr;
544
545         if (path)
546                 list_for_each_entry(pr, &devices, list)
547                         if (!strcmp(basename(pr->dev), basename(path)))
548                                 return pr;
549
550         return NULL;
551 }
552
553 static char* find_mount_point(char *block)
554 {
555         FILE *fp = fopen("/proc/mounts", "r");
556         static char line[256];
557         int len = strlen(block);
558         char *point = NULL;
559
560         if(!fp)
561                 return NULL;
562
563         while (fgets(line, sizeof(line), fp)) {
564                 if (!strncmp(line, block, len)) {
565                         char *p = &line[len + 1];
566                         char *t = strstr(p, " ");
567
568                         if (!t) {
569                                 fclose(fp);
570                                 return NULL;
571                         }
572                         *t = '\0';
573                         point = p;
574                         break;
575                 }
576         }
577
578         fclose(fp);
579
580         return point;
581 }
582
583 static void mkdir_p(char *dir)
584 {
585         char *l = strrchr(dir, '/');
586
587         if (l) {
588                 *l = '\0';
589                 mkdir_p(dir);
590                 *l = '/';
591                 mkdir(dir, 0755);
592         }
593 }
594
595 static void check_filesystem(struct blkid_struct_probe *pr)
596 {
597         pid_t pid;
598         struct stat statbuf;
599         char *e2fsck = "/usr/sbin/e2fsck";
600
601         if (strncmp(pr->id->name, "ext", 3)) {
602                 ERROR("check_filesystem: %s is not supported\n", pr->id->name);
603                 return;
604         }
605
606         if (stat(e2fsck, &statbuf) < 0) {
607                 ERROR("check_filesystem: %s not found\n", e2fsck);
608                 return;
609         }
610
611         pid = fork();
612         if (!pid) {
613                 execl(e2fsck, e2fsck, "-p", pr->dev, NULL);
614                 exit(-1);
615         } else if (pid > 0) {
616                 int status;
617
618                 waitpid(pid, &status, 0);
619                 if (WEXITSTATUS(status))
620                         ERROR("check_filesystem: %s returned %d\n", e2fsck, WEXITSTATUS(status));
621         }
622 }
623
624 static void handle_swapfiles(bool on)
625 {
626         struct stat s;
627         struct mount *m;
628         struct blkid_struct_probe *pr;
629
630         vlist_for_each_element(&mounts, m, node)
631         {
632                 if (m->type != TYPE_SWAP || !m->target)
633                         continue;
634
635                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
636                         continue;
637
638                 pr = _probe_path(m->target);
639
640                 if (!pr)
641                         continue;
642
643                 if (!strcmp(pr->id->name, "swap")) {
644                         if (on)
645                                 swapon(pr->dev, m->prio);
646                         else
647                                 swapoff(pr->dev);
648                 }
649
650                 free(pr);
651         }
652 }
653
654 static int mount_device(struct blkid_struct_probe *pr, int hotplug)
655 {
656         struct mount *m;
657         char *device;
658
659         if (!pr)
660                 return -1;
661
662         device = basename(pr->dev);
663
664         if (!strcmp(pr->id->name, "swap")) {
665                 if (hotplug && !auto_swap)
666                         return -1;
667                 m = find_swap(pr->uuid, pr->label, device);
668                 if (m || anon_swap)
669                         swapon(pr->dev, (m) ? (m->prio) : (0));
670
671                 return 0;
672         }
673
674         if (hotplug && !auto_mount)
675                 return -1;
676
677         if (find_mount_point(pr->dev)) {
678                 ERROR("%s is already mounted\n", pr->dev);
679                 return -1;
680         }
681
682         m = find_block(pr->uuid, pr->label, device, NULL);
683         if (m && m->extroot)
684                 return -1;
685
686         if (m) {
687                 char *target = m->target;
688                 char _target[32];
689                 int err = 0;
690
691                 if (!target) {
692                         snprintf(_target, sizeof(_target), "/mnt/%s", device);
693                         target = _target;
694                 }
695                 mkdir_p(target);
696
697                 if (check_fs)
698                         check_filesystem(pr);
699
700                 err = mount(pr->dev, target, pr->id->name, m->flags,
701                             (m->options) ? (m->options) : (""));
702                 if (err)
703                         ERROR("mounting %s (%s) as %s failed (%d) - %s\n",
704                                         pr->dev, pr->id->name, target, err, strerror(err));
705                 else
706                         handle_swapfiles(true);
707                 return err;
708         }
709
710         if (anon_mount) {
711                 char target[] = "/mnt/mmcblk123";
712                 int err = 0;
713
714                 snprintf(target, sizeof(target), "/mnt/%s", device);
715                 mkdir_p(target);
716
717                 if (check_fs)
718                         check_filesystem(pr);
719
720                 err = mount(pr->dev, target, pr->id->name, 0, "");
721                 if (err)
722                         ERROR("mounting %s (%s) as %s failed (%d) - %s\n",
723                                         pr->dev, pr->id->name, target, err, strerror(err));
724                 else
725                         handle_swapfiles(true);
726                 return err;
727         }
728
729         return 0;
730 }
731
732 static int umount_device(struct blkid_struct_probe *pr)
733 {
734         struct mount *m;
735         char *device = basename(pr->dev);
736         char *mp;
737         int err;
738
739         if (!pr)
740                 return -1;
741
742         if (!strcmp(pr->id->name, "swap"))
743                 return -1;
744
745         mp = find_mount_point(pr->dev);
746         if (!mp)
747                 return -1;
748
749         m = find_block(pr->uuid, pr->label, device, NULL);
750         if (m && m->extroot)
751                 return -1;
752
753         err = umount2(mp, MNT_DETACH);
754         if (err)
755                 ERROR("unmounting %s (%s)  failed (%d) - %s\n",
756                         pr->dev, mp, err, strerror(err));
757         else
758                 ERROR("unmounted %s (%s)\n",
759                         pr->dev, mp);
760
761         return err;
762 }
763
764 static int main_hotplug(int argc, char **argv)
765 {
766         char path[32];
767         char *action, *device, *mount_point;
768
769         action = getenv("ACTION");
770         device = getenv("DEVNAME");
771
772         if (!action || !device)
773                 return -1;
774         snprintf(path, sizeof(path), "/dev/%s", device);
775
776         if (!strcmp(action, "remove")) {
777                 int err = 0;
778                 mount_point = find_mount_point(path);
779                 if (mount_point)
780                         err = umount2(mount_point, MNT_DETACH);
781
782                 if (err)
783                         ERROR("umount of %s failed (%d) - %s\n",
784                                         mount_point, err, strerror(err));
785
786                 return 0;
787         } else if (strcmp(action, "add")) {
788                 ERROR("Unkown action %s\n", action);
789
790                 return -1;
791         }
792
793         if (config_load(NULL))
794                 return -1;
795         cache_load(0);
796
797         return mount_device(find_block_info(NULL, NULL, path), 1);
798 }
799
800 static int find_block_mtd(char *name, char *part, int plen)
801 {
802         FILE *fp = fopen("/proc/mtd", "r");
803         static char line[256];
804         char *index = NULL;
805
806         if(!fp)
807                 return -1;
808
809         while (!index && fgets(line, sizeof(line), fp)) {
810                 if (strstr(line, name)) {
811                         char *eol = strstr(line, ":");
812
813                         if (!eol)
814                                 continue;
815
816                         *eol = '\0';
817                         index = &line[3];
818                 }
819         }
820
821         fclose(fp);
822
823         if (!index)
824                 return -1;
825
826         snprintf(part, plen, "/dev/mtdblock%s", index);
827
828         return 0;
829 }
830
831 #ifdef UBIFS_EXTROOT
832 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
833 {
834         int dev = 0;
835
836         while (ubi_dev_present(libubi, dev))
837         {
838                 struct ubi_dev_info dev_info;
839                 struct ubi_vol_info vol_info;
840
841                 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
842                         continue;
843                 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
844                         continue;
845
846                 *dev_num = dev_info.dev_num;
847                 *vol_id = vol_info.vol_id;
848
849                 return 0;
850         }
851
852         return -1;
853 }
854
855 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
856 {
857         int dev_num;
858         int vol_id;
859         int err = -1;
860
861         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
862         if (!err)
863                 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
864
865         return err;
866 }
867
868 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
869 {
870         int dev_num;
871         int vol_id;
872         int err = -1;
873
874         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
875         if (!err)
876                 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
877
878         return err;
879 }
880 #endif
881
882 static int check_extroot(char *path)
883 {
884         struct blkid_struct_probe *pr = NULL;
885         char fs[32];
886
887 #ifdef UBIFS_EXTROOT
888         if (find_block_mtd("rootfs", fs, sizeof(fs))) {
889                 int err = -1;
890                 libubi_t libubi;
891
892                 libubi = libubi_open();
893                 err = find_block_ubi_RO(libubi, "rootfs", fs, sizeof(fs));
894                 libubi_close(libubi);
895                 if (err)
896                         return -1;
897         }
898 #else
899         if (find_block_mtd("rootfs", fs, sizeof(fs)))
900                 return -1;
901 #endif
902
903         list_for_each_entry(pr, &devices, list) {
904                 if (!strcmp(pr->dev, fs)) {
905                         struct stat s;
906                         FILE *fp = NULL;
907                         char tag[64];
908                         char uuid[64] = { 0 };
909
910                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
911                         if (stat(tag, &s)) {
912                                 fp = fopen(tag, "w+");
913                                 if (!fp) {
914                                         ERROR("extroot: failed to write uuid tag file\n");
915                                         /* return 0 to continue boot regardless of error */
916                                         return 0;
917                                 }
918                                 fputs(pr->uuid, fp);
919                                 fclose(fp);
920                                 return 0;
921                         }
922
923                         fp = fopen(tag, "r");
924                         if (!fp) {
925                                 ERROR("extroot: failed to open uuid tag file\n");
926                                 return -1;
927                         }
928
929                         fgets(uuid, sizeof(uuid), fp);
930                         fclose(fp);
931                         if (!strcasecmp(uuid, pr->uuid))
932                                 return 0;
933                         ERROR("extroot: uuid tag does not match rom uuid\n");
934                 }
935         }
936         return -1;
937 }
938
939 /*
940  * Read info about extroot from UCI (using prefix) and mount it.
941  */
942 static int mount_extroot(char *cfg)
943 {
944         char overlay[] = "/tmp/extroot/overlay";
945         char mnt[] = "/tmp/extroot/mnt";
946         char *path = mnt;
947         struct blkid_struct_probe *pr;
948         struct mount *m;
949         int err = -1;
950
951         /* Load @cfg/etc/config/fstab */
952         if (config_load(cfg))
953                 return -2;
954
955         /* See if there is extroot-specific mount config */
956         m = find_block(NULL, NULL, NULL, "/");
957         if (!m)
958                 m = find_block(NULL, NULL, NULL, "/overlay");
959
960         if (!m || !m->extroot)
961         {
962                 ERROR("extroot: no root or overlay mount defined\n");
963                 return -1;
964         }
965
966         /* Find block device pointed by the mount config */
967         pr = find_block_info(m->uuid, m->label, m->device);
968
969         if (!pr && delay_root){
970                 ERROR("extroot: is not ready yet, retrying in %u seconds\n", delay_root);
971                 sleep(delay_root);
972                 mkblkdev();
973                 cache_load(0);
974                 pr = find_block_info(m->uuid, m->label, m->device);
975         }
976         if (pr) {
977                 if (strncmp(pr->id->name, "ext", 3)) {
978                         ERROR("extroot: %s is not supported, try ext4\n", pr->id->name);
979                         return -1;
980                 }
981                 if (m->overlay)
982                         path = overlay;
983                 mkdir_p(path);
984
985                 if (check_fs)
986                         check_filesystem(pr);
987
988                 err = mount(pr->dev, path, pr->id->name, 0, (m->options) ? (m->options) : (""));
989
990                 if (err) {
991                         ERROR("mounting %s (%s) as %s failed (%d) - %s\n",
992                                         pr->dev, pr->id->name, path, err, strerror(err));
993                 } else if (m->overlay) {
994                         err = check_extroot(path);
995                         if (err)
996                                 umount(path);
997                 }
998         } else {
999                 ERROR("extroot: cannot find block device\n");
1000         }
1001
1002         return err;
1003 }
1004
1005 static int main_extroot(int argc, char **argv)
1006 {
1007         struct blkid_struct_probe *pr;
1008         char fs[32] = { 0 };
1009         char blkdev_path[32] = { 0 };
1010         int err = -1;
1011 #ifdef UBIFS_EXTROOT
1012         libubi_t libubi;
1013 #endif
1014
1015         if (!getenv("PREINIT"))
1016                 return -1;
1017
1018         if (argc != 2) {
1019                 fprintf(stderr, "Usage: block extroot mountpoint\n");
1020                 return -1;
1021         }
1022
1023         mkblkdev();
1024         cache_load(1);
1025
1026         /*
1027          * Make sure there is "rootfs" MTD partition or UBI volume.
1028          * TODO: What for?
1029          */
1030         find_block_mtd("rootfs", fs, sizeof(fs));
1031         if (!fs[0]) {
1032 #ifdef UBIFS_EXTROOT
1033                 libubi = libubi_open();
1034                 find_block_ubi_RO(libubi, "rootfs", fs, sizeof(fs));
1035                 libubi_close(libubi);
1036                 if (!fs[0]) {
1037                         ERROR("extroot: unable to locate rootfs mtdblock / ubiblock\n");
1038                         return -2;
1039                 }
1040 #else
1041                 ERROR("extroot: unable to locate rootfs mtdblock\n");
1042                 return -2;
1043 #endif
1044         }
1045
1046         pr = find_block_info(NULL, NULL, fs);
1047         if (!pr) {
1048                 ERROR("extroot: unable to retrieve rootfs information\n");
1049                 return -3;
1050         }
1051
1052         /*
1053          * Look for "rootfs_data". We will want to mount it and check for
1054          * extroot configuration.
1055          */
1056
1057         /* Start with looking for MTD partition */
1058         find_block_mtd("rootfs_data", blkdev_path, sizeof(blkdev_path));
1059         if (blkdev_path[0]) {
1060                 pr = find_block_info(NULL, NULL, blkdev_path);
1061                 if (pr && !strcmp(pr->id->name, "jffs2")) {
1062                         char cfg[] = "/tmp/jffs_cfg";
1063
1064                         /*
1065                          * Mount MTD part and try extroot (using
1066                          * /etc/config/fstab from that partition)
1067                          */
1068                         mkdir_p(cfg);
1069                         if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1070                                 err = mount_extroot(cfg);
1071                                 umount2(cfg, MNT_DETACH);
1072                         }
1073                         if (err < 0)
1074                                 rmdir("/tmp/overlay");
1075                         rmdir(cfg);
1076                         return err;
1077                 }
1078         }
1079
1080 #ifdef UBIFS_EXTROOT
1081         /* ... but it also could be an UBI volume */
1082         memset(blkdev_path, 0, sizeof(blkdev_path));
1083         libubi = libubi_open();
1084         find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1085         libubi_close(libubi);
1086         if (blkdev_path[0]) {
1087                 char cfg[] = "/tmp/ubifs_cfg";
1088
1089                 /* Mount volume and try extroot (using fstab from that vol) */
1090                 mkdir_p(cfg);
1091                 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1092                         err = mount_extroot(cfg);
1093                         umount2(cfg, MNT_DETACH);
1094                 }
1095                 if (err < 0)
1096                         rmdir("/tmp/overlay");
1097                 rmdir(cfg);
1098                 return err;
1099        }
1100 #endif
1101
1102         return mount_extroot(NULL);
1103 }
1104
1105 static int main_mount(int argc, char **argv)
1106 {
1107         struct blkid_struct_probe *pr;
1108
1109         if (config_load(NULL))
1110                 return -1;
1111
1112         cache_load(1);
1113         list_for_each_entry(pr, &devices, list)
1114                 mount_device(pr, 0);
1115
1116         handle_swapfiles(true);
1117
1118         return 0;
1119 }
1120
1121 static int main_umount(int argc, char **argv)
1122 {
1123         struct blkid_struct_probe *pr;
1124
1125         if (config_load(NULL))
1126                 return -1;
1127
1128         handle_swapfiles(false);
1129
1130         cache_load(0);
1131         list_for_each_entry(pr, &devices, list)
1132                 umount_device(pr);
1133
1134         return 0;
1135 }
1136
1137 static int main_detect(int argc, char **argv)
1138 {
1139         struct blkid_struct_probe *pr;
1140
1141         cache_load(0);
1142         printf("config 'global'\n");
1143         printf("\toption\tanon_swap\t'0'\n");
1144         printf("\toption\tanon_mount\t'0'\n");
1145         printf("\toption\tauto_swap\t'1'\n");
1146         printf("\toption\tauto_mount\t'1'\n");
1147         printf("\toption\tdelay_root\t'5'\n");
1148         printf("\toption\tcheck_fs\t'0'\n\n");
1149         list_for_each_entry(pr, &devices, list)
1150                 print_block_uci(pr);
1151
1152         return 0;
1153 }
1154
1155 static int main_info(int argc, char **argv)
1156 {
1157         int i;
1158         struct blkid_struct_probe *pr;
1159
1160         cache_load(1);
1161         if (argc == 2) {
1162                 list_for_each_entry(pr, &devices, list)
1163                         print_block_info(pr);
1164
1165                 return 0;
1166         };
1167
1168         for (i = 2; i < argc; i++) {
1169                 struct stat s;
1170
1171                 if (stat(argv[i], &s)) {
1172                         ERROR("failed to stat %s\n", argv[i]);
1173                         continue;
1174                 }
1175                 if (!S_ISBLK(s.st_mode)) {
1176                         ERROR("%s is not a block device\n", argv[i]);
1177                         continue;
1178                 }
1179                 pr = find_block_info(NULL, NULL, argv[i]);
1180                 if (pr)
1181                         print_block_info(pr);
1182         }
1183
1184         return 0;
1185 }
1186
1187 static int swapon_usage(void)
1188 {
1189         fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1190                 "\tStart swapping on [DEVICE]\n"
1191                 " -a\tStart swapping on all swap devices\n"
1192                 " -p pri\tSet priority of swap device\n"
1193                 " -s\tShow summary\n");
1194         return -1;
1195 }
1196
1197 static int main_swapon(int argc, char **argv)
1198 {
1199         int ch;
1200         FILE *fp;
1201         char *lineptr;
1202         size_t s;
1203         struct blkid_struct_probe *pr;
1204         int flags = 0;
1205         int pri;
1206         struct stat st;
1207         int err;
1208
1209         while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1210                 switch(ch) {
1211                 case 's':
1212                         fp = fopen("/proc/swaps", "r");
1213                         lineptr = NULL;
1214
1215                         if (!fp) {
1216                                 ERROR("failed to open /proc/swaps\n");
1217                                 return -1;
1218                         }
1219                         while (getline(&lineptr, &s, fp) > 0)
1220                                 printf(lineptr);
1221                         if (lineptr)
1222                                 free(lineptr);
1223                         fclose(fp);
1224                         return 0;
1225                 case 'a':
1226                         cache_load(0);
1227                         list_for_each_entry(pr, &devices, list) {
1228                                 if (strcmp(pr->id->name, "swap"))
1229                                         continue;
1230                                 if (swapon(pr->dev, 0))
1231                                         ERROR("failed to swapon %s\n", pr->dev);
1232                         }
1233                         return 0;
1234                 case 'p':
1235                         pri = atoi(optarg);
1236                         if (pri >= 0)
1237                                 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1238                         break;
1239                 default:
1240                         return swapon_usage();
1241                 }
1242
1243         }
1244
1245         if (optind != (argc - 1))
1246                 return swapon_usage();
1247
1248         if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1249                 ERROR("%s is not a block device or file\n", argv[optind]);
1250                 return -1;
1251         }
1252         err = swapon(argv[optind], flags);
1253         if (err) {
1254                 ERROR("failed to swapon %s (%d)\n", argv[optind], err);
1255                 return err;
1256         }
1257
1258         return 0;
1259 }
1260
1261 static int main_swapoff(int argc, char **argv)
1262 {
1263         if (argc != 2) {
1264                 ERROR("Usage: swapoff [-a] [DEVICE]\n\n"
1265                         "\tStop swapping on DEVICE\n"
1266                         " -a\tStop swapping on all swap devices\n");
1267                 return -1;
1268         }
1269
1270         if (!strcmp(argv[1], "-a")) {
1271                 FILE *fp = fopen("/proc/swaps", "r");
1272                 char line[256];
1273
1274                 if (!fp) {
1275                         ERROR("failed to open /proc/swaps\n");
1276                         return -1;
1277                 }
1278                 fgets(line, sizeof(line), fp);
1279                 while (fgets(line, sizeof(line), fp)) {
1280                         char *end = strchr(line, ' ');
1281                         int err;
1282
1283                         if (!end)
1284                                 continue;
1285                         *end = '\0';
1286                         err = swapoff(line);
1287                         if (err)
1288                                 ERROR("failed to swapoff %s (%d)\n", line, err);
1289                 }
1290                 fclose(fp);
1291         } else {
1292                 struct stat s;
1293                 int err;
1294
1295                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1296                         ERROR("%s is not a block device or file\n", argv[1]);
1297                         return -1;
1298                 }
1299                 err = swapoff(argv[1]);
1300                 if (err) {
1301                         ERROR("fsiled to swapoff %s (%d)\n", argv[1], err);
1302                         return err;
1303                 }
1304         }
1305
1306         return 0;
1307 }
1308
1309 int main(int argc, char **argv)
1310 {
1311         char *base = basename(*argv);
1312
1313         umask(0);
1314
1315         if (!strcmp(base, "swapon"))
1316                 return main_swapon(argc, argv);
1317
1318         if (!strcmp(base, "swapoff"))
1319                 return main_swapoff(argc, argv);
1320
1321         if ((argc > 1) && !strcmp(base, "block")) {
1322                 if (!strcmp(argv[1], "info"))
1323                         return main_info(argc, argv);
1324
1325                 if (!strcmp(argv[1], "detect"))
1326                         return main_detect(argc, argv);
1327
1328                 if (!strcmp(argv[1], "hotplug"))
1329                         return main_hotplug(argc, argv);
1330
1331                 if (!strcmp(argv[1], "extroot"))
1332                         return main_extroot(argc, argv);
1333
1334                 if (!strcmp(argv[1], "mount"))
1335                         return main_mount(argc, argv);
1336
1337                 if (!strcmp(argv[1], "umount"))
1338                         return main_umount(argc, argv);
1339         }
1340
1341         fprintf(stderr, "Usage: block <info|mount|umount|detect>\n");
1342
1343         return -1;
1344 }