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