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

This page was automatically generated by LXR 0.3.1.  •  OpenWrt