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