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