• source navigation  • diff markup  • identifier search  • freetext search  • 

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

This page was automatically generated by LXR 0.3.1.  •  OpenWrt