mm: security: ro protection for dynamic data
Subsystems (8)
v18 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 v17:
* turned all BUGs into WARNs, with the exceptions of the (optional) genalloc selftesting
* added mode descriptive messages, in case of failures
* fixed incorrect description of behavior when destroying a pool
* added tetst case of allocating memory from protected pool
* fixed kerneldoc description also for genalloc.h
* added missing Kconfig dependency for pmalloc, on MMU
* fixed location of initialization of link page struct -> vm_area
Igor Stoppa (7):
genalloc: track beginning of allocations
genalloc: selftest
struct page: add field for vm_struct Protectable Memory
Pmalloc selftest
lkdtm: crash on overwriting protected pmalloc var Documentation for Pmalloc
Documentation/core-api/index.rst | 1 + Documentation/core-api/pmalloc.rst | 111 ++++++ drivers/misc/lkdtm.h | 1 + drivers/misc/lkdtm_core.c | 3 + drivers/misc/lkdtm_perms.c | 28 ++ include/linux/genalloc.h | 367 +++++++++++++++--- include/linux/mm_types.h | 1 + include/linux/pmalloc.h | 242 ++++++++++++ include/linux/test_genalloc.h | 26 ++ include/linux/test_pmalloc.h | 24 ++ include/linux/vmalloc.h | 1 + init/main.c | 4 + lib/Kconfig | 15 + lib/Makefile | 1 + lib/genalloc.c | 745 +++++++++++++++++++++++++++---------- lib/test_genalloc.c | 410 ++++++++++++++++++++ mm/Kconfig | 17 + mm/Makefile | 2 + mm/pmalloc.c | 468 +++++++++++++++++++++++ mm/test_pmalloc.c | 100 +++++ mm/usercopy.c | 33 ++ mm/vmalloc.c | 2 + 22 files changed, 2364 insertions(+), 238 deletions(-) create mode 100644 Documentation/core-api/pmalloc.rst create mode 100644 include/linux/pmalloc.h create mode 100644 include/linux/test_genalloc.h create mode 100644 include/linux/test_pmalloc.h create mode 100644 lib/test_genalloc.c create mode 100644 mm/pmalloc.c create mode 100644 mm/test_pmalloc.c
Signature · 1 line
2.14.1
PATCH v18 1/7 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
The primary effect of this patch is that code using the gen_alloc library does not need anymore to keep track of the size of the allocations it makes.
Prior to this patch, it was necessary to keep track of the size of the allocation, so that it would be possible, later on, to know how much space should be freed.
Now, users of the api can choose to etiher still specify explicitly the size, or let the library determine it, by giving a value of 0.
However, even when the value is specified, the library still uses its on understanding of the space associated with a certain allocation, to confirm that they are consistent.
This verification also confirms that the patch works correctly.
Eventually, the extra parameter (and the corresponding verification) could be dropped, in favor of a simplified API.
--- include/linux/genalloc.h | 354 ++++++++++++++++++++--- lib/genalloc.c | 721 ++++++++++++++++++++++++++++++++++------------- 2 files changed, 837 insertions(+), 238 deletions(-)
include/linux/genalloc.h +312 -42
@@ -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 */ };/*
@@ -93,10 +93,40 @@ struct genpool_data_fixed {unsigned long offset;/* The offset of the specific region */ }; -extern struct gen_pool *gen_pool_create (int ,int ); -extern phys_addr_t gen_pool_virt_to_phys (struct gen_pool *pool,unsigned long ); -extern int gen_pool_add_virt (struct gen_pool *,unsigned long ,phys_addr_t , -size_t ,int ); +/** +* gen_pool_create() - create a new special memory pool +* @min_alloc_order: log base 2 of number of bytes each bitmap entry +* represents +* @nid: node id of the node the pool structure should be allocated on, +* or -1 +* +* Create a new special memory pool that can be used to manage special +* purpose memory not managed by the regular kmalloc/kfree interface. +* +* Return: +* * pointer to the pool - success +* * NULL - otherwise +*/ +struct gen_pool *gen_pool_create (int min_alloc_order,int nid); + +/** +* gen_pool_add_virt() - add a new chunk of special memory to the pool +* @pool: pool to add new memory chunk to +* @virt: virtual starting address of memory chunk to add to pool +* @phys: physical starting address of memory chunk to add to pool +* @size: size in bytes of the memory chunk to add to pool +* @nid: node id of the node the chunk structure and bitmap should be +* allocated on, or -1 +* +* Add a new chunk of special memory to the specified pool. +* +* Return: +* * 0 - success +* * -ve errno - failure +*/ +int gen_pool_add_virt (struct gen_pool *pool,unsigned long virt, +phys_addr_t phys,size_t size,int nid); +/** * gen_pool_add - add a new chunk of special memory to the pool * @pool: pool to add new memory chunk to
@@ -107,60 +137,300 @@ extern int gen_pool_add_virt(struct gen_pool *, unsigned long, phys_addr_t,* * Add a new chunk of special memory to the specified pool. * -* Returns 0 on success or a -ve errno on failure. +* Return: +* * 0 - on success +* *-ve errno - failure */ static inline int gen_pool_add (struct gen_pool *pool,unsigned long addr,size_t size,int nid) {return gen_pool_add_virt (pool, addr,-1 , size, nid); } -extern void gen_pool_destroy (struct gen_pool *); -extern unsigned long gen_pool_alloc (struct gen_pool *,size_t ); -extern unsigned long gen_pool_alloc_algo (struct gen_pool *,size_t , -genpool_algo_t algo,void *data); -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_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 *); -extern size_t gen_pool_size (struct gen_pool *); -extern void gen_pool_set_algo (struct gen_pool *pool,genpool_algo_t algo, -void *data); +/** +* gen_pool_virt_to_phys() - return the physical address of memory +* @pool: pool to allocate from +* @addr: starting address of memory +* +* Return: +* * the physical address - success +* * \-1 - error +*/ +phys_addr_t gen_pool_virt_to_phys (struct gen_pool *pool,unsigned long addr); + +/** +* gen_pool_destroy() - destroy a special memory pool +* @pool: pool to destroy +* +* Destroy the specified special memory pool. Verifies that there are no +* outstanding allocations. +*/ +void gen_pool_destroy (struct gen_pool *pool); + +/** +* gen_pool_alloc() - allocate special memory from the pool +* @pool: pool to allocate from +* @size: number of bytes to allocate from the pool +* +* Allocate the requested number of bytes from the specified pool. +* Uses the pool allocation function (with first-fit algorithm by default). +* Can not be used in NMI handler on architectures without +* NMI-safe cmpxchg implementation. +* +* Return: +* * address of the memory allocated - success +* * NULL - error +*/ +unsigned long gen_pool_alloc (struct gen_pool *pool,size_t size); + +/** +* gen_pool_alloc_algo() - allocate special memory from the pool +* @pool: pool to allocate from +* @size: number of bytes to allocate from the pool +* @algo: algorithm passed from caller +* @data: data passed to algorithm +* +* Allocate the requested number of bytes from the specified pool. +* Uses the pool allocation function (with first-fit algorithm by default). +* Can not be used in NMI handler on architectures without +* NMI-safe cmpxchg implementation. +* +* Return: +* * address of the memory allocated - success +* * NULL - error +*/ +unsigned long gen_pool_alloc_algo (struct gen_pool *pool,size_t size, +genpool_algo_t algo,void *data); + +/** +* gen_pool_dma_alloc() - allocate special memory from the pool for DMA usage +* @pool: pool to allocate from +* @size: number of bytes to allocate from the pool +* @dma: dma-view physical address return value. Use NULL if unneeded. +* +* Allocate the requested number of bytes from the specified pool. +* Uses the pool allocation function (with first-fit algorithm by default). +* Can not be used in NMI handler on architectures without +* NMI-safe cmpxchg implementation. +* +* Return: +* * address of the memory allocated - success +* * NULL - error +*/ +void *gen_pool_dma_alloc (struct gen_pool *pool,size_t size,dma_addr_t *dma); + +/** +* gen_pool_free() - free allocated special memory back to the pool +* @pool: pool to free to +* @addr: starting address of memory to free back to pool +* @size: size in bytes of memory to free or 0, for auto-detection +* +* Free previously allocated special memory back to the specified +* pool. Can not be used in NMI handler on architectures without +* NMI-safe cmpxchg implementation. +*/ +void gen_pool_free (struct gen_pool *pool,unsigned long addr,size_t size); + +/** +* gen_pool_for_each_chunk() - call func for every chunk of generic memory pool +* @pool: the generic memory pool +* @func: func to call +* @data: additional data used by @func +* +* Call @func for every chunk of generic memory pool. The @func is +* called with rcu_read_lock held. +*/ +void gen_pool_for_each_chunk (struct gen_pool *pool, +void (*func)(struct gen_pool *pool, +struct gen_pool_chunk *chunk, +void *data), +void *data); + +/** +* addr_in_gen_pool() - checks if an address falls within the range of a pool +* @pool: the generic memory pool +* @start: start address +* @size: size of the region +* +* Check if the range of addresses falls within the specified pool. +* +* Return: +* * true - the entire range is contained in the pool +* * false - otherwise +*/ +bool addr_in_gen_pool (struct gen_pool *pool,unsigned long start, +size_t size); + +/** +* gen_pool_avail() - get available free space of the pool +* @pool: pool to get available free space +* +* Return: available free space of the specified pool. +*/ +size_t gen_pool_avail (struct gen_pool *pool); -extern unsigned long gen_pool_first_fit (unsigned long *map,unsigned long size, -unsigned long start,unsigned int nr,void *data, -struct gen_pool *pool); +/** +* gen_pool_size() - get size in bytes of memory managed by the pool +* @pool: pool to get size +* +* Return: size in bytes of memory managed by the pool. +*/ +size_t gen_pool_size (struct gen_pool *pool); -extern unsigned long gen_pool_fixed_alloc (unsigned long *map, -unsigned long size,unsigned long start,unsigned int nr, -void *data,struct gen_pool *pool); +/** +* gen_pool_set_algo() - set the allocation algorithm +* @pool: pool to change allocation algorithm +* @algo: custom algorithm function +* @data: additional data used by @algo +* +* Call @algo for each memory allocation in the pool. +* If @algo is NULL use gen_pool_first_fit as default +* memory allocation function. +*/ +void gen_pool_set_algo (struct gen_pool *pool,genpool_algo_t algo,void *data); -extern unsigned long gen_pool_first_fit_align (unsigned long *map, -unsigned long size,unsigned long start,unsigned int nr, -void *data,struct gen_pool *pool); +/** +* gen_pool_first_fit() - find the first available region +* of memory matching the size requirement (no alignment constraint) +* @map: The address to base the search on +* @size: The number of allocation units in the bitmap +* @start: The allocation unit to start searching at +* @nr: The number of allocation units we're looking for +* @data: additional data - unused +* @pool: pool to find the fit region memory from +* +* Return: +* * index of the memory allocated - sufficient space available +* * end of the range - insufficient space +*/ +unsigned long gen_pool_first_fit (unsigned long *map,unsigned long size, +unsigned long start,unsigned int nr, +void *data,struct gen_pool *pool); +/** +* gen_pool_first_fit_align() - find the first available region +* of memory matching the size requirement (alignment constraint) +* @map: The address to base the search on +* @size: The number of allocation units in the bitmap +* @start: The allocation unit to start searching at +* @nr: The number of allocation units we're looking for +* @data: data for alignment +* @pool: pool to get order from +* +* Return: +* * index of the memory allocated - sufficient space available +* * end of the range - insufficient space +*/ +unsigned long gen_pool_first_fit_align (unsigned long *map, +unsigned long size, +unsigned long start, +unsigned int nr,void *data, +struct gen_pool *pool); -extern unsigned long gen_pool_first_fit_order_align (unsigned long *map, -unsigned long size,unsigned long start,unsigned int nr, -void *data,struct gen_pool *pool); +/** +* gen_pool_fixed_alloc() - reserve a specific region +* @map: The address to base the search on +* @size: The number of allocation units in the bitmap +* @start: The allocation unit to start searching at +* @nr: The number of allocation units we're looking for +* @data: data for alignment +* @pool: pool to get order from +* +* Return: +* * index of the memory allocated - sufficient space available +* * end of the range - insufficient space +*/ +unsigned long gen_pool_fixed_alloc (unsigned long *map,unsigned long size, +unsigned long start,unsigned int nr, +void *data,struct gen_pool *pool); -extern unsigned long gen_pool_best_fit (unsigned long *map,unsigned long size, -unsigned long start,unsigned int nr,void *data, -struct gen_pool *pool); +/** +* gen_pool_first_fit_order_align() - find the first available region +* of memory matching the size requirement. The region will be aligned +* to the order of the size specified. +* @map: The address to base the search on +* @size: The number of allocation units in the bitmap +* @start: The allocation unit to start searching at +* @nr: The number of allocation units we're looking for +* @data: additional data - unused +* @pool: pool to find the fit region memory from +* +* Return: +* * index of the memory allocated - sufficient space available +* * end of the range - insufficient space +*/ +unsigned long gen_pool_first_fit_order_align (unsigned long *map, +unsigned long size, +unsigned long start, +unsigned int nr,void *data, +struct gen_pool *pool); +/** +* gen_pool_best_fit() - find the best fitting region of memory +* matching the size requirement (no alignment constraint) +* @map: The address to base the search on +* @size: The number of allocation units in the bitmap +* @start: The allocation unit to start searching at +* @nr: The number of allocation units we're looking for +* @data: additional data - unused +* @pool: pool to find the fit region memory from +* +* Iterate over the bitmap to find the smallest free region +* which we can allocate the memory. +* +* Return: +* * index of the memory allocated - sufficient space available +* * end of the range - insufficient space +*/ +unsigned long gen_pool_best_fit (unsigned long *map,unsigned long size, +unsigned long start,unsigned int nr, +void *data,struct gen_pool *pool); -extern struct gen_pool *devm_gen_pool_create (struct device *dev, -int min_alloc_order,int nid,const char *name); -extern struct gen_pool *gen_pool_get (struct device *dev,const char *name); +/** +* gen_pool_get() - Obtain the gen_pool (if any) for a device +* @dev: device to retrieve the gen_pool from +* @name: name of a gen_pool or NULL, identifies a particular gen_pool +* on device +* +* Return: +* * the gen_pool for the device - if it exists +* * NULL - no pool exists for the device +*/ +struct gen_pool *gen_pool_get (struct device *dev,const char *name); -bool addr_in_gen_pool (struct gen_pool *pool,unsigned long start, -size_t size); +/** +* devm_gen_pool_create() - managed gen_pool_create +* @dev: device that provides the gen_pool +* @min_alloc_order: log base 2 of number of bytes each bitmap bit represents +* @nid: node selector for allocated gen_pool, %NUMA_NO_NODE for all nodes +* @name: name of a gen_pool or NULL, identifies a particular gen_pool on device +* +* Create a new special memory pool that can be used to manage special purpose +* memory not managed by the regular kmalloc/kfree interface. The pool will be +* automatically destroyed by the device management code. +* +* Return: +* * address of the pool - success +* * NULL - error +*/ +struct gen_pool *devm_gen_pool_create (struct device *dev,int min_alloc_order, +int nid,const char *name); +/** +* 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 +* +* 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 +*/ #ifdef CONFIG_OF -extern struct gen_pool *of_gen_pool_get (struct device_node *np, -const char *propname,int index); +struct gen_pool *of_gen_pool_get (struct device_node *np, +const char *propname,int index);#else static inline struct gen_pool *of_gen_pool_get (struct device_node *np,const char *propname,int index)
lib/genalloc.c +525 -196
1,059 lines not on this page · raw message
Signature · 1 line
2.14.1
PATCH v18 2/7 genalloc: selftest
In reply to Igor StoppaIntroduce 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.
The testing takes place in the very early stages of main.c, to ensure that failures in genalloc are caught before they can cause unexplained erratic behavior in any of genalloc users.
Therefore, it would not be advisable to implement it as module.
--- include/linux/test_genalloc.h | 26 +++ init/main.c | 2 + lib/Kconfig | 15 ++ lib/Makefile | 1 + lib/test_genalloc.c | 410 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 454 insertions(+) create mode 100644 include/linux/test_genalloc.h create mode 100644 lib/test_genalloc.c
include/linux/test_genalloc.h new file +26 -0
@@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* test_genalloc.h +* +* (C) Copyright 2017 Huawei Technologies Co. Ltd. +* Author: Igor Stoppa <[email protected]> +*/ + + +#ifndef __LINUX_TEST_GENALLOC_H +#define __LINUX_TEST_GENALLOC_H + + +#ifdef CONFIG_TEST_GENERIC_ALLOCATOR + +#include <linux/genalloc.h> + +void test_genalloc (void ); + +#else + +static inline void test_genalloc (void ){}; + +#endif + +#endif
init/main.c +2 -0
@@ -90,6 +90,7 @@#include <linux/cache.h> #include <linux/rodata_test.h> #include <linux/jump_label.h> +#include <linux/test_genalloc.h> #include <asm/io.h> #include <asm/bugs.h>
@@ -661,6 +662,7 @@ asmlinkage __visible void __init start_kernel(void)*/ mem_encrypt_init (); +test_genalloc ();#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
@@ -287,6 +287,21 @@ config DECOMPRESS_LZ4 config GENERIC_ALLOCATOR bool +config TEST_GENERIC_ALLOCATOR + 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 TEST_GENERIC_ALLOCATOR_VERBOSE + bool "make the genalloc tester more verbose" + default n + select TEST_GENERIC_ALLOCATOR + help + More information will be displayed during the self-testing. + # # reed solomon support is select'ed if needed #
lib/Makefile +1 -0
@@ -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_TEST_GENERIC_ALLOCATOR) += test_genalloc.o obj-$(CONFIG_842_COMPRESS) += 842/ obj-$(CONFIG_842_DECOMPRESS) += 842/
lib/test_genalloc.c new file +410 -0
410 lines not on this page · raw message
Signature · 1 line
2.14.1
PATCH v18 3/7 struct page: add field for vm_struct
In reply to Igor StoppaWhen a page is used for virtual memory, it is often necessary to obtain 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, later on.
--- include/linux/mm_types.h | 1 + mm/vmalloc.c | 2 ++ 2 files changed, 3 insertions(+)
include/linux/mm_types.h +1 -0
@@ -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 +2 -0
@@ -1536,6 +1536,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 ); }
@@ -1705,6 +1706,7 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, area->nr_pages = i; goto fail; } + page->area = area; area->pages[i] = page;if (gfpflags_allow_blocking (gfp_mask|highmem_mask))cond_resched ();
Signature · 1 line
2.14.1
PATCH v18 4/7 Protectable Memory
In reply to Igor StoppaThe 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.
Since pmalloc memory is obtained from vmalloc, an attacker that has gained access to the physical mapping, still has to identify where the target of the attack is actually located.
At the same time, being also based on genalloc, pmalloc does not generate as much trashing of the TLB as it would be caused by using directly only vmalloc.
--- include/linux/genalloc.h | 13 ++ include/linux/pmalloc.h | 242 ++++++++++++++++++++++++ include/linux/vmalloc.h | 1 + lib/genalloc.c | 24 +++ mm/Kconfig | 7 + mm/Makefile | 1 + mm/pmalloc.c | 468 +++++++++++++++++++++++++++++++++++++++++++++++ mm/usercopy.c | 33 ++++ 8 files changed, 789 insertions(+) create mode 100644 include/linux/pmalloc.h create mode 100644 mm/pmalloc.c
include/linux/genalloc.h +13 -0
@@ -231,6 +231,19 @@ void *gen_pool_dma_alloc(struct gen_pool *pool, size_t size, dma_addr_t *dma);*/ void gen_pool_free (struct gen_pool *pool,unsigned long addr,size_t size); +/** +* 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); +/** * gen_pool_for_each_chunk() - call func for every chunk of generic memory pool * @pool: the generic memory pool
include/linux/pmalloc.h new file +242 -0
242 lines not on this page · raw message
include/linux/vmalloc.h +1 -0
@@ -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 +24 -0
@@ -654,6 +654,30 @@ 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; + + 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 +7 -0
@@ -760,3 +760,10 @@ config GUP_BENCHMARK performance of get_user_pages_fast(). See tools/testing/selftests/vm/gup_benchmark.c + +config PROTECTABLE_MEMORY + bool + depends on MMU + depends on ARCH_HAS_SET_MEMORY + select GENERIC_ALLOCATOR + default y
mm/Makefile +1 -0
@@ -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 +468 -0
468 lines not on this page · raw message
mm/usercopy.c +33 -0
@@ -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
PATCH v18 5/7 Pmalloc selftest
In reply to Igor StoppaAdd basic self-test functionality for pmalloc.
The testing is introduced as early as possible, right after the main dependency, genalloc, has passed successfully, so that it can help diagnosing failures in pmalloc users.
--- include/linux/test_pmalloc.h | 24 +++++++++++ init/main.c | 2 + mm/Kconfig | 10 +++++ mm/Makefile | 1 + mm/test_pmalloc.c | 100 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 137 insertions(+) create mode 100644 include/linux/test_pmalloc.h create mode 100644 mm/test_pmalloc.c
include/linux/test_pmalloc.h new file +24 -0
@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* test_pmalloc.h +* +* (C) Copyright 2018 Huawei Technologies Co. Ltd. +* Author: Igor Stoppa <[email protected]> +*/ + + +#ifndef __LINUX_TEST_PMALLOC_H +#define __LINUX_TEST_PMALLOC_H + + +#ifdef CONFIG_TEST_PROTECTABLE_MEMORY + +void test_pmalloc (void ); + +#else + +static inline void test_pmalloc (void ){}; + +#endif + +#endif
init/main.c +2 -0
@@ -91,6 +91,7 @@#include <linux/rodata_test.h> #include <linux/jump_label.h> #include <linux/test_genalloc.h> +#include <linux/test_pmalloc.h> #include <asm/io.h> #include <asm/bugs.h>
@@ -663,6 +664,7 @@ asmlinkage __visible void __init start_kernel(void)mem_encrypt_init ();test_genalloc (); +test_pmalloc ();#ifdef CONFIG_BLK_DEV_INITRD if (initrd_start && !initrd_below_start_ok &&page_to_pfn (virt_to_page ((void *)initrd_start)) < min_low_pfn) {
mm/Kconfig +10 -0
@@ -767,3 +767,13 @@ config PROTECTABLE_MEMORY depends on ARCH_HAS_SET_MEMORY select GENERIC_ALLOCATOR default y + +config TEST_PROTECTABLE_MEMORY + bool "Run self test for pmalloc memory allocator" + depends on MMU + 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
@@ -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_TEST_PROTECTABLE_MEMORY) += test_pmalloc.o obj-$(CONFIG_KSM) += ksm.o obj-$(CONFIG_PAGE_POISONING) += page_poison.o obj-$(CONFIG_SLAB) += slab.o
mm/test_pmalloc.c new file +100 -0
100 lines not on this page · raw message
Signature · 1 line
2.14.1
PATCH v18 6/7 lkdtm: crash on overwriting protected pmalloc var
In reply to Igor StoppaVerify that pmalloc read-only protection is in place: trying to overwrite a protected variable will crash the kernel.
--- drivers/misc/lkdtm.h | 1 + drivers/misc/lkdtm_core.c | 3 +++ drivers/misc/lkdtm_perms.c | 28 ++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+)
drivers/misc/lkdtm.h +1 -0
@@ -38,6 +38,7 @@ void lkdtm_READ_BUDDY_AFTER_FREE(void);void __init lkdtm_perms_init (void );void lkdtm_WRITE_RO (void );void lkdtm_WRITE_RO_AFTER_INIT (void ); +void lkdtm_WRITE_RO_PMALLOC (void );void lkdtm_WRITE_KERN (void );void lkdtm_EXEC_DATA (void );void lkdtm_EXEC_STACK (void );
drivers/misc/lkdtm_core.c +3 -0
@@ -155,6 +155,9 @@ static const struct crashtype crashtypes[] = {CRASHTYPE (ACCESS_USERSPACE ),CRASHTYPE (WRITE_RO ),CRASHTYPE (WRITE_RO_AFTER_INIT ), +#ifdef CONFIG_PROTECTABLE_MEMORY +CRASHTYPE (WRITE_RO_PMALLOC ), +#endifCRASHTYPE (WRITE_KERN ),CRASHTYPE (REFCOUNT_INC_OVERFLOW ), CRASHTYPE(REFCOUNT_ADD_OVERFLOW),
drivers/misc/lkdtm_perms.c +28 -0
@@ -9,6 +9,7 @@#include <linux/vmalloc.h> #include <linux/mman.h> #include <linux/uaccess.h> +#include <linux/pmalloc.h> #include <asm/cacheflush.h> /* Whether or not to fill the target memory area with do_nothing(). */
@@ -104,6 +105,33 @@ void lkdtm_WRITE_RO_AFTER_INIT(void) *ptr ^=0xabcd1234 ; } +#ifdef CONFIG_PROTECTABLE_MEMORY +void lkdtm_WRITE_RO_PMALLOC (void ) +{ +struct gen_pool *pool; +int *i; + + pool =pmalloc_create_pool ("pool" ,0 ); +if (unlikely (!pool)) { +pr_info ("Failed preparing pool for pmalloc test." ); +return ; + } + + i = (int *)pmalloc (pool,sizeof (int ),GFP_KERNEL ); +if (unlikely (!i)) { +pr_info ("Failed allocating memory for pmalloc test." ); +pmalloc_destroy_pool (pool); +return ; + } + + *i =INT_MAX ; +pmalloc_protect_pool (pool); + +pr_info ("attempting bad pmalloc write at %p\n" , i); + *i =0 ; +} +#endif +void lkdtm_WRITE_KERN (void ) {size_t size;
Signature · 1 line
2.14.1
PATCH v18 7/7 Documentation for Pmalloc
In reply to Igor StoppaDetailed documentation about the protectable memory allocator.
--- Documentation/core-api/index.rst | 1 + Documentation/core-api/pmalloc.rst | 111 +++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 Documentation/core-api/pmalloc.rst
Documentation/core-api/index.rst +1 -0
@@ -25,6 +25,7 @@ Core utilities genalloc errseq printk-formats + pmalloc Interfaces for kernel debugging ===============================
Documentation/core-api/pmalloc.rst new file +111 -0
111 lines not on this page · raw message
Signature · 1 line
2.14.1
kbuild test robot
build botRe: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Igor StoppaThank you for the patch! Yet something to improve:
Hi Igor,
Thank you for the patch! Yet something to improve:
[auto build test ERROR on next-20180223]
[also build test ERROR on v4.16-rc3]
[cannot apply to linus/master mmotm/master char-misc/char-misc-testing v4.16-rc3 v4.16-rc2 v4.16-rc1] [if your patch is applied to the wrong git tree, please drop us a note to help improve the system]
url: https://github.com/0day-ci/linux/commits/Igor-Stoppa/mm-security-ro-protection-for-dynamic-data/20180302-232215
config: i386-randconfig-x004-201808 (attached as .config)
compiler: gcc-7 (Debian 7.3.0-1) 7.3.0 reproduce:
# save the attached .config to linux build tree
make ARCH=i386 All error/warnings (new ones prefixed by >>):
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c: In function 'gen_pool_free':
>> lib/genalloc.c:616:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Trying to free unallocated memory"
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
>> lib/genalloc.c:615:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:617:23: note: format string is defined here
" from pool %s", pool);
~^
In file included from include/asm-generic/bug.h:5:0,
from arch/x86/include/asm/bug.h:83,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
>> lib/genalloc.c:624:17: error: implicit declaration of function 'exit_test'; did you mean 'exit_sem'? [-Werror=implicit-function-declaration]
if (unlikely(exit_test(boundary < 0))) {
^
include/linux/compiler.h:77:42: note: in definition of macro 'unlikely'
# define unlikely(x) __builtin_expect(!!(x), 0)
^
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c:626:16: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
WARN(true, "Corrupted pool %s", pool);
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:626:5: note: in expansion of macro 'WARN'
WARN(true, "Corrupted pool %s", pool);
^~~~
lib/genalloc.c:634:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Size provided differs from size "
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:633:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:635:31: note: format string is defined here
"measured from pool %s", pool);
~^
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c:643:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Unexpected bitmap collision while"
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:642:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:644:36: note: format string is defined here
" freeing memory in pool %s", pool);
~^
cc1: some warnings being treated as errorsvim +624 lib/genalloc.c
609
610 rcu_read_lock();
611 list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
612 if (addr >= chunk->start_addr && addr <= chunk->end_addr) {
613 if (unlikely(addr + size - 1 > chunk->end_addr)) {
614 rcu_read_unlock();
> 615 WARN(true,
> 616 "Trying to free unallocated memory"
617 " from pool %s", pool);
618 return;
619 }
620 start_entry = (addr - chunk->start_addr) >> order;
621 remaining_entries = (chunk->end_addr - addr) >> order;
622 boundary = get_boundary(chunk->entries, start_entry,
623 remaining_entries);
> 624 if (unlikely(exit_test(boundary < 0))) { 625 rcu_read_unlock();
626 WARN(true, "Corrupted pool %s", pool);
627 return;
628 }
629 nentries = boundary - start_entry;
630 if (unlikely(size && (nentries !=
631 mem_to_units(size, order)))) {
632 rcu_read_unlock();
633 WARN(true,
634 "Size provided differs from size "
635 "measured from pool %s", pool);
636 return;
637 }
638 remain = alter_bitmap_ll(CLEAR_BITS, chunk->entries,
639 start_entry, nentries);
640 if (unlikely(remain)) {
641 rcu_read_unlock();
642 WARN(true,
643 "Unexpected bitmap collision while"
644 " freeing memory in pool %s", pool);
645 return;
646 }
647 atomic_long_add(nentries << order, &chunk->avail);
648 rcu_read_unlock();
649 return;
650 }
651 }
652 rcu_read_unlock();
653 WARN(true, "address not found in pool %s", pool->name);
654 }
655 EXPORT_SYMBOL(gen_pool_free);
656
---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation
kbuild test robot
build botRe: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Igor StoppaThank you for the patch! Perhaps something to improve:
Hi Igor,
Thank you for the patch! Perhaps something to improve:
[auto build test WARNING on next-20180223]
[also build test WARNING on v4.16-rc3]
[cannot apply to linus/master mmotm/master char-misc/char-misc-testing v4.16-rc3 v4.16-rc2 v4.16-rc1] [if your patch is applied to the wrong git tree, please drop us a note to help improve the system]
url: https://github.com/0day-ci/linux/commits/Igor-Stoppa/mm-security-ro-protection-for-dynamic-data/20180302-232215
config: i386-randconfig-x007-201808 (attached as .config)
compiler: gcc-7 (Debian 7.3.0-1) 7.3.0 reproduce:
# save the attached .config to linux build tree
make ARCH=i386 All warnings (new ones prefixed by >>):
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c: In function 'gen_pool_free':
lib/genalloc.c:616:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Trying to free unallocated memory"
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:615:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:617:23: note: format string is defined here
" from pool %s", pool);
~^
In file included from include/asm-generic/bug.h:5:0,
from arch/x86/include/asm/bug.h:83,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c:624:17: error: implicit declaration of function 'exit_test'; did you mean 'exit_sem'? [-Werror=implicit-function-declaration]
if (unlikely(exit_test(boundary < 0))) {
^
include/linux/compiler.h:58:30: note: in definition of macro '__trace_if'
if (__builtin_constant_p(!!(cond)) ? !!(cond) : \
^~~~
>> lib/genalloc.c:624:4: note: in expansion of macro 'if'
if (unlikely(exit_test(boundary < 0))) {
^~
include/linux/compiler.h:48:24: note: in expansion of macro '__branch_check__'
# define unlikely(x) (__branch_check__(x, 0, __builtin_constant_p(x)))
^~~~~~~~~~~~~~~~
>> lib/genalloc.c:624:8: note: in expansion of macro 'unlikely'
if (unlikely(exit_test(boundary < 0))) {
^~~~~~~~
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c:626:16: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
WARN(true, "Corrupted pool %s", pool);
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:626:5: note: in expansion of macro 'WARN'
WARN(true, "Corrupted pool %s", pool);
^~~~
lib/genalloc.c:634:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Size provided differs from size "
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:633:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:635:31: note: format string is defined here
"measured from pool %s", pool);
~^
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c:643:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Unexpected bitmap collision while"
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:642:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:644:36: note: format string is defined here
" freeing memory in pool %s", pool);
~^cc1: some warnings being treated as errors
vim +/if +624 lib/genalloc.c
609
610 rcu_read_lock();
611 list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
612 if (addr >= chunk->start_addr && addr <= chunk->end_addr) {
613 if (unlikely(addr + size - 1 > chunk->end_addr)) {
614 rcu_read_unlock();
615 WARN(true,
616 "Trying to free unallocated memory"
617 " from pool %s", pool);
618 return;
619 }
620 start_entry = (addr - chunk->start_addr) >> order;
621 remaining_entries = (chunk->end_addr - addr) >> order;
622 boundary = get_boundary(chunk->entries, start_entry,
623 remaining_entries);
> 624 if (unlikely(exit_test(boundary < 0))) { 625 rcu_read_unlock();
626 WARN(true, "Corrupted pool %s", pool);
627 return;
628 }
629 nentries = boundary - start_entry;
630 if (unlikely(size && (nentries !=
631 mem_to_units(size, order)))) {
632 rcu_read_unlock();
633 WARN(true,
634 "Size provided differs from size "
635 "measured from pool %s", pool);
636 return;
637 }
638 remain = alter_bitmap_ll(CLEAR_BITS, chunk->entries,
639 start_entry, nentries);
640 if (unlikely(remain)) {
641 rcu_read_unlock();
642 WARN(true,
643 "Unexpected bitmap collision while"
644 " freeing memory in pool %s", pool);
645 return;
646 }
647 atomic_long_add(nentries << order, &chunk->avail);
648 rcu_read_unlock();
649 return;
650 }
651 }
652 rcu_read_unlock();
653 WARN(true, "address not found in pool %s", pool->name);
654 }
655 EXPORT_SYMBOL(gen_pool_free);
656
---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation
kbuild test robot
build botRe: [PATCH 3/7] struct page: add field for vm_struct
In reply to Igor StoppaThank you for the patch! Perhaps something to improve:
Hi Igor,
Thank you for the patch! Perhaps something to improve:
[auto build test WARNING on next-20180223]
[cannot apply to linus/master mmotm/master char-misc/char-misc-testing v4.16-rc3 v4.16-rc2 v4.16-rc1 v4.16-rc3] [if your patch is applied to the wrong git tree, please drop us a note to help improve the system]
url: https://github.com/0day-ci/linux/commits/Igor-Stoppa/mm-security-ro-protection-for-dynamic-data/20180302-232215
reproduce:
# apt-get install sparse
make ARCH=x86_64 allmodconfig
make C=1 CF=-D__CHECK_ENDIAN__sparse warnings: (new ones prefixed by >>)
lib/genalloc.c:624:29: sparse: undefined identifier 'exit_test'
>> lib/genalloc.c:624:29: sparse: call with no type!
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c: In function 'gen_pool_free':
lib/genalloc.c:616:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Trying to free unallocated memory"
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:615:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:617:23: note: format string is defined here
" from pool %s", pool);
~^
In file included from include/asm-generic/bug.h:5:0,
from arch/x86/include/asm/bug.h:83,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c:624:17: error: implicit declaration of function 'exit_test'; did you mean 'exit_sem'? [-Werror=implicit-function-declaration]
if (unlikely(exit_test(boundary < 0))) {
^
include/linux/compiler.h:77:42: note: in definition of macro 'unlikely'
# define unlikely(x) __builtin_expect(!!(x), 0)
^
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c:626:16: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
WARN(true, "Corrupted pool %s", pool);
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:626:5: note: in expansion of macro 'WARN'
WARN(true, "Corrupted pool %s", pool);
^~~~
lib/genalloc.c:634:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Size provided differs from size "
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:633:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:635:31: note: format string is defined here
"measured from pool %s", pool);
~^
In file included from arch/x86/include/asm/bug.h:83:0,
from include/linux/bug.h:5,
from include/linux/mmdebug.h:5,
from include/linux/gfp.h:5,
from include/linux/slab.h:15,
from lib/genalloc.c:99:
lib/genalloc.c:643:10: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'struct gen_pool *' [-Wformat=]
"Unexpected bitmap collision while"
^
include/asm-generic/bug.h:98:50: note: in definition of macro '__WARN_printf'
#define __WARN_printf(arg...) do { __warn_printk(arg); __WARN(); } while (0)
^~~
lib/genalloc.c:642:5: note: in expansion of macro 'WARN'
WARN(true,
^~~~
lib/genalloc.c:644:36: note: format string is defined here
" freeing memory in pool %s", pool);
~^
cc1: some warnings being treated as errorsvim +624 lib/genalloc.c
929f9727 Dean Nelson 2006-06-23 609
7f184275 Huang Ying 2011-07-13 610 rcu_read_lock();
7f184275 Huang Ying 2011-07-13 611 list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
674470d9 Joonyoung Shim 2013-09-11 612 if (addr >= chunk->start_addr && addr <= chunk->end_addr) {
3406f868 Igor Stoppa 2018-02-28 613 if (unlikely(addr + size - 1 > chunk->end_addr)) {
7f184275 Huang Ying 2011-07-13 614 rcu_read_unlock();
3406f868 Igor Stoppa 2018-02-28 615 WARN(true,
3406f868 Igor Stoppa 2018-02-28 616 "Trying to free unallocated memory"
3406f868 Igor Stoppa 2018-02-28 617 " from pool %s", pool);
7f184275 Huang Ying 2011-07-13 618 return;
f14f75b8 Jes Sorensen 2005-06-21 619 }
3406f868 Igor Stoppa 2018-02-28 620 start_entry = (addr - chunk->start_addr) >> order;
3406f868 Igor Stoppa 2018-02-28 621 remaining_entries = (chunk->end_addr - addr) >> order;
3406f868 Igor Stoppa 2018-02-28 622 boundary = get_boundary(chunk->entries, start_entry,
3406f868 Igor Stoppa 2018-02-28 623 remaining_entries);
3406f868 Igor Stoppa 2018-02-28 @624 if (unlikely(exit_test(boundary < 0))) {
3406f868 Igor Stoppa 2018-02-28 625 rcu_read_unlock();
3406f868 Igor Stoppa 2018-02-28 626 WARN(true, "Corrupted pool %s", pool);
3406f868 Igor Stoppa 2018-02-28 627 return;
f14f75b8 Jes Sorensen 2005-06-21 628 }
3406f868 Igor Stoppa 2018-02-28 629 nentries = boundary - start_entry;
3406f868 Igor Stoppa 2018-02-28 630 if (unlikely(size && (nentries !=
3406f868 Igor Stoppa 2018-02-28 631 mem_to_units(size, order)))) {
7f184275 Huang Ying 2011-07-13 632 rcu_read_unlock();
3406f868 Igor Stoppa 2018-02-28 633 WARN(true,
3406f868 Igor Stoppa 2018-02-28 634 "Size provided differs from size "
3406f868 Igor Stoppa 2018-02-28 635 "measured from pool %s", pool);
3406f868 Igor Stoppa 2018-02-28 636 return;
3406f868 Igor Stoppa 2018-02-28 637 }
3406f868 Igor Stoppa 2018-02-28 638 remain = alter_bitmap_ll(CLEAR_BITS, chunk->entries,
3406f868 Igor Stoppa 2018-02-28 639 start_entry, nentries);
3406f868 Igor Stoppa 2018-02-28 640 if (unlikely(remain)) {
3406f868 Igor Stoppa 2018-02-28 641 rcu_read_unlock();
3406f868 Igor Stoppa 2018-02-28 642 WARN(true,
3406f868 Igor Stoppa 2018-02-28 643 "Unexpected bitmap collision while"
3406f868 Igor Stoppa 2018-02-28 644 " freeing memory in pool %s", pool);
3406f868 Igor Stoppa 2018-02-28 645 return;
3406f868 Igor Stoppa 2018-02-28 646 }
3406f868 Igor Stoppa 2018-02-28 647 atomic_long_add(nentries << order, &chunk->avail);
3406f868 Igor Stoppa 2018-02-28 648 rcu_read_unlock();
3406f868 Igor Stoppa 2018-02-28 649 return;
3406f868 Igor Stoppa 2018-02-28 650 }
3406f868 Igor Stoppa 2018-02-28 651 }
3406f868 Igor Stoppa 2018-02-28 652 rcu_read_unlock();
3406f868 Igor Stoppa 2018-02-28 653 WARN(true, "address not found in pool %s", pool->name);
f14f75b8 Jes Sorensen 2005-06-21 654 }
f14f75b8 Jes Sorensen 2005-06-21 655 EXPORT_SYMBOL(gen_pool_free);
7f184275 Huang Ying 2011-07-13 656 :::::: The code at line 624 was first introduced by commit
:::::: 3406f8684f722bb52edc94f65976585acb6382ce genalloc: track beginning of allocations
:::::: TO: Igor Stoppa <[email protected]>
:::::: CC: 0day robot <[email protected]>
---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation
kbuild test robot
build botRe: [PATCH 5/7] Pmalloc selftest
In reply to Igor StoppaThank you for the patch! Yet something to improve:
Hi Igor,
Thank you for the patch! Yet something to improve:
[auto build test ERROR on next-20180223]
[cannot apply to linus/master mmotm/master char-misc/char-misc-testing v4.16-rc3 v4.16-rc2 v4.16-rc1 v4.16-rc3] [if your patch is applied to the wrong git tree, please drop us a note to help improve the system]
url: https://github.com/0day-ci/linux/commits/Igor-Stoppa/mm-security-ro-protection-for-dynamic-data/20180302-232215
config: arm-allmodconfig (attached as .config)
compiler: arm-linux-gnueabi-gcc (Debian 7.2.0-11) 7.2.0
reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# save the attached .config to linux build tree
make.cross ARCH=arm
All errors (new ones prefixed by >>):
mm/test_pmalloc.c: In function 'test_pmalloc':
>> mm/test_pmalloc.c:52:14: error: implicit declaration of function 'vmalloc'; did you mean 'kvmalloc'? [-Werror=implicit-function-declaration]
var_vmall = vmalloc(SIZE_2);
^~~~~~~
kvmalloc
mm/test_pmalloc.c:52:12: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
var_vmall = vmalloc(SIZE_2);
^
>> mm/test_pmalloc.c:64:2: error: implicit declaration of function 'vfree'; did you mean 'kvfree'? [-Werror=implicit-function-declaration]
vfree(var_vmall);
^~~~~
kvfreecc1: some warnings being treated as errors
vim +52 mm/test_pmalloc.c
27
28 #define is_alloc_ok(variable, size) \
29 validate_alloc(true, variable, size)
30
31 #define is_alloc_no(variable, size) \
32 validate_alloc(false, variable, size)
33
34 void test_pmalloc(void)
35 {
36 struct gen_pool *pool_unprot;
37 struct gen_pool *pool_prot;
38 void *var_prot, *var_unprot, *var_vmall;
39
40 pr_notice("pmalloc-selftest");
41 pool_unprot = pmalloc_create_pool("unprotected", 0);
42 if (unlikely(!pool_unprot))
43 goto error;
44 pool_prot = pmalloc_create_pool("protected", 0);
45 if (unlikely(!(pool_prot)))
46 goto error_release;
47
48 pr_notice("Testing allocation capability");
49 var_unprot = pmalloc(pool_unprot, SIZE_1 - 1, GFP_KERNEL);
50 var_prot = pmalloc(pool_prot, SIZE_1, GFP_KERNEL);
51 *(int *)var_prot = 0;
> 52 var_vmall = vmalloc(SIZE_2);
53
54
55 pr_notice("Test correctness of is_pmalloc_object()");
56 WARN_ON(unlikely(!is_alloc_ok(var_unprot, 10)));
57 WARN_ON(unlikely(!is_alloc_ok(var_unprot, SIZE_1)));
58 WARN_ON(unlikely(!is_alloc_ok(var_unprot, PAGE_SIZE)));
59 WARN_ON(unlikely(!is_alloc_no(var_unprot, SIZE_1 + 1)));
60 WARN_ON(unlikely(!is_alloc_no(var_vmall, 10)));
61
62
63 pfree(pool_unprot, var_unprot);
> 64 vfree(var_vmall);---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Igor Stoppa.
.
Quoted 8 lines · Igor Stoppa
include/linux/genalloc.h +8
-0+ +/** +* gen_pool_dma_alloc() - allocate special memory from the pool for DMA usage +* @pool: pool to allocate from +* @size: number of bytes to allocate from the pool +* @dma: dma-view physical address return value. Use NULL if unneeded. +* +* Allocate the requested number of bytes from the specified pool.
include/linux/genalloc.h extern int gen_pool_add_virt(struct gen_pool *, unsigned long, phys_addr_t, · line 221
Quoted 10 lines
include/linux/genalloc.h +10
-0+* Uses the pool allocation function (with first-fit algorithm by default). +* Can not be used in NMI handler on architectures without +* NMI-safe cmpxchg implementation. +* +* Return: +* * address of the memory allocated - success +* * NULL - error +*/ +void *gen_pool_dma_alloc (struct gen_pool *pool,size_t size,dma_addr_t *dma); +
OK, so gen_pool_dma_alloc() is defined here, which believe is the API line being drawn for this series.
so,
.
.
.
Quoted 14 lines
/**
- *gen_pool_dma_alloc- allocate special memory from the pool for DMA usage
+ *gen_pool_dma_alloc()- allocate special memory from the pool for DMA usage
* @pool: pool to allocate from
* @size: number of bytes to allocate from the pool
* @dma: dma-view physical address return value. Use NULL if unneeded.lib/genalloc.c +2
-0@@ -342,14 +566,15 @@ EXPORT_SYMBOL(gen_pool_alloc_algo);* Uses the pool allocation function (with first-fit algorithm by default). * Can not be used in NMI handler on architectures without * NMI-safe cmpxchg implementation. +* +* Return:
lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc_algo); · line 352
Quoted 10 lines
lib/genalloc.c +2
-3+* * address of the memory allocated - success +* * NULL - error */ void *gen_pool_dma_alloc (struct gen_pool *pool,size_t size,dma_addr_t *dma) {unsigned long vaddr; -if (!pool) -return NULL ; -
why is this being removed? I don't believe this code was getting removed from your v17 series patches.
lib/genalloc.c void *gen_pool_dma_alloc(struct gen_pool *pool, size_t size, dma_addr_t *dma) · line 589
Quoted 7 lines
lib/genalloc.c +0
-0vaddr =gen_pool_alloc (pool, size);if (!vaddr)return NULL ;@@ -362,10 +587,10 @@ void *gen_pool_dma_alloc(struct gen_pool *pool, size_t size, dma_addr_t *dma)EXPORT_SYMBOL (gen_pool_dma_alloc);
Otherwise, looks good,
Re: [PATCH 2/7] genalloc: selftest
In reply to Igor Stoppalib/test_genalloc.c line 28
Quoted 10 lines
lib/test_genalloc.c new file +9
-0+ +/* +* In case of failure of any of these tests, memory corruption is almost +* guarranteed; allowing the boot to continue means risking to corrupt +* also any filesystem/block device accessed write mode. +* Therefore, BUG_ON() is used, when testing. +*/ + +
I like the explanation; good background info on why something is implemented the way it is :-).
Re: [PATCH 3/7] struct page: add field for vm_struct
In reply to Igor StoppaQuoted 47 lines · Igor Stoppa
When a page is used for virtual memory, it is often necessary to obtain 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, later on.
Signed-off-by Igor Stoppa <[email protected]>--- include/linux/mm_types.h | 1 + mm/vmalloc.c | 2 ++ 2 files changed, 3 insertions(+)include/linux/mm_types.h +1
-0@@ -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 +2
-0@@ -1536,6 +1536,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 ); }@@ -1705,6 +1706,7 @@ static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, area->nr_pages = i; goto fail; } + page->area = area; area->pages[i] = page;if (gfpflags_allow_blocking (gfp_mask|highmem_mask))cond_resched ();
Re: [PATCH 4/7] Protectable Memory
In reply to Igor Stoppasnip
.
.
.
mm/Kconfig config GUP_BENCHMARK · line 766
Quoted 4 lines
mm/Kconfig +4
-0+ +config PROTECTABLE_MEMORY + bool + depends on MMU
Curious, would you also want to depend on "SECURITY" as well, as this is being advertised as a compliment to __read_only_after_init, per the file header comments, as I'm assuming ro_after_init would be disabled if the SECURITY Kconfig selection is *NOT* selected?
Quoted 45 lines
mm/Kconfig +3
-0+ depends on ARCH_HAS_SET_MEMORY + select GENERIC_ALLOCATOR + default ymm/Makefile +1
-0@@ -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.omm/pmalloc.c new file +24
-0@@ -0,0 +1,468 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* pmalloc.c: Protectable Memory Allocator +* +* (C) Copyright 2017 Huawei Technologies Co. Ltd. +* Author: Igor Stoppa<[email protected]> +*/ + +#include <linux/printk.h> +#include <linux/init.h> +#include <linux/mm.h> +#include <linux/vmalloc.h> +#include <linux/genalloc.h> +#include <linux/kernel.h> +#include <linux/log2.h> +#include <linux/slab.h> +#include <linux/device.h> +#include <linux/atomic.h> +#include <linux/rculist.h> +#include <linux/set_memory.h> +#include <linux/bug.h> +#include <asm/cacheflush.h> +#include <asm/page.h> +
mm/pmalloc.c line 34
Quoted 10 lines
mm/pmalloc.c new file +10
-0+#include <linux/pmalloc.h> +/* +* pmalloc_data contains the data specific to a pmalloc pool, +* in a format compatible with the design of gen_alloc. +* Some of the fields are used for exposing the corresponding parameter +* to userspace, through sysfs. +*/ +struct pmalloc_data { +struct gen_pool *pool;/* Link back to the associated pool. */ +bool protected;/* Status of the pool: RO or RW. */
nitpick, you could probably get a tad bit better byte packing alignment of this struct if "bool protected" was stuck as the last element in this data structure.
Quoted 38 lines
mm/pmalloc.c new file +38
-0+struct kobj_attribute attr_protected;/* Sysfs attribute. */ +struct kobj_attribute attr_avail;/* Sysfs attribute. */ +struct kobj_attribute attr_size;/* Sysfs attribute. */ +struct kobj_attribute attr_chunks;/* Sysfs attribute. */ +struct kobject *pool_kobject; +struct list_head node;/* list of pools */ +}; + +static LIST_HEAD (pmalloc_final_list); +static LIST_HEAD (pmalloc_tmp_list); +static struct list_head *pmalloc_list = &pmalloc_tmp_list; +static DEFINE_MUTEX (pmalloc_mutex); +static struct kobject *pmalloc_kobject; + +static ssize_t pmalloc_pool_show_protected (struct kobject *dev, +struct kobj_attribute *attr, +char *buf) +{ +struct pmalloc_data *data; + + data = container_of(attr, struct pmalloc_data, attr_protected); +if (data->protected) +return sprintf (buf,"protected\n" ); +else +return sprintf (buf,"unprotected\n" ); +} + +static ssize_t pmalloc_pool_show_avail (struct kobject *dev, +struct kobj_attribute *attr, +char *buf) +{ +struct pmalloc_data *data; + + data = container_of(attr, struct pmalloc_data, attr_avail); +return sprintf (buf,"%lu\n" , + (unsigned long )gen_pool_avail (data->pool)); +} +
mm/pmalloc.c line 82
Quoted 10 lines
mm/pmalloc.c new file +10
-0+static ssize_t pmalloc_pool_show_size (struct kobject *dev, +struct kobj_attribute *attr, +char *buf) +{ +struct pmalloc_data *data; + + data = container_of(attr, struct pmalloc_data, attr_size); +return sprintf (buf,"%lu\n" , + (unsigned long )gen_pool_size (data->pool)); +}
Curious, will this show the size in bytes?
Quoted 57 lines
mm/pmalloc.c new file +57
-0+ +static void pool_chunk_number (struct gen_pool *pool, +struct gen_pool_chunk *chunk,void *data) +{ +unsigned long *counter = data; + + (*counter)++; +} + +static ssize_t pmalloc_pool_show_chunks (struct kobject *dev, +struct kobj_attribute *attr, +char *buf) +{ +struct pmalloc_data *data; +unsigned long chunks_num =0 ; + + data = container_of(attr, struct pmalloc_data, attr_chunks); +gen_pool_for_each_chunk (data->pool, pool_chunk_number, &chunks_num); +return sprintf (buf,"%lu\n" , chunks_num); +} + +/* Exposes the pool and its attributes through sysfs. */ +static struct kobject *pmalloc_connect (struct pmalloc_data *data) +{ +const struct attribute *attrs[] = { + &data->attr_protected.attr, + &data->attr_avail.attr, + &data->attr_size.attr, + &data->attr_chunks.attr, +NULL + }; +struct kobject *kobj; + + kobj =kobject_create_and_add (data->pool->name, pmalloc_kobject); +if (unlikely (!kobj)) +return NULL ; + +if (unlikely (sysfs_create_files (kobj, attrs) <0 )) { +kobject_put (kobj); + kobj =NULL ; + } +return kobj; +} + +/* Removes the pool and its attributes from sysfs. */ +static void pmalloc_disconnect (struct pmalloc_data *data, +struct kobject *kobj) +{ +const struct attribute *attrs[] = { + &data->attr_protected.attr, + &data->attr_avail.attr, + &data->attr_size.attr, + &data->attr_chunks.attr, +NULL + }; + +sysfs_remove_files (kobj, attrs);
mm/pmalloc.c line 149
Quoted 10 lines
mm/pmalloc.c new file +10
-0+kobject_put (kobj); +} + +/* Declares an attribute of the pool. */ +#define pmalloc_attr_init (data, attr_name) \ +do { \ + sysfs_attr_init(&data->attr_##attr_name.attr); \ + data->attr_##attr_name.attr.name = #attr_name; \ + data->attr_##attr_name.attr.mode = VERIFY_OCTAL_PERMISSIONS(0400); \ + data->attr_##attr_name.show = pmalloc_pool_show_##attr_name; \
Why are these ##attr's being used and not the #define macros already in the kernel (DEVICE_ATTR(), DEVICE_ATTR_RO(), etc found in /include/linux/device.h)? Those macros are much easier to read and use.
Quoted 307 lines
mm/pmalloc.c new file +307
-0+}while (0 ) + +struct gen_pool *pmalloc_create_pool(const char *name, int min_alloc_order) +{ +struct gen_pool *pool; +const char *pool_name; +struct pmalloc_data *data; + +if (unlikely (!name)) { +WARN (true,"unnamed pool" ); +return NULL ; + } + +if (min_alloc_order <0 ) + min_alloc_order =ilog2 (sizeof (unsigned long )); + + pool =gen_pool_create (min_alloc_order,NUMA_NO_NODE ); +if (unlikely (!pool)) +return NULL ; + +mutex_lock (&pmalloc_mutex); +list_for_each_entry (data, pmalloc_list, node) +if (!strcmp (name, data->pool->name)) + goto same_name_err; + + pool_name =kstrdup (name,GFP_KERNEL ); +if (unlikely (!pool_name)) + goto name_alloc_err; + + data =kzalloc (sizeof (struct pmalloc_data ),GFP_KERNEL ); +if (unlikely (!data)) + goto data_alloc_err; + + data->protected = false; + data->pool = pool; +pmalloc_attr_init (data, protected); +pmalloc_attr_init (data, avail); +pmalloc_attr_init (data, size); +pmalloc_attr_init (data, chunks); + pool->data = data; + pool->name = pool_name; + +list_add (&data->node, pmalloc_list); +if (pmalloc_list == &pmalloc_final_list) + data->pool_kobject =pmalloc_connect (data); +mutex_unlock (&pmalloc_mutex); +return pool; + +data_alloc_err: +kfree (pool_name); +name_alloc_err: +same_name_err: +mutex_unlock (&pmalloc_mutex); +gen_pool_destroy (pool); +return NULL ; +} + +static inline bool chunk_tagging (void *chunk,bool tag) +{ +struct vm_struct *area; +struct page *page; + +if (!is_vmalloc_addr (chunk)) +return false; + + page =vmalloc_to_page (chunk); +if (unlikely (!page)) +return false; + + area = page->area; +if (tag) + area->flags |=VM_PMALLOC ; +else + area->flags &= ~VM_PMALLOC ; +return true; +} + + +static inline bool tag_chunk (void *chunk) +{ +return chunk_tagging (chunk, true); +} + + +static inline bool untag_chunk (void *chunk) +{ +return chunk_tagging (chunk, false); +} + +enum { +INVALID_PMALLOC_OBJECT =-1 , +NOT_PMALLOC_OBJECT =0 , +VALID_PMALLOC_OBJECT =1 , +}; + +int is_pmalloc_object (const void *ptr,const unsigned long n) +{ +struct vm_struct *area; +struct page *page; +unsigned long area_start; +unsigned long area_end; +unsigned long object_start; +unsigned long object_end; + + +/* +* is_pmalloc_object gets called pretty late, so chances are high +* that the object is indeed of vmalloc type +*/ +if (unlikely (!is_vmalloc_addr (ptr))) +return NOT_PMALLOC_OBJECT ; + + page =vmalloc_to_page (ptr); +if (unlikely (!page)) +return NOT_PMALLOC_OBJECT ; + + area = page->area; + +if (likely (!(area->flags &VM_PMALLOC ))) +return NOT_PMALLOC_OBJECT ; + + area_start = (unsigned long )area->addr; + area_end = area_start + area->nr_pages *PAGE_SIZE -1 ; + object_start = (unsigned long )ptr; + object_end = object_start + n -1 ; + +if (likely ((area_start <= object_start) && + (object_end <= area_end))) +return VALID_PMALLOC_OBJECT ; +else +return INVALID_PMALLOC_OBJECT ; +} + + +bool pmalloc_prealloc (struct gen_pool *pool,size_t size) +{ +void *chunk; +size_t chunk_size; +bool add_error; + +/* Expand pool */ + chunk_size =roundup (size,PAGE_SIZE ); + chunk =vmalloc (chunk_size); +if (unlikely (chunk ==NULL )) +return false; + +/* Locking is already done inside gen_pool_add */ + add_error =gen_pool_add (pool, (unsigned long )chunk, chunk_size, +NUMA_NO_NODE ); +if (unlikely (add_error !=0 )) + goto abort; + +return true; +abort: +vfree_atomic (chunk); +return false; + +} + +void *pmalloc (struct gen_pool *pool,size_t size,gfp_t gfp) +{ +void *chunk; +size_t chunk_size; +bool add_error; +unsigned long retval; + +if (unlikely (((struct pmalloc_data *)(pool->data))->protected)) { +WARN (true,"pool %s is already protected" , pool->name); +return NULL ; + } + +retry_alloc_from_pool: + retval =gen_pool_alloc (pool, size); +if (retval) + goto return_allocation; + +if (unlikely ((gfp & __GFP_ATOMIC))) { +if (unlikely ((gfp & __GFP_NOFAIL))) + goto retry_alloc_from_pool; +else +return NULL ; + } + +/* Expand pool */ + chunk_size =roundup (size,PAGE_SIZE ); + chunk =vmalloc (chunk_size); +if (unlikely (!chunk)) { +if (unlikely ((gfp & __GFP_NOFAIL))) + goto retry_alloc_from_pool; +else +return NULL ; + } +if (unlikely (!tag_chunk (chunk))) + goto free; + +/* Locking is already done inside gen_pool_add */ + add_error =gen_pool_add (pool, (unsigned long )chunk, chunk_size, +NUMA_NO_NODE ); +if (unlikely (add_error)) + goto abort; + + retval =gen_pool_alloc (pool, size); +if (retval) { +return_allocation: + *(size_t *)retval = size; +if (gfp & __GFP_ZERO) +memset ((void *)retval,0 , size); +return (void *)retval; + } +/* +* Here there is no test for __GFP_NO_FAIL because, in case of +* concurrent allocation, one thread might add a chunk to the +* pool and this memory could be allocated by another thread, +* before the first thread gets a chance to use it. +* As long as vmalloc succeeds, it's ok to retry. +*/ + goto retry_alloc_from_pool; +abort: +untag_chunk (chunk); +free: +vfree_atomic (chunk); +return NULL ; +} + +static void pmalloc_chunk_set_protection (struct gen_pool *pool, +struct gen_pool_chunk *chunk, +void *data) +{ +const bool *flag = data; +size_t chunk_size = chunk->end_addr +1 - chunk->start_addr; +unsigned long pages = chunk_size /PAGE_SIZE ; + +if (unlikely (chunk_size & (PAGE_SIZE -1 ))) { +WARN (true,"Chunk size is not a multiple of PAGE_SIZE." ); +return ; + } + +if (*flag) +set_memory_ro (chunk->start_addr, pages); +else +set_memory_rw (chunk->start_addr, pages); +} + +static int pmalloc_pool_set_protection (struct gen_pool *pool,bool protection) +{ +struct pmalloc_data *data; +struct gen_pool_chunk *chunk; + + data = pool->data; +if (unlikely (data->protected == protection)) { +WARN (true,"The pool %s is already protected as requested" , + pool->name); +return 0 ; + } + data->protected = protection; +list_for_each_entry (chunk, &(pool)->chunks, next_chunk) +pmalloc_chunk_set_protection (pool, chunk, &protection); +return 0 ; +} + +int pmalloc_protect_pool (struct gen_pool *pool) +{ +return pmalloc_pool_set_protection (pool, true); +} + + +static void pmalloc_chunk_free (struct gen_pool *pool, +struct gen_pool_chunk *chunk,void *data) +{ +untag_chunk (chunk); +gen_pool_flush_chunk (pool, chunk); +vfree_atomic ((void *)chunk->start_addr); +} + + +int pmalloc_destroy_pool (struct gen_pool *pool) +{ +struct pmalloc_data *data; + + data = pool->data; + +mutex_lock (&pmalloc_mutex); +list_del (&data->node); +mutex_unlock (&pmalloc_mutex); + +if (likely (data->pool_kobject)) +pmalloc_disconnect (data, data->pool_kobject); + +pmalloc_pool_set_protection (pool, false); +gen_pool_for_each_chunk (pool, pmalloc_chunk_free,NULL ); +gen_pool_destroy (pool); +kfree (data); +return 0 ; +} + +/* +* When the sysfs is ready to receive registrations, connect all the +* pools previously created. Also enable further pools to be connected +* right away. +*/ +static int __init pmalloc_late_init (void ) +{ +struct pmalloc_data *data, *n; + + pmalloc_kobject =kobject_create_and_add ("pmalloc" , kernel_kobj); + +mutex_lock (&pmalloc_mutex);
mm/pmalloc.c line 466
Quoted 10 lines
mm/pmalloc.c new file +10
-0+ pmalloc_list = &pmalloc_final_list; + +if (likely (pmalloc_kobject !=NULL )) { +list_for_each_entry_safe (data, n, &pmalloc_tmp_list, node) { +list_move (&data->node, &pmalloc_final_list); +pmalloc_connect (data); + } + } +mutex_unlock (&pmalloc_mutex); +return 0 ;
I'd just go ahead and return a different value if pmalloc_kobject does equal to NULL. __init is already returning a value, and the __init is already checking an error case for failure, might as well go all the way and stick a little icing on the cake and return a different (errno) value for this case.
Quoted 4 lines
Thanks,
Jay
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Igor StoppaQuoted 47 lines · Igor Stoppa
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.cThe primary effect of this patch is that code using the
gen_alloclibrary does not need anymore to keep track of the size of the allocations it makes.Prior to this patch, it was necessary to keep track of the size of the allocation, so that it would be possible, later on, to know how much space should be freed.
Now, users of the api can choose to etiher still specify explicitly the size, or let the library determine it, by giving a value of 0.
However, even when the value is specified, the library still uses its on understanding of the space associated with a certain allocation, to confirm that they are consistent.
This verification also confirms that the patch works correctly.
Quoted 8 lines
Eventually, the extra parameter (and the corresponding verification) could be dropped, in favor of a simplified API.
Signed-off-by Igor Stoppa <[email protected]>--- include/linux/genalloc.h | 354 ++++++++++++++++++++--- lib/genalloc.c | 721 ++++++++++++++++++++++++++++++++++------------- 2 files changed, 837 insertions(+), 238 deletions(-)
Thanks for taking time to update the kernel-doc parts! Some docs related comments below.
Quoted 34 lines
include/linux/genalloc.h +6
-6@@ -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 */ };/* @@ -93,10 +93,40 @@ struct genpool_data_fixed {unsigned long offset;/* The offset of the specific region */ }; -extern struct gen_pool *gen_pool_create (int ,int ); -extern phys_addr_t gen_pool_virt_to_phys (struct gen_pool *pool,unsigned long ); -extern int gen_pool_add_virt (struct gen_pool *,unsigned long ,phys_addr_t , -size_t ,int ); +/** +* gen_pool_create() - create a new special memory pool +* @min_alloc_order: log base 2 of number of bytes each bitmap entry +* represents
include/linux/genalloc.h struct genpool_data_fixed { · line 109
Quoted 10 lines
include/linux/genalloc.h +10
-0+* @nid: node id of the node the pool structure should be allocated on, +* or -1 +* +* Create a new special memory pool that can be used to manage special +* purpose memory not managed by the regular kmalloc/kfree interface. +* +* Return: +* * pointer to the pool - success +* * NULL - otherwise +*/
If I'm not mistaken, several kernel-doc descriptions are duplicated now. Can you please keep a single copy? ;-)
Quoted 23 lines
include/linux/genalloc.h +20
-0+struct gen_pool *gen_pool_create (int min_alloc_order,int nid); + +/** +* gen_pool_add_virt() - add a new chunk of special memory to the pool +* @pool: pool to add new memory chunk to +* @virt: virtual starting address of memory chunk to add to pool +* @phys: physical starting address of memory chunk to add to pool +* @size: size in bytes of the memory chunk to add to pool +* @nid: node id of the node the chunk structure and bitmap should be +* allocated on, or -1 +* +* Add a new chunk of special memory to the specified pool. +* +* Return: +* * 0 - success +* * -ve errno - failure +*/ +int gen_pool_add_virt (struct gen_pool *pool,unsigned long virt, +phys_addr_t phys,size_t size,int nid); +/** * gen_pool_add - add a new chunk of special memory to the pool * @pool: pool to add new memory chunk to
...
Quoted 37 lines
lib/genalloc.c +29
-0@@ -26,6 +26,74 @@* * This source code is licensed under the GNU General Public License, * Version 2. See the file COPYING for more details. +* +* +* +* Encoding of the bitmap tracking the allocations +* ----------------------------------------------- +* +* The bitmap is composed of units of allocations. +* +* Each unit of allocation is represented using 2 consecutive bits. +* +* This makes it possible to encode, for each unit of allocation, +* information about: +* - allocation status (busy/free) +* - beginning of a sequennce of allocation units (first / successive) +* +* +* Dictionary of allocation units (msb to the left, lsb to the right): +* +* 11: first allocation unit in the allocation +* 10: any subsequent allocation unit (if any) in the allocation +* 00: available allocation unit +* 01: invalid +* +* Example, using the same notation as above - MSb.......LSb: +* +* ...000010111100000010101011 <-- Read in this direction. +* \__|\__|\|\____|\______| +* | | | | \___ 4 used allocation units +* | | | \___________ 3 empty allocation units
lib/genalloc.c line 67
Quoted 10 lines
lib/genalloc.c +10
-0+* | | \_________________ 1 used allocation unit +* | \___________________ 2 used allocation units +* \_______________________ 2 empty allocation units +* +* The encoding allows for lockless operations, such as: +* - search for a sufficiently large range of allocation units +* - reservation of a selected range of allocation units +* - release of a specific allocation +* +* The alignment at which to perform the research for sequence of empty
^ search?
Quoted 32 lines
lib/genalloc.c +29
-0+* allocation units (marked as zeros in the bitmap) is 2^1. +* +* This means that an allocation can start only at even places +* (bit 0, bit 2, etc.) in the bitmap. +* +* Therefore, the number of zeroes to look for must be twice the number +* of desired allocation units. +* +* When it's time to free the memory associated to an allocation request, +* it's a matter of checking if the corresponding allocation unit is +* really the beginning of an allocation (both bits are set to 1). +* +* Looking for the ending can also be performed locklessly. +* It's sufficient to identify the first mapped allocation unit +* that is represented either as free (00) or busy (11). +* Even if the allocation status should change in the meanwhile, it +* doesn't matter, since it can only transition between free (00) and +* first-allocated (11). +* +* The parameter indicating to the *_free() function the size of the +* space that should be freed can be either set to 0, for automated +* assessment, or it can be specified explicitly. +* +* In case it is specified explicitly, the value is verified agaisnt what +* the library is tracking internally. +* +* If ever needed, the bitmap could be extended, assigning larger amounts +* of bits to each allocation unit (the increase must follow powers of 2), +* to track other properties of the allocations. */ #include <linux/slab.h>
...
lib/genalloc.c line 226
Quoted 5 lines
lib/genalloc.c +3
-2-/* -* bitmap_set_ll - set the specified number of bits at the specified position + +/** +* get_boundary() - verifies address, then measure length.
There's some lack of consistency between the name and implementation and the description.
It seems that it would be simpler to actually make it get_length() and return the length of the allocation or nentries if the latter is smaller. Then in gen_pool_free() there will be no need to recalculate nentries again.
Quoted 5 lines
* @map: pointer to a bitmap
- * @start: a bit position in @map
- * @nr: number of bits to set
+ * @start_entry: the index of the first entry in the bitmap
+ * @nentries: number of entries to alter
Maybe: "maximal number of entries to check"?
Quoted 35 lines
*
- * Set @nr bits start from @start in @map lock-lessly. Several users
- * can set/clear the same bitmap simultaneously without lock. If two
- * users set the same bit, one user will return remain bits, otherwise
- * return 0.
+ * Return:
+ * * length of an allocation - success
+ * *-EINVAL- invalid parameters
*/lib/genalloc.c +4
-20-static int bitmap_set_ll (unsigned long *map,int start,int nr) +static int get_boundary (unsigned long *map,unsigned int start_entry, +unsigned int nentries) { -unsigned long *p = map +BIT_WORD (start); -const int size = start + nr; -int bits_to_set =BITS_PER_LONG - (start %BITS_PER_LONG ); -unsigned long mask_to_set =BITMAP_FIRST_WORD_MASK (start); - -while (nr - bits_to_set >=0 ) { -if (set_bits_ll (p, mask_to_set)) -return nr; - nr -= bits_to_set; - bits_to_set =BITS_PER_LONG ; - mask_to_set = ~0UL ; - p++; - } -if (nr) { - mask_to_set &=BITMAP_LAST_WORD_MASK (size); -if (set_bits_ll (p, mask_to_set)) -return nr; - } +int i; +unsigned long bitmap_entry; -return 0 ;
lib/genalloc.c line 250
Quoted 10 lines
lib/genalloc.c +10
-0+ +if (unlikely (get_bitmap_entry (map, start_entry) !=ENTRY_HEAD )) +return -EINVAL ; +for (i = start_entry +1 ; i < nentries; i++) { + bitmap_entry =get_bitmap_entry (map, i); +if (bitmap_entry ==ENTRY_HEAD || + bitmap_entry ==ENTRY_UNUSED ) +return i; + } +return nentries - start_entry;
Shouldn't it be "nentries + start_entry"?
Quoted 1 line
}
...
lib/genalloc.c unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size) · line 495
Quoted 6 lines
lib/genalloc.c +1
-1@@ -275,7 +492,7 @@ unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size)EXPORT_SYMBOL (gen_pool_alloc);/** -* gen_pool_alloc_algo - allocate special memory from the pool +* gen_pool_alloc_algo() - allocate special memory from the pool
+ using specified algorithm
lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 502
Quoted 5 lines
lib/genalloc.c +0
-0* @pool: pool to allocate from * @size: number of bytes to allocate from the pool * @algo: algorithm passed from caller @@ -285,14 +502,18 @@ EXPORT_SYMBOL(gen_pool_alloc);* Uses the pool allocation function (with first-fit algorithm by default).
"uses the provided @algo function to find room for the allocation"
Quoted 64 lines
lib/genalloc.c +21
-14* Can not be used in NMI handler on architectures without * NMI-safe cmpxchg implementation. +* +* Return: +* * address of the memory allocated - success +* * NULL - error */ unsigned long gen_pool_alloc_algo (struct gen_pool *pool,size_t size,genpool_algo_t algo,void *data) {struct gen_pool_chunk *chunk;unsigned long addr =0 ; -int order = pool->min_alloc_order; -int nbits, start_bit, end_bit, remain; +unsigned int order = pool->min_alloc_order; +unsigned int nentries, start_entry, end_entry, remain;#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG BUG_ON (in_nmi ());@@ -301,29 +522,32 @@ unsigned long gen_pool_alloc_algo(struct gen_pool *pool, size_t size,if (size ==0 )return 0 ; - nbits = (size + (1UL << order) -1 ) >> order; + nentries =mem_to_units (size, order);rcu_read_lock ();list_for_each_entry_rcu (chunk, &pool->chunks, next_chunk) {if (size >atomic_long_read (&chunk->avail))continue ; - start_bit =0 ; - end_bit =chunk_size (chunk) >> order; + start_entry =0 ; + end_entry =chunk_size (chunk) >> order; retry: - start_bit =algo (chunk->bits, end_bit, start_bit, - nbits, data, pool); -if (start_bit >= end_bit) + start_entry =algo (chunk->entries, end_entry, start_entry, + nentries, data, pool); +if (start_entry >= end_entry)continue ; - remain =bitmap_set_ll (chunk->bits, start_bit, nbits); + remain =alter_bitmap_ll (SET_BITS , chunk->entries, + start_entry, nentries);if (remain) { - remain =bitmap_clear_ll (chunk->bits, start_bit, - nbits - remain); -BUG_ON (remain); + remain =alter_bitmap_ll (CLEAR_BITS , + chunk->entries, + start_entry, + nentries - remain); goto retry; } - addr = chunk->start_addr + ((unsigned long )start_bit << order); - size = nbits << order; + addr = chunk->start_addr + + ((unsigned long )start_entry << order); + size = nentries << order;atomic_long_sub (size, &chunk->avail);break ; }
...
Quoted 28 lines
lib/genalloc.c +7
-5@@ -738,17 +1065,19 @@ 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 */ struct gen_pool *of_gen_pool_get (struct device_node *np, -const char *propname,int index) +const char *propname,int index) {struct platform_device *pdev;struct device_node *np_pool, *parent;Signature · 1 line
2.14.1
Signature · 2 lines
Sincerely yours, Mike.
Re: [PATCH 7/7] Documentation for Pmalloc
In reply to Igor StoppaQuoted 27 lines · Igor Stoppa
Detailed documentation about the protectable memory allocator.
Signed-off-by Igor Stoppa <[email protected]>--- Documentation/core-api/index.rst | 1 + Documentation/core-api/pmalloc.rst | 111 +++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 Documentation/core-api/pmalloc.rstDocumentation/core-api/index.rst +1
-0@@ -25,6 +25,7 @@ Core utilities genalloc errseq printk-formats + pmalloc Interfaces for kernel debugging ===============================Documentation/core-api/pmalloc.rst new file +0
-0
Documentation/core-api/pmalloc.rst line 1
Quoted 1 line
Documentation/core-api/pmalloc.rst new file +1
-0@@ -0,0 +1,111 @@ +.. SPDX-License-Identifier: GPL-2.0
Please add a label to allow cross-referencing
Quoted 9 lines
Documentation/core-api/pmalloc.rst new file +9
-0+ +Protectable memory allocator +============================ + +Purpose +------- + +The pmalloc library is meant to provide R/O status to data that, for some +reason, could neither be declared as constant, nor could it take advantage
Documentation/core-api/pmalloc.rst line 20
Quoted 10 lines
Documentation/core-api/pmalloc.rst new file +10
-0+of the qualifier __ro_after_init, but is write-once and read-only in spirit. +It protects data from both accidental and malicious overwrites. + +Example: A policy that is loaded from userspace. + + +Concept +------- + +pmalloc builds on top of genalloc, using the same concept of memory pools.
It would be nice to add a label to genalloc.rst and reference it here:
Documentation/core-api/genalloc.rst +2 -0
@@ -1,3 +1,5 @@ +.. _genalloc: + The genalloc/genpool subsystem ==============================
Documentation/core-api/pmalloc.rst line 24
Quoted 4 lines
Documentation/core-api/pmalloc.rst new file +4
-0+ +The value added by pmalloc is that now the memory contained in a pool can +become R/O, for the rest of the life of the pool. +
IMHO, "read only" looks better than R/O
Quoted 35 lines
Documentation/core-api/pmalloc.rst new file +35
-0+Different kernel drivers and threads can use different pools, for finer +control of what becomes R/O and when. And for improved lockless concurrency. + + +Caveats +------- + +- Memory freed while a pool is not yet protected will be reused. + +- Once a pool is protected, it's not possible to allocate any more memory + from it. + +- Memory "freed" from a protected pool indicates that such memory is not + in use anymore by the requester; however, it will not become available + for further use, until the pool is destroyed. + +- pmalloc does not provide locking support with respect to allocating vs + protecting an individual pool, for performance reasons. + It is recommended not to share the same pool between unrelated functions. + Should sharing be a necessity, the user of the shared pool is expected + to implement locking for that pool. + +- pmalloc uses genalloc to optimize the use of the space it allocates + through vmalloc. Some more TLB entries will be used, however less than + in the case of using vmalloc directly. The exact number depends on the + size of each allocation request and possible slack. + +- Considering that not much data is supposed to be dynamically allocated + and then marked as read-only, it shouldn't be an issue that the address + range for pmalloc is limited, on 32-bit systems. + +- Regarding SMP systems, the allocations are expected to happen mostly + during an initial transient, after which there should be no more need to + perform cross-processor synchronizations of page tables. +
Documentation/core-api/pmalloc.rst line 69
Quoted 10 lines
Documentation/core-api/pmalloc.rst new file +10
-0+- To facilitate the conversion of existing code to pmalloc pools, several + helper functions are provided, mirroring their kmalloc counterparts. + + +Use +--- + +The typical sequence, when using pmalloc, is: + +1. create a pool
Can we use #. instead of numbers for the numbered list items?
Documentation/core-api/pmalloc.rst line 76
Quoted 7 lines
Documentation/core-api/pmalloc.rst new file +7
-0+.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc_create_pool + +2. [optional] pre-allocate some memory in the pool + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc_prealloc
Maybe it's better to have a short reference to the function and keep all the elaborate descriptions in the API section?
For instance, something like
Documentation/core-api/pmalloc.rst +1 -2
@@ -68,8 +70,7 @@ The typical sequence, when using pmalloc, is: 1. create a pool -.. kernel-doc:: include/linux/pmalloc.h - :functions: pmalloc_create_pool + :c:func:`pmalloc_create_pool`
Quoted 36 lines
Documentation/core-api/pmalloc.rst new file +33
-0+3. issue one or more allocation requests to the pool with locking as needed + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pzalloc + +4. initialize the memory obtained with desired values + +5. [optional] iterate over points 3 & 4 as needed + +6. write-protect the pool + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc_protect_pool + +7. use in read-only mode the handles obtained through the allocations + +8. [optional] release all the memory allocated + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pfree + +9. [optional, but depends on point 8] destroy the pool + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc_destroy_pool + +API +--- + +.. kernel-doc:: include/linux/pmalloc.hSignature · 1 line
2.14.1
Signature · 2 lines
Sincerely yours, Mike.
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Igor StoppaQuoted 46 lines · Igor Stoppa
+ * Encoding of the bitmap tracking the allocations
+ * -----------------------------------------------
+ *
+ * The bitmap is composed of units of allocations.
+ *
+ * Each unit of allocation is represented using 2 consecutive bits.
+ *
+ * This makes it possible to encode, for each unit of allocation,
+ * information about:
+ * - allocation status (busy/free)
+ * - beginning of a sequennce of allocation units (first / successive)
+ *
+ *
+ * Dictionary of allocation units (msb to the left, lsb to the right):
+ *
+ * 11: first allocation unit in the allocation
+ * 10: any subsequent allocation unit (if any) in the allocation
+ * 00: available allocation unit
+ * 01: invalid
+ *
+ * Example, using the same notation as above - MSb.......LSb:
+ *
+ * ...000010111100000010101011 <-- Read in this direction.+ * \__|\__|\|\____|\______| + * | | | | \___ 4 used allocation units + * | | | \___________ 3 empty allocation units + * | | \_________________ 1 used allocation unit + * | \___________________ 2 used allocation units + * \_______________________ 2 empty allocation units+ *
+ * The encoding allows for lockless operations, such as:
+ * - search for a sufficiently large range of allocation units
+ * - reservation of a selected range of allocation units
+ * - release of a specific allocation
+ *
+ * The alignment at which to perform the research for sequence of empty
+ * allocation units (marked as zeros in the bitmap) is 2^1.
+ *
+ * This means that an allocation can start only at even places
+ * (bit 0, bit 2, etc.) in the bitmap.
+ *
+ * Therefore, the number of zeroes to look for must be twice the number
+ * of desired allocation units.
+ *
+ * When it's time to free the memory associated to an allocation request,
+ * it's a matter of checking if the corresponding allocation unit is
Quoted 8 lines
+ * really the beginning of an allocation (both bits are set to 1).
+ *
+ * Looking for the ending can also be performed locklessly.
+ * It's sufficient to identify the first mapped allocation unit
+ * that is represented either as free (00) or busy (11).
+ * Even if the allocation status should change in the meanwhile, it
+ * doesn't matter, since it can only transition between free (00) and
+ * first-allocated (11).
This seems unnecessarily complicated. Why not handle it like this:
- Double the bitmap in size (as you have done) but
- The first half of the bits are unchanged from the existing implementation
- The second half of the bits are used for determining the length
On allocation, you look for a sufficiently-large string of 0 bits in the first-half. When you find it, you set all of them to 1, and set one bit in the second-half to indicate where the tail of the allocation is (you might actually want to use an rbtree or something to handle this ... using all these bits seems pretty inefficient).
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Mike RapoportQuoted 15 lines · Mike Rapoport
Quoted 6 lines
+/**
+ *gen_pool_create()- create a new special memory pool
+ * @min_alloc_order: log base 2 of number of bytes each bitmap entry
+ * represents
+ * @nid: node id of the node the pool structure should be allocated on,
+ * or -1Quoted 8 lines
+ *
+ * Create a new special memory pool that can be used to manage special
+ * purpose memory not managed by the regular kmalloc/kfree interface.
+ *
+ * Return:
+ * * pointer to the pool - success
+ * * NULL - otherwise
+ */
Quoted 2 lines
If I'm not mistaken, several kernel-doc descriptions are duplicated now. Can you please keep a single copy? ;-)
I think the problem is that Igor has chosen to put the kernel-doc with the function declaration. I think we usually recommend putting it with the definition so it's more likely to be updated.
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Matthew WilcoxQuoted 56 lines · Matthew Wilcox
Quoted 46 lines · Igor Stoppa
+ * Encoding of the bitmap tracking the allocations
+ * -----------------------------------------------
+ *
+ * The bitmap is composed of units of allocations.
+ *
+ * Each unit of allocation is represented using 2 consecutive bits.
+ *
+ * This makes it possible to encode, for each unit of allocation,
+ * information about:
+ * - allocation status (busy/free)
+ * - beginning of a sequennce of allocation units (first / successive)
+ *
+ *
+ * Dictionary of allocation units (msb to the left, lsb to the right):
+ *
+ * 11: first allocation unit in the allocation
+ * 10: any subsequent allocation unit (if any) in the allocation
+ * 00: available allocation unit
+ * 01: invalid
+ *
+ * Example, using the same notation as above - MSb.......LSb:
+ *
+ * ...000010111100000010101011 <-- Read in this direction.+ * \__|\__|\|\____|\______| + * | | | | \___ 4 used allocation units + * | | | \___________ 3 empty allocation units + * | | \_________________ 1 used allocation unit + * | \___________________ 2 used allocation units + * \_______________________ 2 empty allocation units+ *
+ * The encoding allows for lockless operations, such as:
+ * - search for a sufficiently large range of allocation units
+ * - reservation of a selected range of allocation units
+ * - release of a specific allocation
+ *
+ * The alignment at which to perform the research for sequence of empty
+ * allocation units (marked as zeros in the bitmap) is 2^1.
+ *
+ * This means that an allocation can start only at even places
+ * (bit 0, bit 2, etc.) in the bitmap.
+ *
+ * Therefore, the number of zeroes to look for must be twice the number
+ * of desired allocation units.
+ *
+ * When it's time to free the memory associated to an allocation request,
+ * it's a matter of checking if the corresponding allocation unit isQuoted 8 lines
+ * really the beginning of an allocation (both bits are set to 1).
+ *
+ * Looking for the ending can also be performed locklessly.
+ * It's sufficient to identify the first mapped allocation unit
+ * that is represented either as free (00) or busy (11).
+ * Even if the allocation status should change in the meanwhile, it
+ * doesn't matter, since it can only transition between free (00) and
+ * first-allocated (11).
Quoted 1 line
This seems unnecessarily complicated.
TBH it seemed to me a natural extension of the existing encoding :-)
Quoted 5 lines
Why not handle it like this:
- Double the bitmap in size (as you have done) but
- The first half of the bits are unchanged from the existing implementation
- The second half of the bits are used for determining the length
Wouldn't that mean a less tight loop and less localized data? The implementation from this patch does not have to jump elsewhere, when (un)marking the allocation units and the start.
Quoted 5 lines
On allocation, you look for a sufficiently-large string of 0 bits in the first-half. When you find it, you set all of them to 1, and set one bit in the second-half to indicate where the tail of the allocation is (you might actually want to use an rbtree or something to handle this ... using all these bits seems pretty inefficient).
1 bit maps to 1 unit of allocation, which is very seldom 1 byte. For pmalloc use, I expect that the average allocation is likely to be 2-4 units, where 1 unit equals either a 32 or 64 bits word. So it's probably likely that for every couple of allocation units, one is marked as start-of-allocation.
In other cases where genalloc is used, like the tracking of uncached pages, 1 unit of allocation equals to 1 page.
I would expect the rbtree to end up generating a far larger footprint.
For the same reasons, since the bitmap is implemented using unsigned longs, chances are high that one allocation will fit in one bitmap "word", which means that if the "beginning" bit and the "occupied" bit are adjacent, one write is sufficient.
In the case you describe, it would be almost always at least 2.
I do not have factual evidence to back my reasoning, but it seems more likely to be the case, from my analysis of data types that could belong to pools (both existing users of genalloc and my experiments with SELinux data structures and pmalloc).
Even in the XFS case, if I understood correctly, it was about protecting 1 or 2 pages at a time, which seems to fit what I have empirically observed.
What makes you think otherwise?
--
igor
Re: [PATCH 5/7] Pmalloc selftest
In reply to Igor StoppaLooks good, and a bit more thorough test than last iteration.
Quoted 203 lines · Igor Stoppa
Add basic self-test functionality for pmalloc.
The testing is introduced as early as possible, right after the main dependency, genalloc, has passed successfully, so that it can help diagnosing failures in pmalloc users.
Signed-off-by Igor Stoppa <[email protected]>--- include/linux/test_pmalloc.h | 24 +++++++++++ init/main.c | 2 + mm/Kconfig | 10 +++++ mm/Makefile | 1 + mm/test_pmalloc.c | 100 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 137 insertions(+)create mode 100644
include/linux/test_pmalloc.h
create mode 100644mm/test_pmalloc.cinclude/linux/test_pmalloc.h new file +24
-0@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* test_pmalloc.h +* +* (C) Copyright 2018 Huawei Technologies Co. Ltd. +* Author: Igor Stoppa <[email protected]> +*/ + + +#ifndef __LINUX_TEST_PMALLOC_H +#define __LINUX_TEST_PMALLOC_H + + +#ifdef CONFIG_TEST_PROTECTABLE_MEMORY + +void test_pmalloc (void ); + +#else + +static inline void test_pmalloc (void ){}; + +#endif + +#endif init/main.c +2
-0@@ -91,6 +91,7 @@#include <linux/rodata_test.h> #include <linux/jump_label.h> #include <linux/test_genalloc.h> +#include <linux/test_pmalloc.h> #include <asm/io.h> #include <asm/bugs.h> @@ -663,6 +664,7 @@ asmlinkage __visible void __init start_kernel(void)mem_encrypt_init ();test_genalloc (); +test_pmalloc ();#ifdef CONFIG_BLK_DEV_INITRD if (initrd_start && !initrd_below_start_ok &&page_to_pfn (virt_to_page ((void *)initrd_start)) < min_low_pfn) {mm/Kconfig +10
-0@@ -767,3 +767,13 @@ config PROTECTABLE_MEMORY depends on ARCH_HAS_SET_MEMORY select GENERIC_ALLOCATOR default y + +config TEST_PROTECTABLE_MEMORY + bool "Run self test for pmalloc memory allocator" + depends on MMU + 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@@ -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_TEST_PROTECTABLE_MEMORY) += test_pmalloc.o obj-$(CONFIG_KSM) += ksm.o obj-$(CONFIG_PAGE_POISONING) += page_poison.o obj-$(CONFIG_SLAB) += slab.omm/test_pmalloc.c new file +100
-0@@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* test_pmalloc.c +* +* (C) Copyright 2018 Huawei Technologies Co. Ltd. +* Author: Igor Stoppa <[email protected]> +*/ + +#include <linux/pmalloc.h> +#include <linux/mm.h> +#include <linux/test_pmalloc.h> +#include <linux/bug.h> + +#define SIZE_1 (PAGE_SIZE * 3) +#define SIZE_2 1000 + +static inline bool validate_alloc (bool expected,void *addr, +unsigned long size) +{ +bool test; + + test =is_pmalloc_object (addr, size) >0 ; +pr_notice ("must be %s: %s" , + expected ?"ok" :"no" , test ?"ok" :"no" ); +return test == expected; +} + +#define is_alloc_ok (variable, size) \ + validate_alloc(true, variable, size) + +#define is_alloc_no (variable, size) \ + validate_alloc(false, variable, size) + +void test_pmalloc (void ) +{ +struct gen_pool *pool_unprot; +struct gen_pool *pool_prot; +void *var_prot, *var_unprot, *var_vmall; + +pr_notice ("pmalloc-selftest" ); + pool_unprot =pmalloc_create_pool ("unprotected" ,0 ); +if (unlikely (!pool_unprot)) + goto error; + pool_prot =pmalloc_create_pool ("protected" ,0 ); +if (unlikely (!(pool_prot))) + goto error_release; + +pr_notice ("Testing allocation capability" ); + 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 ); + + +pr_notice ("Test correctness of is_pmalloc_object()" ); +WARN_ON (unlikely (!is_alloc_ok (var_unprot,10 ))); +WARN_ON (unlikely (!is_alloc_ok (var_unprot,SIZE_1 ))); +WARN_ON (unlikely (!is_alloc_ok (var_unprot,PAGE_SIZE ))); +WARN_ON (unlikely (!is_alloc_no (var_unprot,SIZE_1 +1 ))); +WARN_ON (unlikely (!is_alloc_no (var_vmall,10 ))); + + +pfree (pool_unprot, var_unprot); +vfree (var_vmall); + +pmalloc_protect_pool (pool_prot); + +/* +* This will intentionally trigger a WARN, because the pool being +* allocated from is already protected. +*/ +pr_notice ("Test allocation from a protected pool." +"Expect WARN in pmalloc" ); +if (unlikely (pmalloc (pool_prot,10 ,GFP_KERNEL ))) +WARN (true,"no memory from a protected pool" ); + +/* +* 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. +*/ +pr_notice ("pmalloc-selftest:" +" Expect WARN in pmalloc_pool_set_protection below." ); +pmalloc_destroy_pool (pool_unprot); +pr_notice ("pmalloc-selftest:" +"Critical point for expected WARN passed." ); + +/* This must not cause WARNings */ +pr_notice ("pmalloc-selftest:" +"Expect no WARN below." ); +pmalloc_destroy_pool (pool_prot); +pr_notice ("pmalloc-selftest:" +"Critical point for unexpected WARN passed." ); +return ; +error_release: +pmalloc_destroy_pool (pool_unprot); +error: +WARN (true,"Unable to allocate memory for pmalloc selftest." ); +}
Re: [PATCH 6/7] lkdtm: crash on overwriting protected pmalloc var
In reply to Igor StoppaQuoted 15 lines · Igor Stoppa
Verify that pmalloc read-only protection is in place: trying to overwrite a protected variable will crash the kernel.
Signed-off-by Igor Stoppa <[email protected]>--- drivers/misc/lkdtm.h | 1 + drivers/misc/lkdtm_core.c | 3 +++ drivers/misc/lkdtm_perms.c | 28 ++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+)drivers/misc/lkdtm.h +0
-0
drivers/misc/lkdtm.h void lkdtm_READ_BUDDY_AFTER_FREE(void); · line 41
Quoted 4 lines
drivers/misc/lkdtm.h +1
-0@@ -38,6 +38,7 @@ void lkdtm_READ_BUDDY_AFTER_FREE(void);void __init lkdtm_perms_init (void );void lkdtm_WRITE_RO (void );void lkdtm_WRITE_RO_AFTER_INIT (void ); +void lkdtm_WRITE_RO_PMALLOC (void );
Does this need some sort of #ifdef too?
Quoted 47 lines
drivers/misc/lkdtm.h +0
-0void lkdtm_WRITE_KERN (void );void lkdtm_EXEC_DATA (void );void lkdtm_EXEC_STACK (void );drivers/misc/lkdtm_core.c +3
-0@@ -155,6 +155,9 @@ static const struct crashtype crashtypes[] = {CRASHTYPE (ACCESS_USERSPACE ),CRASHTYPE (WRITE_RO ),CRASHTYPE (WRITE_RO_AFTER_INIT ), +#ifdef CONFIG_PROTECTABLE_MEMORY +CRASHTYPE (WRITE_RO_PMALLOC ), +#endifCRASHTYPE (WRITE_KERN ),CRASHTYPE (REFCOUNT_INC_OVERFLOW ), CRASHTYPE(REFCOUNT_ADD_OVERFLOW),drivers/misc/lkdtm_perms.c +15
-0@@ -9,6 +9,7 @@#include <linux/vmalloc.h> #include <linux/mman.h> #include <linux/uaccess.h> +#include <linux/pmalloc.h> #include <asm/cacheflush.h> /* Whether or not to fill the target memory area with do_nothing(). */ @@ -104,6 +105,33 @@ void lkdtm_WRITE_RO_AFTER_INIT(void) *ptr ^=0xabcd1234 ; } +#ifdef CONFIG_PROTECTABLE_MEMORY +void lkdtm_WRITE_RO_PMALLOC (void ) +{ +struct gen_pool *pool; +int *i; + + pool =pmalloc_create_pool ("pool" ,0 ); +if (unlikely (!pool)) { +pr_info ("Failed preparing pool for pmalloc test." ); +return ; + } + + i = (int *)pmalloc (pool,sizeof (int ),GFP_KERNEL ); +if (unlikely (!i)) {
drivers/misc/lkdtm_perms.c void lkdtm_WRITE_RO_AFTER_INIT(void) · line 131
Quoted 10 lines
drivers/misc/lkdtm_perms.c +10
-0+pr_info ("Failed allocating memory for pmalloc test." ); +pmalloc_destroy_pool (pool); +return ; + } + + *i =INT_MAX ; +pmalloc_protect_pool (pool); + +pr_info ("attempting bad pmalloc write at %p\n" , i); + *i =0 ;
OK, now I'm on the right version of this patch series, same comment applies. I don't get the local *i assignment at the end of the function, but seems harmless.
Except the two minor comments, otherwise,
Quoted 6 lines
drivers/misc/lkdtm_perms.c +3
-0+} +#endif +void lkdtm_WRITE_KERN (void ) {size_t size;
Re: [PATCH 7/7] Documentation for Pmalloc
In reply to Igor StoppaMinus the comment-fixes Mike Rapoport mentioned, looks good:
Quoted 138 lines · Igor Stoppa
Detailed documentation about the protectable memory allocator.
Signed-off-by Igor Stoppa <[email protected]>--- Documentation/core-api/index.rst | 1 + Documentation/core-api/pmalloc.rst | 111 +++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+)create mode 100644
Documentation/core-api/pmalloc.rstDocumentation/core-api/index.rst +1
-0@@ -25,6 +25,7 @@ Core utilities genalloc errseq printk-formats + pmalloc Interfaces for kernel debugging ===============================Documentation/core-api/pmalloc.rst new file +111
-0@@ -0,0 +1,111 @@ +.. SPDX-License-Identifier: GPL-2.0 + +Protectable memory allocator +============================ + +Purpose +------- + +The pmalloc library is meant to provide R/O status to data that, for some +reason, could neither be declared as constant, nor could it take advantage +of the qualifier __ro_after_init, but is write-once and read-only in spirit. +It protects data from both accidental and malicious overwrites. + +Example: A policy that is loaded from userspace. + + +Concept +------- + +pmalloc builds on top of genalloc, using the same concept of memory pools. + +The value added by pmalloc is that now the memory contained in a pool can +become R/O, for the rest of the life of the pool. + +Different kernel drivers and threads can use different pools, for finer +control of what becomes R/O and when. And for improved lockless concurrency. + + +Caveats +------- + +- Memory freed while a pool is not yet protected will be reused. + +- Once a pool is protected, it's not possible to allocate any more memory + from it. + +- Memory "freed" from a protected pool indicates that such memory is not + in use anymore by the requester; however, it will not become available + for further use, until the pool is destroyed. + +- pmalloc does not provide locking support with respect to allocating vs + protecting an individual pool, for performance reasons. + It is recommended not to share the same pool between unrelated functions. + Should sharing be a necessity, the user of the shared pool is expected + to implement locking for that pool. + +- pmalloc uses genalloc to optimize the use of the space it allocates + through vmalloc. Some more TLB entries will be used, however less than + in the case of using vmalloc directly. The exact number depends on the + size of each allocation request and possible slack. + +- Considering that not much data is supposed to be dynamically allocated + and then marked as read-only, it shouldn't be an issue that the address + range for pmalloc is limited, on 32-bit systems. + +- Regarding SMP systems, the allocations are expected to happen mostly + during an initial transient, after which there should be no more need to + perform cross-processor synchronizations of page tables. + +- To facilitate the conversion of existing code to pmalloc pools, several + helper functions are provided, mirroring their kmalloc counterparts. + + +Use +--- + +The typical sequence, when using pmalloc, is: + +1. create a pool + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc_create_pool + +2. [optional] pre-allocate some memory in the pool + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc_prealloc + +3. issue one or more allocation requests to the pool with locking as needed + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pzalloc + +4. initialize the memory obtained with desired values + +5. [optional] iterate over points 3 & 4 as needed + +6. write-protect the pool + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc_protect_pool + +7. use in read-only mode the handles obtained through the allocations + +8. [optional] release all the memory allocated + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pfree + +9. [optional, but depends on point 8] destroy the pool + +.. kernel-doc:: include/linux/pmalloc.h + :functions: pmalloc_destroy_pool + +API +--- + +.. kernel-doc:: include/linux/pmalloc.h
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to J FreyenseeQuoted 52 lines · J Freyensee
.
.Quoted 8 lines · Igor Stoppa
include/linux/genalloc.h +8
-0+ +/** +* gen_pool_dma_alloc() - allocate special memory from the pool for DMA usage +* @pool: pool to allocate from +* @size: number of bytes to allocate from the pool +* @dma: dma-view physical address return value. Use NULL if unneeded. +* +* Allocate the requested number of bytes from the specified pool. include/linux/genalloc.h extern int gen_pool_add_virt(struct gen_pool *, unsigned long, phys_addr_t, · line 221
Quoted 10 lines
include/linux/genalloc.h +10
-0+* Uses the pool allocation function (with first-fit algorithm by default). +* Can not be used in NMI handler on architectures without +* NMI-safe cmpxchg implementation. +* +* Return: +* * address of the memory allocated - success +* * NULL - error +*/ +void *gen_pool_dma_alloc (struct gen_pool *pool,size_t size,dma_addr_t *dma); +OK, so
gen_pool_dma_alloc()is defined here, which believe is the API line being drawn for this series.so,
.
.
.Quoted 21 lines
/**
- *gen_pool_dma_alloc- allocate special memory from the pool for DMA usage
+ *gen_pool_dma_alloc()- allocate special memory from the pool for DMA usage
* @pool: pool to allocate from
* @size: number of bytes to allocate from the pool
* @dma: dma-view physical address return value. Use NULL if unneeded.lib/genalloc.c +4
-0@@ -342,14 +566,15 @@ EXPORT_SYMBOL(gen_pool_alloc_algo);* Uses the pool allocation function (with first-fit algorithm by default). * Can not be used in NMI handler on architectures without * NMI-safe cmpxchg implementation. +* +* Return: +* * address of the memory allocated - success +* * NULL - error */ void *gen_pool_dma_alloc (struct gen_pool *pool,size_t size,dma_addr_t *dma) {unsigned long vaddr;
Quoted 5 lines
lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc_algo); · line 352
Quoted 3 lines
lib/genalloc.c +0
-3-if (!pool) -return NULL ; -why is this being removed? I don't believe this code was getting removed from your v17 series patches.
Because, as Matthew Wilcox pointed out [1] (well, that's how I understood it) de-referencing a NULL pointer will cause the kernel to complain loudly.
Where is the NULL pointer coming from?
a) from a bug in the user of the API - in that case it will be noticed, reported and fixed, that is how also other in-kernel APIs work
b) from an attacker - it will still trigger an error from the kernel, but it cannot really do much else, besides crashing repeatedly and causing a DOS. However, there are so many other places that could be under similar attack, that it doesn't seem to make a difference having a check here only.
If the value was coming from userspace, that would be a completely different case and some sort of sanitation would be mandatory.
Quoted 3 lines
Otherwise, looks good,
Reviewed-by Jay Freyensee <[email protected]>
thanks
[1] http://www.openwall.com/lists/kernel-hardening/2018/02/26/16
--
igor
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Igor StoppaQuoted 1 line · Igor Stoppa
On 06/03/2018 16:10, Matthew Wilcox wrote:
[...]
Quoted 3 lines
Quoted 1 line
This seems unnecessarily complicated.
TBH it seemed to me a natural extension of the existing encoding :-)
BTW, to provide some background, this is where it begun:
http://www.openwall.com/lists/kernel-hardening/2017/08/18/4
Probably that comment about "keeping existing behavior and managing two bitmaps locklessly" is what made me think of growing the 1-bit-per-unit into a 1-word-per-unit.
--
igor
Re: [PATCH 6/7] lkdtm: crash on overwriting protected pmalloc var
In reply to J FreyenseeQuoted 1 line · J Freyensee
On 2/28/18 12:06 PM, Igor Stoppa wrote:
[...]
Quoted 6 lines
Quoted 4 lines
void
__initlkdtm_perms_init(void);
voidlkdtm_WRITE_RO(void);
voidlkdtm_WRITE_RO_AFTER_INIT(void);
+voidlkdtm_WRITE_RO_PMALLOC(void);Does this need some sort of #ifdef too?
Not strictly. It's just a function declaration.
As long as it is not used, the linker will not complain. The #ifdef placed around the use and definition is sufficient, from a correctness perspective.
But it's a different question if there is any standard in linux about hiding also the declaration.
I am not very fond of #ifdefs, so when I can I try to avoid them.
Quoted 6 lines
drivers/misc/lkdtm_perms.c void lkdtm_WRITE_RO_AFTER_INIT(void) · line 131
Quoted 2 lines
drivers/misc/lkdtm_perms.c +2
-0+pr_info ("attempting bad pmalloc write at %p\n" , i); + *i =0 ;OK, now I'm on the right version of this patch series, same comment applies. I don't get the local *i assignment at the end of the function, but seems harmless.
Because that's the whole point of the function: prove that pmalloc protection works (see the message in the pr_info one line above).
The function is supposed to do:
* create a pool
* allocate memory from it
* protect it
* try to alter it (and crash)
*i = 0; performs the last step
--
igor
Re: [PATCH 4/7] Protectable Memory
In reply to J FreyenseeOn 06/03/18 05:59, J Freyensee wrote:
[...]
Quoted 9 lines
mm/Kconfig config GUP_BENCHMARK · line 766
Quoted 3 lines
mm/Kconfig +3
-0+config PROTECTABLE_MEMORY + bool + depends on MMUCurious, would you also want to depend on "SECURITY" as well, as this is being advertised as a compliment to
__read_only_after_init, per the file header comments, as I'm assumingro_after_initwould be disabled if the SECURITYKconfigselection is *NOT* selected?
__ro_after_init is configured like this:
#if defined(CONFIG_STRICT_KERNEL_RWX) || defined(CONFIG_STRICT_MODULE_RWX) bool rodata_enabled __ro_after_init = true;
But even if __ro_after_init and pmalloc are conceptually similar, in practice they have - potentially - different constraints.
1) the __ro_after_init segment belongs to linear kernel memory
2) the pmalloc pools belong to vmalloc memory
There is one extra layer of indirection in pmalloc.
I am not an expert of MMUs but I suppose there might be types where it is possible to mark pages as RO but it's not possible to have virtual memory.
If (and this is a big "if") such MMUs exist and are supported by linux, then __ro_after_init would be possible, while pmalloc would not be.
So it seemed more correct to focus specifically on hte enablers required by pmalloc to perform correctly.
Open Question:
Is it ok that the API disappears in case the enablers are missing? Or should it fall back to something else?
Dealing with lack of ReadOnly support would be pretty simple, it would be enough to make the write-Protection conditional.
But what to do if virtual mapping is not supported?
kmalloc might not have the ability to support large requests made toward pmalloc and this would possibly cause runtime failures.
--
igor
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Mike RapoportQuoted 1 line · Mike Rapoport
On Wed, Feb 28, 2018 at 10:06:14PM +0200, Igor Stoppa wrote:
[...]
Quoted 2 lines
If I'm not mistaken, several kernel-doc descriptions are duplicated now. Can you please keep a single copy? ;-)
What's the preferred approach?
Document the functions that are API in the .h file and leave in the .c those which are not API?
[...]
Quoted 3 lines
Quoted 1 line
+ * The alignment at which to perform the research for sequence of empty
^ search?
yes
Quoted 8 lines
Quoted 1 line
+ *
get_boundary()- verifies address, then measure length.There's some lack of consistency between the name and implementation and the description.
It seems that it would be simpler to actually make itget_length()and return the length of the allocation or nentries if the latter is smaller. Then ingen_pool_free()there will be no need to recalculate nentries again.
There is an error in the documentation. I'll explain below.
Quoted 8 lines
Quoted 6 lines
* @map: pointer to a bitmap
- * @start: a bit position in @map
- * @nr: number of bits to set
+ * @start_entry: the index of the first entry in the bitmap
+ * @nentries: number of entries to alterMaybe: "maximal number of entries to check"?
No, it's actually the total number of entries in the chunk.
[...]
Quoted 3 lines
lib/genalloc.c line 250
Quoted 1 line
lib/genalloc.c +1
-0+return nentries - start_entry;Shouldn't it be "nentries +
start_entry"?
And in the light of the correct comment, also what I am doing should be now more clear:
* start_entry is the index of the initial entry
* nentries is the number of entries in the chunk
If I iterate over the rest of the chunk:
(i = start_entry + 1; i < nentries; i++)
without finding either another HEAD or an empty slot, then it means I was measuring the length of the last allocation in the chunk, which was taking up all the space, to the end.
Simple example:
- chunk with 7 entries -> nentries is 7
- start_entry is 2, meaning that the last allocation starts from the 3rd element, iow it occupies indexes from 2 to 6, for a total of 5 entries
- so the length is (nentries - start_entry) = (7 - 2) = 5
But yeah, the kerneldoc was wrong.
[...]
Quoted 4 lines
Quoted 2 lines
- *
gen_pool_alloc_algo- allocate special memory from the pool
+ *gen_pool_alloc_algo()- allocate special memory from the pool+ using specified algorithm
ok
Quoted 8 lines
Review EXPORT_SYMBOL(gen_pool_alloc); · line 502
Quoted 6 lines
* @pool: pool to allocate from
* @size: number of bytes to allocate from the pool
* @algo: algorithm passed from caller(quoted diff) +0
-0@@ -285,14 +502,18 @@ EXPORT_SYMBOL(gen_pool_alloc); * Uses the pool allocation function (with first-fit algorithm by default)."uses the provided @algo function to find room for the allocation"
ok
--
igor
Re: [PATCH 1/7] genalloc: track beginning of allocations
Quoted 4 lines · Igor Stoppa
Quoted 1 line · Mike Rapoport
On Wed, Feb 28, 2018 at 10:06:14PM +0200, Igor Stoppa wrote:
[...]
Quoted 10 lines
Quoted 8 lines
Quoted 1 line
+ *
get_boundary()- verifies address, then measure length.There's some lack of consistency between the name and implementation and the description.
It seems that it would be simpler to actually make itget_length()and return the length of the allocation or nentries if the latter is smaller. Then ingen_pool_free()there will be no need to recalculate nentries again.There is an error in the documentation. I'll explain below.
Argh, I do not know why I came out with that.
Yes, your comment is correct. I've modified the function accordingly and it is simpler.
I will post it in the next revision.
--
igor
Re: [PATCH 6/7] lkdtm: crash on overwriting protected pmalloc var
In reply to Igor StoppaQuoted 10 lines · Igor Stoppa
Quoted 1 line · J Freyensee
On 2/28/18 12:06 PM, Igor Stoppa wrote:
[...]
Quoted 4 lines
Quoted 4 lines
void __init lkdtm_perms_init(void); void lkdtm_WRITE_RO(void); void lkdtm_WRITE_RO_AFTER_INIT(void);+void
lkdtm_WRITE_RO_PMALLOC(void);
Quoted 8 lines
Quoted 1 line
Does this need some sort of #ifdef too?
Not strictly. It's just a function declaration.
As long as it is not used, the linker will not complain. The #ifdef placed around the use and definition is sufficient, from a correctness perspective.But it's a different question if there is any standard in linux about hiding also the declaration.
I'd prefer hiding it if it's contents are being ifdef'ed out, but I really think it's more of a maintainer preference question.
Quoted 4 lines
I am not very fond of #ifdefs, so when I can I try to avoid them.
Re: [PATCH 1/7] genalloc: track beginning of allocations
In reply to Igor StoppaQuoted 7 lines · Igor Stoppa
Quoted 1 line · Mike Rapoport
On Wed, Feb 28, 2018 at 10:06:14PM +0200, Igor Stoppa wrote:
[...]
Quoted 7 lines
Quoted 1 line
If I'm not mistaken, several kernel-doc descriptions are duplicated
now.
Quoted 1 line
Can you please keep a single copy? ;-)
What's the preferred approach?
Document the functions that are API in the .h file and leave in the .c those which are not API?
I aggree with Matthew: "we usually recommend putting it with the definition so it's more likely to be updated."
I couldn't find the doc with this recommendation, though :)
Quoted 88 lines
[...]
Quoted 1 line
Quoted 1 line
+ * The alignment at which to perform the research for sequence of
empty
Quoted 2 lines
^ search?
yes
Quoted 3 lines
Quoted 1 line
+ *
get_boundary()- verifies address, then measure length.There's some lack of consistency between the name and implementation
and
Quoted 2 lines
the description.
It seems that it would be simpler to actually make itget_length()and
Quoted 1 line
return the length of the allocation or nentries if the latter is
smaller.
Quoted 2 lines
Then in
gen_pool_free()there will be no need to recalculate nentries again.There is an error in the documentation. I'll explain below.
Quoted 8 lines
Quoted 6 lines
* @map: pointer to a bitmap
- * @start: a bit position in @map
- * @nr: number of bits to set
+ * @start_entry: the index of the first entry in the bitmap
+ * @nentries: number of entries to alterMaybe: "maximal number of entries to check"?
No, it's actually the total number of entries in the chunk.
[...]
Quoted 3 lines
lib/genalloc.c line 250
Quoted 1 line
lib/genalloc.c +1
-0+return nentries - start_entry;Shouldn't it be "nentries +
start_entry"?And in the light of the correct comment, also what I am doing should be now more clear:
*
start_entryis the index of the initial entry
* nentries is the number of entries in the chunkIf I iterate over the rest of the chunk:
(i =
start_entry+ 1; i < nentries; i++)without finding either another HEAD or an empty slot, then it means I was measuring the length of the last allocation in the chunk, which was taking up all the space, to the end.
Simple example:
- chunk with 7 entries -> nentries is 7
-start_entryis 2, meaning that the last allocation starts from the 3rd
element, iow it occupies indexes from 2 to 6, for a total of 5 entries
- so the length is (nentries -start_entry) = (7 - 2) = 5But yeah, the kerneldoc was wrong.
[...]
Quoted 4 lines
Quoted 2 lines
- *
gen_pool_alloc_algo- allocate special memory from the pool
+ *gen_pool_alloc_algo()- allocate special memory from the pool+ using specified algorithm
ok
Quoted 6 lines
Review EXPORT_SYMBOL(gen_pool_alloc); · line 502
Quoted 6 lines
* @pool: pool to allocate from
* @size: number of bytes to allocate from the pool
* @algo: algorithm passed from caller(quoted diff) +0
-0@@ -285,14 +502,18 @@ EXPORT_SYMBOL(gen_pool_alloc); * Uses the pool allocation function (with first-fit algorithm bydefault).
Quoted 2 lines
"uses the provided @algo function to find room for the allocation"
ok
--
igor
Signature · 2 lines
Sincerely yours, Mike.
Re: [PATCH 4/7] Protectable Memory
In reply to Igor StoppaQuoted 14 lines · Igor Stoppa
struct
gen_pool*pmalloc_create_pool(const char *name,int min_alloc_order);int
is_pmalloc_object(const void *ptr, const unsigned long n); boolpmalloc_prealloc(struct gen_pool *pool, size_t size);
void *pmalloc(structgen_pool*pool,size_tsize,gfp_tgfp); static inline void *pzalloc(structgen_pool*pool,size_tsize,gfp_tgfp) static inline void *pmalloc_array(structgen_pool*pool,size_tn,
size_tsize,gfp_tflags)
static inline void *pcalloc(structgen_pool*pool,size_tn,
size_tsize,gfp_tflags)
static inline char *pstrdup(structgen_pool*pool, const char *s,gfp_tgfp) intpmalloc_protect_pool(struct gen_pool *pool);
static inline voidpfree(struct gen_pool *pool, const void *addr)intpmalloc_destroy_pool(struct gen_pool *pool);
Do you have users for all these functions? I'm particularly sceptical of pfree(). To my mind, a user wants to:
pmalloc_create();pmalloc(); * Npmalloc_protect();
...pmalloc_destroy();
I don't mind the pstrdup, pcalloc, pmalloc_array, pzalloc variations, but I don't know why you need is_pmalloc_object().
Re: [PATCH 4/7] Protectable Memory
Quoted 16 lines · Matthew Wilcox
Quoted 14 lines · Igor Stoppa
struct
gen_pool*pmalloc_create_pool(const char *name,int min_alloc_order);int
is_pmalloc_object(const void *ptr, const unsigned long n); boolpmalloc_prealloc(struct gen_pool *pool, size_t size);
void *pmalloc(structgen_pool*pool,size_tsize,gfp_tgfp); static inline void *pzalloc(structgen_pool*pool,size_tsize,gfp_tgfp) static inline void *pmalloc_array(structgen_pool*pool,size_tn,
size_tsize,gfp_tflags)
static inline void *pcalloc(structgen_pool*pool,size_tn,
size_tsize,gfp_tflags)
static inline char *pstrdup(structgen_pool*pool, const char *s,gfp_tgfp) intpmalloc_protect_pool(struct gen_pool *pool);
static inline voidpfree(struct gen_pool *pool, const void *addr)intpmalloc_destroy_pool(struct gen_pool *pool);
Quoted 2 lines
Do you have users for all these functions? I'm particularly sceptical of
pfree().
The typical case is when rolling back allocations, on an error path. For example, with SELinux, the userspace provides the policy, which gets processed and converted into a policyDB, where every policy maps to several structures allocated dynamically.
The allocation is not transactional. In case a policy turns out to be bad/broken, while being interpreted, those structures that were initially allocated for that policy, must be freed.
Since pmalloc is meant to be a drop in replacement for k/vmalloc, it needs to provide also pfree.
Quoted 7 lines
To my mind, a user wants to:
pmalloc_create();pmalloc(); * Npmalloc_protect();
...pmalloc_destroy();
This is the simplest case, but also the error path must be supported.
Quoted 1 line
I don't mind the pstrdup, pcalloc,
pmalloc_array, pzalloc variations, but
All those functions turned out to be necessary when converting SELinux to pmalloc.
Yes, I haven't published this code yet, but I was hoping to first be done with pmalloc and then move on to SELinux, which I suspect will be harder to chew :-/
Quoted 1 line
I don't know why you need
is_pmalloc_object().
Because of hardened usercopy [1]:
On 23/05/17 00:38, Kees Cook wrote:
[...]
Quoted 5 lines
I'd like hardened usercopy to grow knowledge of these allocations so we can bounds-check objects. Right now,
mm/usercopy.cjust looks at PageSlab(page) to decide if it should do slab checks. I think adding a check for this type of object would be very important there.
[1] http://www.openwall.com/lists/kernel-hardening/2017/05/23/17
--
igor