Skip to contentSkip to conversation

mm: security: ro protection for dynamic data

RFC PATCH Superseded Igor Stoppa 5 participants 29 messages Feb 12, 2018 – Feb 22, 2018

Subsystems (7)

v16 of 21 Superseded Latest is v21 →

lore
Share & tools
lore
#0 lore raw

v16 cover mm: security: ro protection for dynamic data

This patch-set introduces the possibility of protecting memory that has been allocated dynamically.

The memory is managed in pools: when a memory pool is turned into R/O, all the memory that is part of it, will become R/O.

A R/O pool can be destroyed, to recover its memory, but it cannot be turned back into R/W mode.

This is intentional. This feature is meant for data that doesn't need further modifications after initialization.

However the data might need to be released, for example as part of module unloading.
To do this, the memory must first be freed, then the pool can be destroyed.

An example is provided, in the form of self-testing.

Changes since v15:
[http://www.openwall.com/lists/kernel-hardening/2018/02/11/4]

- Fixed remaining broken comments
- Fixed remaining broken "Returns" instead of "Return:" in kernel-doc
- Converted "Return:" values to lists
- Fixed SPDX license statements

Igor Stoppa (6):
genalloc: track beginning of allocations
genalloc: selftest
struct page: add field for vm_struct
Protectable Memory
Pmalloc: self-test
Documentation for Pmalloc

 Documentation/core-api/index.rst   |   1 +
 Documentation/core-api/pmalloc.rst | 114 +++++++
 include/linux/genalloc-selftest.h  |  26 ++
 include/linux/genalloc.h           |   7 +-
 include/linux/mm_types.h           |   1 +
 include/linux/pmalloc.h            | 242 ++++++++++++++
 include/linux/vmalloc.h            |   1 +
 init/main.c                        |   2 +
 lib/Kconfig                        |  15 +
 lib/Makefile                       |   1 +
 lib/genalloc-selftest.c            | 400 ++++++++++++++++++++++
 lib/genalloc.c                     | 658 +++++++++++++++++++++++++++----------
 mm/Kconfig                         |  15 +
 mm/Makefile                        |   2 +
 mm/pmalloc-selftest.c              |  64 ++++
 mm/pmalloc-selftest.h              |  24 ++
 mm/pmalloc.c                       | 501 ++++++++++++++++++++++++++++
 mm/usercopy.c                      |  33 ++
 mm/vmalloc.c                       |  18 +-
 19 files changed, 1950 insertions(+), 175 deletions(-)
 create mode 100644 Documentation/core-api/pmalloc.rst
 create mode 100644 include/linux/genalloc-selftest.h
 create mode 100644 include/linux/pmalloc.h
 create mode 100644 lib/genalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.h
 create mode 100644 mm/pmalloc.c
Signature · 1 line
2.14.1
#1 lore raw

PATCH v16 1/6 genalloc: track beginning of allocations

The genalloc library is only capable of tracking if a certain unit of allocation is in use or not.

It is not capable of discerning where the memory associated to an allocation request begins and where it ends.

The reason is that units of allocations are tracked by using a bitmap, where each bit represents that the unit is either allocated (1) or available (0).

The user of the API must keep track of how much space was requested, if it ever needs to be freed.

This can cause errors being undetected.
Examples:
* Only a subset of the memory provided to an allocation request is freed
* The memory from a subsequent allocation is freed
* The memory being freed doesn't start at the beginning of an allocation.

The bitmap is used because it allows to perform lockless read/write access, where this is supported by hw through cmpxchg. Similarly, it is possible to scan the bitmap for a sufficiently long sequence of zeros, to identify zones available for allocation.

This patch doubles the space reserved in the bitmap for each allocation, to track their beginning.

For details, see the documentation inside lib/genalloc.c

---
 include/linux/genalloc.h |   4 +-
 lib/genalloc.c           | 631 ++++++++++++++++++++++++++++++++++-------------
 2 files changed, 465 insertions(+), 170 deletions(-)
include/linux/genalloc.h +2 -2
index 872f930f1b06..dcaa33e74b1c 100644
@@ -32,7 +32,7 @@
 
 #include <linux/types.h>
 #include <linux/spinlock_types.h>
-#include <linux/atomic.h>
+#include <linux/slab.h>
 
 struct device;
 struct device_node;
@@ -76,7 +76,7 @@ struct gen_pool_chunk {
 	phys_addr_t phys_addr;		/* physical starting address of memory chunk */
 	unsigned long start_addr;	/* start address of memory chunk */
 	unsigned long end_addr;		/* end address of memory chunk (inclusive) */
-	unsigned long bits[0];		/* bitmap for allocating memory chunk */
+	unsigned long entries[0];	/* bitmap for allocating memory chunk */
 };
 
 /*
lib/genalloc.c +463 -168

964 lines not on this page · raw message

Signature · 1 line
2.14.1
#2 lore raw

Re: [PATCH 1/6] genalloc: track beginning of allocations

Quoted 11 lines · Igor Stoppa
lib/genalloc.c +1 -2
@@ -738,14 +1031,16 @@ EXPORT_SYMBOL(devm_gen_pool_create);
 
 #ifdef CONFIG_OF
 /**
- * of_gen_pool_get - find a pool by phandle property
+ * of_gen_pool_get() - find a pool by phandle property
  * @np: device node
  * @propname: property name containing phandle(s)
  * @index: index into the phandle array
  *
- * Returns the pool that contains the chunk starting at the physical

lib/genalloc.c EXPORT_SYMBOL(devm_gen_pool_create); · line 1046

Quoted 10 lines
lib/genalloc.c +5 -2
- * address of the device tree node pointed at by the phandle property,
- * or NULL if not found.
+ * Return:
+ * * pool address      - it contains the chunk starting at the physical
+ *                       address of the device tree node pointed at by
+ *                       the phandle property
+ * * NULL              - otherwise
  */
 struct gen_pool *of_gen_pool_get(struct device_node *np,
        const char *propname, int index)

I wonder if this might be more readable by splitting the kernel-doc changes from the bitmap changes? I.e. fix all the kernel-doc in one patch, and in the following, make the bitmap changes. Maybe it's such a small part that it doesn't matter, though?

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#3 lore raw

Re: [PATCH 1/6] genalloc: track beginning of allocations

Quoted 19 lines · Kees Cook
Quoted 18 lines · Igor Stoppa
lib/genalloc.c +6 -4
@@ -738,14 +1031,16 @@ EXPORT_SYMBOL(devm_gen_pool_create);
 
 #ifdef CONFIG_OF
 /**
- * of_gen_pool_get - find a pool by phandle property
+ * of_gen_pool_get() - find a pool by phandle property
  * @np: device node
  * @propname: property name containing phandle(s)
  * @index: index into the phandle array
  *
- * Returns the pool that contains the chunk starting at the physical
- * address of the device tree node pointed at by the phandle property,
- * or NULL if not found.
+ * Return:
+ * * pool address      - it contains the chunk starting at the physical
+ *                       address of the device tree node pointed at by
+ *                       the phandle property
+ * * NULL              - otherwise
Quoted 8 lines

lib/genalloc.c EXPORT_SYMBOL(devm_gen_pool_create); · line 1046

Quoted 3 lines
lib/genalloc.c +0 -0
  */
 struct gen_pool *of_gen_pool_get(struct device_node *np,
        const char *propname, int index)

I wonder if this might be more readable by splitting the kernel-doc changes from the bitmap changes? I.e. fix all the kernel-doc in one patch, and in the following, make the bitmap changes. Maybe it's such a small part that it doesn't matter, though?

I had the same thought, but then I would have made most of the kerneldoc changes to something that would be altered by the following patch, because it would have made little sense to fix only those parts that would have survived.

If it is really a problem to keep them together, I could put these changes in a following patch. Would that be ok?

--
igor

#4 lore raw

Re: [PATCH 1/6] genalloc: track beginning of allocations

Quoted 29 lines · Igor Stoppa
Quoted 19 lines · Kees Cook
Quoted 18 lines · Igor Stoppa
lib/genalloc.c +6 -4
@@ -738,14 +1031,16 @@ EXPORT_SYMBOL(devm_gen_pool_create);
 
 #ifdef CONFIG_OF
 /**
- * of_gen_pool_get - find a pool by phandle property
+ * of_gen_pool_get() - find a pool by phandle property
  * @np: device node
  * @propname: property name containing phandle(s)
  * @index: index into the phandle array
  *
- * Returns the pool that contains the chunk starting at the physical
- * address of the device tree node pointed at by the phandle property,
- * or NULL if not found.
+ * Return:
+ * * pool address      - it contains the chunk starting at the physical
+ *                       address of the device tree node pointed at by
+ *                       the phandle property
+ * * NULL              - otherwise
Quoted 8 lines

lib/genalloc.c EXPORT_SYMBOL(devm_gen_pool_create); · line 1046

Quoted 3 lines
lib/genalloc.c +0 -0
  */
 struct gen_pool *of_gen_pool_get(struct device_node *np,
        const char *propname, int index)

I wonder if this might be more readable by splitting the kernel-doc changes from the bitmap changes? I.e. fix all the kernel-doc in one patch, and in the following, make the bitmap changes. Maybe it's such a small part that it doesn't matter, though?

Quoted 7 lines

I had the same thought, but then I would have made most of the kerneldoc changes to something that would be altered by the following patch, because it would have made little sense to fix only those parts that would have survived.

If it is really a problem to keep them together, I could put these changes in a following patch. Would that be ok?

Hmmm... I think keeping it as-is would be better than a trailing docs-only patch. Maybe Jon has an opinion?

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
maintainer
#5 lore raw

Re: [PATCH 1/6] genalloc: track beginning of allocations

Quoted 10 lines · On Wed, 21 Feb 2018 14:29:06 -0800 Kees Cook <[email protected]> wrote:
Quoted 10 lines
Quoted 4 lines

I wonder if this might be more readable by splitting the kernel-doc changes from the bitmap changes? I.e. fix all the kernel-doc in one patch, and in the following, make the bitmap changes. Maybe it's such a small part that it doesn't matter, though?

I had the same thought, but then I would have made most of the kerneldoc changes to something that would be altered by the following patch, because it would have made little sense to fix only those parts that would have survived.

Quoted 5 lines
Quoted 2 lines

If it is really a problem to keep them together, I could put these changes in a following patch. Would that be ok?

Hmmm... I think keeping it as-is would be better than a trailing docs-only patch. Maybe Jon has an opinion?

I would be inclined to agree. Putting docs changes with the associated code changes helps to document the patch itself, among other things. I wouldn't split them up.

jon

#6 lore raw

PATCH v16 2/6 genalloc: selftest

In reply to Igor Stoppa

Introduce a set of macros for writing concise test cases for genalloc.

The test cases are meant to provide regression testing, when working on new functionality for genalloc.

Primarily they are meant to confirm that the various allocation strategy will continue to work as expected.

The execution of the self testing is controlled through a Kconfig option.

---
 include/linux/genalloc-selftest.h |  26 +++
 init/main.c                       |   2 +
 lib/Kconfig                       |  15 ++
 lib/Makefile                      |   1 +
 lib/genalloc-selftest.c           | 400 ++++++++++++++++++++++++++++++++++++++
 5 files changed, 444 insertions(+)
 create mode 100644 include/linux/genalloc-selftest.h
 create mode 100644 lib/genalloc-selftest.c
include/linux/genalloc-selftest.h new file +26 -0
new file mode 100644
index 000000000000..e0ac8f963abc
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * genalloc-selftest.h
+ *
+ * (C) Copyright 2017 Huawei Technologies Co. Ltd.
+ * Author: Igor Stoppa <[email protected]>
+ */
+
+
+#ifndef __LINUX_GENALLOC_SELFTEST_H
+#define __LINUX_GENALLOC_SELFTEST_H
+
+
+#ifdef CONFIG_GENERIC_ALLOCATOR_SELFTEST
+
+#include <linux/genalloc.h>
+
+void genalloc_selftest(void);
+
+#else
+
+static inline void genalloc_selftest(void){};
+
+#endif
+
+#endif
init/main.c +2 -0
index a8100b954839..fb844aa3eb8c 100644
@@ -89,6 +89,7 @@
 #include <linux/io.h>
 #include <linux/cache.h>
 #include <linux/rodata_test.h>
+#include <linux/genalloc-selftest.h>
 
 #include <asm/io.h>
 #include <asm/bugs.h>
@@ -660,6 +661,7 @@ asmlinkage __visible void __init start_kernel(void)
 	 */
 	mem_encrypt_init();
 
+	genalloc_selftest();
 #ifdef CONFIG_BLK_DEV_INITRD
 	if (initrd_start && !initrd_below_start_ok &&
 	    page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
lib/Kconfig +15 -0
index e96089499371..0d526c004e81 100644
@@ -287,6 +287,21 @@ config DECOMPRESS_LZ4
 config GENERIC_ALLOCATOR
 	bool
 
+config GENERIC_ALLOCATOR_SELFTEST
+	bool "genalloc tester"
+	default n
+	select GENERIC_ALLOCATOR
+	help
+	  Enable automated testing of the generic allocator.
+	  The testing is primarily for the tracking of allocated space.
+
+config GENERIC_ALLOCATOR_SELFTEST_VERBOSE
+	bool "make the genalloc tester more verbose"
+	default n
+	select GENERIC_ALLOCATOR_SELFTEST
+	help
+	  More information will be displayed during the self-testing.
+
 #
 # reed solomon support is select'ed if needed
 #
lib/Makefile +1 -0
index a90d4fcd748f..fadb30abde08 100644
@@ -108,6 +108,7 @@ obj-$(CONFIG_LIBCRC32C)	+= libcrc32c.o
 obj-$(CONFIG_CRC8)	+= crc8.o
 obj-$(CONFIG_XXHASH)	+= xxhash.o
 obj-$(CONFIG_GENERIC_ALLOCATOR) += genalloc.o
+obj-$(CONFIG_GENERIC_ALLOCATOR_SELFTEST) += genalloc-selftest.o
 
 obj-$(CONFIG_842_COMPRESS) += 842/
 obj-$(CONFIG_842_DECOMPRESS) += 842/
lib/genalloc-selftest.c new file +400 -0

400 lines not on this page · raw message

Signature · 1 line
2.14.1
#7 lore raw

Re: [PATCH 2/6] genalloc: selftest

Quoted 10 lines · Igor Stoppa

Introduce a set of macros for writing concise test cases for genalloc.

The test cases are meant to provide regression testing, when working on new functionality for genalloc.

Primarily they are meant to confirm that the various allocation strategy will continue to work as expected.

The execution of the self testing is controlled through a Kconfig option.

Quoted 7 lines
---
 include/linux/genalloc-selftest.h |  26 +++
 init/main.c                       |   2 +
 lib/Kconfig                       |  15 ++
 lib/Makefile                      |   1 +
 lib/genalloc-selftest.c           | 400 ++++++++++++++++++++++++++++++++++++++

Nit: make this test_genalloc.c instead.

Quoted 49 lines
 5 files changed, 444 insertions(+)
 create mode 100644 include/linux/genalloc-selftest.h
 create mode 100644 lib/genalloc-selftest.c
include/linux/genalloc-selftest.h new file +26 -0
new file mode 100644
index 000000000000..e0ac8f963abc
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * genalloc-selftest.h
+ *
+ * (C) Copyright 2017 Huawei Technologies Co. Ltd.
+ * Author: Igor Stoppa <[email protected]>
+ */
+
+
+#ifndef __LINUX_GENALLOC_SELFTEST_H
+#define __LINUX_GENALLOC_SELFTEST_H
+
+
+#ifdef CONFIG_GENERIC_ALLOCATOR_SELFTEST
+
+#include <linux/genalloc.h>
+
+void genalloc_selftest(void);
+
+#else
+
+static inline void genalloc_selftest(void){};
+
+#endif
+
+#endif
init/main.c +1 -0
index a8100b954839..fb844aa3eb8c 100644
@@ -89,6 +89,7 @@
 #include <linux/io.h>
 #include <linux/cache.h>
 #include <linux/rodata_test.h>
+#include <linux/genalloc-selftest.h>
 
 #include <asm/io.h>
 #include <asm/bugs.h>

init/main.c asmlinkage __visible void __init start_kernel(void) · line 664

Quoted 4 lines
init/main.c +1 -0
@@ -660,6 +661,7 @@ asmlinkage __visible void __init start_kernel(void)
         */
        mem_encrypt_init();
 
+       genalloc_selftest();

I wonder if it's possible to make this module-loadable instead? That way it could be built and tested separately. Regardless, I love gaining more internal selftests, this is great. :)

lib/Kconfig config DECOMPRESS_LZ4 · line 290

Quoted 12 lines
init/main.c +0 -0
 #ifdef CONFIG_BLK_DEV_INITRD
        if (initrd_start && !initrd_below_start_ok &&
            page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
lib/Kconfig +1 -0
index e96089499371..0d526c004e81 100644
@@ -287,6 +287,21 @@ config DECOMPRESS_LZ4
 config GENERIC_ALLOCATOR
        bool
 
+config GENERIC_ALLOCATOR_SELFTEST

Like the other lib/test_*.c targets, I'd call this TEST_GENERIC_ALLOCATOR.

Quoted 206 lines
lib/Kconfig +14 -0
+       bool "genalloc tester"
+       default n
+       select GENERIC_ALLOCATOR
+       help
+         Enable automated testing of the generic allocator.
+         The testing is primarily for the tracking of allocated space.
+
+config GENERIC_ALLOCATOR_SELFTEST_VERBOSE
+       bool "make the genalloc tester more verbose"
+       default n
+       select GENERIC_ALLOCATOR_SELFTEST
+       help
+         More information will be displayed during the self-testing.
+
 #
 # reed solomon support is select'ed if needed
 #
lib/Makefile +1 -0
index a90d4fcd748f..fadb30abde08 100644
@@ -108,6 +108,7 @@ obj-$(CONFIG_LIBCRC32C)     += libcrc32c.o
 obj-$(CONFIG_CRC8)     += crc8.o
 obj-$(CONFIG_XXHASH)   += xxhash.o
 obj-$(CONFIG_GENERIC_ALLOCATOR) += genalloc.o
+obj-$(CONFIG_GENERIC_ALLOCATOR_SELFTEST) += genalloc-selftest.o
 
 obj-$(CONFIG_842_COMPRESS) += 842/
 obj-$(CONFIG_842_DECOMPRESS) += 842/
lib/genalloc-selftest.c new file +171 -0
new file mode 100644
index 000000000000..e86be22c5512
@@ -0,0 +1,400 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * genalloc-selftest.c
+ *
+ * (C) Copyright 2017 Huawei Technologies Co. Ltd.
+ * Author: Igor Stoppa <[email protected]>
+ */
+
+#include <linux/module.h>
+#include <linux/printk.h>
+#include <linux/init.h>
+#include <linux/vmalloc.h>
+#include <linux/string.h>
+#include <linux/debugfs.h>
+#include <linux/atomic.h>
+#include <linux/genalloc.h>
+
+#include <linux/genalloc-selftest.h>
+/*
+ * Keep the bitmap small, while including case of cross-ulong mapping.
+ * For simplicity, the test cases use only 1 chunk of memory.
+ */
+#define BITMAP_SIZE_C 16
+#define ALLOC_ORDER 0
+
+#define ULONG_SIZE (sizeof(unsigned long))
+#define BITMAP_SIZE_UL (BITMAP_SIZE_C / ULONG_SIZE)
+#define MIN_ALLOC_SIZE (1 << ALLOC_ORDER)
+#define ENTRIES (BITMAP_SIZE_C * 8)
+#define CHUNK_SIZE  (MIN_ALLOC_SIZE * ENTRIES)
+
+#ifndef CONFIG_GENERIC_ALLOCATOR_SELFTEST_VERBOSE
+
+static inline void print_first_chunk_bitmap(struct gen_pool *pool) {}
+
+#else
+
+static void print_first_chunk_bitmap(struct gen_pool *pool)
+{
+       struct gen_pool_chunk *chunk;
+       char bitmap[BITMAP_SIZE_C * 2 + 1];
+       unsigned long i;
+       char *bm = bitmap;
+       char *entry;
+
+       if (unlikely(pool == NULL || pool->chunks.next == NULL))
+               return;
+
+       chunk = container_of(pool->chunks.next, struct gen_pool_chunk,
+                            next_chunk);
+       entry = (void *)chunk->entries;
+       for (i = 1; i <= BITMAP_SIZE_C; i++)
+               bm += snprintf(bm, 3, "%02hhx", entry[BITMAP_SIZE_C - i]);
+       *bm = '\0';
+       pr_notice("chunk: %p    bitmap: 0x%s\n", chunk, bitmap);
+
+}
+
+#endif
+
+enum test_commands {
+       CMD_ALLOCATOR,
+       CMD_ALLOCATE,
+       CMD_FLUSH,
+       CMD_FREE,
+       CMD_NUMBER,
+       CMD_END = CMD_NUMBER,
+};
+
+struct null_struct {
+       void *null;
+};
+
+struct test_allocator {
+       genpool_algo_t algo;
+       union {
+               struct genpool_data_align align;
+               struct genpool_data_fixed offset;
+               struct null_struct null;
+       } data;
+};
+
+struct test_action {
+       unsigned int location;
+       char pattern[BITMAP_SIZE_C];
+       unsigned int size;
+};
+
+
+struct test_command {
+       enum test_commands command;
+       union {
+               struct test_allocator allocator;
+               struct test_action action;
+       };
+};
+
+
+/*
+ * To pass an array literal as parameter to a macro, it must go through
+ * this one, first.
+ */
+#define ARR(...) __VA_ARGS__
+
+#define SET_DATA(parameter, value)     \
+       .parameter = {                  \
+               .parameter = value,     \
+       }                               \
+
+#define SET_ALLOCATOR(alloc, parameter, value)         \
+{                                                      \
+       .command = CMD_ALLOCATOR,                       \
+       .allocator = {                                  \
+               .algo = (alloc),                        \
+               .data = {                               \
+                       SET_DATA(parameter, value),     \
+               },                                      \
+       }                                               \
+}
+
+#define ACTION_MEM(act, mem_size, mem_loc, match)      \
+{                                                      \
+       .command = act,                                 \
+       .action = {                                     \
+               .size = (mem_size),                     \
+               .location = (mem_loc),                  \
+               .pattern = match,                       \
+       },                                              \
+}
+
+#define ALLOCATE_MEM(mem_size, mem_loc, match) \
+       ACTION_MEM(CMD_ALLOCATE, mem_size, mem_loc, ARR(match))
+
+#define FREE_MEM(mem_size, mem_loc, match)     \
+       ACTION_MEM(CMD_FREE, mem_size, mem_loc, ARR(match))
+
+#define FLUSH_MEM()            \
+{                              \
+       .command = CMD_FLUSH,   \
+}
+
+#define END()                  \
+{                              \
+       .command = CMD_END,     \
+}
+
+static inline int compare_bitmaps(const struct gen_pool *pool,
+                                  const char *reference)
+{
+       struct gen_pool_chunk *chunk;
+       char *bitmap;
+       unsigned int i;
+
+       chunk = container_of(pool->chunks.next, struct gen_pool_chunk,
+                            next_chunk);
+       bitmap = (char *)chunk->entries;
+
+       for (i = 0; i < BITMAP_SIZE_C; i++)
+               if (bitmap[i] != reference[i])
+                       return -1;
+       return 0;
+}
+
+static void callback_set_allocator(struct gen_pool *pool,
+                                  const struct test_command *cmd,
+                                  unsigned long *locations)
+{
+       gen_pool_set_algo(pool, cmd->allocator.algo,
+                         (void *)&cmd->allocator.data);
+}
+

lib/genalloc-selftest.c line 181

Quoted 10 lines
lib/genalloc-selftest.c new file +10 -0
+static void callback_allocate(struct gen_pool *pool,
+                             const struct test_command *cmd,
+                             unsigned long *locations)
+{
+       const struct test_action *action = &cmd->action;
+
+       locations[action->location] = gen_pool_alloc(pool, action->size);
+       BUG_ON(!locations[action->location]);
+       print_first_chunk_bitmap(pool);
+       BUG_ON(compare_bitmaps(pool, action->pattern));

There's been a lot recently on BUG vs WARN. It does seem crazy to not BUG for an allocator selftest, but if we can avoid it, we should.

Also, I wonder if it might make sense to split this series up a little more, as in:

1/n: add genalloc selftest
2/n: update bitmaps
3/n: add/change bitmap tests to selftest

Maybe I'm over-thinking it, but the great thing about this self test is that it's checking much more than just the bitmap changes you're making, and that can be used to "prove" that genalloc continues to work after the changes (i.e. the selftest passes before the changes, and after, rather than just after).

Quoted 220 lines
lib/genalloc-selftest.c new file +219 -1
+}
+
+static void callback_flush(struct gen_pool *pool,
+                         const struct test_command *cmd,
+                         unsigned long *locations)
+{
+       unsigned int i;
+
+       for (i = 0; i < ENTRIES; i++)
+               if (locations[i]) {
+                       gen_pool_free(pool, locations[i], 0);
+                       locations[i] = 0;
+               }
+}
+
+static void callback_free(struct gen_pool *pool,
+                         const struct test_command *cmd,
+                         unsigned long *locations)
+{
+       const struct test_action *action = &cmd->action;
+
+       gen_pool_free(pool, locations[action->location], 0);
+       locations[action->location] = 0;
+       print_first_chunk_bitmap(pool);
+       BUG_ON(compare_bitmaps(pool, action->pattern));
+}
+
+static void (* const callbacks[CMD_NUMBER])(struct gen_pool *,
+                                           const struct test_command *,
+                                           unsigned long *) = {
+       [CMD_ALLOCATOR] = callback_set_allocator,
+       [CMD_ALLOCATE] = callback_allocate,
+       [CMD_FREE] = callback_free,
+       [CMD_FLUSH] = callback_flush,
+};
+
+static const struct test_command test_first_fit[] = {
+       SET_ALLOCATOR(gen_pool_first_fit, null, NULL),
+       ALLOCATE_MEM(3, 0, ARR({0x2b})),
+       ALLOCATE_MEM(2, 1, ARR({0xeb, 0x02})),
+       ALLOCATE_MEM(5, 2, ARR({0xeb, 0xae, 0x0a})),
+       FREE_MEM(2, 1,  ARR({0x2b, 0xac, 0x0a})),
+       ALLOCATE_MEM(1, 1, ARR({0xeb, 0xac, 0x0a})),
+       FREE_MEM(0, 2,  ARR({0xeb})),
+       FREE_MEM(0, 0,  ARR({0xc0})),
+       FREE_MEM(0, 1,  ARR({0x00})),
+       END(),
+};
+
+/*
+ * To make the test work for both 32bit and 64bit ulong sizes,
+ * allocate (8 / 2 * 4 - 1) = 15 bytes bytes, then 16, then 2.
+ * The first allocation prepares for the crossing of the 32bit ulong
+ * threshold. The following crosses the 32bit threshold and prepares for
+ * crossing the 64bit thresholds. The last is large enough (2 bytes) to
+ * cross the 64bit threshold.
+ * Then free the allocations in the order: 2nd, 1st, 3rd.
+ */
+static const struct test_command test_ulong_span[] = {
+       SET_ALLOCATOR(gen_pool_first_fit, null, NULL),
+       ALLOCATE_MEM(15, 0, ARR({0xab, 0xaa, 0xaa, 0x2a})),
+       ALLOCATE_MEM(16, 1, ARR({0xab, 0xaa, 0xaa, 0xea,
+                               0xaa, 0xaa, 0xaa, 0x2a})),
+       ALLOCATE_MEM(2, 2, ARR({0xab, 0xaa, 0xaa, 0xea,
+                              0xaa, 0xaa, 0xaa, 0xea,
+                              0x02})),
+       FREE_MEM(0, 1, ARR({0xab, 0xaa, 0xaa, 0x2a,
+                          0x00, 0x00, 0x00, 0xc0,
+                          0x02})),
+       FREE_MEM(0, 0, ARR({0x00, 0x00, 0x00, 0x00,
+                          0x00, 0x00, 0x00, 0xc0,
+                          0x02})),
+       FREE_MEM(0, 2, ARR({0x00})),
+       END(),
+};
+
+/*
+ * Create progressively smaller allocations A B C D E.
+ * then free B and D.
+ * Then create new allocation that would fit in both of the gaps left by
+ * B and D. Verify that it uses the gap from B.
+ */
+static const struct test_command test_first_fit_gaps[] = {
+       SET_ALLOCATOR(gen_pool_first_fit, null, NULL),
+       ALLOCATE_MEM(10, 0, ARR({0xab, 0xaa, 0x0a})),
+       ALLOCATE_MEM(8, 1, ARR({0xab, 0xaa, 0xba, 0xaa,
+                              0x0a})),
+       ALLOCATE_MEM(6, 2, ARR({0xab, 0xaa, 0xba, 0xaa,
+                              0xba, 0xaa})),
+       ALLOCATE_MEM(4, 3, ARR({0xab, 0xaa, 0xba, 0xaa,
+                              0xba, 0xaa, 0xab})),
+       ALLOCATE_MEM(2, 4, ARR({0xab, 0xaa, 0xba, 0xaa,
+                              0xba, 0xaa, 0xab, 0x0b})),
+       FREE_MEM(0, 1, ARR({0xab, 0xaa, 0x0a, 0x00,
+                          0xb0, 0xaa, 0xab, 0x0b})),
+       FREE_MEM(0, 3, ARR({0xab, 0xaa, 0x0a, 0x00,
+                          0xb0, 0xaa, 0x00, 0x0b})),
+       ALLOCATE_MEM(3, 3, ARR({0xab, 0xaa, 0xba, 0x02,
+                              0xb0, 0xaa, 0x00, 0x0b})),
+       FLUSH_MEM(),
+       END(),
+};
+
+/* Test first fit align */
+static const struct test_command test_first_fit_align[] = {
+       SET_ALLOCATOR(gen_pool_first_fit_align, align, 4),
+       ALLOCATE_MEM(5, 0, ARR({0xab, 0x02})),
+       ALLOCATE_MEM(3, 1, ARR({0xab, 0x02, 0x2b})),
+       ALLOCATE_MEM(2, 2, ARR({0xab, 0x02, 0x2b, 0x0b})),
+       ALLOCATE_MEM(1, 3, ARR({0xab, 0x02, 0x2b, 0x0b, 0x03})),
+       FREE_MEM(0, 0, ARR({0x00, 0x00, 0x2b, 0x0b, 0x03})),
+       FREE_MEM(0, 2, ARR({0x00, 0x00, 0x2b, 0x00, 0x03})),
+       ALLOCATE_MEM(2, 0, ARR({0x0b, 0x00, 0x2b, 0x00, 0x03})),
+       FLUSH_MEM(),
+       END(),
+};
+
+
+/* Test fixed alloc */
+static const struct test_command test_fixed_data[] = {
+       SET_ALLOCATOR(gen_pool_fixed_alloc, offset, 1),
+       ALLOCATE_MEM(5, 0, ARR({0xac, 0x0a})),
+       SET_ALLOCATOR(gen_pool_fixed_alloc, offset, 8),
+       ALLOCATE_MEM(3, 1, ARR({0xac, 0x0a, 0x2b})),
+       SET_ALLOCATOR(gen_pool_fixed_alloc, offset, 6),
+       ALLOCATE_MEM(2, 2, ARR({0xac, 0xba, 0x2b})),
+       SET_ALLOCATOR(gen_pool_fixed_alloc, offset, 30),
+       ALLOCATE_MEM(40, 3, ARR({0xac, 0xba, 0x2b, 0x00,
+                               0x00, 0x00, 0x00, 0xb0,
+                               0xaa, 0xaa, 0xaa, 0xaa,
+                               0xaa, 0xaa, 0xaa, 0xaa})),
+       FLUSH_MEM(),
+       END(),
+};
+
+
+/* Test first fit order align */
+static const struct test_command test_first_fit_order_align[] = {
+       SET_ALLOCATOR(gen_pool_first_fit_order_align, null, NULL),
+       ALLOCATE_MEM(5, 0, ARR({0xab, 0x02})),
+       ALLOCATE_MEM(3, 1, ARR({0xab, 0x02, 0x2b})),
+       ALLOCATE_MEM(2, 2, ARR({0xab, 0xb2, 0x2b})),
+       ALLOCATE_MEM(1, 3, ARR({0xab, 0xbe, 0x2b})),
+       ALLOCATE_MEM(1, 4, ARR({0xab, 0xbe, 0xeb})),
+       ALLOCATE_MEM(2, 5, ARR({0xab, 0xbe, 0xeb, 0x0b})),
+       FLUSH_MEM(),
+       END(),
+};
+
+
+/* 007 Test best fit */
+static const struct test_command test_best_fit[] = {
+       SET_ALLOCATOR(gen_pool_best_fit, null, NULL),
+       ALLOCATE_MEM(5, 0, ARR({0xab, 0x02})),
+       ALLOCATE_MEM(3, 1, ARR({0xab, 0xae})),
+       ALLOCATE_MEM(3, 2, ARR({0xab, 0xae, 0x2b})),
+       ALLOCATE_MEM(1, 3, ARR({0xab, 0xae, 0xeb})),
+       FREE_MEM(0, 0, ARR({0x00, 0xac, 0xeb})),
+       FREE_MEM(0, 2, ARR({0x00, 0xac, 0xc0})),
+       ALLOCATE_MEM(2, 0, ARR({0x00, 0xac, 0xcb})),
+       FLUSH_MEM(),
+       END(),
+};
+
+
+enum test_cases_indexes {
+       TEST_CASE_FIRST_FIT,
+       TEST_CASE_ULONG_SPAN,
+       TEST_CASE_FIRST_FIT_GAPS,
+       TEST_CASE_FIRST_FIT_ALIGN,
+       TEST_CASE_FIXED_DATA,
+       TEST_CASE_FIRST_FIT_ORDER_ALIGN,
+       TEST_CASE_BEST_FIT,
+       TEST_CASES_NUM,
+};
+
+static const struct test_command *test_cases[TEST_CASES_NUM] = {
+       [TEST_CASE_FIRST_FIT] = test_first_fit,
+       [TEST_CASE_ULONG_SPAN] = test_ulong_span,
+       [TEST_CASE_FIRST_FIT_GAPS] = test_first_fit_gaps,
+       [TEST_CASE_FIRST_FIT_ALIGN] = test_first_fit_align,
+       [TEST_CASE_FIXED_DATA] = test_fixed_data,
+       [TEST_CASE_FIRST_FIT_ORDER_ALIGN] = test_first_fit_order_align,
+       [TEST_CASE_BEST_FIT] = test_best_fit,
+};
+
+
+void genalloc_selftest(void)
+{
+       static struct gen_pool *pool;
+       unsigned long locations[ENTRIES];
+       char chunk[CHUNK_SIZE];
+       int retval;
+       unsigned int i;
+       const struct test_command *cmd;
+
+       pool = gen_pool_create(ALLOC_ORDER, -1);
+       if (unlikely(!pool)) {
+               pr_err("genalloc-selftest: no memory for pool.");
+               return;
+       }
+
+       retval = gen_pool_add_virt(pool, (unsigned long)chunk, 0,
+                                  CHUNK_SIZE, -1);
+       if (unlikely(retval)) {
+               pr_err("genalloc-selftest: could not register chunk.");
+               goto destroy_pool;
+       }
+
+       memset(locations, 0, ENTRIES * sizeof(unsigned long));
+       for (i = 0; i < TEST_CASES_NUM; i++)
+               for (cmd = test_cases[i]; cmd->command < CMD_END; cmd++)
+                       callbacks[cmd->command](pool, cmd, locations);
+       pr_notice("genalloc-selftest: executed successfully %d tests",
+                 TEST_CASES_NUM);
+
+destroy_pool:
+       gen_pool_destroy(pool);
+}
--
Quoted 2 lines

2.14.1

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#8 lore raw

Re: [PATCH 2/6] genalloc: selftest

Quoted 1 line · Kees Cook

On Mon, Feb 12, 2018 at 8:52 AM, Igor Stoppa <[email protected]> wrote:

[...]

Quoted 3 lines
Quoted 1 line
 lib/genalloc-selftest.c           | 400 ++++++++++++++++++++++++++++++++++++++

Nit: make this test_genalloc.c instead.

ok

[...]

Quoted 4 lines
Quoted 1 line

+ genalloc_selftest();

I wonder if it's possible to make this module-loadable instead? That way it could be built and tested separately.

In my case modules are not an option.
Of course it could be still built in, but what is the real gain?

[...]

Quoted 3 lines
Quoted 1 line

+config GENERIC_ALLOCATOR_SELFTEST

Like the other lib/test_*.c targets, I'd call this TEST_GENERIC_ALLOCATOR.

ok

[...]

Quoted 4 lines
Quoted 1 line

+ BUG_ON(compare_bitmaps(pool, action->pattern));

There's been a lot recently on BUG vs WARN. It does seem crazy to not BUG for an allocator selftest, but if we can avoid it, we should.

If this fails, I would expect that memory corruption is almost guaranteed. Do we really want to allow the boot to continue, possibly mounting a filesystem, only to corrupt it? It seems very dangerous.

Quoted 7 lines

Also, I wonder if it might make sense to split this series up a little more, as in:

1/n: add genalloc selftest
2/n: update bitmaps
3/n: add/change bitmap tests to selftest

Quoted 5 lines

Maybe I'm over-thinking it, but the great thing about this self test is that it's checking much more than just the bitmap changes you're making, and that can be used to "prove" that genalloc continues to work after the changes (i.e. the selftest passes before the changes, and after, rather than just after).

If I really have to ... but to me the evidence that the changes to the bitmaps do really work is already provided by the bitmap patch itself.

Since the patch doesn't remove the parameter indicating the space to be freed, it can actually compare what the kernel passes to it vs. what it thinks the space should be.

If the values were different, it would complain, but it doesn't ... Isn't that even stronger evidence that the bitmap changes work as expected?

(eventually the parameter can be removed, but I intentionally left it, for facilitating the merge)

--
igor

#9 lore raw

Re: [PATCH 2/6] genalloc: selftest

Quoted 15 lines · Igor Stoppa
Quoted 1 line · Kees Cook

On Mon, Feb 12, 2018 at 8:52 AM, Igor Stoppa <[email protected]> wrote:

[...]

Quoted 3 lines
Quoted 1 line
 lib/genalloc-selftest.c           | 400 ++++++++++++++++++++++++++++++++++++++

Nit: make this test_genalloc.c instead.

ok

[...]

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

+ genalloc_selftest();

I wonder if it's possible to make this module-loadable instead? That way it could be built and tested separately.

In my case modules are not an option.
Of course it could be still built in, but what is the real gain?

The gain for it being a module is that it can be loaded and tested separately from the final kernel image and module collection. For example, Chrome OS builds lots of debugging test modules but doesn't include them on the final image. They're only used for testing, and can be separate from the kernel and "production" modules.

Quoted 10 lines

[...]

Quoted 4 lines
Quoted 1 line

+ BUG_ON(compare_bitmaps(pool, action->pattern));

There's been a lot recently on BUG vs WARN. It does seem crazy to not BUG for an allocator selftest, but if we can avoid it, we should.

If this fails, I would expect that memory corruption is almost guaranteed. Do we really want to allow the boot to continue, possibly mounting a filesystem, only to corrupt it? It seems very dangerous.

I would include the rationale in either a comment or the commit log. BUG() tends to need to be very well justified these days.

Quoted 20 lines
Quoted 7 lines

Also, I wonder if it might make sense to split this series up a little more, as in:

1/n: add genalloc selftest
2/n: update bitmaps
3/n: add/change bitmap tests to selftest

Quoted 5 lines

Maybe I'm over-thinking it, but the great thing about this self test is that it's checking much more than just the bitmap changes you're making, and that can be used to "prove" that genalloc continues to work after the changes (i.e. the selftest passes before the changes, and after, rather than just after).

If I really have to ... but to me the evidence that the changes to the bitmaps do really work is already provided by the bitmap patch itself.

Since the patch doesn't remove the parameter indicating the space to be freed, it can actually compare what the kernel passes to it vs. what it thinks the space should be.

Quoted 5 lines

If the values were different, it would complain, but it doesn't ... Isn't that even stronger evidence that the bitmap changes work as expected?

(eventually the parameter can be removed, but I intentionally left it, for facilitating the merge)

I'll leave it up to the -mm folks, but that was just my thought.

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#10 lore raw

Re: [PATCH 2/6] genalloc: selftest

Quoted 5 lines · Kees Cook
Quoted 4 lines · Igor Stoppa
Quoted 1 line · Kees Cook

On Mon, Feb 12, 2018 at 8:52 AM, Igor Stoppa <[email protected]> wrote:

[...]

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
Quoted 1 line

+ genalloc_selftest();

I wonder if it's possible to make this module-loadable instead? That way it could be built and tested separately.

Quoted 8 lines
Quoted 2 lines

In my case modules are not an option.
Of course it could be still built in, but what is the real gain?

The gain for it being a module is that it can be loaded and tested separately from the final kernel image and module collection. For example, Chrome OS builds lots of debugging test modules but doesn't include them on the final image. They're only used for testing, and can be separate from the kernel and "production" modules.

ok

Quoted 8 lines
Quoted 8 lines

[...]

Quoted 4 lines
Quoted 1 line

+ BUG_ON(compare_bitmaps(pool, action->pattern));

There's been a lot recently on BUG vs WARN. It does seem crazy to not BUG for an allocator selftest, but if we can avoid it, we should.

Quoted 6 lines
Quoted 3 lines

If this fails, I would expect that memory corruption is almost guaranteed. Do we really want to allow the boot to continue, possibly mounting a filesystem, only to corrupt it? It seems very dangerous.

I would include the rationale in either a comment or the commit log. BUG() tends to need to be very well justified these days.

ok

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

Also, I wonder if it might make sense to split this series up a little more, as in:

1/n: add genalloc selftest
2/n: update bitmaps
3/n: add/change bitmap tests to selftest

[...]

Quoted 1 line

I'll leave it up to the -mm folks, but that was just my thought.

The reasons why I have doubts about your proposal are:

1) leaving 2/n and 3/n separate mean that the selftest could be broken, if one does bisections with selftest enabled

2) since I would need to change the selftest, to make it work with the updated bitmap, it would not really prove that the change is correct.

If there was a selftest that can work without changes, after the bitmap update, I would definitely agree to introduce it first.

OTOH, as I wrote, the bitmap patch itself is already introducing verification of the calculated value (from the bitmap) against the provided value (from the call parameters).

This, unfortunately, cannot be split, because it still relies on the "find end of the allocation" capability introduced by the very same patch.

Anyway, putting aside concerns about the verification of the correctness of the patch, I still see point #1 as a problem: breaking bisectability.

Or did I not understand correctly how this works?

--
igor

#11 lore raw

Re: [PATCH 2/6] genalloc: selftest

Quoted 19 lines · Igor Stoppa
Quoted 5 lines · Kees Cook
Quoted 4 lines · Igor Stoppa
Quoted 1 line · Kees Cook

On Mon, Feb 12, 2018 at 8:52 AM, Igor Stoppa <[email protected]> wrote:

[...]

Quoted 8 lines
Quoted 7 lines
Quoted 4 lines
Quoted 1 line

+ genalloc_selftest();

I wonder if it's possible to make this module-loadable instead? That way it could be built and tested separately.

In my case modules are not an option.
Of course it could be still built in, but what is the real gain?

Quoted 7 lines
Quoted 5 lines

The gain for it being a module is that it can be loaded and tested separately from the final kernel image and module collection. For example, Chrome OS builds lots of debugging test modules but doesn't include them on the final image. They're only used for testing, and can be separate from the kernel and "production" modules.

ok

I started to turn this into a module, but after all it doesn't seem like it would give any real advantage, compared to the current implementation.

This testing is meant to catch bugs in memory management as early as possible in the boot phase, before users of genalloc start to fail in mysterious ways.

This includes, but is not limited to: MCE on x86, uncached pages provider on arm64, dma on arm.

Should genalloc fail, it's highly unlikely that the test rig would even reach the point where it can load a module and run it, even if it is located in initrd.

The test would not be run, precisely at the moment where its output would be needed the most, leaving a crash log that is hard to debug because of memory corruption.

I do not know how Chrome OS builds are organized, but I imagine that probably there is a separate test build, where options like lockdep, ubsan, etc. are enabled.

All options that cannot be left enabled in a production kernel, but are very useful for sanity checks and require a separate build.

Genalloc testing should be added there, rather than in a module, imho.

--
igor

#12 lore raw

PATCH v16 3/6 struct page: add field for vm_struct

In reply to Igor Stoppa

When a page is used for virtual memory, it is often necessary to obtian a handler to the corresponding vm_struct, which refers to the virtually continuous area generated when invoking vmalloc.

The struct page has a "mapping" field, which can be re-used, to store a pointer to the parent area. This will avoid more expensive searches.

As example, the function find_vm_area is reimplemented, to take advantage of the newly introduced field.

---
 include/linux/mm_types.h |  1 +
 mm/vmalloc.c             | 18 +++++++++++++-----
 2 files changed, 14 insertions(+), 5 deletions(-)
include/linux/mm_types.h +1 -0
index fd1af6b9591d..c3a4825e10c0 100644
@@ -84,6 +84,7 @@ struct page {
 		void *s_mem;			/* slab first object */
 		atomic_t compound_mapcount;	/* first tail page */
 		/* page_deferred_list().next	 -- second tail page */
+		struct vm_struct *area;
 	};
 
 	/* Second double word */
mm/vmalloc.c +13 -5
index 673942094328..9404ffd0ee98 100644
@@ -1466,13 +1466,16 @@ struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
  */
 struct vm_struct *find_vm_area(const void *addr)
 {
-	struct vmap_area *va;
+	struct page *page;
 
-	va = find_vmap_area((unsigned long)addr);
-	if (va && va->flags & VM_VM_AREA)
-		return va->vm;
+	if (unlikely(!is_vmalloc_addr(addr)))
+		return NULL;
 
-	return NULL;
+	page = vmalloc_to_page(addr);
+	if (unlikely(!page))
+		return NULL;
+
+	return page->area;
 }
 
 /**
@@ -1536,6 +1539,7 @@ static void __vunmap(const void *addr, int deallocate_pages)
 			struct page *page = area->pages[i];
 
 			BUG_ON(!page);
+			page->area = NULL;
 			__free_pages(page, 0);
 		}
 
@@ -1744,6 +1748,7 @@ void *__vmalloc_node_range(unsigned long size, unsigned long align,
 			const void *caller)
 {
 	struct vm_struct *area;
+	unsigned int i;
 	void *addr;
 	unsigned long real_size = size;
 
@@ -1769,6 +1774,9 @@ void *__vmalloc_node_range(unsigned long size, unsigned long align,
 
 	kmemleak_vmalloc(area, size, gfp_mask);
 
+	for (i = 0; i < area->nr_pages; i++)
+		area->pages[i]->area = area;
+
 	return addr;
 
 fail:
Signature · 1 line
2.14.1
#13 lore raw

PATCH v16 4/6 Protectable Memory

In reply to Igor Stoppa

The MMU available in many systems running Linux can often provide R/O protection to the memory pages it handles.

However, the MMU-based protection works efficiently only when said pages contain exclusively data that will not need further modifications.

Statically allocated variables can be segregated into a dedicated section, but this does not sit very well with dynamically allocated ones.

Dynamic allocation does not provide, currently, any means for grouping variables in memory pages that would contain exclusively data suitable for conversion to read only access mode.

The allocator here provided (pmalloc - protectable memory allocator) introduces the concept of pools of protectable memory.

A module can request a pool and then refer any allocation request to the pool handler it has received.

Once all the chunks of memory associated to a specific pool are initialized, the pool can be protected.

After this point, the pool can only be destroyed (it is up to the module to avoid any further references to the memory from the pool, after the destruction is invoked).

The latter case is mainly meant for releasing memory, when a module is unloaded.

A module can have as many pools as needed, for example to support the protection of data that is initialized in sufficiently distinct phases.

---
 include/linux/genalloc.h |   3 +
 include/linux/pmalloc.h  | 242 +++++++++++++++++++++++
 include/linux/vmalloc.h  |   1 +
 lib/genalloc.c           |  27 +++
 mm/Kconfig               |   6 +
 mm/Makefile              |   1 +
 mm/pmalloc.c             | 499 +++++++++++++++++++++++++++++++++++++++++++++++
 mm/usercopy.c            |  33 ++++
 8 files changed, 812 insertions(+)
 create mode 100644 include/linux/pmalloc.h
 create mode 100644 mm/pmalloc.c
include/linux/genalloc.h +3 -0
index dcaa33e74b1c..b6c4cea9fbd8 100644
@@ -121,6 +121,9 @@ extern unsigned long gen_pool_alloc_algo(struct gen_pool *, size_t,
 extern void *gen_pool_dma_alloc(struct gen_pool *pool, size_t size,
 		dma_addr_t *dma);
 extern void gen_pool_free(struct gen_pool *, unsigned long, size_t);
+
+extern void gen_pool_flush_chunk(struct gen_pool *pool,
+				 struct gen_pool_chunk *chunk);
 extern void gen_pool_for_each_chunk(struct gen_pool *,
 	void (*)(struct gen_pool *, struct gen_pool_chunk *, void *), void *);
 extern size_t gen_pool_avail(struct gen_pool *);
include/linux/pmalloc.h new file +242 -0

242 lines not on this page · raw message

include/linux/vmalloc.h +1 -0
index 1e5d8c392f15..116d280cca53 100644
@@ -20,6 +20,7 @@ struct notifier_block;		/* in notifier.h */
 #define VM_UNINITIALIZED	0x00000020	/* vm_struct is not fully initialized */
 #define VM_NO_GUARD		0x00000040      /* don't add guard page */
 #define VM_KASAN		0x00000080      /* has allocated kasan shadow memory */
+#define VM_PMALLOC		0x00000100	/* pmalloc area - see docs */
 /* bits [20..32] reserved for arch specific ioremap internals */
 
 /*
lib/genalloc.c +27 -0
index 87f62f31b52f..24ed35035095 100644
@@ -625,6 +625,33 @@ void gen_pool_free(struct gen_pool *pool, unsigned long addr, size_t size)
 }
 EXPORT_SYMBOL(gen_pool_free);
 
+
+/**
+ * gen_pool_flush_chunk() - drops all the allocations from a specific chunk
+ * @pool:	the generic memory pool
+ * @chunk:	The chunk to wipe clear.
+ *
+ * This is meant to be called only while destroying a pool. It's up to the
+ * caller to avoid races, but really, at this point the pool should have
+ * already been retired and it should have become unavailable for any other
+ * sort of operation.
+ */
+void gen_pool_flush_chunk(struct gen_pool *pool,
+			  struct gen_pool_chunk *chunk)
+{
+	size_t size;
+
+	if (unlikely(!(pool && chunk)))
+		return;
+
+	size = chunk->end_addr + 1 - chunk->start_addr;
+	memset(chunk->entries, 0,
+	       DIV_ROUND_UP(size >> pool->min_alloc_order * BITS_PER_ENTRY,
+			    BITS_PER_BYTE));
+	atomic_long_set(&chunk->avail, size);
+}
+
+
 /**
  * gen_pool_for_each_chunk() - call func for every chunk of generic memory pool
  * @pool:	the generic memory pool
mm/Kconfig +6 -0
index c782e8fb7235..be578fbdce6d 100644
@@ -760,3 +760,9 @@ config GUP_BENCHMARK
 	  performance of get_user_pages_fast().
 
 	  See tools/testing/selftests/vm/gup_benchmark.c
+
+config PROTECTABLE_MEMORY
+    bool
+    depends on ARCH_HAS_SET_MEMORY
+    select GENERIC_ALLOCATOR
+    default y
mm/Makefile +1 -0
index e669f02c5a54..959fdbdac118 100644
@@ -65,6 +65,7 @@ obj-$(CONFIG_SPARSEMEM)	+= sparse.o
 obj-$(CONFIG_SPARSEMEM_VMEMMAP) += sparse-vmemmap.o
 obj-$(CONFIG_SLOB) += slob.o
 obj-$(CONFIG_MMU_NOTIFIER) += mmu_notifier.o
+obj-$(CONFIG_PROTECTABLE_MEMORY) += pmalloc.o
 obj-$(CONFIG_KSM) += ksm.o
 obj-$(CONFIG_PAGE_POISONING) += page_poison.o
 obj-$(CONFIG_SLAB) += slab.o
mm/pmalloc.c new file +499 -0

499 lines not on this page · raw message

mm/usercopy.c +33 -0
index e9e9325f7638..946ce051e296 100644
@@ -240,6 +240,36 @@ static inline void check_heap_object(const void *ptr, unsigned long n,
 	}
 }
 
+#ifdef CONFIG_PROTECTABLE_MEMORY
+
+int is_pmalloc_object(const void *ptr, const unsigned long n);
+
+static void check_pmalloc_object(const void *ptr, unsigned long n,
+				 bool to_user)
+{
+	int retv;
+
+	retv = is_pmalloc_object(ptr, n);
+	if (unlikely(retv)) {
+		if (unlikely(!to_user))
+			usercopy_abort("pmalloc",
+				       "trying to write to pmalloc object",
+				       to_user, (const unsigned long)ptr, n);
+		if (retv < 0)
+			usercopy_abort("pmalloc",
+				       "invalid pmalloc object",
+				       to_user, (const unsigned long)ptr, n);
+	}
+}
+
+#else
+
+static void check_pmalloc_object(const void *ptr, unsigned long n,
+				 bool to_user)
+{
+}
+#endif
+
 /*
  * Validates that the given object is:
  * - not bogus address
@@ -277,5 +307,8 @@ void __check_object_size(const void *ptr, unsigned long n, bool to_user)
 
 	/* Check for object in kernel to avoid text exposure. */
 	check_kernel_text_object((const unsigned long)ptr, n, to_user);
+
+	/* Check if object is from a pmalloc chunk. */
+	check_pmalloc_object(ptr, n, to_user);
 }
 EXPORT_SYMBOL(__check_object_size);
Signature · 1 line
2.14.1
#14 lore raw

PATCH v16 5/6 Pmalloc: self-test

In reply to Igor Stoppa

Add basic self-test functionality for pmalloc.

---
 mm/Kconfig            |  9 ++++++++
 mm/Makefile           |  1 +
 mm/pmalloc-selftest.c | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++
 mm/pmalloc-selftest.h | 24 +++++++++++++++++++
 mm/pmalloc.c          |  2 ++
 5 files changed, 100 insertions(+)
 create mode 100644 mm/pmalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.h
mm/Kconfig +9 -0
index be578fbdce6d..098aefef78b1 100644
@@ -766,3 +766,12 @@ config PROTECTABLE_MEMORY
     depends on ARCH_HAS_SET_MEMORY
     select GENERIC_ALLOCATOR
     default y
+
+config PROTECTABLE_MEMORY_SELFTEST
+	bool "Run self test for pmalloc memory allocator"
+	depends on ARCH_HAS_SET_MEMORY
+	select PROTECTABLE_MEMORY
+	default n
+	help
+	  Tries to verify that pmalloc works correctly and that the memory
+	  is effectively protected.
mm/Makefile +1 -0
index 959fdbdac118..f7bbbfde6967 100644
@@ -66,6 +66,7 @@ obj-$(CONFIG_SPARSEMEM_VMEMMAP) += sparse-vmemmap.o
 obj-$(CONFIG_SLOB) += slob.o
 obj-$(CONFIG_MMU_NOTIFIER) += mmu_notifier.o
 obj-$(CONFIG_PROTECTABLE_MEMORY) += pmalloc.o
+obj-$(CONFIG_PROTECTABLE_MEMORY_SELFTEST) += pmalloc-selftest.o
 obj-$(CONFIG_KSM) += ksm.o
 obj-$(CONFIG_PAGE_POISONING) += page_poison.o
 obj-$(CONFIG_SLAB) += slab.o
mm/pmalloc-selftest.c new file +64 -0

64 lines not on this page · raw message

mm/pmalloc-selftest.h new file +24 -0
new file mode 100644
index 000000000000..58a5a0cbec14
@@ -0,0 +1,24 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * pmalloc-selftest.h
+ *
+ * (C) Copyright 2018 Huawei Technologies Co. Ltd.
+ * Author: Igor Stoppa <[email protected]>
+ */
+
+
+#ifndef __MM_PMALLOC_SELFTEST_H
+#define __MM_PMALLOC_SELFTEST_H
+
+
+#ifdef CONFIG_PROTECTABLE_MEMORY_SELFTEST
+
+void pmalloc_selftest(void);
+
+#else
+
+static inline void pmalloc_selftest(void){};
+
+#endif
+
+#endif
mm/pmalloc.c +2 -0
index abddba90a9f6..eb445c574b19 100644
@@ -22,6 +22,7 @@
 #include <asm/page.h>
 
 #include <linux/pmalloc.h>
+#include "pmalloc-selftest.h"
 /*
  * pmalloc_data contains the data specific to a pmalloc pool,
  * in a format compatible with the design of gen_alloc.
@@ -494,6 +495,7 @@ static int __init pmalloc_late_init(void)
 		}
 	}
 	mutex_unlock(&pmalloc_mutex);
+	pmalloc_selftest();
 	return 0;
 }
 late_initcall(pmalloc_late_init);
Signature · 1 line
2.14.1
#15 lore raw

Re: [PATCH 5/6] Pmalloc: self-test

Quoted 35 lines · Igor Stoppa

Add basic self-test functionality for pmalloc.

---
 mm/Kconfig            |  9 ++++++++
 mm/Makefile           |  1 +
 mm/pmalloc-selftest.c | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++
 mm/pmalloc-selftest.h | 24 +++++++++++++++++++
 mm/pmalloc.c          |  2 ++
 5 files changed, 100 insertions(+)
 create mode 100644 mm/pmalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.h
mm/Kconfig +9 -0
index be578fbdce6d..098aefef78b1 100644
@@ -766,3 +766,12 @@ config PROTECTABLE_MEMORY
     depends on ARCH_HAS_SET_MEMORY
     select GENERIC_ALLOCATOR
     default y
+
+config PROTECTABLE_MEMORY_SELFTEST
+       bool "Run self test for pmalloc memory allocator"
+       depends on ARCH_HAS_SET_MEMORY
+       select PROTECTABLE_MEMORY
+       default n
+       help
+         Tries to verify that pmalloc works correctly and that the memory
+         is effectively protected.
mm/Makefile +0 -0
index 959fdbdac118..f7bbbfde6967 100644

mm/Makefile obj-$(CONFIG_SPARSEMEM_VMEMMAP) += sparse-vmemmap.o · line 69

Quoted 4 lines
mm/Makefile +1 -0
@@ -66,6 +66,7 @@ obj-$(CONFIG_SPARSEMEM_VMEMMAP) += sparse-vmemmap.o
 obj-$(CONFIG_SLOB) += slob.o
 obj-$(CONFIG_MMU_NOTIFIER) += mmu_notifier.o
 obj-$(CONFIG_PROTECTABLE_MEMORY) += pmalloc.o
+obj-$(CONFIG_PROTECTABLE_MEMORY_SELFTEST) += pmalloc-selftest.o

Nit: self-test modules are traditionally named "test_$thing.o" (outside of the tools/ directory).

Quoted 63 lines
mm/Makefile +0 -0
 obj-$(CONFIG_KSM) += ksm.o
 obj-$(CONFIG_PAGE_POISONING) += page_poison.o
 obj-$(CONFIG_SLAB) += slab.o
mm/pmalloc-selftest.c new file +54 -0
new file mode 100644
index 000000000000..97ba52d17f69
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * pmalloc-selftest.c
+ *
+ * (C) Copyright 2018 Huawei Technologies Co. Ltd.
+ * Author: Igor Stoppa <[email protected]>
+ */
+
+#include <linux/pmalloc.h>
+#include <linux/mm.h>
+
+#include "pmalloc-selftest.h"
+
+#define SIZE_1 (PAGE_SIZE * 3)
+#define SIZE_2 1000
+
+#define validate_alloc(expected, variable, size)       \
+       pr_notice("must be " expected ": %s",           \
+                 is_pmalloc_object(variable, size) > 0 ? "ok" : "no")
+
+#define is_alloc_ok(variable, size)    \
+       validate_alloc("ok", variable, size)
+
+#define is_alloc_no(variable, size)    \
+       validate_alloc("no", variable, size)
+
+void pmalloc_selftest(void)
+{
+       struct gen_pool *pool_unprot;
+       struct gen_pool *pool_prot;
+       void *var_prot, *var_unprot, *var_vmall;
+
+       pr_notice("pmalloc self-test");
+       pool_unprot = pmalloc_create_pool("unprotected", 0);
+       pool_prot = pmalloc_create_pool("protected", 0);
+       BUG_ON(!(pool_unprot && pool_prot));
+
+       var_unprot = pmalloc(pool_unprot,  SIZE_1 - 1, GFP_KERNEL);
+       var_prot = pmalloc(pool_prot,  SIZE_1, GFP_KERNEL);
+       *(int *)var_prot = 0;
+       var_vmall = vmalloc(SIZE_2);
+       is_alloc_ok(var_unprot, 10);
+       is_alloc_ok(var_unprot, SIZE_1);
+       is_alloc_ok(var_unprot, PAGE_SIZE);
+       is_alloc_no(var_unprot, SIZE_1 + 1);
+       is_alloc_no(var_vmall, 10);
+
+
+       pfree(pool_unprot, var_unprot);
+       vfree(var_vmall);
+
+       pmalloc_protect_pool(pool_prot);
+
+       /*

mm/pmalloc-selftest.c line 64

Quoted 10 lines
mm/pmalloc-selftest.c new file +10 -0
+        * This will intentionally trigger a WARN because the pool being
+        * destroyed is not protected, which is unusual and should happen
+        * on error paths only, where probably other warnings are already
+        * displayed.
+        */
+       pmalloc_destroy_pool(pool_unprot);
+
+       /* This must not cause WARNings */
+       pmalloc_destroy_pool(pool_prot);
+}

I wonder if lkdtm should grow a test too, to validate the RO-ness of the allocations at the right time in API usage?

Otherwise, yay! Selftests!

-Kees

Quoted 53 lines
mm/pmalloc-selftest.h new file +24 -0
new file mode 100644
index 000000000000..58a5a0cbec14
@@ -0,0 +1,24 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * pmalloc-selftest.h
+ *
+ * (C) Copyright 2018 Huawei Technologies Co. Ltd.
+ * Author: Igor Stoppa <[email protected]>
+ */
+
+
+#ifndef __MM_PMALLOC_SELFTEST_H
+#define __MM_PMALLOC_SELFTEST_H
+
+
+#ifdef CONFIG_PROTECTABLE_MEMORY_SELFTEST
+
+void pmalloc_selftest(void);
+
+#else
+
+static inline void pmalloc_selftest(void){};
+
+#endif
+
+#endif
mm/pmalloc.c +2 -1
index abddba90a9f6..eb445c574b19 100644
@@ -22,6 +22,7 @@
 #include <asm/page.h>
 
 #include <linux/pmalloc.h>
+#include "pmalloc-selftest.h"
 /*
  * pmalloc_data contains the data specific to a pmalloc pool,
  * in a format compatible with the design of gen_alloc.
@@ -494,6 +495,7 @@ static int __init pmalloc_late_init(void)
                }
        }
        mutex_unlock(&pmalloc_mutex);
+       pmalloc_selftest();
        return 0;
 }
 late_initcall(pmalloc_late_init);
--

2.14.1

Signature · 2 lines
Kees Cook
Pixel Security
#16 lore raw

Re: [PATCH 5/6] Pmalloc: self-test

Quoted 1 line · Kees Cook

On Mon, Feb 12, 2018 at 8:53 AM, Igor Stoppa <[email protected]> wrote:

[...]

Quoted 4 lines
Quoted 1 line

+obj-$(CONFIG_PROTECTABLE_MEMORY_SELFTEST) += pmalloc-selftest.o

Nit: self-test modules are traditionally named "test_$thing.o" (outside of the tools/ directory).

ok

[...]

Quoted 2 lines

I wonder if lkdtm should grow a test too, to validate the RO-ness of the allocations at the right time in API usage?

sorry for being dense ... are you proposing that I do something to lkdtm_rodata.c ? An example would probably help me understand.

--
igor

#17 lore raw

Re: [PATCH 5/6] Pmalloc: self-test

Quoted 13 lines · Igor Stoppa
Quoted 1 line · Kees Cook

On Mon, Feb 12, 2018 at 8:53 AM, Igor Stoppa <[email protected]> wrote:

[...]

Quoted 4 lines
Quoted 1 line

+obj-$(CONFIG_PROTECTABLE_MEMORY_SELFTEST) += pmalloc-selftest.o

Nit: self-test modules are traditionally named "test_$thing.o" (outside of the tools/ directory).

ok

Quoted 7 lines

[...]

Quoted 2 lines

I wonder if lkdtm should grow a test too, to validate the RO-ness of the allocations at the right time in API usage?

sorry for being dense ... are you proposing that I do something to lkdtm_rodata.c ? An example would probably help me understand.

It would likely live in lkdtm_perms.c (or maybe lkdtm_heap.c). Namely, use the pmalloc API and then attempt to write to a read-only variable in the pmalloc region (to prove that the permission adjustment actually happened). Likely a good example is lkdtm_WRITE_RO_AFTER_INIT().

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#18 lore raw

Re: [PATCH 5/6] Pmalloc: self-test

Quoted 1 line · Kees Cook

On Tue, Feb 20, 2018 at 8:40 AM, Igor Stoppa <[email protected]> wrote:

[...]

Quoted 8 lines
Quoted 2 lines

sorry for being dense ... are you proposing that I do something to lkdtm_rodata.c ? An example would probably help me understand.

It would likely live in lkdtm_perms.c (or maybe lkdtm_heap.c). Namely, use the pmalloc API and then attempt to write to a read-only variable in the pmalloc region (to prove that the permission adjustment actually happened). Likely a good example is lkdtm_WRITE_RO_AFTER_INIT().

ok, thanks for the explanation, I will do it

--
igor

#19 lore raw

PATCH v16 6/6 Documentation for Pmalloc

In reply to Igor Stoppa

Detailed documentation about the protectable memory allocator.

---
 Documentation/core-api/index.rst   |   1 +
 Documentation/core-api/pmalloc.rst | 114 +++++++++++++++++++++++++++++++++++++
 2 files changed, 115 insertions(+)
 create mode 100644 Documentation/core-api/pmalloc.rst
Documentation/core-api/index.rst +1 -0
index c670a8031786..8f5de42d6571 100644
@@ -25,6 +25,7 @@ Core utilities
    genalloc
    errseq
    printk-formats
+   pmalloc
 
 Interfaces for kernel debugging
 ===============================
Documentation/core-api/pmalloc.rst new file +114 -0

114 lines not on this page · raw message

Signature · 1 line
2.14.1
#20 lore raw
In reply to Igor Stoppa
Quoted 11 lines · Igor Stoppa

This patch-set introduces the possibility of protecting memory that has been allocated dynamically.

The memory is managed in pools: when a memory pool is turned into R/O, all the memory that is part of it, will become R/O.

A R/O pool can be destroyed, to recover its memory, but it cannot be turned back into R/W mode.

This is intentional. This feature is meant for data that doesn't need further modifications after initialization.

This series came up in discussions with Dave Chinner (and Matthew Wilcox, already part of the discussion, and others) at LCA. I wonder if XFS would make a good initial user of this, as it could allocate all the function pointers and other const information about a superblock in pmalloc(), keeping it separate from the R/W portions? Could other filesystems do similar things?

Do you have other immediate users in mind for pmalloc? Adding those to the series could really help both define the API and clarify the usage.

-Kees

Quoted 54 lines

However the data might need to be released, for example as part of module unloading.
To do this, the memory must first be freed, then the pool can be destroyed.

An example is provided, in the form of self-testing.

Changes since v15:
[http://www.openwall.com/lists/kernel-hardening/2018/02/11/4]

- Fixed remaining broken comments
- Fixed remaining broken "Returns" instead of "Return:" in kernel-doc
- Converted "Return:" values to lists
- Fixed SPDX license statements

Igor Stoppa (6):
genalloc: track beginning of allocations
genalloc: selftest
struct page: add field for vm_struct
Protectable Memory
Pmalloc: self-test
Documentation for Pmalloc

 Documentation/core-api/index.rst   |   1 +
 Documentation/core-api/pmalloc.rst | 114 +++++++
 include/linux/genalloc-selftest.h  |  26 ++
 include/linux/genalloc.h           |   7 +-
 include/linux/mm_types.h           |   1 +
 include/linux/pmalloc.h            | 242 ++++++++++++++
 include/linux/vmalloc.h            |   1 +
 init/main.c                        |   2 +
 lib/Kconfig                        |  15 +
 lib/Makefile                       |   1 +
 lib/genalloc-selftest.c            | 400 ++++++++++++++++++++++
 lib/genalloc.c                     | 658 +++++++++++++++++++++++++++----------
 mm/Kconfig                         |  15 +
 mm/Makefile                        |   2 +
 mm/pmalloc-selftest.c              |  64 ++++
 mm/pmalloc-selftest.h              |  24 ++
 mm/pmalloc.c                       | 501 ++++++++++++++++++++++++++++
 mm/usercopy.c                      |  33 ++
 mm/vmalloc.c                       |  18 +-
 19 files changed, 1950 insertions(+), 175 deletions(-)
 create mode 100644 Documentation/core-api/pmalloc.rst
 create mode 100644 include/linux/genalloc-selftest.h
 create mode 100644 include/linux/pmalloc.h
 create mode 100644 lib/genalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.c
 create mode 100644 mm/pmalloc-selftest.h
 create mode 100644 mm/pmalloc.c

--
2.14.1

Signature · 2 lines
Kees Cook
Pixel Security
#21 lore raw
Quoted 13 lines · Kees Cook
Quoted 11 lines · Igor Stoppa

This patch-set introduces the possibility of protecting memory that has been allocated dynamically.

The memory is managed in pools: when a memory pool is turned into R/O, all the memory that is part of it, will become R/O.

A R/O pool can be destroyed, to recover its memory, but it cannot be turned back into R/W mode.

This is intentional. This feature is meant for data that doesn't need further modifications after initialization.

Quoted 6 lines

This series came up in discussions with Dave Chinner (and Matthew Wilcox, already part of the discussion, and others) at LCA. I wonder if XFS would make a good initial user of this, as it could allocate all the function pointers and other const information about a superblock in pmalloc(), keeping it separate from the R/W portions? Could other filesystems do similar things?

I wasn't cc'd on this patchset, (please use [email protected] for future postings) so I can't really say anything about it right now. My interest for XFS was that we have a fair amount of static data in XFS that we set up at mount time and it never gets modified after that. I'm not so worried about VFS level objects (that's a much more complex issue) but there is a lot of low hanging fruit in the XFS structures we could convert to write-once structures.

Cheers,

Dave.

Signature · 2 lines
Dave Chinner
[email protected]
#22 lore raw
Quoted 21 lines · Dave Chinner
Quoted 13 lines · Kees Cook
Quoted 11 lines · Igor Stoppa

This patch-set introduces the possibility of protecting memory that has been allocated dynamically.

The memory is managed in pools: when a memory pool is turned into R/O, all the memory that is part of it, will become R/O.

A R/O pool can be destroyed, to recover its memory, but it cannot be turned back into R/W mode.

This is intentional. This feature is meant for data that doesn't need further modifications after initialization.

Quoted 6 lines

This series came up in discussions with Dave Chinner (and Matthew Wilcox, already part of the discussion, and others) at LCA. I wonder if XFS would make a good initial user of this, as it could allocate all the function pointers and other const information about a superblock in pmalloc(), keeping it separate from the R/W portions? Could other filesystems do similar things?

Quoted 2 lines

I wasn't cc'd on this patchset, (please use [email protected] for future postings)

Apologies, somehow I didn't realize that I should have put you too in CC. It will be fixed at the next iteration.

Quoted 4 lines

so I can't really say anything about it right
now. My interest for XFS was that we have a fair amount of static data in XFS that we set up at mount time and it never gets modified after that.

This is the typical use case I had in mind, although it requires a conversion.
Ex:

before:

static int a;

void set_a(void)

{
	a = 4;
}

after:

static int *a __ro_after_init;
struct gen_pool *pool;

void init_a(void)

{
	pool = pmalloc_create_pool("pool", 0);
	a = (int *)pmalloc(pool, sizeof(int), GFP_KERNEL);
}

void set_a(void)

{
	*a = 4;
	pmalloc_protect_pool(pool);
}
Quoted 3 lines

I'm not so worried about VFS level objects (that's a much more complex issue) but there is a lot of low hanging fruit in the XFS structures we could convert to write-once structures.

I'd be interested to have your review of the pmalloc API, if you think something is missing, once I send out the next revision.

--
igor

#23 lore raw
Quoted 24 lines · Igor Stoppa
Quoted 21 lines · Dave Chinner
Quoted 19 lines · Kees Cook
Quoted 11 lines · Igor Stoppa

This patch-set introduces the possibility of protecting memory that has been allocated dynamically.

The memory is managed in pools: when a memory pool is turned into R/O, all the memory that is part of it, will become R/O.

A R/O pool can be destroyed, to recover its memory, but it cannot be turned back into R/W mode.

This is intentional. This feature is meant for data that doesn't need further modifications after initialization.

This series came up in discussions with Dave Chinner (and Matthew Wilcox, already part of the discussion, and others) at LCA. I wonder if XFS would make a good initial user of this, as it could allocate all the function pointers and other const information about a superblock in pmalloc(), keeping it separate from the R/W portions? Could other filesystems do similar things?

Quoted 5 lines
Quoted 2 lines

I wasn't cc'd on this patchset, (please use [email protected] for future postings)

Apologies, somehow I didn't realize that I should have put you too in CC. It will be fixed at the next iteration.

No worries, If you weren't at LCA, you wouldn't have known :P

Quoted 32 lines
Quoted 4 lines

so I can't really say anything about it right
now. My interest for XFS was that we have a fair amount of static data in XFS that we set up at mount time and it never gets modified after that.

This is the typical use case I had in mind, although it requires a conversion.
Ex:

before:

static int a;

void set_a(void)

{
	a = 4;
}

after:

static int *a __ro_after_init;
struct gen_pool *pool;

void init_a(void)

{
	pool = pmalloc_create_pool("pool", 0);
	a = (int *)pmalloc(pool, sizeof(int), GFP_KERNEL);
}
Quoted 5 lines

void set_a(void)

{
	*a = 4;
	pmalloc_protect_pool(pool);
}

Yeah, that's kinda what I figured. I'm guessing that I treat a pool just like a normal heap allocation, but then when all the objects I need to allocate are fully initialised, then I write protect the pool? i.e. the API isn't using an object-based protection scope?

FWIW, I'm not wanting to use it to replace static variables. All the structures are dynamically allocated right now, and get assigned to other dynamically allocated pointers. I'd likely split the current structures into a "ro after init" structure and rw structure, so how does the "__ro_after_init" attribute work in that case? Is it something like this?

struct xfs_mount {
	struct xfs_mount_ro{
		.......
	} *ro __ro_after_init;
	......

Also, what compile time checks are in place to catch writes to ro structure members? Is sparse going to be able to check this sort of thing, like is does with endian-specific variables?

Quoted 2 lines

I'd be interested to have your review of the pmalloc API, if you think something is missing, once I send out the next revision.

I'll look at it in more depth when it comes past again. :P

Cheers,

Dave.

Signature · 2 lines
Dave Chinner
[email protected]
#24 lore raw
Quoted 7 lines · Dave Chinner

FWIW, I'm not wanting to use it to replace static variables. All the structures are dynamically allocated right now, and get assigned to other dynamically allocated pointers. I'd likely split the current structures into a "ro after init" structure and rw structure, so how does the "__ro_after_init" attribute work in that case? Is it something like this?

Quoted 5 lines
struct xfs_mount {
	struct xfs_mount_ro{
		.......
	} *ro __ro_after_init;
	......

No, you'd do:

struct xfs_mount_ro {
	[...]
};
struct xfs_mount {
	const struct xfs_mount_ro *ro;
	[...]
};

We can't do protection on less than a page boundary, so you can't embed a ro struct inside a rw struct.

Quoted 3 lines

Also, what compile time checks are in place to catch writes to ro structure members? Is sparse going to be able to check this sort of thing, like is does with endian-specific variables?

Just labelling the pointer const should be enough for the compiler to catch unintended writes.

Quoted 4 lines
Quoted 2 lines

I'd be interested to have your review of the pmalloc API, if you think something is missing, once I send out the next revision.

I'll look at it in more depth when it comes past again. :P

I think the key question is whether you want a slab-style interface or whether you want a kmalloc-style interface. I'd been assuming the former, but Igor has implemented the latter already.

#25 lore raw
Quoted 8 lines · Matthew Wilcox
Quoted 7 lines · Dave Chinner

FWIW, I'm not wanting to use it to replace static variables. All the structures are dynamically allocated right now, and get assigned to other dynamically allocated pointers. I'd likely split the current structures into a "ro after init" structure and rw structure, so how does the "__ro_after_init" attribute work in that case? Is it something like this?

Quoted 4 lines
Quoted 4 lines
struct xfs_mount {
	struct xfs_mount_ro{
		.......
	} *ro __ro_after_init;
       ^^^^^^^^

pointer, not embedded structure....

Quoted 4 lines
Quoted 1 line
	......

No, you'd do:

Quoted 8 lines
struct xfs_mount_ro {
	[...]
};
struct xfs_mount {
	const struct xfs_mount_ro *ro;
	[...]
};

.... so that's pretty much the same thing :P

Quoted 6 lines
Quoted 3 lines

Also, what compile time checks are in place to catch writes to ro structure members? Is sparse going to be able to check this sort of thing, like is does with endian-specific variables?

Just labelling the pointer const should be enough for the compiler to catch unintended writes.

Ok.

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

I'd be interested to have your review of the pmalloc API, if you think something is missing, once I send out the next revision.

I'll look at it in more depth when it comes past again. :P

I think the key question is whether you want a slab-style interface or whether you want a kmalloc-style interface. I'd been assuming the former, but Igor has implemented the latter already.

Slabs are rally only useful when you have lots of a specific type of object. I'm concerned mostly about one-off per-mount point structures, of which there are relatively few. A heap-like pool per mount is fine for this.

Cheers,

Dave.

Signature · 2 lines
Dave Chinner
[email protected]
#26 lore raw
Quoted 6 lines · Dave Chinner
Quoted 5 lines · Matthew Wilcox
Quoted 4 lines · Dave Chinner

FWIW, I'm not wanting to use it to replace static variables. All the structures are dynamically allocated right now, and get assigned to other dynamically allocated pointers. I'd likely split the current structures into a "ro after init"

I would prefer to use a different terminology, because, if I have understood the use case, this is not exactly the same as __ro_after_init

So, this is my understanding:

* "const" needs to be known at link time - there might be some adjustments later on, ex: patching of "const" pointers, after relocation has taken place - I am assuming we are not planning to patch const data The compiler can perform whatever optimization it feels like and it is allowed to do, on this.

* __ro_after_init is almost the same as a const, from a r/w perspective, but it will become effectively read_only after the completion of the init phase. The compiler cannot use it in any way to detect errors, AFAIK. The system will just generate a runtime error is someone tries to alter some __ro_after_init data, when it's read-only.
The only trick available is to use, after the protection, a different type of handle, const.

* pmalloc pools can be protected (hence the "p") at any time, but they start as r/w. Also, they cannot be declared statically.

* data which is either const or __ro_after_init is placed into specific sections (on arm64 it's actually the same) and its pages are then marked as read-only.

Quoted 11 lines
Quoted 8 lines
Quoted 8 lines

structure and rw structure, so
how does the "__ro_after_init" attribute work in that case? Is it something like this?

struct xfs_mount {
	struct xfs_mount_ro{
		.......
	} *ro __ro_after_init;
       ^^^^^^^^

pointer, not embedded structure....

I doubt this would work, because I think it's not possible to put a field of a structure into a separate section, afaik.

__ro_after_init would refer to the ro field, not to the memory it refers to.

Quoted 7 lines
Quoted 7 lines
Quoted 1 line
	......

No, you'd do:

struct xfs_mount_ro {
	[...]
};

is this something that is readonly from the beginning and then shared among mount points or is it specific to each mount point?

Quoted 6 lines
Quoted 4 lines
struct xfs_mount {
	const struct xfs_mount_ro *ro;
	[...]
};

.... so that's pretty much the same thing :P

The "const" modifier is a nice way to catch errors through the compiler, iff the ro data will not be initialized through this handle, when it's still writable.

Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

Also, what compile time checks are in place to catch writes to ro structure members? Is sparse going to be able to check this sort of thing, like is does with endian-specific variables?

Just labelling the pointer const should be enough for the compiler to catch unintended writes.

Ok.

yes, anyway the first one trying to alter it at run time, is in for some surprise.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
Quoted 2 lines

I'd be interested to have your review of the pmalloc API, if you think something is missing, once I send out the next revision.

I'll look at it in more depth when it comes past again. :P

Quoted 8 lines
Quoted 3 lines

I think the key question is whether you want a slab-style interface or whether you want a kmalloc-style interface. I'd been assuming the former, but Igor has implemented the latter already.

Slabs are rally only useful when you have lots of a specific type of object. I'm concerned mostly about one-off per-mount point structures, of which there are relatively few. A heap-like pool per mount is fine for this.

That was my same sentiment.

Actually it would be even possible to simulate caches with pools: each pool supports a granularity parameter, during creation. One could have multiple pools, each with different granularity, but it would probably lead to a proliferation of pools.

Instead, I preferred to have pmalloc as a drop-in replacement for the variants of k/v/kv malloc.

The only real issue was the - previous - inability of tracking the size of an allocation, given its address, but that is taken care of by the patch for the genalloc bitmap.

If I could have a pointer to a good candidate for the pmalloc treatment, I could come up with a patch, to show how it could be done.

Then it might be easier to discuss if the API needs to be modified and/or extended somehow.

--
igor

#27 lore raw
Quoted 10 lines · Igor Stoppa
Quoted 6 lines · Dave Chinner
Quoted 5 lines · Matthew Wilcox
Quoted 4 lines · Dave Chinner

FWIW, I'm not wanting to use it to replace static variables. All the structures are dynamically allocated right now, and get assigned to other dynamically allocated pointers. I'd likely split the current structures into a "ro after init"

I would prefer to use a different terminology, because, if I have understood the use case, this is not exactly the same as __ro_after_init

I want a dynamically allocated "write once" structure.

A "write once" structure is, conceptually, is exactly the same as "ro after init". Implementation wise, it may be different to "__ro_after_init", especially when compared to static/global variables.

It seems lots of people get confused when discussing concepts vs implementation... :)

Quoted 10 lines
Quoted 7 lines
Quoted 7 lines
Quoted 1 line
	......

No, you'd do:

struct xfs_mount_ro {
	[...]
};

is this something that is readonly from the beginning and then shared among mount points or is it specific to each mount point?

It's dynamically allocated for each mount point, made read-only before the mount completes and lives for the length of the mount point.

Quoted 10 lines
Quoted 6 lines
Quoted 4 lines
struct xfs_mount {
	const struct xfs_mount_ro *ro;
	[...]
};

.... so that's pretty much the same thing :P

The "const" modifier is a nice way to catch errors through the compiler, iff the ro data will not be initialized through this handle, when it's still writable.

That's kinda implied by the const, isn't it? If we don't do it that way, then the compiler will throw errors....

Cheers,

Dave.

Signature · 2 lines
Dave Chinner
[email protected]
#28 lore raw
Quoted 1 line · Dave Chinner

On Wed, Feb 21, 2018 at 11:56:22AM +0200, Igor Stoppa wrote:

[...]

Quoted 2 lines

It seems lots of people get confused when discussing concepts vs implementation... :)

IMHO, if possible, it's better to use unambiguous terms at every point. __ro_after_init is already taken :-P

In this specific case, I wanted to be absolutely sure I understood correctly what you need. I think I have now, thanks.

Quoted 6 lines
Quoted 2 lines

is this something that is readonly from the beginning and then shared among mount points or is it specific to each mount point?

It's dynamically allocated for each mount point, made read-only before the mount completes and lives for the length of the mount point.

ok. And destroyed when the mount point is unmounted, I expect.

[...]

Quoted 6 lines
Quoted 3 lines

The "const" modifier is a nice way to catch errors through the compiler, iff the ro data will not be initialized through this handle, when it's still writable.

That's kinda implied by the const, isn't it? If we don't do it that way, then the compiler will throw errors....

I might be splitting the hair, but since I'm advertising something I worte, I don't want to look like a peddler of snake oil, in hindsight :-P

To clarify my previous comment:

* const can mean the world to the compiler, but that doesn't automatically translate into write-protected memory, yet I do appreciate the advantage of teaching the compiler what should not be altered. And I have nothing against doing it.

* even if some handle will be const, it still needs to be aliased to some other pointer that is not const, at the beginning, because it must be initialized and it's anyway writable. So, this cannot be avoided.

--
igor