531551
From c43588bf03cc05b2eae724751b6652949e5c9caa Mon Sep 17 00:00:00 2001
531551
From: Karel Zak <kzak@redhat.com>
531551
Date: Tue, 21 Mar 2017 13:04:17 +0100
531551
Subject: [PATCH 106/116] zramctl: backport from v2.29
531551
531551
Addresses: https://bugzilla.redhat.com/show_bug.cgi?id=1358755
531551
Signed-off-by: Karel Zak <kzak@redhat.com>
531551
---
531551
 .gitignore              |   1 +
531551
 configure.ac            |   6 +
531551
 include/Makemodule.am   |   1 +
531551
 include/c.h             |   8 +
531551
 include/strutils.h      |   9 +
531551
 include/strv.h          |  55 ++++
531551
 include/sysfs.h         |   3 +
531551
 lib/Makemodule.am       |   3 +-
531551
 lib/strutils.c          | 129 +++++++++
531551
 lib/strv.c              | 403 ++++++++++++++++++++++++++
531551
 lib/sysfs.c             |  45 ++-
531551
 sys-utils/Makemodule.am |   7 +
531551
 sys-utils/zramctl.8     | 123 ++++++++
531551
 sys-utils/zramctl.c     | 736 ++++++++++++++++++++++++++++++++++++++++++++++++
531551
 14 files changed, 1524 insertions(+), 5 deletions(-)
531551
 create mode 100644 include/strv.h
531551
 create mode 100644 lib/strv.c
531551
 create mode 100644 sys-utils/zramctl.8
531551
 create mode 100644 sys-utils/zramctl.c
531551
531551
diff --git a/configure.ac b/configure.ac
531551
index f87a885..db7095a 100644
531551
--- a/configure.ac
531551
+++ b/configure.ac
531551
@@ -826,6 +826,12 @@ UL_REQUIRES_LINUX([losetup])
531551
 AM_CONDITIONAL(BUILD_LOSETUP, test "x$build_losetup" = xyes)
531551
 
531551
 
531551
+UL_BUILD_INIT([zramctl], [check])
531551
+UL_REQUIRES_LINUX([zramctl])
531551
+UL_REQUIRES_BUILD([zramctl], [libsmartcols])
531551
+AM_CONDITIONAL([BUILD_ZRAMCTL], [test "x$build_zramctl" = xyes])
531551
+
531551
+
531551
 AC_ARG_ENABLE([cytune],
531551
   AS_HELP_STRING([--disable-cytune], [do not build cytune]),
531551
   [], enable_cytune=check
531551
diff --git a/include/Makemodule.am b/include/Makemodule.am
531551
index 757f317..1680296 100644
531551
--- a/include/Makemodule.am
531551
+++ b/include/Makemodule.am
531551
@@ -39,6 +39,7 @@ dist_noinst_HEADERS += \
531551
 	include/readutmp.h \
531551
 	include/setproctitle.h \
531551
 	include/strutils.h \
531551
+	include/strv.h \
531551
 	include/swapheader.h \
531551
 	include/sysfs.h \
531551
 	include/timer.h \
531551
diff --git a/include/c.h b/include/c.h
531551
index a2779a5..3754e75 100644
531551
--- a/include/c.h
531551
+++ b/include/c.h
531551
@@ -309,6 +309,14 @@ static inline int usleep(useconds_t usec)
531551
 #endif
531551
 
531551
 /*
531551
+ * Macros to convert #define'itions to strings, for example
531551
+ * #define XYXXY 42
531551
+ * printf ("%s=%s\n", stringify(XYXXY), stringify_value(XYXXY));
531551
+ */
531551
+#define stringify_value(s) stringify(s)
531551
+#define stringify(s) #s
531551
+
531551
+/*
531551
  * Note that sysconf(_SC_GETPW_R_SIZE_MAX) returns *initial* suggested size for
531551
  * pwd buffer and in some cases it is not large enough. See POSIX and
531551
  * getpwnam_r man page for more details.
531551
diff --git a/include/strutils.h b/include/strutils.h
531551
index 709fcad..aa7b95f 100644
531551
--- a/include/strutils.h
531551
+++ b/include/strutils.h
531551
@@ -5,6 +5,7 @@
531551
 #include <inttypes.h>
531551
 #include <string.h>
531551
 #include <sys/types.h>
531551
+#include <stdio.h>
531551
 
531551
 /* default strtoxx_or_err() exit code */
531551
 #ifndef STRTOXX_EXIT_CODE
531551
@@ -102,4 +103,12 @@ extern int parse_range(const char *str, int *lower, int *upper, int def);
531551
 
531551
 extern int streq_except_trailing_slash(const char *s1, const char *s2);
531551
 
531551
+extern char *strnappend(const char *s, const char *suffix, size_t b);
531551
+extern char *strappend(const char *s, const char *suffix);
531551
+extern char *strfappend(const char *s, const char *format, ...)
531551
+		 __attribute__ ((__format__ (__printf__, 2, 0)));
531551
+extern const char *split(const char **state, size_t *l, const char *separator, int quoted);
531551
+
531551
+extern int skip_fline(FILE *fp);
531551
+
531551
 #endif
531551
diff --git a/include/strv.h b/include/strv.h
531551
new file mode 100644
531551
index 0000000..260ad12
531551
--- /dev/null
531551
+++ b/include/strv.h
531551
@@ -0,0 +1,55 @@
531551
+#ifndef UTIL_LINUX_STRV
531551
+#define UTIL_LINUX_STRV
531551
+
531551
+#include <stdarg.h>
531551
+
531551
+#include "c.h"
531551
+
531551
+char **strv_free(char **l);
531551
+void strv_clear(char **l);
531551
+char **strv_copy(char * const *l);
531551
+unsigned strv_length(char * const *l);
531551
+
531551
+int strv_extend_strv(char ***a, char **b);
531551
+int strv_extend_strv_concat(char ***a, char **b, const char *suffix);
531551
+int strv_extend(char ***l, const char *value);
531551
+int strv_extendv(char ***l, const char *format, va_list ap);
531551
+int strv_extendf(char ***l, const char *format, ...)
531551
+			__attribute__ ((__format__ (__printf__, 2, 0)));
531551
+int strv_push(char ***l, char *value);
531551
+int strv_push_prepend(char ***l, char *value);
531551
+int strv_consume(char ***l, char *value);
531551
+int strv_consume_prepend(char ***l, char *value);
531551
+
531551
+char **strv_remove(char **l, const char *s);
531551
+
531551
+char **strv_new(const char *x, ...);
531551
+char **strv_new_ap(const char *x, va_list ap);
531551
+
531551
+static inline const char* STRV_IFNOTNULL(const char *x) {
531551
+        return x ? x : (const char *) -1;
531551
+}
531551
+
531551
+static inline int strv_isempty(char * const *l) {
531551
+        return !l || !*l;
531551
+}
531551
+
531551
+char **strv_split(const char *s, const char *separator);
531551
+char *strv_join(char **l, const char *separator);
531551
+
531551
+#define STRV_FOREACH(s, l)                      \
531551
+        for ((s) = (l); (s) && *(s); (s)++)
531551
+
531551
+#define STRV_FOREACH_BACKWARDS(s, l)            \
531551
+        STRV_FOREACH(s, l)                      \
531551
+                ;                               \
531551
+        for ((s)--; (l) && ((s) >= (l)); (s)--)
531551
+
531551
+
531551
+#define STRV_MAKE_EMPTY ((char*[1]) { NULL })
531551
+
531551
+char **strv_reverse(char **l);
531551
+
531551
+#endif /* UTIL_LINUX_STRV */
531551
+
531551
+
531551
diff --git a/include/sysfs.h b/include/sysfs.h
531551
index 0a9c218..a547005 100644
531551
--- a/include/sysfs.h
531551
+++ b/include/sysfs.h
531551
@@ -58,6 +58,9 @@ extern int sysfs_read_s64(struct sysfs_cxt *cxt, const char *attr, int64_t *res)
531551
 extern int sysfs_read_u64(struct sysfs_cxt *cxt, const char *attr, uint64_t *res);
531551
 extern int sysfs_read_int(struct sysfs_cxt *cxt, const char *attr, int *res);
531551
 
531551
+extern int sysfs_write_string(struct sysfs_cxt *cxt, const char *attr, const char *str);
531551
+extern int sysfs_write_u64(struct sysfs_cxt *cxt, const char *attr, uint64_t num);
531551
+
531551
 extern char *sysfs_get_devname(struct sysfs_cxt *cxt, char *buf, size_t bufsiz);
531551
 
531551
 extern char *sysfs_strdup(struct sysfs_cxt *cxt, const char *attr);
531551
diff --git a/lib/Makemodule.am b/lib/Makemodule.am
531551
index 73280f9..faf9d74 100644
531551
--- a/lib/Makemodule.am
531551
+++ b/lib/Makemodule.am
531551
@@ -27,7 +27,8 @@ libcommon_la_SOURCES = \
531551
 	lib/ttyutils.c \
531551
 	lib/xgetpass.c \
531551
 	lib/exec_shell.c \
531551
-	lib/readutmp.c
531551
+	lib/readutmp.c \
531551
+	lib/strv.c
531551
 
531551
 if LINUX
531551
 libcommon_la_SOURCES += \
531551
diff --git a/lib/strutils.c b/lib/strutils.c
531551
index f9cdcbb..4b8a813 100644
531551
--- a/lib/strutils.c
531551
+++ b/lib/strutils.c
531551
@@ -10,6 +10,7 @@
531551
 #include <errno.h>
531551
 #include <sys/stat.h>
531551
 #include <string.h>
531551
+#include <assert.h>
531551
 
531551
 #include "c.h"
531551
 #include "nls.h"
531551
@@ -687,6 +688,134 @@ int streq_except_trailing_slash(const char *s1, const char *s2)
531551
 	return equal;
531551
 }
531551
 
531551
+char *strnappend(const char *s, const char *suffix, size_t b)
531551
+{
531551
+        size_t a;
531551
+        char *r;
531551
+
531551
+        if (!s && !suffix)
531551
+                return strdup("");
531551
+        if (!s)
531551
+                return strndup(suffix, b);
531551
+        if (!suffix)
531551
+                return strdup(s);
531551
+
531551
+        assert(s);
531551
+        assert(suffix);
531551
+
531551
+        a = strlen(s);
531551
+        if (b > ((size_t) -1) - a)
531551
+                return NULL;
531551
+
531551
+        r = malloc(a + b + 1);
531551
+        if (!r)
531551
+                return NULL;
531551
+
531551
+        memcpy(r, s, a);
531551
+        memcpy(r + a, suffix, b);
531551
+        r[a+b] = 0;
531551
+
531551
+        return r;
531551
+}
531551
+
531551
+char *strappend(const char *s, const char *suffix)
531551
+{
531551
+        return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
531551
+}
531551
+
531551
+char *strfappend(const char *s, const char *format, ...)
531551
+{
531551
+	va_list ap;
531551
+	char *val, *res;
531551
+	int sz;
531551
+
531551
+	va_start(ap, format);
531551
+	sz = vasprintf(&val, format, ap);
531551
+	va_end(ap);
531551
+
531551
+	if (sz < 0)
531551
+		return NULL;
531551
+
531551
+	res = strnappend(s, val, sz);
531551
+	free(val);
531551
+	return res;
531551
+}
531551
+
531551
+static size_t strcspn_escaped(const char *s, const char *reject)
531551
+{
531551
+        int escaped = 0;
531551
+        int n;
531551
+
531551
+        for (n=0; s[n]; n++) {
531551
+                if (escaped)
531551
+                        escaped = 0;
531551
+                else if (s[n] == '\\')
531551
+                        escaped = 1;
531551
+                else if (strchr(reject, s[n]))
531551
+                        break;
531551
+        }
531551
+
531551
+        /* if s ends in \, return index of previous char */
531551
+        return n - escaped;
531551
+}
531551
+
531551
+/* Split a string into words. */
531551
+const char *split(const char **state, size_t *l, const char *separator, int quoted)
531551
+{
531551
+        const char *current;
531551
+
531551
+        current = *state;
531551
+
531551
+        if (!*current) {
531551
+                assert(**state == '\0');
531551
+                return NULL;
531551
+        }
531551
+
531551
+        current += strspn(current, separator);
531551
+        if (!*current) {
531551
+                *state = current;
531551
+                return NULL;
531551
+        }
531551
+
531551
+        if (quoted && strchr("\'\"", *current)) {
531551
+                char quotechars[2] = {*current, '\0'};
531551
+
531551
+                *l = strcspn_escaped(current + 1, quotechars);
531551
+                if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
531551
+                    (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
531551
+                        /* right quote missing or garbage at the end */
531551
+                        *state = current;
531551
+                        return NULL;
531551
+                }
531551
+                *state = current++ + *l + 2;
531551
+        } else if (quoted) {
531551
+                *l = strcspn_escaped(current, separator);
531551
+                if (current[*l] && !strchr(separator, current[*l])) {
531551
+                        /* unfinished escape */
531551
+                        *state = current;
531551
+                        return NULL;
531551
+                }
531551
+                *state = current + *l;
531551
+        } else {
531551
+                *l = strcspn(current, separator);
531551
+                *state = current + *l;
531551
+        }
531551
+
531551
+        return current;
531551
+}
531551
+
531551
+/* Rewind file pointer forward to new line.  */
531551
+int skip_fline(FILE *fp)
531551
+{
531551
+	int ch;
531551
+
531551
+	do {
531551
+		if ((ch = fgetc(fp)) == EOF)
531551
+			return 1;
531551
+		if (ch == '\n')
531551
+			return 0;
531551
+	} while (1);
531551
+}
531551
 
531551
 #ifdef TEST_PROGRAM
531551
 
531551
diff --git a/lib/strv.c b/lib/strv.c
531551
new file mode 100644
531551
index 0000000..ddc2a0c
531551
--- /dev/null
531551
+++ b/lib/strv.c
531551
@@ -0,0 +1,403 @@
531551
+/*
531551
+ *
531551
+ * Copyright 2010 Lennart Poettering
531551
+ *
531551
+ * This is free software; you can redistribute it and/or modify it
531551
+ * under the terms of the GNU Lesser General Public License as published by
531551
+ * the Free Software Foundation; either version 2.1 of the License, or
531551
+ * (at your option) any later version.
531551
+ *
531551
+ *
531551
+ * Copyright (C) 2015 Karel Zak <kzak@redhat.com>
531551
+ *    Modified the original version from systemd project for util-linux.
531551
+ */
531551
+
531551
+#include <stdlib.h>
531551
+#include <stdarg.h>
531551
+#include <string.h>
531551
+#include <errno.h>
531551
+#include <stdbool.h>
531551
+#include <assert.h>
531551
+
531551
+#include "strutils.h"
531551
+#include "strv.h"
531551
+
531551
+void strv_clear(char **l) {
531551
+        char **k;
531551
+
531551
+        if (!l)
531551
+                return;
531551
+
531551
+        for (k = l; *k; k++)
531551
+                free(*k);
531551
+
531551
+        *l = NULL;
531551
+}
531551
+
531551
+char **strv_free(char **l) {
531551
+        strv_clear(l);
531551
+        free(l);
531551
+        return NULL;
531551
+}
531551
+
531551
+char **strv_copy(char * const *l) {
531551
+        char **r, **k;
531551
+
531551
+        k = r = malloc(sizeof(char *) * (strv_length(l) + 1));
531551
+        if (!r)
531551
+                return NULL;
531551
+
531551
+        if (l)
531551
+                for (; *l; k++, l++) {
531551
+                        *k = strdup(*l);
531551
+                        if (!*k) {
531551
+                                strv_free(r);
531551
+                                return NULL;
531551
+                        }
531551
+                }
531551
+
531551
+        *k = NULL;
531551
+        return r;
531551
+}
531551
+
531551
+unsigned strv_length(char * const *l) {
531551
+        unsigned n = 0;
531551
+
531551
+        if (!l)
531551
+                return 0;
531551
+
531551
+        for (; *l; l++)
531551
+                n++;
531551
+
531551
+        return n;
531551
+}
531551
+
531551
+char **strv_new_ap(const char *x, va_list ap) {
531551
+        const char *s;
531551
+        char **a;
531551
+        unsigned n = 0, i = 0;
531551
+        va_list aq;
531551
+
531551
+        /* As a special trick we ignore all listed strings that equal
531551
+         * (const char*) -1. This is supposed to be used with the
531551
+         * STRV_IFNOTNULL() macro to include possibly NULL strings in
531551
+         * the string list. */
531551
+
531551
+        if (x) {
531551
+                n = x == (const char*) -1 ? 0 : 1;
531551
+
531551
+                va_copy(aq, ap);
531551
+                while ((s = va_arg(aq, const char*))) {
531551
+                        if (s == (const char*) -1)
531551
+                                continue;
531551
+
531551
+                        n++;
531551
+                }
531551
+
531551
+                va_end(aq);
531551
+        }
531551
+
531551
+        a = malloc(sizeof(char *) * (n + 1));
531551
+        if (!a)
531551
+                return NULL;
531551
+
531551
+        if (x) {
531551
+                if (x != (const char*) -1) {
531551
+                        a[i] = strdup(x);
531551
+                        if (!a[i])
531551
+                                goto fail;
531551
+                        i++;
531551
+                }
531551
+
531551
+                while ((s = va_arg(ap, const char*))) {
531551
+
531551
+                        if (s == (const char*) -1)
531551
+                                continue;
531551
+
531551
+                        a[i] = strdup(s);
531551
+                        if (!a[i])
531551
+                                goto fail;
531551
+
531551
+                        i++;
531551
+                }
531551
+        }
531551
+
531551
+        a[i] = NULL;
531551
+
531551
+        return a;
531551
+
531551
+fail:
531551
+        strv_free(a);
531551
+        return NULL;
531551
+}
531551
+
531551
+char **strv_new(const char *x, ...) {
531551
+        char **r;
531551
+        va_list ap;
531551
+
531551
+        va_start(ap, x);
531551
+        r = strv_new_ap(x, ap);
531551
+        va_end(ap);
531551
+
531551
+        return r;
531551
+}
531551
+
531551
+int strv_extend_strv(char ***a, char **b) {
531551
+        int r;
531551
+        char **s;
531551
+
531551
+        STRV_FOREACH(s, b) {
531551
+                r = strv_extend(a, *s);
531551
+                if (r < 0)
531551
+                        return r;
531551
+        }
531551
+
531551
+        return 0;
531551
+}
531551
+
531551
+int strv_extend_strv_concat(char ***a, char **b, const char *suffix) {
531551
+        int r;
531551
+        char **s;
531551
+
531551
+        STRV_FOREACH(s, b) {
531551
+                char *v;
531551
+
531551
+                v = strappend(*s, suffix);
531551
+                if (!v)
531551
+                        return -ENOMEM;
531551
+
531551
+                r = strv_push(a, v);
531551
+                if (r < 0) {
531551
+                        free(v);
531551
+                        return r;
531551
+                }
531551
+        }
531551
+
531551
+        return 0;
531551
+}
531551
+
531551
+
531551
+#define _FOREACH_WORD(word, length, s, separator, quoted, state)        \
531551
+        for ((state) = (s), (word) = split(&(state), &(length), (separator), (quoted)); (word); (word) = split(&(state), &(length), (separator), (quoted)))
531551
+
531551
+#define FOREACH_WORD_SEPARATOR(word, length, s, separator, state)       \
531551
+        _FOREACH_WORD(word, length, s, separator, false, state)
531551
+
531551
+
531551
+char **strv_split(const char *s, const char *separator) {
531551
+        const char *word, *state;
531551
+        size_t l;
531551
+        unsigned n, i;
531551
+        char **r;
531551
+
531551
+        assert(s);
531551
+
531551
+        n = 0;
531551
+        FOREACH_WORD_SEPARATOR(word, l, s, separator, state)
531551
+                n++;
531551
+
531551
+        r = malloc(sizeof(char *) * (n + 1));
531551
+        if (!r)
531551
+                return NULL;
531551
+
531551
+        i = 0;
531551
+        FOREACH_WORD_SEPARATOR(word, l, s, separator, state) {
531551
+                r[i] = strndup(word, l);
531551
+                if (!r[i]) {
531551
+                        strv_free(r);
531551
+                        return NULL;
531551
+                }
531551
+
531551
+                i++;
531551
+        }
531551
+
531551
+        r[i] = NULL;
531551
+        return r;
531551
+}
531551
+
531551
+char *strv_join(char **l, const char *separator) {
531551
+        char *r, *e;
531551
+        char **s;
531551
+        size_t n, k;
531551
+
531551
+        if (!separator)
531551
+                separator = " ";
531551
+
531551
+        k = strlen(separator);
531551
+
531551
+        n = 0;
531551
+        STRV_FOREACH(s, l) {
531551
+                if (n != 0)
531551
+                        n += k;
531551
+                n += strlen(*s);
531551
+        }
531551
+
531551
+        r = malloc(n + 1);
531551
+        if (!r)
531551
+                return NULL;
531551
+
531551
+        e = r;
531551
+        STRV_FOREACH(s, l) {
531551
+                if (e != r)
531551
+                        e = stpcpy(e, separator);
531551
+
531551
+                e = stpcpy(e, *s);
531551
+        }
531551
+
531551
+        *e = 0;
531551
+
531551
+        return r;
531551
+}
531551
+
531551
+int strv_push(char ***l, char *value) {
531551
+        char **c;
531551
+        unsigned n, m;
531551
+
531551
+        if (!value)
531551
+                return 0;
531551
+
531551
+        n = strv_length(*l);
531551
+
531551
+        /* Increase and check for overflow */
531551
+        m = n + 2;
531551
+        if (m < n)
531551
+                return -ENOMEM;
531551
+
531551
+        c = realloc(*l, sizeof(char *) * m);
531551
+        if (!c)
531551
+                return -ENOMEM;
531551
+
531551
+        c[n] = value;
531551
+        c[n+1] = NULL;
531551
+
531551
+        *l = c;
531551
+        return 0;
531551
+}
531551
+
531551
+int strv_push_prepend(char ***l, char *value) {
531551
+        char **c;
531551
+        unsigned n, m, i;
531551
+
531551
+        if (!value)
531551
+                return 0;
531551
+
531551
+        n = strv_length(*l);
531551
+
531551
+        /* increase and check for overflow */
531551
+        m = n + 2;
531551
+        if (m < n)
531551
+                return -ENOMEM;
531551
+
531551
+        c = malloc(sizeof(char *) * m);
531551
+        if (!c)
531551
+                return -ENOMEM;
531551
+
531551
+        for (i = 0; i < n; i++)
531551
+                c[i+1] = (*l)[i];
531551
+
531551
+        c[0] = value;
531551
+        c[n+1] = NULL;
531551
+
531551
+        free(*l);
531551
+        *l = c;
531551
+
531551
+        return 0;
531551
+}
531551
+
531551
+int strv_consume(char ***l, char *value) {
531551
+        int r;
531551
+
531551
+        r = strv_push(l, value);
531551
+        if (r < 0)
531551
+                free(value);
531551
+
531551
+        return r;
531551
+}
531551
+
531551
+int strv_consume_prepend(char ***l, char *value) {
531551
+        int r;
531551
+
531551
+        r = strv_push_prepend(l, value);
531551
+        if (r < 0)
531551
+                free(value);
531551
+
531551
+        return r;
531551
+}
531551
+
531551
+int strv_extend(char ***l, const char *value) {
531551
+        char *v;
531551
+
531551
+        if (!value)
531551
+                return 0;
531551
+
531551
+        v = strdup(value);
531551
+        if (!v)
531551
+                return -ENOMEM;
531551
+
531551
+        return strv_consume(l, v);
531551
+}
531551
+
531551
+char **strv_remove(char **l, const char *s) {
531551
+        char **f, **t;
531551
+
531551
+        if (!l)
531551
+                return NULL;
531551
+
531551
+        assert(s);
531551
+
531551
+        /* Drops every occurrence of s in the string list, edits
531551
+         * in-place. */
531551
+
531551
+        for (f = t = l; *f; f++)
531551
+                if (strcmp(*f, s) == 0)
531551
+                        free(*f);
531551
+                else
531551
+                        *(t++) = *f;
531551
+
531551
+        *t = NULL;
531551
+        return l;
531551
+}
531551
+
531551
+int strv_extendf(char ***l, const char *format, ...) {
531551
+        va_list ap;
531551
+        char *x;
531551
+        int r;
531551
+
531551
+        va_start(ap, format);
531551
+        r = vasprintf(&x, format, ap);
531551
+        va_end(ap);
531551
+
531551
+        if (r < 0)
531551
+                return -ENOMEM;
531551
+
531551
+        return strv_consume(l, x);
531551
+}
531551
+
531551
+int strv_extendv(char ***l, const char *format, va_list ap) {
531551
+        char *x;
531551
+        int r;
531551
+
531551
+        r = vasprintf(&x, format, ap);
531551
+        if (r < 0)
531551
+                return -ENOMEM;
531551
+
531551
+        return strv_consume(l, x);
531551
+}
531551
+
531551
+char **strv_reverse(char **l) {
531551
+        unsigned n, i;
531551
+
531551
+        n = strv_length(l);
531551
+        if (n <= 1)
531551
+                return l;
531551
+
531551
+        for (i = 0; i < n / 2; i++) {
531551
+                char *t;
531551
+
531551
+                t = l[i];
531551
+                l[i] = l[n-1-i];
531551
+                l[n-1-i] = t;
531551
+        }
531551
+
531551
+        return l;
531551
+}
531551
diff --git a/lib/sysfs.c b/lib/sysfs.c
531551
index 0bfd622..65a8394 100644
531551
--- a/lib/sysfs.c
531551
+++ b/lib/sysfs.c
531551
@@ -10,6 +10,7 @@
531551
 #include "at.h"
531551
 #include "pathnames.h"
531551
 #include "sysfs.h"
531551
+#include "all-io.h"
531551
 
531551
 char *sysfs_devno_attribute_path(dev_t devno, char *buf,
531551
 				 size_t bufsiz, const char *attr)
531551
@@ -203,9 +204,9 @@ int sysfs_has_attribute(struct sysfs_cxt *cxt, const char *attr)
531551
 	return sysfs_stat(cxt, attr, &st) == 0;
531551
 }
531551
 
531551
-static int sysfs_open(struct sysfs_cxt *cxt, const char *attr)
531551
+static int sysfs_open(struct sysfs_cxt *cxt, const char *attr, int flags)
531551
 {
531551
-	int fd = open_at(cxt->dir_fd, cxt->dir_path, attr, O_RDONLY|O_CLOEXEC);
531551
+	int fd = open_at(cxt->dir_fd, cxt->dir_path, attr, flags);
531551
 
531551
 	if (fd == -1 && errno == ENOENT &&
531551
 	    strncmp(attr, "queue/", 6) == 0 && cxt->parent) {
531551
@@ -238,7 +239,7 @@ DIR *sysfs_opendir(struct sysfs_cxt *cxt, const char *attr)
531551
 	int fd = -1;
531551
 
531551
 	if (attr)
531551
-		fd = sysfs_open(cxt, attr);
531551
+		fd = sysfs_open(cxt, attr, O_RDONLY|O_CLOEXEC);
531551
 
531551
 	else if (cxt->dir_fd >= 0)
531551
 		/* request to open root of device in sysfs (/sys/block/<dev>)
531551
@@ -263,7 +264,7 @@ DIR *sysfs_opendir(struct sysfs_cxt *cxt, const char *attr)
531551
 
531551
 static FILE *sysfs_fopen(struct sysfs_cxt *cxt, const char *attr)
531551
 {
531551
-	int fd = sysfs_open(cxt, attr);
531551
+	int fd = sysfs_open(cxt, attr, O_RDONLY|O_CLOEXEC);
531551
 
531551
 	return fd < 0 ? NULL : fdopen(fd, "r" UL_CLOEXECSTR);
531551
 }
531551
@@ -417,6 +418,42 @@ int sysfs_read_int(struct sysfs_cxt *cxt, const char *attr, int *res)
531551
 	return -1;
531551
 }
531551
 
531551
+int sysfs_write_string(struct sysfs_cxt *cxt, const char *attr, const char *str)
531551
+{
531551
+	int fd = sysfs_open(cxt, attr, O_WRONLY|O_CLOEXEC);
531551
+	int rc, errsv;
531551
+
531551
+	if (fd < 0)
531551
+		return -errno;
531551
+	rc = write_all(fd, str, strlen(str));
531551
+
531551
+	errsv = errno;
531551
+	close(fd);
531551
+	errno = errsv;
531551
+	return rc;
531551
+}
531551
+
531551
+int sysfs_write_u64(struct sysfs_cxt *cxt, const char *attr, uint64_t num)
531551
+{
531551
+	char buf[sizeof(stringify_value(ULLONG_MAX))];
531551
+	int fd, rc = 0, len, errsv;
531551
+
531551
+	fd = sysfs_open(cxt, attr, O_WRONLY|O_CLOEXEC);
531551
+	if (fd < 0)
531551
+		return -errno;
531551
+
531551
+	len = snprintf(buf, sizeof(buf), "%" PRIu64, num);
531551
+	if (len < 0 || (size_t) len >= sizeof(buf))
531551
+		rc = len < 0 ? -errno : -E2BIG;
531551
+	else
531551
+		rc = write_all(fd, buf, len);
531551
+
531551
+	errsv = errno;
531551
+	close(fd);
531551
+	errno = errsv;
531551
+	return rc;
531551
+}
531551
+
531551
 char *sysfs_strdup(struct sysfs_cxt *cxt, const char *attr)
531551
 {
531551
 	char buf[1024];
531551
diff --git a/sys-utils/Makemodule.am b/sys-utils/Makemodule.am
531551
index 6badd17..408e884 100644
531551
--- a/sys-utils/Makemodule.am
531551
+++ b/sys-utils/Makemodule.am
531551
@@ -184,6 +184,13 @@ losetup_static_LDADD = $(losetup_LDADD)
531551
 endif
531551
 endif # BUILD_LOSETUP
531551
 
531551
+if BUILD_ZRAMCTL
531551
+sbin_PROGRAMS += zramctl
531551
+dist_man_MANS += sys-utils/zramctl.8
531551
+zramctl_SOURCES = sys-utils/zramctl.c
531551
+zramctl_LDADD = $(LDADD) libcommon.la libsmartcols.la
531551
+zramctl_CFLAGS = $(AM_CFLAGS) -I$(ul_libsmartcols_incdir)
531551
+endif
531551
 
531551
 if BUILD_PRLIMIT
531551
 usrbin_exec_PROGRAMS += prlimit
531551
diff --git a/sys-utils/zramctl.8 b/sys-utils/zramctl.8
531551
new file mode 100644
531551
index 0000000..f6fc45c
531551
--- /dev/null
531551
+++ b/sys-utils/zramctl.8
531551
@@ -0,0 +1,123 @@
531551
+.TH ZRAMCTL 8 "July 2014" "util-linux" "System Administration"
531551
+.SH NAME
531551
+zramctl \- set up and control zram devices
531551
+.SH SYNOPSIS
531551
+.ad l
531551
+Get info:
531551
+.sp
531551
+.in +5
531551
+.BR zramctl " [options]"
531551
+.sp
531551
+.in -5
531551
+Reset zram:
531551
+.sp
531551
+.in +5
531551
+.B "zramctl \-r"
531551
+.IR zramdev ...
531551
+.sp
531551
+.in -5
531551
+Print name of first unused zram device:
531551
+.sp
531551
+.in +5
531551
+.B "zramctl \-f"
531551
+.sp
531551
+.in -5
531551
+Set up a zram device:
531551
+.sp
531551
+.in +5
531551
+.B zramctl
531551
+.RB [ \-f " | "\fIzramdev\fP ]
531551
+.RB [ \-s
531551
+.IR size ]
531551
+.RB [ \-t
531551
+.IR number ]
531551
+.RB [ \-a
531551
+.IR algorithm ]
531551
+.sp
531551
+.in -5
531551
+.ad b
531551
+.SH DESCRIPTION
531551
+.B zramctl
531551
+is used to quickly set up zram device parameters, to reset zram devices, and to
531551
+query the status of used zram devices.  If no option is given, all zram devices
531551
+are shown.
531551
+
531551
+.SH OPTIONS
531551
+.TP
531551
+.BR \-a , " \-\-algorithm lzo" | lz4
531551
+Set the compression algorithm to be used for compressing data in the zram device.
531551
+.TP
531551
+.BR \-f , " \-\-find"
531551
+Find the first unused zram device.  If a \fB--size\fR argument is present, then
531551
+initialize the device.
531551
+.TP
531551
+.BR \-n , " \-\-noheadings"
531551
+Do not print a header line in status output.
531551
+.TP
531551
+.BR \-o , " \-\-output " \fIlist
531551
+Define the status output columns to be used.  If no output arrangement is
531551
+specified, then a default set is used.
531551
+Use \fB\-\-help\fP to get a list of all supported columns.
531551
+.TP
531551
+.B \-\-raw
531551
+Use the raw format for status output.
531551
+.TP
531551
+.BR \-r , " \-\-reset"
531551
+Reset the options of the specified zram device(s).  Zram device settings
531551
+can be changed only after a reset.
531551
+.TP
531551
+.BR \-s , " \-\-size " \fIsize
531551
+Create a zram device of the specified \fIsize\fR.
531551
+Zram devices are aligned to memory pages; when the requested \fIsize\fR is
531551
+not a multiple of the page size, it will be rounded up to the next multiple.
531551
+When not otherwise specified, the unit of the \fIsize\fR parameter is bytes.
531551
+.IP
531551
+The \fIsize\fR argument may be followed by the multiplicative suffixes KiB (=1024),
531551
+MiB (=1024*1024), and so on for GiB, TiB, PiB, EiB, ZiB and YiB (the "iB"
531551
+is optional, e.g., "K" has the same meaning as "KiB") or the suffixes
531551
+KB (=1000), MB (=1000*1000), and so on for GB, TB, PB, EB, ZB and YB.
531551
+.TP
531551
+.BR \-t , " \-\-streams " \fInumber
531551
+Set the maximum number of compression streams that can be used for the device.
531551
+The default is one stream.
531551
+.TP
531551
+.BR \-V , " \-\-version"
531551
+Display version information and exit.
531551
+.TP
531551
+.BR \-h , " \-\-help"
531551
+Display help text and exit.
531551
+
531551
+.SH RETURN VALUE
531551
+.B zramctl
531551
+returns 0 on success, nonzero on failure.
531551
+
531551
+.SH FILES
531551
+.TP
531551
+.I /dev/zram[0..N]
531551
+zram block devices
531551
+
531551
+.SH EXAMPLE
531551
+The following commands set up a zram device with a size of one gigabyte
531551
+and use it as swap device.
531551
+.nf
531551
+.IP
531551
+# zramctl --find --size 1024M
531551
+/dev/zram0
531551
+# mkswap /dev/zram0
531551
+# swapon /dev/zram0
531551
+ ...
531551
+# swapoff /dev/zram0
531551
+# zramctl --reset /dev/zram0
531551
+.fi
531551
+.SH SEE ALSO
531551
+.UR http://git.\:kernel.\:org\:/cgit\:/linux\:/kernel\:/git\:/torvalds\:/linux.git\:/tree\:/Documentation\:/blockdev\:/zram.txt
531551
+Linux kernel documentation
531551
+.UE .
531551
+.SH AUTHORS
531551
+.nf
531551
+Timofey Titovets <nefelim4ag@gmail.com>
531551
+Karel Zak <kzak@redhat.com>
531551
+.fi
531551
+.SH AVAILABILITY
531551
+The zramctl command is part of the util-linux package and is available from
531551
+https://www.kernel.org/pub/linux/utils/util-linux/.
531551
diff --git a/sys-utils/zramctl.c b/sys-utils/zramctl.c
531551
new file mode 100644
531551
index 0000000..853401c
531551
--- /dev/null
531551
+++ b/sys-utils/zramctl.c
531551
@@ -0,0 +1,736 @@
531551
+/*
531551
+ * zramctl - control compressed block devices in RAM
531551
+ *
531551
+ * Copyright (c) 2014 Timofey Titovets <Nefelim4ag@gmail.com>
531551
+ * Copyright (C) 2014 Karel Zak <kzak@redhat.com>
531551
+ *
531551
+ * This program is free software; you can redistribute it and/or
531551
+ * modify it under the terms of the GNU General Public License as
531551
+ * published by the Free Software Foundation.
531551
+ *
531551
+ * This program is distributed in the hope that it would be useful,
531551
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
531551
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
531551
+ * GNU General Public License for more details.
531551
+ *
531551
+ * You should have received a copy of the GNU General Public License along
531551
+ * with this program; if not, write to the Free Software Foundation, Inc.,
531551
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
531551
+ */
531551
+
531551
+#include <getopt.h>
531551
+#include <stdlib.h>
531551
+#include <string.h>
531551
+#include <stdarg.h>
531551
+#include <assert.h>
531551
+
531551
+#include <libsmartcols.h>
531551
+
531551
+#include "c.h"
531551
+#include "nls.h"
531551
+#include "closestream.h"
531551
+#include "strutils.h"
531551
+#include "xalloc.h"
531551
+#include "sysfs.h"
531551
+#include "optutils.h"
531551
+#include "ismounted.h"
531551
+#include "strv.h"
531551
+#include "path.h"
531551
+#include "pathnames.h"
531551
+
531551
+/*#define CONFIG_ZRAM_DEBUG*/
531551
+
531551
+#ifdef CONFIG_ZRAM_DEBUG
531551
+# define DBG(x)	 do { fputs("zram: ", stderr); x; fputc('\n', stderr); } while(0)
531551
+#else
531551
+# define DBG(x)
531551
+#endif
531551
+
531551
+/* status output columns */
531551
+struct colinfo {
531551
+	const char *name;
531551
+	double whint;
531551
+	int flags;
531551
+	const char *help;
531551
+};
531551
+
531551
+enum {
531551
+	COL_NAME = 0,
531551
+	COL_DISKSIZE,
531551
+	COL_ORIG_SIZE,
531551
+	COL_COMP_SIZE,
531551
+	COL_ALGORITHM,
531551
+	COL_STREAMS,
531551
+	COL_ZEROPAGES,
531551
+	COL_MEMTOTAL,
531551
+	COL_MEMLIMIT,
531551
+	COL_MEMUSED,
531551
+	COL_MIGRATED,
531551
+	COL_MOUNTPOINT
531551
+};
531551
+
531551
+static const struct colinfo infos[] = {
531551
+	[COL_NAME]      = { "NAME",      0.25, 0, N_("zram device name") },
531551
+	[COL_DISKSIZE]  = { "DISKSIZE",     5, SCOLS_FL_RIGHT, N_("limit on the uncompressed amount of data") },
531551
+	[COL_ORIG_SIZE] = { "DATA",         5, SCOLS_FL_RIGHT, N_("uncompressed size of stored data") },
531551
+	[COL_COMP_SIZE] = { "COMPR",        5, SCOLS_FL_RIGHT, N_("compressed size of stored data") },
531551
+	[COL_ALGORITHM] = { "ALGORITHM",    3, 0, N_("the selected compression algorithm") },
531551
+	[COL_STREAMS]   = { "STREAMS",      3, SCOLS_FL_RIGHT, N_("number of concurrent compress operations") },
531551
+	[COL_ZEROPAGES] = { "ZERO-PAGES",   3, SCOLS_FL_RIGHT, N_("empty pages with no allocated memory") },
531551
+	[COL_MEMTOTAL]  = { "TOTAL",        5, SCOLS_FL_RIGHT, N_("all memory including allocator fragmentation and metadata overhead") },
531551
+	[COL_MEMLIMIT]  = { "MEM-LIMIT",    5, SCOLS_FL_RIGHT, N_("memory limit used to store compressed data") },
531551
+	[COL_MEMUSED]   = { "MEM-USED",     5, SCOLS_FL_RIGHT, N_("memory zram have been consumed to store compressed data") },
531551
+	[COL_MIGRATED]  = { "MIGRATED",     5, SCOLS_FL_RIGHT, N_("number of objects migrated by compaction") },
531551
+	[COL_MOUNTPOINT]= { "MOUNTPOINT",0.10, SCOLS_FL_TRUNC, N_("where the device is mounted") },
531551
+};
531551
+
531551
+static int columns[ARRAY_SIZE(infos) * 2] = {-1};
531551
+static int ncolumns;
531551
+
531551
+enum {
531551
+	MM_ORIG_DATA_SIZE = 0,
531551
+	MM_COMPR_DATA_SIZE,
531551
+	MM_MEM_USED_TOTAL,
531551
+	MM_MEM_LIMIT,
531551
+	MM_MEM_USED_MAX,
531551
+	MM_ZERO_PAGES,
531551
+	MM_NUM_MIGRATED
531551
+};
531551
+
531551
+static const char *mm_stat_names[] = {
531551
+	[MM_ORIG_DATA_SIZE]  = "orig_data_size",
531551
+	[MM_COMPR_DATA_SIZE] = "compr_data_size",
531551
+	[MM_MEM_USED_TOTAL]  = "mem_used_total",
531551
+	[MM_MEM_LIMIT]       = "mem_limit",
531551
+	[MM_MEM_USED_MAX]    = "mem_used_max",
531551
+	[MM_ZERO_PAGES]      = "zero_pages",
531551
+	[MM_NUM_MIGRATED]    = "num_migrated"
531551
+};
531551
+
531551
+
531551
+struct zram {
531551
+	char	devname[32];
531551
+	struct sysfs_cxt sysfs;
531551
+	char	**mm_stat;
531551
+
531551
+	unsigned int mm_stat_probed : 1,
531551
+		     control_probed : 1,
531551
+		     has_control : 1;	/* has /sys/class/zram-control/ */
531551
+};
531551
+
531551
+#define ZRAM_EMPTY	{ .devname = { '\0' }, .sysfs = UL_SYSFSCXT_EMPTY }
531551
+
531551
+static unsigned int raw, no_headings, inbytes;
531551
+
531551
+
531551
+static int get_column_id(int num)
531551
+{
531551
+	assert(num < ncolumns);
531551
+	assert(columns[num] < (int) ARRAY_SIZE(infos));
531551
+	return columns[num];
531551
+}
531551
+
531551
+static const struct colinfo *get_column_info(int num)
531551
+{
531551
+	return &infos[ get_column_id(num) ];
531551
+}
531551
+
531551
+static int column_name_to_id(const char *name, size_t namesz)
531551
+{
531551
+	size_t i;
531551
+
531551
+	for (i = 0; i < ARRAY_SIZE(infos); i++) {
531551
+		const char *cn = infos[i].name;
531551
+
531551
+		if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
531551
+			return i;
531551
+	}
531551
+	warnx(_("unknown column: %s"), name);
531551
+	return -1;
531551
+}
531551
+
531551
+static void zram_reset_stat(struct zram *z)
531551
+{
531551
+	if (z) {
531551
+		strv_free(z->mm_stat);
531551
+		z->mm_stat = NULL;
531551
+		z->mm_stat_probed = 0;
531551
+	}
531551
+}
531551
+
531551
+static void zram_set_devname(struct zram *z, const char *devname, size_t n)
531551
+{
531551
+	assert(z);
531551
+
531551
+	if (!devname)
531551
+		snprintf(z->devname, sizeof(z->devname), "/dev/zram%zu", n);
531551
+	else {
531551
+		strncpy(z->devname, devname, sizeof(z->devname));
531551
+		z->devname[sizeof(z->devname) - 1] = '\0';
531551
+	}
531551
+
531551
+	DBG(fprintf(stderr, "set devname: %s", z->devname));
531551
+	sysfs_deinit(&z->sysfs);
531551
+	zram_reset_stat(z);
531551
+}
531551
+
531551
+static int zram_get_devnum(struct zram *z)
531551
+{
531551
+	int n;
531551
+
531551
+	assert(z);
531551
+
531551
+	if (sscanf(z->devname, "/dev/zram%d", &n) == 1)
531551
+		return n;
531551
+	return -EINVAL;
531551
+}
531551
+
531551
+static struct zram *new_zram(const char *devname)
531551
+{
531551
+	struct zram *z = xcalloc(1, sizeof(struct zram));
531551
+
531551
+	DBG(fprintf(stderr, "new: %p", z));
531551
+	if (devname)
531551
+		zram_set_devname(z, devname, 0);
531551
+	return z;
531551
+}
531551
+
531551
+static void free_zram(struct zram *z)
531551
+{
531551
+	if (!z)
531551
+		return;
531551
+	DBG(fprintf(stderr, "free: %p", z));
531551
+	sysfs_deinit(&z->sysfs);
531551
+	zram_reset_stat(z);
531551
+	free(z);
531551
+}
531551
+
531551
+static struct sysfs_cxt *zram_get_sysfs(struct zram *z)
531551
+{
531551
+	assert(z);
531551
+
531551
+	if (!z->sysfs.devno) {
531551
+		dev_t devno = sysfs_devname_to_devno(z->devname, NULL);
531551
+		if (!devno)
531551
+			return NULL;
531551
+		if (sysfs_init(&z->sysfs, devno, NULL))
531551
+			return NULL;
531551
+		if (*z->devname != '/') {
531551
+			/* canonicalize the device name according to /sys */
531551
+			char name[PATH_MAX];
531551
+			if (sysfs_get_devname(&z->sysfs, name, sizeof(name)))
531551
+				snprintf(z->devname, sizeof(z->devname), "/dev/%s", name);
531551
+		}
531551
+	}
531551
+
531551
+	return &z->sysfs;
531551
+}
531551
+
531551
+static inline int zram_exist(struct zram *z)
531551
+{
531551
+	assert(z);
531551
+
531551
+	errno = 0;
531551
+	if (zram_get_sysfs(z) == NULL) {
531551
+		errno = ENODEV;
531551
+		return 0;
531551
+	}
531551
+
531551
+	DBG(fprintf(stderr, "%s exists", z->devname));
531551
+	return 1;
531551
+}
531551
+
531551
+static int zram_set_u64parm(struct zram *z, const char *attr, uint64_t num)
531551
+{
531551
+	struct sysfs_cxt *sysfs = zram_get_sysfs(z);
531551
+	if (!sysfs)
531551
+		return -EINVAL;
531551
+	DBG(fprintf(stderr, "%s writing %ju to %s", z->devname, num, attr));
531551
+	return sysfs_write_u64(sysfs, attr, num);
531551
+}
531551
+
531551
+static int zram_set_strparm(struct zram *z, const char *attr, const char *str)
531551
+{
531551
+	struct sysfs_cxt *sysfs = zram_get_sysfs(z);
531551
+	if (!sysfs)
531551
+		return -EINVAL;
531551
+	DBG(fprintf(stderr, "%s writing %s to %s", z->devname, str, attr));
531551
+	return sysfs_write_string(sysfs, attr, str);
531551
+}
531551
+
531551
+
531551
+static int zram_used(struct zram *z)
531551
+{
531551
+	uint64_t size;
531551
+	struct sysfs_cxt *sysfs = zram_get_sysfs(z);
531551
+
531551
+	if (sysfs &&
531551
+	    sysfs_read_u64(sysfs, "disksize", &size) == 0 &&
531551
+	    size > 0) {
531551
+
531551
+		DBG(fprintf(stderr, "%s used", z->devname));
531551
+		return 1;
531551
+	}
531551
+	DBG(fprintf(stderr, "%s unused", z->devname));
531551
+	return 0;
531551
+}
531551
+
531551
+static int zram_has_control(struct zram *z)
531551
+{
531551
+	if (!z->control_probed) {
531551
+		z->has_control = access(_PATH_SYS_CLASS "/zram-control/", F_OK) == 0 ? 1 : 0;
531551
+		z->control_probed = 1;
531551
+		DBG(fprintf(stderr, "zram-control: %s", z->has_control ? "yes" : "no"));
531551
+	}
531551
+
531551
+	return z->has_control;
531551
+}
531551
+
531551
+static int zram_control_add(struct zram *z)
531551
+{
531551
+	int n;
531551
+
531551
+	if (!zram_has_control(z))
531551
+		return -ENOSYS;
531551
+
531551
+	n = path_read_s32(_PATH_SYS_CLASS "/zram-control/hot_add");
531551
+	if (n < 0)
531551
+		return n;
531551
+
531551
+	DBG(fprintf(stderr, "hot-add: %d", n));
531551
+	zram_set_devname(z, NULL, n);
531551
+	return 0;
531551
+}
531551
+
531551
+static int zram_control_remove(struct zram *z)
531551
+{
531551
+	char str[sizeof stringify_value(INT_MAX)];
531551
+	int n;
531551
+
531551
+	if (!zram_has_control(z))
531551
+		return -ENOSYS;
531551
+
531551
+	n = zram_get_devnum(z);
531551
+	if (n < 0)
531551
+		return n;
531551
+
531551
+	DBG(fprintf(stderr, "hot-remove: %d", n));
531551
+	snprintf(str, sizeof(str), "%d", n);
531551
+	return path_write_str(str, _PATH_SYS_CLASS "/zram-control/hot_remove");
531551
+}
531551
+
531551
+static struct zram *find_free_zram(void)
531551
+{
531551
+	struct zram *z = new_zram(NULL);
531551
+	size_t i;
531551
+	int isfree = 0;
531551
+
531551
+	for (i = 0; isfree == 0; i++) {
531551
+		DBG(fprintf(stderr, "find free: checking zram%zu", i));
531551
+		zram_set_devname(z, NULL, i);
531551
+		if (!zram_exist(z) && zram_control_add(z) != 0)
531551
+			break;
531551
+		isfree = !zram_used(z);
531551
+	}
531551
+	if (!isfree) {
531551
+		free_zram(z);
531551
+		z = NULL;
531551
+	}
531551
+	return z;
531551
+}
531551
+
531551
+static char *get_mm_stat(struct zram *z, size_t idx, int bytes)
531551
+{
531551
+	struct sysfs_cxt *sysfs;
531551
+	const char *name;
531551
+	uint64_t num;
531551
+
531551
+	assert(idx < ARRAY_SIZE(mm_stat_names));
531551
+	assert(z);
531551
+
531551
+	sysfs = zram_get_sysfs(z);
531551
+	if (!sysfs)
531551
+		return NULL;
531551
+
531551
+	/* Linux >= 4.1 uses /sys/block/zram<id>/mm_stat */
531551
+	if (!z->mm_stat && !z->mm_stat_probed) {
531551
+		char *str;
531551
+
531551
+		str = sysfs_strdup(sysfs, "mm_stat");
531551
+		if (str) {
531551
+			z->mm_stat = strv_split(str, " ");
531551
+			if (strv_length(z->mm_stat) < ARRAY_SIZE(mm_stat_names))
531551
+				errx(EXIT_FAILURE, _("Failed to parse mm_stat"));
531551
+		}
531551
+		z->mm_stat_probed = 1;
531551
+		free(str);
531551
+
531551
+	}
531551
+
531551
+	if (z->mm_stat) {
531551
+		if (bytes)
531551
+			return xstrdup(z->mm_stat[idx]);
531551
+
531551
+		num = strtou64_or_err(z->mm_stat[idx], _("Failed to parse mm_stat"));
531551
+		return size_to_human_string(SIZE_SUFFIX_1LETTER, num);
531551
+	}
531551
+
531551
+	/* Linux < 4.1 uses /sys/block/zram<id>/<attrname> */
531551
+	name = mm_stat_names[idx];
531551
+	if (bytes)
531551
+		return sysfs_strdup(sysfs, name);
531551
+	else if (sysfs_read_u64(sysfs, name, &num) == 0)
531551
+		return size_to_human_string(SIZE_SUFFIX_1LETTER, num);
531551
+	return NULL;
531551
+}
531551
+
531551
+static void fill_table_row(struct libscols_table *tb, struct zram *z)
531551
+{
531551
+	static struct libscols_line *ln;
531551
+	struct sysfs_cxt *sysfs;
531551
+	size_t i;
531551
+	uint64_t num;
531551
+
531551
+	assert(tb);
531551
+	assert(z);
531551
+
531551
+	DBG(fprintf(stderr, "%s: filling status table", z->devname));
531551
+
531551
+	sysfs = zram_get_sysfs(z);
531551
+	if (!sysfs)
531551
+		return;
531551
+
531551
+	ln = scols_table_new_line(tb, NULL);
531551
+	if (!ln)
531551
+		err(EXIT_FAILURE, _("failed to initialize output line"));
531551
+
531551
+	for (i = 0; i < (size_t) ncolumns; i++) {
531551
+		char *str = NULL;
531551
+
531551
+		switch (get_column_id(i)) {
531551
+		case COL_NAME:
531551
+			str = xstrdup(z->devname);
531551
+			break;
531551
+		case COL_DISKSIZE:
531551
+			if (inbytes)
531551
+				str = sysfs_strdup(sysfs, "disksize");
531551
+			else if (sysfs_read_u64(sysfs, "disksize", &num) == 0)
531551
+				str = size_to_human_string(SIZE_SUFFIX_1LETTER, num);
531551
+			break;
531551
+		case COL_ALGORITHM:
531551
+		{
531551
+			char *alg = sysfs_strdup(sysfs, "comp_algorithm");
531551
+			if (!alg)
531551
+				break;
531551
+			if (strstr(alg, "[lzo]") == NULL) {
531551
+				if (strstr(alg, "[lz4]") == NULL)
531551
+					;
531551
+				else
531551
+					str = xstrdup("lz4");
531551
+			} else
531551
+				str = xstrdup("lzo");
531551
+			free(alg);
531551
+			break;
531551
+		}
531551
+		case COL_MOUNTPOINT:
531551
+		{
531551
+			char path[PATH_MAX] = { '\0' };
531551
+			int fl;
531551
+
531551
+			check_mount_point(z->devname, &fl, path, sizeof(path));
531551
+			if (*path)
531551
+				str = xstrdup(path);
531551
+			break;
531551
+		}
531551
+		case COL_STREAMS:
531551
+			str = sysfs_strdup(sysfs, "max_comp_streams");
531551
+			break;
531551
+		case COL_ZEROPAGES:
531551
+			str = get_mm_stat(z, MM_ZERO_PAGES, 1);
531551
+			break;
531551
+		case COL_ORIG_SIZE:
531551
+			str = get_mm_stat(z, MM_ORIG_DATA_SIZE, inbytes);
531551
+			break;
531551
+		case COL_COMP_SIZE:
531551
+			str = get_mm_stat(z, MM_COMPR_DATA_SIZE, inbytes);
531551
+			break;
531551
+		case COL_MEMTOTAL:
531551
+			str = get_mm_stat(z, MM_MEM_USED_TOTAL, inbytes);
531551
+			break;
531551
+		case COL_MEMLIMIT:
531551
+			str = get_mm_stat(z, MM_MEM_LIMIT, inbytes);
531551
+			break;
531551
+		case COL_MEMUSED:
531551
+			str = get_mm_stat(z, MM_MEM_USED_MAX, inbytes);
531551
+			break;
531551
+		case COL_MIGRATED:
531551
+			str = get_mm_stat(z, MM_NUM_MIGRATED, inbytes);
531551
+			break;
531551
+		}
531551
+		if (str)
531551
+			scols_line_refer_data(ln, i, str);
531551
+	}
531551
+}
531551
+
531551
+static void status(struct zram *z)
531551
+{
531551
+	struct libscols_table *tb;
531551
+	size_t i;
531551
+
531551
+	scols_init_debug(0);
531551
+
531551
+	tb = scols_new_table();
531551
+	if (!tb)
531551
+		err(EXIT_FAILURE, _("failed to initialize output table"));
531551
+
531551
+	scols_table_enable_raw(tb, raw);
531551
+	scols_table_enable_noheadings(tb, no_headings);
531551
+
531551
+	for (i = 0; i < (size_t) ncolumns; i++) {
531551
+		const struct colinfo *col = get_column_info(i);
531551
+
531551
+		if (!scols_table_new_column(tb, col->name, col->whint, col->flags))
531551
+			err(EXIT_FAILURE, _("failed to initialize output column"));
531551
+	}
531551
+
531551
+	if (z)
531551
+		fill_table_row(tb, z);		/* just one device specified */
531551
+	else {
531551
+		/* list all used devices */
531551
+		z = new_zram(NULL);
531551
+
531551
+		for (i = 0; ; i++) {
531551
+			zram_set_devname(z, NULL, i);
531551
+			if (!zram_exist(z))
531551
+				break;
531551
+			if (zram_used(z))
531551
+				fill_table_row(tb, z);
531551
+		}
531551
+		free_zram(z);
531551
+	}
531551
+
531551
+	scols_print_table(tb);
531551
+	scols_unref_table(tb);
531551
+}
531551
+
531551
+static void __attribute__ ((__noreturn__)) usage(FILE * out)
531551
+{
531551
+	size_t i;
531551
+
531551
+	fputs(USAGE_HEADER, out);
531551
+	fprintf(out, _(	" %1$s [options] <device>\n"
531551
+			" %1$s -r <device> [...]\n"
531551
+			" %1$s [options] -f | <device> -s <size>\n"),
531551
+			program_invocation_short_name);
531551
+
531551
+	fputs(USAGE_SEPARATOR, out);
531551
+	fputs(_("Set up and control zram devices.\n"), out);
531551
+
531551
+	fputs(USAGE_OPTIONS, out);
531551
+	fputs(_(" -a, --algorithm lzo|lz4   compression algorithm to use\n"), out);
531551
+	fputs(_(" -b, --bytes               print sizes in bytes rather than in human readable format\n"), out);
531551
+	fputs(_(" -f, --find                find a free device\n"), out);
531551
+	fputs(_(" -n, --noheadings          don't print headings\n"), out);
531551
+	fputs(_(" -o, --output <list>       columns to use for status output\n"), out);
531551
+	fputs(_("     --raw                 use raw status output format\n"), out);
531551
+	fputs(_(" -r, --reset               reset all specified devices\n"), out);
531551
+	fputs(_(" -s, --size <size>         device size\n"), out);
531551
+	fputs(_(" -t, --streams <number>    number of compression streams\n"), out);
531551
+
531551
+	fputs(USAGE_SEPARATOR, out);
531551
+	fputs(USAGE_HELP, out);
531551
+	fputs(USAGE_VERSION, out);
531551
+
531551
+	fputs(_("\nAvailable columns (for --output):\n"), out);
531551
+	for (i = 0; i < ARRAY_SIZE(infos); i++)
531551
+		fprintf(out, " %11s  %s\n", infos[i].name, _(infos[i].help));
531551
+
531551
+	fprintf(out, USAGE_MAN_TAIL("zramctl(8)"));
531551
+	exit(out == stderr ? 1 : EXIT_SUCCESS);
531551
+}
531551
+
531551
+/* actions */
531551
+enum {
531551
+	A_NONE = 0,
531551
+	A_STATUS,
531551
+	A_CREATE,
531551
+	A_FINDONLY,
531551
+	A_RESET
531551
+};
531551
+
531551
+int main(int argc, char **argv)
531551
+{
531551
+	uintmax_t size = 0, nstreams = 0;
531551
+	char *algorithm = NULL;
531551
+	int rc = 0, c, find = 0, act = A_NONE;
531551
+	struct zram *zram = NULL;
531551
+
531551
+	enum { OPT_RAW = CHAR_MAX + 1 };
531551
+
531551
+	static const struct option longopts[] = {
531551
+		{ "algorithm", required_argument, NULL, 'a' },
531551
+		{ "bytes",     no_argument, NULL, 'b' },
531551
+		{ "find",      no_argument, NULL, 'f' },
531551
+		{ "help",      no_argument, NULL, 'h' },
531551
+		{ "output",    required_argument, NULL, 'o' },
531551
+		{ "noheadings",no_argument, NULL, 'n' },
531551
+		{ "reset",     no_argument, NULL, 'r' },
531551
+		{ "raw",       no_argument, NULL, OPT_RAW },
531551
+		{ "size",      required_argument, NULL, 's' },
531551
+		{ "streams",   required_argument, NULL, 't' },
531551
+		{ "version",   no_argument, NULL, 'V' },
531551
+		{ NULL, 0, NULL, 0 }
531551
+	};
531551
+
531551
+	static const ul_excl_t excl[] = {
531551
+		{ 'f', 'o', 'r' },
531551
+		{ 'o', 'r', 's' },
531551
+		{ 0 }
531551
+	};
531551
+	int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
531551
+
531551
+	setlocale(LC_ALL, "");
531551
+	bindtextdomain(PACKAGE, LOCALEDIR);
531551
+	textdomain(PACKAGE);
531551
+	atexit(close_stdout);
531551
+
531551
+	while ((c = getopt_long(argc, argv, "a:bfho:nrs:t:V", longopts, NULL)) != -1) {
531551
+
531551
+		err_exclusive_options(c, longopts, excl, excl_st);
531551
+
531551
+		switch (c) {
531551
+		case 'a':
531551
+			if (strcmp(optarg,"lzo") && strcmp(optarg,"lz4"))
531551
+				errx(EXIT_FAILURE, _("unsupported algorithm: %s"),
531551
+					     optarg);
531551
+			algorithm = optarg;
531551
+			break;
531551
+		case 'b':
531551
+			inbytes = 1;
531551
+			break;
531551
+		case 'f':
531551
+			find = 1;
531551
+			break;
531551
+		case 'o':
531551
+			ncolumns = string_to_idarray(optarg,
531551
+						     columns, ARRAY_SIZE(columns),
531551
+						     column_name_to_id);
531551
+			if (ncolumns < 0)
531551
+				return EXIT_FAILURE;
531551
+			break;
531551
+		case 's':
531551
+			size = strtosize_or_err(optarg, _("failed to parse size"));
531551
+			act = A_CREATE;
531551
+			break;
531551
+		case 't':
531551
+			nstreams = strtou64_or_err(optarg, _("failed to parse streams"));
531551
+			break;
531551
+		case 'r':
531551
+			act = A_RESET;
531551
+			break;
531551
+		case OPT_RAW:
531551
+			raw = 1;
531551
+			break;
531551
+		case 'n':
531551
+			no_headings = 1;
531551
+			break;
531551
+		case 'V':
531551
+			printf(UTIL_LINUX_VERSION);
531551
+			return EXIT_SUCCESS;
531551
+		case 'h':
531551
+			usage(stdout);
531551
+		default:
531551
+			usage(stderr);
531551
+		}
531551
+	}
531551
+
531551
+	if (find && optind < argc)
531551
+		errx(EXIT_FAILURE, _("option --find is mutually exclusive "
531551
+				     "with <device>"));
531551
+	if (act == A_NONE)
531551
+		act = find ? A_FINDONLY : A_STATUS;
531551
+
531551
+	if (act != A_RESET && optind + 1 < argc)
531551
+		errx(EXIT_FAILURE, _("only one <device> at a time is allowed"));
531551
+
531551
+	if ((act == A_STATUS || act == A_FINDONLY) && (algorithm || nstreams))
531551
+		errx(EXIT_FAILURE, _("options --algorithm and --streams "
531551
+				     "must be combined with --size"));
531551
+
531551
+	switch (act) {
531551
+	case A_STATUS:
531551
+		if (!ncolumns) {		/* default columns */
531551
+			columns[ncolumns++] = COL_NAME;
531551
+			columns[ncolumns++] = COL_ALGORITHM;
531551
+			columns[ncolumns++] = COL_DISKSIZE;
531551
+			columns[ncolumns++] = COL_ORIG_SIZE;
531551
+			columns[ncolumns++] = COL_COMP_SIZE;
531551
+			columns[ncolumns++] = COL_MEMTOTAL;
531551
+			columns[ncolumns++] = COL_STREAMS;
531551
+			columns[ncolumns++] = COL_MOUNTPOINT;
531551
+		}
531551
+		if (optind < argc) {
531551
+			zram = new_zram(argv[optind++]);
531551
+			if (!zram_exist(zram))
531551
+				err(EXIT_FAILURE, "%s", zram->devname);
531551
+		}
531551
+		status(zram);
531551
+		free_zram(zram);
531551
+		break;
531551
+	case A_RESET:
531551
+		if (optind == argc)
531551
+			errx(EXIT_FAILURE, _("no device specified"));
531551
+		while (optind < argc) {
531551
+			zram = new_zram(argv[optind]);
531551
+			if (!zram_exist(zram)
531551
+			    || zram_set_u64parm(zram, "reset", 1)) {
531551
+				warn(_("%s: failed to reset"), zram->devname);
531551
+				rc = 1;
531551
+			}
531551
+			zram_control_remove(zram);
531551
+			free_zram(zram);
531551
+			optind++;
531551
+		}
531551
+		break;
531551
+	case A_FINDONLY:
531551
+		zram = find_free_zram();
531551
+		if (!zram)
531551
+			errx(EXIT_FAILURE, _("no free zram device found"));
531551
+		printf("%s\n", zram->devname);
531551
+		free_zram(zram);
531551
+		break;
531551
+	case A_CREATE:
531551
+		if (find) {
531551
+			zram = find_free_zram();
531551
+			if (!zram)
531551
+				errx(EXIT_FAILURE, _("no free zram device found"));
531551
+		} else if (optind == argc)
531551
+			errx(EXIT_FAILURE, _("no device specified"));
531551
+		else {
531551
+			zram = new_zram(argv[optind]);
531551
+			if (!zram_exist(zram))
531551
+				err(EXIT_FAILURE, "%s", zram->devname);
531551
+		}
531551
+
531551
+		if (zram_set_u64parm(zram, "reset", 1))
531551
+			err(EXIT_FAILURE, _("%s: failed to reset"), zram->devname);
531551
+
531551
+		if (nstreams &&
531551
+		    zram_set_u64parm(zram, "max_comp_streams", nstreams))
531551
+			err(EXIT_FAILURE, _("%s: failed to set number of streams"), zram->devname);
531551
+
531551
+		if (algorithm &&
531551
+		    zram_set_strparm(zram, "comp_algorithm", algorithm))
531551
+			err(EXIT_FAILURE, _("%s: failed to set algorithm"), zram->devname);
531551
+
531551
+		if (zram_set_u64parm(zram, "disksize", size))
531551
+			err(EXIT_FAILURE, _("%s: failed to set disksize (%ju bytes)"),
531551
+				zram->devname, size);
531551
+		if (find)
531551
+			printf("%s\n", zram->devname);
531551
+		free_zram(zram);
531551
+		break;
531551
+	}
531551
+
531551
+	return rc ? EXIT_FAILURE : EXIT_SUCCESS;
531551
+}
531551
-- 
531551
2.9.3
531551