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