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