cdown / rpms / util-linux

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