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