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