Blob Blame History Raw
From 4fde7a853f61fa025a9d42a7571161a69fdae162 Mon Sep 17 00:00:00 2001
From: Karel Zak <kzak@redhat.com>
Date: Mon, 23 Oct 2017 15:54:54 +0200
Subject: [PATCH] lsmem, chmem: backport new commands

Addresses: https://bugzilla.redhat.com/show_bug.cgi?id=1496421
Signed-off-by: Karel Zak <kzak@redhat.com>
---
 configure.ac            |  19 ++
 include/c.h             |  10 +
 include/path.h          |   5 +-
 include/strutils.h      |   1 +
 lib/path.c              |  36 ++-
 lib/strutils.c          |  17 +-
 sys-utils/Makemodule.am |  14 +
 sys-utils/chmem.8       | 114 ++++++++
 sys-utils/chmem.c       | 447 +++++++++++++++++++++++++++++++
 sys-utils/lsmem.1       |  95 +++++++
 sys-utils/lsmem.c       | 687 ++++++++++++++++++++++++++++++++++++++++++++++++
 11 files changed, 1432 insertions(+), 13 deletions(-)
 create mode 100644 sys-utils/chmem.8
 create mode 100644 sys-utils/chmem.c
 create mode 100644 sys-utils/lsmem.1
 create mode 100644 sys-utils/lsmem.c

diff --git a/configure.ac b/configure.ac
index 96c5838cf..d561e01d0 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1138,6 +1138,25 @@ UL_REQUIRES_SYSCALL_CHECK([pivot_root], [UL_CHECK_SYSCALL([pivot_root])])
 AM_CONDITIONAL(BUILD_PIVOT_ROOT, test "x$build_pivot_root" = xyes)
 
 
+AC_ARG_ENABLE([lsmem],
+  AS_HELP_STRING([--disable-lsmem], [do not build lsmem]),
+  [], enable_lsmem=check
+)
+UL_BUILD_INIT([lsmem])
+UL_REQUIRES_LINUX([lsmem])
+UL_REQUIRES_BUILD([lsmem], [libsmartcols])
+AM_CONDITIONAL([BUILD_LSMEM], [test "x$build_lsmem" = xyes])
+
+
+AC_ARG_ENABLE([chmem],
+  AS_HELP_STRING([--disable-chmem], [do not build chmem]),
+  [], enable_chmem=check
+)
+UL_BUILD_INIT([chmem])
+UL_REQUIRES_LINUX([chmem])
+AM_CONDITIONAL([BUILD_CHMEM], [test "x$build_chmem" = xyes])
+
+
 AC_ARG_ENABLE([elvtune],
   AS_HELP_STRING([--enable-elvtune], [build elvtune (only works with 2.2 and 2.4 kernels)]),
   [], enable_elvtune=no
diff --git a/include/c.h b/include/c.h
index 8ff61b484..124035ea5 100644
--- a/include/c.h
+++ b/include/c.h
@@ -302,6 +302,16 @@ static inline int usleep(useconds_t usec)
 
 #define UTIL_LINUX_VERSION _("%s from %s\n"), program_invocation_short_name, PACKAGE_STRING
 
+/* backported to RHEL */
+#define USAGE_COLUMNS    _("\nAvailable output columns:\n")
+#define USAGE_OPTSTR_HELP     _("display this help")
+#define USAGE_OPTSTR_VERSION  _("display version")
+#define USAGE_HELP_OPTIONS(marg_dsc) \
+		"%-" #marg_dsc "s%s\n" \
+		"%-" #marg_dsc "s%s\n" \
+		, " -h, --help",    USAGE_OPTSTR_HELP \
+		, " -V, --version", USAGE_OPTSTR_VERSION
+
 /*
  * scanf modifiers for "strings allocation"
  */
diff --git a/include/path.h b/include/path.h
index 45da692f8..1ab5724fc 100644
--- a/include/path.h
+++ b/include/path.h
@@ -4,6 +4,10 @@
 #include <stdio.h>
 #include <stdint.h>
 
+extern int path_set_prefix(const char *);
+
+extern const char *path_get(const char *path, ...);
+
 extern char *path_strdup(const char *path, ...)
 			__attribute__ ((__format__ (__printf__, 1, 2)));
 extern FILE *path_fopen(const char *mode, int exit_on_err, const char *path, ...)
@@ -27,7 +31,6 @@ extern cpu_set_t *path_read_cpuset(int, const char *path, ...)
 			      __attribute__ ((__format__ (__printf__, 2, 3)));
 extern cpu_set_t *path_read_cpulist(int, const char *path, ...)
 			       __attribute__ ((__format__ (__printf__, 2, 3)));
-extern void path_set_prefix(const char *);
 #endif /* HAVE_CPU_SET_T */
 
 #endif /* UTIL_LINUX_PATH_H */
diff --git a/include/strutils.h b/include/strutils.h
index aa7b95f96..1f028e4ed 100644
--- a/include/strutils.h
+++ b/include/strutils.h
@@ -25,6 +25,7 @@ extern uint32_t strtou32_or_err(const char *str, const char *errmesg);
 
 extern int64_t strtos64_or_err(const char *str, const char *errmesg);
 extern uint64_t strtou64_or_err(const char *str, const char *errmesg);
+extern uint64_t strtox64_or_err(const char *str, const char *errmesg);
 
 extern double strtod_or_err(const char *str, const char *errmesg);
 
diff --git a/lib/path.c b/lib/path.c
index e47d31418..49ca9b5e0 100644
--- a/lib/path.c
+++ b/lib/path.c
@@ -38,6 +38,20 @@
 static size_t prefixlen;
 static char pathbuf[PATH_MAX];
 
+int
+path_set_prefix(const char *prefix)
+{
+	size_t len = strlen(prefix);
+
+	if (len >= sizeof(pathbuf) - 1) {
+		errno = ENAMETOOLONG;
+		return -1;
+	}
+	prefixlen = len;
+	strcpy(pathbuf, prefix);
+	return 0;
+}
+
 static const char *
 path_vcreate(const char *path, va_list ap)
 {
@@ -49,6 +63,19 @@ path_vcreate(const char *path, va_list ap)
 	return pathbuf;
 }
 
+const char *
+path_get(const char *path, ...)
+{
+	const char *p;
+	va_list ap;
+
+	va_start(ap, path);
+	p = path_vcreate(path, ap);
+	va_end(ap);
+
+	return p;
+}
+
 char *
 path_strdup(const char *path, ...)
 {
@@ -246,13 +273,6 @@ path_read_cpulist(int maxcpus, const char *path, ...)
 
 	return set;
 }
-
 #endif /* HAVE_CPU_SET_T */
 
-void
-path_set_prefix(const char *prefix)
-{
-	prefixlen = strlen(prefix);
-	strncpy(pathbuf, prefix, sizeof(pathbuf));
-	pathbuf[sizeof(pathbuf) - 1] = '\0';
-}
+
diff --git a/lib/strutils.c b/lib/strutils.c
index 4b8a8130d..2458a2c2f 100644
--- a/lib/strutils.c
+++ b/lib/strutils.c
@@ -237,27 +237,36 @@ err:
 	errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
 }
 
-uint64_t strtou64_or_err(const char *str, const char *errmesg)
+static uint64_t _strtou64_or_err(const char *str, const char *errmesg, int base)
 {
 	uintmax_t num;
 	char *end = NULL;
 
+	errno = 0;
 	if (str == NULL || *str == '\0')
 		goto err;
-	errno = 0;
-	num = strtoumax(str, &end, 10);
+	num = strtoumax(str, &end, base);
 
 	if (errno || str == end || (end && *end))
 		goto err;
 
 	return num;
 err:
-	if (errno)
+	if (errno == ERANGE)
 		err(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
 
 	errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
 }
 
+uint64_t strtou64_or_err(const char *str, const char *errmesg)
+{
+	return _strtou64_or_err(str, errmesg, 10);
+}
+
+uint64_t strtox64_or_err(const char *str, const char *errmesg)
+{
+	return _strtou64_or_err(str, errmesg, 16);
+}
 
 double strtod_or_err(const char *str, const char *errmesg)
 {
diff --git a/sys-utils/Makemodule.am b/sys-utils/Makemodule.am
index 0496b84e3..21585ce80 100644
--- a/sys-utils/Makemodule.am
+++ b/sys-utils/Makemodule.am
@@ -1,3 +1,17 @@
+if BUILD_LSMEM
+usrbin_exec_PROGRAMS += lsmem
+dist_man_MANS += sys-utils/lsmem.1
+lsmem_SOURCES = sys-utils/lsmem.c
+lsmem_LDADD = $(LDADD) libcommon.la libsmartcols.la
+lsmem_CFLAGS = $(AM_CFLAGS) -I$(ul_libsmartcols_incdir)
+endif
+
+if BUILD_CHMEM
+usrbin_exec_PROGRAMS += chmem
+dist_man_MANS += sys-utils/chmem.8
+chmem_SOURCES = sys-utils/chmem.c
+chmem_LDADD = $(LDADD) libcommon.la
+endif
 
 usrbin_exec_PROGRAMS += flock
 dist_man_MANS += sys-utils/flock.1
diff --git a/sys-utils/chmem.8 b/sys-utils/chmem.8
new file mode 100644
index 000000000..dae7413d4
--- /dev/null
+++ b/sys-utils/chmem.8
@@ -0,0 +1,114 @@
+.TH CHMEM 8 "October 2016" "util-linux" "System Administration"
+.SH NAME
+chmem \- configure memory
+.SH SYNOPSIS
+.B chmem
+.RB [ \-h "] [" \-V "] [" \-v "] [" \-e | \-d "]"
+[\fISIZE\fP|\fIRANGE\fP|\fB\-b\fP \fIBLOCKRANGE\fP]
+[-z ZONE]
+.SH DESCRIPTION
+The chmem command sets a particular size or range of memory online or offline.
+.
+.IP "\(hy" 2
+Specify \fISIZE\fP as <size>[m|M|g|G]. With m or M, <size> specifies the memory
+size in MiB (1024 x 1024 bytes). With g or G, <size> specifies the memory size
+in GiB (1024 x 1024 x 1024 bytes). The default unit is MiB.
+.
+.IP "\(hy" 2
+Specify \fIRANGE\fP in the form 0x<start>-0x<end> as shown in the output of the
+\fBlsmem\fP command. <start> is the hexadecimal address of the first byte and <end>
+is the hexadecimal address of the last byte in the memory range.
+.
+.IP "\(hy" 2
+Specify \fIBLOCKRANGE\fP in the form <first>-<last> or <block> as shown in the
+output of the \fBlsmem\fP command. <first> is the number of the first memory block
+and <last> is the number of the last memory block in the memory
+range. Alternatively a single block can be specified. \fIBLOCKRANGE\fP requires
+the \fB--blocks\fP option.
+.
+.IP "\(hy" 2
+Specify \fIZONE\fP as the name of a memory zone, as shown in the output of the
+\fBlsmem -o +ZONES\fP command. The output shows one or more valid memory zones
+for each memory range. If multiple zones are shown, then the memory range
+currently belongs to the first zone. By default, chmem will set memory online
+to the zone Movable, if this is among the valid zones. This default can be
+changed by specifying the \fB--zone\fP option with another valid zone.
+For memory ballooning, it is recommended to select the zone Movable for memory
+online and offline, if possible. Memory in this zone is much more likely to be
+able to be offlined again, but it cannot be used for arbitrary kernel
+allocations, only for migratable pages (e.g. anonymous and page cache pages).
+Use the \fB\-\-help\fR option to see all available zones.
+.
+.PP
+\fISIZE\fP and \fIRANGE\fP must be aligned to the Linux memory block size, as
+shown in the output of the \fBlsmem\fP command.
+
+Setting memory online can fail for various reasons. On virtualized systems it
+can fail if the hypervisor does not have enough memory left, for example
+because memory was overcommitted. Setting memory offline can fail if Linux
+cannot free the memory. If only part of the requested memory can be set online
+or offline, a message tells you how much memory was set online or offline
+instead of the requested amount.
+
+When setting memory online \fBchmem\fP starts with the lowest memory block
+numbers. When setting memory offline \fBchmem\fP starts with the highest memory
+block numbers.
+.SH OPTIONS
+.TP
+.BR \-b ", " \-\-blocks
+Use a \fIBLOCKRANGE\fP parameter instead of \fIRANGE\fP or \fISIZE\fP for the
+\fB--enable\fP and \fB--disable\fP options.
+.TP
+.BR \-d ", " \-\-disable
+Set the specified \fIRANGE\fP, \fISIZE\fP, or \fIBLOCKRANGE\fP of memory offline.
+.TP
+.BR \-e ", " \-\-enable
+Set the specified \fIRANGE\fP, \fISIZE\fP, or \fIBLOCKRANGE\fP of memory online.
+.TP
+.BR \-z ", " \-\-zone
+Select the memory \fIZONE\fP where to set the specified \fIRANGE\fP, \fISIZE\fP,
+or \fIBLOCKRANGE\fP of memory online or offline. By default, memory will be set
+online to the zone Movable, if possible.
+.TP
+.BR \-h ", " \-\-help
+Print a short help text, then exit.
+.TP
+.BR \-v ", " \-\-verbose
+Verbose mode. Causes \fBchmem\fP to print debugging messages about it's
+progress.
+.TP
+.BR \-V ", " \-\-version
+Print the version number, then exit.
+.SH RETURN CODES
+.B chmem
+has the following return codes:
+.TP
+.BR 0
+success
+.TP
+.BR 1
+failure
+.TP
+.BR 64
+partial success
+.SH EXAMPLES
+.TP
+.B chmem --enable 1024
+This command requests 1024 MiB of memory to be set online.
+.TP
+.B chmem -e 2g
+This command requests 2 GiB of memory to be set online.
+.TP
+.B chmem --disable 0x00000000e4000000-0x00000000f3ffffff
+This command requests the memory range starting with 0x00000000e4000000
+and ending with 0x00000000f3ffffff to be set offline.
+.TP
+.B chmem -b -d 10
+This command requests the memory block number 10 to be set offline.
+.SH SEE ALSO
+.BR lsmem (1)
+.SH AVAILABILITY
+The \fBchmem\fP command is part of the util-linux package and is available from
+.UR https://\:www.kernel.org\:/pub\:/linux\:/utils\:/util-linux/
+Linux Kernel Archive
+.UE .
diff --git a/sys-utils/chmem.c b/sys-utils/chmem.c
new file mode 100644
index 000000000..0e5e84727
--- /dev/null
+++ b/sys-utils/chmem.c
@@ -0,0 +1,447 @@
+/*
+ * chmem - Memory configuration tool
+ *
+ * Copyright IBM Corp. 2016
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it would be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <getopt.h>
+#include <assert.h>
+#include <dirent.h>
+#include <ctype.h>
+
+#include "c.h"
+#include "nls.h"
+#include "path.h"
+#include "strutils.h"
+#include "strv.h"
+#include "optutils.h"
+#include "closestream.h"
+#include "xalloc.h"
+
+/* partial success, otherwise we return regular EXIT_{SUCCESS,FAILURE} */
+#define CHMEM_EXIT_SOMEOK		64
+
+#define _PATH_SYS_MEMORY		"/sys/devices/system/memory"
+#define _PATH_SYS_MEMORY_BLOCK_SIZE	_PATH_SYS_MEMORY "/block_size_bytes"
+
+struct chmem_desc {
+	struct dirent	**dirs;
+	int		ndirs;
+	uint64_t	block_size;
+	uint64_t	start;
+	uint64_t	end;
+	uint64_t	size;
+	unsigned int	use_blocks : 1;
+	unsigned int	is_size	   : 1;
+	unsigned int	verbose	   : 1;
+	unsigned int	have_zones : 1;
+};
+
+enum {
+	CMD_MEMORY_ENABLE = 0,
+	CMD_MEMORY_DISABLE,
+	CMD_NONE
+};
+
+enum zone_id {
+	ZONE_DMA = 0,
+	ZONE_DMA32,
+	ZONE_NORMAL,
+	ZONE_HIGHMEM,
+	ZONE_MOVABLE,
+	ZONE_DEVICE,
+};
+
+static char *zone_names[] = {
+	[ZONE_DMA]	= "DMA",
+	[ZONE_DMA32]	= "DMA32",
+	[ZONE_NORMAL]	= "Normal",
+	[ZONE_HIGHMEM]	= "Highmem",
+	[ZONE_MOVABLE]	= "Movable",
+	[ZONE_DEVICE]	= "Device",
+};
+
+/*
+ * name must be null-terminated
+ */
+static int zone_name_to_id(const char *name)
+{
+	size_t i;
+
+	for (i = 0; i < ARRAY_SIZE(zone_names); i++) {
+		if (!strcasecmp(name, zone_names[i]))
+			return i;
+	}
+	return -1;
+}
+
+static void idxtostr(struct chmem_desc *desc, uint64_t idx, char *buf, size_t bufsz)
+{
+	uint64_t start, end;
+
+	start = idx * desc->block_size;
+	end = start + desc->block_size - 1;
+	snprintf(buf, bufsz,
+		 _("Memory Block %"PRIu64" (0x%016"PRIx64"-0x%016"PRIx64")"),
+		 idx, start, end);
+}
+
+static int chmem_size(struct chmem_desc *desc, int enable, int zone_id)
+{
+	char *name, *onoff, line[BUFSIZ], str[BUFSIZ];
+	uint64_t size, index;
+	const char *zn;
+	int i, rc;
+
+	size = desc->size;
+	onoff = enable ? "online" : "offline";
+	i = enable ? 0 : desc->ndirs - 1;
+
+	if (enable && zone_id >= 0) {
+		if (zone_id == ZONE_MOVABLE)
+			onoff = "online_movable";
+		else
+			onoff = "online_kernel";
+	}
+
+	for (; i >= 0 && i < desc->ndirs && size; i += enable ? 1 : -1) {
+		name = desc->dirs[i]->d_name;
+		index = strtou64_or_err(name + 6, _("Failed to parse index"));
+		path_read_str(line, sizeof(line), _PATH_SYS_MEMORY "/%s/state", name);
+		if (strncmp(onoff, line, 6) == 0)
+			continue;
+
+		if (desc->have_zones) {
+			path_read_str(line, sizeof(line),
+				      _PATH_SYS_MEMORY "/%s/valid_zones", name);
+			if (zone_id >= 0) {
+				zn = zone_names[zone_id];
+				if (enable && !strcasestr(line, zn))
+					continue;
+				if (!enable && strncasecmp(line, zn, strlen(zn)))
+					continue;
+			} else if (enable) {
+				/* By default, use zone Movable for online, if valid */
+				if (strcasestr(line, zone_names[ZONE_MOVABLE]))
+					onoff = "online_movable";
+				else
+					onoff = "online";
+			}
+		}
+
+		idxtostr(desc, index, str, sizeof(str));
+		rc = path_write_str(onoff, _PATH_SYS_MEMORY"/%s/state", name);
+		if (rc == -1 && desc->verbose) {
+			if (enable)
+				fprintf(stdout, _("%s enable failed\n"), str);
+			else
+				fprintf(stdout, _("%s disable failed\n"), str);
+		} else if (rc == 0 && desc->verbose) {
+			if (enable)
+				fprintf(stdout, _("%s enabled\n"), str);
+			else
+				fprintf(stdout, _("%s disabled\n"), str);
+		}
+		if (rc == 0)
+			size--;
+	}
+	if (size) {
+		uint64_t bytes;
+		char *sizestr;
+
+		bytes = (desc->size - size) * desc->block_size;
+		sizestr = size_to_human_string(SIZE_SUFFIX_1LETTER, bytes);
+		if (enable)
+			warnx(_("Could only enable %s of memory"), sizestr);
+		else
+			warnx(_("Could only disable %s of memory"), sizestr);
+		free(sizestr);
+	}
+	return size == 0 ? 0 : size == desc->size ? -1 : 1;
+}
+
+static int chmem_range(struct chmem_desc *desc, int enable, int zone_id)
+{
+	char *name, *onoff, line[BUFSIZ], str[BUFSIZ];
+	uint64_t index, todo;
+	const char *zn;
+	int i, rc;
+
+	todo = desc->end - desc->start + 1;
+	onoff = enable ? "online" : "offline";
+
+	if (enable && zone_id >= 0) {
+		if (zone_id == ZONE_MOVABLE)
+			onoff = "online_movable";
+		else
+			onoff = "online_kernel";
+	}
+
+	for (i = 0; i < desc->ndirs; i++) {
+		name = desc->dirs[i]->d_name;
+		index = strtou64_or_err(name + 6, _("Failed to parse index"));
+		if (index < desc->start)
+			continue;
+		if (index > desc->end)
+			break;
+		idxtostr(desc, index, str, sizeof(str));
+		path_read_str(line, sizeof(line), _PATH_SYS_MEMORY "/%s/state", name);
+		if (strncmp(onoff, line, 6) == 0) {
+			if (desc->verbose && enable)
+				fprintf(stdout, _("%s already enabled\n"), str);
+			else if (desc->verbose && !enable)
+				fprintf(stdout, _("%s already disabled\n"), str);
+			todo--;
+			continue;
+		}
+
+		if (desc->have_zones) {
+			path_read_str(line, sizeof(line),
+				      _PATH_SYS_MEMORY "/%s/valid_zones", name);
+			if (zone_id >= 0) {
+				zn = zone_names[zone_id];
+				if (enable && !strcasestr(line, zn)) {
+					warnx(_("%s enable failed: Zone mismatch"), str);
+					continue;
+				}
+				if (!enable && strncasecmp(line, zn, strlen(zn))) {
+					warnx(_("%s disable failed: Zone mismatch"), str);
+					continue;
+				}
+			} else if (enable) {
+				/* By default, use zone Movable for online, if valid */
+				if (strcasestr(line, zone_names[ZONE_MOVABLE]))
+					onoff = "online_movable";
+				else
+					onoff = "online";
+			}
+		}
+
+		rc = path_write_str(onoff, _PATH_SYS_MEMORY"/%s/state", name);
+		if (rc == -1) {
+			if (enable)
+				warn(_("%s enable failed"), str);
+			else
+				warn(_("%s disable failed"), str);
+		} else if (desc->verbose) {
+			if (enable)
+				fprintf(stdout, _("%s enabled\n"), str);
+			else
+				fprintf(stdout, _("%s disabled\n"), str);
+		}
+		if (rc == 0)
+			todo--;
+	}
+	return todo == 0 ? 0 : todo == desc->end - desc->start + 1 ? -1 : 1;
+}
+
+static int filter(const struct dirent *de)
+{
+	if (strncmp("memory", de->d_name, 6))
+		return 0;
+	return isdigit_string(de->d_name + 6);
+}
+
+static void read_info(struct chmem_desc *desc)
+{
+	char line[BUFSIZ];
+
+	desc->ndirs = scandir(_PATH_SYS_MEMORY, &desc->dirs, filter, versionsort);
+	if (desc->ndirs <= 0)
+		err(EXIT_FAILURE, _("Failed to read %s"), _PATH_SYS_MEMORY);
+	path_read_str(line, sizeof(line), _PATH_SYS_MEMORY_BLOCK_SIZE);
+	desc->block_size = strtoumax(line, NULL, 16);
+}
+
+static void parse_single_param(struct chmem_desc *desc, char *str)
+{
+	if (desc->use_blocks) {
+		desc->start = strtou64_or_err(str, _("Failed to parse block number"));
+		desc->end = desc->start;
+		return;
+	}
+	desc->is_size = 1;
+	desc->size = strtosize_or_err(str, _("Failed to parse size"));
+	if (isdigit(str[strlen(str) - 1]))
+		desc->size *= 1024*1024;
+	if (desc->size % desc->block_size) {
+		errx(EXIT_FAILURE, _("Size must be aligned to memory block size (%s)"),
+		     size_to_human_string(SIZE_SUFFIX_1LETTER, desc->block_size));
+	}
+	desc->size /= desc->block_size;
+}
+
+static void parse_range_param(struct chmem_desc *desc, char *start, char *end)
+{
+	if (desc->use_blocks) {
+		desc->start = strtou64_or_err(start, _("Failed to parse start"));
+		desc->end = strtou64_or_err(end, _("Failed to parse end"));
+		return;
+	}
+	if (strlen(start) < 2 || start[1] != 'x')
+		errx(EXIT_FAILURE, _("Invalid start address format: %s"), start);
+	if (strlen(end) < 2 || end[1] != 'x')
+		errx(EXIT_FAILURE, _("Invalid end address format: %s"), end);
+	desc->start = strtox64_or_err(start, _("Failed to parse start address"));
+	desc->end = strtox64_or_err(end, _("Failed to parse end address"));
+	if (desc->start % desc->block_size || (desc->end + 1) % desc->block_size) {
+		errx(EXIT_FAILURE,
+		     _("Start address and (end address + 1) must be aligned to "
+		       "memory block size (%s)"),
+		     size_to_human_string(SIZE_SUFFIX_1LETTER, desc->block_size));
+	}
+	desc->start /= desc->block_size;
+	desc->end /= desc->block_size;
+}
+
+static void parse_parameter(struct chmem_desc *desc, char *param)
+{
+	char **split;
+
+	split = strv_split(param, "-");
+	if (strv_length(split) > 2)
+		errx(EXIT_FAILURE, _("Invalid parameter: %s"), param);
+	if (strv_length(split) == 1)
+		parse_single_param(desc, split[0]);
+	else
+		parse_range_param(desc, split[0], split[1]);
+	strv_free(split);
+	if (desc->start > desc->end)
+		errx(EXIT_FAILURE, _("Invalid range: %s"), param);
+}
+
+static void __attribute__((__noreturn__)) usage(void)
+{
+	FILE *out = stdout;
+	size_t i;
+
+	fputs(USAGE_HEADER, out);
+	fprintf(out, _(" %s [options] [SIZE|RANGE|BLOCKRANGE]\n"), program_invocation_short_name);
+
+	fputs(USAGE_SEPARATOR, out);
+	fputs(_("Set a particular size or range of memory online or offline.\n"), out);
+
+	fputs(USAGE_OPTIONS, out);
+	fputs(_(" -e, --enable       enable memory\n"), out);
+	fputs(_(" -d, --disable      disable memory\n"), out);
+	fputs(_(" -b, --blocks       use memory blocks\n"), out);
+	fputs(_(" -z, --zone <name>  select memory zone (see below)\n"), out);
+	fputs(_(" -v, --verbose      verbose output\n"), out);
+	printf(USAGE_HELP_OPTIONS(20));
+
+	fputs(_("\nSupported zones:\n"), out);
+	for (i = 0; i < ARRAY_SIZE(zone_names); i++)
+		fprintf(out, " %s\n", zone_names[i]);
+
+	printf(USAGE_MAN_TAIL("chmem(8)"));
+
+	exit(EXIT_SUCCESS);
+}
+
+int main(int argc, char **argv)
+{
+	struct chmem_desc _desc = { }, *desc = &_desc;
+	int cmd = CMD_NONE, zone_id = -1;
+	char *zone = NULL;
+	int c, rc;
+
+	static const struct option longopts[] = {
+		{"block",	no_argument,		NULL, 'b'},
+		{"disable",	no_argument,		NULL, 'd'},
+		{"enable",	no_argument,		NULL, 'e'},
+		{"help",	no_argument,		NULL, 'h'},
+		{"verbose",	no_argument,		NULL, 'v'},
+		{"version",	no_argument,		NULL, 'V'},
+		{"zone",	required_argument,	NULL, 'z'},
+		{NULL,		0,			NULL, 0}
+	};
+
+	static const ul_excl_t excl[] = {	/* rows and cols in ASCII order */
+		{ 'd','e' },
+		{ 0 }
+	};
+	int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
+
+	setlocale(LC_ALL, "");
+	bindtextdomain(PACKAGE, LOCALEDIR);
+	textdomain(PACKAGE);
+	atexit(close_stdout);
+
+	read_info(desc);
+
+	while ((c = getopt_long(argc, argv, "bdehvVz:", longopts, NULL)) != -1) {
+
+		err_exclusive_options(c, longopts, excl, excl_st);
+
+		switch (c) {
+		case 'd':
+			cmd = CMD_MEMORY_DISABLE;
+			break;
+		case 'e':
+			cmd = CMD_MEMORY_ENABLE;
+			break;
+		case 'b':
+			desc->use_blocks = 1;
+			break;
+		case 'h':
+			usage();
+			break;
+		case 'v':
+			desc->verbose = 1;
+			break;
+		case 'V':
+			printf(UTIL_LINUX_VERSION);
+			return EXIT_SUCCESS;
+		case 'z':
+			zone = xstrdup(optarg);
+			break;
+		default:
+			errtryhelp(EXIT_FAILURE);
+		}
+	}
+
+	if ((argc == 1) || (argc != optind + 1) || (cmd == CMD_NONE)) {
+		warnx(_("bad usage"));
+		errtryhelp(EXIT_FAILURE);
+	}
+
+	parse_parameter(desc, argv[optind]);
+
+	/* The valid_zones sysfs attribute was introduced with kernel 3.18 */
+	if (path_exist(_PATH_SYS_MEMORY "/memory0/valid_zones"))
+		desc->have_zones = 1;
+	else if (zone)
+		warnx(_("zone ignored, no valid_zones sysfs attribute present"));
+
+	if (zone && desc->have_zones) {
+		zone_id = zone_name_to_id(zone);
+		if (zone_id == -1) {
+			warnx(_("unknown memory zone: %s"), zone);
+			errtryhelp(EXIT_FAILURE);
+		}
+	}
+
+	if (desc->is_size)
+		rc = chmem_size(desc, cmd == CMD_MEMORY_ENABLE ? 1 : 0, zone_id);
+	else
+		rc = chmem_range(desc, cmd == CMD_MEMORY_ENABLE ? 1 : 0, zone_id);
+
+	return rc == 0 ? EXIT_SUCCESS :
+		rc < 0 ? EXIT_FAILURE : CHMEM_EXIT_SOMEOK;
+}
diff --git a/sys-utils/lsmem.1 b/sys-utils/lsmem.1
new file mode 100644
index 000000000..3f5cd7d4b
--- /dev/null
+++ b/sys-utils/lsmem.1
@@ -0,0 +1,95 @@
+.TH LSMEM 1 "October 2016" "util-linux" "User Commands"
+.SH NAME
+lsmem \- list the ranges of available memory with their online status
+.SH SYNOPSIS
+.B lsmem
+[options]
+.SH DESCRIPTION
+The \fBlsmem\fP command lists the ranges of available memory with their online
+status. The listed memory blocks correspond to the memory block representation
+in sysfs. The command also shows the memory block size and the amount of memory
+in online and offline state.
+
+The default output compatible with original implementation from s390-tools, but
+it's strongly recommended to avoid using default outputs in your scripts.
+Always explicitly define expected columns by using the \fB\-\-output\fR option
+together with a columns list in environments where a stable output is required.
+
+The \fBlsmem\fP command lists a new memory range always when the current memory
+block distinguish from the previous block by STATE, REMOVABLE, NODE or ZONES
+attribute.  This default behavior is possible to override by the
+\fB\-\-split\fR option (e.g. \fBlsmem \-\-split=STATE,ZONES\fR).  The special
+word "none" may be used to ignore all differences between memory blocks and to
+create as large as possible continuous ranges.  The opposite semantic is
+\fB\-\-all\fR to list individual memory blocks.  The default split policy is
+subject to change.  Always explicitly use \fB\-\-split\fR in environments where
+a stable output is required.
+
+Note that some output columns may provide inaccurate information if a split policy
+forces \fBlsmem\fP to ignore diffrences in some attributes. For example if you
+merge removable and non-removable memory blocks to the one range than all
+the range will be marked as non-removable on \fBlsmem\fP output.
+
+Not all columns are supported on all systems.  If an unsupported column is
+specified, \fBlsmem\fP prints the column but does not provide any data for it.
+
+Use the \fB\-\-help\fR option to see the columns description.
+
+.SH OPTIONS
+.TP
+.BR \-a ", " \-\-all
+List each individual memory block, instead of combining memory blocks with
+similar attributes.
+.TP
+.BR \-b , " \-\-bytes"
+Print the SIZE column in bytes rather than in a human-readable format.
+.TP
+.BR \-h ", " \-\-help
+Display help text and exit.
+.TP
+.BR \-n , " \-\-noheadings"
+Do not print a header line.
+.TP
+.BR \-o , " \-\-output " \fIlist\fP
+Specify which output columns to print.  Use \fB\-\-help\fR
+to get a list of all supported columns.
+The default list of columns may be extended if \fIlist\fP is
+specified in the format \fB+\fIlist\fP (e.g. \fBlsmem \-o +NODE\fP).
+.TP
+.BR \-P , " \-\-pairs"
+Produce output in the form of key="value" pairs.
+All potentially unsafe characters are hex-escaped (\\x<code>).
+.TP
+.BR \-r , " \-\-raw"
+Produce output in raw format.  All potentially unsafe characters are hex-escaped
+(\\x<code>).
+.TP
+.BR \-S , " \-\-split " \fIlist\fP
+Specify which columns (attributes) use to split memory blocks to ranges.  The
+supported columns are STATE, REMOVABLE, NODE and ZONES, or "none". The another columns are
+silently ignored. For more details see DESCRIPTION above.
+.TP
+.BR \-s , " \-\-sysroot " \fIdirectory\fP
+Gather memory data for a Linux instance other than the instance from which the
+\fBlsmem\fP command is issued.  The specified \fIdirectory\fP is the system
+root of the Linux instance to be inspected.
+.TP
+.BR \-V ", " \-\-version
+Display version information and exit.
+.TP
+\fB\-\-summary\fR[=\fIwhen\fR]
+This option controls summary lines output.  The optional argument \fIwhen\fP can be
+\fBnever\fR, \fBalways\fR or \fBonly\fR.  If the \fIwhen\fR argument is
+omitted, it defaults to \fB"only"\fR. The summary output is suppresed for
+\fB\-\-raw\fR and \fB\-\-pairs\fR.
+.SH AUTHOR
+.B lsmem
+was originally written by Gerald Schaefer for s390-tools in Perl. The C version
+for util-linux was written by Clemens von Mann, Heiko Carstens and Karel Zak.
+.SH SEE ALSO
+.BR chmem (8)
+.SH AVAILABILITY
+The \fBlsmem\fP command is part of the util-linux package and is available from
+.UR https://\:www.kernel.org\:/pub\:/linux\:/utils\:/util-linux/
+Linux Kernel Archive
+.UE .
diff --git a/sys-utils/lsmem.c b/sys-utils/lsmem.c
new file mode 100644
index 000000000..34a2847af
--- /dev/null
+++ b/sys-utils/lsmem.c
@@ -0,0 +1,687 @@
+/*
+ * lsmem - Show memory configuration
+ *
+ * Copyright IBM Corp. 2016
+ * Copyright (C) 2016 Karel Zak <kzak@redhat.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it would be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+#include <c.h>
+#include <nls.h>
+#include <path.h>
+#include <strutils.h>
+#include <closestream.h>
+#include <xalloc.h>
+#include <getopt.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <assert.h>
+#include <optutils.h>
+#include <libsmartcols.h>
+
+#define _PATH_SYS_MEMORY		"/sys/devices/system/memory"
+#define _PATH_SYS_MEMORY_BLOCK_SIZE	_PATH_SYS_MEMORY "/block_size_bytes"
+
+#define MEMORY_STATE_ONLINE		0
+#define MEMORY_STATE_OFFLINE		1
+#define MEMORY_STATE_GOING_OFFLINE	2
+#define MEMORY_STATE_UNKNOWN		3
+
+enum zone_id {
+	ZONE_DMA = 0,
+	ZONE_DMA32,
+	ZONE_NORMAL,
+	ZONE_HIGHMEM,
+	ZONE_MOVABLE,
+	ZONE_DEVICE,
+	ZONE_NONE,
+	ZONE_UNKNOWN,
+	MAX_NR_ZONES,
+};
+
+struct memory_block {
+	uint64_t	index;
+	uint64_t	count;
+	int		state;
+	int		node;
+	int		nr_zones;
+	int		zones[MAX_NR_ZONES];
+	unsigned int	removable:1;
+};
+
+struct lsmem {
+	struct dirent		**dirs;
+	int			ndirs;
+	struct memory_block	*blocks;
+	int			nblocks;
+	uint64_t		block_size;
+	uint64_t		mem_online;
+	uint64_t		mem_offline;
+
+	struct libscols_table	*table;
+	unsigned int		have_nodes : 1,
+				raw : 1,
+				export : 1,
+				noheadings : 1,
+				summary : 1,
+				list_all : 1,
+				bytes : 1,
+				want_summary : 1,
+				want_table : 1,
+				split_by_node : 1,
+				split_by_state : 1,
+				split_by_removable : 1,
+				split_by_zones : 1,
+				have_zones : 1;
+};
+
+
+enum {
+	COL_RANGE,
+	COL_SIZE,
+	COL_STATE,
+	COL_REMOVABLE,
+	COL_BLOCK,
+	COL_NODE,
+	COL_ZONES,
+};
+
+static char *zone_names[] = {
+	[ZONE_DMA]	= "DMA",
+	[ZONE_DMA32]	= "DMA32",
+	[ZONE_NORMAL]	= "Normal",
+	[ZONE_HIGHMEM]	= "Highmem",
+	[ZONE_MOVABLE]	= "Movable",
+	[ZONE_DEVICE]	= "Device",
+	[ZONE_NONE]	= "None",	/* block contains more than one zone, can't be offlined */
+	[ZONE_UNKNOWN]	= "Unknown",
+};
+
+/* column names */
+struct coldesc {
+	const char	*name;		/* header */
+	double		whint;		/* width hint (N < 1 is in percent of termwidth) */
+	int		flags;		/* SCOLS_FL_* */
+	const char      *help;
+
+	int	sort_type;		/* SORT_* */
+};
+
+/* columns descriptions */
+static struct coldesc coldescs[] = {
+	[COL_RANGE]	= { "RANGE", 0, 0, N_("start and end address of the memory range")},
+	[COL_SIZE]	= { "SIZE", 5, SCOLS_FL_RIGHT, N_("size of the memory range")},
+	[COL_STATE]	= { "STATE", 0, SCOLS_FL_RIGHT, N_("online status of the memory range")},
+	[COL_REMOVABLE]	= { "REMOVABLE", 0, SCOLS_FL_RIGHT, N_("memory is removable")},
+	[COL_BLOCK]	= { "BLOCK", 0, SCOLS_FL_RIGHT, N_("memory block number or blocks range")},
+	[COL_NODE]	= { "NODE", 0, SCOLS_FL_RIGHT, N_("numa node of memory")},
+	[COL_ZONES]	= { "ZONES", 0, SCOLS_FL_RIGHT, N_("valid zones for the memory range")},
+};
+
+/* columns[] array specifies all currently wanted output column. The columns
+ * are defined by coldescs[] array and you can specify (on command line) each
+ * column twice. That's enough, dynamically allocated array of the columns is
+ * unnecessary overkill and over-engineering in this case */
+static int columns[ARRAY_SIZE(coldescs) * 2];
+static size_t ncolumns;
+
+static inline size_t err_columns_index(size_t arysz, size_t idx)
+{
+	if (idx >= arysz)
+		errx(EXIT_FAILURE, _("too many columns specified, "
+				     "the limit is %zu columns"),
+				arysz - 1);
+	return idx;
+}
+
+/*
+ * name must be null-terminated
+ */
+static int zone_name_to_id(const char *name)
+{
+	size_t i;
+
+	for (i = 0; i < ARRAY_SIZE(zone_names); i++) {
+		if (!strcasecmp(name, zone_names[i]))
+			return i;
+	}
+	return ZONE_UNKNOWN;
+}
+
+#define add_column(ary, n, id)	\
+		((ary)[ err_columns_index(ARRAY_SIZE(ary), (n)) ] = (id))
+
+static int column_name_to_id(const char *name, size_t namesz)
+{
+	size_t i;
+
+	for (i = 0; i < ARRAY_SIZE(coldescs); i++) {
+		const char *cn = coldescs[i].name;
+
+		if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
+			return i;
+	}
+	warnx(_("unknown column: %s"), name);
+	return -1;
+}
+
+static inline int get_column_id(int num)
+{
+	assert(num >= 0);
+	assert((size_t) num < ncolumns);
+	assert(columns[num] < (int) ARRAY_SIZE(coldescs));
+
+	return columns[num];
+}
+
+static inline struct coldesc *get_column_desc(int num)
+{
+	return &coldescs[ get_column_id(num) ];
+}
+
+static inline void reset_split_policy(struct lsmem *l, int enable)
+{
+	l->split_by_state = enable;
+	l->split_by_node = enable;
+	l->split_by_removable = enable;
+	l->split_by_zones = enable;
+}
+
+static void add_scols_line(struct lsmem *lsmem, struct memory_block *blk)
+{
+	size_t i;
+	struct libscols_line *line;
+
+	line = scols_table_new_line(lsmem->table, NULL);
+	if (!line)
+		err_oom();
+
+	for (i = 0; i < ncolumns; i++) {
+		char *str = NULL;
+
+		switch (get_column_id(i)) {
+		case COL_RANGE:
+		{
+			uint64_t start = blk->index * lsmem->block_size;
+			uint64_t size = blk->count * lsmem->block_size;
+			xasprintf(&str, "0x%016"PRIx64"-0x%016"PRIx64, start, start + size - 1);
+			break;
+		}
+		case COL_SIZE:
+			if (lsmem->bytes)
+				xasprintf(&str, "%"PRId64, (uint64_t) blk->count * lsmem->block_size);
+			else
+				str = size_to_human_string(SIZE_SUFFIX_1LETTER,
+						(uint64_t) blk->count * lsmem->block_size);
+			break;
+		case COL_STATE:
+			str = xstrdup(
+				blk->state == MEMORY_STATE_ONLINE ? _("online") :
+				blk->state == MEMORY_STATE_OFFLINE ? _("offline") :
+				blk->state == MEMORY_STATE_GOING_OFFLINE ? _("on->off") :
+				"?");
+			break;
+		case COL_REMOVABLE:
+			if (blk->state == MEMORY_STATE_ONLINE)
+				str = xstrdup(blk->removable ? _("yes") : _("no"));
+			else
+				str = xstrdup("-");
+			break;
+		case COL_BLOCK:
+			if (blk->count == 1)
+				xasprintf(&str, "%"PRId64, blk->index);
+			else
+				xasprintf(&str, "%"PRId64"-%"PRId64,
+					 blk->index, blk->index + blk->count - 1);
+			break;
+		case COL_NODE:
+			if (lsmem->have_nodes)
+				xasprintf(&str, "%d", blk->node);
+			else
+				str = xstrdup("-");
+			break;
+		case COL_ZONES:
+			if (lsmem->have_zones) {
+				char valid_zones[BUFSIZ];
+				int j, zone_id;
+
+				valid_zones[0] = '\0';
+				for (j = 0; j < blk->nr_zones; j++) {
+					zone_id = blk->zones[j];
+					if (strlen(valid_zones) +
+					    strlen(zone_names[zone_id]) > BUFSIZ - 2)
+						break;
+					strcat(valid_zones, zone_names[zone_id]);
+					if (j + 1 < blk->nr_zones)
+						strcat(valid_zones, "/");
+				}
+				str = xstrdup(valid_zones);
+			} else
+				str = xstrdup("-");
+			break;
+		}
+
+		if (str && scols_line_refer_data(line, i, str) != 0)
+			err_oom();
+	}
+}
+
+static void fill_scols_table(struct lsmem *lsmem)
+{
+	int i;
+
+	for (i = 0; i < lsmem->nblocks; i++)
+		add_scols_line(lsmem, &lsmem->blocks[i]);
+}
+
+static void print_summary(struct lsmem *lsmem)
+{
+	if (lsmem->bytes) {
+		printf("%-23s %15"PRId64"\n",_("Memory block size:"), lsmem->block_size);
+		printf("%-23s %15"PRId64"\n",_("Total online memory:"), lsmem->mem_online);
+		printf("%-23s %15"PRId64"\n",_("Total offline memory:"), lsmem->mem_offline);
+	} else {
+		printf("%-23s %5s\n",_("Memory block size:"),
+			size_to_human_string(SIZE_SUFFIX_1LETTER, lsmem->block_size));
+		printf("%-23s %5s\n",_("Total online memory:"),
+			size_to_human_string(SIZE_SUFFIX_1LETTER, lsmem->mem_online));
+		printf("%-23s %5s\n",_("Total offline memory:"),
+			size_to_human_string(SIZE_SUFFIX_1LETTER, lsmem->mem_offline));
+	}
+}
+
+static int memory_block_get_node(char *name)
+{
+	struct dirent *de;
+	const char *path;
+	DIR *dir;
+	int node;
+
+	path = path_get(_PATH_SYS_MEMORY"/%s", name);
+	if (!path || !(dir= opendir(path)))
+		err(EXIT_FAILURE, _("Failed to open %s"), path ? path : name);
+
+	node = -1;
+	while ((de = readdir(dir)) != NULL) {
+		if (strncmp("node", de->d_name, 4))
+			continue;
+		if (!isdigit_string(de->d_name + 4))
+			continue;
+		node = strtol(de->d_name + 4, NULL, 10);
+		break;
+	}
+	closedir(dir);
+	return node;
+}
+
+static void memory_block_read_attrs(struct lsmem *lsmem, char *name,
+				    struct memory_block *blk)
+{
+	char *token = NULL;
+	char line[BUFSIZ];
+	int i;
+
+	blk->count = 1;
+	blk->index = strtoumax(name + 6, NULL, 10); /* get <num> of "memory<num>" */
+	blk->removable = path_read_u64(_PATH_SYS_MEMORY"/%s/removable", name);
+	blk->state = MEMORY_STATE_UNKNOWN;
+
+	path_read_str(line, sizeof(line), _PATH_SYS_MEMORY"/%s/state", name);
+	if (strcmp(line, "offline") == 0)
+		blk->state = MEMORY_STATE_OFFLINE;
+	else if (strcmp(line, "online") == 0)
+		blk->state = MEMORY_STATE_ONLINE;
+	else if (strcmp(line, "going-offline") == 0)
+		blk->state = MEMORY_STATE_GOING_OFFLINE;
+
+	if (lsmem->have_nodes)
+		blk->node = memory_block_get_node(name);
+
+	blk->nr_zones = 0;
+	if (lsmem->have_zones) {
+		path_read_str(line, sizeof(line), _PATH_SYS_MEMORY"/%s/valid_zones", name);
+		token = strtok(line, " ");
+	}
+	for (i = 0; i < MAX_NR_ZONES; i++) {
+		if (token) {
+			blk->zones[i] = zone_name_to_id(token);
+			blk->nr_zones++;
+			token = strtok(NULL, " ");
+		}
+	}
+}
+
+static int is_mergeable(struct lsmem *lsmem, struct memory_block *blk)
+{
+	struct memory_block *curr;
+	int i;
+
+	if (!lsmem->nblocks)
+		return 0;
+	curr = &lsmem->blocks[lsmem->nblocks - 1];
+	if (lsmem->list_all)
+		return 0;
+	if (curr->index + curr->count != blk->index)
+		return 0;
+	if (lsmem->split_by_state && curr->state != blk->state)
+		return 0;
+	if (lsmem->split_by_removable && curr->removable != blk->removable)
+		return 0;
+	if (lsmem->split_by_node && lsmem->have_nodes) {
+		if (curr->node != blk->node)
+			return 0;
+	}
+	if (lsmem->split_by_zones && lsmem->have_zones) {
+		if (curr->nr_zones != blk->nr_zones)
+			return 0;
+		for (i = 0; i < curr->nr_zones; i++) {
+			if (curr->zones[i] == ZONE_UNKNOWN ||
+			    curr->zones[i] != blk->zones[i])
+				return 0;
+		}
+	}
+	return 1;
+}
+
+static void read_info(struct lsmem *lsmem)
+{
+	struct memory_block blk;
+	char line[BUFSIZ];
+	int i;
+
+	path_read_str(line, sizeof(line), _PATH_SYS_MEMORY_BLOCK_SIZE);
+	lsmem->block_size = strtoumax(line, NULL, 16);
+
+	for (i = 0; i < lsmem->ndirs; i++) {
+		memory_block_read_attrs(lsmem, lsmem->dirs[i]->d_name, &blk);
+		if (is_mergeable(lsmem, &blk)) {
+			lsmem->blocks[lsmem->nblocks - 1].count++;
+			continue;
+		}
+		lsmem->nblocks++;
+		lsmem->blocks = xrealloc(lsmem->blocks, lsmem->nblocks * sizeof(blk));
+		*&lsmem->blocks[lsmem->nblocks - 1] = blk;
+	}
+	for (i = 0; i < lsmem->nblocks; i++) {
+		if (lsmem->blocks[i].state == MEMORY_STATE_ONLINE)
+			lsmem->mem_online += lsmem->block_size * lsmem->blocks[i].count;
+		else
+			lsmem->mem_offline += lsmem->block_size * lsmem->blocks[i].count;
+	}
+}
+
+static int memory_block_filter(const struct dirent *de)
+{
+	if (strncmp("memory", de->d_name, 6))
+		return 0;
+	return isdigit_string(de->d_name + 6);
+}
+
+static void read_basic_info(struct lsmem *lsmem)
+{
+	const char *dir;
+
+	if (!path_exist(_PATH_SYS_MEMORY_BLOCK_SIZE))
+		errx(EXIT_FAILURE, _("This system does not support memory blocks"));
+
+	dir = path_get(_PATH_SYS_MEMORY);
+	if (!dir)
+		err(EXIT_FAILURE, _("Failed to read %s"), _PATH_SYS_MEMORY);
+
+	lsmem->ndirs = scandir(dir, &lsmem->dirs, memory_block_filter, versionsort);
+	if (lsmem->ndirs <= 0)
+		err(EXIT_FAILURE, _("Failed to read %s"), _PATH_SYS_MEMORY);
+
+	if (memory_block_get_node(lsmem->dirs[0]->d_name) != -1)
+		lsmem->have_nodes = 1;
+
+	/* The valid_zones sysfs attribute was introduced with kernel 3.18 */
+	if (path_exist(_PATH_SYS_MEMORY "/memory0/valid_zones"))
+		lsmem->have_zones = 1;
+}
+
+static void __attribute__((__noreturn__)) usage(void)
+{
+	FILE *out = stdout;
+	size_t i;
+
+	fputs(USAGE_HEADER, out);
+	fprintf(out, _(" %s [options]\n"), program_invocation_short_name);
+
+	fputs(USAGE_SEPARATOR, out);
+	fputs(_("List the ranges of available memory with their online status.\n"), out);
+
+	fputs(USAGE_OPTIONS, out);
+	fputs(_(" -P, --pairs          use key=\"value\" output format\n"), out);
+	fputs(_(" -a, --all            list each individual memory block\n"), out);
+	fputs(_(" -b, --bytes          print SIZE in bytes rather than in human readable format\n"), out);
+	fputs(_(" -n, --noheadings     don't print headings\n"), out);
+	fputs(_(" -o, --output <list>  output columns\n"), out);
+	fputs(_(" -r, --raw            use raw output format\n"), out);
+	fputs(_(" -S, --split <list>   split ranges by specified columns\n"), out);
+	fputs(_(" -s, --sysroot <dir>  use the specified directory as system root\n"), out);
+	fputs(_("     --summary[=when] print summary information (never,always or only)\n"), out);
+
+	fputs(USAGE_SEPARATOR, out);
+	printf(USAGE_HELP_OPTIONS(22));
+
+	fputs(USAGE_COLUMNS, out);
+	for (i = 0; i < ARRAY_SIZE(coldescs); i++)
+		fprintf(out, " %10s  %s\n", coldescs[i].name, _(coldescs[i].help));
+
+	printf(USAGE_MAN_TAIL("lsmem(1)"));
+
+	exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
+}
+
+int main(int argc, char **argv)
+{
+	struct lsmem _lsmem = {
+			.want_table = 1,
+			.want_summary = 1
+		}, *lsmem = &_lsmem;
+
+	const char *outarg = NULL, *splitarg = NULL;
+	int c;
+	size_t i;
+
+	enum {
+		LSMEM_OPT_SUMARRY = CHAR_MAX + 1
+	};
+
+	static const struct option longopts[] = {
+		{"all",		no_argument,		NULL, 'a'},
+		{"bytes",	no_argument,		NULL, 'b'},
+		{"help",	no_argument,		NULL, 'h'},
+		{"noheadings",	no_argument,		NULL, 'n'},
+		{"output",	required_argument,	NULL, 'o'},
+		{"pairs",	no_argument,		NULL, 'P'},
+		{"raw",		no_argument,		NULL, 'r'},
+		{"sysroot",	required_argument,	NULL, 's'},
+		{"split",       required_argument,      NULL, 'S'},
+		{"version",	no_argument,		NULL, 'V'},
+		{"summary",     optional_argument,	NULL, LSMEM_OPT_SUMARRY },
+		{NULL,		0,			NULL, 0}
+	};
+	static const ul_excl_t excl[] = {	/* rows and cols in ASCII order */
+		{ 'J', 'P', 'r' },
+		{ 'S', 'a' },
+		{ 0 }
+	};
+	int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
+
+	setlocale(LC_ALL, "");
+	bindtextdomain(PACKAGE, LOCALEDIR);
+	textdomain(PACKAGE);
+	atexit(close_stdout);
+
+	while ((c = getopt_long(argc, argv, "abhJno:PrS:s:V", longopts, NULL)) != -1) {
+
+		err_exclusive_options(c, longopts, excl, excl_st);
+
+		switch (c) {
+		case 'a':
+			lsmem->list_all = 1;
+			break;
+		case 'b':
+			lsmem->bytes = 1;
+			break;
+		case 'h':
+			usage();
+			break;
+		case 'n':
+			lsmem->noheadings = 1;
+			break;
+		case 'o':
+			outarg = optarg;
+			break;
+		case 'P':
+			lsmem->export = 1;
+			lsmem->want_summary = 0;
+			break;
+		case 'r':
+			lsmem->raw = 1;
+			lsmem->want_summary = 0;
+			break;
+		case 's':
+			if(path_set_prefix(optarg))
+				err(EXIT_FAILURE, _("invalid argument to %s"), "--sysroot");
+			break;
+		case 'S':
+			splitarg = optarg;
+			break;
+		case 'V':
+			printf(UTIL_LINUX_VERSION);
+			return 0;
+		case LSMEM_OPT_SUMARRY:
+			if (optarg) {
+				if (strcmp(optarg, "never") == 0)
+					lsmem->want_summary = 0;
+				else if (strcmp(optarg, "only") == 0)
+					lsmem->want_table = 0;
+				else if (strcmp(optarg, "always") == 0)
+					lsmem->want_summary = 1;
+				else
+					errx(EXIT_FAILURE, _("unsupported --summary argument"));
+			} else
+				lsmem->want_table = 0;
+			break;
+		default:
+			errtryhelp(EXIT_FAILURE);
+		}
+	}
+
+	if (argc != optind) {
+		warnx(_("bad usage"));
+		errtryhelp(EXIT_FAILURE);
+	}
+
+	if (lsmem->want_table + lsmem->want_summary == 0)
+		errx(EXIT_FAILURE, _("options --{raw,pairs} and --summary=only are mutually exclusive"));
+
+	/* Shortcut to avoid scols machinery on --summary=only */
+	if (lsmem->want_table == 0 && lsmem->want_summary) {
+		read_basic_info(lsmem);
+		read_info(lsmem);
+		print_summary(lsmem);
+		return EXIT_SUCCESS;
+	}
+
+	/*
+	 * Default columns
+	 */
+	if (!ncolumns) {
+		add_column(columns, ncolumns++, COL_RANGE);
+		add_column(columns, ncolumns++, COL_SIZE);
+		add_column(columns, ncolumns++, COL_STATE);
+		add_column(columns, ncolumns++, COL_REMOVABLE);
+		add_column(columns, ncolumns++, COL_BLOCK);
+	}
+
+	if (outarg && string_add_to_idarray(outarg, columns, ARRAY_SIZE(columns),
+					 (int *) &ncolumns, column_name_to_id) < 0)
+		return EXIT_FAILURE;
+
+	/*
+	 * Initialize output
+	 */
+	scols_init_debug(0);
+
+	if (!(lsmem->table = scols_new_table()))
+		errx(EXIT_FAILURE, _("failed to initialize output table"));
+	scols_table_enable_raw(lsmem->table, lsmem->raw);
+	scols_table_enable_export(lsmem->table, lsmem->export);
+	scols_table_enable_noheadings(lsmem->table, lsmem->noheadings);
+
+	for (i = 0; i < ncolumns; i++) {
+		struct coldesc *ci = get_column_desc(i);
+		if (!scols_table_new_column(lsmem->table, ci->name, ci->whint, ci->flags))
+			err(EXIT_FAILURE, _("Failed to initialize output column"));
+	}
+
+	if (splitarg) {
+		int split[ARRAY_SIZE(coldescs)] = { 0 };
+		static size_t nsplits = 0;
+
+		reset_split_policy(lsmem, 0);	/* disable all */
+
+		if (strcasecmp(splitarg, "none") == 0)
+			;
+		else if (string_add_to_idarray(splitarg, split, ARRAY_SIZE(split),
+					(int *) &nsplits, column_name_to_id) < 0)
+			return EXIT_FAILURE;
+
+		for (i = 0; i < nsplits; i++) {
+			switch (split[i]) {
+			case COL_STATE:
+				lsmem->split_by_state = 1;
+				break;
+			case COL_NODE:
+				lsmem->split_by_node = 1;
+				break;
+			case COL_REMOVABLE:
+				lsmem->split_by_removable = 1;
+				break;
+			case COL_ZONES:
+				lsmem->split_by_zones = 1;
+				break;
+			}
+		}
+	} else
+		reset_split_policy(lsmem, 1); /* enable all */
+
+	/*
+	 * Read data and print output
+	 */
+	read_basic_info(lsmem);
+	read_info(lsmem);
+
+	if (lsmem->want_table) {
+		fill_scols_table(lsmem);
+		scols_print_table(lsmem->table);
+
+		if (lsmem->want_summary)
+			fputc('\n', stdout);
+	}
+
+	if (lsmem->want_summary)
+		print_summary(lsmem);
+
+	scols_unref_table(lsmem->table);
+	return 0;
+}
-- 
2.13.6