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