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