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