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