cdown / rpms / util-linux

Forked from rpms/util-linux 2 years ago
Clone

Blame SOURCES/0142-lsmem-chmem-backport-new-commands.patch

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