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