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