084e7fc95f076776660232dd9500cb8f4419e116
[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 int print_block_uci(struct probe_info *pr)
579 {
580 if (!strcmp(pr->type, "swap")) {
581 printf("config 'swap'\n");
582 } else {
583 printf("config 'mount'\n");
584 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
585 }
586 if (pr->uuid)
587 printf("\toption\tuuid\t'%s'\n", pr->uuid);
588 else
589 printf("\toption\tdevice\t'%s'\n", pr->dev);
590 printf("\toption\tenabled\t'0'\n\n");
591
592 return 0;
593 }
594
595 static struct device* find_block_device(char *uuid, char *label, char *path)
596 {
597 struct device *dev;
598
599 if (uuid)
600 vlist_for_each_element(&devices, dev, node)
601 if (dev->pr->uuid && !strcasecmp(dev->pr->uuid, uuid))
602 return dev;
603
604 if (label)
605 vlist_for_each_element(&devices, dev, node)
606 if (dev->pr->label && !strcmp(dev->pr->label, label))
607 return dev;
608
609 if (path)
610 vlist_for_each_element(&devices, dev, node)
611 if (dev->pr->dev && !strcmp(basename(dev->pr->dev), basename(path)))
612 return dev;
613
614 return NULL;
615 }
616
617 static char* find_mount_point(char *block)
618 {
619 FILE *fp = fopen("/proc/self/mountinfo", "r");
620 static char line[256];
621 char *point = NULL, *pos, *tmp, *cpoint, *devname;
622 struct stat s;
623 int rstat;
624 unsigned int minor, major;
625
626 if (!fp)
627 return NULL;
628
629 rstat = stat(block, &s);
630
631 while (fgets(line, sizeof(line), fp)) {
632 pos = strchr(line, ' ');
633 if (!pos)
634 continue;
635
636 pos = strchr(pos + 1, ' ');
637 if (!pos)
638 continue;
639
640 tmp = ++pos;
641 pos = strchr(pos, ':');
642 if (!pos)
643 continue;
644
645 *pos = '\0';
646 major = atoi(tmp);
647 tmp = ++pos;
648 pos = strchr(pos, ' ');
649 if (!pos)
650 continue;
651
652 *pos = '\0';
653 minor = atoi(tmp);
654 pos = strchr(pos + 1, ' ');
655 if (!pos)
656 continue;
657 tmp = ++pos;
658
659 pos = strchr(pos, ' ');
660 if (!pos)
661 continue;
662 *pos = '\0';
663 cpoint = tmp;
664
665 pos = strchr(pos + 1, ' ');
666 if (!pos)
667 continue;
668
669 pos = strchr(pos + 1, ' ');
670 if (!pos)
671 continue;
672
673 pos = strchr(pos + 1, ' ');
674 if (!pos)
675 continue;
676
677 tmp = ++pos;
678 pos = strchr(pos, ' ');
679 if (!pos)
680 continue;
681
682 *pos = '\0';
683 devname = tmp;
684 if (!strcmp(block, devname)) {
685 point = strdup(cpoint);
686 break;
687 }
688
689 if (rstat)
690 continue;
691
692 if (!S_ISBLK(s.st_mode))
693 continue;
694
695 if (major == major(s.st_rdev) &&
696 minor == minor(s.st_rdev)) {
697 point = strdup(cpoint);
698 break;
699 }
700 }
701
702 fclose(fp);
703
704 return point;
705 }
706
707 static int print_block_info(struct probe_info *pr)
708 {
709 static char *mp;
710
711 mp = find_mount_point(pr->dev);
712 printf("%s:", pr->dev);
713 if (pr->uuid)
714 printf(" UUID=\"%s\"", pr->uuid);
715
716 if (pr->label)
717 printf(" LABEL=\"%s\"", pr->label);
718
719 if (pr->version)
720 printf(" VERSION=\"%s\"", pr->version);
721
722 if (mp) {
723 printf(" MOUNT=\"%s\"", mp);
724 free(mp);
725 }
726
727 printf(" TYPE=\"%s\"\n", pr->type);
728
729 return 0;
730 }
731
732 static void mkdir_p(char *dir)
733 {
734 char *l = strrchr(dir, '/');
735
736 if (l) {
737 *l = '\0';
738 mkdir_p(dir);
739 *l = '/';
740 mkdir(dir, 0755);
741 }
742 }
743
744 static void check_filesystem(struct probe_info *pr)
745 {
746 pid_t pid;
747 struct stat statbuf;
748 const char *e2fsck = "/usr/sbin/e2fsck";
749 const char *f2fsck = "/usr/sbin/fsck.f2fs";
750 const char *fatfsck = "/usr/sbin/fsck.fat";
751 const char *btrfsck = "/usr/bin/btrfsck";
752 const char *ntfsck = "/usr/bin/ntfsfix";
753 const char *ckfs;
754
755 /* UBIFS does not need stuff like fsck */
756 if (!strncmp(pr->type, "ubifs", 5))
757 return;
758
759 if (!strncmp(pr->type, "vfat", 4)) {
760 ckfs = fatfsck;
761 } else if (!strncmp(pr->type, "f2fs", 4)) {
762 ckfs = f2fsck;
763 } else if (!strncmp(pr->type, "ext", 3)) {
764 ckfs = e2fsck;
765 } else if (!strncmp(pr->type, "btrfs", 5)) {
766 ckfs = btrfsck;
767 } else if (!strncmp(pr->type, "ntfs", 4)) {
768 ckfs = ntfsck;
769 } else {
770 ULOG_ERR("check_filesystem: %s is not supported\n", pr->type);
771 return;
772 }
773
774 if (stat(ckfs, &statbuf) < 0) {
775 ULOG_ERR("check_filesystem: %s not found\n", ckfs);
776 return;
777 }
778
779 pid = fork();
780 if (!pid) {
781 if(!strncmp(pr->type, "f2fs", 4)) {
782 execl(ckfs, ckfs, "-f", pr->dev, NULL);
783 exit(EXIT_FAILURE);
784 } else if(!strncmp(pr->type, "btrfs", 5)) {
785 execl(ckfs, ckfs, "--repair", pr->dev, NULL);
786 exit(EXIT_FAILURE);
787 } else if(!strncmp(pr->type, "ntfs", 4)) {
788 execl(ckfs, ckfs, "-b", pr->dev, NULL);
789 exit(EXIT_FAILURE);
790 } else {
791 execl(ckfs, ckfs, "-p", pr->dev, NULL);
792 exit(EXIT_FAILURE);
793 }
794 } else if (pid > 0) {
795 int status;
796
797 waitpid(pid, &status, 0);
798 if (WIFEXITED(status) && WEXITSTATUS(status))
799 ULOG_ERR("check_filesystem: %s returned %d\n", ckfs, WEXITSTATUS(status));
800 if (WIFSIGNALED(status))
801 ULOG_ERR("check_filesystem: %s terminated by %s\n", ckfs, strsignal(WTERMSIG(status)));
802 }
803 }
804
805 static void handle_swapfiles(bool on)
806 {
807 struct stat s;
808 struct mount *m;
809 struct probe_info *pr;
810
811 vlist_for_each_element(&mounts, m, node)
812 {
813 if (m->type != TYPE_SWAP || !m->target)
814 continue;
815
816 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
817 continue;
818
819 pr = _probe_path(m->target);
820
821 if (!pr)
822 continue;
823
824 if (!strcmp(pr->type, "swap")) {
825 if (on)
826 swapon(pr->dev, m->prio);
827 else
828 swapoff(pr->dev);
829 }
830
831 free(pr);
832 }
833 }
834
835 static void to_devnull(int fd)
836 {
837 int devnull = open("/dev/null", fd ? O_WRONLY : O_RDONLY);
838
839 if (devnull >= 0)
840 dup2(devnull, fd);
841
842 if (devnull > STDERR_FILENO)
843 close(devnull);
844 }
845
846 static int exec_mount(const char *source, const char *target,
847 const char *fstype, const char *options)
848 {
849 pid_t pid;
850 struct stat s;
851 FILE *mount_fd;
852 int err, status, pfds[2];
853 char errmsg[128], cmd[sizeof("/sbin/mount.XXXXXXXXXXXXXXXX\0")];
854
855 snprintf(cmd, sizeof(cmd), "/sbin/mount.%s", fstype);
856
857 if (stat(cmd, &s) < 0 || !S_ISREG(s.st_mode) || !(s.st_mode & S_IXUSR)) {
858 ULOG_ERR("No \"mount.%s\" utility available\n", fstype);
859 return -1;
860 }
861
862 if (pipe(pfds) < 0)
863 return -1;
864
865 fcntl(pfds[0], F_SETFD, fcntl(pfds[0], F_GETFD) | FD_CLOEXEC);
866 fcntl(pfds[1], F_SETFD, fcntl(pfds[1], F_GETFD) | FD_CLOEXEC);
867
868 pid = vfork();
869
870 switch (pid) {
871 case -1:
872 close(pfds[0]);
873 close(pfds[1]);
874
875 return -1;
876
877 case 0:
878 to_devnull(STDIN_FILENO);
879 to_devnull(STDOUT_FILENO);
880
881 dup2(pfds[1], STDERR_FILENO);
882 close(pfds[0]);
883 close(pfds[1]);
884
885 if (options && *options)
886 execl(cmd, cmd, "-o", options, source, target, NULL);
887 else
888 execl(cmd, cmd, source, target, NULL);
889
890 return -1;
891
892 default:
893 close(pfds[1]);
894
895 mount_fd = fdopen(pfds[0], "r");
896
897 while (fgets(errmsg, sizeof(errmsg), mount_fd))
898 ULOG_ERR("mount.%s: %s", fstype, errmsg);
899
900 fclose(mount_fd);
901
902 err = waitpid(pid, &status, 0);
903
904 if (err != -1) {
905 if (status != 0) {
906 ULOG_ERR("mount.%s: failed with status %d\n", fstype, status);
907 errno = EINVAL;
908 err = -1;
909 } else {
910 errno = 0;
911 err = 0;
912 }
913 }
914
915 break;
916 }
917
918 return err;
919 }
920
921 static int hotplug_call_mount(const char *action, const char *device)
922 {
923 pid_t pid;
924 int err = 0;
925
926 pid = fork();
927 if (!pid) {
928 char * const argv[] = { "hotplug-call", "mount", NULL };
929
930 setenv("ACTION", action, 1);
931 setenv("DEVICE", device, 1);
932
933 execv("/sbin/hotplug-call", argv);
934 exit(-1);
935 } else if (pid > 0) {
936 int status;
937
938 pid = waitpid(pid, &status, 0);
939 if (pid <= 0 || !WIFEXITED(status) || WEXITSTATUS(status)) {
940 err = -ENOEXEC;
941 ULOG_ERR("hotplug-call call failed\n");
942 }
943 } else {
944 err = -errno;
945 }
946
947 return err;
948 }
949
950 static int handle_mount(const char *source, const char *target,
951 const char *fstype, struct mount *m)
952 {
953 int i, err;
954 size_t mount_opts_len;
955 char *mount_opts = NULL, *ptr;
956
957 err = mount(source, target, fstype, m ? m->flags : 0,
958 (m && m->options) ? m->options : "");
959
960 /* Requested file system type is not available in kernel,
961 attempt to call mount helper. */
962 if (err == -1 && errno == ENODEV) {
963 if (m) {
964 /* Convert mount flags back into string representation,
965 first calculate needed length of string buffer... */
966 mount_opts_len = 1 + (m->options ? strlen(m->options) : 0);
967
968 for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
969 if ((mount_flags[i].flag > 0) &&
970 (mount_flags[i].flag < INT_MAX) &&
971 (m->flags & (uint32_t)mount_flags[i].flag))
972 mount_opts_len += strlen(mount_flags[i].name) + 1;
973
974 /* ... then now allocate and fill it ... */
975 ptr = mount_opts = calloc(1, mount_opts_len);
976
977 if (!ptr) {
978 errno = ENOMEM;
979 return -1;
980 }
981
982 if (m->options)
983 ptr += sprintf(ptr, "%s,", m->options);
984
985 for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
986 if ((mount_flags[i].flag > 0) &&
987 (mount_flags[i].flag < INT_MAX) &&
988 (m->flags & (uint32_t)mount_flags[i].flag))
989 ptr += sprintf(ptr, "%s,", mount_flags[i].name);
990
991 mount_opts[mount_opts_len - 1] = 0;
992 }
993
994 /* ... and now finally invoke the external mount program */
995 err = exec_mount(source, target, fstype, mount_opts);
996 }
997
998 return err;
999 }
1000
1001 static int blockd_notify(char *device, struct mount *m, struct probe_info *pr)
1002 {
1003 struct ubus_context *ctx = ubus_connect(NULL);
1004 uint32_t id;
1005 int err;
1006
1007 if (!ctx)
1008 return -ENXIO;
1009
1010 if (!ubus_lookup_id(ctx, "block", &id)) {
1011 struct blob_buf buf = { 0 };
1012 char *d = strrchr(device, '/');
1013
1014 if (d)
1015 d++;
1016 else
1017 d = device;
1018
1019 blob_buf_init(&buf, 0);
1020
1021 if (m) {
1022
1023 blobmsg_add_string(&buf, "device", d);
1024 if (m->uuid)
1025 blobmsg_add_string(&buf, "uuid", m->uuid);
1026 if (m->label)
1027 blobmsg_add_string(&buf, "label", m->label);
1028 if (m->target)
1029 blobmsg_add_string(&buf, "target", m->target);
1030 if (m->options)
1031 blobmsg_add_string(&buf, "options", m->options);
1032 if (m->autofs)
1033 blobmsg_add_u32(&buf, "autofs", m->autofs);
1034 if (pr->type)
1035 blobmsg_add_string(&buf, "type", pr->type);
1036 if (pr->version)
1037 blobmsg_add_string(&buf, "version", pr->version);
1038 } else if (pr) {
1039 blobmsg_add_string(&buf, "device", d);
1040 if (pr->uuid)
1041 blobmsg_add_string(&buf, "uuid", pr->uuid);
1042 if (pr->label)
1043 blobmsg_add_string(&buf, "label", pr->label);
1044 if (pr->type)
1045 blobmsg_add_string(&buf, "type", pr->type);
1046 if (pr->version)
1047 blobmsg_add_string(&buf, "version", pr->version);
1048 blobmsg_add_u32(&buf, "anon", 1);
1049 } else {
1050 blobmsg_add_string(&buf, "device", d);
1051 blobmsg_add_u32(&buf, "remove", 1);
1052 }
1053
1054 err = ubus_invoke(ctx, id, "hotplug", buf.head, NULL, NULL, 3000);
1055 } else {
1056 err = -ENOENT;
1057 }
1058
1059 ubus_free(ctx);
1060
1061 return err;
1062 }
1063
1064 static int mount_device(struct device *dev, int type)
1065 {
1066 struct mount *m;
1067 struct probe_info *pr;
1068 char _target[32];
1069 char *target;
1070 char *device;
1071 char *mp;
1072 int err;
1073
1074 if (!dev)
1075 return -1;
1076
1077 pr = dev->pr;
1078 device = basename(pr->dev);
1079
1080 if (!strcmp(pr->type, "swap")) {
1081 if ((type == TYPE_HOTPLUG) && !auto_swap)
1082 return -1;
1083 m = find_swap(pr->uuid, pr->label, device);
1084 if (m || anon_swap)
1085 swapon(pr->dev, (m) ? (m->prio) : (0));
1086
1087 return 0;
1088 }
1089
1090 m = dev->m;
1091 if (m && m->extroot)
1092 return -1;
1093
1094 mp = find_mount_point(pr->dev);
1095 if (mp && (type != TYPE_HOTPLUG)) {
1096 ULOG_ERR("%s is already mounted on %s\n", pr->dev, mp);
1097 free(mp);
1098 return -1;
1099 }
1100
1101 if (type == TYPE_HOTPLUG)
1102 blockd_notify(device, m, pr);
1103
1104 /* Check if device should be mounted & set the target directory */
1105 if (m) {
1106 switch (type) {
1107 case TYPE_HOTPLUG:
1108 if (m->autofs)
1109 return 0;
1110 if (!auto_mount)
1111 return -1;
1112 break;
1113 case TYPE_AUTOFS:
1114 if (!m->autofs)
1115 return -1;
1116 break;
1117 case TYPE_DEV:
1118 if (m->autofs)
1119 return -1;
1120 break;
1121 }
1122
1123 if (m->autofs) {
1124 snprintf(_target, sizeof(_target), "/tmp/run/blockd/%s", device);
1125 target = _target;
1126 } else if (m->target) {
1127 target = m->target;
1128 } else {
1129 snprintf(_target, sizeof(_target), "/mnt/%s", device);
1130 target = _target;
1131 }
1132 } else if (anon_mount) {
1133 snprintf(_target, sizeof(_target), "/mnt/%s", device);
1134 target = _target;
1135 } else {
1136 /* No reason to mount this device */
1137 return 0;
1138 }
1139
1140 /* Mount the device */
1141
1142 if (check_fs)
1143 check_filesystem(pr);
1144
1145 mkdir_p(target);
1146
1147 err = handle_mount(pr->dev, target, pr->type, m);
1148 if (err) {
1149 ULOG_ERR("mounting %s (%s) as %s failed (%d) - %m\n",
1150 pr->dev, pr->type, target, errno);
1151 return err;
1152 }
1153
1154 handle_swapfiles(true);
1155
1156 if (type != TYPE_AUTOFS)
1157 hotplug_call_mount("add", device);
1158
1159 return 0;
1160 }
1161
1162 static int umount_device(char *path, int type, bool all)
1163 {
1164 char *mp;
1165 int err;
1166
1167 mp = find_mount_point(path);
1168 if (!mp)
1169 return -1;
1170 if (!strcmp(mp, "/") && !all)
1171 return 0;
1172
1173 if (type != TYPE_AUTOFS)
1174 hotplug_call_mount("remove", basename(path));
1175
1176 err = umount2(mp, MNT_DETACH);
1177 if (err) {
1178 ULOG_ERR("unmounting %s (%s) failed (%d) - %m\n", path, mp,
1179 errno);
1180 } else {
1181 ULOG_INFO("unmounted %s (%s)\n", path, mp);
1182 rmdir(mp);
1183 }
1184
1185 free(mp);
1186 return err;
1187 }
1188
1189 static int mount_action(char *action, char *device, int type)
1190 {
1191 struct device *the_dev, *dev;
1192 char path[32];
1193
1194 if (!action || !device)
1195 return -1;
1196
1197 if (config_load(NULL))
1198 return -1;
1199 cache_load(0);
1200
1201 the_dev = find_block_device(NULL, NULL, device);
1202
1203 if (!strcmp(action, "remove")) {
1204 if (type == TYPE_HOTPLUG)
1205 blockd_notify(device, NULL, NULL);
1206
1207 if (!the_dev || !the_dev->m || the_dev->m->type != TYPE_MOUNT) {
1208 snprintf(path, sizeof(path), "/dev/%s", device);
1209 umount_device(path, type, true);
1210 } else
1211 vlist_for_element_to_last_reverse(&devices, the_dev, dev, node)
1212 if (dev->m && dev->m->type == TYPE_MOUNT)
1213 umount_device(dev->pr->dev, type, true);
1214 return 0;
1215 } else if (!strcmp(action, "add")) {
1216 if (!the_dev)
1217 return -1;
1218 if (the_dev->m && the_dev->m->type == TYPE_MOUNT) {
1219 vlist_for_first_to_element(&devices, the_dev, dev, node) {
1220 if (dev->m && dev->m->type == TYPE_MOUNT) {
1221 int err = mount_device(dev, type);
1222 if (err)
1223 return err;
1224 }
1225 }
1226 return 0;
1227 } else
1228 return mount_device(the_dev, type);
1229 }
1230 ULOG_ERR("Unkown action %s\n", action);
1231 return -1;
1232 }
1233
1234 static int main_hotplug(int argc, char **argv)
1235 {
1236 return mount_action(getenv("ACTION"), getenv("DEVNAME"), TYPE_HOTPLUG);
1237 }
1238
1239 static int main_autofs(int argc, char **argv)
1240 {
1241 int err = 0;
1242
1243 if (argc < 3)
1244 return -1;
1245
1246 if (!strcmp(argv[2], "start")) {
1247 struct device *dev;
1248 struct probe_info *pr;
1249
1250 if (config_load(NULL))
1251 return -1;
1252
1253 cache_load(0);
1254 vlist_for_each_element(&devices, dev, node) {
1255 struct mount *m;
1256
1257 pr = dev->pr;
1258 if (!strcmp(pr->type, "swap"))
1259 continue;
1260
1261 m = dev->m;
1262 if (m && m->extroot)
1263 continue;
1264
1265 blockd_notify(pr->dev, m, pr);
1266 }
1267 } else if (!strcmp(argv[2], "available")) {
1268 err = hotplug_call_mount("add", argv[3]);
1269 } else if (!strcmp(argv[2], "unavailable")) {
1270 err = hotplug_call_mount("remove", argv[3]);
1271 } else {
1272 if (argc < 4)
1273 return -EINVAL;
1274
1275 err = mount_action(argv[2], argv[3], TYPE_AUTOFS);
1276 }
1277
1278 if (err) {
1279 ULOG_ERR("autofs: \"%s\" action has failed: %d\n", argv[2], err);
1280 }
1281
1282 return err;
1283 }
1284
1285 static int find_block_mtd(char *name, char *part, int plen)
1286 {
1287 FILE *fp = fopen("/proc/mtd", "r");
1288 static char line[256];
1289 char *index = NULL;
1290
1291 if(!fp)
1292 return -1;
1293
1294 while (!index && fgets(line, sizeof(line), fp)) {
1295 if (strstr(line, name)) {
1296 char *eol = strstr(line, ":");
1297
1298 if (!eol)
1299 continue;
1300
1301 *eol = '\0';
1302 index = &line[3];
1303 }
1304 }
1305
1306 fclose(fp);
1307
1308 if (!index)
1309 return -1;
1310
1311 snprintf(part, plen, "/dev/mtdblock%s", index);
1312
1313 return 0;
1314 }
1315
1316 #ifdef UBIFS_EXTROOT
1317 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
1318 {
1319 int dev = 0;
1320
1321 while (ubi_dev_present(libubi, dev))
1322 {
1323 struct ubi_dev_info dev_info;
1324 struct ubi_vol_info vol_info;
1325
1326 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
1327 continue;
1328 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
1329 continue;
1330
1331 *dev_num = dev_info.dev_num;
1332 *vol_id = vol_info.vol_id;
1333
1334 return 0;
1335 }
1336
1337 return -1;
1338 }
1339
1340 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
1341 {
1342 int dev_num;
1343 int vol_id;
1344 int err = -1;
1345
1346 err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1347 if (!err)
1348 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
1349
1350 return err;
1351 }
1352
1353 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
1354 {
1355 int dev_num;
1356 int vol_id;
1357 int err = -1;
1358
1359 err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1360 if (!err)
1361 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
1362
1363 return err;
1364 }
1365
1366 #else
1367
1368 static int find_root_dev(char *buf, int len)
1369 {
1370 DIR *d;
1371 dev_t root;
1372 struct stat s;
1373 struct dirent *e;
1374
1375 if (stat("/", &s))
1376 return -1;
1377
1378 if (!(d = opendir("/dev")))
1379 return -1;
1380
1381 root = s.st_dev;
1382
1383 while ((e = readdir(d)) != NULL) {
1384 snprintf(buf, len, "/dev/%s", e->d_name);
1385
1386 if (stat(buf, &s) || s.st_rdev != root)
1387 continue;
1388
1389 closedir(d);
1390 return 0;
1391 }
1392
1393 closedir(d);
1394 return -1;
1395 }
1396
1397 #endif
1398
1399 static int test_fs_support(const char *name)
1400 {
1401 char line[128], *p;
1402 int rv = -1;
1403 FILE *f;
1404
1405 if ((f = fopen("/proc/filesystems", "r")) != NULL) {
1406 while (fgets(line, sizeof(line), f)) {
1407 p = strtok(line, "\t\n");
1408
1409 if (p && !strcmp(p, "nodev"))
1410 p = strtok(NULL, "\t\n");
1411
1412 if (p && !strcmp(p, name)) {
1413 rv = 0;
1414 break;
1415 }
1416 }
1417 fclose(f);
1418 }
1419
1420 return rv;
1421 }
1422
1423 static int check_extroot(char *path)
1424 {
1425 struct device *dev;
1426 struct probe_info *pr;
1427 char devpath[32];
1428
1429 #ifdef UBIFS_EXTROOT
1430 if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
1431 int err = -1;
1432 libubi_t libubi;
1433
1434 libubi = libubi_open();
1435 err = find_block_ubi_RO(libubi, "rootfs", devpath, sizeof(devpath));
1436 libubi_close(libubi);
1437 if (err)
1438 return -1;
1439 }
1440 #else
1441 if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
1442 if (find_root_dev(devpath, sizeof(devpath))) {
1443 ULOG_ERR("extroot: unable to determine root device\n");
1444 return -1;
1445 }
1446 }
1447 #endif
1448
1449 vlist_for_each_element(&devices, dev, node) {
1450 pr = dev->pr;
1451 if (!strcmp(pr->dev, devpath)) {
1452 struct stat s;
1453 FILE *fp = NULL;
1454 char tag[64];
1455 char uuid[64] = { 0 };
1456
1457 snprintf(tag, sizeof(tag), "%s/etc", path);
1458 if (stat(tag, &s))
1459 mkdir_p(tag);
1460
1461 snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
1462 if (stat(tag, &s)) {
1463 fp = fopen(tag, "w+");
1464 if (!fp) {
1465 ULOG_ERR("extroot: failed to write UUID to %s: %d (%m)\n",
1466 tag, errno);
1467 /* return 0 to continue boot regardless of error */
1468 return 0;
1469 }
1470 fputs(pr->uuid, fp);
1471 fclose(fp);
1472 return 0;
1473 }
1474
1475 fp = fopen(tag, "r");
1476 if (!fp) {
1477 ULOG_ERR("extroot: failed to read UUID from %s: %d (%m)\n",
1478 tag, errno);
1479 return -1;
1480 }
1481
1482 if (!fgets(uuid, sizeof(uuid), fp))
1483 ULOG_ERR("extroot: failed to read UUID from %s: %d (%m)\n",
1484 tag, errno);
1485 fclose(fp);
1486
1487 if (*uuid && !strcasecmp(uuid, pr->uuid))
1488 return 0;
1489
1490 ULOG_ERR("extroot: UUID mismatch (root: %s, %s: %s)\n",
1491 pr->uuid, basename(path), uuid);
1492 return -1;
1493 }
1494 }
1495
1496 ULOG_ERR("extroot: unable to lookup root device %s\n", devpath);
1497 return -1;
1498 }
1499
1500 /*
1501 * Read info about extroot from UCI (using prefix) and mount it.
1502 */
1503 static int mount_extroot(char *cfg)
1504 {
1505 char overlay[] = "/tmp/extroot/overlay";
1506 char mnt[] = "/tmp/extroot/mnt";
1507 char *path = mnt;
1508 struct device *dev;
1509 struct probe_info *pr;
1510 struct mount *m;
1511 int err = -1;
1512
1513 /* Load @cfg/etc/config/fstab */
1514 if (config_load(cfg))
1515 return -2;
1516
1517 /* See if there is extroot-specific mount config */
1518 m = find_block(NULL, NULL, NULL, "/");
1519 if (!m)
1520 m = find_block(NULL, NULL, NULL, "/overlay");
1521
1522 if (!m || !m->extroot)
1523 {
1524 ULOG_INFO("extroot: not configured\n");
1525 return -1;
1526 }
1527
1528 /* Find block device pointed by the mount config */
1529 dev = find_block_device(m->uuid, m->label, m->device);
1530
1531 if (!dev && delay_root){
1532 ULOG_INFO("extroot: device not present, retrying in %u seconds\n", delay_root);
1533 sleep(delay_root);
1534 make_devs();
1535 cache_load(0);
1536 dev = find_block_device(m->uuid, m->label, m->device);
1537 }
1538 if (dev) {
1539 pr = dev->pr;
1540 if (strncmp(pr->type, "ext", 3) &&
1541 strncmp(pr->type, "f2fs", 4) &&
1542 strncmp(pr->type, "btrfs", 5) &&
1543 strncmp(pr->type, "ntfs", 4) &&
1544 strncmp(pr->type, "ubifs", 5)) {
1545 ULOG_ERR("extroot: unsupported filesystem %s, try ext4, f2fs, btrfs, ntfs or ubifs\n", pr->type);
1546 return -1;
1547 }
1548
1549 if (test_fs_support(pr->type)) {
1550 ULOG_ERR("extroot: filesystem %s not supported by kernel\n", pr->type);
1551 return -1;
1552 }
1553
1554 if (m->overlay)
1555 path = overlay;
1556 mkdir_p(path);
1557
1558 if (check_fs)
1559 check_filesystem(pr);
1560
1561 err = mount(pr->dev, path, pr->type, m->flags,
1562 (m->options) ? (m->options) : (""));
1563
1564 if (err) {
1565 ULOG_ERR("extroot: mounting %s (%s) on %s failed: %d (%m)\n",
1566 pr->dev, pr->type, path, errno);
1567 } else if (m->overlay) {
1568 err = check_extroot(path);
1569 if (err)
1570 umount(path);
1571 }
1572 } else {
1573 ULOG_ERR("extroot: cannot find device %s%s\n",
1574 (m->uuid ? "with UUID " : (m->label ? "with label " : "")),
1575 (m->uuid ? m->uuid : (m->label ? m->label : m->device)));
1576 }
1577
1578 return err;
1579 }
1580
1581 static int main_extroot(int argc, char **argv)
1582 {
1583 char blkdev_path[32] = { 0 };
1584 int err = -1;
1585 #ifdef UBIFS_EXTROOT
1586 libubi_t libubi;
1587 #endif
1588
1589 if (!getenv("PREINIT"))
1590 return -1;
1591
1592 if (argc != 2) {
1593 ULOG_ERR("Usage: block extroot\n");
1594 return -1;
1595 }
1596
1597 make_devs();
1598 cache_load(1);
1599
1600 /* enable LOG_INFO messages */
1601 ulog_threshold(LOG_INFO);
1602
1603 /*
1604 * Look for "rootfs_data". We will want to mount it and check for
1605 * extroot configuration.
1606 */
1607
1608 /* Start with looking for MTD partition */
1609 find_block_mtd("\"rootfs_data\"", blkdev_path, sizeof(blkdev_path));
1610 if (blkdev_path[0]) {
1611 struct device *dev = find_block_device(NULL, NULL, blkdev_path);
1612 if (dev && !strcmp(dev->pr->type, "jffs2")) {
1613 char cfg[] = "/tmp/jffs_cfg";
1614
1615 /*
1616 * Mount MTD part and try extroot (using
1617 * /etc/config/fstab from that partition)
1618 */
1619 mkdir_p(cfg);
1620 if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1621 err = mount_extroot(cfg);
1622 umount2(cfg, MNT_DETACH);
1623 }
1624 if (err < 0)
1625 rmdir("/tmp/overlay");
1626 rmdir(cfg);
1627 return err;
1628 }
1629 }
1630
1631 #ifdef UBIFS_EXTROOT
1632 /* ... but it also could be an UBI volume */
1633 memset(blkdev_path, 0, sizeof(blkdev_path));
1634 libubi = libubi_open();
1635 find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1636 libubi_close(libubi);
1637 if (blkdev_path[0]) {
1638 char cfg[] = "/tmp/ubifs_cfg";
1639
1640 /* Mount volume and try extroot (using fstab from that vol) */
1641 mkdir_p(cfg);
1642 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1643 err = mount_extroot(cfg);
1644 umount2(cfg, MNT_DETACH);
1645 }
1646 if (err < 0)
1647 rmdir("/tmp/overlay");
1648 rmdir(cfg);
1649 return err;
1650 }
1651 #endif
1652
1653 return mount_extroot(NULL);
1654 }
1655
1656 static int main_mount(int argc, char **argv)
1657 {
1658 struct device *dev;
1659
1660 if (config_load(NULL))
1661 return -1;
1662
1663 cache_load(1);
1664 vlist_for_each_element(&devices, dev, node)
1665 mount_device(dev, TYPE_DEV);
1666
1667 handle_swapfiles(true);
1668
1669 return 0;
1670 }
1671
1672 static int main_umount(int argc, char **argv)
1673 {
1674 struct device *dev;
1675 struct probe_info *pr;
1676 bool all = false;
1677
1678 if (config_load(NULL))
1679 return -1;
1680
1681 handle_swapfiles(false);
1682
1683 cache_load(0);
1684
1685 if (argc == 3)
1686 all = !strcmp(argv[2], "-a");
1687
1688 vlist_for_each_element_reverse(&devices, dev, node) {
1689 struct mount *m;
1690
1691 pr = dev->pr;
1692 if (!strcmp(pr->type, "swap"))
1693 continue;
1694
1695 m = dev->m;
1696 if (m && m->extroot)
1697 continue;
1698
1699 umount_device(pr->dev, TYPE_DEV, all);
1700 }
1701
1702 return 0;
1703 }
1704
1705 static int main_detect(int argc, char **argv)
1706 {
1707 struct device *dev;
1708
1709 cache_load(0);
1710 printf("config 'global'\n");
1711 printf("\toption\tanon_swap\t'0'\n");
1712 printf("\toption\tanon_mount\t'0'\n");
1713 printf("\toption\tauto_swap\t'1'\n");
1714 printf("\toption\tauto_mount\t'1'\n");
1715 printf("\toption\tdelay_root\t'5'\n");
1716 printf("\toption\tcheck_fs\t'0'\n\n");
1717 vlist_for_each_element(&devices, dev, node)
1718 print_block_uci(dev->pr);
1719
1720 return 0;
1721 }
1722
1723 static int main_info(int argc, char **argv)
1724 {
1725 int i;
1726 struct device *dev;
1727
1728 cache_load(1);
1729 if (argc == 2) {
1730 vlist_for_each_element(&devices, dev, node)
1731 print_block_info(dev->pr);
1732
1733 return 0;
1734 };
1735
1736 for (i = 2; i < argc; i++) {
1737 struct stat s;
1738
1739 if (stat(argv[i], &s)) {
1740 ULOG_ERR("failed to stat %s\n", argv[i]);
1741 continue;
1742 }
1743 if (!S_ISBLK(s.st_mode) && !(S_ISCHR(s.st_mode) && major(s.st_rdev) == 250)) {
1744 ULOG_ERR("%s is not a block device\n", argv[i]);
1745 continue;
1746 }
1747 dev = find_block_device(NULL, NULL, argv[i]);
1748 if (dev)
1749 print_block_info(dev->pr);
1750 }
1751
1752 return 0;
1753 }
1754
1755 static int swapon_usage(void)
1756 {
1757 fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1758 "\tStart swapping on [DEVICE]\n"
1759 " -a\tStart swapping on all swap devices\n"
1760 " -p pri\tSet priority of swap device\n"
1761 " -s\tShow summary\n");
1762 return -1;
1763 }
1764
1765 static int main_swapon(int argc, char **argv)
1766 {
1767 int ch;
1768 FILE *fp;
1769 char *lineptr;
1770 size_t s;
1771 struct device *dev;
1772 struct probe_info *pr;
1773 int flags = 0;
1774 int pri;
1775 struct stat st;
1776 int err;
1777
1778 while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1779 switch(ch) {
1780 case 's':
1781 fp = fopen("/proc/swaps", "r");
1782 lineptr = NULL;
1783
1784 if (!fp) {
1785 ULOG_ERR("failed to open /proc/swaps\n");
1786 return -1;
1787 }
1788 while (getline(&lineptr, &s, fp) > 0)
1789 printf("%s", lineptr);
1790 if (lineptr)
1791 free(lineptr);
1792 fclose(fp);
1793 return 0;
1794 case 'a':
1795 cache_load(0);
1796 vlist_for_each_element(&devices, dev, node) {
1797 pr = dev->pr;
1798 if (strcmp(pr->type, "swap"))
1799 continue;
1800 if (swapon(pr->dev, 0))
1801 ULOG_ERR("failed to swapon %s\n", pr->dev);
1802 }
1803 return 0;
1804 case 'p':
1805 pri = atoi(optarg);
1806 if (pri >= 0)
1807 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1808 break;
1809 default:
1810 return swapon_usage();
1811 }
1812 }
1813
1814 if (optind != (argc - 1))
1815 return swapon_usage();
1816
1817 if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1818 ULOG_ERR("%s is not a block device or file\n", argv[optind]);
1819 return -1;
1820 }
1821 err = swapon(argv[optind], flags);
1822 if (err) {
1823 ULOG_ERR("failed to swapon %s (%d)\n", argv[optind], err);
1824 return err;
1825 }
1826
1827 return 0;
1828 }
1829
1830 static int main_swapoff(int argc, char **argv)
1831 {
1832 if (argc != 2) {
1833 ULOG_ERR("Usage: swapoff [-a] [DEVICE]\n\n"
1834 "\tStop swapping on DEVICE\n"
1835 " -a\tStop swapping on all swap devices\n");
1836 return -1;
1837 }
1838
1839 if (!strcmp(argv[1], "-a")) {
1840 FILE *fp = fopen("/proc/swaps", "r");
1841 char line[256];
1842
1843 if (!fp) {
1844 ULOG_ERR("failed to open /proc/swaps\n");
1845 return -1;
1846 }
1847 if (fgets(line, sizeof(line), fp))
1848 while (fgets(line, sizeof(line), fp)) {
1849 char *end = strchr(line, ' ');
1850 int err;
1851
1852 if (!end)
1853 continue;
1854 *end = '\0';
1855 err = swapoff(line);
1856 if (err)
1857 ULOG_ERR("failed to swapoff %s (%d)\n", line, err);
1858 }
1859 fclose(fp);
1860 } else {
1861 struct stat s;
1862 int err;
1863
1864 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1865 ULOG_ERR("%s is not a block device or file\n", argv[1]);
1866 return -1;
1867 }
1868 err = swapoff(argv[1]);
1869 if (err) {
1870 ULOG_ERR("failed to swapoff %s (%d)\n", argv[1], err);
1871 return err;
1872 }
1873 }
1874
1875 return 0;
1876 }
1877
1878 int main(int argc, char **argv)
1879 {
1880 char *base = basename(*argv);
1881
1882 umask(0);
1883
1884 ulog_open(-1, -1, "block");
1885 ulog_threshold(LOG_NOTICE);
1886
1887 if (!strcmp(base, "swapon"))
1888 return main_swapon(argc, argv);
1889
1890 if (!strcmp(base, "swapoff"))
1891 return main_swapoff(argc, argv);
1892
1893 if ((argc > 1) && !strcmp(base, "block")) {
1894 if (!strcmp(argv[1], "info"))
1895 return main_info(argc, argv);
1896
1897 if (!strcmp(argv[1], "detect"))
1898 return main_detect(argc, argv);
1899
1900 if (!strcmp(argv[1], "hotplug"))
1901 return main_hotplug(argc, argv);
1902
1903 if (!strcmp(argv[1], "autofs"))
1904 return main_autofs(argc, argv);
1905
1906 if (!strcmp(argv[1], "extroot"))
1907 return main_extroot(argc, argv);
1908
1909 if (!strcmp(argv[1], "mount"))
1910 return main_mount(argc, argv);
1911
1912 if (!strcmp(argv[1], "umount"))
1913 return main_umount(argc, argv);
1914
1915 if (!strcmp(argv[1], "remount")) {
1916 int ret = main_umount(argc, argv);
1917
1918 if (!ret)
1919 ret = main_mount(argc, argv);
1920 return ret;
1921 }
1922 }
1923
1924 ULOG_ERR("Usage: block <info|mount|umount|detect>\n");
1925
1926 return -1;
1927 }