2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
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
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.
30 #include <sys/types.h>
32 #include <sys/mount.h>
34 #include <sys/sysmacros.h>
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>
50 #include "libubi/libubi.h"
59 struct vlist_node node;
75 static struct vlist_tree mounts;
76 static struct blob_buf b;
77 static LIST_HEAD(devices);
78 static int anon_mount, anon_swap, auto_mount, auto_swap, check_fs;
79 static unsigned int delay_root;
91 static const struct blobmsg_policy config_policy[__CFG_MAX] = {
92 [CFG_ANON_SWAP] = { .name = "anon_swap", .type = BLOBMSG_TYPE_INT32 },
93 [CFG_ANON_MOUNT] = { .name = "anon_mount", .type = BLOBMSG_TYPE_INT32 },
94 [CFG_AUTO_SWAP] = { .name = "auto_swap", .type = BLOBMSG_TYPE_INT32 },
95 [CFG_AUTO_MOUNT] = { .name = "auto_mount", .type = BLOBMSG_TYPE_INT32 },
96 [CFG_DELAY_ROOT] = { .name = "delay_root", .type = BLOBMSG_TYPE_INT32 },
97 [CFG_CHECK_FS] = { .name = "check_fs", .type = BLOBMSG_TYPE_INT32 },
110 static const struct uci_blob_param_list config_attr_list = {
111 .n_params = __CFG_MAX,
112 .params = config_policy,
115 static const struct blobmsg_policy mount_policy[__MOUNT_MAX] = {
116 [MOUNT_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
117 [MOUNT_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
118 [MOUNT_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
119 [MOUNT_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
120 [MOUNT_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_STRING },
121 [MOUNT_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
124 static const struct uci_blob_param_list mount_attr_list = {
125 .n_params = __MOUNT_MAX,
126 .params = mount_policy,
138 static const struct blobmsg_policy swap_policy[__SWAP_MAX] = {
139 [SWAP_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
140 [SWAP_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
141 [SWAP_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
142 [SWAP_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
143 [SWAP_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
146 static const struct uci_blob_param_list swap_attr_list = {
147 .n_params = __SWAP_MAX,
148 .params = swap_policy,
156 static const struct mount_flag mount_flags[] = {
157 { "sync", MS_SYNCHRONOUS },
158 { "async", ~MS_SYNCHRONOUS },
159 { "dirsync", MS_DIRSYNC },
160 { "mand", MS_MANDLOCK },
161 { "nomand", ~MS_MANDLOCK },
162 { "atime", ~MS_NOATIME },
163 { "noatime", MS_NOATIME },
164 { "dev", ~MS_NODEV },
165 { "nodev", MS_NODEV },
166 { "diratime", ~MS_NODIRATIME },
167 { "nodiratime", MS_NODIRATIME },
168 { "exec", ~MS_NOEXEC },
169 { "noexec", MS_NOEXEC },
170 { "suid", ~MS_NOSUID },
171 { "nosuid", MS_NOSUID },
172 { "rw", ~MS_RDONLY },
174 { "relatime", MS_RELATIME },
175 { "norelatime", ~MS_RELATIME },
176 { "strictatime", MS_STRICTATIME },
177 { "acl", MS_POSIXACL },
178 { "noacl", ~MS_POSIXACL },
179 { "nouser_xattr", MS_NOUSER },
180 { "user_xattr", ~MS_NOUSER },
183 static char *blobmsg_get_strdup(struct blob_attr *attr)
188 return strdup(blobmsg_get_string(attr));
191 static char *blobmsg_get_basename(struct blob_attr *attr)
196 return strdup(basename(blobmsg_get_string(attr)));
199 static void parse_mount_options(struct mount *m, char *optstr)
203 char *p, *opts, *last;
208 if (!optstr || !*optstr)
211 m->options = opts = calloc(1, strlen(optstr) + 1);
224 for (i = 0, is_flag = false; i < ARRAY_SIZE(mount_flags); i++) {
225 if (!strcmp(last, mount_flags[i].name)) {
226 if (mount_flags[i].flag < 0)
227 m->flags &= (uint32_t)mount_flags[i].flag;
229 m->flags |= (uint32_t)mount_flags[i].flag;
236 opts += sprintf(opts, "%s%s", (opts > m->options) ? "," : "", last);
245 static int mount_add(struct uci_section *s)
247 struct blob_attr *tb[__MOUNT_MAX] = { 0 };
250 blob_buf_init(&b, 0);
251 uci_to_blob(&b, s, &mount_attr_list);
252 blobmsg_parse(mount_policy, __MOUNT_MAX, tb, blob_data(b.head), blob_len(b.head));
254 if (!tb[MOUNT_LABEL] && !tb[MOUNT_UUID] && !tb[MOUNT_DEVICE])
257 if (tb[MOUNT_ENABLE] && !blobmsg_get_u32(tb[MOUNT_ENABLE]))
260 m = malloc(sizeof(struct mount));
261 m->type = TYPE_MOUNT;
262 m->uuid = blobmsg_get_strdup(tb[MOUNT_UUID]);
263 m->label = blobmsg_get_strdup(tb[MOUNT_LABEL]);
264 m->target = blobmsg_get_strdup(tb[MOUNT_TARGET]);
265 m->device = blobmsg_get_basename(tb[MOUNT_DEVICE]);
267 parse_mount_options(m, blobmsg_get_strdup(tb[MOUNT_OPTIONS]));
269 m->overlay = m->extroot = 0;
270 if (m->target && !strcmp(m->target, "/"))
272 if (m->target && !strcmp(m->target, "/overlay"))
273 m->extroot = m->overlay = 1;
275 if (m->target && *m->target != '/') {
276 ULOG_WARN("ignoring mount section %s due to invalid target '%s'\n",
277 s->e.name, m->target);
283 vlist_add(&mounts, &m->node, m->uuid);
285 vlist_add(&mounts, &m->node, m->label);
287 vlist_add(&mounts, &m->node, m->device);
292 static int swap_add(struct uci_section *s)
294 struct blob_attr *tb[__SWAP_MAX] = { 0 };
297 blob_buf_init(&b, 0);
298 uci_to_blob(&b, s, &swap_attr_list);
299 blobmsg_parse(swap_policy, __SWAP_MAX, tb, blob_data(b.head), blob_len(b.head));
301 if (!tb[SWAP_UUID] && !tb[SWAP_LABEL] && !tb[SWAP_DEVICE])
304 m = malloc(sizeof(struct mount));
305 memset(m, 0, sizeof(struct mount));
307 m->uuid = blobmsg_get_strdup(tb[SWAP_UUID]);
308 m->label = blobmsg_get_strdup(tb[SWAP_LABEL]);
309 m->device = blobmsg_get_basename(tb[SWAP_DEVICE]);
311 m->prio = blobmsg_get_u32(tb[SWAP_PRIO]);
313 m->prio = ((m->prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
315 if ((!tb[SWAP_ENABLE]) || blobmsg_get_u32(tb[SWAP_ENABLE])) {
316 /* store complete swap path */
318 m->target = blobmsg_get_strdup(tb[SWAP_DEVICE]);
321 vlist_add(&mounts, &m->node, m->uuid);
323 vlist_add(&mounts, &m->node, m->label);
325 vlist_add(&mounts, &m->node, m->device);
331 static int global_add(struct uci_section *s)
333 struct blob_attr *tb[__CFG_MAX] = { 0 };
335 blob_buf_init(&b, 0);
336 uci_to_blob(&b, s, &config_attr_list);
337 blobmsg_parse(config_policy, __CFG_MAX, tb, blob_data(b.head), blob_len(b.head));
339 if ((tb[CFG_ANON_MOUNT]) && blobmsg_get_u32(tb[CFG_ANON_MOUNT]))
341 if ((tb[CFG_ANON_SWAP]) && blobmsg_get_u32(tb[CFG_ANON_SWAP]))
344 if ((tb[CFG_AUTO_MOUNT]) && blobmsg_get_u32(tb[CFG_AUTO_MOUNT]))
346 if ((tb[CFG_AUTO_SWAP]) && blobmsg_get_u32(tb[CFG_AUTO_SWAP]))
349 if (tb[CFG_DELAY_ROOT])
350 delay_root = blobmsg_get_u32(tb[CFG_DELAY_ROOT]);
352 if ((tb[CFG_CHECK_FS]) && blobmsg_get_u32(tb[CFG_CHECK_FS]))
358 static struct mount* find_swap(const char *uuid, const char *label, const char *device)
362 vlist_for_each_element(&mounts, m, node) {
363 if (m->type != TYPE_SWAP)
365 if (uuid && m->uuid && !strcasecmp(m->uuid, uuid))
367 if (label && m->label && !strcmp(m->label, label))
369 if (device && m->device && !strcmp(m->device, device))
376 static struct mount* find_block(const char *uuid, const char *label, const char *device,
381 vlist_for_each_element(&mounts, m, node) {
382 if (m->type != TYPE_MOUNT)
384 if (m->uuid && uuid && !strcasecmp(m->uuid, uuid))
386 if (m->label && label && !strcmp(m->label, label))
388 if (m->target && target && !strcmp(m->target, target))
390 if (m->device && device && !strcmp(m->device, device))
397 static void mounts_update(struct vlist_tree *tree, struct vlist_node *node_new,
398 struct vlist_node *node_old)
402 static struct uci_package * config_try_load(struct uci_context *ctx, char *path)
404 char *file = basename(path);
405 char *dir = dirname(path);
407 struct uci_package *pkg;
409 uci_set_confdir(ctx, dir);
410 ULOG_INFO("attempting to load %s/%s\n", dir, file);
412 if (uci_load(ctx, file, &pkg)) {
413 uci_get_errorstr(ctx, &err, file);
414 ULOG_ERR("unable to load configuration (%s)\n", err);
423 static int config_load(char *cfg)
425 struct uci_context *ctx = uci_alloc_context();
426 struct uci_package *pkg = NULL;
427 struct uci_element *e;
430 vlist_init(&mounts, avl_strcmp, mounts_update);
433 snprintf(path, sizeof(path), "%s/upper/etc/config/fstab", cfg);
434 pkg = config_try_load(ctx, path);
437 snprintf(path, sizeof(path), "%s/etc/config/fstab", cfg);
438 pkg = config_try_load(ctx, path);
443 snprintf(path, sizeof(path), "/etc/config/fstab");
444 pkg = config_try_load(ctx, path);
448 ULOG_ERR("no usable configuration\n");
452 vlist_update(&mounts);
453 uci_foreach_element(&pkg->sections, e) {
454 struct uci_section *s = uci_to_section(e);
456 if (!strcmp(s->type, "mount"))
458 if (!strcmp(s->type, "swap"))
460 if (!strcmp(s->type, "global"))
463 vlist_flush(&mounts);
468 static struct probe_info* _probe_path(char *path)
470 struct probe_info *pr;
473 /* skip ubi device if ubiblock device is present */
474 if (path[5] == 'u' && path[6] == 'b' && path[7] == 'i' &&
475 path[8] >= '0' && path[8] <= '9' ) {
476 snprintf(tmppath, sizeof(tmppath), "/dev/ubiblock%s", path + 8);
477 list_for_each_entry(pr, &devices, list)
478 if (!strcasecmp(pr->dev, tmppath))
482 return probe_path(path);
485 static int _cache_load(const char *path)
487 int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
491 if (glob(path, gl_flags, NULL, &gl) < 0)
494 for (j = 0; j < gl.gl_pathc; j++) {
495 struct probe_info *pr = _probe_path(gl.gl_pathv[j]);
497 list_add_tail(&pr->list, &devices);
505 static void cache_load(int mtd)
508 _cache_load("/dev/mtdblock*");
509 _cache_load("/dev/ubiblock*");
510 _cache_load("/dev/ubi[0-9]*");
512 _cache_load("/dev/loop*");
513 _cache_load("/dev/mmcblk*");
514 _cache_load("/dev/sd*");
515 _cache_load("/dev/hd*");
516 _cache_load("/dev/md*");
517 _cache_load("/dev/vd*");
518 _cache_load("/dev/mapper/*");
522 static int print_block_uci(struct probe_info *pr)
524 if (!strcmp(pr->type, "swap")) {
525 printf("config 'swap'\n");
527 printf("config 'mount'\n");
528 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
531 printf("\toption\tuuid\t'%s'\n", pr->uuid);
533 printf("\toption\tdevice\t'%s'\n", pr->dev);
534 printf("\toption\tenabled\t'0'\n\n");
539 static struct probe_info* find_block_info(char *uuid, char *label, char *path)
541 struct probe_info *pr = NULL;
544 list_for_each_entry(pr, &devices, list)
545 if (pr->uuid && !strcasecmp(pr->uuid, uuid))
549 list_for_each_entry(pr, &devices, list)
550 if (pr->label && !strcmp(pr->label, label))
554 list_for_each_entry(pr, &devices, list)
555 if (pr->dev && !strcmp(basename(pr->dev), basename(path)))
561 static char* find_mount_point(char *block)
563 FILE *fp = fopen("/proc/self/mountinfo", "r");
564 static char line[256];
565 int len = strlen(block);
566 char *point = NULL, *pos, *tmp, *cpoint, *devname;
569 unsigned int minor, major;
574 rstat = stat(block, &s);
576 while (fgets(line, sizeof(line), fp)) {
577 pos = strchr(line, ' ');
581 pos = strchr(pos + 1, ' ');
586 pos = strchr(pos, ':');
593 pos = strchr(pos, ' ');
599 pos = strchr(pos + 1, ' ');
604 pos = strchr(pos, ' ');
610 pos = strchr(pos + 1, ' ');
614 pos = strchr(pos + 1, ' ');
618 pos = strchr(pos + 1, ' ');
623 pos = strchr(pos, ' ');
629 if (!strncmp(block, devname, len)) {
630 point = strdup(cpoint);
637 if (!S_ISBLK(s.st_mode))
640 if (major == major(s.st_rdev) &&
641 minor == minor(s.st_rdev)) {
642 point = strdup(cpoint);
652 static int print_block_info(struct probe_info *pr)
656 mp = find_mount_point(pr->dev);
657 printf("%s:", pr->dev);
659 printf(" UUID=\"%s\"", pr->uuid);
662 printf(" LABEL=\"%s\"", pr->label);
665 printf(" VERSION=\"%s\"", pr->version);
668 printf(" MOUNT=\"%s\"", mp);
672 printf(" TYPE=\"%s\"\n", pr->type);
677 static void mkdir_p(char *dir)
679 char *l = strrchr(dir, '/');
689 static void check_filesystem(struct probe_info *pr)
693 const char *e2fsck = "/usr/sbin/e2fsck";
694 const char *f2fsck = "/usr/sbin/fsck.f2fs";
695 const char *dosfsck = "/usr/sbin/dosfsck";
698 /* UBIFS does not need stuff like fsck */
699 if (!strncmp(pr->type, "ubifs", 5))
702 if (!strncmp(pr->type, "vfat", 4)) {
704 } else if (!strncmp(pr->type, "f2fs", 4)) {
706 } else if (!strncmp(pr->type, "ext", 3)) {
709 ULOG_ERR("check_filesystem: %s is not supported\n", pr->type);
713 if (stat(ckfs, &statbuf) < 0) {
714 ULOG_ERR("check_filesystem: %s not found\n", ckfs);
720 if(!strncmp(pr->type, "f2fs", 4)) {
721 execl(ckfs, ckfs, "-f", pr->dev, NULL);
724 execl(ckfs, ckfs, "-p", pr->dev, NULL);
727 } else if (pid > 0) {
730 waitpid(pid, &status, 0);
731 if (WEXITSTATUS(status))
732 ULOG_ERR("check_filesystem: %s returned %d\n", ckfs, WEXITSTATUS(status));
736 static void handle_swapfiles(bool on)
740 struct probe_info *pr;
742 vlist_for_each_element(&mounts, m, node)
744 if (m->type != TYPE_SWAP || !m->target)
747 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
750 pr = _probe_path(m->target);
755 if (!strcmp(pr->type, "swap")) {
757 swapon(pr->dev, m->prio);
766 static void to_devnull(int fd)
768 int devnull = open("/dev/null", fd ? O_WRONLY : O_RDONLY);
773 if (devnull > STDERR_FILENO)
777 static int exec_mount(const char *source, const char *target,
778 const char *fstype, const char *options)
783 int err, status, pfds[2];
784 char errmsg[128], cmd[sizeof("/sbin/mount.XXXXXXXXXXXXXXXX\0")];
786 snprintf(cmd, sizeof(cmd), "/sbin/mount.%s", fstype);
788 if (stat(cmd, &s) < 0 || !S_ISREG(s.st_mode) || !(s.st_mode & S_IXUSR)) {
789 ULOG_ERR("No \"mount.%s\" utility available\n", fstype);
796 fcntl(pfds[0], F_SETFD, fcntl(pfds[0], F_GETFD) | FD_CLOEXEC);
797 fcntl(pfds[1], F_SETFD, fcntl(pfds[1], F_GETFD) | FD_CLOEXEC);
809 to_devnull(STDIN_FILENO);
810 to_devnull(STDOUT_FILENO);
812 dup2(pfds[1], STDERR_FILENO);
816 if (options && *options)
817 execl(cmd, cmd, "-o", options, source, target, NULL);
819 execl(cmd, cmd, source, target, NULL);
826 mount_fd = fdopen(pfds[0], "r");
828 while (fgets(errmsg, sizeof(errmsg), mount_fd))
829 ULOG_ERR("mount.%s: %s", fstype, errmsg);
833 err = waitpid(pid, &status, 0);
837 ULOG_ERR("mount.%s: failed with status %d\n", fstype, status);
852 static int handle_mount(const char *source, const char *target,
853 const char *fstype, struct mount *m)
856 size_t mount_opts_len;
857 char *mount_opts = NULL, *ptr;
859 err = mount(source, target, fstype, m ? m->flags : 0,
860 (m && m->options) ? m->options : "");
862 /* Requested file system type is not available in kernel,
863 attempt to call mount helper. */
864 if (err == -1 && errno == ENODEV) {
866 /* Convert mount flags back into string representation,
867 first calculate needed length of string buffer... */
868 mount_opts_len = 1 + (m->options ? strlen(m->options) : 0);
870 for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
871 if ((mount_flags[i].flag > 0) &&
872 (mount_flags[i].flag < INT_MAX) &&
873 (m->flags & (uint32_t)mount_flags[i].flag))
874 mount_opts_len += strlen(mount_flags[i].name) + 1;
876 /* ... then now allocate and fill it ... */
877 ptr = mount_opts = calloc(1, mount_opts_len);
885 ptr += sprintf(ptr, "%s,", m->options);
887 for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
888 if ((mount_flags[i].flag > 0) &&
889 (mount_flags[i].flag < INT_MAX) &&
890 (m->flags & (uint32_t)mount_flags[i].flag))
891 ptr += sprintf(ptr, "%s,", mount_flags[i].name);
893 mount_opts[mount_opts_len - 1] = 0;
896 /* ... and now finally invoke the external mount program */
897 err = exec_mount(source, target, fstype, mount_opts);
903 static int mount_device(struct probe_info *pr, int hotplug)
912 device = basename(pr->dev);
914 if (!strcmp(pr->type, "swap")) {
915 if (hotplug && !auto_swap)
917 m = find_swap(pr->uuid, pr->label, device);
919 swapon(pr->dev, (m) ? (m->prio) : (0));
924 if (hotplug && !auto_mount)
927 mp = find_mount_point(pr->dev);
929 ULOG_ERR("%s is already mounted on %s\n", pr->dev, mp);
934 m = find_block(pr->uuid, pr->label, device, NULL);
939 char *target = m->target;
944 snprintf(_target, sizeof(_target), "/mnt/%s", device);
950 check_filesystem(pr);
952 err = handle_mount(pr->dev, target, pr->type, m);
954 ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
955 pr->dev, pr->type, target, errno, strerror(errno));
957 handle_swapfiles(true);
965 snprintf(target, sizeof(target), "/mnt/%s", device);
969 check_filesystem(pr);
971 err = handle_mount(pr->dev, target, pr->type, NULL);
973 ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
974 pr->dev, pr->type, target, errno, strerror(errno));
976 handle_swapfiles(true);
983 static int umount_device(struct probe_info *pr)
986 char *device = basename(pr->dev);
993 if (!strcmp(pr->type, "swap"))
996 mp = find_mount_point(pr->dev);
1000 m = find_block(pr->uuid, pr->label, device, NULL);
1001 if (m && m->extroot)
1004 err = umount2(mp, MNT_DETACH);
1006 ULOG_ERR("unmounting %s (%s) failed (%d) - %s\n",
1007 pr->dev, mp, errno, strerror(errno));
1009 ULOG_INFO("unmounted %s (%s)\n",
1016 static int main_hotplug(int argc, char **argv)
1019 char *action, *device, *mount_point;
1021 action = getenv("ACTION");
1022 device = getenv("DEVNAME");
1024 if (!action || !device)
1026 snprintf(path, sizeof(path), "/dev/%s", device);
1028 if (!strcmp(action, "remove")) {
1030 mount_point = find_mount_point(path);
1032 err = umount2(mount_point, MNT_DETACH);
1035 ULOG_ERR("umount of %s failed (%d) - %s\n",
1036 mount_point, errno, strerror(errno));
1040 } else if (strcmp(action, "add")) {
1041 ULOG_ERR("Unkown action %s\n", action);
1046 if (config_load(NULL))
1050 return mount_device(find_block_info(NULL, NULL, path), 1);
1053 static int find_block_mtd(char *name, char *part, int plen)
1055 FILE *fp = fopen("/proc/mtd", "r");
1056 static char line[256];
1062 while (!index && fgets(line, sizeof(line), fp)) {
1063 if (strstr(line, name)) {
1064 char *eol = strstr(line, ":");
1079 snprintf(part, plen, "/dev/mtdblock%s", index);
1084 #ifdef UBIFS_EXTROOT
1085 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
1089 while (ubi_dev_present(libubi, dev))
1091 struct ubi_dev_info dev_info;
1092 struct ubi_vol_info vol_info;
1094 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
1096 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
1099 *dev_num = dev_info.dev_num;
1100 *vol_id = vol_info.vol_id;
1108 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
1114 err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1116 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
1121 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
1127 err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1129 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
1136 static int find_root_dev(char *buf, int len)
1146 if (!(d = opendir("/dev")))
1151 while ((e = readdir(d)) != NULL) {
1152 snprintf(buf, len, "/dev/%s", e->d_name);
1154 if (stat(buf, &s) || s.st_rdev != root)
1167 static int test_fs_support(const char *name)
1173 if ((f = fopen("/proc/filesystems", "r")) != NULL) {
1174 while (fgets(line, sizeof(line), f)) {
1175 p = strtok(line, "\t\n");
1177 if (p && !strcmp(p, "nodev"))
1178 p = strtok(NULL, "\t\n");
1180 if (p && !strcmp(p, name)) {
1191 static int check_extroot(char *path)
1193 struct probe_info *pr = NULL;
1196 #ifdef UBIFS_EXTROOT
1197 if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
1201 libubi = libubi_open();
1202 err = find_block_ubi_RO(libubi, "rootfs", devpath, sizeof(devpath));
1203 libubi_close(libubi);
1208 if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
1209 if (find_root_dev(devpath, sizeof(devpath))) {
1210 ULOG_ERR("extroot: unable to determine root device\n");
1216 list_for_each_entry(pr, &devices, list) {
1217 if (!strcmp(pr->dev, devpath)) {
1221 char uuid[64] = { 0 };
1223 snprintf(tag, sizeof(tag), "%s/etc", path);
1227 snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
1228 if (stat(tag, &s)) {
1229 fp = fopen(tag, "w+");
1231 ULOG_ERR("extroot: failed to write UUID to %s: %d (%s)\n",
1232 tag, errno, strerror(errno));
1233 /* return 0 to continue boot regardless of error */
1236 fputs(pr->uuid, fp);
1241 fp = fopen(tag, "r");
1243 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1244 tag, errno, strerror(errno));
1248 if (!fgets(uuid, sizeof(uuid), fp))
1249 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1250 tag, errno, strerror(errno));
1253 if (*uuid && !strcasecmp(uuid, pr->uuid))
1256 ULOG_ERR("extroot: UUID mismatch (root: %s, %s: %s)\n",
1257 pr->uuid, basename(path), uuid);
1262 ULOG_ERR("extroot: unable to lookup root device %s\n", devpath);
1267 * Read info about extroot from UCI (using prefix) and mount it.
1269 static int mount_extroot(char *cfg)
1271 char overlay[] = "/tmp/extroot/overlay";
1272 char mnt[] = "/tmp/extroot/mnt";
1274 struct probe_info *pr;
1278 /* Load @cfg/etc/config/fstab */
1279 if (config_load(cfg))
1282 /* See if there is extroot-specific mount config */
1283 m = find_block(NULL, NULL, NULL, "/");
1285 m = find_block(NULL, NULL, NULL, "/overlay");
1287 if (!m || !m->extroot)
1289 ULOG_INFO("extroot: not configured\n");
1293 /* Find block device pointed by the mount config */
1294 pr = find_block_info(m->uuid, m->label, m->device);
1296 if (!pr && delay_root){
1297 ULOG_INFO("extroot: device not present, retrying in %u seconds\n", delay_root);
1301 pr = find_block_info(m->uuid, m->label, m->device);
1304 if (strncmp(pr->type, "ext", 3) &&
1305 strncmp(pr->type, "f2fs", 4) &&
1306 strncmp(pr->type, "ubifs", 5)) {
1307 ULOG_ERR("extroot: unsupported filesystem %s, try ext4, f2fs or ubifs\n", pr->type);
1311 if (test_fs_support(pr->type)) {
1312 ULOG_ERR("extroot: filesystem %s not supported by kernel\n", pr->type);
1321 check_filesystem(pr);
1323 err = mount(pr->dev, path, pr->type, m->flags,
1324 (m->options) ? (m->options) : (""));
1327 ULOG_ERR("extroot: mounting %s (%s) on %s failed: %d (%s)\n",
1328 pr->dev, pr->type, path, errno, strerror(errno));
1329 } else if (m->overlay) {
1330 err = check_extroot(path);
1335 ULOG_ERR("extroot: cannot find device %s%s\n",
1336 (m->uuid ? "with UUID " : (m->label ? "with label " : "")),
1337 (m->uuid ? m->uuid : (m->label ? m->label : m->device)));
1343 static int main_extroot(int argc, char **argv)
1345 struct probe_info *pr;
1346 char blkdev_path[32] = { 0 };
1348 #ifdef UBIFS_EXTROOT
1352 if (!getenv("PREINIT"))
1356 ULOG_ERR("Usage: block extroot\n");
1363 /* enable LOG_INFO messages */
1364 ulog_threshold(LOG_INFO);
1367 * Look for "rootfs_data". We will want to mount it and check for
1368 * extroot configuration.
1371 /* Start with looking for MTD partition */
1372 find_block_mtd("\"rootfs_data\"", blkdev_path, sizeof(blkdev_path));
1373 if (blkdev_path[0]) {
1374 pr = find_block_info(NULL, NULL, blkdev_path);
1375 if (pr && !strcmp(pr->type, "jffs2")) {
1376 char cfg[] = "/tmp/jffs_cfg";
1379 * Mount MTD part and try extroot (using
1380 * /etc/config/fstab from that partition)
1383 if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1384 err = mount_extroot(cfg);
1385 umount2(cfg, MNT_DETACH);
1388 rmdir("/tmp/overlay");
1394 #ifdef UBIFS_EXTROOT
1395 /* ... but it also could be an UBI volume */
1396 memset(blkdev_path, 0, sizeof(blkdev_path));
1397 libubi = libubi_open();
1398 find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1399 libubi_close(libubi);
1400 if (blkdev_path[0]) {
1401 char cfg[] = "/tmp/ubifs_cfg";
1403 /* Mount volume and try extroot (using fstab from that vol) */
1405 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1406 err = mount_extroot(cfg);
1407 umount2(cfg, MNT_DETACH);
1410 rmdir("/tmp/overlay");
1416 return mount_extroot(NULL);
1419 static int main_mount(int argc, char **argv)
1421 struct probe_info *pr;
1423 if (config_load(NULL))
1427 list_for_each_entry(pr, &devices, list)
1428 mount_device(pr, 0);
1430 handle_swapfiles(true);
1435 static int main_umount(int argc, char **argv)
1437 struct probe_info *pr;
1439 if (config_load(NULL))
1442 handle_swapfiles(false);
1445 list_for_each_entry(pr, &devices, list)
1451 static int main_detect(int argc, char **argv)
1453 struct probe_info *pr;
1456 printf("config 'global'\n");
1457 printf("\toption\tanon_swap\t'0'\n");
1458 printf("\toption\tanon_mount\t'0'\n");
1459 printf("\toption\tauto_swap\t'1'\n");
1460 printf("\toption\tauto_mount\t'1'\n");
1461 printf("\toption\tdelay_root\t'5'\n");
1462 printf("\toption\tcheck_fs\t'0'\n\n");
1463 list_for_each_entry(pr, &devices, list)
1464 print_block_uci(pr);
1469 static int main_info(int argc, char **argv)
1472 struct probe_info *pr;
1476 list_for_each_entry(pr, &devices, list)
1477 print_block_info(pr);
1482 for (i = 2; i < argc; i++) {
1485 if (stat(argv[i], &s)) {
1486 ULOG_ERR("failed to stat %s\n", argv[i]);
1489 if (!S_ISBLK(s.st_mode) && !(S_ISCHR(s.st_mode) && major(s.st_rdev) == 250)) {
1490 ULOG_ERR("%s is not a block device\n", argv[i]);
1493 pr = find_block_info(NULL, NULL, argv[i]);
1495 print_block_info(pr);
1501 static int swapon_usage(void)
1503 fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1504 "\tStart swapping on [DEVICE]\n"
1505 " -a\tStart swapping on all swap devices\n"
1506 " -p pri\tSet priority of swap device\n"
1507 " -s\tShow summary\n");
1511 static int main_swapon(int argc, char **argv)
1517 struct probe_info *pr;
1523 while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1526 fp = fopen("/proc/swaps", "r");
1530 ULOG_ERR("failed to open /proc/swaps\n");
1533 while (getline(&lineptr, &s, fp) > 0)
1534 printf("%s", lineptr);
1541 list_for_each_entry(pr, &devices, list) {
1542 if (strcmp(pr->type, "swap"))
1544 if (swapon(pr->dev, 0))
1545 ULOG_ERR("failed to swapon %s\n", pr->dev);
1551 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1554 return swapon_usage();
1559 if (optind != (argc - 1))
1560 return swapon_usage();
1562 if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1563 ULOG_ERR("%s is not a block device or file\n", argv[optind]);
1566 err = swapon(argv[optind], flags);
1568 ULOG_ERR("failed to swapon %s (%d)\n", argv[optind], err);
1575 static int main_swapoff(int argc, char **argv)
1578 ULOG_ERR("Usage: swapoff [-a] [DEVICE]\n\n"
1579 "\tStop swapping on DEVICE\n"
1580 " -a\tStop swapping on all swap devices\n");
1584 if (!strcmp(argv[1], "-a")) {
1585 FILE *fp = fopen("/proc/swaps", "r");
1589 ULOG_ERR("failed to open /proc/swaps\n");
1592 if (fgets(line, sizeof(line), fp))
1593 while (fgets(line, sizeof(line), fp)) {
1594 char *end = strchr(line, ' ');
1600 err = swapoff(line);
1602 ULOG_ERR("failed to swapoff %s (%d)\n", line, err);
1609 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1610 ULOG_ERR("%s is not a block device or file\n", argv[1]);
1613 err = swapoff(argv[1]);
1615 ULOG_ERR("failed to swapoff %s (%d)\n", argv[1], err);
1623 int main(int argc, char **argv)
1625 char *base = basename(*argv);
1629 ulog_open(-1, -1, "block");
1630 ulog_threshold(LOG_NOTICE);
1632 if (!strcmp(base, "swapon"))
1633 return main_swapon(argc, argv);
1635 if (!strcmp(base, "swapoff"))
1636 return main_swapoff(argc, argv);
1638 if ((argc > 1) && !strcmp(base, "block")) {
1639 if (!strcmp(argv[1], "info"))
1640 return main_info(argc, argv);
1642 if (!strcmp(argv[1], "detect"))
1643 return main_detect(argc, argv);
1645 if (!strcmp(argv[1], "hotplug"))
1646 return main_hotplug(argc, argv);
1648 if (!strcmp(argv[1], "extroot"))
1649 return main_extroot(argc, argv);
1651 if (!strcmp(argv[1], "mount"))
1652 return main_mount(argc, argv);
1654 if (!strcmp(argv[1], "umount"))
1655 return main_umount(argc, argv);
1657 if (!strcmp(argv[1], "remount")) {
1658 int ret = main_umount(argc, argv);
1661 ret = main_mount(argc, argv);
1666 ULOG_ERR("Usage: block <info|mount|umount|detect>\n");