incoming
Subsystems (98)
Andrew Morton
maintainerPATCH 110/200 ia64: split virtual map initialization out of paging_init()
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: ia64: split virtual map initialization out of paging_init()
For both FLATMEM and DISCONTIGMEM/SPARSEMEM the virtual map initialization is spread over paging_init() for no good reason.
Split out the bits related to virtual map initialization to a helper functions, one for FLATMEM and another for !FLATMEM configurations.
---
arch/ia64/mm/contig.c | 34 ++++++++++++++++++++-------------- arch/ia64/mm/discontig.c | 37 ++++++++++++++++++++----------------- 2 files changed, 40 insertions(+), 31 deletions(-)
arch/ia64/mm/contig.c renamed from arch/ia64/mm/contig.c~ia64-split-virtual-map-initialization-out-of-paging_init +20 -14
@@ -166,21 +166,8 @@ find_memory (void)alloc_per_cpu_data (); } -/* -* Set up the page tables. -*/ - -void __init -paging_init (void ) +static void __init virtual_map_init (void ) { -unsigned long max_dma; -unsigned long max_zone_pfns[MAX_NR_ZONES ]; - -memset (max_zone_pfns,0 ,sizeof (max_zone_pfns)); - max_dma =virt_to_phys ((void *)MAX_DMA_ADDRESS ) >>PAGE_SHIFT ; - max_zone_pfns[ZONE_DMA32 ] = max_dma; - max_zone_pfns[ZONE_NORMAL ] = max_low_pfn; -#ifdef CONFIG_VIRTUAL_MEM_MAP efi_memmap_walk (find_largest_hole, (u64 *)&max_gap);if (max_gap <LARGE_GAP ) {
@@ -206,6 +193,25 @@ paging_init (void) printk("Virtual mem_map starts at 0x%p\n", mem_map); }#endif /* !CONFIG_VIRTUAL_MEM_MAP */ +} + +/* +* Set up the page tables. +*/ + +void __init +paging_init (void ) +{ +unsigned long max_dma; +unsigned long max_zone_pfns[MAX_NR_ZONES ]; + +memset (max_zone_pfns,0 ,sizeof (max_zone_pfns)); + max_dma =virt_to_phys ((void *)MAX_DMA_ADDRESS ) >>PAGE_SHIFT ; + max_zone_pfns[ZONE_DMA32 ] = max_dma; + max_zone_pfns[ZONE_NORMAL ] = max_low_pfn; + +virtual_map_init (); +free_area_init (max_zone_pfns); zero_page_memmap_ptr =virt_to_page (ia64_imva (empty_zero_page)); }
arch/ia64/mm/discontig.c renamed from arch/ia64/mm/discontig.c~ia64-split-virtual-map-initialization-out-of-paging_init +20 -17
@@ -584,6 +584,25 @@ void call_pernode_memory(unsigned long s } } +static void __init virtual_map_init (void ) +{ +#ifdef CONFIG_VIRTUAL_MEM_MAP +int node; + +VMALLOC_END -=PAGE_ALIGN (ALIGN (max_low_pfn,MAX_ORDER_NR_PAGES ) * +sizeof (struct page )); + vmem_map = (struct page *)VMALLOC_END ; +efi_memmap_walk (create_mem_map_page_table,NULL ); +printk ("Virtual mem_map starts at 0x%p\n" , vmem_map); + +for_each_online_node (node) { +unsigned long pfn_offset = mem_data[node].min_pfn; + +NODE_DATA (node)->node_mem_map = vmem_map + pfn_offset; + } +#endif +} +/** * paging_init - setup page tables *
@@ -593,29 +612,13 @@ void call_pernode_memory(unsigned long svoid __init paging_init (void ) {unsigned long max_dma; -unsigned long pfn_offset =0 ; -int node;unsigned long max_zone_pfns[MAX_NR_ZONES ]; max_dma =virt_to_phys ((void *)MAX_DMA_ADDRESS ) >>PAGE_SHIFT ;sparse_init (); -#ifdef CONFIG_VIRTUAL_MEM_MAP -VMALLOC_END -=PAGE_ALIGN (ALIGN (max_low_pfn,MAX_ORDER_NR_PAGES ) * -sizeof (struct page )); - vmem_map = (struct page *)VMALLOC_END ; -efi_memmap_walk (create_mem_map_page_table,NULL ); -printk ("Virtual mem_map starts at 0x%p\n" , vmem_map); -#endif - -for_each_online_node (node) { - pfn_offset = mem_data[node].min_pfn; - -#ifdef CONFIG_VIRTUAL_MEM_MAP -NODE_DATA (node)->node_mem_map = vmem_map + pfn_offset; -#endif - } +virtual_map_init ();memset (max_zone_pfns,0 ,sizeof (max_zone_pfns)); max_zone_pfns[ZONE_DMA32 ] = max_dma;
_
Andrew Morton
maintainerPATCH 111/200 ia64: forbid using VIRTUAL_MEM_MAP with FLATMEM
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: ia64: forbid using VIRTUAL_MEM_MAP with FLATMEM
Virtual memory map was intended to avoid wasting memory on the memory map on systems with large holes in the physical memory layout. Long ago it been superseded first by DISCONTIGMEM and then by SPARSEMEM. Moreover, SPARSEMEM_VMEMMAP provide the same functionality in much more portable way.
As the first step to removing the VIRTUAL_MEM_MAP forbid it's usage with FLATMEM and panic on systems with large holes in the physical memory layout that try to run FLATMEM kernels.
---
arch/ia64/Kconfig | 2 - arch/ia64/include/asm/meminit.h | 2 - arch/ia64/mm/contig.c | 52 +++++++++++++----------------- arch/ia64/mm/init.c | 14 -------- 4 files changed, 24 insertions(+), 46 deletions(-)
arch/ia64/include/asm/meminit.h renamed from arch/ia64/include/asm/meminit.h~ia64-forbid-using-virtual_mem_map-with-flatmem +0 -2
@@ -59,10 +59,8 @@ extern int reserve_elfcorehdr(u64 *startextern int register_active_ranges (u64 start,u64 len,int nid);#ifdef CONFIG_VIRTUAL_MEM_MAP -# define LARGE_GAP 0x40000000/* Use virtual mem map if hole is > than this */ extern unsigned long VMALLOC_END ;extern struct page *vmem_map; -extern int find_largest_hole (u64 start,u64 end,void *arg);extern int create_mem_map_page_table (u64 start,u64 end,void *arg);extern int vmemmap_find_next_valid_pfn (int ,int );#else
arch/ia64/Kconfig renamed from arch/ia64/Kconfig~ia64-forbid-using-virtual_mem_map-with-flatmem +1 -1
@@ -329,7 +329,7 @@ config NODES_SHIFT # VIRTUAL_MEM_MAP has been retained for historical reasons. config VIRTUAL_MEM_MAP bool "Virtual mem map" - depends on !SPARSEMEM + depends on !SPARSEMEM && !FLATMEM default y help Say Y to compile the kernel with support for a virtual mem map.
arch/ia64/mm/contig.c renamed from arch/ia64/mm/contig.c~ia64-forbid-using-virtual_mem_map-with-flatmem +23 -29
78 lines not on this page · raw message
arch/ia64/mm/init.c renamed from arch/ia64/mm/init.c~ia64-forbid-using-virtual_mem_map-with-flatmem +0 -14
@@ -574,20 +574,6 @@ ia64_pfn_valid (unsigned long pfn) }EXPORT_SYMBOL (ia64_pfn_valid); -int __init find_largest_hole (u64 start,u64 end,void *arg) -{ -u64 *max_gap = arg; - -static u64 last_end =PAGE_OFFSET ; - -/* NOTE: this algorithm assumes efi memmap table is ordered */ - -if (*max_gap < (start - last_end)) - *max_gap = start - last_end; - last_end = end; -return 0 ; -} -#endif /* CONFIG_VIRTUAL_MEM_MAP */ int __init register_active_ranges (u64 start,u64 len,int nid)
_
Andrew Morton
maintainerPATCH 112/200 ia64: make SPARSEMEM default and disable DISCONTIGMEM
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: ia64: make SPARSEMEM default and disable DISCONTIGMEM
SPARSEMEM memory model suitable for systems with large holes in their phyiscal memory layout. With SPARSEMEM_VMEMMAP enabled it provides pfn_to_page() and page_to_pfn() as fast as FLATMEM.
Make it the default memory model for IA-64 and disable DISCONTIGMEM which is considered obsolete for quite some time.
---
arch/ia64/Kconfig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
arch/ia64/Kconfig renamed from arch/ia64/Kconfig~ia64-make-sparsemem-default-and-disable-discontigmem +3 -3
@@ -288,6 +288,7 @@ config ARCH_SELECT_MEMORY_MODEL config ARCH_DISCONTIGMEM_ENABLE def_bool y + depends on BROKEN help Say Y to support efficient handling of discontiguous physical memory, for architectures which are either NUMA (Non-Uniform Memory Access)
@@ -299,12 +300,11 @@ config ARCH_FLATMEM_ENABLE config ARCH_SPARSEMEM_ENABLE def_bool y - depends on ARCH_DISCONTIGMEM_ENABLE select SPARSEMEM_VMEMMAP_ENABLE -config ARCH_DISCONTIGMEM_DEFAULT +config ARCH_SPARSEMEM_DEFAULT def_bool y - depends on ARCH_DISCONTIGMEM_ENABLE + depends on ARCH_SPARSEMEM_ENABLE config NUMA bool "NUMA support"
_
Andrew Morton
maintainerPATCH 113/200 arm: remove CONFIG_ARCH_HAS_HOLES_MEMORYMODEL
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: arm: remove CONFIG_ARCH_HAS_HOLES_MEMORYMODEL
ARM is the only architecture that defines CONFIG_ARCH_HAS_HOLES_MEMORYMODEL which in turn enables memmap_valid_within() function that is intended to verify existence of struct page associated with a pfn when there are holes in the memory map.
However, the ARCH_HAS_HOLES_MEMORYMODEL also enables HAVE_ARCH_PFN_VALID and arch-specific pfn_valid() implementation that also deals with the holes in the memory map.
The only two users of memmap_valid_within() call this function after a call to pfn_valid() so the memmap_valid_within() check becomes redundant.
Remove CONFIG_ARCH_HAS_HOLES_MEMORYMODEL and memmap_valid_within() and rely entirely on ARM's implementation of pfn_valid() that is now enabled unconditionally.
---
Documentation/vm/memory-model.rst | 3 -- arch/arm/Kconfig | 8 +------ arch/arm/mach-bcm/Kconfig | 1 arch/arm/mach-davinci/Kconfig | 1 arch/arm/mach-exynos/Kconfig | 1 arch/arm/mach-highbank/Kconfig | 1 arch/arm/mach-omap2/Kconfig | 1 arch/arm/mach-s5pv210/Kconfig | 1 arch/arm/mach-tango/Kconfig | 1 fs/proc/kcore.c | 2 - include/linux/mmzone.h | 31 ---------------------------- mm/mmzone.c | 14 ------------ mm/vmstat.c | 4 --- 13 files changed, 3 insertions(+), 66 deletions(-)
arch/arm/Kconfig renamed from arch/arm/Kconfig~arm-remove-config_arch_has_holes_memorymodel +2 -6
@@ -25,7 +25,7 @@ config ARM select ARCH_HAS_TICK_BROADCAST if GENERIC_CLOCKEVENTS_BROADCAST select ARCH_HAVE_CUSTOM_GPIO_H select ARCH_HAS_GCOV_PROFILE_ALL - select ARCH_KEEP_MEMBLOCK if HAVE_ARCH_PFN_VALID || KEXEC + select ARCH_KEEP_MEMBLOCK select ARCH_MIGHT_HAVE_PC_PARPORT select ARCH_NO_SG_CHAIN if !ARM_HAS_SG_CHAIN select ARCH_OPTIONAL_KERNEL_RWX if ARCH_HAS_STRICT_KERNEL_RWX
@@ -520,7 +520,6 @@ config ARCH_S3C24XX config ARCH_OMAP1 bool "TI OMAP1" depends on MMU - select ARCH_HAS_HOLES_MEMORYMODEL select ARCH_OMAP select CLKDEV_LOOKUP select CLKSRC_MMIO
@@ -1480,9 +1479,6 @@ config OABI_COMPAT UNPREDICTABLE (in fact it can be predicted that it won't work at all). If in doubt say N. -config ARCH_HAS_HOLES_MEMORYMODEL - bool - config ARCH_SELECT_MEMORY_MODEL bool
@@ -1494,7 +1490,7 @@ config ARCH_SPARSEMEM_ENABLE select SPARSEMEM_STATIC if SPARSEMEM config HAVE_ARCH_PFN_VALID - def_bool ARCH_HAS_HOLES_MEMORYMODEL || !SPARSEMEM + def_bool y config HIGHMEM bool "High Memory Support"
arch/arm/mach-bcm/Kconfig renamed from arch/arm/mach-bcm/Kconfig~arm-remove-config_arch_has_holes_memorymodel +0 -1
@@ -211,7 +211,6 @@ config ARCH_BRCMSTB select BCM7038_L1_IRQ select BRCMSTB_L2_IRQ select BCM7120_L2_IRQ - select ARCH_HAS_HOLES_MEMORYMODEL select ZONE_DMA if ARM_LPAE select SOC_BRCMSTB select SOC_BUS
arch/arm/mach-davinci/Kconfig renamed from arch/arm/mach-davinci/Kconfig~arm-remove-config_arch_has_holes_memorymodel +0 -1
@@ -5,7 +5,6 @@ menuconfig ARCH_DAVINCI depends on ARCH_MULTI_V5 select DAVINCI_TIMER select ZONE_DMA - select ARCH_HAS_HOLES_MEMORYMODEL select PM_GENERIC_DOMAINS if PM select PM_GENERIC_DOMAINS_OF if PM && OF select REGMAP_MMIO
arch/arm/mach-exynos/Kconfig renamed from arch/arm/mach-exynos/Kconfig~arm-remove-config_arch_has_holes_memorymodel +0 -1
@@ -8,7 +8,6 @@ menuconfig ARCH_EXYNOS bool "Samsung Exynos" depends on ARCH_MULTI_V7 - select ARCH_HAS_HOLES_MEMORYMODEL select ARCH_SUPPORTS_BIG_ENDIAN select ARM_AMBA select ARM_GIC
arch/arm/mach-highbank/Kconfig renamed from arch/arm/mach-highbank/Kconfig~arm-remove-config_arch_has_holes_memorymodel +0 -1
@@ -2,7 +2,6 @@ config ARCH_HIGHBANK bool "Calxeda ECX-1000/2000 (Highbank/Midway)" depends on ARCH_MULTI_V7 - select ARCH_HAS_HOLES_MEMORYMODEL select ARCH_SUPPORTS_BIG_ENDIAN select ARM_AMBA select ARM_ERRATA_764369 if SMP
arch/arm/mach-omap2/Kconfig renamed from arch/arm/mach-omap2/Kconfig~arm-remove-config_arch_has_holes_memorymodel +0 -1
@@ -93,7 +93,6 @@ config SOC_DRA7XX config ARCH_OMAP2PLUS bool select ARCH_HAS_BANDGAP - select ARCH_HAS_HOLES_MEMORYMODEL select ARCH_HAS_RESET_CONTROLLER select ARCH_OMAP select CLKSRC_MMIO
arch/arm/mach-s5pv210/Kconfig renamed from arch/arm/mach-s5pv210/Kconfig~arm-remove-config_arch_has_holes_memorymodel +0 -1
@@ -8,7 +8,6 @@ config ARCH_S5PV210 bool "Samsung S5PV210/S5PC110" depends on ARCH_MULTI_V7 - select ARCH_HAS_HOLES_MEMORYMODEL select ARM_VIC select CLKSRC_SAMSUNG_PWM select COMMON_CLK_SAMSUNG
arch/arm/mach-tango/Kconfig renamed from arch/arm/mach-tango/Kconfig~arm-remove-config_arch_has_holes_memorymodel +0 -1
@@ -3,7 +3,6 @@ config ARCH_TANGO bool "Sigma Designs Tango4 (SMP87xx)" depends on ARCH_MULTI_V7 # Cortex-A9 MPCore r3p0, PL310 r3p2 - select ARCH_HAS_HOLES_MEMORYMODEL select ARM_ERRATA_754322 select ARM_ERRATA_764369 if SMP select ARM_ERRATA_775420
Documentation/vm/memory-model.rst renamed from Documentation/vm/memory-model.rst~arm-remove-config_arch_has_holes_memorymodel +1 -2
@@ -51,8 +51,7 @@ call :c:func:`free_area_init` function. usable until the call to :c:func:`memblock_free_all` that hands all the memory to the page allocator. -If an architecture enables `CONFIG_ARCH_HAS_HOLES_MEMORYMODEL` option, -it may free parts of the `mem_map` array that do not cover the +An architecture may free parts of the `mem_map` array that do not cover the actual physical pages. In such case, the architecture specific :c:func:`pfn_valid` implementation should take the holes in the `mem_map` into account.
fs/proc/kcore.c renamed from fs/proc/kcore.c~arm-remove-config_arch_has_holes_memorymodel +0 -2
@@ -193,8 +193,6 @@ kclist_add_private(unsigned long pfn, unreturn 1 ; p =pfn_to_page (pfn); -if (!memmap_valid_within (pfn, p,page_zone (p))) -return 1 ; ent =kmalloc (sizeof (*ent),GFP_KERNEL );if (!ent)
include/linux/mmzone.h renamed from include/linux/mmzone.h~arm-remove-config_arch_has_holes_memorymodel +0 -31
@@ -1440,37 +1440,6 @@ void sparse_init(void);#define pfn_valid_within (pfn) (1)#endif -#ifdef CONFIG_ARCH_HAS_HOLES_MEMORYMODEL -/* -* pfn_valid() is meant to be able to tell if a given PFN has valid memmap -* associated with it or not. This means that a struct page exists for this -* pfn. The caller cannot assume the page is fully initialized in general. -* Hotplugable pages might not have been onlined yet. pfn_to_online_page() -* will ensure the struct page is fully online and initialized. Special pages -* (e.g. ZONE_DEVICE) are never onlined and should be treated accordingly. -* -* In FLATMEM, it is expected that holes always have valid memmap as long as -* there is valid PFNs either side of the hole. In SPARSEMEM, it is assumed -* that a valid section has a memmap for the entire section. -* -* However, an ARM, and maybe other embedded architectures in the future -* free memmap backing holes to save memory on the assumption the memmap is -* never used. The page_zone linkages are then broken even though pfn_valid() -* returns true. A walker of the full memmap must then do this additional -* check to ensure the memmap they are looking at is sane by making sure -* the zone and PFN linkages are still valid. This is expensive, but walkers -* of the full memmap are extremely rare. -*/ -bool memmap_valid_within (unsigned long pfn, -struct page *page,struct zone *zone); -#else -static inline bool memmap_valid_within (unsigned long pfn, -struct page *page,struct zone *zone) -{ -return true; -} -#endif /* CONFIG_ARCH_HAS_HOLES_MEMORYMODEL */ -#endif /* !__GENERATING_BOUNDS.H */ #endif /* !__ASSEMBLY__ */ #endif /* _LINUX_MMZONE_H */
mm/mmzone.c renamed from mm/mmzone.c~arm-remove-config_arch_has_holes_memorymodel +0 -14
@@ -72,20 +72,6 @@ struct zoneref *__next_zones_zonelist(streturn z; } -#ifdef CONFIG_ARCH_HAS_HOLES_MEMORYMODEL -bool memmap_valid_within (unsigned long pfn, -struct page *page,struct zone *zone) -{ -if (page_to_pfn (page) != pfn) -return false; - -if (page_zone (page) != zone) -return false; - -return true; -} -#endif /* CONFIG_ARCH_HAS_HOLES_MEMORYMODEL */ -void lruvec_init (struct lruvec *lruvec) {enum lru_list lru;
mm/vmstat.c renamed from mm/vmstat.c~arm-remove-config_arch_has_holes_memorymodel +0 -4
@@ -1503,10 +1503,6 @@ static void pagetypeinfo_showblockcount_if (!page)continue ; -/* Watch for unexpected holes punched in the memmap */ -if (!memmap_valid_within (pfn, page, zone)) -continue ; -if (page_zone (page) != zone)continue ;
_
Andrew Morton
maintainerPATCH 114/200 arm, arm64: move free_unused_memmap() to generic mm
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: arm, arm64: move free_unused_memmap() to generic mm
ARM and ARM64 free unused parts of the memory map just before the initialization of the page allocator. To allow holes in the memory map both architectures overload pfn_valid() and define HAVE_ARCH_PFN_VALID.
Allowing holes in the memory map for FLATMEM may be useful for small machines, such as ARC and m68k and will enable those architectures to cease using DISCONTIGMEM and still support more than one memory bank.
Move the functions that free unused memory map to generic mm and enable them in case HAVE_ARCH_PFN_VALID=y.
---
arch/Kconfig | 3 + arch/arm/Kconfig | 4 -- arch/arm/mm/init.c | 78 --------------------------------------- arch/arm64/Kconfig | 4 -- arch/arm64/mm/init.c | 68 ---------------------------------- mm/memblock.c | 80 +++++++++++++++++++++++++++++++++++++++++ 6 files changed, 85 insertions(+), 152 deletions(-)
arch/arm64/Kconfig renamed from arch/arm64/Kconfig~arm-arm64-move-free_unused_memmap-to-generic-mm +1 -3
@@ -140,6 +140,7 @@ config ARM64 select HAVE_ARCH_KGDB select HAVE_ARCH_MMAP_RND_BITS select HAVE_ARCH_MMAP_RND_COMPAT_BITS if COMPAT + select HAVE_ARCH_PFN_VALID select HAVE_ARCH_PREL32_RELOCATIONS select HAVE_ARCH_SECCOMP_FILTER select HAVE_ARCH_STACKLEAK
@@ -1043,9 +1044,6 @@ config ARCH_SELECT_MEMORY_MODEL config ARCH_FLATMEM_ENABLE def_bool !NUMA -config HAVE_ARCH_PFN_VALID - def_bool y - config HW_PERF_EVENTS def_bool y depends on ARM_PMU
arch/arm64/mm/init.c renamed from arch/arm64/mm/init.c~arm-arm64-move-free_unused_memmap-to-generic-mm +0 -68
80 lines not on this page · raw message
arch/arm/Kconfig renamed from arch/arm/Kconfig~arm-arm64-move-free_unused_memmap-to-generic-mm +1 -3
@@ -69,6 +69,7 @@ config ARM select HAVE_ARCH_JUMP_LABEL if !XIP_KERNEL && !CPU_ENDIAN_BE32 && MMU select HAVE_ARCH_KGDB if !CPU_ENDIAN_BE32 && MMU select HAVE_ARCH_MMAP_RND_BITS if MMU + select HAVE_ARCH_PFN_VALID select HAVE_ARCH_SECCOMP select HAVE_ARCH_SECCOMP_FILTER if AEABI && !OABI_COMPAT select HAVE_ARCH_THREAD_STRUCT_WHITELIST
@@ -1489,9 +1490,6 @@ config ARCH_SPARSEMEM_ENABLE bool select SPARSEMEM_STATIC if SPARSEMEM -config HAVE_ARCH_PFN_VALID - def_bool y - config HIGHMEM bool "High Memory Support" depends on MMU
arch/arm/mm/init.c renamed from arch/arm/mm/init.c~arm-arm64-move-free_unused_memmap-to-generic-mm +0 -78
90 lines not on this page · raw message
arch/Kconfig renamed from arch/Kconfig~arm-arm64-move-free_unused_memmap-to-generic-mm +3 -0
@@ -1044,6 +1044,9 @@ config ARCH_WANT_LD_ORPHAN_WARN by the linker, since the locations of such sections can change between linker versions. +config HAVE_ARCH_PFN_VALID + bool + source "kernel/gcov/Kconfig" source "scripts/gcc-plugins/Kconfig"
mm/memblock.c renamed from mm/memblock.c~arm-arm64-move-free_unused_memmap-to-generic-mm +80 -0
92 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 115/200 arc: use FLATMEM with freeing of unused memory map instead of DISCONTIGMEM
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: arc: use FLATMEM with freeing of unused memory map instead of DISCONTIGMEM
Currently ARC uses DISCONTIGMEM to cope with sparse physical memory address space on systems with 2 memory banks. While DISCONTIGMEM avoids wasting memory on unpopulated memory map, it adds both memory and CPU overhead relatively to FLATMEM. Moreover, DISCONTINGMEM is generally considered deprecated.
The obvious replacement for DISCONTIGMEM would be SPARSEMEM, but it is also less efficient than FLATMEM in pfn_to_page() and page_to_pfn() conversions. Besides it requires tuning of SECTION_SIZE which is not trivial for possible ARC memory configuration.
Since the memory map for both banks is always allocated from the "lowmem" bank, it is possible to use FLATMEM for two-bank configuration and simply free the unused hole in the memory map. All is required for that is to provide ARC-specific pfn_valid() that will take into account actual physical memory configuration and define HAVE_ARCH_PFN_VALID.
The resulting kernel image configured with defconfig + HIGHMEM=y is smaller:
$ size a/vmlinux b/vmlinux text data bss dec hex filename 4673503 1245456 279756 6198715 5e95bb a/vmlinux 4658706 1246864 279756 6185326 5e616e b/vmlinux
$ ./scripts/bloat-o-meter a/vmlinux b/vmlinux add/remove: 28/30 grow/shrink: 42/399 up/down: 10986/-29025 (-18039) ... Total: Before=4709315, After = 4691276, chg -0.38%
Booting nSIM with haps_ns.dts results in the following memory usage reports:
a:
Memory: 1559104K/1572864K available (3531K kernel code, 595K rwdata, 752K rodata, 136K init, 275K bss, 13760K reserved, 0K cma-reserved, 1048576K highmem)
b:
Memory: 1559112K/1572864K available (3519K kernel code, 594K rwdata, 752K rodata, 136K init, 280K bss, 13752K reserved, 0K cma-reserved, 1048576K highmem)
---
arch/arc/Kconfig | 3 ++- arch/arc/include/asm/page.h | 20 +++++++++++++++++--- arch/arc/mm/init.c | 29 ++++++++++++++++++++++------- 3 files changed, 41 insertions(+), 11 deletions(-)
arch/arc/include/asm/page.h renamed from arch/arc/include/asm/page.h~arc-use-flatmem-with-freeing-of-unused-memory-map-instead-of-discontigmem +17 -3
@@ -82,11 +82,25 @@ typedef pte_t * pgtable_t;*/ #define virt_to_pfn (kaddr) (__pa(kaddr) >> PAGE_SHIFT) -#define ARCH_PFN_OFFSET virt_to_pfn(CONFIG_LINUX_RAM_BASE) +/* +* When HIGHMEM is enabled we have holes in the memory map so we need +* pfn_valid() that takes into account the actual extents of the physical +* memory +*/ +#ifdef CONFIG_HIGHMEM + +extern unsigned long arch_pfn_offset; +#define ARCH_PFN_OFFSET arch_pfn_offset -#ifdef CONFIG_FLATMEM +extern int pfn_valid (unsigned long pfn); +#define pfn_valid pfn_valid + +#else /* CONFIG_HIGHMEM */ + +#define ARCH_PFN_OFFSET virt_to_pfn(CONFIG_LINUX_RAM_BASE)#define pfn_valid (pfn) (((pfn) - ARCH_PFN_OFFSET) < max_mapnr) -#endif + +#endif /* CONFIG_HIGHMEM */ /* * __pa, __va, virt_to_page (ALERT: deprecated, don't use them)
arch/arc/Kconfig renamed from arch/arc/Kconfig~arc-use-flatmem-with-freeing-of-unused-memory-map-instead-of-discontigmem +2 -1
@@ -67,6 +67,7 @@ config GENERIC_CSUM config ARCH_DISCONTIGMEM_ENABLE def_bool n + depends on BROKEN config ARCH_FLATMEM_ENABLE def_bool y
@@ -506,7 +507,7 @@ config LINUX_RAM_BASE config HIGHMEM bool "High Memory Support" - select ARCH_DISCONTIGMEM_ENABLE + select HAVE_ARCH_PFN_VALID help With ARC 2G:2G address split, only upper 2G is directly addressable by kernel. Enable this to potentially allow access to rest of 2G and PAE
arch/arc/mm/init.c renamed from arch/arc/mm/init.c~arc-use-flatmem-with-freeing-of-unused-memory-map-instead-of-discontigmem +22 -7
@@ -28,6 +28,8 @@ static unsigned long low_mem_sz;static unsigned long min_high_pfn, max_high_pfn;static phys_addr_t high_mem_start;static phys_addr_t high_mem_sz; +unsigned long arch_pfn_offset; +EXPORT_SYMBOL (arch_pfn_offset);#endif #ifdef CONFIG_DISCONTIGMEM
@@ -98,16 +100,11 @@ void __init setup_arch_memory(void) init_mm.brk = (unsigned long )_end;/* first page of system - kernel .vector starts here */ - min_low_pfn =ARCH_PFN_OFFSET ; + min_low_pfn =virt_to_pfn (CONFIG_LINUX_RAM_BASE );/* Last usable page of low mem */ max_low_pfn = max_pfn =PFN_DOWN (low_mem_start + low_mem_sz); -#ifdef CONFIG_FLATMEM -/* pfn_valid() uses this */ - max_mapnr = max_low_pfn - min_low_pfn; -#endif -/*------------- bootmem allocator setup -----------------------*/ /*
@@ -153,7 +150,9 @@ void __init setup_arch_memory(void)* DISCONTIGMEM in turns requires multiple nodes. node 0 above is * populated with normal memory zone while node 1 only has highmem */ +#ifdef CONFIG_DISCONTIGMEM node_set_online (1 ); +#endif min_high_pfn =PFN_DOWN (high_mem_start); max_high_pfn =PFN_DOWN (high_mem_start + high_mem_sz);
@@ -161,8 +160,15 @@ void __init setup_arch_memory(void) max_zone_pfn[ZONE_HIGHMEM ] = min_low_pfn; high_memory = (void *)(min_high_pfn <<PAGE_SHIFT ); + + arch_pfn_offset =min (min_low_pfn, min_high_pfn);kmap_init (); -#endif + +#else /* CONFIG_HIGHMEM */ +/* pfn_valid() uses this when FLATMEM=y and HIGHMEM=n */ + max_mapnr = max_low_pfn - min_low_pfn; + +#endif /* CONFIG_HIGHMEM */ free_area_init (max_zone_pfn); }
@@ -190,3 +196,12 @@ void __init mem_init(void)highmem_init ();mem_init_print_info (NULL ); } + +#ifdef CONFIG_HIGHMEM +int pfn_valid (unsigned long pfn) +{ +return (pfn >= min_high_pfn && pfn <= max_high_pfn) || + (pfn >= min_low_pfn && pfn <= max_low_pfn); +} +EXPORT_SYMBOL (pfn_valid); +#endif
_
Andrew Morton
maintainerPATCH 116/200 m68k/mm: make node data and node setup depend on CONFIG_DISCONTIGMEM
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: m68k/mm: make node data and node setup depend on CONFIG_DISCONTIGMEM
The pg_data_t node structures and their initialization currently depends on !CONFIG_SINGLE_MEMORY_CHUNK. Since they are required only for DISCONTIGMEM make this dependency explicit and replace usage of CONFIG_SINGLE_MEMORY_CHUNK with CONFIG_DISCONTIGMEM where appropriate.
The CONFIG_SINGLE_MEMORY_CHUNK was implicitly disabled on the ColdFire MMU variant, although it always presumed a single memory bank. As there is no actual need for DISCONTIGMEM in this case, make sure that ColdFire MMU systems set CONFIG_SINGLE_MEMORY_CHUNK to 'y'.
---
arch/m68k/Kconfig.cpu | 4 ++-- arch/m68k/include/asm/page_mm.h | 2 +- arch/m68k/include/asm/virtconvert.h | 2 +- arch/m68k/mm/init.c | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-)
arch/m68k/include/asm/page_mm.h renamed from arch/m68k/include/asm/page_mm.h~m68k-mm-make-node-data-and-node-setup-depend-on-config_discontigmem +1 -1
@@ -126,7 +126,7 @@ static inline void *__va(unsigned long xextern int m68k_virt_to_node_shift; -#ifdef CONFIG_SINGLE_MEMORY_CHUNK +#ifndef CONFIG_DISCONTIGMEM #define __virt_to_node (addr) (&pg_data_map[0])#else extern struct pglist_data *pg_data_table[];
arch/m68k/include/asm/virtconvert.h renamed from arch/m68k/include/asm/virtconvert.h~m68k-mm-make-node-data-and-node-setup-depend-on-config_discontigmem +1 -1
@@ -29,7 +29,7 @@ static inline void *phys_to_virt(unsigne }/* Permanent address of a page. */ -#if defined(CONFIG_MMU ) && defined(CONFIG_SINGLE_MEMORY_CHUNK ) +#if defined(CONFIG_MMU ) && !defined(CONFIG_DISCONTIGMEM )#define page_to_phys (page) \ __pa(PAGE_OFFSET + (((page) - pg_data_map[0].node_mem_map) << PAGE_SHIFT))#else
arch/m68k/Kconfig.cpu renamed from arch/m68k/Kconfig.cpu~m68k-mm-make-node-data-and-node-setup-depend-on-config_discontigmem +2 -2
@@ -373,7 +373,7 @@ config RMW_INSNS config SINGLE_MEMORY_CHUNK bool "Use one physical chunk of memory only" if ADVANCED && !SUN3 depends on MMU - default y if SUN3 + default y if SUN3 || MMU_COLDFIRE select NEED_MULTIPLE_NODES help Ignore all but the first contiguous chunk of physical memory for VM
@@ -406,7 +406,7 @@ config M68K_L2_CACHE config NODES_SHIFT int default "3" - depends on !SINGLE_MEMORY_CHUNK + depends on DISCONTIGMEM config CPU_HAS_NO_BITFIELDS bool
arch/m68k/mm/init.c renamed from arch/m68k/mm/init.c~m68k-mm-make-node-data-and-node-setup-depend-on-config_discontigmem +2 -2
@@ -47,14 +47,14 @@ EXPORT_SYMBOL(pg_data_map);int m68k_virt_to_node_shift; -#ifndef CONFIG_SINGLE_MEMORY_CHUNK +#ifdef CONFIG_DISCONTIGMEM pg_data_t *pg_data_table[65 ];EXPORT_SYMBOL (pg_data_table);#endif void __init m68k_setup_node (int node) { -#ifndef CONFIG_SINGLE_MEMORY_CHUNK +#ifdef CONFIG_DISCONTIGMEM struct m68k_mem_info *info = m68k_memory + node;int i, end;
_
Andrew Morton
maintainerPATCH 117/200 m68k/mm: enable use of generic memory_model.h for !DISCONTIGMEM
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: m68k/mm: enable use of generic memory_model.h for !DISCONTIGMEM
The pg_data_map and pg_data_table arrays as well as page_to_pfn() and pfn_to_page() are required only for DISCONTIGMEM. Other memory models can use the generic definitions in asm-generic/memory_model.h.
---
arch/m68k/Kconfig.cpu | 1 - arch/m68k/include/asm/page.h | 2 ++ arch/m68k/include/asm/page_mm.h | 5 +++++ arch/m68k/include/asm/virtconvert.h | 5 ----- arch/m68k/mm/init.c | 6 +++--- 5 files changed, 10 insertions(+), 9 deletions(-)
arch/m68k/include/asm/page.h renamed from arch/m68k/include/asm/page.h~m68k-mm-enable-use-of-generic-memory_modelh-for-discontigmem +2 -0
@@ -62,8 +62,10 @@ extern unsigned long _ramend;#include <asm/page_no.h> #endif +#ifdef CONFIG_DISCONTIGMEM #define __phys_to_pfn (paddr) ((unsigned long)((paddr) >> PAGE_SHIFT))#define __pfn_to_phys (pfn) PFN_PHYS(pfn) +#endif #include <asm-generic/getorder.h>
arch/m68k/include/asm/page_mm.h renamed from arch/m68k/include/asm/page_mm.h~m68k-mm-enable-use-of-generic-memory_modelh-for-discontigmem +5 -0
@@ -153,6 +153,7 @@ static inline __attribute_const__ int __pfn_to_virt (page_to_pfn (page)); \ }) +#ifdef CONFIG_DISCONTIGMEM #define pfn_to_page (pfn) ({ \ unsigned long __pfn = (pfn); \ struct pglist_data *pgdat; \
@@ -165,6 +166,10 @@ static inline __attribute_const__ int __ pgdat = &pg_data_map[page_to_nid (__p)]; \ ((__p) - pgdat->node_mem_map) + pgdat->node_start_pfn; \ }) +#else +#define ARCH_PFN_OFFSET (m68k_memory[0].addr) +#include <asm-generic/memory_model.h> +#endif #define virt_addr_valid (kaddr) ((void *)(kaddr) >= (void *)PAGE_OFFSET && (void *)(kaddr) < high_memory)#define pfn_valid (pfn) virt_addr_valid(pfn_to_virt(pfn))
arch/m68k/include/asm/virtconvert.h renamed from arch/m68k/include/asm/virtconvert.h~m68k-mm-enable-use-of-generic-memory_modelh-for-discontigmem +0 -5
@@ -29,12 +29,7 @@ static inline void *phys_to_virt(unsigne }/* Permanent address of a page. */ -#if defined(CONFIG_MMU ) && !defined(CONFIG_DISCONTIGMEM ) -#define page_to_phys (page) \ - __pa(PAGE_OFFSET + (((page) - pg_data_map[0].node_mem_map) << PAGE_SHIFT)) -#else #define page_to_phys (page) (page_to_pfn(page) << PAGE_SHIFT) -#endif /* * IO bus memory addresses are 1:1 with the physical address,
arch/m68k/Kconfig.cpu renamed from arch/m68k/Kconfig.cpu~m68k-mm-enable-use-of-generic-memory_modelh-for-discontigmem +0 -1
@@ -374,7 +374,6 @@ config SINGLE_MEMORY_CHUNK bool "Use one physical chunk of memory only" if ADVANCED && !SUN3 depends on MMU default y if SUN3 || MMU_COLDFIRE - select NEED_MULTIPLE_NODES help Ignore all but the first contiguous chunk of physical memory for VM purposes. This will save a few bytes kernel size and may speed up
arch/m68k/mm/init.c renamed from arch/m68k/mm/init.c~m68k-mm-enable-use-of-generic-memory_modelh-for-discontigmem +3 -3
@@ -42,12 +42,12 @@ EXPORT_SYMBOL(empty_zero_page);#ifdef CONFIG_MMU -pg_data_t pg_data_map[MAX_NUMNODES ]; -EXPORT_SYMBOL (pg_data_map); -int m68k_virt_to_node_shift;#ifdef CONFIG_DISCONTIGMEM +pg_data_t pg_data_map[MAX_NUMNODES ]; +EXPORT_SYMBOL (pg_data_map); +pg_data_t *pg_data_table[65 ];EXPORT_SYMBOL (pg_data_table);#endif
_
Andrew Morton
maintainerPATCH 118/200 m68k: deprecate DISCONTIGMEM
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: m68k: deprecate DISCONTIGMEM
DISCONTIGMEM was intended to provide more efficient support for systems with holes in their physical address space that FLATMEM did.
Yet, it's overhead in terms of the memory consumption seems to overweight the savings on the unused memory map.
For a ARAnyM system with 16 MBytes of FastRAM configured, the memory usage reported after page allocator initialization is
Memory: 23828K/30720K available (3206K kernel code, 535K rwdata, 936K rodata, 768K init, 193K bss, 6892K reserved, 0K cma-reserved)
and with DISCONTIGMEM disabled and with relatively large hole in the memory map it is:
Memory: 23864K/30720K available (3197K kernel code, 516K rwdata, 936K rodata, 764K init, 179K bss, 6856K reserved, 0K cma-reserved)
Moreover, since m68k already has custom pfn_valid() it is possible to define HAVE_ARCH_PFN_VALID to enable freeing of unused memory map. The minimal size of a hole that can be freed should not be less than MAX_ORDER_NR_PAGES so to achieve more substantial memory savings let m68k also define custom FORCE_MAX_ZONEORDER.
With FORCE_MAX_ZONEORDER set to 9 memory usage becomes:
Memory: 23880K/30720K available (3197K kernel code, 516K rwdata, 936K rodata, 764K init, 179K bss, 6840K reserved, 0K cma-reserved)
---
arch/m68k/Kconfig.cpu | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-)
arch/m68k/Kconfig.cpu renamed from arch/m68k/Kconfig.cpu~m68k-deprecate-discontigmem +25 -1
@@ -20,6 +20,7 @@ choice config M68KCLASSIC bool "Classic M68K CPU family support" + select HAVE_ARCH_PFN_VALID config COLDFIRE bool "Coldfire CPU family support"
@@ -377,11 +378,34 @@ config SINGLE_MEMORY_CHUNK help Ignore all but the first contiguous chunk of physical memory for VM purposes. This will save a few bytes kernel size and may speed up - some operations. Say N if not sure. + some operations. + When this option os set to N, you may want to lower "Maximum zone + order" to save memory that could be wasted for unused memory map. + Say N if not sure. config ARCH_DISCONTIGMEM_ENABLE + depends on BROKEN def_bool MMU && !SINGLE_MEMORY_CHUNK +config FORCE_MAX_ZONEORDER + int "Maximum zone order" if ADVANCED + depends on !SINGLE_MEMORY_CHUNK + default "11" + help + The kernel memory allocator divides physically contiguous memory + blocks into "zones", where each zone is a power of two number of + pages. This option selects the largest power of two that the kernel + keeps in the memory allocator. If you need to allocate very large + blocks of physically contiguous memory, then you may need to + increase this value. + + For systems that have holes in their physical address space this + value also defines the minimal size of the hole that allows + freeing unused memory map. + + This config option is actually maximum order plus one. For example, + a value of 11 means that the largest free memory block is 2^10 pages. + config 060_WRITETHROUGH bool "Use write-through caching for 68060 supervisor accesses" depends on ADVANCED && M68060
_
Andrew Morton
maintainerPATCH 119/200 mm: introduce debug_pagealloc_{map,unmap}_pages() helpers
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: mm: introduce debug_pagealloc_{map,unmap}_pages() helpers
Patch series "arch, mm: improve robustness of direct map manipulation", v7.
During recent discussion about KVM protected memory, David raised a concern about usage of __kernel_map_pages() outside of DEBUG_PAGEALLOC scope [1].
Indeed, for architectures that define CONFIG_ARCH_HAS_SET_DIRECT_MAP it is possible that __kernel_map_pages() would fail, but since this function is void, the failure will go unnoticed.
Moreover, there's lack of consistency of __kernel_map_pages() semantics across architectures as some guard this function with #ifdef DEBUG_PAGEALLOC, some refuse to update the direct map if page allocation debugging is disabled at run time and some allow modifying the direct map regardless of DEBUG_PAGEALLOC settings.
This set straightens this out by restoring dependency of __kernel_map_pages() on DEBUG_PAGEALLOC and updating the call sites accordingly.
Since currently the only user of __kernel_map_pages() outside DEBUG_PAGEALLOC is hibernation, it is updated to make direct map accesses there more explicit.
[1] https://lore.kernel.org/lkml/[email protected]
This patch (of 4):
When CONFIG_DEBUG_PAGEALLOC is enabled, it unmaps pages from the kernel direct mapping after free_pages(). The pages than need to be mapped back before they could be used. Theese mapping operations use __kernel_map_pages() guarded with with debug_pagealloc_enabled().
The only place that calls __kernel_map_pages() without checking whether DEBUG_PAGEALLOC is enabled is the hibernation code that presumes availability of this function when ARCH_HAS_SET_DIRECT_MAP is set. Still, on arm64, __kernel_map_pages() will bail out when DEBUG_PAGEALLOC is not enabled but set_direct_map_invalid_noflush() may render some pages not present in the direct map and hibernation code won't be able to save such pages.
To make page allocation debugging and hibernation interaction more robust, the dependency on DEBUG_PAGEALLOC or ARCH_HAS_SET_DIRECT_MAP has to be made more explicit.
Start with combining the guard condition and the call to __kernel_map_pages() into debug_pagealloc_map_pages() and debug_pagealloc_unmap_pages() functions to emphasize that __kernel_map_pages() should not be called without DEBUG_PAGEALLOC and use these new functions to map/unmap pages when page allocation debugging is enabled.
---
include/linux/mm.h | 15 +++++++++++++++ mm/memory_hotplug.c | 3 +-- mm/page_alloc.c | 6 ++---- mm/slab.c | 2 +- 4 files changed, 19 insertions(+), 7 deletions(-)
include/linux/mm.h renamed from include/linux/mm.h~mm-introduce-debug_pagealloc_mapunmap_pages-helpers +15 -0
@@ -2943,12 +2943,27 @@ kernel_map_pages(struct page *page, int {__kernel_map_pages (page, numpages, enable); } + +static inline void debug_pagealloc_map_pages (struct page *page,int numpages) +{ +if (debug_pagealloc_enabled_static ()) +__kernel_map_pages (page, numpages,1 ); +} + +static inline void debug_pagealloc_unmap_pages (struct page *page,int numpages) +{ +if (debug_pagealloc_enabled_static ()) +__kernel_map_pages (page, numpages,0 ); +} +#ifdef CONFIG_HIBERNATION extern bool kernel_page_present (struct page *page);#endif /* CONFIG_HIBERNATION */ #else /* CONFIG_DEBUG_PAGEALLOC || CONFIG_ARCH_HAS_SET_DIRECT_MAP */ static inline void kernel_map_pages (struct page *page,int numpages,int enable) {} +static inline void debug_pagealloc_map_pages (struct page *page,int numpages) {} +static inline void debug_pagealloc_unmap_pages (struct page *page,int numpages) {}#ifdef CONFIG_HIBERNATION static inline bool kernel_page_present (struct page *page) {return true; }#endif /* CONFIG_HIBERNATION */
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-introduce-debug_pagealloc_mapunmap_pages-helpers +1 -2
@@ -596,8 +596,7 @@ void generic_online_page(struct page *pa* so we should map it first. This is better than introducing a special * case in page freeing fast path. */ -if (debug_pagealloc_enabled_static ()) -kernel_map_pages (page,1 << order,1 ); +debug_pagealloc_map_pages (page,1 << order);__free_pages_core (page, order);totalram_pages_add (1UL << order);#ifdef CONFIG_HIGHMEM
mm/page_alloc.c renamed from mm/page_alloc.c~mm-introduce-debug_pagealloc_mapunmap_pages-helpers +2 -4
@@ -1273,8 +1273,7 @@ static __always_inline bool free_pages_p*/ arch_free_page (page, order); -if (debug_pagealloc_enabled_static ()) -kernel_map_pages (page,1 << order,0 ); +debug_pagealloc_unmap_pages (page,1 << order);kasan_free_nondeferred_pages (page, order);
@@ -2279,8 +2278,7 @@ inline void post_alloc_hook(struct pageset_page_refcounted (page);arch_alloc_page (page, order); -if (debug_pagealloc_enabled_static ()) -kernel_map_pages (page,1 << order,1 ); +debug_pagealloc_map_pages (page,1 << order);kasan_alloc_pages (page, order);kernel_poison_pages (page,1 << order,1 );set_page_owner (page, order, gfp_flags);
mm/slab.c renamed from mm/slab.c~mm-introduce-debug_pagealloc_mapunmap_pages-helpers +1 -1
@@ -1435,7 +1435,7 @@ static void slab_kernel_map(struct kmem_if (!is_debug_pagealloc_cache (cachep))return ; - kernel_map_pages(virt_to_page(objp), cachep->size / PAGE_SIZE, map); + __kernel_map_pages(virt_to_page(objp), cachep->size / PAGE_SIZE, map); }#else
_
Andrew Morton
maintainerPATCH 120/200 PM: hibernate: make direct map manipulations more explicit
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: PM: hibernate: make direct map manipulations more explicit
When DEBUG_PAGEALLOC or ARCH_HAS_SET_DIRECT_MAP is enabled a page may be not present in the direct map and has to be explicitly mapped before it could be copied.
Introduce hibernate_map_page() and hibernation_unmap_page() that will explicitly use set_direct_map_{default,invalid}_noflush() for ARCH_HAS_SET_DIRECT_MAP case and debug_pagealloc_{map,unmap}_pages() for DEBUG_PAGEALLOC case.
The remapping of the pages in safe_copy_page() presumes that it only changes protection bits in an existing PTE and so it is safe to ignore return value of set_direct_map_{default,invalid}_noflush().
Still, add a pr_warn() so that future changes in set_memory APIs will not silently break hibernation.
---
include/linux/mm.h | 12 ------------ kernel/power/snapshot.c | 38 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 14 deletions(-)
include/linux/mm.h renamed from include/linux/mm.h~pm-hibernate-make-direct-map-manipulations-more-explicit +0 -12
@@ -2934,16 +2934,6 @@ static inline bool debug_pagealloc_enabl#if defined(CONFIG_DEBUG_PAGEALLOC ) || defined(CONFIG_ARCH_HAS_SET_DIRECT_MAP )extern void __kernel_map_pages (struct page *page,int numpages,int enable); -/* -* When called in DEBUG_PAGEALLOC context, the call should most likely be -* guarded by debug_pagealloc_enabled() or debug_pagealloc_enabled_static() -*/ -static inline void -kernel_map_pages (struct page *page,int numpages,int enable) -{ -__kernel_map_pages (page, numpages, enable); -} -static inline void debug_pagealloc_map_pages (struct page *page,int numpages) {if (debug_pagealloc_enabled_static ())
@@ -2960,8 +2950,6 @@ static inline void debug_pagealloc_unmapextern bool kernel_page_present (struct page *page);#endif /* CONFIG_HIBERNATION */ #else /* CONFIG_DEBUG_PAGEALLOC || CONFIG_ARCH_HAS_SET_DIRECT_MAP */ -static inline void -kernel_map_pages (struct page *page,int numpages,int enable) {}static inline void debug_pagealloc_map_pages (struct page *page,int numpages) {}static inline void debug_pagealloc_unmap_pages (struct page *page,int numpages) {}#ifdef CONFIG_HIBERNATION
kernel/power/snapshot.c renamed from kernel/power/snapshot.c~pm-hibernate-make-direct-map-manipulations-more-explicit +36 -2
@@ -76,6 +76,40 @@ static inline void hibernate_restore_prostatic inline void hibernate_restore_unprotect_page (void *page_address) {}#endif /* CONFIG_STRICT_KERNEL_RWX && CONFIG_ARCH_HAS_SET_MEMORY */ + +/* +* The calls to set_direct_map_*() should not fail because remapping a page +* here means that we only update protection bits in an existing PTE. +* It is still worth to have a warning here if something changes and this +* will no longer be the case. +*/ +static inline void hibernate_map_page (struct page *page) +{ +if (IS_ENABLED (CONFIG_ARCH_HAS_SET_DIRECT_MAP )) { +int ret =set_direct_map_default_noflush (page); + +if (ret) +pr_warn_once ("Failed to remap page\n" ); + }else { +debug_pagealloc_map_pages (page,1 ); + } +} + +static inline void hibernate_unmap_page (struct page *page) +{ +if (IS_ENABLED (CONFIG_ARCH_HAS_SET_DIRECT_MAP )) { +unsigned long addr = (unsigned long )page_address (page); +int ret =set_direct_map_invalid_noflush (page); + +if (ret) +pr_warn_once ("Failed to remap page\n" ); + +flush_tlb_kernel_range (addr, addr +PAGE_SIZE ); + }else { +debug_pagealloc_unmap_pages (page,1 ); + } +} +static int swsusp_page_is_free (struct page *);static void swsusp_set_page_forbidden (struct page *);static void swsusp_unset_page_forbidden (struct page *);
@@ -1355,9 +1389,9 @@ static void safe_copy_page(void *dst, stif (kernel_page_present (s_page)) {do_copy_page (dst,page_address (s_page)); }else { -kernel_map_pages (s_page,1 ,1 ); +hibernate_map_page (s_page);do_copy_page (dst,page_address (s_page)); -kernel_map_pages (s_page,1 ,0 ); +hibernate_unmap_page (s_page); } }
_
Andrew Morton
maintainerPATCH 121/200 arch, mm: restore dependency of __kernel_map_pages() on DEBUG_PAGEALLOC
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: arch, mm: restore dependency of __kernel_map_pages() on DEBUG_PAGEALLOC
The design of DEBUG_PAGEALLOC presumes that __kernel_map_pages() must never fail. With this assumption is wouldn't be safe to allow general usage of this function.
Moreover, some architectures that implement __kernel_map_pages() have this function guarded by #ifdef DEBUG_PAGEALLOC and some refuse to map/unmap pages when page allocation debugging is disabled at runtime.
As all the users of __kernel_map_pages() were converted to use debug_pagealloc_map_pages() it is safe to make it available only when DEBUG_PAGEALLOC is set.
---
arch/Kconfig | 3 +++ arch/arm64/Kconfig | 4 +--- arch/arm64/mm/pageattr.c | 8 ++++++-- arch/powerpc/Kconfig | 5 +---- arch/riscv/Kconfig | 4 +--- arch/riscv/include/asm/pgtable.h | 2 -- arch/riscv/mm/pageattr.c | 2 ++ arch/s390/Kconfig | 4 +--- arch/sparc/Kconfig | 4 +--- arch/x86/Kconfig | 4 +--- arch/x86/mm/pat/set_memory.c | 2 ++ include/linux/mm.h | 10 +++++++--- 12 files changed, 26 insertions(+), 26 deletions(-)
arch/arm64/Kconfig renamed from arch/arm64/Kconfig~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +1 -3
@@ -71,6 +71,7 @@ config ARM64 select ARCH_USE_QUEUED_RWLOCKS select ARCH_USE_QUEUED_SPINLOCKS select ARCH_USE_SYM_ANNOTATIONS + select ARCH_SUPPORTS_DEBUG_PAGEALLOC select ARCH_SUPPORTS_MEMORY_FAILURE select ARCH_SUPPORTS_SHADOW_CALL_STACK if CC_HAVE_SHADOW_CALL_STACK select ARCH_SUPPORTS_ATOMIC_RMW
@@ -1028,9 +1029,6 @@ config HOLES_IN_ZONE source "kernel/Kconfig.hz" -config ARCH_SUPPORTS_DEBUG_PAGEALLOC - def_bool y - config ARCH_SPARSEMEM_ENABLE def_bool y select SPARSEMEM_VMEMMAP_ENABLE
arch/arm64/mm/pageattr.c renamed from arch/arm64/mm/pageattr.c~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +6 -2
@@ -155,7 +155,7 @@ int set_direct_map_invalid_noflush(struc .clear_mask = __pgprot(PTE_VALID), }; -if (!rodata_full) +if (!debug_pagealloc_enabled () && !rodata_full)return 0 ; return apply_to_page_range(&init_mm,
@@ -170,7 +170,7 @@ int set_direct_map_default_noflush(struc .clear_mask = __pgprot(PTE_RDONLY), }; -if (!rodata_full) +if (!debug_pagealloc_enabled () && !rodata_full)return 0 ; return apply_to_page_range(&init_mm,
@@ -178,6 +178,7 @@ int set_direct_map_default_noflush(struc PAGE_SIZE, change_page_range, &data); } +#ifdef CONFIG_DEBUG_PAGEALLOC void __kernel_map_pages (struct page *page,int numpages,int enable) {if (!debug_pagealloc_enabled () && !rodata_full)
@@ -186,6 +187,7 @@ void __kernel_map_pages(struct page *pagset_memory_valid ((unsigned long )page_address (page), numpages, enable); } +#ifdef CONFIG_HIBERNATION /* * This function is used to determine if a linear map page has been marked as * not-valid. Walk the page table and check the PTE_VALID bit. This is based
@@ -232,3 +234,5 @@ bool kernel_page_present(struct page *pa ptep =pte_offset_kernel (pmdp, addr);return pte_valid (READ_ONCE (*ptep)); } +#endif /* CONFIG_HIBERNATION */ +#endif /* CONFIG_DEBUG_PAGEALLOC */
arch/Kconfig renamed from arch/Kconfig~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +3 -0
@@ -1047,6 +1047,9 @@ config ARCH_WANT_LD_ORPHAN_WARN config HAVE_ARCH_PFN_VALID bool +config ARCH_SUPPORTS_DEBUG_PAGEALLOC + bool + source "kernel/gcov/Kconfig" source "scripts/gcc-plugins/Kconfig"
arch/powerpc/Kconfig renamed from arch/powerpc/Kconfig~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +1 -4
@@ -146,6 +146,7 @@ config PPC select ARCH_MIGHT_HAVE_PC_SERIO select ARCH_OPTIONAL_KERNEL_RWX if ARCH_HAS_STRICT_KERNEL_RWX select ARCH_SUPPORTS_ATOMIC_RMW + select ARCH_SUPPORTS_DEBUG_PAGEALLOC if PPC32 || PPC_BOOK3S_64 select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_CMPXCHG_LOCKREF if PPC64 select ARCH_USE_QUEUED_RWLOCKS if PPC_QUEUED_SPINLOCKS
@@ -356,10 +357,6 @@ config PPC_OF_PLATFORM_PCI depends on PCI depends on PPC64 # not supported on 32 bits yet -config ARCH_SUPPORTS_DEBUG_PAGEALLOC - depends on PPC32 || PPC_BOOK3S_64 - def_bool y - config ARCH_SUPPORTS_UPROBES def_bool y
arch/riscv/include/asm/pgtable.h renamed from arch/riscv/include/asm/pgtable.h~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +0 -2
@@ -461,8 +461,6 @@ static inline int ptep_clear_flush_young#define VMALLOC_START 0#define VMALLOC_END TASK_SIZE -static inline void __kernel_map_pages (struct page *page,int numpages,int enable) {} -#endif /* !CONFIG_MMU */ #define kern_addr_valid (addr) (1)/* FIXME */
arch/riscv/Kconfig renamed from arch/riscv/Kconfig~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +1 -3
@@ -14,6 +14,7 @@ config RISCV def_bool y select ARCH_CLOCKSOURCE_INIT select ARCH_SUPPORTS_ATOMIC_RMW + select ARCH_SUPPORTS_DEBUG_PAGEALLOC if MMU select ARCH_HAS_BINFMT_FLAT select ARCH_HAS_DEBUG_VM_PGTABLE select ARCH_HAS_DEBUG_VIRTUAL if MMU
@@ -153,9 +154,6 @@ config ARCH_SELECT_MEMORY_MODEL config ARCH_WANT_GENERAL_HUGETLB def_bool y -config ARCH_SUPPORTS_DEBUG_PAGEALLOC - def_bool y - config SYS_SUPPORTS_HUGETLBFS depends on MMU def_bool y
arch/riscv/mm/pageattr.c renamed from arch/riscv/mm/pageattr.c~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +2 -0
@@ -184,6 +184,7 @@ int set_direct_map_default_noflush(strucreturn ret; } +#ifdef CONFIG_DEBUG_PAGEALLOC void __kernel_map_pages (struct page *page,int numpages,int enable) {if (!debug_pagealloc_enabled ())
@@ -196,3 +197,4 @@ void __kernel_map_pages(struct page *pag__set_memory ((unsigned long )page_address (page), numpages, __pgprot(0), __pgprot(_PAGE_PRESENT)); } +#endif
arch/s390/Kconfig renamed from arch/s390/Kconfig~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +1 -3
@@ -35,9 +35,6 @@ config GENERIC_LOCKBREAK config PGSTE def_bool y if KVM -config ARCH_SUPPORTS_DEBUG_PAGEALLOC - def_bool y - config AUDIT_ARCH def_bool y
@@ -106,6 +103,7 @@ config S390 select ARCH_INLINE_WRITE_UNLOCK_IRQRESTORE select ARCH_STACKWALK select ARCH_SUPPORTS_ATOMIC_RMW + select ARCH_SUPPORTS_DEBUG_PAGEALLOC select ARCH_SUPPORTS_NUMA_BALANCING select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_CMPXCHG_LOCKREF
arch/sparc/Kconfig renamed from arch/sparc/Kconfig~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +1 -3
@@ -88,6 +88,7 @@ config SPARC64 select HAVE_C_RECORDMCOUNT select HAVE_ARCH_AUDITSYSCALL select ARCH_SUPPORTS_ATOMIC_RMW + select ARCH_SUPPORTS_DEBUG_PAGEALLOC select HAVE_NMI select HAVE_REGS_AND_STACK_ACCESS_API select ARCH_USE_QUEUED_RWLOCKS
@@ -148,9 +149,6 @@ config GENERIC_ISA_DMA bool default y if SPARC32 -config ARCH_SUPPORTS_DEBUG_PAGEALLOC - def_bool y if SPARC64 - config PGTABLE_LEVELS default 4 if 64BIT default 3
arch/x86/Kconfig renamed from arch/x86/Kconfig~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +1 -3
@@ -91,6 +91,7 @@ config X86 select ARCH_STACKWALK select ARCH_SUPPORTS_ACPI select ARCH_SUPPORTS_ATOMIC_RMW + select ARCH_SUPPORTS_DEBUG_PAGEALLOC select ARCH_SUPPORTS_NUMA_BALANCING if X86_64 select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_QUEUED_RWLOCKS
@@ -331,9 +332,6 @@ config ZONE_DMA32 config AUDIT_ARCH def_bool y if X86_64 -config ARCH_SUPPORTS_DEBUG_PAGEALLOC - def_bool y - config KASAN_SHADOW_OFFSET hex depends on KASAN
arch/x86/mm/pat/set_memory.c renamed from arch/x86/mm/pat/set_memory.c~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +2 -0
@@ -2194,6 +2194,7 @@ int set_direct_map_default_noflush(strucreturn __set_pages_p (page,1 ); } +#ifdef CONFIG_DEBUG_PAGEALLOC void __kernel_map_pages (struct page *page,int numpages,int enable) {if (PageHighMem (page))
@@ -2239,6 +2240,7 @@ bool kernel_page_present(struct page *pareturn (pte_val (*pte) & _PAGE_PRESENT); }#endif /* CONFIG_HIBERNATION */ +#endif /* CONFIG_DEBUG_PAGEALLOC */ int __init kernel_map_pages_in_pgd (pgd_t *pgd,u64 pfn,unsigned long address,unsigned numpages,unsigned long page_flags)
include/linux/mm.h renamed from include/linux/mm.h~arch-mm-restore-dependency-of-__kernel_map_pages-on-debug_pagealloc +7 -3
@@ -2931,7 +2931,11 @@ static inline bool debug_pagealloc_enablreturn static_branch_unlikely (&_debug_pagealloc_enabled); } -#if defined(CONFIG_DEBUG_PAGEALLOC ) || defined(CONFIG_ARCH_HAS_SET_DIRECT_MAP ) +#ifdef CONFIG_DEBUG_PAGEALLOC +/* +* To support DEBUG_PAGEALLOC architecture must ensure that +* __kernel_map_pages() never fails +*/ extern void __kernel_map_pages (struct page *page,int numpages,int enable);static inline void debug_pagealloc_map_pages (struct page *page,int numpages)
@@ -2949,13 +2953,13 @@ static inline void debug_pagealloc_unmap#ifdef CONFIG_HIBERNATION extern bool kernel_page_present (struct page *page);#endif /* CONFIG_HIBERNATION */ -#else /* CONFIG_DEBUG_PAGEALLOC || CONFIG_ARCH_HAS_SET_DIRECT_MAP */ +#else /* CONFIG_DEBUG_PAGEALLOC */ static inline void debug_pagealloc_map_pages (struct page *page,int numpages) {}static inline void debug_pagealloc_unmap_pages (struct page *page,int numpages) {}#ifdef CONFIG_HIBERNATION static inline bool kernel_page_present (struct page *page) {return true; }#endif /* CONFIG_HIBERNATION */ -#endif /* CONFIG_DEBUG_PAGEALLOC || CONFIG_ARCH_HAS_SET_DIRECT_MAP */ +#endif /* CONFIG_DEBUG_PAGEALLOC */ #ifdef __HAVE_ARCH_GATE_AREAextern struct vm_area_struct *get_gate_vma (struct mm_struct *mm);
_
Andrew Morton
maintainerPATCH 122/200 arch, mm: make kernel_page_present() always available
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: arch, mm: make kernel_page_present() always available
For architectures that enable ARCH_HAS_SET_MEMORY having the ability to verify that a page is mapped in the kernel direct map can be useful regardless of hibernation.
Add RISC-V implementation of kernel_page_present(), update its forward declarations and stubs to be a part of set_memory API and remove ugly ifdefery in inlcude/linux/mm.h around current declarations of kernel_page_present().
---
arch/arm64/include/asm/cacheflush.h | 1 arch/arm64/mm/pageattr.c | 4 --- arch/riscv/include/asm/set_memory.h | 1 arch/riscv/mm/pageattr.c | 29 ++++++++++++++++++++++++++ arch/x86/include/asm/set_memory.h | 1 arch/x86/mm/pat/set_memory.c | 4 --- include/linux/mm.h | 7 ------ include/linux/set_memory.h | 5 ++++ 8 files changed, 39 insertions(+), 13 deletions(-)
arch/arm64/include/asm/cacheflush.h renamed from arch/arm64/include/asm/cacheflush.h~arch-mm-make-kernel_page_present-always-available +1 -0
@@ -140,6 +140,7 @@ int set_memory_valid(unsigned long addr,int set_direct_map_invalid_noflush (struct page *page);int set_direct_map_default_noflush (struct page *page); +bool kernel_page_present (struct page *page);#include <asm-generic/cacheflush.h>
arch/arm64/mm/pageattr.c renamed from arch/arm64/mm/pageattr.c~arch-mm-make-kernel_page_present-always-available +1 -3
@@ -186,8 +186,8 @@ void __kernel_map_pages(struct page *pag set_memory_valid((unsigned long)page_address(page), numpages, enable); } +#endif /* CONFIG_DEBUG_PAGEALLOC */ -#ifdef CONFIG_HIBERNATION /* * This function is used to determine if a linear map page has been marked as * not-valid. Walk the page table and check the PTE_VALID bit. This is based
@@ -234,5 +234,3 @@ bool kernel_page_present(struct page *pa ptep =pte_offset_kernel (pmdp, addr);return pte_valid (READ_ONCE (*ptep)); } -#endif /* CONFIG_HIBERNATION */ -#endif /* CONFIG_DEBUG_PAGEALLOC */
arch/riscv/include/asm/set_memory.h renamed from arch/riscv/include/asm/set_memory.h~arch-mm-make-kernel_page_present-always-available +1 -0
@@ -24,6 +24,7 @@ static inline int set_memory_nx(unsignedint set_direct_map_invalid_noflush (struct page *page);int set_direct_map_default_noflush (struct page *page); +bool kernel_page_present (struct page *page);#endif /* __ASSEMBLY__ */
arch/riscv/mm/pageattr.c renamed from arch/riscv/mm/pageattr.c~arch-mm-make-kernel_page_present-always-available +29 -0
@@ -198,3 +198,32 @@ void __kernel_map_pages(struct page *pag __pgprot(0), __pgprot(_PAGE_PRESENT)); }#endif + +bool kernel_page_present (struct page *page) +{ +unsigned long addr = (unsigned long )page_address (page); +pgd_t *pgd; +pud_t *pud; +p4d_t *p4d; +pmd_t *pmd; +pte_t *pte; + + pgd =pgd_offset_k (addr); +if (!pgd_present (*pgd)) +return false; + + p4d =p4d_offset (pgd, addr); +if (!p4d_present (*p4d)) +return false; + + pud =pud_offset (p4d, addr); +if (!pud_present (*pud)) +return false; + + pmd =pmd_offset (pud, addr); +if (!pmd_present (*pmd)) +return false; + + pte =pte_offset_kernel (pmd, addr); +return pte_present (*pte); +}
arch/x86/include/asm/set_memory.h renamed from arch/x86/include/asm/set_memory.h~arch-mm-make-kernel_page_present-always-available +1 -0
@@ -82,6 +82,7 @@ int set_pages_rw(struct page *page, intint set_direct_map_invalid_noflush (struct page *page);int set_direct_map_default_noflush (struct page *page); +bool kernel_page_present (struct page *page);extern int kernel_set_to_readonly;
arch/x86/mm/pat/set_memory.c renamed from arch/x86/mm/pat/set_memory.c~arch-mm-make-kernel_page_present-always-available +1 -3
@@ -2226,8 +2226,8 @@ void __kernel_map_pages(struct page *pag arch_flush_lazy_mmu_mode(); } +#endif /* CONFIG_DEBUG_PAGEALLOC */ -#ifdef CONFIG_HIBERNATION bool kernel_page_present (struct page *page) {unsigned int level;
@@ -2239,8 +2239,6 @@ bool kernel_page_present(struct page *pa pte =lookup_address ((unsigned long )page_address (page), &level);return (pte_val (*pte) & _PAGE_PRESENT); } -#endif /* CONFIG_HIBERNATION */ -#endif /* CONFIG_DEBUG_PAGEALLOC */ int __init kernel_map_pages_in_pgd (pgd_t *pgd,u64 pfn,unsigned long address,unsigned numpages,unsigned long page_flags)
include/linux/mm.h renamed from include/linux/mm.h~arch-mm-make-kernel_page_present-always-available +0 -7
@@ -2949,16 +2949,9 @@ static inline void debug_pagealloc_unmapif (debug_pagealloc_enabled_static ()) __kernel_map_pages(page, numpages, 0); } - -#ifdef CONFIG_HIBERNATION -extern bool kernel_page_present (struct page *page); -#endif /* CONFIG_HIBERNATION */ #else /* CONFIG_DEBUG_PAGEALLOC */ static inline void debug_pagealloc_map_pages (struct page *page,int numpages) {}static inline void debug_pagealloc_unmap_pages (struct page *page,int numpages) {} -#ifdef CONFIG_HIBERNATION -static inline bool kernel_page_present (struct page *page) {return true; } -#endif /* CONFIG_HIBERNATION */ #endif /* CONFIG_DEBUG_PAGEALLOC */ #ifdef __HAVE_ARCH_GATE_AREA
include/linux/set_memory.h renamed from include/linux/set_memory.h~arch-mm-make-kernel_page_present-always-available +5 -0
@@ -23,6 +23,11 @@ static inline int set_direct_map_default {return 0 ; } + +static inline bool kernel_page_present (struct page *page) +{ +return true; +}#endif #ifndef set_mce_nospec
_
Andrew Morton
maintainerPATCH 123/200 mm, page_alloc: clean up pageset high and batch update
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_alloc: clean up pageset high and batch update
Patch series "disable pcplists during memory offline", v3.
As per the discussions [1] [2] this is an attempt to implement David's suggestion that page isolation should disable pcplists to avoid races with page freeing in progress. This is done without extra checks in fast paths, as explained in Patch 9. The repeated draining done by [2] is then no longer needed. Previous version (RFC) is at [3].
The RFC tried to hide pcplists disabling/enabling into page isolation, but it wasn't completely possible, as memory offline does not unisolation. Michal suggested an explicit API in [4] so that's the current implementation and it seems indeed nicer.
Once we accept that page isolation users need to do explicit actions around it depending on the needed guarantees, we can also IMHO accept that the current pcplist draining can be also done by the callers, which is more effective. After all, there are only two users of page isolation. So patch 6 does effectively the same thing as Pavel proposed in [5], and patch 7 implement stronger guarantees only for memory offline. If CMA decides to opt-in to the stronger guarantee, it can be added later.
Patches 1-5 are preparatory cleanups for pcplist disabling.
Patchset was briefly tested in QEMU so that memory online/offline works, but I haven't done a stress test that would prove the race fixed by [2] is eliminated.
Note that patch 7 could be avoided if we instead adjusted page freeing in shown in [6], but I believe the current implementation of disabling pcplists is not too much complex, so I would prefer this instead of adding new checks and longer irq-disabled section into page freeing hotpaths.
[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://lore.kernel.org/linux-mm/[email protected]/
[3] https://lore.kernel.org/linux-mm/[email protected]/
[4] https://lore.kernel.org/linux-mm/[email protected]/
[5] https://lore.kernel.org/linux-mm/[email protected]/
[6] https://lore.kernel.org/linux-mm/[email protected]/
[7] https://lore.kernel.org/linux-mm/[email protected]/
[8] https://lore.kernel.org/linux-mm/[email protected]/
This patch (of 7):
The updates to pcplists' high and batch values are handled by multiple functions that make the calculations hard to follow. Consolidate everything to pageset_set_high_and_batch() and remove pageset_set_batch() and pageset_set_high() wrappers.
The only special case using one of the removed wrappers was:build_all_zonelists_init()
setup_pageset()
pageset_set_batch()
which was hardcoding batch as 0, so we can just open-code a call to pageset_update() with constant parameters instead.
No functional change.
---
mm/page_alloc.c | 49 ++++++++++++++++++---------------------------- 1 file changed, 20 insertions(+), 29 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-clean-up-pageset-high-and-batch-update +20 -29
@@ -5919,7 +5919,7 @@ static void build_zonelists(pg_data_t *p* not check if the processor is online before following the pageset pointer. * Other parts of the kernel may not check if the zone is available. */ -static void setup_pageset (struct per_cpu_pageset *p,unsigned long batch); +static void setup_pageset (struct per_cpu_pageset *p); static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset); static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
@@ -5987,7 +5987,7 @@ build_all_zonelists_init(void)* (a chicken-egg dilemma). */ for_each_possible_cpu (cpu) -setup_pageset (&per_cpu (boot_pageset, cpu),0 ); +setup_pageset (&per_cpu (boot_pageset, cpu));mminit_verify_zonelist ();cpuset_init_current_mems_allowed ();
@@ -6296,12 +6296,6 @@ static void pageset_update(struct per_cp pcp->batch = batch; } -/* a companion to pageset_set_high() */ -static void pageset_set_batch (struct per_cpu_pageset *p,unsigned long batch) -{ -pageset_update (&p->pcp,6 * batch,max (1UL ,1 * batch)); -} -static void pageset_init (struct per_cpu_pageset *p) {struct per_cpu_pages *pcp;
@@ -6314,35 +6308,32 @@ static void pageset_init(struct per_cpu_INIT_LIST_HEAD (&pcp->lists[migratetype]); } -static void setup_pageset (struct per_cpu_pageset *p,unsigned long batch) +static void setup_pageset (struct per_cpu_pageset *p) {pageset_init (p); -pageset_set_batch (p, batch); +pageset_update (&p->pcp,0 ,1 ); }/* -* pageset_set_high() sets the high water mark for hot per_cpu_pagelist -* to the value high for the pageset p. +* Calculate and set new high and batch values for given per-cpu pageset of a +* zone, based on the zone's size and the percpu_pagelist_fraction sysctl. */ -static void pageset_set_high (struct per_cpu_pageset *p, -unsigned long high) -{ -unsigned long batch =max (1UL , high /4 ); -if ((high /4 ) > (PAGE_SHIFT *8 )) - batch =PAGE_SHIFT *8 ; - -pageset_update (&p->pcp, high, batch); -} -static void pageset_set_high_and_batch (struct zone *zone, -struct per_cpu_pageset *pcp) +struct per_cpu_pageset *p) { -if (percpu_pagelist_fraction) -pageset_set_high (pcp, - (zone_managed_pages (zone) / - percpu_pagelist_fraction)); -else -pageset_set_batch (pcp,zone_batchsize (zone)); +unsigned long new_high, new_batch; + +if (percpu_pagelist_fraction) { + new_high =zone_managed_pages (zone) / percpu_pagelist_fraction; + new_batch =max (1UL , new_high /4 ); +if ((new_high /4 ) > (PAGE_SHIFT *8 )) + new_batch =PAGE_SHIFT *8 ; + }else { + new_batch =zone_batchsize (zone); + new_high =6 * new_batch; + new_batch =max (1UL ,1 * new_batch); + } +pageset_update (&p->pcp, new_high, new_batch); }static void __meminit zone_pageset_init (struct zone *zone,int cpu)
_
Andrew Morton
maintainerPATCH 124/200 mm, page_alloc: calculate pageset high and batch once per zone
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_alloc: calculate pageset high and batch once per zone
We currently call pageset_set_high_and_batch() for each possible cpu, which repeats the same calculations of high and batch values.
Instead call the function just once per zone, and make it apply the calculated values to all per-cpu pagesets of the zone.
This also allows removing the zone_pageset_init() and __zone_pcp_update() wrappers.
No functional change.
---
mm/page_alloc.c | 42 ++++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 24 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-calculate-pageset-high-and-batch-once-per-zone +18 -24
@@ -6315,13 +6315,14 @@ static void setup_pageset(struct per_cpu }/* -* Calculate and set new high and batch values for given per-cpu pageset of a +* Calculate and set new high and batch values for all per-cpu pagesets of a * zone, based on the zone's size and the percpu_pagelist_fraction sysctl. */ -static void pageset_set_high_and_batch (struct zone *zone, -struct per_cpu_pageset *p) +static void zone_set_pageset_high_and_batch (struct zone *zone) {unsigned long new_high, new_batch; +struct per_cpu_pageset *p; +int cpu;if (percpu_pagelist_fraction) { new_high =zone_managed_pages (zone) / percpu_pagelist_fraction;
@@ -6333,23 +6334,25 @@ static void pageset_set_high_and_batch(s new_high =6 * new_batch; new_batch =max (1UL ,1 * new_batch); } -pageset_update (&p->pcp, new_high, new_batch); -} - -static void __meminit zone_pageset_init (struct zone *zone,int cpu) -{ -struct per_cpu_pageset *pcp =per_cpu_ptr (zone->pageset, cpu); -pageset_init (pcp); -pageset_set_high_and_batch (zone, pcp); +for_each_possible_cpu (cpu) { + p =per_cpu_ptr (zone->pageset, cpu); +pageset_update (&p->pcp, new_high, new_batch); + } }void __meminit setup_zone_pageset (struct zone *zone) { +struct per_cpu_pageset *p;int cpu; + zone->pageset = alloc_percpu(struct per_cpu_pageset); -for_each_possible_cpu (cpu) -zone_pageset_init (zone, cpu); +for_each_possible_cpu (cpu) { + p =per_cpu_ptr (zone->pageset, cpu); +pageset_init (p); + } + +zone_set_pageset_high_and_batch (zone); }/*
@@ -8083,15 +8086,6 @@ int lowmem_reserve_ratio_sysctl_handler(return 0 ; } -static void __zone_pcp_update (struct zone *zone) -{ -unsigned int cpu; - -for_each_possible_cpu (cpu) -pageset_set_high_and_batch (zone, -per_cpu_ptr (zone->pageset, cpu)); -} -/* * percpu_pagelist_fraction - changes the pcp->high for each zone on each * cpu. It is the fraction of total pages in each zone that a hot per cpu
@@ -8124,7 +8118,7 @@ int percpu_pagelist_fraction_sysctl_hand goto out;for_each_populated_zone (zone) -__zone_pcp_update (zone); +zone_set_pageset_high_and_batch (zone); out:mutex_unlock (&pcp_batch_high_lock);return ret;
@@ -8731,7 +8725,7 @@ EXPORT_SYMBOL(free_contig_range);void __meminit zone_pcp_update (struct zone *zone) {mutex_lock (&pcp_batch_high_lock); -__zone_pcp_update (zone); +zone_set_pageset_high_and_batch (zone);mutex_unlock (&pcp_batch_high_lock); }
_
Andrew Morton
maintainerPATCH 125/200 mm, page_alloc: remove setup_pageset()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_alloc: remove setup_pageset()
We initialize boot-time pagesets with setup_pageset(), which sets high and batch values that effectively disable pcplists.
We can remove this wrapper if we just set these values for all pagesets in pageset_init(). Non-boot pagesets then subsequently update them to the proper values.
No functional change.
---
mm/page_alloc.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-remove-setup_pageset +10 -7
@@ -5919,7 +5919,7 @@ static void build_zonelists(pg_data_t *p* not check if the processor is online before following the pageset pointer. * Other parts of the kernel may not check if the zone is available. */ -static void setup_pageset (struct per_cpu_pageset *p); +static void pageset_init (struct per_cpu_pageset *p); static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset); static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
@@ -5987,7 +5987,7 @@ build_all_zonelists_init(void)* (a chicken-egg dilemma). */ for_each_possible_cpu (cpu) -setup_pageset (&per_cpu (boot_pageset, cpu)); +pageset_init (&per_cpu (boot_pageset, cpu));mminit_verify_zonelist ();cpuset_init_current_mems_allowed ();
@@ -6306,12 +6306,15 @@ static void pageset_init(struct per_cpu_ pcp = &p->pcp;for (migratetype =0 ; migratetype <MIGRATE_PCPTYPES ; migratetype++)INIT_LIST_HEAD (&pcp->lists[migratetype]); -} -static void setup_pageset (struct per_cpu_pageset *p) -{ -pageset_init (p); -pageset_update (&p->pcp,0 ,1 ); +/* +* Set batch and high values safe for a boot pageset. A true percpu +* pageset's initialization will update them subsequently. Here we don't +* need to be as careful as pageset_update() as nobody can access the +* pageset yet. +*/ + pcp->high =0 ; + pcp->batch =1 ; }/*
_
Andrew Morton
maintainerPATCH 126/200 mm, page_alloc: simplify pageset_update()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_alloc: simplify pageset_update()
pageset_update() attempts to update pcplist's high and batch values in a way that readers don't observe batch > high. It uses smp_wmb() to order the updates in a way to achieve this. However, without proper pairing read barriers in readers this guarantee doesn't hold, and there are no such barriers in e.g. free_unref_page_commit().
Commit 88e8ac11d2ea ("mm, page_alloc: fix core hung in free_pcppages_bulk()") already showed this is problematic, and solved this by ultimately only trusing pcp->count of the current cpu with interrupts disabled.
The update dance with unpaired write barriers thus makes no sense. Replace them with plain WRITE_ONCE to prevent store tearing, and document that the values can change asynchronously and should not be trusted for correctness.
All current readers appear to be OK after 88e8ac11d2ea. Convert them to READ_ONCE to prevent unnecessary read tearing, but mainly to alert anybody making future changes to the code that special care is needed.
---
mm/page_alloc.c | 42 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 23 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-simplify-pageset_update +19 -23
@@ -1344,7 +1344,7 @@ static void free_pcppages_bulk(struct zo {int migratetype =0 ;int batch_free =0 ; -int prefetch_nr =0 ; +int prefetch_nr =READ_ONCE (pcp->batch);bool isolated_pageblocks;struct page *page, *tmp;LIST_HEAD (head);
@@ -1395,8 +1395,10 @@ static void free_pcppages_bulk(struct zo* avoid excessive prefetching due to large count, only * prefetch buddy for the first pcp->batch nr of pages. */ -if (prefetch_nr++ < pcp->batch) +if (prefetch_nr) {prefetch_buddy (page); + prefetch_nr--; + } }while (--count && --batch_free && !list_empty (list)); }
@@ -3197,10 +3199,8 @@ static void free_unref_page_commit(struc pcp = &this_cpu_ptr (zone->pageset)->pcp;list_add (&page->lru, &pcp->lists[migratetype]); pcp->count++; -if (pcp->count >= pcp->high) { -unsigned long batch =READ_ONCE (pcp->batch); -free_pcppages_bulk (zone, batch, pcp); - } +if (pcp->count >=READ_ONCE (pcp->high)) +free_pcppages_bulk (zone,READ_ONCE (pcp->batch), pcp); }/*
@@ -3385,7 +3385,7 @@ static struct page *__rmqueue_pcplist(st do { if (list_empty(list)) { pcp->count += rmqueue_bulk(zone, 0, - pcp->batch, list, + READ_ONCE(pcp->batch), list, migratetype, alloc_flags); if (unlikely(list_empty(list))) return NULL;
@@ -6270,13 +6270,16 @@ static int zone_batchsize(struct zone *z }/* -* pcp->high and pcp->batch values are related and dependent on one another: -* ->batch must never be higher then ->high. -* The following function updates them in a safe manner without read side -* locking. -* -* Any new users of pcp->batch and pcp->high should ensure they can cope with -* those fields changing asynchronously (acording to the above rule). +* pcp->high and pcp->batch values are related and generally batch is lower +* than high. They are also related to pcp->count such that count is lower +* than high, and as soon as it reaches high, the pcplist is flushed. +* +* However, guaranteeing these relations at all times would require e.g. write +* barriers here but also careful usage of read barriers at the read side, and +* thus be prone to error and bad for performance. Thus the update only prevents +* store tearing. Any new users of pcp->batch and pcp->high should ensure they +* can cope with those fields changing asynchronously, and fully trust only the +* pcp->count field on the local CPU with interrupts disabled. * * mutex_is_locked(&pcp_batch_high_lock) required when calling this function * outside of boot time (or some other assurance that no concurrent updaters
@@ -6285,15 +6288,8 @@ static int zone_batchsize(struct zone *zstatic void pageset_update (struct per_cpu_pages *pcp,unsigned long high,unsigned long batch) { -/* start with a fail safe value for batch */ - pcp->batch =1 ; -smp_wmb (); - -/* Update high, then batch, in order */ - pcp->high = high; -smp_wmb (); - - pcp->batch = batch; +WRITE_ONCE (pcp->batch, batch); +WRITE_ONCE (pcp->high, high); }static void pageset_init (struct per_cpu_pageset *p)
_
Andrew Morton
maintainerPATCH 127/200 mm, page_alloc: cache pageset high and batch in struct zone
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_alloc: cache pageset high and batch in struct zone
All per-cpu pagesets for a zone use the same high and batch values, that are duplicated there just for performance (locality) reasons. This patch adds the same variables also to struct zone as a shared copy.
This will be useful later for making possible to disable pcplists temporarily by setting high value to 0, while remembering the values for restoring them later. But we can also immediately benefit from not updating pagesets of all possible cpus in case the newly recalculated values (after sysctl change or memory online/offline) are actually unchanged from the previous ones.
---
include/linux/mmzone.h | 6 ++++++ mm/page_alloc.c | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-)
include/linux/mmzone.h renamed from include/linux/mmzone.h~mm-page_alloc-cache-pageset-high-and-batch-in-struct-zone +6 -0
@@ -470,6 +470,12 @@ struct zone {#endif struct pglist_data *zone_pgdat;struct per_cpu_pageset __percpu *pageset; +/* +* the high and batch values are copied to individual pagesets for +* faster access +*/ +int pageset_high; +int pageset_batch;#ifndef CONFIG_SPARSEMEM /*
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-cache-pageset-high-and-batch-in-struct-zone +14 -2
@@ -5920,6 +5920,9 @@ static void build_zonelists(pg_data_t *p* Other parts of the kernel may not check if the zone is available. */ static void pageset_init (struct per_cpu_pageset *p); +/* These effectively disable the pcplists in the boot pageset completely */ +#define BOOT_PAGESET_HIGH 0 +#define BOOT_PAGESET_BATCH 1 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset); static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
@@ -6309,8 +6312,8 @@ static void pageset_init(struct per_cpu_* need to be as careful as pageset_update() as nobody can access the * pageset yet. */ - pcp->high =0 ; - pcp->batch =1 ; + pcp->high =BOOT_PAGESET_HIGH ; + pcp->batch =BOOT_PAGESET_BATCH ; }/*
@@ -6334,6 +6337,13 @@ static void zone_set_pageset_high_and_ba new_batch =max (1UL ,1 * new_batch); } +if (zone->pageset_high == new_high && + zone->pageset_batch == new_batch) +return ; + + zone->pageset_high = new_high; + zone->pageset_batch = new_batch; +for_each_possible_cpu (cpu) { p =per_cpu_ptr (zone->pageset, cpu);pageset_update (&p->pcp, new_high, new_batch);
@@ -6394,6 +6404,8 @@ static __meminit void zone_pcp_init(stru* offset of a (static) per cpu variable into the per cpu area. */ zone->pageset = &boot_pageset; + zone->pageset_high =BOOT_PAGESET_HIGH ; + zone->pageset_batch =BOOT_PAGESET_BATCH ;if (populated_zone (zone)) printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
_
Andrew Morton
maintainerPATCH 128/200 mm, page_alloc: move draining pcplists to page isolation users
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_alloc: move draining pcplists to page isolation users
Currently, pcplists are drained during set_migratetype_isolate() which means once per pageblock processed start_isolate_page_range(). This is somewhat wasteful. Moreover, the callers might need different guarantees, and the draining is currently prone to races and does not guarantee that no page from isolated pageblock will end up on the pcplist after the drain.
Better guarantees are added by later patches and require explicit actions by page isolation users that need them. Thus it makes sense to move the current imperfect draining to the callers also as a preparation step.
---
mm/memory_hotplug.c | 11 ++++++----- mm/page_alloc.c | 2 ++ mm/page_isolation.c | 10 +++++----- 3 files changed, 13 insertions(+), 10 deletions(-)
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-page_alloc-move-draining-pcplists-to-page-isolation-users +6 -5
@@ -1500,6 +1500,8 @@ int __ref offline_pages(unsigned long st goto failed_removal; } +drain_all_pages (zone); + arg.start_pfn = start_pfn; arg.nr_pages = nr_pages;node_states_check_changes_offline (nr_pages, zone, &arg);
@@ -1550,11 +1552,10 @@ int __ref offline_pages(unsigned long st }/* -* per-cpu pages are drained in start_isolate_page_range, but if -* there are still pages that are not free, make sure that we -* drain again, because when we isolated range we might -* have raced with another thread that was adding pages to pcp -* list. +* per-cpu pages are drained after start_isolate_page_range, but +* if there are still pages that are not free, make sure that we +* drain again, because when we isolated range we might have +* raced with another thread that was adding pages to pcp list. * * Forward progress should be still guaranteed because * pages on the pcp list can only belong to MOVABLE_ZONE
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-move-draining-pcplists-to-page-isolation-users +2 -0
@@ -8528,6 +8528,8 @@ int alloc_contig_range(unsigned long staif (ret)return ret; +drain_all_pages (cc.zone); +/* * In case of -EBUSY, we'd like to know which page causes problem. * So, just fall through. test_pages_isolated() has a tracepoint
mm/page_isolation.c renamed from mm/page_isolation.c~mm-page_alloc-move-draining-pcplists-to-page-isolation-users +5 -5
@@ -49,7 +49,6 @@ static int set_migratetype_isolate(struc__mod_zone_freepage_state (zone, -nr_pages, mt);spin_unlock_irqrestore (&zone->lock, flags); -drain_all_pages (zone);return 0 ; }
@@ -172,11 +171,12 @@ __first_valid_page(unsigned long pfn, un* * Please note that there is no strong synchronization with the page allocator * either. Pages might be freed while their page blocks are marked ISOLATED. -* In some cases pages might still end up on pcp lists and that would allow +* A call to drain_all_pages() after isolation can flush most of them. However +* in some cases pages might still end up on pcp lists and that would allow * for their allocation even when they are in fact isolated already. Depending -* on how strong of a guarantee the caller needs drain_all_pages might be needed -* (e.g. __offline_pages will need to call it after check for isolated range for -* a next retry). +* on how strong of a guarantee the caller needs, further drain_all_pages() +* might be needed (e.g. __offline_pages will need to call it after check for +* isolated range for a next retry). * * Return: 0 on success and -EBUSY if any part of range cannot be isolated. */
_
Andrew Morton
maintainerPATCH 129/200 mm, page_alloc: disable pcplists during memory offline
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_alloc: disable pcplists during memory offline
Memory offlining relies on page isolation to guarantee a forward progress because pages cannot be reused while they are isolated. But the page isolation itself doesn't prevent from races while freed pages are stored on pcp lists and thus can be reused. This can be worked around by repeated draining of pcplists, as done by commit 968318261221 ("mm/memory_hotplug: drain per-cpu pages again during memory offline").
David and Michal would prefer that this race was closed in a way that callers of page isolation who need stronger guarantees don't need to repeatedly drain. David suggested disabling pcplists usage completely during page isolation, instead of repeatedly draining them.
To achieve this without adding special cases in alloc/free fastpath, we can use the same approach as boot pagesets - when pcp->high is 0, any pcplist addition will be immediately flushed.
The race can thus be closed by setting pcp->high to 0 and draining pcplists once, before calling start_isolate_page_range(). The draining will serialize after processes that already disabled interrupts and read the old value of pcp->high in free_unref_page_commit(), and processes that have not yet disabled interrupts, will observe pcp->high == 0 when they are rescheduled, and skip pcplists. This guarantees no stray pages on pcplists in zones where isolation happens.
This patch thus adds zone_pcp_disable() and zone_pcp_enable() functions that page isolation users can call before start_isolate_page_range() and after unisolating (or offlining) the isolated pages.
Also, drain_all_pages() is optimized to only execute on cpus where pcplists are not empty. The check can however race with a free to pcplist that has not yet increased the pcp->count from 0 to 1. Thus make the drain optionally skip the racy check and drain on all cpus, and use this option in zone_pcp_disable().
As we have to avoid external updates to high and batch while pcplists are disabled, we take pcp_batch_high_lock in zone_pcp_disable() and release it in zone_pcp_enable(). This also synchronizes multiple users of zone_pcp_disable()/enable().
Currently the only user of this functionality is offline_pages().
---
mm/internal.h | 2 + mm/memory_hotplug.c | 28 ++++++---------- mm/page_alloc.c | 73 +++++++++++++++++++++++++++++++++++------- mm/page_isolation.c | 6 +-- 4 files changed, 78 insertions(+), 31 deletions(-)
mm/internal.h renamed from mm/internal.h~mm-page_alloc-disable-pcplists-during-memory-offline +2 -0
@@ -204,6 +204,8 @@ extern void free_unref_page_list(structextern void zone_pcp_update (struct zone *zone);extern void zone_pcp_reset (struct zone *zone); +extern void zone_pcp_disable (struct zone *zone); +extern void zone_pcp_enable (struct zone *zone);#if definedCONFIG_COMPACTION || definedCONFIG_CMA
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-page_alloc-disable-pcplists-during-memory-offline +12 -16
@@ -1491,17 +1491,21 @@ int __ref offline_pages(unsigned long st } node =zone_to_nid (zone); +/* +* Disable pcplists so that page isolation cannot race with freeing +* in a way that pages from isolated pageblock are left on pcplists. +*/ +zone_pcp_disable (zone); +/* set above range as isolated */ ret =start_isolate_page_range (start_pfn, end_pfn,MIGRATE_MOVABLE ,MEMORY_OFFLINE |REPORT_FAILURE );if (ret) { reason ="failure to isolate range" ; - goto failed_removal; + goto failed_removal_pcplists_disabled; } -drain_all_pages (zone); - arg.start_pfn = start_pfn; arg.nr_pages = nr_pages;node_states_check_changes_offline (nr_pages, zone, &arg);
@@ -1551,20 +1555,8 @@ int __ref offline_pages(unsigned long st goto failed_removal_isolated; } -/* -* per-cpu pages are drained after start_isolate_page_range, but -* if there are still pages that are not free, make sure that we -* drain again, because when we isolated range we might have -* raced with another thread that was adding pages to pcp list. -* -* Forward progress should be still guaranteed because -* pages on the pcp list can only belong to MOVABLE_ZONE -* because has_unmovable_pages explicitly checks for -* PageBuddy on freed pages on other zones. -*/ ret =test_pages_isolated (start_pfn, end_pfn,MEMORY_OFFLINE ); -if (ret) -drain_all_pages (zone); + }while (ret);/* Mark all sections offline and remove free pages from the buddy. */
@@ -1580,6 +1572,8 @@ int __ref offline_pages(unsigned long st zone->nr_isolate_pageblock -= nr_pages / pageblock_nr_pages;spin_unlock_irqrestore (&zone->lock, flags); +zone_pcp_enable (zone); +/* removal success */ adjust_managed_page_count (pfn_to_page (start_pfn), -nr_pages); zone->present_pages -= nr_pages;
@@ -1612,6 +1606,8 @@ int __ref offline_pages(unsigned long st failed_removal_isolated:undo_isolate_page_range (start_pfn, end_pfn,MIGRATE_MOVABLE );memory_notify (MEM_CANCEL_OFFLINE , &arg); +failed_removal_pcplists_disabled: +zone_pcp_enable (zone); failed_removal: pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n", (unsigned long long) start_pfn << PAGE_SHIFT,
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-disable-pcplists-during-memory-offline +61 -12
117 lines not on this page · raw message
mm/page_isolation.c renamed from mm/page_isolation.c~mm-page_alloc-disable-pcplists-during-memory-offline +3 -3
@@ -174,9 +174,9 @@ __first_valid_page(unsigned long pfn, un* A call to drain_all_pages() after isolation can flush most of them. However * in some cases pages might still end up on pcp lists and that would allow * for their allocation even when they are in fact isolated already. Depending -* on how strong of a guarantee the caller needs, further drain_all_pages() -* might be needed (e.g. __offline_pages will need to call it after check for -* isolated range for a next retry). +* on how strong of a guarantee the caller needs, zone_pcp_disable/enable() +* might be used to flush and disable pcplist before isolation and enable after +* unisolation. * * Return: 0 on success and -EBUSY if any part of range cannot be isolated. */
_
Andrew Morton
maintainerPATCH 130/200 include/linux/page-flags.h: remove unused __[Set|Clear]PagePrivate
In reply to Andrew MortonFrom: Miaohe Lin <[email protected]>
Subject: include/linux/page-flags.h: remove unused __[Set|Clear]PagePrivate
They are not used anymore.
---
include/linux/page-flags.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
include/linux/page-flags.h renamed from include/linux/page-flags.h~page-flags-remove-unused-__pageprivate +1 -2
@@ -363,8 +363,7 @@ PAGEFLAG(SwapBacked, swapbacked, PF_NO_T* for its own purposes. * - PG_private and PG_private_2 cause releasepage() and co to be invoked */ -PAGEFLAG(Private, private, PF_ANY) __SETPAGEFLAG(Private, private, PF_ANY) - __CLEARPAGEFLAG(Private, private, PF_ANY) +PAGEFLAG(Private, private, PF_ANY) PAGEFLAG(Private2, private_2, PF_ANY) TESTSCFLAG(Private2, private_2, PF_ANY) PAGEFLAG(OwnerPriv1, owner_priv_1, PF_ANY)TESTCLEARFLAG (OwnerPriv1, owner_priv_1,PF_ANY )
_
Andrew Morton
maintainerPATCH 131/200 mm/page-flags: fix comment
In reply to Andrew MortonFrom: "Matthew Wilcox (Oracle)" <[email protected]>
Subject: mm/page-flags: fix comment
We haven't had 'dontuse' flags since 2002. Replace this obsolete warning with a hopefully more useful one.
---
include/linux/page-flags.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
include/linux/page-flags.h renamed from include/linux/page-flags.h~mm-page-flags-fix-comment +1 -2
@@ -86,8 +86,7 @@*/ /* -* Don't use the *_dontuse flags. Use the macros. Otherwise you'll break -* locked- and dirty-page accounting. +* Don't use the pageflags directly. Use the PageFoo macros. * * The page flags field is split into two parts, the main flags area * which extends from the low bits upwards, and the fields area which
_
Andrew Morton
maintainerPATCH 132/200 mm/page_alloc: add __free_pages() documentation
In reply to Andrew MortonFrom: "Matthew Wilcox (Oracle)" <[email protected]>
Subject: mm/page_alloc: add __free_pages() documentation
Provide some guidance towards when this might not be the right interface to use.
---
mm/page_alloc.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-add-__free_pages-documentation +20 -0
@@ -5043,6 +5043,26 @@ static inline void free_the_page(struct__free_pages_ok (page, order,FPI_NONE ); } +/** +* __free_pages - Free pages allocated with alloc_pages(). +* @page: The page pointer returned from alloc_pages(). +* @order: The order of the allocation. +* +* This function can free multi-page allocations that are not compound +* pages. It does not check that the @order passed in matches that of +* the allocation, so it is easy to leak memory. Freeing more memory +* than was allocated will probably emit a warning. +* +* If the last reference to this page is speculative, it will be released +* by put_page() which only frees the first page of a non-compound +* allocation. To prevent the remaining pages from being leaked, we free +* the subsequent pages here. If you want to use the page's reference +* count to decide when to free the allocation, you should allocate a +* compound page, and use put_page() instead of __free_pages(). +* +* Context: May be called in interrupt context or while holding a normal +* spinlock, but not in NMI context or while holding a raw spinlock. +*/ void __free_pages (struct page *page,unsigned int order) {if (put_page_testzero (page))
_
Andrew Morton
maintainerPATCH 133/200 mm/page_alloc: mark some symbols with static keyword
In reply to Andrew MortonFrom: Zou Wei <[email protected]>
Subject: mm/page_alloc: mark some symbols with static keyword
Fix the following sparse warnings:
mm/page_alloc.c:3040:6: warning: symbol '__drain_all_pages' was not declared. Should it be static? mm/page_alloc.c:6349:6: warning: symbol '__zone_set_pageset_high_and_batch' was not declared. Should it be static?
---
mm/page_alloc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-mark-some-symbols-with-static-keyword +2 -2
@@ -3035,7 +3035,7 @@ static void drain_local_pages_wq(struct* that need the guarantee that every CPU has drained can disable the * optimizing racy check. */ -void __drain_all_pages (struct zone *zone,bool force_all_cpus) +static void __drain_all_pages (struct zone *zone,bool force_all_cpus) {int cpu;
@@ -6357,7 +6357,7 @@ static void pageset_init(struct per_cpu_ pcp->batch =BOOT_PAGESET_BATCH ; } -void __zone_set_pageset_high_and_batch (struct zone *zone,unsigned long high, +static void __zone_set_pageset_high_and_batch (struct zone *zone,unsigned long high,unsigned long batch) {struct per_cpu_pageset *p;
_
Andrew Morton
maintainerPATCH 134/200 mm/page_alloc: clear all pages in post_alloc_hook() with init_on_alloc=1
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm/page_alloc: clear all pages in post_alloc_hook() with init_on_alloc=1
commit 6471384af2a6 ("mm: security: introduce init_on_alloc=1 and init_on_free=1 boot options") resulted with init_on_alloc=1 in all pages leaving the buddy via alloc_pages() and friends to be initialized/cleared/zeroed on allocation.
However, the same logic is currently not applied to alloc_contig_pages():
allocated pages leaving the buddy aren't cleared with init_on_alloc=1 and init_on_free=0. Let's also properly clear pages on that allocation path.
To achieve that, let's move clearing into post_alloc_hook(). This will not only affect alloc_contig_pages() allocations but also any pages used as migration target in compaction code via compaction_alloc().
While this sounds sub-optimal, it's the very same handling as when allocating migration targets via alloc_migration_target() - pages will get properly cleared with init_on_free=1. In case we ever want to optimize migration in that regard, we should tackle all such migration users - if we believe migration code can be fully trusted.
With this change, we will see double clearing of pages in some cases. One example are gigantic pages (either allocated via CMA, or allocated dynamically via alloc_contig_pages()) - which is the right thing to do (and to be optimized outside of the buddy in the callers) as discussed in:
https://lkml.kernel.org/r/[email protected]
This change implies that with init_on_alloc=1
- All CMA allocations will be cleared
- Gigantic pages allocated via alloc_contig_pages() will be cleared
- virtio-mem memory to be unplugged will be cleared. While this is suboptimal, it's similar to memory balloon drivers handling, where all pages to be inflated will get cleared as well.
- Pages isolated for compaction will be cleared
---
mm/page_alloc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-clear-all-pages-in-post_alloc_hook-with-init_on_alloc=1 +3 -3
@@ -2284,6 +2284,9 @@ inline void post_alloc_hook(struct pagekasan_alloc_pages (page, order);kernel_poison_pages (page,1 << order,1 );set_page_owner (page, order, gfp_flags); + +if (!free_pages_prezeroed () &&want_init_on_alloc (gfp_flags)) +kernel_init_free_pages (page,1 << order); } static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
@@ -2291,9 +2294,6 @@ static void prep_new_page(struct page *p {post_alloc_hook (page, order, gfp_flags); -if (!free_pages_prezeroed () &&want_init_on_alloc (gfp_flags)) -kernel_init_free_pages (page,1 << order); -if (order && (gfp_flags & __GFP_COMP))prep_compound_page (page, order);
_
Andrew Morton
maintainerPATCH 135/200 init/main: fix broken buffer_init when DEFERRED_STRUCT_PAGE_INIT set
In reply to Andrew MortonFrom: Lin Feng <[email protected]>
Subject: init/main: fix broken buffer_init when DEFERRED_STRUCT_PAGE_INIT set
In the booting phase if CONFIG_DEFERRED_STRUCT_PAGE_INIT is set, we have following callchain:
start_kernel
...
mm_init
mem_init
memblock_free_all
reset_all_zones_managed_pages
free_low_memory_core_early
...
buffer_init
nr_free_buffer_pages
zone->managed_pages
...
rest_init
kernel_init
kernel_init_freeable
page_alloc_init_late
kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
wait_for_completion(&pgdat_init_all_done_comp);
...
files_maxfiles_initIt's clear that buffer_init depends on zone->managed_pages, but it's reset in reset_all_zones_managed_pages after that pages are readded into zone->managed_pages, but when buffer_init runs this process is half done and most of them will finally be added till deferred_init_memmap done. In large memory couting of nr_free_buffer_pages drifts too much, also drifting from kernels to kernels on same hardware.
Fix is simple, it delays buffer_init run till deferred_init_memmap all done.
But as corrected by this patch, max_buffer_heads becomes very large, the value is roughly as many as 4 times of totalram_pages, formula:max_buffer_heads = nrpages * (10%) * (PAGE_SIZE / sizeof(struct buffer_head));
Say in a 64GB memory box we have 16777216 pages, then max_buffer_heads turns out to be roughly 67,108,864. In common cases, should a buffer_head be mapped to one page/block(4KB)? So max_buffer_heads never exceeds totalram_pages. IMO it's likely to make buffer_heads_over_limit bool value alwasy false, then make codes 'if (buffer_heads_over_limit)' test in vmscan unnecessary.
So this patch will change the original behavior related to buffer_heads_over_limit in vmscan since we used a half done value of zone->managed_pages before, or should we use a smaller factor(<10%) in previous formula.
akpm: I think this is OK - the max_buffer_heads code is only needed on highmem machines, to prevent ZONE_NORMAL from being consumed by large amounts of buffer_heads attached to highmem pagecache. This problem will not occur on 64-bit machines, so this feature's non-functionality on such machines is a feature, not a bug.
---
init/main.c | 2 -- mm/page_alloc.c | 3 +++ 2 files changed, 3 insertions(+), 2 deletions(-)
init/main.c renamed from init/main.c~init-main-fix-broken-buffer_init-when-deferred_struct_page_init-set +0 -2
@@ -58,7 +58,6 @@#include <linux/rmap.h> #include <linux/mempolicy.h> #include <linux/key.h> -#include <linux/buffer_head.h> #include <linux/page_ext.h> #include <linux/debug_locks.h> #include <linux/debugobjects.h>
@@ -1036,7 +1035,6 @@ asmlinkage __visible void __init __no_safork_init ();proc_caches_init ();uts_ns_init (); -buffer_init ();key_init ();security_init ();dbg_late_init ();
mm/page_alloc.c renamed from mm/page_alloc.c~init-main-fix-broken-buffer_init-when-deferred_struct_page_init-set +3 -0
@@ -71,6 +71,7 @@#include <linux/psi.h> #include <linux/padata.h> #include <linux/khugepaged.h> +#include <linux/buffer_head.h> #include <asm/sections.h> #include <asm/tlbflush.h>
@@ -2113,6 +2114,8 @@ void __init page_alloc_init_late(void)files_maxfiles_init ();#endif +buffer_init (); +/* Discard memblock private memory */ memblock_discard ();
_
Andrew Morton
maintainerPATCH 136/200 mm: page_alloc: refactor setup_per_zone_lowmem_reserve()
In reply to Andrew MortonFrom: Lorenzo Stoakes <[email protected]>
Subject: mm: page_alloc: refactor setup_per_zone_lowmem_reserve()
setup_per_zone_lowmem_reserve() iterates through each zone setting zone->lowmem_reserve[j] = 0 (where j is the zone's index) then iterates backwards through all preceding zones, setting lower_zone->lowmem_reserve[j] = sum(managed pages of higher zones) / lowmem_reserve_ratio[idx] for each (where idx is the lower zone's index).
If the lower zone has no managed pages or its ratio is 0 then all of its lowmem_reserve[] entries are effectively zeroed.
As these arrays are only assigned here and all lowmem_reserve[] entries for index < this zone's index are implicitly assumed to be 0 (as these are specifically output in show_free_areas() and zoneinfo_show_print() for example) there is no need to additionally zero index == this zone's index too. This patch avoids zeroing unnecessarily.
Rather than iterating through zones and setting lowmem_reserve[j] for each lower zone this patch reverse the process and populates each zone's lowmem_reserve[] values in ascending order.
This clarifies what is going on especially in the case of zero managed pages or ratio which is now explicitly shown to clear these values.
---
mm/page_alloc.c | 33 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 20 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-refactor-setup_per_zone_lowmem_reserve +13 -20
@@ -7862,31 +7862,24 @@ static void calculate_totalreserve_pagesstatic void setup_per_zone_lowmem_reserve (void ) {struct pglist_data *pgdat; -enum zone_type j, idx; +enum zone_type i, j;for_each_online_pgdat (pgdat) { -for (j =0 ; j <MAX_NR_ZONES ; j++) { -struct zone *zone = pgdat->node_zones + j; -unsigned long managed_pages =zone_managed_pages (zone); +for (i =0 ; i <MAX_NR_ZONES -1 ; i++) { +struct zone *zone = &pgdat->node_zones[i]; +int ratio = sysctl_lowmem_reserve_ratio[i]; +bool clear = !ratio || !zone_managed_pages (zone); +unsigned long managed_pages =0 ; - zone->lowmem_reserve[j] =0 ; - - idx = j; -while (idx) { -struct zone *lower_zone; - - idx--; - lower_zone = pgdat->node_zones + idx; - -if (!sysctl_lowmem_reserve_ratio[idx] || - !zone_managed_pages (lower_zone)) { - lower_zone->lowmem_reserve[j] =0 ; -continue ; +for (j = i +1 ; j <MAX_NR_ZONES ; j++) { +if (clear) { + zone->lowmem_reserve[j] =0 ; }else { - lower_zone->lowmem_reserve[j] = - managed_pages / sysctl_lowmem_reserve_ratio[idx]; +struct zone *upper_zone = &pgdat->node_zones[j]; + + managed_pages +=zone_managed_pages (upper_zone); + zone->lowmem_reserve[j] = managed_pages / ratio; } - managed_pages +=zone_managed_pages (lower_zone); } } }
_
Andrew Morton
maintainerPATCH 137/200 mm/page_alloc: speed up the iteration of max_order
In reply to Andrew MortonFrom: Muchun Song <[email protected]>
Subject: mm/page_alloc: speed up the iteration of max_order
When we free a page whose order is very close to MAX_ORDER and greater than pageblock_order, it wastes some CPU cycles to increase max_order to MAX_ORDER one by one and check the pageblock migratetype of that page repeatedly especially when MAX_ORDER is much larger than pageblock_order.
We also should not be checking migratetype of buddy when "order == MAX_ORDER - 1" as the buddy pfn may be invalid, so adjust the condition. With the new check, we don't need the max_order check anymore, so we replace it.
Also adjust max_order initialization so that it's lower by one than previously, which makes the code hopefully more clear.
---
mm/page_alloc.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-speeding-up-the-iteration-of-max_order +4 -4
@@ -996,7 +996,7 @@ static inline void __free_one_page(strucstruct page *buddy;bool to_tail; - max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1); + max_order = min_t(unsigned int, MAX_ORDER - 1, pageblock_order);VM_BUG_ON (!zone_is_initialized (zone));VM_BUG_ON_PAGE (page->flags &PAGE_FLAGS_CHECK_AT_PREP , page);
@@ -1009,7 +1009,7 @@ static inline void __free_one_page(strucVM_BUG_ON_PAGE (bad_range (zone, page), page); continue_merging: -while (order < max_order -1 ) { +while (order < max_order) {if (compaction_capture (capc, page, order, migratetype)) {__mod_zone_freepage_state (zone, -(1 << order), migratetype);
@@ -1035,7 +1035,7 @@ continue_merging: pfn = combined_pfn; order++; } -if (max_order <MAX_ORDER ) { +if (order <MAX_ORDER -1 ) {/* If we are here, it means order is >= pageblock_order. * We want to prevent merge between freepages on isolate * pageblock and normal pageblock. Without this, pageblock
@@ -1056,7 +1056,7 @@ continue_merging: is_migrate_isolate(buddy_mt))) goto done_merging; } - max_order++; + max_order = order +1 ; goto continue_merging; }
_
Andrew Morton
maintainerPATCH 138/200 mm,hwpoison: drain pcplists before bailing out for non-buddy zero-refcount page
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,hwpoison: drain pcplists before bailing out for non-buddy zero-refcount page
Patch series "HWpoison: further fixes and cleanups", v5.
This patchset includes some more fixes and a cleanup.
Patch#2 and patch#3 are both fixes for taking a HWpoison page off a buddy freelist, since having them there has proved to be bad (see [1] and pathch#2's commit log). Patch#3 does the same for hugetlb pages.
[1] https://lkml.org/lkml/2020/9/22/565
This patch (of 4):
A page with 0-refcount and !PageBuddy could perfectly be a pcppage. Currently, we bail out with an error if we encounter such a page, meaning that we do not handle pcppages neither from hard-offline nor from soft-offline path.
Fix this by draining pcplists whenever we find this kind of page and retry the check again. It might be that pcplists have been spilled into the buddy allocator and so we can handle it.
---
mm/memory-failure.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-)
mm/memory-failure.c renamed from mm/memory-failure.c~mmhwpoison-drain-pcplists-before-bailing-out-for-non-buddy-zero-refcount-page +22 -2
@@ -946,13 +946,13 @@ static int page_action(struct page_state }/** -* get_hwpoison_page() - Get refcount for memory error handling: +* __get_hwpoison_page() - Get refcount for memory error handling: * @page: raw error page (hit by memory error) * * Return: return 0 if failed to grab the refcount, otherwise true (some * non-zero value.) */ -static int get_hwpoison_page (struct page *page) +static int __get_hwpoison_page (struct page *page) {struct page *head =compound_head (page);
@@ -982,6 +982,26 @@ static int get_hwpoison_page(struct pagereturn 0 ; } +static int get_hwpoison_page (struct page *p) +{ +int ret; +bool drained = false; + +retry: + ret =__get_hwpoison_page (p); +if (!ret && !is_free_buddy_page (p) && !page_count (p) && !drained) { +/* +* The page might be in a pcplist, so try to drain those +* and see if we are lucky. +*/ +drain_all_pages (page_zone (p)); + drained = true; + goto retry; + } + +return ret; +} +/* * Do all that is necessary to remove user space mappings. Unmap * the pages and send SIGBUS to the processes if the data was dirty.
_
Andrew Morton
maintainerPATCH 139/200 mm,hwpoison: take free pages off the buddy freelists
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,hwpoison: take free pages off the buddy freelists
The crux of the matter is that historically we left poisoned pages in the buddy system because we have some checks in place when allocating a page that are gatekeeper for poisoned pages. Unfortunately, we do have other users (e.g: compaction [1]) that scan buddy freelists and try to get a page from there without checking whether the page is HWPoison.
As I stated already, I think it is fundamentally wrong to keep HWPoison pages within the buddy systems, checks in place or not.
Let us fix this the same way we did for soft_offline [2], taking the page off the buddy freelist so it is completely unreachable.
Note that this is fairly simple to trigger, as we only need to poison free buddy pages (madvise MADV_HWPOISON) and then run some sort of memory stress system.
Just for a matter of reference, I put a dump_page() in compaction_alloc() to trigger for HWPoison patches:
kernel: page:0000000012b2982b refcount:1 mapcount:0 mapping:0000000000000000 index:0x1 pfn:0x1d5db
kernel: flags: 0xfffffc0800000(hwpoison)
kernel: raw: 000fffffc0800000 ffffea00007573c8 ffffc90000857de0 0000000000000000
kernel: raw: 0000000000000001 0000000000000000 00000001ffffffff 0000000000000000
kernel: page dumped because: compaction_alloc
kernel: CPU: 4 PID: 123 Comm: kcompactd0 Tainted: G E 5.9.0-rc2-mm1-1-default+ #5 kernel: Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.10.2-0-g5f4c7b1-prebuilt.qemu-project.org 04/01/2014 kernel: Call Trace: kernel: dump_stack+0x6d/0x8b kernel: compaction_alloc+0xb2/0xc0 kernel: migrate_pages+0x2a6/0x12a0 kernel: ? isolate_freepages+0xc80/0xc80 kernel: ? __ClearPageMovable+0xb0/0xb0 kernel: compact_zone+0x5eb/0x11c0 kernel: ? finish_task_switch+0x74/0x300 kernel: ? lock_timer_base+0xa8/0x170 kernel: proactive_compact_node+0x89/0xf0 kernel: ? kcompactd+0x2d0/0x3a0 kernel: kcompactd+0x2d0/0x3a0 kernel: ? finish_wait+0x80/0x80 kernel: ? kcompactd_do_work+0x350/0x350 kernel: kthread+0x118/0x130 kernel: ? kthread_associate_blkcg+0xa0/0xa0 kernel: ret_from_fork+0x22/0x30
After that, if e.g: a process faults in the page, it will get killed unexpectedly.
Fix it by containing the page immediatelly.
Besides that, two more changes can be noticed:
* MF_DELAYED no longer suits as we are fixing the issue by containing the page immediately, so it does no longer rely on the allocation-time checks to stop HWPoison to be handed over.
gain unless it is unpoisoned, so we fixed the situation. Because of that, let us use MF_RECOVERED from now on.
* The second block that handles PageBuddy pages is no longer needed:
We call shake_page and then check whether the page is Buddy because shake_page calls drain_all_pages, which sends pcp-pages back to the buddy freelists, so we could have a chance to handle free pages. Currently, get_hwpoison_page already calls drain_all_pages, and we call get_hwpoison_page right before coming here, so we should be on the safe side.
[1] https://lore.kernel.org/linux-mm/20190826104144.GA7849@linux/T/#u
[2] https://patchwork.kernel.org/cover/11792607/
---
mm/memory-failure.c | 46 +++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 16 deletions(-)
mm/memory-failure.c renamed from mm/memory-failure.c~mmhwpoison-take-free-pages-off-the-buddy-freelists +30 -16
@@ -809,7 +809,7 @@ static int me_swapcache_clean(struct pag*/ static int me_huge_page (struct page *p,unsigned long pfn) { -int res =0 ; +int res;struct page *hpage =compound_head (p);struct address_space *mapping;
@@ -820,6 +820,7 @@ static int me_huge_page(struct page *p,if (mapping) { res =truncate_error_page (hpage, pfn, mapping); }else { + res =MF_FAILED ;unlock_page (hpage);/* * migration entry prevents later access on error anonymous
@@ -828,8 +829,10 @@ static int me_huge_page(struct page *p,*/ if (PageAnon (hpage))put_page (hpage); -dissolve_free_huge_page (p); - res =MF_RECOVERED ; +if (!dissolve_free_huge_page (p) &&take_page_off_buddy (p)) { +page_ref_inc (p); + res =MF_RECOVERED ; + }lock_page (hpage); }
@@ -1196,9 +1199,13 @@ static int memory_failure_hugetlb(unsign } }unlock_page (head); -dissolve_free_huge_page (p); -action_result (pfn,MF_MSG_FREE_HUGE ,MF_DELAYED ); -return 0 ; + res =MF_FAILED ; +if (!dissolve_free_huge_page (p) &&take_page_off_buddy (p)) { +page_ref_inc (p); + res =MF_RECOVERED ; + } +action_result (pfn,MF_MSG_FREE_HUGE , res); +return res ==MF_RECOVERED ?0 : -EBUSY ; }lock_page (head);
@@ -1339,6 +1346,7 @@ int memory_failure(unsigned long pfn, instruct dev_pagemap *pgmap;int res;unsigned long page_flags; +bool retry = true;if (!sysctl_memory_failure_recovery)panic ("Memory failure on page %lx" , pfn);
@@ -1356,6 +1364,7 @@ int memory_failure(unsigned long pfn, inreturn -ENXIO ; } +try_again:if (PageHuge (p))return memory_failure_hugetlb (pfn, flags);if (TestSetPageHWPoison (p)) {
@@ -1380,8 +1389,21 @@ int memory_failure(unsigned long pfn, in*/ if (!(flags &MF_COUNT_INCREASED ) && !get_hwpoison_page (p)) {if (is_free_buddy_page (p)) { -action_result (pfn,MF_MSG_BUDDY ,MF_DELAYED ); -return 0 ; +if (take_page_off_buddy (p)) { +page_ref_inc (p); + res =MF_RECOVERED ; + }else { +/* We lost the race, try again */ +if (retry) { +ClearPageHWPoison (p); +num_poisoned_pages_dec (); + retry = false; + goto try_again; + } + res =MF_FAILED ; + } +action_result (pfn,MF_MSG_BUDDY , res); +return res ==MF_RECOVERED ?0 : -EBUSY ; }else {action_result (pfn,MF_MSG_KERNEL_HIGH_ORDER ,MF_IGNORED );return -EBUSY ;
@@ -1405,14 +1427,6 @@ int memory_failure(unsigned long pfn, in* walked by the page reclaim code, however that's not a big loss. */ shake_page (p,0 ); -/* shake_page could have turned it free. */ -if (!PageLRU (p) &&is_free_buddy_page (p)) { -if (flags &MF_COUNT_INCREASED ) -action_result (pfn,MF_MSG_BUDDY ,MF_DELAYED ); -else -action_result (pfn,MF_MSG_BUDDY_2ND ,MF_DELAYED ); -return 0 ; - }lock_page (p);
_
Andrew Morton
maintainerPATCH 140/200 mm,hwpoison: drop unneeded pcplist draining
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,hwpoison: drop unneeded pcplist draining
memory_failure and soft_offline_path paths now drain pcplists by calling get_hwpoison_page.
memory_failure flags the page as HWPoison before, so that page cannot longer go into a pcplist, and soft_offline_page only flags a page as HWPoison if 1) we took the page off a buddy freelist 2) the page was in-use and we migrated it 3) was a clean pagecache.
Because of that, a page cannot longer be poisoned and be in a pcplist.
---
mm/madvise.c | 5 ----- 1 file changed, 5 deletions(-)
mm/madvise.c renamed from mm/madvise.c~mmhwpoison-drop-unneeded-pcplist-draining +0 -5
@@ -877,7 +877,6 @@ static long madvise_remove(struct vm_arestatic int madvise_inject_error (int behavior,unsigned long start,unsigned long end) { -struct zone *zone;unsigned long size;if (!capable (CAP_SYS_ADMIN ))
@@ -922,10 +921,6 @@ static int madvise_inject_error(int beha return ret; } -/* Ensure that all poisoned pages are removed from per-cpu lists */ -for_each_populated_zone (zone) -drain_all_pages (zone); -return 0 ; }#endif
_
Andrew Morton
maintainerPATCH 141/200 mm,hwpoison: refactor get_any_page
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,hwpoison: refactor get_any_page
Patch series "HWPoison: Refactor get page interface", v2.
This patch (of 3):
When we want to grab a refcount via get_any_page, we call __get_any_page that calls get_hwpoison_page to get the actual refcount.
get_any_page() is only there because we have a sort of retry mechanism in case the page we met is unknown to us or if we raced with an allocation.
Also __get_any_page() prints some messages about the page type in case the page was a free page or the page type was unknown, but if anything, we only need to print a message in case the pagetype was unknown, as that is reporting an error down the chain.
Let us merge get_any_page() and __get_any_page(), and let the message be printed in soft_offline_page. While we are it, we can also remove the 'pfn' parameter as it is no longer used.
---
mm/memory-failure.c | 99 +++++++++++++++++------------------------- 1 file changed, 42 insertions(+), 57 deletions(-)
mm/memory-failure.c renamed from mm/memory-failure.c~mmhwpoison-refactor-get_any_page +42 -57
@@ -1707,70 +1707,51 @@ EXPORT_SYMBOL(unpoison_memory);/* * Safely get reference count of an arbitrary page. -* Returns 0 for a free page, -EIO for a zero refcount page -* that is not free, and 1 for any other page type. -* For 1 the page is returned with increased page count, otherwise not. +* Returns 0 for a free page, 1 for an in-use page, -EIO for a page-type we +* cannot handle and -EBUSY if we raced with an allocation. +* We only incremented refcount in case the page was already in-use and it is +* a known type we can handle. */ -static int __get_any_page (struct page *p,unsigned long pfn,int flags) +static int get_any_page (struct page *p,int flags) { -int ret; +int ret =0 , pass =0 ; +bool count_increased = false;if (flags &MF_COUNT_INCREASED ) -return 1 ; + count_increased = true; -/* -* When the target page is a free hugepage, just remove it -* from free hugepage list. -*/ -if (!get_hwpoison_page (p)) { -if (PageHuge (p)) { -pr_info ("%s: %#lx free huge page\n" , __func__, pfn); - ret =0 ; - }else if (is_free_buddy_page (p)) { -pr_info ("%s: %#lx free buddy page\n" , __func__, pfn); - ret =0 ; - }else if (page_count (p)) { -/* raced with allocation */ +try_again: +if (!count_increased && !get_hwpoison_page (p)) { +if (page_count (p)) { +/* We raced with an allocation, retry. */ +if (pass++ <3 ) + goto try_again; ret = -EBUSY ; - }else { -pr_info ("%s: %#lx: unknown zero refcount page type %lx\n" , - __func__, pfn, p->flags); + }else if (!PageHuge (p) && !is_free_buddy_page (p)) { +/* We raced with put_page, retry. */ +if (pass++ <3 ) + goto try_again; ret = -EIO ; } }else { -/* Not a free page */ - ret =1 ; - } -return ret; -} - -static int get_any_page (struct page *page,unsigned long pfn,int flags) -{ -int ret =__get_any_page (page, pfn, flags); - -if (ret == -EBUSY ) - ret =__get_any_page (page, pfn, flags); - -if (ret ==1 && !PageHuge (page) && - !PageLRU (page) && !__PageMovable (page)) { -/* -* Try to free it. -*/ -put_page (page); -shake_page (page,1 ); - -/* -* Did it turn free? -*/ - ret =__get_any_page (page, pfn,0 ); -if (ret ==1 && !PageLRU (page)) { -/* Drop page reference which is from __get_any_page() */ -put_page (page); -pr_info ("soft_offline: %#lx: unknown non LRU page type %lx (%pGp)\n" , - pfn, page->flags, &page->flags); -return -EIO ; +if (PageHuge (p) ||PageLRU (p) ||__PageMovable (p)) { + ret =1 ; + }else { +/* +* A page we cannot handle. Check whether we can turn +* it into something we can handle. +*/ +if (pass++ <3 ) { +put_page (p); +shake_page (p,1 ); + count_increased = false; + goto try_again; + } +put_page (p); + ret = -EIO ; } } +return ret; }
@@ -1939,7 +1920,7 @@ int soft_offline_page(unsigned long pfn,return -EIO ;if (PageHWPoison (page)) { -pr_info ("soft offline: %#lx page already poisoned\n" , pfn); +pr_info ("%s: %#lx page already poisoned\n" , __func__, pfn);if (flags &MF_COUNT_INCREASED )put_page (page);return 0 ;
@@ -1947,16 +1928,20 @@ int soft_offline_page(unsigned long pfn, retry:get_online_mems (); - ret =get_any_page (page, pfn, flags); + ret =get_any_page (page, flags);put_online_mems (); -if (ret >0 ) +if (ret >0 ) { ret =soft_offline_in_use_page (page); -else if (ret ==0 ) + }else if (ret ==0 ) {if (soft_offline_free_page (page) && try_again) { try_again = false; goto retry; } + }else if (ret == -EIO ) { +pr_info ("%s: %#lx: unknown page type: %lx (%pGP)\n" , + __func__, pfn, page->flags, &page->flags); + }return ret; }
_
Andrew Morton
maintainerPATCH 142/200 mm,hwpoison: disable pcplists before grabbing a refcount
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,hwpoison: disable pcplists before grabbing a refcount
Currently, we have a sort of retry mechanism to make sure pages in pcp-lists are spilled to the buddy system, so we can handle those.
We can save us this extra checks with the new disable-pcplist mechanism that is available with [1].
zone_pcplist_disable makes sure to 1) disable pcplists, so any page that is freed up from that point onwards will end up in the buddy system and 2) drain pcplists, so those pages that already in pcplists are spilled to buddy.
With that, we can make a common entry point for grabbing a refcount from both soft_offline and memory_failure paths that is guarded by zone_pcplist_disable/zone_pcplist_enable.
[1] https://patchwork.kernel.org/project/linux-mm/cover/[email protected]/
---
mm/memory-failure.c | 132 ++++++++++++++++++++---------------------- 1 file changed, 65 insertions(+), 67 deletions(-)
mm/memory-failure.c renamed from mm/memory-failure.c~mmhwpoison-disable-pcplists-before-grabbing-a-refcount +65 -67
@@ -985,26 +985,73 @@ static int __get_hwpoison_page(struct pareturn 0 ; } -static int get_hwpoison_page (struct page *p) +/* +* Safely get reference count of an arbitrary page. +* +* Returns 0 for a free page, 1 for an in-use page, +* -EIO for a page-type we cannot handle and -EBUSY if we raced with an +* allocation. +* We only incremented refcount in case the page was already in-use and it +* is a known type we can handle. +*/ +static int get_any_page (struct page *p,unsigned long flags) { -int ret; -bool drained = false; +int ret =0 , pass =0 ; +bool count_increased = false; -retry: - ret =__get_hwpoison_page (p); -if (!ret && !is_free_buddy_page (p) && !page_count (p) && !drained) { -/* -* The page might be in a pcplist, so try to drain those -* and see if we are lucky. -*/ -drain_all_pages (page_zone (p)); - drained = true; - goto retry; +if (flags &MF_COUNT_INCREASED ) + count_increased = true; + +try_again: +if (!count_increased && !__get_hwpoison_page (p)) { +if (page_count (p)) { +/* We raced with an allocation, retry. */ +if (pass++ <3 ) + goto try_again; + ret = -EBUSY ; + }else if (!PageHuge (p) && !is_free_buddy_page (p)) { +/* We raced with put_page, retry. */ +if (pass++ <3 ) + goto try_again; + ret = -EIO ; + } + }else { +if (PageHuge (p) ||PageLRU (p) ||__PageMovable (p)) { + ret =1 ; + }else { +/* +* A page we cannot handle. Check whether we can turn +* it into something we can handle. +*/ +if (pass++ <3 ) { +put_page (p); +shake_page (p,1 ); + count_increased = false; + goto try_again; + } +put_page (p); + ret = -EIO ; + } }return ret; } +static int get_hwpoison_page (struct page *p,unsigned long flags, +enum mf_flags ctxt) +{ +int ret; + +zone_pcp_disable (page_zone (p)); +if (ctxt ==MF_SOFT_OFFLINE ) + ret =get_any_page (p, flags); +else + ret =__get_hwpoison_page (p); +zone_pcp_enable (page_zone (p)); + +return ret; +} +/* * Do all that is necessary to remove user space mappings. Unmap * the pages and send SIGBUS to the processes if the data was dirty.
@@ -1185,7 +1232,7 @@ static int memory_failure_hugetlb(unsignnum_poisoned_pages_inc (); -if (!(flags &MF_COUNT_INCREASED ) && !get_hwpoison_page (p)) { +if (!(flags &MF_COUNT_INCREASED ) && !get_hwpoison_page (p, flags,0 )) {/* * Check "filter hit" and "race with other subpage." */
@@ -1387,7 +1434,7 @@ try_again:* In fact it's dangerous to directly bump up page count from 0, * that may make page_ref_freeze()/page_ref_unfreeze() mismatch. */ -if (!(flags &MF_COUNT_INCREASED ) && !get_hwpoison_page (p)) { +if (!(flags &MF_COUNT_INCREASED ) && !get_hwpoison_page (p, flags,0 )) {if (is_free_buddy_page (p)) {if (take_page_off_buddy (p)) {page_ref_inc (p);
@@ -1630,6 +1677,7 @@ int unpoison_memory(unsigned long pfn)struct page *page;struct page *p;int freeit =0 ; +unsigned long flags =0 ; static DEFINE_RATELIMIT_STATE(unpoison_rs, DEFAULT_RATELIMIT_INTERVAL, DEFAULT_RATELIMIT_BURST);
@@ -1674,7 +1722,7 @@ int unpoison_memory(unsigned long pfn)return 0 ; } -if (!get_hwpoison_page (p)) { +if (!get_hwpoison_page (p, flags,0 )) {if (TestClearPageHWPoison (p))num_poisoned_pages_dec (); unpoison_pr_info("Unpoison: Software-unpoisoned free page %#lx\n",
@@ -1705,56 +1753,6 @@ int unpoison_memory(unsigned long pfn) }EXPORT_SYMBOL (unpoison_memory); -/* -* Safely get reference count of an arbitrary page. -* Returns 0 for a free page, 1 for an in-use page, -EIO for a page-type we -* cannot handle and -EBUSY if we raced with an allocation. -* We only incremented refcount in case the page was already in-use and it is -* a known type we can handle. -*/ -static int get_any_page (struct page *p,int flags) -{ -int ret =0 , pass =0 ; -bool count_increased = false; - -if (flags &MF_COUNT_INCREASED ) - count_increased = true; - -try_again: -if (!count_increased && !get_hwpoison_page (p)) { -if (page_count (p)) { -/* We raced with an allocation, retry. */ -if (pass++ <3 ) - goto try_again; - ret = -EBUSY ; - }else if (!PageHuge (p) && !is_free_buddy_page (p)) { -/* We raced with put_page, retry. */ -if (pass++ <3 ) - goto try_again; - ret = -EIO ; - } - }else { -if (PageHuge (p) ||PageLRU (p) ||__PageMovable (p)) { - ret =1 ; - }else { -/* -* A page we cannot handle. Check whether we can turn -* it into something we can handle. -*/ -if (pass++ <3 ) { -put_page (p); -shake_page (p,1 ); - count_increased = false; - goto try_again; - } -put_page (p); - ret = -EIO ; - } - } - -return ret; -} -static bool isolate_page (struct page *page,struct list_head *pagelist) {bool isolated = false;
@@ -1928,7 +1926,7 @@ int soft_offline_page(unsigned long pfn, retry:get_online_mems (); - ret =get_any_page (page, flags); + ret =get_hwpoison_page (page, flags,MF_SOFT_OFFLINE );put_online_mems ();if (ret >0 ) {
_
Andrew Morton
maintainerPATCH 143/200 mm,hwpoison: remove drain_all_pages from shake_page
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,hwpoison: remove drain_all_pages from shake_page
get_hwpoison_page already drains pcplists, previously disabling them when trying to grab a refcount. We do not need shake_page to take care of it anymore.
---
mm/memory-failure.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-)
mm/memory-failure.c renamed from mm/memory-failure.c~mmhwpoison-remove-drain_all_pages-from-shake_page +2 -5
@@ -263,8 +263,8 @@ static int kill_proc(struct to_kill *tk, }/* -* When a unknown page type is encountered drain as many buffers as possible -* in the hope to turn the page into a LRU or free page, which we can handle. +* Unknown page type encountered. Try to check whether it can turn PageLRU by +* lru_add_drain_all, or a free page by reclaiming slabs when possible. */ void shake_page (struct page *p,int access) {
@@ -273,9 +273,6 @@ void shake_page(struct page *p, int acceif (!PageSlab (p)) {lru_add_drain_all (); -if (PageLRU (p)) -return ; -drain_all_pages (page_zone (p));if (PageLRU (p) ||is_free_buddy_page (p))return ; }
_
Andrew Morton
maintainerPATCH 144/200 mm,memory_failure: always pin the page in madvise_inject_error
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,memory_failure: always pin the page in madvise_inject_error
madvise_inject_error() uses get_user_pages_fast to translate the address we specified to a page. After [1], we drop the extra reference count for memory_failure() path. That commit says that memory_failure wanted to keep the pin in order to take the page out of circulation.
The truth is that we need to keep the page pinned, otherwise the page might be re-used after the put_page() and we can end up messing with someone else's memory.
E.g:
CPU0
process X CPU1
madvise_inject_error
get_user_pages
put_page
page gets reclaimed process Y allocates the page
memory_failure
// We mess with process Y memory
madvise() is meant to operate on a self address space, so messing with pages that do not belong to us seems the wrong thing to do. To avoid that, let us keep the page pinned for memory_failure as well.
Pages for DAX mappings will release this extra refcount in memory_failure_dev_pagemap.
[1] ("23e7b5c2e271: mm, madvise_inject_error:
Let memory_failure() optionally take a page reference")
---
mm/madvise.c | 9 +-------- mm/memory-failure.c | 6 ++++++ 2 files changed, 7 insertions(+), 8 deletions(-)
mm/madvise.c renamed from mm/madvise.c~mmmemory_failure-always-pin-the-page-in-madvise_inject_error +1 -8
@@ -907,14 +907,7 @@ static int madvise_inject_error(int beha }else {pr_info ("Injecting memory failure for pfn %#lx at process virtual address %#lx\n" , pfn, start); -/* -* Drop the page reference taken by get_user_pages_fast(). In -* the absence of MF_COUNT_INCREASED the memory_failure() -* routine is responsible for pinning the page to prevent it -* from being released back to the page allocator. -*/ -put_page (page); - ret =memory_failure (pfn,0 ); + ret =memory_failure (pfn,MF_COUNT_INCREASED ); }if (ret)
mm/memory-failure.c renamed from mm/memory-failure.c~mmmemory_failure-always-pin-the-page-in-madvise_inject_error +6 -0
@@ -1302,6 +1302,12 @@ static int memory_failure_dev_pagemap(unloff_t start;dax_entry_t cookie; +if (flags &MF_COUNT_INCREASED ) +/* +* Drop the extra refcount in case we come from madvise(). +*/ +put_page (page); +/* * Prevent the inode from being freed while we are interrogating * the address_space, typically this would be handled by
_
Andrew Morton
maintainerPATCH 145/200 mm,hwpoison: return -EBUSY when migration fails
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,hwpoison: return -EBUSY when migration fails
Currently, we return -EIO when we fail to migrate the page.
Migrations' failures are rather transient as they can happen due to several reasons, e.g: high page refcount bump, mapping->migrate_page failing etc. All meaning that at that time the page could not be migrated, but that has nothing to do with an EIO error.
Let us return -EBUSY instead, as we do in case we failed to isolate the page.
While are it, let us remove the "ret" print as its value does not change.
---
mm/memory-failure.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
mm/memory-failure.c renamed from mm/memory-failure.c~mmhwpoison-return-ebusy-when-migration-fails +3 -3
@@ -1855,11 +1855,11 @@ static int __soft_offline_page(struct papr_info ("soft offline: %#lx: %s migration failed %d, type %lx (%pGp)\n" , pfn, msg_page[huge], ret, page->flags, &page->flags);if (ret >0 ) - ret = -EIO ; + ret = -EBUSY ; } }else { -pr_info ("soft offline: %#lx: %s isolation failed: %d, page count %d, type %lx (%pGp)\n" , - pfn, msg_page[huge], ret,page_count (page), page->flags, &page->flags); +pr_info ("soft offline: %#lx: %s isolation failed, page count %d, type %lx (%pGp)\n" , + pfn, msg_page[huge],page_count (page), page->flags, &page->flags); ret = -EBUSY ; }return ret;
_
Andrew Morton
maintainerPATCH 146/200 mm/hugetlb.c: just use put_page_testzero() instead of page_count()
In reply to Andrew MortonFrom: Hui Su <[email protected]>
Subject: mm/hugetlb.c: just use put_page_testzero() instead of page_count()
We test the page reference count is zero or not here, it can be a bug here if page refercence count is not zero. So we can just use put_page_testzero() instead of page_count().
---
mm/hugetlb.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
mm/hugetlb.c renamed from mm/hugetlb.c~mm-hugetlbc-just-use-put_page_testzero-instead-of-page_count +1 -2
@@ -2014,8 +2014,7 @@ retry:* This page is now managed by the hugetlb allocator and has * no users -- drop the buddy allocator's reference. */ -put_page_testzero (page); -VM_BUG_ON_PAGE (page_count (page), page); +VM_BUG_ON_PAGE (!put_page_testzero (page), page);enqueue_huge_page (h, page); } free:
_
Andrew Morton
maintainerPATCH 147/200 include/linux/huge_mm.h: remove extern keyword
In reply to Andrew MortonFrom: Ralph Campbell <[email protected]>
Subject: include/linux/huge_mm.h: remove extern keyword
The external function definitions don't need the "extern" keyword. Remove them so future changes don't copy the function definition style.
---
include/linux/huge_mm.h | 93 ++++++++++++++++---------------------- 1 file changed, 41 insertions(+), 52 deletions(-)
include/linux/huge_mm.h renamed from include/linux/huge_mm.h~include-linux-huge_mmh-remove-extern-keyword +41 -52
@@ -7,43 +7,37 @@#include <linux/fs.h> /* only for vma_is_dax() */ -extern vm_fault_t do_huge_pmd_anonymous_page (struct vm_fault *vmf); -extern int copy_huge_pmd (struct mm_struct *dst_mm,struct mm_struct *src_mm, -pmd_t *dst_pmd,pmd_t *src_pmd,unsigned long addr, -struct vm_area_struct *vma); -extern void huge_pmd_set_accessed (struct vm_fault *vmf,pmd_t orig_pmd); -extern int copy_huge_pud (struct mm_struct *dst_mm,struct mm_struct *src_mm, -pud_t *dst_pud,pud_t *src_pud,unsigned long addr, -struct vm_area_struct *vma); +vm_fault_t do_huge_pmd_anonymous_page (struct vm_fault *vmf); +int copy_huge_pmd (struct mm_struct *dst_mm,struct mm_struct *src_mm, +pmd_t *dst_pmd,pmd_t *src_pmd,unsigned long addr, +struct vm_area_struct *vma); +void huge_pmd_set_accessed (struct vm_fault *vmf,pmd_t orig_pmd); +int copy_huge_pud (struct mm_struct *dst_mm,struct mm_struct *src_mm, +pud_t *dst_pud,pud_t *src_pud,unsigned long addr, +struct vm_area_struct *vma);#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD -extern void huge_pud_set_accessed (struct vm_fault *vmf,pud_t orig_pud); +void huge_pud_set_accessed (struct vm_fault *vmf,pud_t orig_pud);#else static inline void huge_pud_set_accessed (struct vm_fault *vmf,pud_t orig_pud) { }#endif -extern vm_fault_t do_huge_pmd_wp_page (struct vm_fault *vmf,pmd_t orig_pmd); -extern struct page *follow_trans_huge_pmd (struct vm_area_struct *vma, -unsigned long addr, -pmd_t *pmd, -unsigned int flags); -extern bool madvise_free_huge_pmd (struct mmu_gather *tlb, -struct vm_area_struct *vma, -pmd_t *pmd,unsigned long addr,unsigned long next); -extern int zap_huge_pmd (struct mmu_gather *tlb, -struct vm_area_struct *vma, -pmd_t *pmd,unsigned long addr); -extern int zap_huge_pud (struct mmu_gather *tlb, -struct vm_area_struct *vma, -pud_t *pud,unsigned long addr); -extern bool move_huge_pmd (struct vm_area_struct *vma,unsigned long old_addr, -unsigned long new_addr, -pmd_t *old_pmd,pmd_t *new_pmd); -extern int change_huge_pmd (struct vm_area_struct *vma,pmd_t *pmd, -unsigned long addr,pgprot_t newprot, -unsigned long cp_flags); +vm_fault_t do_huge_pmd_wp_page (struct vm_fault *vmf,pmd_t orig_pmd); +struct page *follow_trans_huge_pmd (struct vm_area_struct *vma, +unsigned long addr,pmd_t *pmd, +unsigned int flags); +bool madvise_free_huge_pmd (struct mmu_gather *tlb,struct vm_area_struct *vma, +pmd_t *pmd,unsigned long addr,unsigned long next); +int zap_huge_pmd (struct mmu_gather *tlb,struct vm_area_struct *vma,pmd_t *pmd, +unsigned long addr); +int zap_huge_pud (struct mmu_gather *tlb,struct vm_area_struct *vma,pud_t *pud, +unsigned long addr); +bool move_huge_pmd (struct vm_area_struct *vma,unsigned long old_addr, +unsigned long new_addr,pmd_t *old_pmd,pmd_t *new_pmd); +int change_huge_pmd (struct vm_area_struct *vma,pmd_t *pmd,unsigned long addr, +pgprot_t newprot,unsigned long cp_flags);vm_fault_t vmf_insert_pfn_pmd_prot (struct vm_fault *vmf,pfn_t pfn,pgprot_t pgprot,bool write);
@@ -100,13 +94,13 @@ enum transparent_hugepage_flag {struct kobject ;struct kobj_attribute ; -extern ssize_t single_hugepage_flag_store (struct kobject *kobj, -struct kobj_attribute *attr, -const char *buf,size_t count, -enum transparent_hugepage_flag flag); -extern ssize_t single_hugepage_flag_show (struct kobject *kobj, -struct kobj_attribute *attr,char *buf, -enum transparent_hugepage_flag flag); +ssize_t single_hugepage_flag_store (struct kobject *kobj, +struct kobj_attribute *attr, +const char *buf,size_t count, +enum transparent_hugepage_flag flag); +ssize_t single_hugepage_flag_show (struct kobject *kobj, +struct kobj_attribute *attr,char *buf, +enum transparent_hugepage_flag flag);extern struct kobj_attribute shmem_enabled_attr;#define HPAGE_PMD_ORDER (HPAGE_PMD_SHIFT-PAGE_SHIFT)
@@ -179,12 +173,11 @@ static inline bool transhuge_vma_suitabl (transparent_hugepage_flags & \ (1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG)) -extern unsigned long thp_get_unmapped_area (struct file *filp, -unsigned long addr,unsigned long len,unsigned long pgoff, -unsigned long flags); +unsigned long thp_get_unmapped_area (struct file *filp,unsigned long addr, +unsigned long len,unsigned long pgoff,unsigned long flags); -extern void prep_transhuge_page (struct page *page); -extern void free_transhuge_page (struct page *page); +void prep_transhuge_page (struct page *page); +void free_transhuge_page (struct page *page);bool is_transparent_hugepage (struct page *page);bool can_split_huge_page (struct page *page,int *pextra_pins);
@@ -222,16 +215,12 @@ void __split_huge_pud(struct vm_area_str__split_huge_pud (__vma, __pud, __address); \ }while (0 ) -extern int hugepage_madvise(struct vm_area_struct *vma, -unsigned long *vm_flags,int advice); -extern void vma_adjust_trans_huge (struct vm_area_struct *vma, -unsigned long start, -unsigned long end, -long adjust_next); -extern spinlock_t *__pmd_trans_huge_lock (pmd_t *pmd, -struct vm_area_struct *vma); -extern spinlock_t *__pud_trans_huge_lock (pud_t *pud, -struct vm_area_struct *vma); +int hugepage_madvise(struct vm_area_struct *vma, unsigned long *vm_flags, + int advice); +void vma_adjust_trans_huge (struct vm_area_struct *vma,unsigned long start, +unsigned long end,long adjust_next); +spinlock_t *__pmd_trans_huge_lock (pmd_t *pmd,struct vm_area_struct *vma); +spinlock_t *__pud_trans_huge_lock (pud_t *pud,struct vm_area_struct *vma);static inline int is_swap_pmd (pmd_t pmd) {
@@ -294,7 +283,7 @@ struct page *follow_devmap_pmd(struct vmstruct page *follow_devmap_pud (struct vm_area_struct *vma,unsigned long addr,pud_t *pud,int flags,struct dev_pagemap **pgmap); -extern vm_fault_t do_huge_pmd_numa_page (struct vm_fault *vmf,pmd_t orig_pmd); +vm_fault_t do_huge_pmd_numa_page (struct vm_fault *vmf,pmd_t orig_pmd);extern struct page *huge_zero_page;
_
Andrew Morton
maintainerPATCH 148/200 khugepaged: add parameter explanations for kernel-doc markup
In reply to Andrew MortonFrom: Alex Shi <[email protected]>
Subject: khugepaged: add parameter explanations for kernel-doc markup
Add missed parameter explanation for some kernel-doc warnings:mm/khugepaged.c:102: warning: Function parameter or member 'nr_pte_mapped_thp' not described in 'mm_slot' mm/khugepaged.c:102: warning: Function parameter or member 'pte_mapped_thp' not described in 'mm_slot' mm/khugepaged.c:1424: warning: Function parameter or member 'mm' not described in 'collapse_pte_mapped_thp'mm/khugepaged.c:1424: warning: Function parameter or member 'addr' not described in 'collapse_pte_mapped_thp'mm/khugepaged.c:1626: warning: Function parameter or member 'mm' not described in 'collapse_file'mm/khugepaged.c:1626: warning: Function parameter or member 'file' not described in 'collapse_file'mm/khugepaged.c:1626: warning: Function parameter or member 'start' not described in 'collapse_file'mm/khugepaged.c:1626: warning: Function parameter or member 'hpage' not described in 'collapse_file'mm/khugepaged.c:1626: warning: Function parameter or member 'node' not described in 'collapse_file'
---
mm/khugepaged.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
mm/khugepaged.c renamed from mm/khugepaged.c~khugepaged-add-couples-parameter-explanation-for-kernel-doc-markup +13 -1
@@ -90,6 +90,8 @@ static struct kmem_cache *mm_slot_cache* @hash: hash collision list * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head * @mm: the mm that this information is valid for +* @nr_pte_mapped_thp: number of pte mapped THP +* @pte_mapped_thp: address array corresponding pte mapped THP */ struct mm_slot {struct hlist_node hash;
@@ -1414,7 +1416,11 @@ static int khugepaged_add_pte_mapped_thp }/** -* Try to collapse a pte-mapped THP for mm at address haddr. +* collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at +* address haddr. +* +* @mm: process address space where collapse happens +* @addr: THP collapse address * * This function checks whether all the PTEs in the PMD are pointing to the * right THP. If so, retract the page table so the THP can refault in with
@@ -1605,6 +1611,12 @@ static void retract_page_tables(struct a/** * collapse_file - collapse filemap/tmpfs/shmem pages into huge one. * +* @mm: process address space where collapse happens +* @file: file that collapse on +* @start: collapse start address +* @hpage: new allocated huge page for collapse +* @node: appointed node the new huge page allocate from +* * Basic scheme is simple, details are more complex: * - allocate and lock a new huge page; * - scan page cache replacing old pages with the new one
_
Andrew Morton
maintainerPATCH 149/200 mm: hugetlb: fix type of delta parameter and related local variables in gather_surplus_pages()
In reply to Andrew MortonFrom: Liu Xiang <[email protected]>
Subject: mm: hugetlb: fix type of delta parameter and related local variables in gather_surplus_pages()
On 64-bit machine, delta variable in hugetlb_acct_memory() may be larger than 0xffffffff, but gather_surplus_pages() can only use the low 32-bit value now. So we need to fix type of delta parameter and related local variables in gather_surplus_pages().
---
mm/hugetlb.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
mm/hugetlb.c renamed from mm/hugetlb.c~mm-hugetlb-fix-type-of-delta-parameter-and-related-local-variables-in-gather_surplus_pages +4 -3
@@ -1944,13 +1944,14 @@ struct page *alloc_huge_page_vma(struct* Increase the hugetlb pool such that it can accommodate a reservation * of size 'delta'. */ -static int gather_surplus_pages (struct hstate *h,int delta) +static int gather_surplus_pages (struct hstate *h,long delta) __must_hold(&hugetlb_lock) {struct list_head surplus_list;struct page *page, *tmp; -int ret, i; -int needed, allocated; +int ret; +long i; +long needed, allocated;bool alloc_ok = true; needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
_
Andrew Morton
maintainerPATCH 150/200 mm,hugetlb: remove unneeded initialization
In reply to Andrew MortonFrom: Oscar Salvador <[email protected]>
Subject: mm,hugetlb: remove unneeded initialization
hugetlb_add_hstate initializes nr_huge_pages and free_huge_pages to 0, but since hstates[] is a global variable, all its fields are defined to 0 already.
---
mm/hugetlb.c | 2 -- 1 file changed, 2 deletions(-)
mm/hugetlb.c renamed from mm/hugetlb.c~mmhugetlb-remove-unneded-initialization +0 -2
@@ -3198,8 +3198,6 @@ void __init hugetlb_add_hstate(unsigned h = &hstates[hugetlb_max_hstate++]; h->order = order; h->mask = ~((1ULL << (order +PAGE_SHIFT )) -1 ); - h->nr_huge_pages =0 ; - h->free_huge_pages =0 ;for (i =0 ; i <MAX_NUMNODES ; ++i)INIT_LIST_HEAD (&h->hugepage_freelists[i]);INIT_LIST_HEAD (&h->hugepage_activelist);
_
Andrew Morton
maintainerPATCH 151/200 hugetlb: fix an error code in hugetlb_reserve_pages()
In reply to Andrew MortonFrom: Dan Carpenter <[email protected]>
Subject: hugetlb: fix an error code in hugetlb_reserve_pages()
Preserve the error code from region_add() instead of returning success.
---
mm/hugetlb.c | 1 + 1 file changed, 1 insertion(+)
mm/hugetlb.c renamed from mm/hugetlb.c~hugetlb-fix-an-error-code-in-hugetlb_reserve_pages +1 -0
@@ -5113,6 +5113,7 @@ int hugetlb_reserve_pages(struct inode *if (unlikely (add <0 )) {hugetlb_acct_memory (h, -gbl_reserve); + ret = add; goto out_put_pages; }else if (unlikely (chg > add)) {/*
_
Andrew Morton
maintainerPATCH 152/200 mm: don't wake kswapd prematurely when watermark boosting is disabled
In reply to Andrew MortonFrom: Johannes Weiner <[email protected]>
Subject: mm: don't wake kswapd prematurely when watermark boosting is disabled
On 2-node NUMA hosts we see bursts of kswapd reclaim and subsequent pressure spikes and stalls from cache refaults while there is plenty of free memory in the system.
Usually, kswapd is woken up when all eligible nodes in an allocation are full. But the code related to watermark boosting can wake kswapd on one full node while the other one is mostly empty. This may be justified to fight fragmentation, but is currently unconditionally done whether watermark boosting is occurring or not.
In our case, many of our workloads' throughput scales with available memory, and pure utilization is a more tangible concern than trends around longer-term fragmentation. As a result we generally disable watermark boosting.
Wake kswapd only woken when watermark boosting is requested.
---
mm/page_alloc.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-dont-wake-kswapd-prematurely-when-watermark-boosting-is-disabled +7 -6
@@ -2482,12 +2482,12 @@ static bool can_steal_fallback(unsignedreturn false; } -static inline void boost_watermark (struct zone *zone) +static inline bool boost_watermark (struct zone *zone) {unsigned long max_boost;if (!watermark_boost_factor) -return ; +return false;/* * Don't bother in zones that are unlikely to produce results. * On small machines, including kdump capture kernels running
@@ -2495,7 +2495,7 @@ static inline void boost_watermark(struc* memory situation immediately. */ if ((pageblock_nr_pages *4 ) >zone_managed_pages (zone)) -return ; +return false; max_boost =mult_frac (zone->_watermark[WMARK_HIGH ], watermark_boost_factor,10000 );
@@ -2509,12 +2509,14 @@ static inline void boost_watermark(struc* boosted watermark resulting in a hang. */ if (!max_boost) -return ; +return false; max_boost =max (pageblock_nr_pages, max_boost); zone->watermark_boost =min (zone->watermark_boost + pageblock_nr_pages, max_boost); + +return true; }/*
@@ -2552,8 +2554,7 @@ static void steal_suitable_fallback(stru* likelihood of future fallbacks. Wake kswapd now as the node * may be balanced overall and kswapd will not wake naturally. */ -boost_watermark (zone); -if (alloc_flags &ALLOC_KSWAPD ) +if (boost_watermark (zone) && (alloc_flags &ALLOC_KSWAPD ))set_bit (ZONE_BOOSTED_WATERMARK , &zone->flags);/* We are not allowed to try stealing from the whole block */
_
Andrew Morton
maintainerPATCH 153/200 mm/vmscan: drop unneeded assignment in kswapd()
In reply to Andrew MortonFrom: Lukas Bulwahn <[email protected]>
Subject: mm/vmscan: drop unneeded assignment in kswapd()
The refactoring to kswapd() in commit e716f2eb24de ("mm, vmscan: prevent kswapd sleeping prematurely due to mismatched classzone_idx") turned an assignment to reclaim_order into a dead store, as in all further paths, reclaim_order will be assigned again before it is used.
make clang-analyzer on x86_64 tinyconfig caught my attention with:
mm/vmscan.c: warning: Although the value stored to 'reclaim_order' is used in the enclosing expression, the value is never actually read from 'reclaim_order' [clang-analyzer-deadcode.DeadStores]
Compilers will detect this unneeded assignment and optimize this anyway. So, the resulting binary is identical before and after this change.
Simplify the code and remove unneeded assignment to make clang-analyzer happy.
No functional change. No change in binary code.
---
mm/vmscan.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/vmscan.c renamed from mm/vmscan.c~mm-vmscan-drop-unneeded-assignment-in-kswapd +1 -1
@@ -3895,7 +3895,7 @@ kswapd_try_sleep: highest_zoneidx);/* Read the new order and highest_zoneidx */ - alloc_order = reclaim_order =READ_ONCE (pgdat->kswapd_order); + alloc_order =READ_ONCE (pgdat->kswapd_order); highest_zoneidx =kswapd_highest_zoneidx (pgdat, highest_zoneidx);WRITE_ONCE (pgdat->kswapd_order,0 );
_
Andrew Morton
maintainerPATCH 154/200 mm/vmscan.c: remove the filename in the top of file comment
In reply to Andrew MortonFrom: "logic.yu" <[email protected]>
Subject: mm/vmscan.c: remove the filename in the top of file comment
No point in having the filename inside the file.
---
mm/vmscan.c | 2 -- 1 file changed, 2 deletions(-)
mm/vmscan.c renamed from mm/vmscan.c~mm-remove-the-filename-in-the-top-of-file-comment-in-vmscanc +0 -2
@@ -1,7 +1,5 @@// SPDX-License-Identifier: GPL-2.0 /* -* linux/mm/vmscan.c -* * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds * * Swap reorganised 29.12.95, Stephen Tweedie.
_
Andrew Morton
maintainerPATCH 155/200 mm/page_isolation: do not isolate the max order page
In reply to Andrew MortonFrom: Muchun Song <[email protected]>
Subject: mm/page_isolation: do not isolate the max order page
A max order page has no buddy page and never merges to another order. So isolating and then freeing it is pointless.
---
mm/page_isolation.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/page_isolation.c renamed from mm/page_isolation.c~mm-page_isolation-do-not-isolate-the-max-order-page +1 -1
@@ -88,7 +88,7 @@ static void unset_migratetype_isolate(st*/ if (PageBuddy (page)) { order =buddy_order (page); -if (order >= pageblock_order) { +if (order >= pageblock_order && order <MAX_ORDER -1 ) { pfn =page_to_pfn (page); buddy_pfn =__find_buddy_pfn (pfn, order); buddy = page + (buddy_pfn - pfn);
_
Andrew Morton
maintainerPATCH 156/200 z3fold: simplify freeing slots
In reply to Andrew MortonFrom: Vitaly Wool <[email protected]>
Subject: z3fold: simplify freeing slots
Patch series "z3fold: stability / rt fixes".
Address z3fold stability issues under stress load, primarily in the reclaim and free aspects. Besides, it fixes the locking problems that were only seen in real-time kernel configuration.
This patch (of 3):
There used to be two places in the code where slots could be freed, namely when freeing the last allocated handle from the slots and when releasing the z3fold header these slots aree linked to. The logic to decide on whether to free certain slots was complicated and error prone in both functions and it led to failures in RT case.
To fix that, make free_handle() the single point of freeing slots.
---
mm/z3fold.c | 55 +++++++++++--------------------------------------- 1 file changed, 13 insertions(+), 42 deletions(-)
mm/z3fold.c renamed from mm/z3fold.c~z3fold-simplify-freeing-slots +13 -42
@@ -90,7 +90,7 @@ struct z3fold_buddy_slots {* be enough slots to hold all possible variants */ unsigned long slot[BUDDY_MASK +1 ]; -unsigned long pool;/* back link + flags */ +unsigned long pool;/* back link */ rwlock_t lock; };#define HANDLE_FLAG_MASK (0x03)
@@ -182,13 +182,6 @@ enum z3fold_page_flags { };/* -* handle flags, go under HANDLE_FLAG_MASK -*/ -enum z3fold_handle_flags { -HANDLES_ORPHANED =0 , -}; - -/* * Forward declarations */ static struct z3fold_header *__z3fold_alloc (struct z3fold_pool *,size_t ,bool );
@@ -303,10 +296,9 @@ static inline void put_z3fold_header(strz3fold_page_unlock (zhdr); } -static inline void free_handle (unsigned long handle) +static inline void free_handle (unsigned long handle,struct z3fold_header *zhdr) {struct z3fold_buddy_slots *slots; -struct z3fold_header *zhdr;int i;bool is_free;
@@ -316,22 +308,13 @@ static inline void free_handle(unsignedif (WARN_ON (*(unsigned long *)handle ==0 ))return ; - zhdr =handle_to_z3fold_header (handle); slots =handle_to_slots (handle);write_lock (&slots->lock); *(unsigned long *)handle =0 ; -if (zhdr->slots == slots) { -write_unlock (&slots->lock); -return ;/* simple case, nothing else to do */ - } +if (zhdr->slots != slots) + zhdr->foreign_handles--; -/* we are freeing a foreign handle if we are here */ - zhdr->foreign_handles--; is_free = true; -if (!test_bit (HANDLES_ORPHANED , &slots->pool)) { -write_unlock (&slots->lock); -return ; - }for (i =0 ; i <=BUDDY_MASK ; i++) {if (slots->slot[i]) { is_free = false;
@@ -343,6 +326,8 @@ static inline void free_handle(unsignedif (is_free) {struct z3fold_pool *pool =slots_to_pool (slots); +if (zhdr->slots == slots) + zhdr->slots =NULL ;kmem_cache_free (pool->c_handle, slots); } }
@@ -525,8 +510,6 @@ static void __release_z3fold_page(struct {struct page *page =virt_to_page (zhdr);struct z3fold_pool *pool =zhdr_to_pool (zhdr); -bool is_free = true; -int i;WARN_ON (!list_empty (&zhdr->buddy));set_bit (PAGE_STALE , &page->private);
@@ -536,21 +519,6 @@ static void __release_z3fold_page(structlist_del_init (&page->lru);spin_unlock (&pool->lock); -/* If there are no foreign handles, free the handles array */ -read_lock (&zhdr->slots->lock); -for (i =0 ; i <=BUDDY_MASK ; i++) { -if (zhdr->slots->slot[i]) { - is_free = false; -break ; - } - } -if (!is_free) -set_bit (HANDLES_ORPHANED , &zhdr->slots->pool); -read_unlock (&zhdr->slots->lock); - -if (is_free) -kmem_cache_free (pool->c_handle, zhdr->slots); -if (locked)z3fold_page_unlock (zhdr);
@@ -973,6 +941,9 @@ lookup: } } +if (zhdr && !zhdr->slots) + zhdr->slots =alloc_slots (pool, + can_sleep ?GFP_NOIO :GFP_ATOMIC );return zhdr; }
@@ -1270,7 +1241,7 @@ static void z3fold_free(struct z3fold_po }if (!page_claimed) -free_handle (handle); +free_handle (handle, zhdr);if (kref_put (&zhdr->refcount, release_z3fold_page_locked_list)) {atomic64_dec (&pool->pages_nr);return ;
@@ -1429,19 +1400,19 @@ static int z3fold_reclaim_page(struct z3 ret = pool->ops->evict (pool, middle_handle);if (ret) goto next; -free_handle (middle_handle); +free_handle (middle_handle, zhdr); }if (first_handle) { ret = pool->ops->evict (pool, first_handle);if (ret) goto next; -free_handle (first_handle); +free_handle (first_handle, zhdr); }if (last_handle) { ret = pool->ops->evict (pool, last_handle);if (ret) goto next; -free_handle (last_handle); +free_handle (last_handle, zhdr); } next:if (test_bit (PAGE_HEADLESS , &page->private)) {
_
Andrew Morton
maintainerPATCH 157/200 z3fold: stricter locking and more careful reclaim
In reply to Andrew MortonFrom: Vitaly Wool <[email protected]>
Subject: z3fold: stricter locking and more careful reclaim
Use temporary slots in reclaim function to avoid possible race when freeing those.
While at it, make sure we check CLAIMED flag under page lock in the reclaim function to make sure we are not racing with z3fold_alloc().
---
mm/z3fold.c | 143 +++++++++++++++++++++++++++++--------------------- 1 file changed, 85 insertions(+), 58 deletions(-)
mm/z3fold.c renamed from mm/z3fold.c~z3fold-stricter-locking-and-more-careful-reclaim +85 -58
@@ -182,6 +182,13 @@ enum z3fold_page_flags { };/* +* handle flags, go under HANDLE_FLAG_MASK +*/ +enum z3fold_handle_flags { +HANDLES_NOFREE =0 , +}; + +/* * Forward declarations */ static struct z3fold_header *__z3fold_alloc (struct z3fold_pool *,size_t ,bool );
@@ -311,6 +318,12 @@ static inline void free_handle(unsigned slots =handle_to_slots (handle);write_lock (&slots->lock); *(unsigned long *)handle =0 ; + +if (test_bit (HANDLES_NOFREE , &slots->pool)) { +write_unlock (&slots->lock); +return ;/* simple case, nothing else to do */ + } +if (zhdr->slots != slots) zhdr->foreign_handles--;
@@ -621,6 +634,28 @@ static inline void add_to_unbuddied(stru } } +static inline enum buddy get_free_buddy (struct z3fold_header *zhdr,int chunks) +{ +enum buddy bud =HEADLESS ; + +if (zhdr->middle_chunks) { +if (!zhdr->first_chunks && + chunks <= zhdr->start_middle -ZHDR_CHUNKS ) + bud =FIRST ; +else if (!zhdr->last_chunks) + bud =LAST ; + }else { +if (!zhdr->first_chunks) + bud =FIRST ; +else if (!zhdr->last_chunks) + bud =LAST ; +else + bud =MIDDLE ; + } + +return bud; +} +static inline void *mchunk_memmove (struct z3fold_header *zhdr,unsigned short dst_chunk) {
@@ -682,18 +717,7 @@ static struct z3fold_header *compact_sinif (WARN_ON (new_zhdr == zhdr)) goto out_fail; -if (new_zhdr->first_chunks ==0 ) { -if (new_zhdr->middle_chunks !=0 && - chunks >= new_zhdr->start_middle) { - new_bud =LAST ; - }else { - new_bud =FIRST ; - } - }else if (new_zhdr->last_chunks ==0 ) { - new_bud =LAST ; - }else if (new_zhdr->middle_chunks ==0 ) { - new_bud =MIDDLE ; - } + new_bud =get_free_buddy (new_zhdr, chunks); q = new_zhdr;switch (new_bud) {case FIRST :
@@ -815,9 +839,8 @@ static void do_compact_page(struct z3folreturn ; } -if (unlikely (PageIsolated (page) || -test_bit (PAGE_CLAIMED , &page->private) || -test_bit (PAGE_STALE , &page->private))) { +if (test_bit (PAGE_STALE , &page->private) || +test_and_set_bit (PAGE_CLAIMED , &page->private)) {z3fold_page_unlock (zhdr);return ; }
@@ -826,13 +849,16 @@ static void do_compact_page(struct z3fol zhdr->mapped_count == 0 && compact_single_buddy(zhdr)) {if (kref_put (&zhdr->refcount, release_z3fold_page_locked))atomic64_dec (&pool->pages_nr); -else +else { +clear_bit (PAGE_CLAIMED , &page->private);z3fold_page_unlock (zhdr); + }return ; }z3fold_compact_page (zhdr);add_to_unbuddied (pool, zhdr); +clear_bit (PAGE_CLAIMED , &page->private);z3fold_page_unlock (zhdr); }
@@ -1080,17 +1106,8 @@ static int z3fold_alloc(struct z3fold_po retry: zhdr =__z3fold_alloc (pool, size, can_sleep);if (zhdr) { -if (zhdr->first_chunks ==0 ) { -if (zhdr->middle_chunks !=0 && - chunks >= zhdr->start_middle) - bud =LAST ; -else - bud =FIRST ; - }else if (zhdr->last_chunks ==0 ) - bud =LAST ; -else if (zhdr->middle_chunks ==0 ) - bud =MIDDLE ; -else { + bud =get_free_buddy (zhdr, chunks); +if (bud ==HEADLESS ) {if (kref_put (&zhdr->refcount, release_z3fold_page_locked))atomic64_dec (&pool->pages_nr);
@@ -1236,7 +1253,6 @@ static void z3fold_free(struct z3fold_popr_err ("%s: unknown bud %d\n" , __func__, bud);WARN_ON (1 );put_z3fold_header (zhdr); -clear_bit (PAGE_CLAIMED , &page->private);return ; }
@@ -1251,8 +1267,7 @@ static void z3fold_free(struct z3fold_poz3fold_page_unlock (zhdr);return ; } -if (unlikely (PageIsolated (page)) || -test_and_set_bit (NEEDS_COMPACTING , &page->private)) { +if (test_and_set_bit (NEEDS_COMPACTING , &page->private)) {put_z3fold_header (zhdr);clear_bit (PAGE_CLAIMED , &page->private);return ;
@@ -1316,6 +1331,10 @@ static int z3fold_reclaim_page(struct z3struct page *page =NULL ;struct list_head *pos;unsigned long first_handle =0 , middle_handle =0 , last_handle =0 ; + struct z3fold_buddy_slots slots __attribute__((aligned(SLOTS_ALIGN))); + +rwlock_init (&slots.lock); + slots.pool = (unsigned long )pool | (1 <<HANDLES_NOFREE );spin_lock (&pool->lock);if (!pool->ops || !pool->ops->evict || retries ==0 ) {
@@ -1330,35 +1349,36 @@ static int z3fold_reclaim_page(struct z3list_for_each_prev (pos, &pool->lru) { page = list_entry(pos, struct page, lru); -/* this bit could have been set by free, in which case -* we pass over to the next page in the pool. -*/ -if (test_and_set_bit (PAGE_CLAIMED , &page->private)) { - page =NULL ; -continue ; - } - -if (unlikely (PageIsolated (page))) { -clear_bit (PAGE_CLAIMED , &page->private); - page =NULL ; -continue ; - } zhdr =page_address (page);if (test_bit (PAGE_HEADLESS , &page->private))break ; +if (kref_get_unless_zero (&zhdr->refcount) ==0 ) { + zhdr =NULL ; +break ; + }if (!z3fold_page_trylock (zhdr)) { -clear_bit (PAGE_CLAIMED , &page->private); +if (kref_put (&zhdr->refcount, + release_z3fold_page)) +atomic64_dec (&pool->pages_nr); zhdr =NULL ;continue ;/* can't evict at this point */ } -if (zhdr->foreign_handles) { -clear_bit (PAGE_CLAIMED , &page->private); -z3fold_page_unlock (zhdr); + +/* test_and_set_bit is of course atomic, but we still +* need to do it under page lock, otherwise checking +* that bit in __z3fold_alloc wouldn't make sense +*/ +if (zhdr->foreign_handles || +test_and_set_bit (PAGE_CLAIMED , &page->private)) { +if (kref_put (&zhdr->refcount, + release_z3fold_page)) +atomic64_dec (&pool->pages_nr); +else +z3fold_page_unlock (zhdr); zhdr =NULL ;continue ;/* can't evict such page */ } -kref_get (&zhdr->refcount);list_del_init (&zhdr->buddy); zhdr->cpu =-1 ;break ;
@@ -1380,12 +1400,16 @@ static int z3fold_reclaim_page(struct z3 first_handle =0 ; last_handle =0 ; middle_handle =0 ; +memset (slots.slot,0 ,sizeof (slots.slot));if (zhdr->first_chunks) - first_handle =encode_handle (zhdr,FIRST ); + first_handle =__encode_handle (zhdr, &slots, +FIRST );if (zhdr->middle_chunks) - middle_handle =encode_handle (zhdr,MIDDLE ); + middle_handle =__encode_handle (zhdr, &slots, +MIDDLE );if (zhdr->last_chunks) - last_handle =encode_handle (zhdr,LAST ); + last_handle =__encode_handle (zhdr, &slots, +LAST );/* * it's safe to unlock here because we hold a * reference to this page
@@ -1400,19 +1424,16 @@ static int z3fold_reclaim_page(struct z3 ret = pool->ops->evict (pool, middle_handle);if (ret) goto next; -free_handle (middle_handle, zhdr); }if (first_handle) { ret = pool->ops->evict (pool, first_handle);if (ret) goto next; -free_handle (first_handle, zhdr); }if (last_handle) { ret = pool->ops->evict (pool, last_handle);if (ret) goto next; -free_handle (last_handle, zhdr); } next:if (test_bit (PAGE_HEADLESS , &page->private)) {
@@ -1426,9 +1447,11 @@ next:spin_unlock (&pool->lock);clear_bit (PAGE_CLAIMED , &page->private); }else { +struct z3fold_buddy_slots *slots = zhdr->slots;z3fold_page_lock (zhdr);if (kref_put (&zhdr->refcount, release_z3fold_page_locked)) { +kmem_cache_free (pool->c_handle, slots);atomic64_dec (&pool->pages_nr);return 0 ; }
@@ -1544,8 +1567,7 @@ static bool z3fold_page_isolate(struct pVM_BUG_ON_PAGE (!PageMovable (page), page);VM_BUG_ON_PAGE (PageIsolated (page), page); -if (test_bit (PAGE_HEADLESS , &page->private) || -test_bit (PAGE_CLAIMED , &page->private)) +if (test_bit (PAGE_HEADLESS , &page->private))return false; zhdr =page_address (page);
@@ -1557,6 +1579,8 @@ static bool z3fold_page_isolate(struct pif (zhdr->mapped_count !=0 || zhdr->foreign_handles !=0 ) goto out; +if (test_and_set_bit (PAGE_CLAIMED , &page->private)) + goto out; pool =zhdr_to_pool (zhdr);spin_lock (&pool->lock);if (!list_empty (&zhdr->buddy))
@@ -1583,16 +1607,17 @@ static int z3fold_page_migrate(struct adVM_BUG_ON_PAGE (!PageMovable (page), page);VM_BUG_ON_PAGE (!PageIsolated (page), page); +VM_BUG_ON_PAGE (!test_bit (PAGE_CLAIMED , &page->private), page);VM_BUG_ON_PAGE (!PageLocked (newpage), newpage); zhdr =page_address (page); pool =zhdr_to_pool (zhdr); -if (!z3fold_page_trylock (zhdr)) { +if (!z3fold_page_trylock (zhdr))return -EAGAIN ; - }if (zhdr->mapped_count !=0 || zhdr->foreign_handles !=0 ) {z3fold_page_unlock (zhdr); +clear_bit (PAGE_CLAIMED , &page->private);return -EBUSY ; }if (work_pending (&zhdr->work)) {
@@ -1634,6 +1659,7 @@ static int z3fold_page_migrate(struct adqueue_work_on (new_zhdr->cpu, pool->compact_wq, &new_zhdr->work);page_mapcount_reset (page); +clear_bit (PAGE_CLAIMED , &page->private);put_page (page);return 0 ; }
@@ -1657,6 +1683,7 @@ static void z3fold_page_putback(struct pspin_lock (&pool->lock);list_add (&page->lru, &pool->lru);spin_unlock (&pool->lock); +clear_bit (PAGE_CLAIMED , &page->private);z3fold_page_unlock (zhdr); }
_
Andrew Morton
maintainerPATCH 158/200 z3fold: remove preempt disabled sections for RT
In reply to Andrew MortonFrom: Vitaly Wool <[email protected]>
Subject: z3fold: remove preempt disabled sections for RT
Replace get_cpu_ptr() with migrate_disable()+this_cpu_ptr() so RT can take spinlocks that become sleeping locks.
Signed-off-by Mike Galbraith <[email protected]>
---
mm/z3fold.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-)
mm/z3fold.c renamed from mm/z3fold.c~z3fold-remove-preempt-disabled-sections-for-rt +10 -7
@@ -623,14 +623,16 @@ static inline void add_to_unbuddied(stru {if (zhdr->first_chunks ==0 || zhdr->last_chunks ==0 || zhdr->middle_chunks ==0 ) { -struct list_head *unbuddied =get_cpu_ptr (pool->unbuddied); - +struct list_head *unbuddied;int freechunks =num_free_chunks (zhdr); + +migrate_disable (); + unbuddied =this_cpu_ptr (pool->unbuddied);spin_lock (&pool->lock);list_add (&zhdr->buddy, &unbuddied[freechunks]);spin_unlock (&pool->lock); zhdr->cpu =smp_processor_id (); -put_cpu_ptr (pool->unbuddied); +migrate_enable (); } }
@@ -880,8 +882,9 @@ static inline struct z3fold_header *__z3int chunks =size_to_chunks (size), i; lookup: +migrate_disable ();/* First, try to find an unbuddied z3fold page. */ - unbuddied =get_cpu_ptr (pool->unbuddied); + unbuddied =this_cpu_ptr (pool->unbuddied);for_each_unbuddied_list (i, chunks) {struct list_head *l = &unbuddied[i];
@@ -899,7 +902,7 @@ lookup: !z3fold_page_trylock(zhdr)) {spin_unlock (&pool->lock); zhdr =NULL ; -put_cpu_ptr (pool->unbuddied); +migrate_enable ();if (can_sleep)cond_resched (); goto lookup;
@@ -913,7 +916,7 @@ lookup: test_bit(PAGE_CLAIMED, &page->private)) {z3fold_page_unlock (zhdr); zhdr =NULL ; -put_cpu_ptr (pool->unbuddied); +migrate_enable ();if (can_sleep)cond_resched (); goto lookup;
@@ -928,7 +931,7 @@ lookup:kref_get (&zhdr->refcount);break ; } -put_cpu_ptr (pool->unbuddied); +migrate_enable ();if (!zhdr) {int cpu;
_
Andrew Morton
maintainerPATCH 159/200 mm/compaction: rename 'start_pfn' to 'iteration_start_pfn' in compact_zone()
In reply to Andrew MortonFrom: Yanfei Xu <[email protected]>
Subject: mm/compaction: rename 'start_pfn' to 'iteration_start_pfn' in compact_zone()
There are two 'start_pfn' declared in compact_zone() which have different meanings. Rename the second one to 'iteration_start_pfn' to prevent confusion.
Also, remove an useless semicolon.
---
mm/compaction.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
mm/compaction.c renamed from mm/compaction.c~mm-compaction-rename-start_pfn-to-iteration_start_pfn-in-compact_zone +3 -4
@@ -2275,7 +2275,7 @@ compact_zone(struct compact_control *cc,while ((ret =compact_finished (cc)) ==COMPACT_CONTINUE ) {int err; -unsigned long start_pfn = cc->migrate_pfn; +unsigned long iteration_start_pfn = cc->migrate_pfn;/* * Avoid multiple rescans which can happen if a page cannot be
@@ -2287,7 +2287,7 @@ compact_zone(struct compact_control *cc,*/ cc->rescan = false;if (pageblock_start_pfn (last_migrated_pfn) == -pageblock_start_pfn (start_pfn)) { +pageblock_start_pfn (iteration_start_pfn)) { cc->rescan = true; }
@@ -2311,8 +2311,7 @@ compact_zone(struct compact_control *cc, goto check_drain;case ISOLATE_SUCCESS : update_cached = false; - last_migrated_pfn = start_pfn; - ; + last_migrated_pfn = iteration_start_pfn; } err = migrate_pages(&cc->migratepages, compaction_alloc,
_
Andrew Morton
maintainerPATCH 160/200 mm/compaction: move compaction_suitable's comment to right place
In reply to Andrew MortonFrom: Hui Su <[email protected]>
Subject: mm/compaction: move compaction_suitable's comment to right place
Since commit 837d026d560c ("mm/compaction: more trace to understand when/why compaction start/finish"), the comment place is not suitable.
So move compaction_suitable's comment to right place.
---
mm/compaction.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
mm/compaction.c renamed from mm/compaction.c~mm-compaction-move-compaction_suitables-comment-to-right-place +7 -7
@@ -2070,13 +2070,6 @@ static enum compact_result compact_finisreturn ret; } -/* -* compaction_suitable: Is this suitable to run compaction on this zone now? -* Returns -* COMPACT_SKIPPED - If there are too few free pages for compaction -* COMPACT_SUCCESS - If the allocation would succeed without compaction -* COMPACT_CONTINUE - If compaction should run now -*/ static enum compact_result __compaction_suitable(struct zone *zone, int order, unsigned int alloc_flags, int highest_zoneidx,
@@ -2120,6 +2113,13 @@ static enum compact_result __compaction_return COMPACT_CONTINUE ; } +/* +* compaction_suitable: Is this suitable to run compaction on this zone now? +* Returns +* COMPACT_SKIPPED - If there are too few free pages for compaction +* COMPACT_SUCCESS - If the allocation would succeed without compaction +* COMPACT_CONTINUE - If compaction should run now +*/ enum compact_result compaction_suitable (struct zone *zone,int order,unsigned int alloc_flags,int highest_zoneidx)
_
Andrew Morton
maintainerPATCH 161/200 mm/compaction: make defer_compaction and compaction_deferred static
In reply to Andrew MortonFrom: Hui Su <[email protected]>
Subject: mm/compaction: make defer_compaction and compaction_deferred static
defer_compaction() and compaction_deferred() and compaction_restarting() in mm/compaction.c won't be used in other files, so make them static, and remove the declaration in the header file.
Take the chance to fix a typo.
---
include/linux/compaction.h | 12 ------------ mm/compaction.c | 8 ++++---- 2 files changed, 4 insertions(+), 16 deletions(-)
include/linux/compaction.h renamed from include/linux/compaction.h~mm-compaction-make-defer_compaction-and-compaction_deferred-static +0 -12
@@ -98,11 +98,8 @@ extern void reset_isolation_suitable(pg_extern enum compact_result compaction_suitable (struct zone *zone,int order,unsigned int alloc_flags,int highest_zoneidx); -extern void defer_compaction (struct zone *zone,int order); -extern bool compaction_deferred (struct zone *zone,int order);extern void compaction_defer_reset (struct zone *zone,int order,bool alloc_success); -extern bool compaction_restarting (struct zone *zone,int order);/* Compaction has made some progress and retrying makes sense */ static inline bool compaction_made_progress (enum compact_result result)
@@ -194,15 +191,6 @@ static inline enum compact_result compacreturn COMPACT_SKIPPED ; } -static inline void defer_compaction (struct zone *zone,int order) -{ -} - -static inline bool compaction_deferred (struct zone *zone,int order) -{ -return true; -} -static inline bool compaction_made_progress (enum compact_result result) {return false;
mm/compaction.c renamed from mm/compaction.c~mm-compaction-make-defer_compaction-and-compaction_deferred-static +4 -4
@@ -157,7 +157,7 @@ EXPORT_SYMBOL(__ClearPageMovable);* allocation success. 1 << compact_defer_shift, compactions are skipped up * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT */ -void defer_compaction (struct zone *zone,int order) +static void defer_compaction (struct zone *zone,int order) { zone->compact_considered =0 ; zone->compact_defer_shift++;
@@ -172,7 +172,7 @@ void defer_compaction(struct zone *zone, }/* Returns true if compaction should be skipped this time */ -bool compaction_deferred (struct zone *zone,int order) +static bool compaction_deferred (struct zone *zone,int order) {unsigned long defer_limit =1UL << zone->compact_defer_shift;
@@ -209,7 +209,7 @@ void compaction_defer_reset(struct zone }/* Returns true if restarting compaction after many failures */ -bool compaction_restarting (struct zone *zone,int order) +static bool compaction_restarting (struct zone *zone,int order) {if (order < zone->compact_order_failed)return false;
@@ -237,7 +237,7 @@ static void reset_cached_positions(struc }/* -* Compound pages of >= pageblock_order should consistenly be skipped until +* Compound pages of >= pageblock_order should consistently be skipped until * released. It is always pointless to compact pages of such order (if they are * migratable), and the pageblocks they occupy cannot contain any free pages. */
_
Andrew Morton
maintainerPATCH 162/200 mm/oom_kill: change comment and rename is_dump_unreclaim_slabs()
In reply to Andrew MortonFrom: Hui Su <[email protected]>
Subject: mm/oom_kill: change comment and rename is_dump_unreclaim_slabs()
Change the comment of is_dump_unreclaim_slabs(), it just check whether nr_unreclaimable slabs amount is greater than user memory, and explain why we dump unreclaim slabs.
Rename it to should_dump_unreclaim_slab() maybe better.
---
mm/oom_kill.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-)
mm/oom_kill.c renamed from mm/oom_kill.c~mm-oom_kill-change-comment-and-rename-is_dump_unreclaim_slabs +8 -6
@@ -170,11 +170,13 @@ static bool oom_unkillable_task(struct treturn false; } -/* -* Print out unreclaimble slabs info when unreclaimable slabs amount is greater -* than all user memory (LRU pages) -*/ -static bool is_dump_unreclaim_slabs (void ) +/** +* Check whether unreclaimable slab amount is greater than +* all user memory(LRU pages). +* dump_unreclaimable_slab() could help in the case that +* oom due to too much unreclaimable slab used by kernel. +*/ +static bool should_dump_unreclaim_slab (void ) {unsigned long nr_lru;
@@ -463,7 +465,7 @@ static void dump_header(struct oom_contrmem_cgroup_print_oom_meminfo (oc->memcg); else {show_mem (SHOW_MEM_FILTER_NODES , oc->nodemask); -if (is_dump_unreclaim_slabs ()) +if (should_dump_unreclaim_slab ())dump_unreclaimable_slab (); }if (sysctl_oom_dump_tasks)
_
Andrew Morton
maintainerPATCH 163/200 mm/migrate.c: fix comment spelling
In reply to Andrew MortonFrom: Long Li <[email protected]>
Subject: mm/migrate.c: fix comment spelling
The word in the comment is misspelled, it should be "include".
---
mm/migrate.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/migrate.c renamed from mm/migrate.c~mm-migrate-fix-comment-spelling +1 -1
@@ -1696,7 +1696,7 @@ static int move_pages_and_store_status(s* Positive err means the number of failed * pages to migrate. Since we are going to * abort and return the number of non-migrated -* pages, so need to incude the rest of the +* pages, so need to include the rest of the * nr_pages that have not been attempted as * well. */
_
Andrew Morton
maintainerPATCH 164/200 mm/migrate.c: optimize migrate_vma_pages() mmu notifier
In reply to Andrew MortonFrom: Ralph Campbell <[email protected]>
Subject: mm/migrate.c: optimize migrate_vma_pages() mmu notifier
When migrating a zero page or pte_none() anonymous page to device private memory, migrate_vma_setup() will initialize the src[] array with a NULL PFN. This lets the device driver allocate device private memory and clear it instead of DMAing a page of zeros over the device bus.
Since the source page didn't exist at the time, no struct page was locked nor a migration PTE inserted into the CPU page tables. The actual PTE insertion happens in migrate_vma_pages() when it tries to insert the device private struct page PTE into the CPU page tables. migrate_vma_pages() has to call the mmu notifiers again since another device could fault on the same page before the page table locks are acquired.
Allow device drivers to optimize the invalidation similar to migrate_vma_setup() by calling mmu_notifier_range_init() which sets struct mmu_notifier_range event type to MMU_NOTIFY_MIGRATE and the migrate_pgmap_owner field.
---
mm/migrate.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-)
mm/migrate.c renamed from mm/migrate.c~mm-optimize-migrate_vma_pages-mmu-notifier +4 -5
@@ -3001,11 +3001,10 @@ void migrate_vma_pages(struct migrate_vmif (!notified) { notified = true; -mmu_notifier_range_init (&range, -MMU_NOTIFY_CLEAR ,0 , -NULL , - migrate->vma->vm_mm, - addr, migrate->end); +mmu_notifier_range_init_migrate (&range,0 , + migrate->vma, migrate->vma->vm_mm, + addr, migrate->end, + migrate->pgmap_owner);mmu_notifier_invalidate_range_start (&range); } migrate_vma_insert_page(migrate, addr, newpage,
_
Andrew Morton
maintainerPATCH 165/200 mm: support THPs in zero_user_segments
In reply to Andrew MortonFrom: "Matthew Wilcox (Oracle)" <[email protected]>
Subject: mm: support THPs in zero_user_segments
We can only kmap() one subpage of a THP at a time, so loop over all relevant subpages, skipping ones which don't need to be zeroed. This is too large to inline when THPs are enabled and we actually need highmem, so put it in highmem.c.
---
include/linux/highmem.h | 19 ++++++++++--- mm/highmem.c | 52 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 4 deletions(-)
include/linux/highmem.h renamed from include/linux/highmem.h~mm-support-thps-in-zero_user_segments +15 -4
@@ -284,13 +284,22 @@ static inline void clear_highpage(structkunmap_atomic (kaddr); } +/* +* If we pass in a base or tail page, we can zero up to PAGE_SIZE. +* If we pass in a head page, we can zero up to the size of the compound page. +*/ +#if defined(CONFIG_HIGHMEM ) && defined(CONFIG_TRANSPARENT_HUGEPAGE ) +void zero_user_segments (struct page *page,unsigned start1,unsigned end1, +unsigned start2,unsigned end2); +#else /* !HIGHMEM || !TRANSPARENT_HUGEPAGE */ static inline void zero_user_segments (struct page *page, -unsigned start1,unsigned end1, -unsigned start2,unsigned end2) +unsigned start1,unsigned end1, +unsigned start2,unsigned end2) {void *kaddr =kmap_atomic (page); +unsigned int i; -BUG_ON (end1 >PAGE_SIZE || end2 >PAGE_SIZE ); +BUG_ON (end1 >page_size (page) || end2 >page_size (page));if (end1 > start1)memset (kaddr + start1,0 , end1 - start1);
@@ -299,8 +308,10 @@ static inline void zero_user_segments(stmemset (kaddr + start2,0 , end2 - start2);kunmap_atomic (kaddr); -flush_dcache_page (page); +for (i =0 ; i <compound_nr (page); i++) + flush_dcache_page(page + i); } +#endif /* !HIGHMEM || !TRANSPARENT_HUGEPAGE */ static inline void zero_user_segment (struct page *page,unsigned start,unsigned end)
mm/highmem.c renamed from mm/highmem.c~mm-support-thps-in-zero_user_segments +52 -0
58 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 166/200 mm: truncate_complete_page() does not exist any more
In reply to Andrew MortonFrom: Yang Shi <[email protected]>
Subject: mm: truncate_complete_page() does not exist any more
Patch series "mm: misc migrate cleanup and improvement", v3.
This patch (of 5):
The commit 9f4e41f4717832e ("mm: refactor truncate_complete_page()") refactored truncate_complete_page(), and it is not existed anymore, correct the comment in vmscan and migrate to avoid confusion.
---
mm/migrate.c | 2 +- mm/vmscan.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)
mm/migrate.c renamed from mm/migrate.c~mm-truncate_complete_page-is-not-existed-anymore +1 -1
@@ -1106,7 +1106,7 @@ static int __unmap_and_move(struct page* and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. -* 2. An orphaned page (see truncate_complete_page) might have +* 2. An orphaned page (see truncate_cleanup_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to
mm/vmscan.c renamed from mm/vmscan.c~mm-truncate_complete_page-is-not-existed-anymore +1 -1
@@ -1390,7 +1390,7 @@ static unsigned int shrink_page_list(str* * Rarely, pages can have buffers and no ->mapping. These are * the pages which were not successfully invalidated in -* truncate_complete_page(). We try to drop those buffers here +* truncate_cleanup_page(). We try to drop those buffers here * and if that worked, and the page is no longer mapped into * process address space (page_count == 1) it can be freed. * Otherwise, leave the page on the LRU so it is swappable.
_
Andrew Morton
maintainerPATCH 167/200 mm: migrate: simplify the logic for handling permanent failure
In reply to Andrew MortonFrom: Yang Shi <[email protected]>
Subject: mm: migrate: simplify the logic for handling permanent failure
When unmap_and_move{_huge_page}() returns !-EAGAIN and !MIGRATEPAGE_SUCCESS, the page would be put back to LRU or proper list if it is non-LRU movable page. But, the callers always call putback_movable_pages() to put the failed pages back later on, so it seems not very efficient to put every single page back immediately, and the code looks convoluted.
Put the failed page on a separate list, then splice the list to migrate list when all pages are tried. It is the caller's responsibility to call putback_movable_pages() to handle failures. This also makes the code simpler and more readable.
After the change the rules are:
* Success: non hugetlb page will be freed, hugetlb page will be put back
* -EAGAIN: stay on the from list
* -ENOMEM: stay on the from list
* Other errno: put on ret_pages list then splice to from list
The from list would be empty iff all pages are migrated successfully, it was not so before. This has no impact to current existing callsites.
---
mm/migrate.c | 68 +++++++++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 30 deletions(-)
mm/migrate.c renamed from mm/migrate.c~mm-migrate-simplify-the-logic-for-handling-permanent-failure +38 -30
@@ -1168,7 +1168,8 @@ static int unmap_and_move(new_page_t getfree_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, - enum migrate_reason reason) + enum migrate_reason reason, + struct list_head *ret) { int rc = MIGRATEPAGE_SUCCESS;struct page *newpage =NULL ;
@@ -1205,7 +1206,14 @@ out:* migrated will have kept its references and be restored. */ list_del (&page->lru); + } +/* +* If migration is successful, releases reference grabbed during +* isolation. Otherwise, restore the page to right list unless +* we want to retry. +*/ +if (rc ==MIGRATEPAGE_SUCCESS ) {/* * Compaction can migrate also non-LRU pages which are * not accounted to NR_ISOLATED_*. They can be recognized
@@ -1214,35 +1222,16 @@ out:if (likely (!__PageMovable (page)))mod_node_page_state (page_pgdat (page),NR_ISOLATED_ANON +page_is_file_lru (page), -thp_nr_pages (page)); - } -/* -* If migration is successful, releases reference grabbed during -* isolation. Otherwise, restore the page to right list unless -* we want to retry. -*/ -if (rc ==MIGRATEPAGE_SUCCESS ) {if (reason !=MR_MEMORY_FAILURE )/* * We release the page in page_handle_poison. */ put_page (page); }else { -if (rc != -EAGAIN ) { -if (likely (!__PageMovable (page))) { -putback_lru_page (page); - goto put_new; - } +if (rc != -EAGAIN ) +list_add_tail (&page->lru, ret); -lock_page (page); -if (PageMovable (page)) -putback_movable_page (page); -else -__ClearPageIsolated (page); -unlock_page (page); -put_page (page); - } -put_new:if (put_new_page)put_new_page (newpage, private);else
@@ -1273,7 +1262,8 @@ put_new:static int unmap_and_move_huge_page (new_page_t get_new_page,free_page_t put_new_page,unsigned long private,struct page *hpage,int force, -enum migrate_mode mode,int reason) +enum migrate_mode mode,int reason, +struct list_head *ret) {int rc = -EAGAIN ;int page_was_mapped =0 ;
@@ -1289,7 +1279,7 @@ static int unmap_and_move_huge_page(new_* kicking migration. */ if (!hugepage_migration_supported (page_hstate (hpage))) { -putback_active_hugepage (hpage); +list_move_tail (&hpage->lru, ret);return -ENOSYS ; }
@@ -1374,8 +1364,10 @@ put_anon: out_unlock:unlock_page (hpage); out: -if (rc != -EAGAIN ) +if (rc ==MIGRATEPAGE_SUCCESS )putback_active_hugepage (hpage); +else if (rc != -EAGAIN && rc !=MIGRATEPAGE_SUCCESS ) +list_move_tail (&hpage->lru, ret);/* * If migration was not successful and there's a freeing callback, use
@@ -1406,8 +1398,8 @@ out:* * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. -* The caller should call putback_movable_pages() to return pages to the LRU -* or free list only if ret != 0. +* It is caller's responsibility to call putback_movable_pages() to return pages +* to the LRU or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */
@@ -1428,6 +1420,7 @@ int migrate_pages(struct list_head *fromstruct page *page2;int swapwrite = current->flags &PF_SWAPWRITE ;int rc, nr_subpages; +LIST_HEAD (ret_pages);if (!swapwrite) current->flags |=PF_SWAPWRITE ;
@@ -1450,12 +1443,21 @@ retry:if (PageHuge (page)) rc =unmap_and_move_huge_page (get_new_page, put_new_page, private, page, - pass >2 , mode, reason); + pass >2 , mode, reason, + &ret_pages);else rc =unmap_and_move (get_new_page, put_new_page, private, page, pass >2 , mode, - reason); - + reason, &ret_pages); +/* +* The rules are: +* Success: non hugetlb page will be freed, hugetlb +* page will be put back +* -EAGAIN: stay on the from list +* -ENOMEM: stay on the from list +* Other errno: put on ret_pages list then splice to +* from list +*/ switch (rc) {case -ENOMEM :/*
@@ -1521,6 +1523,12 @@ retry: nr_thp_failed += thp_retry; rc = nr_failed; out: +/* +* Put the permanent failure page back to migration list, they +* will be put back to the right list by the caller. +*/ +list_splice (&ret_pages, from); +count_vm_events (PGMIGRATE_SUCCESS , nr_succeeded);count_vm_events (PGMIGRATE_FAIL , nr_failed);count_vm_events (THP_MIGRATION_SUCCESS , nr_thp_succeeded);
_
Andrew Morton
maintainerPATCH 168/200 mm: migrate: skip shared exec THP for NUMA balancing
In reply to Andrew MortonFrom: Yang Shi <[email protected]>
Subject: mm: migrate: skip shared exec THP for NUMA balancing
The NUMA balancing skip shared exec base page. Since CONFIG_READ_ONLY_THP_FOR_FS was introduced, there are probably shared exec THP, so skip such THPs for NUMA balancing as well.
And Willy's regular filesystem THP support patches could create shared exec THP wven without that config.
In addition, the page_is_file_lru() is used to tell if the page is file cache or not, but it filters out shmem page. It sounds like a typical usecase by putting executables in shmem to achieve performance gain via using shmem-THP, so it sounds worth skipping migration for such case too.
---
mm/migrate.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-)
mm/migrate.c renamed from mm/migrate.c~mm-migrate-skip-shared-exec-thp-for-numa-balancing +16 -2
@@ -2071,6 +2071,17 @@ bool pmd_trans_migrating(pmd_t pmd)return PageLocked (page); } +static inline bool is_shared_exec_page (struct vm_area_struct *vma, +struct page *page) +{ +if (page_mapcount (page) !=1 && + (page_is_file_lru (page) ||vma_is_shmem (vma)) && + (vma->vm_flags &VM_EXEC )) +return true; + +return false; +} +/* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on
@@ -2088,8 +2099,7 @@ int migrate_misplaced_page(struct page ** Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ -if (page_mapcount (page) !=1 &&page_is_file_lru (page) && - (vma->vm_flags &VM_EXEC )) +if (is_shared_exec_page (vma, page)) goto out;/*
@@ -2144,6 +2154,9 @@ int migrate_misplaced_transhuge_page(strint page_lru =page_is_file_lru (page);unsigned long start = address &HPAGE_PMD_MASK ; +if (is_shared_exec_page (vma, page)) + goto out; + new_page =alloc_pages_node (node, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE),HPAGE_PMD_ORDER );
@@ -2255,6 +2268,7 @@ out_fail: out_unlock:unlock_page (page); +out:put_page (page);return 0 ; }
_
Andrew Morton
maintainerPATCH 169/200 mm: migrate: clean up migrate_prep{_local}
In reply to Andrew MortonFrom: Yang Shi <[email protected]>
Subject: mm: migrate: clean up migrate_prep{_local}
The migrate_prep{_local} never fails, so it is pointless to have return value and check the return value.
---
include/linux/migrate.h | 4 ++-- mm/mempolicy.c | 8 ++------ mm/migrate.c | 8 ++------ 3 files changed, 6 insertions(+), 14 deletions(-)
include/linux/migrate.h renamed from include/linux/migrate.h~mm-migrate-clean-up-migrate_prep_local +2 -2
@@ -45,8 +45,8 @@ extern struct page *alloc_migration_targextern int isolate_movable_page (struct page *page,isolate_mode_t mode);extern void putback_movable_page (struct page *page); -extern int migrate_prep (void ); -extern int migrate_prep_local (void ); +extern void migrate_prep (void ); +extern void migrate_prep_local (void );extern void migrate_page_states (struct page *newpage,struct page *page);extern void migrate_page_copy (struct page *newpage,struct page *page); extern int migrate_huge_page_move_mapping(struct address_space *mapping,
mm/mempolicy.c renamed from mm/mempolicy.c~mm-migrate-clean-up-migrate_prep_local +2 -6
@@ -1114,9 +1114,7 @@ int do_migrate_pages(struct mm_struct *mint err;nodemask_t tmp; - err =migrate_prep (); -if (err) -return err; +migrate_prep ();mmap_read_lock (mm);
@@ -1315,9 +1313,7 @@ static long do_mbind(unsigned long startif (flags & (MPOL_MF_MOVE |MPOL_MF_MOVE_ALL )) { - err =migrate_prep (); -if (err) - goto mpol_out; +migrate_prep (); } {NODEMASK_SCRATCH (scratch);
mm/migrate.c renamed from mm/migrate.c~mm-migrate-clean-up-migrate_prep_local +2 -6
@@ -62,7 +62,7 @@* to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ -int migrate_prep (void ) +void migrate_prep (void ) {/* * Clear the LRU lists so pages can be isolated.
@@ -71,16 +71,12 @@ int migrate_prep(void)* pages that may be busy. */ lru_add_drain_all (); - -return 0 ; }/* Do the necessary work of migrate_prep but not if it involves other CPUs */ -int migrate_prep_local (void ) +void migrate_prep_local (void ) {lru_add_drain (); - -return 0 ; }int isolate_movable_page (struct page *page,isolate_mode_t mode)
_
Andrew Morton
maintainerPATCH 170/200 mm: migrate: return -ENOSYS if THP migration is unsupported
In reply to Andrew MortonFrom: Yang Shi <[email protected]>
Subject: mm: migrate: return -ENOSYS if THP migration is unsupported
In the current implementation unmap_and_move() would return -ENOMEM if THP migration is unsupported, then the THP will be split. If split is failed just exit without trying to migrate other pages. It doesn't make too much sense since there may be enough free memory to migrate other pages and there may be a lot base pages on the list.
Return -ENOSYS to make consistent with hugetlb. And if THP split is failed just skip and try other pages on the list.
Just skip the whole list and exit when free memory is really low.
---
mm/migrate.c | 62 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 16 deletions(-)
mm/migrate.c renamed from mm/migrate.c~mm-migrate-return-enosys-if-thp-migration-is-unsupported +46 -16
@@ -1171,7 +1171,7 @@ static int unmap_and_move(new_page_t getstruct page *newpage =NULL ;if (!thp_migration_supported () &&PageTransHuge (page)) -return -ENOMEM ; +return -ENOSYS ;if (page_count (page) ==1 ) {/* page was freed from under us. So we are done. */
@@ -1378,6 +1378,20 @@ out:return rc; } +static inline int try_split_thp (struct page *page,struct page **page2, +struct list_head *from) +{ +int rc =0 ; + +lock_page (page); + rc =split_huge_page_to_list (page, from); +unlock_page (page); +if (!rc) +list_safe_reset_next (page, *page2, lru); + +return rc; +} +/* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration
@@ -1455,24 +1469,40 @@ retry:* from list */ switch (rc) { +/* +* THP migration might be unsupported or the +* allocation could've failed so we should +* retry on the same page with the THP split +* to base pages. +* +* Head page is retried immediately and tail +* pages are added to the tail of the list so +* we encounter them after the rest of the list +* is processed. +*/ +case -ENOSYS : +/* THP migration is unsupported */ +if (is_thp) { +if (!try_split_thp (page, &page2, from)) { + nr_thp_split++; + goto retry; + } + + nr_thp_failed++; + nr_failed += nr_subpages; +break ; + } + +/* Hugetlb migration is unsupported */ + nr_failed++; +break ;case -ENOMEM :/* -* THP migration might be unsupported or the -* allocation could've failed so we should -* retry on the same page with the THP split -* to base pages. -* -* Head page is retried immediately and tail -* pages are added to the tail of the list so -* we encounter them after the rest of the list -* is processed. +* When memory is low, don't bother to try to migrate +* other pages, just exit. */ if (is_thp) { -lock_page (page); - rc =split_huge_page_to_list (page, from); -unlock_page (page); -if (!rc) { -list_safe_reset_next (page, page2, lru); +if (!try_split_thp (page, &page2, from)) { nr_thp_split++; goto retry; }
@@ -1500,7 +1530,7 @@ retry:break ;default :/* -* Permanent failure (-EBUSY, -ENOSYS, etc.): +* Permanent failure (-EBUSY, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop.
_
Andrew Morton
maintainerPATCH 171/200 mm: migrate: remove unused parameter in migrate_vma_insert_page()
In reply to Andrew MortonFrom: Stephen Zhang <[email protected]>
Subject: mm: migrate: remove unused parameter in migrate_vma_insert_page()
"dst" parameter to migrate_vma_insert_page() is not used anymore.
---
mm/migrate.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
mm/migrate.c renamed from mm/migrate.c~mm-migrate-remove-unused-parameter-in-migrate_vma_insert_page +2 -4
@@ -2894,8 +2894,7 @@ EXPORT_SYMBOL(migrate_vma_setup);static void migrate_vma_insert_page (struct migrate_vma *migrate,unsigned long addr,struct page *page, -unsigned long *src, -unsigned long *dst) +unsigned long *src) {struct vm_area_struct *vma = migrate->vma;struct mm_struct *mm = vma->vm_mm;
@@ -3056,8 +3055,7 @@ void migrate_vma_pages(struct migrate_vmmmu_notifier_invalidate_range_start (&range); }migrate_vma_insert_page (migrate, addr, newpage, - &migrate->src[i], - &migrate->dst[i]); + &migrate->src[i]);continue ; }
_
Andrew Morton
maintainerPATCH 172/200 mm/cma.c: remove redundant cma_mutex lock
In reply to Andrew MortonFrom: Lecopzer Chen <[email protected]>
Subject: mm/cma.c: remove redundant cma_mutex lock
The cma_mutex which protects alloc_contig_range() was first appeared in commit 7ee793a62fa8c ("cma: Remove potential deadlock situation"), at that time, there is no guarantee the behavior of concurrency inside alloc_contig_range().
After commit 2c7452a075d4db2dc ("mm/page_isolation.c: make start_isolate_page_range() fail if already isolated")
Quoted 5 lines
However, two subsystems (CMA and gigantic
huge pages for example) could attempt operations on the same range. If this happens, one thread may 'undo' the work another thread is doing. This can result in pageblocks being incorrectly left marked asMIGRATE_ISOLATEand therefore not available for page allocation.
The concurrency inside alloc_contig_range() was clarified.
Now we can find that hugepage and virtio call alloc_contig_range() without any lock, thus cma_mutex is "redundant" in cma_alloc() now.
---
mm/cma.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
mm/cma.c renamed from mm/cma.c~mm-cmac-remove-redundant-cma_mutex-lock +1 -3
@@ -38,7 +38,6 @@struct cma cma_areas[MAX_CMA_AREAS ];unsigned cma_area_count; -static DEFINE_MUTEX (cma_mutex);phys_addr_t cma_get_base (const struct cma *cma) {
@@ -454,10 +453,9 @@ struct page *cma_alloc(struct cma *cma,mutex_unlock (&cma->lock); pfn = cma->base_pfn + (bitmap_no << cma->order_per_bit); -mutex_lock (&cma_mutex); ret =alloc_contig_range (pfn, pfn + count,MIGRATE_CMA ,GFP_KERNEL | (no_warn ? __GFP_NOWARN :0 )); -mutex_unlock (&cma_mutex); +if (ret ==0 ) { page =pfn_to_page (pfn);break ;
_
Andrew Morton
maintainerPATCH 173/200 mm: cma: improve pr_debug log in cma_release()
In reply to Andrew MortonFrom: Charan Teja Reddy <[email protected]>
Subject: mm: cma: improve pr_debug log in cma_release()
It is required to print 'count' of pages, along with the pages, passed to cma_release to debug the cases of mismatched count value passed between cma_alloc() and cma_release() from a code path.
As an example, consider the below scenario:
1) CMA pool size is 4MB and
2) User doing the erroneous step of allocating 2 pages but freeing 1 page in a loop from this CMA pool. The step 2 causes cma_alloc() to return NULL at one point of time because of -ENOMEM condition.
And the current pr_debug logs is not giving the info about these types of allocation patterns because of count value not being printed in cma_release().
We are printing the count value in the trace logs, just extend the same to pr_debug logs too.
---
mm/cma.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/cma.c renamed from mm/cma.c~mm-cma-improve-pr_debug-log-in-cma_release +1 -1
@@ -510,7 +510,7 @@ bool cma_release(struct cma *cma, constif (!cma || !pages)return false; -pr_debug ("%s(page %p)\n" , __func__, (void *)pages); +pr_debug ("%s(page %p, count %u)\n" , __func__, (void *)pages, count); pfn =page_to_pfn (pages);
_
Andrew Morton
maintainerPATCH 174/200 mm, page_alloc: do not rely on the order of page_poison and init_on_alloc/free parameters
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_alloc: do not rely on the order of page_poison and init_on_alloc/free parameters
Patch series "cleanup page poisoning", v3.
I have identified a number of issues and opportunities for cleanup with CONFIG_PAGE_POISON and friends:
- interaction with init_on_alloc and init_on_free parameters depends on the order of parameters (Patch 1)
- the boot time enabling uses static key, but inefficienty (Patch 2)
- sanity checking is incompatible with hibernation (Patch 3)
- CONFIG_PAGE_POISONING_NO_SANITY can be removed now that we have init_on_free (Patch 4)
- CONFIG_PAGE_POISONING_ZERO can be most likely removed now that we have init_on_free (Patch 5)
This patch (of 5):
Enabling page_poison=1 together with init_on_alloc=1 or init_on_free=1 produces a warning in dmesg that page_poison takes precedence. However, as these warnings are printed in early_param handlers for init_on_alloc/free, they are not printed if page_poison is enabled later on the command line (handlers are called in the order of their parameters), or when init_on_alloc/free is always enabled by the respective config option - before the page_poison early param handler is called, it is not considered to be enabled. This is inconsistent.
We can remove the dependency on order by making the init_on_* parameters only set a boolean variable, and postponing the evaluation after all early params have been processed. Introduce a new init_mem_debugging_and_hardening() function for that, and move the related debug_pagealloc processing there as well.
As a result init_mem_debugging_and_hardening() knows always accurately if init_on_* and/or page_poison options were enabled. Thus we can also optimize want_init_on_alloc() and want_init_on_free(). We don't need to check page_poisoning_enabled() there, we can instead not enable the init_on_* static keys at all, if page poisoning is enabled. This results in a simpler and more effective code.
---
include/linux/mm.h | 20 +-------- init/main.c | 2 mm/page_alloc.c | 88 ++++++++++++++++++++----------------------- 3 files changed, 46 insertions(+), 64 deletions(-)
include/linux/mm.h renamed from include/linux/mm.h~mm-page_alloc-do-not-rely-on-the-order-of-page_poison-and-init_on_alloc-free-parameters +3 -17
@@ -2872,6 +2872,7 @@ extern int apply_to_existing_page_range( unsigned long address, unsigned long size, pte_fn_t fn, void *data); +extern void init_mem_debugging_and_hardening (void );#ifdef CONFIG_PAGE_POISONING extern bool page_poisoning_enabled (void );extern void kernel_poison_pages (struct page *page,int numpages,int enable);
@@ -2881,35 +2882,20 @@ static inline void kernel_poison_pages(s int enable) { }#endif -#ifdef CONFIG_INIT_ON_ALLOC_DEFAULT_ON -DECLARE_STATIC_KEY_TRUE (init_on_alloc); -#else DECLARE_STATIC_KEY_FALSE (init_on_alloc); -#endif static inline bool want_init_on_alloc (gfp_t flags) { -if (static_branch_unlikely (&init_on_alloc) && - !page_poisoning_enabled ()) +if (static_branch_unlikely (&init_on_alloc))return true;return flags & __GFP_ZERO; } -#ifdef CONFIG_INIT_ON_FREE_DEFAULT_ON -DECLARE_STATIC_KEY_TRUE (init_on_free); -#else DECLARE_STATIC_KEY_FALSE (init_on_free); -#endif static inline bool want_init_on_free (void ) { -return static_branch_unlikely (&init_on_free) && - !page_poisoning_enabled (); +return static_branch_unlikely (&init_on_free); } -#ifdef CONFIG_DEBUG_PAGEALLOC -extern void init_debug_pagealloc (void ); -#else -static inline void init_debug_pagealloc (void ) {} -#endif extern bool _debug_pagealloc_enabled_early;DECLARE_STATIC_KEY_FALSE (_debug_pagealloc_enabled);
init/main.c renamed from init/main.c~mm-page_alloc-do-not-rely-on-the-order-of-page_poison-and-init_on_alloc-free-parameters +1 -1
@@ -824,7 +824,7 @@ static void __init mm_init(void)* bigger than MAX_ORDER unless SPARSEMEM. */ page_ext_init_flatmem (); -init_debug_pagealloc (); +init_mem_debugging_and_hardening ();report_meminit ();mem_init ();/* page_owner must be initialized after buddy is ready */
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-do-not-rely-on-the-order-of-page_poison-and-init_on_alloc-free-parameters +42 -46
120 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 175/200 mm, page_poison: use static key more efficiently
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_poison: use static key more efficiently
Commit 11c9c7edae06 ("mm/page_poison.c: replace bool variable with static key") changed page_poisoning_enabled() to a static key check. However, the function is not inlined, so each check still involves a function call with overhead not eliminated when page poisoning is disabled.
Analogically to how debug_pagealloc is handled, this patch converts page_poisoning_enabled() back to boolean check, and introduces page_poisoning_enabled_static() for fast paths. Both functions are inlined.
The function kernel_poison_pages() is also called unconditionally and does the static key check inside. Remove it from there and put it to callers. Also split it to two functions kernel_poison_pages() and kernel_unpoison_pages() instead of the confusing bool parameter.
Also optimize the check that enables page poisoning instead of debug_pagealloc for architectures without proper debug_pagealloc support. Move the check to init_mem_debugging_and_hardening() to enable a single static key instead of having two static branches in page_poisoning_enabled_static().
---
drivers/virtio/virtio_balloon.c | 2 - include/linux/mm.h | 33 ++++++++++++++++-- mm/page_alloc.c | 18 ++++++++-- mm/page_poison.c | 53 +++--------------------------- 4 files changed, 52 insertions(+), 54 deletions(-)
drivers/virtio/virtio_balloon.c renamed from drivers/virtio/virtio_balloon.c~mm-page_poison-use-static-key-more-efficiently +1 -1
@@ -1116,7 +1116,7 @@ static int virtballoon_validate(struct v*/ if (!want_init_on_free () && (IS_ENABLED (CONFIG_PAGE_POISONING_NO_SANITY ) || - !page_poisoning_enabled ())) + !page_poisoning_enabled_static ()))__virtio_clear_bit (vdev,VIRTIO_BALLOON_F_PAGE_POISON );else if (!virtio_has_feature (vdev,VIRTIO_BALLOON_F_PAGE_POISON ))__virtio_clear_bit (vdev,VIRTIO_BALLOON_F_REPORTING );
include/linux/mm.h renamed from include/linux/mm.h~mm-page_poison-use-static-key-more-efficiently +29 -4
@@ -2874,12 +2874,37 @@ extern int apply_to_existing_page_range(extern void init_mem_debugging_and_hardening (void );#ifdef CONFIG_PAGE_POISONING -extern bool page_poisoning_enabled (void ); -extern void kernel_poison_pages (struct page *page,int numpages,int enable); +extern void __kernel_poison_pages (struct page *page,int numpages); +extern void __kernel_unpoison_pages (struct page *page,int numpages); +extern bool _page_poisoning_enabled_early; +DECLARE_STATIC_KEY_FALSE (_page_poisoning_enabled); +static inline bool page_poisoning_enabled (void ) +{ +return _page_poisoning_enabled_early; +} +/* +* For use in fast paths after init_mem_debugging() has run, or when a +* false negative result is not harmful when called too early. +*/ +static inline bool page_poisoning_enabled_static (void ) +{ +return static_branch_unlikely (&_page_poisoning_enabled); +} +static inline void kernel_poison_pages (struct page *page,int numpages) +{ +if (page_poisoning_enabled_static ()) +__kernel_poison_pages (page, numpages); +} +static inline void kernel_unpoison_pages (struct page *page,int numpages) +{ +if (page_poisoning_enabled_static ()) +__kernel_unpoison_pages (page, numpages); +}#else static inline bool page_poisoning_enabled (void ) {return false; } -static inline void kernel_poison_pages (struct page *page,int numpages, -int enable) { } +static inline bool page_poisoning_enabled_static (void ) {return false; } +static inline void kernel_poison_pages (struct page *page,int numpages) { } +static inline void kernel_unpoison_pages (struct page *page,int numpages) { }#endif DECLARE_STATIC_KEY_FALSE (init_on_alloc);
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_poison-use-static-key-more-efficiently +15 -3
@@ -777,6 +777,17 @@ void init_mem_debugging_and_hardening(vostatic_branch_enable (&init_on_free); } +#ifdef CONFIG_PAGE_POISONING +/* +* Page poisoning is debug page alloc for some arches. If +* either of those options are enabled, enable poisoning. +*/ +if (page_poisoning_enabled () || + (!IS_ENABLED (CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC ) && +debug_pagealloc_enabled ())) +static_branch_enable (&_page_poisoning_enabled); +#endif +#ifdef CONFIG_DEBUG_PAGEALLOC if (!debug_pagealloc_enabled ())return ;
@@ -1262,7 +1273,8 @@ static __always_inline bool free_pages_pif (want_init_on_free ())kernel_init_free_pages (page,1 << order); -kernel_poison_pages (page,1 << order,0 ); +kernel_poison_pages (page,1 << order); +/* * arch_free_page() can make the page's contents inaccessible. s390 * does this. So nothing which can access the page's contents should
@@ -2219,7 +2231,7 @@ static inline int check_new_page(structstatic inline bool free_pages_prezeroed (void ) {return (IS_ENABLED (CONFIG_PAGE_POISONING_ZERO ) && -page_poisoning_enabled ()) ||want_init_on_free (); +page_poisoning_enabled_static ()) ||want_init_on_free (); }#ifdef CONFIG_DEBUG_VM
@@ -2281,7 +2293,7 @@ inline void post_alloc_hook(struct pagearch_alloc_page (page, order);debug_pagealloc_map_pages (page,1 << order);kasan_alloc_pages (page, order); -kernel_poison_pages (page,1 << order,1 ); +kernel_unpoison_pages (page,1 << order);set_page_owner (page, order, gfp_flags);if (!free_pages_prezeroed () &&want_init_on_alloc (gfp_flags))
mm/page_poison.c renamed from mm/page_poison.c~mm-page_poison-use-static-key-more-efficiently +7 -46
83 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 176/200 kernel/power: allow hibernation with page_poison sanity checking
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: kernel/power: allow hibernation with page_poison sanity checking
Page poisoning used to be incompatible with hibernation, as the state of poisoned pages was lost after resume, thus enabling CONFIG_HIBERNATION forces CONFIG_PAGE_POISONING_NO_SANITY. For the same reason, the poisoning with zeroes variant CONFIG_PAGE_POISONING_ZERO used to disable hibernation. The latter restriction was removed by commit 1ad1410f632d ("PM / Hibernate: allow hibernation with PAGE_POISONING_ZERO") and similarly for init_on_free by commit 18451f9f9e58 ("PM: hibernate: fix crashes with init_on_free=1") by making sure free pages are cleared after resume.
We can use the same mechanism to instead poison free pages with PAGE_POISON after resume. This covers both zero and 0xAA patterns. Thus we can remove the Kconfig restriction that disables page poison sanity checking when hibernation is enabled.
---
include/linux/mm.h | 1 + kernel/power/hibernate.c | 2 +- kernel/power/power.h | 2 +- kernel/power/snapshot.c | 14 +++++++++++--- mm/Kconfig.debug | 1 - 5 files changed, 14 insertions(+), 6 deletions(-)
include/linux/mm.h renamed from include/linux/mm.h~kernel-power-allow-hibernation-with-page_poison-sanity-checking +1 -0
@@ -2903,6 +2903,7 @@ static inline void kernel_unpoison_pages#else static inline bool page_poisoning_enabled (void ) {return false; }static inline bool page_poisoning_enabled_static (void ) {return false; } +static inline void __kernel_poison_pages (struct page *page,int nunmpages) { }static inline void kernel_poison_pages (struct page *page,int numpages) { }static inline void kernel_unpoison_pages (struct page *page,int numpages) { }#endif
kernel/power/hibernate.c renamed from kernel/power/hibernate.c~kernel-power-allow-hibernation-with-page_poison-sanity-checking +1 -1
@@ -326,7 +326,7 @@ static int create_image(int platform_modif (!in_suspend) { events_check_enabled = false; -clear_free_pages (); +clear_or_poison_free_pages (); }platform_leave (platform_mode);
kernel/power/power.h renamed from kernel/power/power.h~kernel-power-allow-hibernation-with-page_poison-sanity-checking +1 -1
@@ -106,7 +106,7 @@ extern int create_basic_memory_bitmaps(vextern void free_basic_memory_bitmaps (void );extern int hibernate_preallocate_memory (void ); -extern void clear_free_pages (void ); +extern void clear_or_poison_free_pages (void );/** * Auxiliary structure used for reading the snapshot image data and
kernel/power/snapshot.c renamed from kernel/power/snapshot.c~kernel-power-allow-hibernation-with-page_poison-sanity-checking +11 -3
@@ -1178,7 +1178,15 @@ void free_basic_memory_bitmaps(void)pr_debug ("Basic memory bitmaps freed\n" ); } -void clear_free_pages (void ) +static void clear_or_poison_free_page (struct page *page) +{ +if (page_poisoning_enabled_static ()) +__kernel_poison_pages (page,1 ); +else if (want_init_on_free ()) +clear_highpage (page); +} + +void clear_or_poison_free_pages (void ) {struct memory_bitmap *bm = free_pages_map;unsigned long pfn;
@@ -1186,12 +1194,12 @@ void clear_free_pages(void)if (WARN_ON (!(free_pages_map)))return ; -if (IS_ENABLED (CONFIG_PAGE_POISONING_ZERO ) ||want_init_on_free ()) { +if (page_poisoning_enabled () ||want_init_on_free ()) {memory_bm_position_reset (bm); pfn =memory_bm_next_pfn (bm);while (pfn !=BM_END_OF_MAP ) {if (pfn_valid (pfn)) -clear_highpage (pfn_to_page (pfn)); +clear_or_poison_free_page (pfn_to_page (pfn)); pfn =memory_bm_next_pfn (bm); }
mm/Kconfig.debug renamed from mm/Kconfig.debug~kernel-power-allow-hibernation-with-page_poison-sanity-checking +0 -1
@@ -64,7 +64,6 @@ config PAGE_OWNER config PAGE_POISONING bool "Poison pages after freeing" - select PAGE_POISONING_NO_SANITY if HIBERNATION help Fill the pages with poison patterns after free_pages() and verify the patterns before alloc_pages. The filling of the memory helps
_
Andrew Morton
maintainerPATCH 177/200 mm, page_poison: remove CONFIG_PAGE_POISONING_NO_SANITY
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_poison: remove CONFIG_PAGE_POISONING_NO_SANITY
CONFIG_PAGE_POISONING_NO_SANITY skips the check on page alloc whether the poison pattern was corrupted, suggesting a use-after-free. The motivation to introduce it in commit 8823b1dbc05f ("mm/page_poison.c: enable PAGE_POISONING as a separate option") was to simply sanitize freed pages, optimally together with CONFIG_PAGE_POISONING_ZERO.
These days we have an init_on_free=1 boot option, which makes this use case of page poisoning redundant. For sanitizing, writing zeroes is sufficient, there is pretty much no benefit from writing the 0xAA poison pattern to freed pages, without checking it back on alloc. Thus, remove this option and suggest init_on_free instead in the main config's help.
---
drivers/virtio/virtio_balloon.c | 4 +--- mm/Kconfig.debug | 15 ++++----------- mm/page_poison.c | 3 --- 3 files changed, 5 insertions(+), 17 deletions(-)
drivers/virtio/virtio_balloon.c renamed from drivers/virtio/virtio_balloon.c~mm-page_poison-remove-config_page_poisoning_no_sanity +1 -3
@@ -1114,9 +1114,7 @@ static int virtballoon_validate(struct v* page reporting as it could potentially change the contents * of our free pages. */ -if (!want_init_on_free () && - (IS_ENABLED (CONFIG_PAGE_POISONING_NO_SANITY ) || - !page_poisoning_enabled_static ())) +if (!want_init_on_free () && !page_poisoning_enabled_static ())__virtio_clear_bit (vdev,VIRTIO_BALLOON_F_PAGE_POISON );else if (!virtio_has_feature (vdev,VIRTIO_BALLOON_F_PAGE_POISON ))__virtio_clear_bit (vdev,VIRTIO_BALLOON_F_REPORTING );
mm/Kconfig.debug renamed from mm/Kconfig.debug~mm-page_poison-remove-config_page_poisoning_no_sanity +4 -11
@@ -74,18 +74,11 @@ config PAGE_POISONING Note that "poison" here is not the same thing as the "HWPoison" for CONFIG_MEMORY_FAILURE. This is software poisoning only. - If unsure, say N - -config PAGE_POISONING_NO_SANITY - depends on PAGE_POISONING - bool "Only poison, don't sanity check" - help - Skip the sanity checking on alloc, only fill the pages with - poison on free. This reduces some of the overhead of the - poisoning feature. + If you are only interested in sanitization of freed pages without + checking the poison pattern on alloc, you can boot the kernel with + "init_on_free=1" instead of enabling this. - If you are only interested in sanitization, say Y. Otherwise - say N. + If unsure, say N config PAGE_POISONING_ZERO bool "Use zero for poisoning instead of debugging value"
mm/page_poison.c renamed from mm/page_poison.c~mm-page_poison-remove-config_page_poisoning_no_sanity +0 -3
@@ -51,9 +51,6 @@ static void check_poison_mem(unsigned chunsigned char *start;unsigned char *end; -if (IS_ENABLED (CONFIG_PAGE_POISONING_NO_SANITY )) -return ; - start =memchr_inv (mem,PAGE_POISON , bytes);if (!start)return ;
_
Andrew Morton
maintainerPATCH 178/200 mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, page_poison: remove CONFIG_PAGE_POISONING_ZERO
CONFIG_PAGE_POISONING_ZERO uses the zero pattern instead of 0xAA. It was introduced by commit 1414c7f4f7d7 ("mm/page_poisoning.c: allow for zero poisoning"), noting that using zeroes retains the benefit of sanitizing content of freed pages, with the benefit of not having to zero them again on alloc, and the downside of making some forms of corruption (stray writes of NULLs) harder to detect than with the 0xAA pattern. Together with CONFIG_PAGE_POISONING_NO_SANITY it made possible to sanitize the contents on free without checking it back on alloc.
These days we have the init_on_free() option to achieve sanitization with zeroes and to save clearing on alloc (and without checking on alloc). Arguably if someone does choose to check the poison for corruption on alloc, the savings of not clearing the page are secondary, and it makes sense to always use the 0xAA poison pattern. Thus, remove the CONFIG_PAGE_POISONING_ZERO option for being redundant.
---
include/linux/poison.h | 4 ---- mm/Kconfig.debug | 12 ------------ mm/page_alloc.c | 8 +------- tools/include/linux/poison.h | 6 +----- 4 files changed, 2 insertions(+), 28 deletions(-)
include/linux/poison.h renamed from include/linux/poison.h~mm-page_poison-remove-config_page_poisoning_zero +0 -4
@@ -27,11 +27,7 @@#define TIMER_ENTRY_STATIC ((void *) 0x300 + POISON_POINTER_DELTA)/********** mm/page_poison.c **********/ -#ifdef CONFIG_PAGE_POISONING_ZERO -#define PAGE_POISON 0x00 -#else #define PAGE_POISON 0xaa -#endif /********** mm/page_alloc.c ************/
mm/Kconfig.debug renamed from mm/Kconfig.debug~mm-page_poison-remove-config_page_poisoning_zero +0 -12
@@ -80,18 +80,6 @@ config PAGE_POISONING If unsure, say N -config PAGE_POISONING_ZERO - bool "Use zero for poisoning instead of debugging value" - depends on PAGE_POISONING - help - Instead of using the existing poison value, fill the pages with - zeros. This makes it harder to detect when errors are occurring - due to sanitization but the zeroing at free means that it is - no longer necessary to write zeros when GFP_ZERO is used on - allocation. - - If unsure, say N - config DEBUG_PAGE_REF bool "Enable tracepoint to track down page reference manipulation" depends on DEBUG_KERNEL
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_poison-remove-config_page_poisoning_zero +1 -7
@@ -2228,12 +2228,6 @@ static inline int check_new_page(structreturn 1 ; } -static inline bool free_pages_prezeroed (void ) -{ -return (IS_ENABLED (CONFIG_PAGE_POISONING_ZERO ) && -page_poisoning_enabled_static ()) ||want_init_on_free (); -} -#ifdef CONFIG_DEBUG_VM /* * With DEBUG_VM enabled, order-0 pages are checked for expected state when
@@ -2296,7 +2290,7 @@ inline void post_alloc_hook(struct pagekernel_unpoison_pages (page,1 << order);set_page_owner (page, order, gfp_flags); -if (!free_pages_prezeroed () &&want_init_on_alloc (gfp_flags)) +if (!want_init_on_free () &&want_init_on_alloc (gfp_flags))kernel_init_free_pages (page,1 << order); }
tools/include/linux/poison.h renamed from tools/include/linux/poison.h~mm-page_poison-remove-config_page_poisoning_zero +1 -5
@@ -35,12 +35,8 @@*/ #define TIMER_ENTRY_STATIC ((void *) 0x300 + POISON_POINTER_DELTA) -/********** mm/debug-pagealloc.c **********/ -#ifdef CONFIG_PAGE_POISONING_ZERO -#define PAGE_POISON 0x00 -#else +/********** mm/page_poison.c **********/ #define PAGE_POISON 0xaa -#endif /********** mm/page_alloc.c ************/
_
Andrew Morton
maintainerPATCH 179/200 userfaultfd: add UFFD_USER_MODE_ONLY
In reply to Andrew MortonFrom: Lokesh Gidra <[email protected]>
Subject: userfaultfd: add UFFD_USER_MODE_ONLY
Patch series "Control over userfaultfd kernel-fault handling", v6.
This patch series is split from [1]. The other series enables SELinux support for userfaultfd file descriptors so that its creation and movement can be controlled.
It has been demonstrated on various occasions that suspending kernel code execution for an arbitrary amount of time at any access to userspace memory (copy_from_user()/copy_to_user()/...) can be exploited to change the intended behavior of the kernel. For instance, handling page faults in kernel-mode using userfaultfd has been exploited in [2, 3]. Likewise, FUSE, which is similar to userfaultfd in this respect, has been exploited in [4, 5] for similar outcome.
This small patch series adds a new flag to userfaultfd(2) that allows callers to give up the ability to handle kernel-mode faults with the resulting UFFD file object. It then adds a 'user-mode only' option to the unprivileged_userfaultfd sysctl knob to require unprivileged callers to use this new flag.
The purpose of this new interface is to decrease the chance of an unprivileged userfaultfd user taking advantage of userfaultfd to enhance security vulnerabilities by lengthening the race window in kernel code.
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://duasynt.com/blog/linux-kernel-heap-spray
[3] https://duasynt.com/blog/cve-2016-6187-heap-off-by-one-exploit
[4] https://googleprojectzero.blogspot.com/2016/06/exploiting-recursion-in-linux-kernel_20.html
[5] https://bugs.chromium.org/p/project-zero/issues/detail?id=808
This patch (of 2):
userfaultfd handles page faults from both user and kernel code. Add a new UFFD_USER_MODE_ONLY flag for userfaultfd(2) that makes the resulting userfaultfd object refuse to handle faults from kernel mode, treating these faults as if SIGBUS were always raised, causing the kernel code to fail with EFAULT.
A future patch adds a knob allowing administrators to give some processes the ability to create userfaultfd file objects only if they pass UFFD_USER_MODE_ONLY, reducing the likelihood that these processes will exploit userfaultfd's ability to delay kernel page faults to open timing windows for future exploits.
---
fs/userfaultfd.c | 10 +++++++++- include/uapi/linux/userfaultfd.h | 9 +++++++++ 2 files changed, 18 insertions(+), 1 deletion(-)
fs/userfaultfd.c renamed from fs/userfaultfd.c~add-uffd_user_mode_only +9 -1
@@ -405,6 +405,13 @@ vm_fault_t handle_userfault(struct vm_faif (ctx->features &UFFD_FEATURE_SIGBUS ) goto out; +if ((vmf->flags &FAULT_FLAG_USER ) ==0 && + ctx->flags &UFFD_USER_MODE_ONLY ) { +printk_once (KERN_WARNING "uffd: Set unprivileged_userfaultfd " +"sysctl knob to 1 if kernel faults must be handled " +"without obtaining CAP_SYS_PTRACE capability\n" ); + goto out; + }/* * If it's already released don't get it. This avoids to loop
@@ -1965,10 +1972,11 @@ SYSCALL_DEFINE1(userfaultfd, int, flags)BUG_ON (!current->mm);/* Check the UFFD_* constants for consistency. */ +BUILD_BUG_ON (UFFD_USER_MODE_ONLY &UFFD_SHARED_FCNTL_FLAGS );BUILD_BUG_ON (UFFD_CLOEXEC !=O_CLOEXEC );BUILD_BUG_ON (UFFD_NONBLOCK !=O_NONBLOCK ); -if (flags & ~UFFD_SHARED_FCNTL_FLAGS ) +if (flags & ~(UFFD_SHARED_FCNTL_FLAGS |UFFD_USER_MODE_ONLY ))return -EINVAL ; ctx =kmem_cache_alloc (userfaultfd_ctx_cachep,GFP_KERNEL );
include/uapi/linux/userfaultfd.h renamed from include/uapi/linux/userfaultfd.h~add-uffd_user_mode_only +9 -0
@@ -257,4 +257,13 @@ struct uffdio_writeprotect { __u64 mode; }; +/* +* Flags for the userfaultfd(2) system call itself. +*/ + +/* +* Create a userfaultfd that can handle page faults only in user mode. +*/ +#define UFFD_USER_MODE_ONLY 1 +#endif /* _LINUX_USERFAULTFD_H */
_
Andrew Morton
maintainerPATCH 180/200 userfaultfd: add user-mode only option to unprivileged_userfaultfd sysctl knob
In reply to Andrew MortonFrom: Lokesh Gidra <[email protected]>
Subject: userfaultfd: add user-mode only option to unprivileged_userfaultfd sysctl knob
With this change, when the knob is set to 0, it allows unprivileged users to call userfaultfd, like when it is set to 1, but with the restriction that page faults from only user-mode can be handled. In this mode, an unprivileged user (without SYS_CAP_PTRACE capability) must pass UFFD_USER_MODE_ONLY to userfaultd or the API will fail with EPERM.
This enables administrators to reduce the likelihood that an attacker with access to userfaultfd can delay faulting kernel code to widen timing windows for other exploits.
The default value of this knob is changed to 0. This is required for correct functioning of pipe mutex. However, this will fail postcopy live migration, which will be unnoticeable to the VM guests. To avoid this, set 'vm.userfault = 1' in /sys/sysctl.conf.
The main reason this change is desirable as in the short term is that the Android userland will behave as with the sysctl set to zero. So without this commit, any Linux binary using userfaultfd to manage its memory would behave differently if run within the Android userland. For more details, refer to Andrea's reply [1].
[1] https://lore.kernel.org/lkml/[email protected]/
---
Documentation/admin-guide/sysctl/vm.rst | 15 ++++++++++----- fs/userfaultfd.c | 10 ++++++++-- 2 files changed, 18 insertions(+), 7 deletions(-)
Documentation/admin-guide/sysctl/vm.rst renamed from Documentation/admin-guide/sysctl/vm.rst~add-user-mode-only-option-to-unprivileged_userfaultfd-sysctl-knob +10 -5
@@ -873,12 +873,17 @@ file-backed pages is less than the high unprivileged_userfaultfd ======================== -This flag controls whether unprivileged users can use the userfaultfd -system calls. Set this to 1 to allow unprivileged users to use the -userfaultfd system calls, or set this to 0 to restrict userfaultfd to only -privileged users (with SYS_CAP_PTRACE capability). +This flag controls the mode in which unprivileged users can use the +userfaultfd system calls. Set this to 0 to restrict unprivileged users +to handle page faults in user mode only. In this case, users without +SYS_CAP_PTRACE must pass UFFD_USER_MODE_ONLY in order for userfaultfd to +succeed. Prohibiting use of userfaultfd for handling faults from kernel +mode may make certain vulnerabilities more difficult to exploit. -The default value is 1. +Set this to 1 to allow unprivileged users to use the userfaultfd system +calls without any restrictions. + +The default value is 0. user_reserve_kbytes
fs/userfaultfd.c renamed from fs/userfaultfd.c~add-user-mode-only-option-to-unprivileged_userfaultfd-sysctl-knob +8 -2
@@ -28,7 +28,7 @@#include <linux/security.h> #include <linux/hugetlb.h> -int sysctl_unprivileged_userfaultfd__read_mostly =1 ; +int sysctl_unprivileged_userfaultfd__read_mostly ;static struct kmem_cache *userfaultfd_ctx_cachep__read_mostly ;
@@ -1966,8 +1966,14 @@ SYSCALL_DEFINE1(userfaultfd, int, flags)struct userfaultfd_ctx *ctx;int fd; -if (!sysctl_unprivileged_userfaultfd && !capable (CAP_SYS_PTRACE )) +if (!sysctl_unprivileged_userfaultfd && + (flags &UFFD_USER_MODE_ONLY ) ==0 && + !capable (CAP_SYS_PTRACE )) { +printk_once (KERN_WARNING "uffd: Set unprivileged_userfaultfd " +"sysctl knob to 1 if kernel faults must be handled " +"without obtaining CAP_SYS_PTRACE capability\n" );return -EPERM ; + }BUG_ON (!current->mm);
_
Andrew Morton
maintainerPATCH 181/200 userfaultfd: selftests: make __{s,u}64 format specifiers portable
In reply to Andrew MortonFrom: Axel Rasmussen <[email protected]>
Subject: userfaultfd: selftests: make __{s,u}64 format specifiers portable
On certain platforms (powerpcle is the one on which I ran into this), "%Ld" and "%Lu" are unsuitable for printing __s64 and __u64, respectively, resulting in build warnings. Cast to {u,}int64_t, and use the PRI{d,u}64 macros defined in inttypes.h to print them. This ought to be portable to all platforms.
Splitting this off into a separate macro lets us remove some lines, and get rid of some (I would argue) stylistically odd cases where we joined printf() and exit() into a single statement with a ,.
Finally, this also fixes a "missing braces around initializer" warning when we initialize prms in wp_range().
---
tools/testing/selftests/vm/userfaultfd.c | 81 +++++++++------------ 1 file changed, 35 insertions(+), 46 deletions(-)
tools/testing/selftests/vm/userfaultfd.c renamed from tools/testing/selftests/vm/userfaultfd.c~userfaultfd-selftests-make-__su64-format-specifiers-portable +35 -46
@@ -55,6 +55,8 @@#include <setjmp.h> #include <stdbool.h> #include <assert.h> +#include <inttypes.h> +#include <stdint.h> #include "../kselftest.h"
@@ -135,6 +137,13 @@ static void usage(void)exit (1 ); } +#define uffd_error (code, fmt, ...) \ + do { \ + fprintf(stderr, fmt, ##__VA_ARGS__); \ + fprintf(stderr, ": %" PRId64 "\n", (int64_t)(code)); \ + exit(1); \ + } while (0) +static void uffd_stats_reset (struct uffd_stats *uffd_stats,unsigned long n_cpus) {
@@ -338,7 +347,7 @@ static int my_bcmp(char *str1, char *strstatic void wp_range (int ufd,__u64 start,__u64 len,bool wp) { -struct uffdio_writeprotect prms = {0 }; +struct uffdio_writeprotect prms;/* Write protection page faults */ prms.range.start = start;
@@ -347,7 +356,8 @@ static void wp_range(int ufd, __u64 star prms.mode = wp ?UFFDIO_WRITEPROTECT_MODE_WP :0 ;if (ioctl (ufd,UFFDIO_WRITEPROTECT , &prms)) { -fprintf (stderr,"clear WP failed for address 0x%Lx\n" , start); +fprintf (stderr,"clear WP failed for address 0x%" PRIx64"\n" , + (uint64_t )start);exit (1 ); } }
@@ -481,14 +491,11 @@ static void retry_copy_page(int ufd, strif (ioctl (ufd,UFFDIO_COPY , uffdio_copy)) {/* real retval in ufdio_copy.copy */ if (uffdio_copy->copy != -EEXIST ) { -fprintf (stderr,"UFFDIO_COPY retry error %Ld\n" , - uffdio_copy->copy); -exit (1 ); +uffd_error (uffdio_copy->copy, +"UFFDIO_COPY retry error" ); } - }else { -fprintf (stderr,"UFFDIO_COPY retry unexpected %Ld\n" , - uffdio_copy->copy);exit (1 ); - } + }else +uffd_error (uffdio_copy->copy,"UFFDIO_COPY retry unexpected" ); }static int __copy_page (int ufd,unsigned long offset,bool retry)
@@ -509,14 +516,10 @@ static int __copy_page(int ufd, unsigned uffdio_copy.copy =0 ;if (ioctl (ufd,UFFDIO_COPY , &uffdio_copy)) {/* real retval in ufdio_copy.copy */ -if (uffdio_copy.copy != -EEXIST ) { -fprintf (stderr,"UFFDIO_COPY error %Ld\n" , - uffdio_copy.copy); -exit (1 ); - } +if (uffdio_copy.copy != -EEXIST ) +uffd_error (uffdio_copy.copy,"UFFDIO_COPY error" ); }else if (uffdio_copy.copy != page_size) { -fprintf (stderr,"UFFDIO_COPY unexpected copy %Ld\n" , - uffdio_copy.copy);exit (1 ); +uffd_error (uffdio_copy.copy,"UFFDIO_COPY unexpected copy" ); }else {if (test_uffdio_copy_eexist && retry) { test_uffdio_copy_eexist = false;
@@ -795,7 +798,8 @@ static int userfaultfd_open(int featuresreturn 1 ; }if (uffdio_api.api !=UFFD_API ) { -fprintf (stderr,"UFFDIO_API error %Lu\n" , uffdio_api.api); +fprintf (stderr,"UFFDIO_API error: %" PRIu64"\n" , + (uint64_t )uffdio_api.api);return 1 ; }
@@ -957,13 +961,12 @@ static void retry_uffdio_zeropage(int uf offset);if (ioctl (ufd,UFFDIO_ZEROPAGE , uffdio_zeropage)) {if (uffdio_zeropage->zeropage != -EEXIST ) { -fprintf (stderr,"UFFDIO_ZEROPAGE retry error %Ld\n" , - uffdio_zeropage->zeropage); -exit (1 ); +uffd_error (uffdio_zeropage->zeropage, +"UFFDIO_ZEROPAGE retry error" ); } }else { -fprintf (stderr,"UFFDIO_ZEROPAGE retry unexpected %Ld\n" , - uffdio_zeropage->zeropage);exit (1 ); +uffd_error (uffdio_zeropage->zeropage, +"UFFDIO_ZEROPAGE retry unexpected" ); } }
@@ -972,6 +975,7 @@ static int __uffdio_zeropage(int ufd, unstruct uffdio_zeropage uffdio_zeropage;int ret;unsigned long has_zeropage; +__s64 res; has_zeropage = uffd_test_ops->expected_ioctls & (1 << _UFFDIO_ZEROPAGE);
@@ -983,29 +987,17 @@ static int __uffdio_zeropage(int ufd, un uffdio_zeropage.range.len = page_size; uffdio_zeropage.mode =0 ; ret =ioctl (ufd,UFFDIO_ZEROPAGE , &uffdio_zeropage); + res = uffdio_zeropage.zeropage;if (ret) {/* real retval in ufdio_zeropage.zeropage */ if (has_zeropage) { -if (uffdio_zeropage.zeropage == -EEXIST ) { -fprintf (stderr,"UFFDIO_ZEROPAGE -EEXIST\n" ); -exit (1 ); - }else { -fprintf (stderr,"UFFDIO_ZEROPAGE error %Ld\n" , - uffdio_zeropage.zeropage); -exit (1 ); - } - }else { -if (uffdio_zeropage.zeropage != -EINVAL ) { -fprintf (stderr, -"UFFDIO_ZEROPAGE not -EINVAL %Ld\n" , - uffdio_zeropage.zeropage); -exit (1 ); - } - } +uffd_error (res,"UFFDIO_ZEROPAGE %s" , + res == -EEXIST ?"-EEXIST" :"error" ); + }else if (res != -EINVAL ) +uffd_error (res,"UFFDIO_ZEROPAGE not -EINVAL" ); }else if (has_zeropage) { -if (uffdio_zeropage.zeropage != page_size) { -fprintf (stderr,"UFFDIO_ZEROPAGE unexpected %Ld\n" , - uffdio_zeropage.zeropage);exit (1 ); +if (res != page_size) { +uffd_error (res,"UFFDIO_ZEROPAGE unexpected" ); }else {if (test_uffdio_zeropage_eexist && retry) { test_uffdio_zeropage_eexist = false;
@@ -1014,11 +1006,8 @@ static int __uffdio_zeropage(int ufd, un }return 1 ; } - }else { -fprintf (stderr, -"UFFDIO_ZEROPAGE succeeded %Ld\n" , - uffdio_zeropage.zeropage);exit (1 ); - } + }else +uffd_error (res,"UFFDIO_ZEROPAGE succeeded" );return 0 ; }
_
Andrew Morton
maintainerPATCH 182/200 userfaultfd/selftests: always dump something in modes
In reply to Andrew MortonFrom: Peter Xu <[email protected]>
Subject: userfaultfd/selftests: always dump something in modes
Patch series "userfaultfd: selftests: Small fixes".
Some very trivial fixes that I kept locally to userfaultfd selftest program.
This patch (of 3):
BOUNCE_POLL is a special bit that if cleared it means "READ" instead. Dump that too otherwise we'll see tests with empty modes.
---
tools/testing/selftests/vm/userfaultfd.c | 2 ++ 1 file changed, 2 insertions(+)
tools/testing/selftests/vm/userfaultfd.c renamed from tools/testing/selftests/vm/userfaultfd.c~userfaultfd-selftests-always-dump-something-in-modes +2 -0
@@ -1291,6 +1291,8 @@ static int userfaultfd_stress(void)printf (" ver" );if (bounces &BOUNCE_POLL )printf (" poll" ); +else +printf (" read" );printf (", " );fflush (stdout);
_
Andrew Morton
maintainerPATCH 183/200 userfaultfd/selftests: fix retval check for userfaultfd_open()
In reply to Andrew MortonFrom: Peter Xu <[email protected]>
Subject: userfaultfd/selftests: fix retval check for userfaultfd_open()
userfaultfd_open() returns 1 for errors rather than negatives. Fix it on all the callers so when UFFDIO_API failed the test will bail out.
---
tools/testing/selftests/vm/userfaultfd.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tools/testing/selftests/vm/userfaultfd.c renamed from tools/testing/selftests/vm/userfaultfd.c~userfaultfd-selftests-fix-retval-check-for-userfaultfd_open +4 -4
@@ -1029,7 +1029,7 @@ static int userfaultfd_zeropage_test(voiif (uffd_test_ops->release_pages (area_dst))return 1 ; -if (userfaultfd_open (0 ) <0 ) +if (userfaultfd_open (0 ))return 1 ; uffdio_register.range.start = (unsigned long ) area_dst; uffdio_register.range.len = nr_pages * page_size;
@@ -1079,7 +1079,7 @@ static int userfaultfd_events_test(void) features =UFFD_FEATURE_EVENT_FORK |UFFD_FEATURE_EVENT_REMAP |UFFD_FEATURE_EVENT_REMOVE ; -if (userfaultfd_open (features) <0 ) +if (userfaultfd_open (features))return 1 ;fcntl (uffd,F_SETFL , uffd_flags |O_NONBLOCK );
@@ -1151,7 +1151,7 @@ static int userfaultfd_sig_test(void)return 1 ; features =UFFD_FEATURE_EVENT_FORK |UFFD_FEATURE_SIGBUS ; -if (userfaultfd_open (features) <0 ) +if (userfaultfd_open (features))return 1 ;fcntl (uffd,F_SETFL , uffd_flags |O_NONBLOCK );
@@ -1231,7 +1231,7 @@ static int userfaultfd_stress(void)if (!area_dst)return 1 ; -if (userfaultfd_open (0 ) <0 ) +if (userfaultfd_open (0 ))return 1 ; count_verify =malloc (nr_pages *sizeof (unsigned long long ));
_
Andrew Morton
maintainerPATCH 184/200 userfaultfd/selftests: hint the test runner on required privilege
In reply to Andrew MortonFrom: Peter Xu <[email protected]>
Subject: userfaultfd/selftests: hint the test runner on required privilege
Now userfaultfd test program requires either root or ptrace privilege due to the signal/event tests. When UFFDIO_API failed, hint the test runner about this fact verbosely.
---
tools/testing/selftests/vm/userfaultfd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
tools/testing/selftests/vm/userfaultfd.c renamed from tools/testing/selftests/vm/userfaultfd.c~userfaultfd-selftests-hint-the-test-runner-on-required-privilege +2 -1
@@ -794,7 +794,8 @@ static int userfaultfd_open(int features uffdio_api.api =UFFD_API ; uffdio_api.features = features;if (ioctl (uffd,UFFDIO_API , &uffdio_api)) { -fprintf (stderr,"UFFDIO_API\n" ); +fprintf (stderr,"UFFDIO_API failed.\nPlease make sure to " +"run with either root or ptrace capability.\n" );return 1 ; }if (uffdio_api.api !=UFFD_API ) {
_
Andrew Morton
maintainerPATCH 185/200 mm/zswap: make struct kernel_param_ops definitions const
In reply to Andrew MortonFrom: Joe Perches <[email protected]>
Subject: mm/zswap: make struct kernel_param_ops definitions const
These should be const, so make it so.
---
mm/zswap.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
mm/zswap.c renamed from mm/zswap.c~mm-zswap-make-struct-kernel_param_ops-definitions-const +3 -3
@@ -81,7 +81,7 @@ static bool zswap_pool_reached_full;static bool zswap_enabled =IS_ENABLED (CONFIG_ZSWAP_DEFAULT_ON );static int zswap_enabled_param_set (const char *,const struct kernel_param *); -static struct kernel_param_ops zswap_enabled_param_ops = { +static const struct kernel_param_ops zswap_enabled_param_ops = { .set = zswap_enabled_param_set, .get = param_get_bool, };
@@ -91,7 +91,7 @@ module_param_cb(enabled, &zswap_enabled_static char *zswap_compressor =CONFIG_ZSWAP_COMPRESSOR_DEFAULT ;static int zswap_compressor_param_set (const char *,const struct kernel_param *); -static struct kernel_param_ops zswap_compressor_param_ops = { +static const struct kernel_param_ops zswap_compressor_param_ops = { .set = zswap_compressor_param_set, .get = param_get_charp, .free = param_free_charp,
@@ -102,7 +102,7 @@ module_param_cb(compressor, &zswap_compr/* Compressed storage zpool to use */ static char *zswap_zpool_type =CONFIG_ZSWAP_ZPOOL_DEFAULT ;static int zswap_zpool_param_set (const char *,const struct kernel_param *); -static struct kernel_param_ops zswap_zpool_param_ops = { +static const struct kernel_param_ops zswap_zpool_param_ops = { .set = zswap_zpool_param_set, .get = param_get_charp, .free = param_free_charp,
_
Andrew Morton
maintainerPATCH 186/200 mm/zswap: fix passing zero to 'PTR_ERR' warning
In reply to Andrew MortonFrom: YueHaibing <[email protected]>
Subject: mm/zswap: fix passing zero to 'PTR_ERR' warning
Fix smatch warning:
mm/zswap.c:425 zswap_cpu_comp_prepare() warn: passing zero to 'PTR_ERR'
crypto_alloc_comp() never return NULL, use IS_ERR instead of IS_ERR_OR_NULL to fix this.
---
mm/zswap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/zswap.c renamed from mm/zswap.c~mm-zswap-fix-passing-zero-to-ptr_err-warning +1 -1
@@ -421,7 +421,7 @@ static int zswap_cpu_comp_prepare(unsignreturn 0 ; tfm =crypto_alloc_comp (pool->tfm_name,0 ,0 ); -if (IS_ERR_OR_NULL (tfm)) { +if (IS_ERR (tfm)) {pr_err ("could not alloc crypto comp %s : %ld\n" , pool->tfm_name,PTR_ERR (tfm));return -ENOMEM ;
_
Andrew Morton
maintainerPATCH 187/200 mm/zswap: move to use crypto_acomp API for hardware acceleration
In reply to Andrew MortonFrom: Barry Song <[email protected]>
Subject: mm/zswap: move to use crypto_acomp API for hardware acceleration
Right now, all new ZIP drivers are adapted to crypto_acomp APIs rather than legacy crypto_comp APIs. Tradiontal ZIP drivers like lz4,lzo etc have been also wrapped into acomp via scomp backend. But zswap.c is still using the old APIs. That means zswap won't be able to work on any new ZIP drivers in kernel.
This patch moves to use cryto_acomp APIs to fix the disconnected bridge between new ZIP drivers and zswap. It is probably the first real user to use acomp but perhaps not a good example to demonstrate how multiple acomp requests can be executed in parallel in one acomp instance. frontswap is doing page load and store page by page synchronously. swap_writepage() depends on the completion of frontswap_store() to decide if it should call __swap_writepage() to swap to disk.
However this patch creates multiple acomp instances, so multiple threads running on multiple different cpus can actually do (de)compression parallelly, leveraging the power of multiple ZIP hardware queues. This is also consistent with frontswap's page management model.
The old zswap code uses atomic context and avoids the race conditions while shared resources like zswap_dstmem are accessed. Here since acomp can sleep, per-cpu mutex is used to replace preemption-disable.
While it is possible to make mm/page_io.c and mm/frontswap.c support async (de)compression in some way, the entire design requires careful thinking and performance evaluation. For the first step, the base with fixed connection between ZIP drivers and zswap should be built.
---
mm/zswap.c | 185 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 138 insertions(+), 47 deletions(-)
mm/zswap.c renamed from mm/zswap.c~mm-zswap-move-to-use-crypto_acomp-api-for-hardware-acceleration +138 -47
@@ -24,8 +24,10 @@#include <linux/rbtree.h> #include <linux/swap.h> #include <linux/crypto.h> +#include <linux/scatterlist.h> #include <linux/mempool.h> #include <linux/zpool.h> +#include <crypto/acompress.h> #include <linux/mm_types.h> #include <linux/page-flags.h>
@@ -127,9 +129,17 @@ module_param_named(same_filled_pages_ena* data structures **********************************/ +struct crypto_acomp_ctx { +struct crypto_acomp *acomp; +struct acomp_req *req; +struct crypto_wait wait; +u8 *dstmem; +struct mutex *mutex; +}; +struct zswap_pool {struct zpool *zpool; -struct crypto_comp *__percpu *tfm; +struct crypto_acomp_ctx __percpu *acomp_ctx;struct kref kref;struct list_head list;struct work_struct release_work;
@@ -388,23 +398,43 @@ static struct zswap_entry *zswap_entry_f* per-cpu code **********************************/ static DEFINE_PER_CPU(u8 *, zswap_dstmem); +/* +* If users dynamically change the zpool type and compressor at runtime, i.e. +* zswap is running, zswap can have more than one zpool on one cpu, but they +* are sharing dtsmem. So we need this mutex to be per-cpu. +*/ +static DEFINE_PER_CPU(struct mutex *, zswap_mutex);static int zswap_dstmem_prepare (unsigned int cpu) { +struct mutex *mutex;u8 *dst; dst =kmalloc_node (PAGE_SIZE *2 ,GFP_KERNEL ,cpu_to_node (cpu));if (!dst)return -ENOMEM ; + mutex =kmalloc_node (sizeof (*mutex),GFP_KERNEL ,cpu_to_node (cpu)); +if (!mutex) { +kfree (dst); +return -ENOMEM ; + } + +mutex_init (mutex);per_cpu (zswap_dstmem, cpu) = dst; +per_cpu (zswap_mutex, cpu) = mutex;return 0 ; }static int zswap_dstmem_dead (unsigned int cpu) { +struct mutex *mutex;u8 *dst; + mutex =per_cpu (zswap_mutex, cpu); +kfree (mutex); +per_cpu (zswap_mutex, cpu) =NULL ; + dst =per_cpu (zswap_dstmem, cpu);kfree (dst);per_cpu (zswap_dstmem, cpu) =NULL ;
@@ -415,30 +445,54 @@ static int zswap_dstmem_dead(unsigned instatic int zswap_cpu_comp_prepare (unsigned int cpu,struct hlist_node *node) { struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node); -struct crypto_comp *tfm; - -if (WARN_ON (*per_cpu_ptr (pool->tfm, cpu))) -return 0 ; - - tfm =crypto_alloc_comp (pool->tfm_name,0 ,0 ); -if (IS_ERR (tfm)) { -pr_err ("could not alloc crypto comp %s : %ld\n" , - pool->tfm_name,PTR_ERR (tfm)); +struct crypto_acomp_ctx *acomp_ctx =per_cpu_ptr (pool->acomp_ctx, cpu); +struct crypto_acomp *acomp; +struct acomp_req *req; + + acomp =crypto_alloc_acomp_node (pool->tfm_name,0 ,0 ,cpu_to_node (cpu)); +if (IS_ERR (acomp)) { +pr_err ("could not alloc crypto acomp %s : %ld\n" , + pool->tfm_name,PTR_ERR (acomp)); +return PTR_ERR (acomp); + } + acomp_ctx->acomp = acomp; + + req =acomp_request_alloc (acomp_ctx->acomp); +if (!req) { +pr_err ("could not alloc crypto acomp_request %s\n" , + pool->tfm_name); +crypto_free_acomp (acomp_ctx->acomp);return -ENOMEM ; } - *per_cpu_ptr (pool->tfm, cpu) = tfm; + acomp_ctx->req = req; + +crypto_init_wait (&acomp_ctx->wait); +/* +* if the backend of acomp is async zip, crypto_req_done() will wakeup +* crypto_wait_req(); if the backend of acomp is scomp, the callback +* won't be called, crypto_wait_req() will return without blocking. +*/ +acomp_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , + crypto_req_done, &acomp_ctx->wait); + + acomp_ctx->mutex =per_cpu (zswap_mutex, cpu); + acomp_ctx->dstmem =per_cpu (zswap_dstmem, cpu); +return 0 ; }static int zswap_cpu_comp_dead (unsigned int cpu,struct hlist_node *node) { struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node); -struct crypto_comp *tfm; +struct crypto_acomp_ctx *acomp_ctx =per_cpu_ptr (pool->acomp_ctx, cpu); + +if (!IS_ERR_OR_NULL (acomp_ctx)) { +if (!IS_ERR_OR_NULL (acomp_ctx->req)) +acomp_request_free (acomp_ctx->req); +if (!IS_ERR_OR_NULL (acomp_ctx->acomp)) +crypto_free_acomp (acomp_ctx->acomp); + } - tfm = *per_cpu_ptr (pool->tfm, cpu); -if (!IS_ERR_OR_NULL (tfm)) -crypto_free_comp (tfm); - *per_cpu_ptr (pool->tfm, cpu) =NULL ;return 0 ; }
@@ -561,8 +615,9 @@ static struct zswap_pool *zswap_pool_crepr_debug ("using %s zpool\n" ,zpool_get_type (pool->zpool));strlcpy (pool->tfm_name, compressor,sizeof (pool->tfm_name)); - pool->tfm = alloc_percpu(struct crypto_comp *); -if (!pool->tfm) { + + pool->acomp_ctx =alloc_percpu (*pool->acomp_ctx); +if (!pool->acomp_ctx) {pr_err ("percpu alloc failed\n" ); goto error; }
@@ -585,7 +640,8 @@ static struct zswap_pool *zswap_pool_crereturn pool; error: -free_percpu (pool->tfm); +if (pool->acomp_ctx) +free_percpu (pool->acomp_ctx);if (pool->zpool)zpool_destroy_pool (pool->zpool);kfree (pool);
@@ -596,14 +652,14 @@ static __init struct zswap_pool *__zswap {bool has_comp, has_zpool; - has_comp =crypto_has_comp (zswap_compressor,0 ,0 ); + has_comp =crypto_has_acomp (zswap_compressor,0 ,0 );if (!has_comp &&strcmp (zswap_compressor,CONFIG_ZSWAP_COMPRESSOR_DEFAULT )) {pr_err ("compressor %s not available, using default %s\n" , zswap_compressor,CONFIG_ZSWAP_COMPRESSOR_DEFAULT );param_free_charp (&zswap_compressor); zswap_compressor =CONFIG_ZSWAP_COMPRESSOR_DEFAULT ; - has_comp =crypto_has_comp (zswap_compressor,0 ,0 ); + has_comp =crypto_has_acomp (zswap_compressor,0 ,0 ); }if (!has_comp) { pr_err("default compressor %s not available\n",
@@ -639,7 +695,7 @@ static void zswap_pool_destroy(struct zszswap_pool_debug ("destroying" , pool);cpuhp_state_remove_instance (CPUHP_MM_ZSWP_POOL_PREPARE , &pool->node); -free_percpu (pool->tfm); +free_percpu (pool->acomp_ctx);zpool_destroy_pool (pool->zpool);kfree (pool); }
@@ -723,7 +779,7 @@ static int __zswap_param_set(const char } type = s; }else if (!compressor) { -if (!crypto_has_comp (s,0 ,0 )) { +if (!crypto_has_acomp (s,0 ,0 )) {pr_err ("compressor %s not available\n" , s);return -ENOENT ; }
@@ -774,7 +830,7 @@ static int __zswap_param_set(const char* failed, maybe both compressor and zpool params were bad. * Allow changing this param, so pool creation will succeed * when the other param is changed. We already verified this -* param is ok in the zpool_has_pool() or crypto_has_comp() +* param is ok in the zpool_has_pool() or crypto_has_acomp() * checks above. */ ret =param_set_charp (s, kp);
@@ -876,8 +932,10 @@ static int zswap_writeback_entry(structpgoff_t offset;struct zswap_entry *entry;struct page *page; -struct crypto_comp *tfm; -u8 *src, *dst; +struct scatterlist input, output; +struct crypto_acomp_ctx *acomp_ctx; + +u8 *src;unsigned int dlen;int ret;struct writeback_control wbc = {
@@ -916,14 +974,20 @@ static int zswap_writeback_entry(structcase ZSWAP_SWAPCACHE_NEW :/* page is locked */ /* decompress */ + acomp_ctx =raw_cpu_ptr (entry->pool->acomp_ctx); + dlen =PAGE_SIZE ; src = (u8 *)zhdr +sizeof (struct zswap_header ); - dst =kmap_atomic (page); - tfm = *get_cpu_ptr (entry->pool->tfm); - ret =crypto_comp_decompress (tfm, src, entry->length, - dst, &dlen); -put_cpu_ptr (entry->pool->tfm); -kunmap_atomic (dst); + +mutex_lock (acomp_ctx->mutex); +sg_init_one (&input, src, entry->length); +sg_init_table (&output,1 ); +sg_set_page (&output, page,PAGE_SIZE ,0 ); +acomp_request_set_params (acomp_ctx->req, &input, &output, entry->length, dlen); + ret =crypto_wait_req (crypto_acomp_decompress (acomp_ctx->req), &acomp_ctx->wait); + dlen = acomp_ctx->req->dlen; +mutex_unlock (acomp_ctx->mutex); +BUG_ON (ret);BUG_ON (dlen !=PAGE_SIZE );
@@ -1004,7 +1068,8 @@ static int zswap_frontswap_store(unsigne {struct zswap_tree *tree = zswap_trees[type];struct zswap_entry *entry, *dupentry; -struct crypto_comp *tfm; +struct scatterlist input, output; +struct crypto_acomp_ctx *acomp_ctx;int ret;unsigned int hlen, dlen =PAGE_SIZE ;unsigned long handle, value;
@@ -1074,12 +1139,32 @@ static int zswap_frontswap_store(unsigne }/* compress */ - dst =get_cpu_var (zswap_dstmem); - tfm = *get_cpu_ptr (entry->pool->tfm); - src =kmap_atomic (page); - ret =crypto_comp_compress (tfm, src,PAGE_SIZE , dst, &dlen); -kunmap_atomic (src); -put_cpu_ptr (entry->pool->tfm); + acomp_ctx =raw_cpu_ptr (entry->pool->acomp_ctx); + +mutex_lock (acomp_ctx->mutex); + + dst = acomp_ctx->dstmem; +sg_init_table (&input,1 ); +sg_set_page (&input, page,PAGE_SIZE ,0 ); + +/* zswap_dstmem is of size (PAGE_SIZE * 2). Reflect same in sg_list */ +sg_init_one (&output, dst,PAGE_SIZE *2 ); +acomp_request_set_params (acomp_ctx->req, &input, &output,PAGE_SIZE , dlen); +/* +* it maybe looks a little bit silly that we send an asynchronous request, +* then wait for its completion synchronously. This makes the process look +* synchronous in fact. +* Theoretically, acomp supports users send multiple acomp requests in one +* acomp instance, then get those requests done simultaneously. but in this +* case, frontswap actually does store and load page by page, there is no +* existing method to send the second page before the first page is done +* in one thread doing frontswap. +* but in different threads running on different cpu, we have different +* acomp instance, so multiple threads can do (de)compression in parallel. +*/ + ret =crypto_wait_req (crypto_acomp_compress (acomp_ctx->req), &acomp_ctx->wait); + dlen = acomp_ctx->req->dlen; +if (ret) { ret = -EINVAL ; goto put_dstmem;
@@ -1103,7 +1188,7 @@ static int zswap_frontswap_store(unsignememcpy (buf, &zhdr, hlen);memcpy (buf + hlen, dst, dlen);zpool_unmap_handle (entry->pool->zpool, handle); -put_cpu_var (zswap_dstmem); +mutex_unlock (acomp_ctx->mutex);/* populate entry */ entry->offset = offset;
@@ -1131,7 +1216,7 @@ insert_entry:return 0 ; put_dstmem: -put_cpu_var (zswap_dstmem); +mutex_unlock (acomp_ctx->mutex);zswap_pool_put (entry->pool); freepage:zswap_entry_cache_free (entry);
@@ -1148,7 +1233,8 @@ static int zswap_frontswap_load(unsigned {struct zswap_tree *tree = zswap_trees[type];struct zswap_entry *entry; -struct crypto_comp *tfm; +struct scatterlist input, output; +struct crypto_acomp_ctx *acomp_ctx;u8 *src, *dst;unsigned int dlen;int ret;
@@ -1175,11 +1261,16 @@ static int zswap_frontswap_load(unsigned src =zpool_map_handle (entry->pool->zpool, entry->handle,ZPOOL_MM_RO );if (zpool_evictable (entry->pool->zpool)) src +=sizeof (struct zswap_header ); - dst =kmap_atomic (page); - tfm = *get_cpu_ptr (entry->pool->tfm); - ret =crypto_comp_decompress (tfm, src, entry->length, dst, &dlen); -put_cpu_ptr (entry->pool->tfm); -kunmap_atomic (dst); + + acomp_ctx =raw_cpu_ptr (entry->pool->acomp_ctx); +mutex_lock (acomp_ctx->mutex); +sg_init_one (&input, src, entry->length); +sg_init_table (&output,1 ); +sg_set_page (&output, page,PAGE_SIZE ,0 ); +acomp_request_set_params (acomp_ctx->req, &input, &output, entry->length, dlen); + ret =crypto_wait_req (crypto_acomp_decompress (acomp_ctx->req), &acomp_ctx->wait); +mutex_unlock (acomp_ctx->mutex); +zpool_unmap_handle (entry->pool->zpool, entry->handle);BUG_ON (ret);
_
Andrew Morton
maintainerPATCH 188/200 mm/zsmalloc.c: rework the list_add code in insert_zspage()
In reply to Andrew MortonFrom: Miaohe Lin <[email protected]>
Subject: mm/zsmalloc.c: rework the list_add code in insert_zspage()
Rework the list_add code to make it more readable and simple.
---
mm/zsmalloc.c | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-)
mm/zsmalloc.c renamed from mm/zsmalloc.c~zsmalloc-rework-the-list_add-code-in-insert_zspage +4 -7
@@ -726,13 +726,10 @@ static void insert_zspage(struct size_cl* We want to see more ZS_FULL pages and less almost empty/full. * Put pages with higher ->inuse first. */ -if (head) { -if (get_zspage_inuse (zspage) <get_zspage_inuse (head)) { -list_add (&zspage->list, &head->list); -return ; - } - } -list_add (&zspage->list, &class->fullness_list[fullness]); +if (head &&get_zspage_inuse (zspage) <get_zspage_inuse (head)) +list_add (&zspage->list, &head->list); +else +list_add (&zspage->list, &class->fullness_list[fullness]); }/*
_
Andrew Morton
maintainerPATCH 189/200 mm/process_vm_access: remove redundant initialization of iov_r
In reply to Andrew MortonFrom: Colin Ian King <[email protected]>
Subject: mm/process_vm_access: remove redundant initialization of iov_r
The pointer iov_r is being initialized with a value that is never read and it is being updated later with a new value. The initialization is redundant and can be removed.
Addresses-Coverity: ("Unused value")
---
mm/process_vm_access.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/process_vm_access.c renamed from mm/process_vm_access.c~mm-process_vm_access-remove-redundant-initialization-of-iov_r +1 -1
@@ -260,7 +260,7 @@ static ssize_t process_vm_rw(pid_t pid,struct iovec iovstack_l[UIO_FASTIOV ];struct iovec iovstack_r[UIO_FASTIOV ];struct iovec *iov_l = iovstack_l; -struct iovec *iov_r = iovstack_r; +struct iovec *iov_r;struct iov_iter iter;ssize_t rc;int dir = vm_write ?WRITE :READ ;
_
Andrew Morton
maintainerPATCH 190/200 zram: support page writeback
In reply to Andrew MortonFrom: Minchan Kim <[email protected]>
Subject: zram: support page writeback
There is demand to writeback specific process pages to backing store instead of all idles pages in the system due to storage wear out concerns and to launching latency of apps which are most of the time idle but are critical for resume latency.
This patch extends the writeback knob to support a specific page writeback.
---
Documentation/admin-guide/blockdev/zram.rst | 5 ++++ drivers/block/zram/zram_drv.c | 21 ++++++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-)
Documentation/admin-guide/blockdev/zram.rst renamed from Documentation/admin-guide/blockdev/zram.rst~zram-support-a-page-writeback +5 -0
@@ -334,6 +334,11 @@ Admin can request writeback of those idl With the command, zram writeback idle pages from memory to the storage. +If admin want to write a specific page in zram device to backing device, +they could write a page index into the interface. + + echo "page_index=1251" > /sys/block/zramX/writeback + If there are lots of write IO with flash device, potentially, it has flash wearout problem so that admin needs to design write limitation to guarantee storage health for entire product life.
drivers/block/zram/zram_drv.c renamed from drivers/block/zram/zram_drv.c~zram-support-a-page-writeback +17 -4
@@ -620,15 +620,19 @@ static int read_from_bdev_async(struct zreturn 1 ; } +#define PAGE_WB_SIG "page_index=" + +#define PAGE_WRITEBACK 0#define HUGE_WRITEBACK 1#define IDLE_WRITEBACK 2 +static ssize_t writeback_store (struct device *dev,struct device_attribute *attr,const char *buf,size_t len) {struct zram *zram =dev_to_zram (dev);unsigned long nr_pages = zram->disksize >>PAGE_SHIFT ; -unsigned long index; +unsigned long index =0 ;struct bio bio;struct bio_vec bio_vec;struct page *page;
@@ -640,8 +644,17 @@ static ssize_t writeback_store(struct de mode =IDLE_WRITEBACK ; else if (sysfs_streq(buf, "huge")) mode =HUGE_WRITEBACK ; - else - return -EINVAL; + else { +if (strncmp (buf,PAGE_WB_SIG ,sizeof (PAGE_WB_SIG ) -1 )) +return -EINVAL ; + + ret =kstrtol (buf +sizeof (PAGE_WB_SIG ) -1 ,10 , &index); +if (ret || index >= nr_pages) +return -EINVAL ; + + nr_pages =1 ; + mode =PAGE_WRITEBACK ; + }down_read (&zram->init_lock);if (!init_done (zram)) {
@@ -660,7 +673,7 @@ static ssize_t writeback_store(struct de goto release_init_lock; } -for (index =0 ; index < nr_pages; index++) { +while (nr_pages--) {struct bio_vec bvec; bvec.bv_page = page;
_
Andrew Morton
maintainerPATCH 191/200 zram: add stat to gather incompressible pages since zram set up
In reply to Andrew MortonFrom: Minchan Kim <[email protected]>
Subject: zram: add stat to gather incompressible pages since zram set up
Currently, zram supports the stat via /sys/block/zram/mm_stat to represent how many of incompressible pages are stored at the moment but it couldn't show how many times incompressible pages were wrote down since zram set up. It's also good indication to see how zram is effective in the system.
---
Documentation/admin-guide/blockdev/zram.rst | 1 + drivers/block/zram/zram_drv.c | 6 ++++-- drivers/block/zram/zram_drv.h | 1 + 3 files changed, 6 insertions(+), 2 deletions(-)
Documentation/admin-guide/blockdev/zram.rst renamed from Documentation/admin-guide/blockdev/zram.rst~zram-add-stat-to-gather-incompressible-pages-since-zram-set-up +1 -0
@@ -266,6 +266,7 @@ line of text and contains the following No memory is allocated for such pages. pages_compacted the number of pages freed during compaction huge_pages the number of incompressible pages + huge_pages_since the number of incompressible pages since zram set up ================ ============================================================= File /sys/block/zram<id>/bd_stat
drivers/block/zram/zram_drv.c renamed from drivers/block/zram/zram_drv.c~zram-add-stat-to-gather-incompressible-pages-since-zram-set-up +4 -2
@@ -1084,7 +1084,7 @@ static ssize_t mm_stat_show(struct devic max_used =atomic_long_read (&zram->stats.max_used_pages); ret = scnprintf(buf, PAGE_SIZE, - "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu\n", + "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu %8llu\n", orig_size << PAGE_SHIFT, (u64)atomic64_read(&zram->stats.compr_data_size), mem_used << PAGE_SHIFT,
@@ -1092,7 +1092,8 @@ static ssize_t mm_stat_show(struct devic max_used <<PAGE_SHIFT , (u64 )atomic64_read (&zram->stats.same_pages), pool_stats.pages_compacted, - (u64)atomic64_read(&zram->stats.huge_pages)); + (u64 )atomic64_read (&zram->stats.huge_pages), + (u64)atomic64_read(&zram->stats.huge_pages_since));up_read (&zram->init_lock);return ret;
@@ -1424,6 +1425,7 @@ out:if (comp_len ==PAGE_SIZE ) {zram_set_flag (zram, index,ZRAM_HUGE );atomic64_inc (&zram->stats.huge_pages); +atomic64_inc (&zram->stats.huge_pages_since); }if (flags) {
drivers/block/zram/zram_drv.h renamed from drivers/block/zram/zram_drv.h~zram-add-stat-to-gather-incompressible-pages-since-zram-set-up +1 -0
@@ -78,6 +78,7 @@ struct zram_stats {atomic64_t notify_free;/* no. of swap slot free notifications */ atomic64_t same_pages;/* no. of same element filled pages */ atomic64_t huge_pages;/* no. of huge pages */ +atomic64_t huge_pages_since;/* no. of huge pages since zram set up */ atomic64_t pages_stored;/* no. of pages currently stored */ atomic_long_t max_used_pages;/* no. of maximum pages stored */ atomic64_t writestall;/* no. of write slow paths */
_
Andrew Morton
maintainerPATCH 192/200 zram: break the strict dependency from lzo
In reply to Andrew MortonFrom: Rui Salvaterra <[email protected]>
Subject: zram: break the strict dependency from lzo
Quoted 1 line
From the beginning, the zram block device always enabled
CRYPTO_LZO, since
lzo-rle is hardcoded as the fallback compression algorithm. As a consequence, on systems where another compression algorithm is chosen (e.g. CRYPTO_ZSTD), the lzo kernel module becomes unused, while still having to be built/loaded.
This patch removes the hardcoded lzo-rle dependency and allows the user to select the default compression algorithm for zram at build time. The previous behaviour is kept, as the default algorithm is still lzo-rle.
---
drivers/block/zram/Kconfig | 42 +++++++++++++++++++++++++++++++- drivers/block/zram/zcomp.c | 2 + drivers/block/zram/zram_drv.c | 2 - 3 files changed, 44 insertions(+), 2 deletions(-)
drivers/block/zram/Kconfig renamed from drivers/block/zram/Kconfig~zram-break-the-strict-dependency-from-lzo +41 -1
@@ -2,7 +2,7 @@ config ZRAM tristate "Compressed RAM block device support" depends on BLOCK && SYSFS && ZSMALLOC && CRYPTO - select CRYPTO_LZO + depends on CRYPTO_LZO || CRYPTO_ZSTD || CRYPTO_LZ4 || CRYPTO_LZ4HC || CRYPTO_842 help Creates virtual block devices called /dev/zramX (X = 0, 1, ...). Pages written to these disks are compressed and stored in memory
@@ -14,6 +14,46 @@ config ZRAM See Documentation/admin-guide/blockdev/zram.rst for more information. +choice + prompt "Default zram compressor" + default ZRAM_DEF_COMP_LZORLE + depends on ZRAM + +config ZRAM_DEF_COMP_LZORLE + bool "lzo-rle" + depends on CRYPTO_LZO + +config ZRAM_DEF_COMP_ZSTD + bool "zstd" + depends on CRYPTO_ZSTD + +config ZRAM_DEF_COMP_LZ4 + bool "lz4" + depends on CRYPTO_LZ4 + +config ZRAM_DEF_COMP_LZO + bool "lzo" + depends on CRYPTO_LZO + +config ZRAM_DEF_COMP_LZ4HC + bool "lz4hc" + depends on CRYPTO_LZ4HC + +config ZRAM_DEF_COMP_842 + bool "842" + depends on CRYPTO_842 + +endchoice + +config ZRAM_DEF_COMP + string + default "lzo-rle" if ZRAM_DEF_COMP_LZORLE + default "zstd" if ZRAM_DEF_COMP_ZSTD + default "lz4" if ZRAM_DEF_COMP_LZ4 + default "lzo" if ZRAM_DEF_COMP_LZO + default "lz4hc" if ZRAM_DEF_COMP_LZ4HC + default "842" if ZRAM_DEF_COMP_842 + config ZRAM_WRITEBACK bool "Write back incompressible or idle page to backing device" depends on ZRAM
drivers/block/zram/zcomp.c renamed from drivers/block/zram/zcomp.c~zram-break-the-strict-dependency-from-lzo +2 -0
@@ -15,8 +15,10 @@#include "zcomp.h" static const char *const backends[] = { +#if IS_ENABLED(CONFIG_CRYPTO_LZO)"lzo" ,"lzo-rle" , +#endif #if IS_ENABLED(CONFIG_CRYPTO_LZ4)"lz4" , #endif
drivers/block/zram/zram_drv.c renamed from drivers/block/zram/zram_drv.c~zram-break-the-strict-dependency-from-lzo +1 -1
@@ -42,7 +42,7 @@ static DEFINE_IDR(zram_index_idr);static DEFINE_MUTEX (zram_index_mutex);static int zram_major; -static const char *default_compressor ="lzo-rle" ; +static const char *default_compressor =CONFIG_ZRAM_DEF_COMP ;/* Module params (documentation at end) */ static unsigned int num_devices =1 ;
_
Andrew Morton
maintainerPATCH 193/200 mm: fix kernel-doc markups
In reply to Andrew MortonFrom: Mauro Carvalho Chehab <[email protected]>
Subject: mm: fix kernel-doc markups
Kernel-doc markups should use this format:
identifier - description
Fix some issues on mm files:
1) The definition for get_user_pages_locked() doesn't follow it. Also, it expects a short descrpition at the header, followed by a long one, after the parameters. Fix it.
2) Kernel-doc requires that a kernel-doc markup to be immediately below the function prototype, as otherwise it will rename it. So, move get_pfnblock_flags_mask() description to the right place.
3) Make invalidate_mapping_pagevec() to also follow the expected kernel-doc format.
While here, fix a few minor English syntax issues, as suggested by Matthew:
will used -> will be used similar with -> similar to
---
mm/gup.c | 24 +++++++++++++----------- mm/page_alloc.c | 16 ++++++++-------- mm/truncate.c | 6 +++--- 3 files changed, 24 insertions(+), 22 deletions(-)
mm/gup.c renamed from mm/gup.c~mm-fix-kernel-doc-markups +13 -11
@@ -1845,7 +1845,19 @@ long get_user_pages(unsigned long start,EXPORT_SYMBOL (get_user_pages);/** -* get_user_pages_locked() is suitable to replace the form: +* get_user_pages_locked() - variant of get_user_pages() +* +* @start: starting user address +* @nr_pages: number of pages from start to pin +* @gup_flags: flags modifying lookup behaviour +* @pages: array that receives pointers to the pages pinned. +* Should be at least nr_pages long. Or NULL, if caller +* only intends to ensure the pages are faulted in. +* @locked: pointer to lock flag indicating whether lock is held and +* subsequently whether VM_FAULT_RETRY functionality can be +* utilised. Lock must initially be held. +* +* It is suitable to replace the form: * * mmap_read_lock(mm); * do_something()
@@ -1861,16 +1873,6 @@ EXPORT_SYMBOL(get_user_pages);* if (locked) * mmap_read_unlock(mm); * -* @start: starting user address -* @nr_pages: number of pages from start to pin -* @gup_flags: flags modifying lookup behaviour -* @pages: array that receives pointers to the pages pinned. -* Should be at least nr_pages long. Or NULL, if caller -* only intends to ensure the pages are faulted in. -* @locked: pointer to lock flag indicating whether lock is held and -* subsequently whether VM_FAULT_RETRY functionality can be -* utilised. Lock must initially be held. -* * We can leverage the VM_FAULT_RETRY functionality in the page fault * paths better by using either get_user_pages_locked() or * get_user_pages_unlocked().
mm/page_alloc.c renamed from mm/page_alloc.c~mm-fix-kernel-doc-markups +8 -8
@@ -470,14 +470,6 @@ static inline int pfn_to_bitidx(struct preturn (pfn >> pageblock_order) *NR_PAGEBLOCK_BITS ; } -/** -* get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages -* @page: The page within the block of interest -* @pfn: The target page frame number -* @mask: mask of bits that the caller is interested in -* -* Return: pageblock_bits flags -*/ static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
@@ -496,6 +488,14 @@ unsigned long __get_pfnblock_flags_mask(return (word >> bitidx) & mask; } +/** +* get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages +* @page: The page within the block of interest +* @pfn: The target page frame number +* @mask: mask of bits that the caller is interested in +* +* Return: pageblock_bits flags +*/ unsigned long get_pfnblock_flags_mask (struct page *page,unsigned long pfn,unsigned long mask) {
mm/truncate.c renamed from mm/truncate.c~mm-fix-kernel-doc-markups +3 -3
@@ -643,9 +643,9 @@ EXPORT_SYMBOL(invalidate_mapping_pages);* @end: the offset 'to' which to invalidate (inclusive) * @nr_pagevec: invalidate failed page number for caller * -* This helper is similar with invalidate_mapping_pages, except that it accounts -* for pages that failed to invalidate on a pagevec and count them in -* @nr_pagevec, which will used by the caller. +* This helper is similar to invalidate_mapping_pages(), except that it accounts +* for pages that are likely on a pagevec and counts them in @nr_pagevec, which +* will be used by the caller. */ void invalidate_mapping_pagevec (struct address_space *mapping,pgoff_t start,pgoff_t end,unsigned long *nr_pagevec)
_
Andrew Morton
maintainerPATCH 194/200 mm: use sysfs_emit for struct kobject * uses
In reply to Andrew MortonFrom: Joe Perches <[email protected]>
Subject: mm: use sysfs_emit for struct kobject * uses
Patch series "mm: Convert sysfs sprintf family to sysfs_emit", v2.
Use the new sysfs_emit family and not the sprintf family.
This patch (of 5):
Use the sysfs_emit function instead of the sprintf family.
Done with cocci script as in commit 3c6bff3cf988
("RDMA: Convert sysfs kobject * show functions to use sysfs_emit()")
---
mm/huge_memory.c | 28 ++++++++++++++++------------ mm/hugetlb.c | 13 +++++++------ mm/khugepaged.c | 22 +++++++++++----------- mm/ksm.c | 32 ++++++++++++++++---------------- mm/swap_state.c | 3 ++- 5 files changed, 52 insertions(+), 46 deletions(-)
mm/huge_memory.c renamed from mm/huge_memory.c~mm-use-sysfs_emit-for-struct-kobject-uses +16 -12
@@ -164,11 +164,11 @@ static ssize_t enabled_show(struct kobje struct kobj_attribute *attr, char *buf) { if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags)) - return sprintf(buf, "[always] madvise never\n"); + return sysfs_emit(buf, "[always] madvise never\n"); else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags)) - return sprintf(buf, "always [madvise] never\n"); + return sysfs_emit(buf, "always [madvise] never\n"); else - return sprintf(buf, "always madvise [never]\n"); + return sysfs_emit(buf, "always madvise [never]\n"); } static ssize_t enabled_store(struct kobject *kobj,
@@ -233,14 +233,18 @@ static ssize_t defrag_show(struct kobjec struct kobj_attribute *attr, char *buf) { if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags)) - return sprintf(buf, "[always] defer defer+madvise madvise never\n"); + return sysfs_emit(buf, + "[always] defer defer+madvise madvise never\n");if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG , &transparent_hugepage_flags)) -return sprintf (buf,"always [defer] defer+madvise madvise never\n" ); +return sysfs_emit (buf, +"always [defer] defer+madvise madvise never\n" );if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG , &transparent_hugepage_flags)) -return sprintf (buf,"always defer [defer+madvise] madvise never\n" ); +return sysfs_emit (buf, +"always defer [defer+madvise] madvise never\n" );if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG , &transparent_hugepage_flags)) -return sprintf (buf,"always defer defer+madvise [madvise] never\n" ); -return sprintf (buf,"always defer defer+madvise madvise [never]\n" ); +return sysfs_emit (buf, +"always defer defer+madvise [madvise] never\n" ); +return sysfs_emit (buf,"always defer defer+madvise madvise [never]\n" ); } static ssize_t defrag_store(struct kobject *kobj,
@@ -281,10 +285,10 @@ static struct kobj_attribute defrag_attr__ATTR (defrag,0644 , defrag_show, defrag_store);static ssize_t use_zero_page_show (struct kobject *kobj, -struct kobj_attribute *attr,char *buf) +struct kobj_attribute *attr,char *buf) {return single_hugepage_flag_show (kobj, attr, buf, -TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG ); +TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG ); }static ssize_t use_zero_page_store (struct kobject *kobj,struct kobj_attribute *attr,const char *buf,size_t count)
@@ -296,9 +300,9 @@ static struct kobj_attribute use_zero_pa__ATTR (use_zero_page,0644 , use_zero_page_show, use_zero_page_store);static ssize_t hpage_pmd_size_show (struct kobject *kobj, -struct kobj_attribute *attr,char *buf) +struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%lu\n" ,HPAGE_PMD_SIZE ); +return sysfs_emit (buf,"%lu\n" ,HPAGE_PMD_SIZE ); }static struct kobj_attribute hpage_pmd_size_attr =__ATTR_RO (hpage_pmd_size);
mm/hugetlb.c renamed from mm/hugetlb.c~mm-use-sysfs_emit-for-struct-kobject-uses +7 -6
@@ -2760,7 +2760,7 @@ static ssize_t nr_hugepages_show_common(else nr_huge_pages = h->nr_huge_pages_node[nid]; -return sprintf (buf,"%lu\n" , nr_huge_pages); +return sysfs_emit (buf,"%lu\n" , nr_huge_pages); } static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
@@ -2833,7 +2833,8 @@ HSTATE_ATTR(nr_hugepages);* huge page alloc/free. */ static ssize_t nr_hugepages_mempolicy_show (struct kobject *kobj, -struct kobj_attribute *attr,char *buf) +struct kobj_attribute *attr, +char *buf) {return nr_hugepages_show_common (kobj, attr, buf); }
@@ -2851,7 +2852,7 @@ static ssize_t nr_overcommit_hugepages_s struct kobj_attribute *attr, char *buf) { struct hstate *h = kobj_to_hstate(kobj, NULL); -return sprintf (buf,"%lu\n" , h->nr_overcommit_huge_pages); +return sysfs_emit (buf,"%lu\n" , h->nr_overcommit_huge_pages); } static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
@@ -2889,7 +2890,7 @@ static ssize_t free_hugepages_show(strucelse free_huge_pages = h->free_huge_pages_node[nid]; -return sprintf (buf,"%lu\n" , free_huge_pages); +return sysfs_emit (buf,"%lu\n" , free_huge_pages); }HSTATE_ATTR_RO (free_hugepages);
@@ -2897,7 +2898,7 @@ static ssize_t resv_hugepages_show(struc struct kobj_attribute *attr, char *buf) { struct hstate *h = kobj_to_hstate(kobj, NULL); -return sprintf (buf,"%lu\n" , h->resv_huge_pages); +return sysfs_emit (buf,"%lu\n" , h->resv_huge_pages); }HSTATE_ATTR_RO (resv_hugepages);
@@ -2914,7 +2915,7 @@ static ssize_t surplus_hugepages_show(stelse surplus_huge_pages = h->surplus_huge_pages_node[nid]; -return sprintf (buf,"%lu\n" , surplus_huge_pages); +return sysfs_emit (buf,"%lu\n" , surplus_huge_pages); }HSTATE_ATTR_RO (surplus_hugepages);
mm/khugepaged.c renamed from mm/khugepaged.c~mm-use-sysfs_emit-for-struct-kobject-uses +11 -11
@@ -126,7 +126,7 @@ static ssize_t scan_sleep_millisecs_showstruct kobj_attribute *attr, char *buf) { - return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs); + return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs); } static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
@@ -154,7 +154,7 @@ static ssize_t alloc_sleep_millisecs_shostruct kobj_attribute *attr, char *buf) { - return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs); + return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs); } static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
@@ -182,7 +182,7 @@ static ssize_t pages_to_scan_show(structstruct kobj_attribute *attr, char *buf) { - return sprintf(buf, "%u\n", khugepaged_pages_to_scan); + return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan); } static ssize_t pages_to_scan_store(struct kobject *kobj, struct kobj_attribute *attr,
@@ -207,7 +207,7 @@ static ssize_t pages_collapsed_show(strustruct kobj_attribute *attr, char *buf) { - return sprintf(buf, "%u\n", khugepaged_pages_collapsed); + return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed); }static struct kobj_attribute pages_collapsed_attr =__ATTR_RO (pages_collapsed);
@@ -216,7 +216,7 @@ static ssize_t full_scans_show(struct kostruct kobj_attribute *attr, char *buf) { - return sprintf(buf, "%u\n", khugepaged_full_scans); + return sysfs_emit(buf, "%u\n", khugepaged_full_scans); }static struct kobj_attribute full_scans_attr =__ATTR_RO (full_scans);
@@ -225,7 +225,7 @@ static ssize_t khugepaged_defrag_show(st struct kobj_attribute *attr, char *buf) { return single_hugepage_flag_show(kobj, attr, buf, -TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG ); +TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG ); } static ssize_t khugepaged_defrag_store(struct kobject *kobj, struct kobj_attribute *attr,
@@ -250,7 +250,7 @@ static ssize_t khugepaged_max_ptes_none_struct kobj_attribute *attr, char *buf) { - return sprintf(buf, "%u\n", khugepaged_max_ptes_none); + return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none); } static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj, struct kobj_attribute *attr,
@@ -275,7 +275,7 @@ static ssize_t khugepaged_max_ptes_swap_struct kobj_attribute *attr, char *buf) { - return sprintf(buf, "%u\n", khugepaged_max_ptes_swap); + return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap); } static ssize_t khugepaged_max_ptes_swap_store(struct kobject *kobj,
@@ -299,10 +299,10 @@ static struct kobj_attribute khugepaged_ khugepaged_max_ptes_swap_store);static ssize_t khugepaged_max_ptes_shared_show (struct kobject *kobj, -struct kobj_attribute *attr, -char *buf) +struct kobj_attribute *attr, +char *buf) { -return sprintf (buf,"%u\n" , khugepaged_max_ptes_shared); +return sysfs_emit (buf,"%u\n" , khugepaged_max_ptes_shared); } static ssize_t khugepaged_max_ptes_shared_store(struct kobject *kobj,
mm/ksm.c renamed from mm/ksm.c~mm-use-sysfs_emit-for-struct-kobject-uses +16 -16
@@ -2833,7 +2833,7 @@ static void wait_while_offlining(void)static ssize_t sleep_millisecs_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%u\n" , ksm_thread_sleep_millisecs); +return sysfs_emit (buf,"%u\n" , ksm_thread_sleep_millisecs); } static ssize_t sleep_millisecs_store(struct kobject *kobj,
@@ -2857,7 +2857,7 @@ KSM_ATTR(sleep_millisecs);static ssize_t pages_to_scan_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%u\n" , ksm_thread_pages_to_scan); +return sysfs_emit (buf,"%u\n" , ksm_thread_pages_to_scan); } static ssize_t pages_to_scan_store(struct kobject *kobj,
@@ -2880,7 +2880,7 @@ KSM_ATTR(pages_to_scan);static ssize_t run_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%lu\n" , ksm_run); +return sysfs_emit (buf,"%lu\n" , ksm_run); } static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
@@ -2927,9 +2927,9 @@ KSM_ATTR(run);#ifdef CONFIG_NUMA static ssize_t merge_across_nodes_show (struct kobject *kobj, -struct kobj_attribute *attr,char *buf) +struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%u\n" , ksm_merge_across_nodes); +return sysfs_emit (buf,"%u\n" , ksm_merge_across_nodes); } static ssize_t merge_across_nodes_store(struct kobject *kobj,
@@ -2984,9 +2984,9 @@ KSM_ATTR(merge_across_nodes);#endif static ssize_t use_zero_pages_show (struct kobject *kobj, -struct kobj_attribute *attr,char *buf) +struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%u\n" , ksm_use_zero_pages); +return sysfs_emit (buf,"%u\n" , ksm_use_zero_pages); } static ssize_t use_zero_pages_store(struct kobject *kobj, struct kobj_attribute *attr,
@@ -3008,7 +3008,7 @@ KSM_ATTR(use_zero_pages);static ssize_t max_page_sharing_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%u\n" , ksm_max_page_sharing); +return sysfs_emit (buf,"%u\n" , ksm_max_page_sharing); } static ssize_t max_page_sharing_store(struct kobject *kobj,
@@ -3049,21 +3049,21 @@ KSM_ATTR(max_page_sharing);static ssize_t pages_shared_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%lu\n" , ksm_pages_shared); +return sysfs_emit (buf,"%lu\n" , ksm_pages_shared); }KSM_ATTR_RO (pages_shared);static ssize_t pages_sharing_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%lu\n" , ksm_pages_sharing); +return sysfs_emit (buf,"%lu\n" , ksm_pages_sharing); }KSM_ATTR_RO (pages_sharing);static ssize_t pages_unshared_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%lu\n" , ksm_pages_unshared); +return sysfs_emit (buf,"%lu\n" , ksm_pages_unshared); }KSM_ATTR_RO (pages_unshared);
@@ -3080,21 +3080,21 @@ static ssize_t pages_volatile_show(struc*/ if (ksm_pages_volatile <0 ) ksm_pages_volatile =0 ; -return sprintf (buf,"%ld\n" , ksm_pages_volatile); +return sysfs_emit (buf,"%ld\n" , ksm_pages_volatile); }KSM_ATTR_RO (pages_volatile);static ssize_t stable_node_dups_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%lu\n" , ksm_stable_node_dups); +return sysfs_emit (buf,"%lu\n" , ksm_stable_node_dups); }KSM_ATTR_RO (stable_node_dups);static ssize_t stable_node_chains_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%lu\n" , ksm_stable_node_chains); +return sysfs_emit (buf,"%lu\n" , ksm_stable_node_chains); }KSM_ATTR_RO (stable_node_chains);
@@ -3103,7 +3103,7 @@ stable_node_chains_prune_millisecs_show(struct kobj_attribute *attr, char *buf) { - return sprintf(buf, "%u\n", ksm_stable_node_chains_prune_millisecs); + return sysfs_emit(buf, "%u\n", ksm_stable_node_chains_prune_millisecs); } static ssize_t
@@ -3127,7 +3127,7 @@ KSM_ATTR(stable_node_chains_prune_millisstatic ssize_t full_scans_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%lu\n" , ksm_scan.seqnr); +return sysfs_emit (buf,"%lu\n" , ksm_scan.seqnr); }KSM_ATTR_RO (full_scans);
mm/swap_state.c renamed from mm/swap_state.c~mm-use-sysfs_emit-for-struct-kobject-uses +2 -1
@@ -902,7 +902,8 @@ struct page *swapin_readahead(swp_entry_static ssize_t vma_ra_enabled_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -return sprintf (buf,"%s\n" , enable_vma_readahead ?"true" :"false" ); +return sysfs_emit (buf,"%s\n" , + enable_vma_readahead ?"true" :"false" ); } static ssize_t vma_ra_enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
_
Andrew Morton
maintainerPATCH 195/200 mm: huge_memory: convert remaining use of sprintf to sysfs_emit and neatening
In reply to Andrew MortonFrom: Joe Perches <[email protected]>
Subject: mm: huge_memory: convert remaining use of sprintf to sysfs_emit and neatening
Convert the only use of sprintf with struct kobject * that the cocci script could not convert.
Miscellanea:
o Neaten the uses of a constant string with sysfs_emit to use a const char * to reduce overall object size
---
mm/huge_memory.c | 52 ++++++++++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 21 deletions(-)
mm/huge_memory.c renamed from mm/huge_memory.c~mm-huge_memory-convert-remaining-use-of-sprintf-to-sysfs_emit-and-neatening +31 -21
@@ -163,12 +163,17 @@ static struct shrinker huge_zero_page_shstatic ssize_t enabled_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { +const char *output; +if (test_bit (TRANSPARENT_HUGEPAGE_FLAG , &transparent_hugepage_flags)) -return sysfs_emit (buf,"[always] madvise never\n" ); -else if (test_bit (TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG , &transparent_hugepage_flags)) -return sysfs_emit (buf,"always [madvise] never\n" ); + output ="[always] madvise never" ; +else if (test_bit (TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG , + &transparent_hugepage_flags)) + output ="always [madvise] never" ;else -return sysfs_emit (buf,"always madvise [never]\n" ); + output ="always madvise [never]" ; + +return sysfs_emit (buf,"%s\n" , output); } static ssize_t enabled_store(struct kobject *kobj,
@@ -200,11 +205,11 @@ static struct kobj_attribute enabled_att__ATTR (enabled,0644 , enabled_show, enabled_store);ssize_t single_hugepage_flag_show (struct kobject *kobj, -struct kobj_attribute *attr,char *buf, -enum transparent_hugepage_flag flag) +struct kobj_attribute *attr,char *buf, +enum transparent_hugepage_flag flag) { -return sprintf (buf,"%d\n" , - !!test_bit (flag, &transparent_hugepage_flags)); +return sysfs_emit (buf,"%d\n" , + !!test_bit (flag, &transparent_hugepage_flags)); } ssize_t single_hugepage_flag_store(struct kobject *kobj,
@@ -232,19 +237,24 @@ ssize_t single_hugepage_flag_store(strucstatic ssize_t defrag_show (struct kobject *kobj,struct kobj_attribute *attr,char *buf) { -if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG , &transparent_hugepage_flags)) -return sysfs_emit (buf, -"[always] defer defer+madvise madvise never\n" ); -if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG , &transparent_hugepage_flags)) -return sysfs_emit (buf, -"always [defer] defer+madvise madvise never\n" ); -if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG , &transparent_hugepage_flags)) -return sysfs_emit (buf, -"always defer [defer+madvise] madvise never\n" ); -if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG , &transparent_hugepage_flags)) -return sysfs_emit (buf, -"always defer defer+madvise [madvise] never\n" ); -return sysfs_emit (buf,"always defer defer+madvise madvise [never]\n" ); +const char *output; + +if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG , + &transparent_hugepage_flags)) + output ="[always] defer defer+madvise madvise never" ; +else if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG , + &transparent_hugepage_flags)) + output ="always [defer] defer+madvise madvise never" ; +else if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG , + &transparent_hugepage_flags)) + output ="always defer [defer+madvise] madvise never" ; +else if (test_bit (TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG , + &transparent_hugepage_flags)) + output ="always defer defer+madvise [madvise] never" ; +else + output ="always defer defer+madvise madvise [never]" ; + +return sysfs_emit (buf,"%s\n" , output); } static ssize_t defrag_store(struct kobject *kobj,
_
Andrew Morton
maintainerPATCH 196/200 mm:backing-dev: use sysfs_emit in macro defining functions
In reply to Andrew MortonFrom: Joe Perches <[email protected]>
Subject: mm:backing-dev: use sysfs_emit in macro defining functions
The cocci script used in commit bdacbb8d04f ("mm: Use sysfs_emit for struct kobject * uses") does not convert the name##_show macro because the macro uses concatenation via ##.
Convert it by hand.
---
mm/backing-dev.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
mm/backing-dev.c renamed from mm/backing-dev.c~mm-backing-dev-use-sysfs_emit-in-macro-defining-functions +4 -4
@@ -150,11 +150,11 @@ static ssize_t read_ahead_kb_store(struc#define BDI_SHOW (name, expr) \ static ssize_t name##_show(struct device *dev, \ - struct device_attribute *attr, char *page) \ + struct device_attribute *attr, char *buf) \ { \ struct backing_dev_info *bdi = dev_get_drvdata(dev); \ \ - return snprintf(page, PAGE_SIZE-1, "%lld\n", (long long)expr); \ + return sysfs_emit(buf, "%lld\n", (long long)expr); \ } \ static DEVICE_ATTR_RW(name);
@@ -200,11 +200,11 @@ BDI_SHOW(max_ratio, bdi->max_ratio)static ssize_t stable_pages_required_show (struct device *dev,struct device_attribute *attr, -char *page) +char *buf) {dev_warn_once (dev,"the stable_pages_required attribute has been removed. Use the stable_writes queue attribute instead.\n" ); -return snprintf (page,PAGE_SIZE -1 ,"%d\n" ,0 ); +return sysfs_emit (buf,"%d\n" ,0 ); }static DEVICE_ATTR_RO (stable_pages_required);
_
Andrew Morton
maintainerPATCH 197/200 mm: shmem: convert shmem_enabled_show to use sysfs_emit_at
In reply to Andrew MortonFrom: Joe Perches <[email protected]>
Subject: mm: shmem: convert shmem_enabled_show to use sysfs_emit_at
Update the function to use sysfs_emit_at while neatening the uses of sprintf and overwriting the last space char with a newline to avoid possible output buffer overflow.
Miscellanea:
o in shmem_enabled_show, the removal of the indirected use of fmt allows __printf verification
---
mm/shmem.c | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-)
mm/shmem.c renamed from mm/shmem.c~mm-shmem-convert-shmem_enabled_show-to-use-sysfs_emit_at +12 -9
@@ -4020,7 +4020,7 @@ out2: #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS) static ssize_t shmem_enabled_show(struct kobject *kobj, - struct kobj_attribute *attr, char *buf) + struct kobj_attribute *attr, char *buf) { static const int values[] = { SHMEM_HUGE_ALWAYS,
@@ -4030,16 +4030,19 @@ static ssize_t shmem_enabled_show(structSHMEM_HUGE_DENY , SHMEM_HUGE_FORCE, }; -int i, count; +int len =0 ; +int i; -for (i =0 , count =0 ; i <ARRAY_SIZE (values); i++) { -const char *fmt = shmem_huge == values[i] ?"[%s] " :"%s " ; - - count +=sprintf (buf + count, fmt, -shmem_format_huge (values[i])); +for (i =0 ; i <ARRAY_SIZE (values); i++) { + len +=sysfs_emit_at (buf, len, + shmem_huge == values[i] ?"%s[%s]" :"%s%s" , + i ?" " :"" , +shmem_format_huge (values[i])); } - buf[count -1 ] ='\n' ; -return count; + + len +=sysfs_emit_at (buf, len,"\n" ); + +return len; } static ssize_t shmem_enabled_store(struct kobject *kobj,
_
Andrew Morton
maintainerPATCH 198/200 mm: slub: convert sysfs sprintf family to sysfs_emit/sysfs_emit_at
In reply to Andrew MortonFrom: Joe Perches <[email protected]>
Subject: mm: slub: convert sysfs sprintf family to sysfs_emit/sysfs_emit_at
Convert the unbounded uses of sprintf to sysfs_emit.
A few conversions may now not end in a newline if the output buffer is overflowed.
---
mm/slub.c | 146 ++++++++++++++++++++++++++-------------------------- 1 file changed, 75 insertions(+), 71 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-convert-sysfs-sprintf-family-to-sysfs_emit-sysfs_emit_at +75 -71
@@ -4724,7 +4724,7 @@ static void process_slab(struct loc_trac }static int list_locations (struct kmem_cache *s,char *buf, -enum track_item alloc) +enum track_item alloc) {int len =0 ;unsigned long i;
@@ -4734,7 +4734,7 @@ static int list_locations(struct kmem_caif (!alloc_loc_track (&t,PAGE_SIZE /sizeof (struct location ),GFP_KERNEL )) { -return sprintf (buf,"Out of memory\n" ); +return sysfs_emit (buf,"Out of memory\n" ); }/* Push back cpu slabs */ flush_all (s);
@@ -4757,50 +4757,45 @@ static int list_locations(struct kmem_cafor (i =0 ; i < t.count; i++) {struct location *l = &t.loc[i]; -if (len >PAGE_SIZE -KSYM_SYMBOL_LEN -100 ) -break ; - len +=sprintf (buf + len,"%7ld " , l->count); + len +=sysfs_emit_at (buf, len,"%7ld " , l->count);if (l->addr) - len +=sprintf (buf + len,"%pS" , (void *)l->addr); + len +=sysfs_emit_at (buf, len,"%pS" , (void *)l->addr);else - len +=sprintf (buf + len,"<not-available>" ); + len +=sysfs_emit_at (buf, len,"<not-available>" ); -if (l->sum_time != l->min_time) { - len +=sprintf (buf + len," age=%ld/%ld/%ld" , - l->min_time, - (long )div_u64 (l->sum_time, l->count), - l->max_time); - }else - len +=sprintf (buf + len," age=%ld" , - l->min_time); +if (l->sum_time != l->min_time) + len +=sysfs_emit_at (buf, len," age=%ld/%ld/%ld" , + l->min_time, + (long )div_u64 (l->sum_time, + l->count), + l->max_time); +else + len +=sysfs_emit_at (buf, len," age=%ld" , l->min_time);if (l->min_pid != l->max_pid) - len +=sprintf (buf + len," pid=%ld-%ld" , - l->min_pid, l->max_pid); + len +=sysfs_emit_at (buf, len," pid=%ld-%ld" , + l->min_pid, l->max_pid);else - len +=sprintf (buf + len," pid=%ld" , - l->min_pid); + len +=sysfs_emit_at (buf, len," pid=%ld" , + l->min_pid);if (num_online_cpus () >1 && - !cpumask_empty (to_cpumask (l->cpus)) && - len <PAGE_SIZE -60 ) - len +=scnprintf (buf + len,PAGE_SIZE - len -50 , -" cpus=%*pbl" , -cpumask_pr_args (to_cpumask (l->cpus))); - -if (nr_online_nodes >1 && !nodes_empty (l->nodes) && - len <PAGE_SIZE -60 ) - len +=scnprintf (buf + len,PAGE_SIZE - len -50 , -" nodes=%*pbl" , -nodemask_pr_args (&l->nodes)); + !cpumask_empty (to_cpumask (l->cpus))) + len +=sysfs_emit_at (buf, len," cpus=%*pbl" , +cpumask_pr_args (to_cpumask (l->cpus))); + +if (nr_online_nodes >1 && !nodes_empty (l->nodes)) + len +=sysfs_emit_at (buf, len," nodes=%*pbl" , +nodemask_pr_args (&l->nodes)); - len +=sprintf (buf + len,"\n" ); + len +=sysfs_emit_at (buf, len,"\n" ); }free_loc_track (&t);if (!t.count) - len +=sprintf (buf,"No data\n" ); + len +=sysfs_emit_at (buf, len,"No data\n" ); + return len; }#endif /* CONFIG_SLUB_DEBUG */
@@ -4897,12 +4892,13 @@ __setup("slub_memcg_sysfs=", setup_slub_#endif static ssize_t show_slab_objects (struct kmem_cache *s, -char *buf,unsigned long flags) +char *buf,unsigned long flags) {unsigned long total =0 ;int node;int x;unsigned long *nodes; +int len =0 ; nodes =kcalloc (nr_node_ids,sizeof (unsigned long ),GFP_KERNEL );if (!nodes)
@@ -4991,15 +4987,19 @@ static ssize_t show_slab_objects(struct nodes[node] += x; } } - x =sprintf (buf,"%lu" , total); + + len +=sysfs_emit_at (buf, len,"%lu" , total);#ifdef CONFIG_NUMA -for (node =0 ; node < nr_node_ids; node++) +for (node =0 ; node < nr_node_ids; node++) {if (nodes[node]) - x +=sprintf (buf + x," N%d=%lu" , - node, nodes[node]); + len +=sysfs_emit_at (buf, len," N%d=%lu" , + node, nodes[node]); + }#endif + len +=sysfs_emit_at (buf, len,"\n" );kfree (nodes); -return x +sprintf (buf + x,"\n" ); + +return len; }#define to_slab_attr (n) container_of(n, struct slab_attribute, attr)
@@ -5021,37 +5021,37 @@ struct slab_attribute {static ssize_t slab_size_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%u\n" , s->size); +return sysfs_emit (buf,"%u\n" , s->size); }SLAB_ATTR_RO (slab_size);static ssize_t align_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%u\n" , s->align); +return sysfs_emit (buf,"%u\n" , s->align); }SLAB_ATTR_RO (align);static ssize_t object_size_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%u\n" , s->object_size); +return sysfs_emit (buf,"%u\n" , s->object_size); }SLAB_ATTR_RO (object_size);static ssize_t objs_per_slab_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%u\n" ,oo_objects (s->oo)); +return sysfs_emit (buf,"%u\n" ,oo_objects (s->oo)); }SLAB_ATTR_RO (objs_per_slab);static ssize_t order_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%u\n" ,oo_order (s->oo)); +return sysfs_emit (buf,"%u\n" ,oo_order (s->oo)); }SLAB_ATTR_RO (order);static ssize_t min_partial_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%lu\n" , s->min_partial); +return sysfs_emit (buf,"%lu\n" , s->min_partial); } static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
@@ -5071,7 +5071,7 @@ SLAB_ATTR(min_partial);static ssize_t cpu_partial_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%u\n" ,slub_cpu_partial (s)); +return sysfs_emit (buf,"%u\n" ,slub_cpu_partial (s)); } static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
@@ -5096,13 +5096,13 @@ static ssize_t ctor_show(struct kmem_cac {if (!s->ctor)return 0 ; -return sprintf (buf,"%pS\n" , s->ctor); +return sysfs_emit (buf,"%pS\n" , s->ctor); }SLAB_ATTR_RO (ctor);static ssize_t aliases_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , s->refcount <0 ?0 : s->refcount -1 ); +return sysfs_emit (buf,"%d\n" , s->refcount <0 ?0 : s->refcount -1 ); }SLAB_ATTR_RO (aliases);
@@ -5135,7 +5135,7 @@ static ssize_t slabs_cpu_partial_show(stint objects =0 ;int pages =0 ;int cpu; -int len; +int len =0 ;for_each_online_cpu (cpu) {struct page *page;
@@ -5148,52 +5148,53 @@ static ssize_t slabs_cpu_partial_show(st } } - len =sprintf (buf,"%d(%d)" , objects, pages); + len +=sysfs_emit_at (buf, len,"%d(%d)" , objects, pages);#ifdef CONFIG_SMP for_each_online_cpu (cpu) {struct page *page; page =slub_percpu_partial (per_cpu_ptr (s->cpu_slab, cpu)); - -if (page && len <PAGE_SIZE -20 ) - len +=sprintf (buf + len," C%d=%d(%d)" , cpu, - page->pobjects, page->pages); +if (page) + len +=sysfs_emit_at (buf, len," C%d=%d(%d)" , + cpu, page->pobjects, page->pages); }#endif -return len +sprintf (buf + len,"\n" ); + len +=sysfs_emit_at (buf, len,"\n" ); + +return len; }SLAB_ATTR_RO (slabs_cpu_partial);static ssize_t reclaim_account_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_RECLAIM_ACCOUNT )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_RECLAIM_ACCOUNT )); }SLAB_ATTR_RO (reclaim_account);static ssize_t hwcache_align_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_HWCACHE_ALIGN )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_HWCACHE_ALIGN )); }SLAB_ATTR_RO (hwcache_align);#ifdef CONFIG_ZONE_DMA static ssize_t cache_dma_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_CACHE_DMA )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_CACHE_DMA )); }SLAB_ATTR_RO (cache_dma);#endif static ssize_t usersize_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%u\n" , s->usersize); +return sysfs_emit (buf,"%u\n" , s->usersize); }SLAB_ATTR_RO (usersize);static ssize_t destroy_by_rcu_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_TYPESAFE_BY_RCU )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_TYPESAFE_BY_RCU )); }SLAB_ATTR_RO (destroy_by_rcu);
@@ -5212,33 +5213,33 @@ SLAB_ATTR_RO(total_objects);static ssize_t sanity_checks_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_CONSISTENCY_CHECKS )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_CONSISTENCY_CHECKS )); }SLAB_ATTR_RO (sanity_checks);static ssize_t trace_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_TRACE )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_TRACE )); }SLAB_ATTR_RO (trace);static ssize_t red_zone_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_RED_ZONE )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_RED_ZONE )); }SLAB_ATTR_RO (red_zone);static ssize_t poison_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_POISON )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_POISON )); }SLAB_ATTR_RO (poison);static ssize_t store_user_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_STORE_USER )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_STORE_USER )); }SLAB_ATTR_RO (store_user);
@@ -5282,7 +5283,7 @@ SLAB_ATTR_RO(free_calls);#ifdef CONFIG_FAILSLAB static ssize_t failslab_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%d\n" , !!(s->flags &SLAB_FAILSLAB )); +return sysfs_emit (buf,"%d\n" , !!(s->flags &SLAB_FAILSLAB )); }SLAB_ATTR_RO (failslab);#endif
@@ -5306,7 +5307,7 @@ SLAB_ATTR(shrink);#ifdef CONFIG_NUMA static ssize_t remote_node_defrag_ratio_show (struct kmem_cache *s,char *buf) { -return sprintf (buf,"%u\n" , s->remote_node_defrag_ratio /10 ); +return sysfs_emit (buf,"%u\n" , s->remote_node_defrag_ratio /10 ); } static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
@@ -5333,7 +5334,7 @@ static int show_stat(struct kmem_cache * {unsigned long sum =0 ;int cpu; -int len; +int len =0 ;int *data =kmalloc_array (nr_cpu_ids,sizeof (int ),GFP_KERNEL );if (!data)
@@ -5346,16 +5347,19 @@ static int show_stat(struct kmem_cache * sum += x; } - len =sprintf (buf,"%lu" , sum); + len +=sysfs_emit_at (buf, len,"%lu" , sum);#ifdef CONFIG_SMP for_each_online_cpu (cpu) { -if (data[cpu] && len <PAGE_SIZE -20 ) - len +=sprintf (buf + len," C%d=%u" , cpu, data[cpu]); +if (data[cpu]) + len +=sysfs_emit_at (buf, len," C%d=%u" , + cpu, data[cpu]); }#endif kfree (data); -return len +sprintf (buf + len,"\n" ); + len +=sysfs_emit_at (buf, len,"\n" ); + +return len; }static void clear_stat (struct kmem_cache *s,enum stat_item si)
_
Andrew Morton
maintainerPATCH 199/200 mm: fix fall-through warnings for Clang
In reply to Andrew MortonFrom: "Gustavo A. R. Silva" <[email protected]>
Subject: mm: fix fall-through warnings for Clang
In preparation to enable -Wimplicit-fallthrough for Clang, fix a couple of warnings by explicitly adding a break statement instead of just letting the code fall through to the next, and by adding a fallthrough pseudo-keyword in places where the code is intended to fall through.
---
mm/mm_init.c | 1 + mm/vmscan.c | 1 + 2 files changed, 2 insertions(+)
mm/mm_init.c renamed from mm/mm_init.c~mm-fix-fall-through-warnings-for-clang +1 -0
@@ -173,6 +173,7 @@ static int __meminit mm_compute_batch_nocase MEM_ONLINE :case MEM_OFFLINE :mm_compute_batch (sysctl_overcommit_memory); +break ;default :break ; }
mm/vmscan.c renamed from mm/vmscan.c~mm-fix-fall-through-warnings-for-clang +1 -0
@@ -1369,6 +1369,7 @@ static unsigned int shrink_page_list(strif (PageDirty (page) ||PageWriteback (page)) goto keep_locked; mapping =page_mapping (page); + fallthrough;case PAGE_CLEAN : ;/* try to free the page below */ }
_
Andrew Morton
maintainerPATCH 200/200 mm: cleanup kstrto*() usage
In reply to Andrew MortonFrom: Alexey Dobriyan <[email protected]>
Subject: mm: cleanup kstrto*() usage
Range checks can folded into proper conversion function. kstrto*() exist for all arithmetic types.
---
mm/khugepaged.c | 18 +++++++++--------- mm/ksm.c | 18 +++++++++--------- 2 files changed, 18 insertions(+), 18 deletions(-)
mm/khugepaged.c renamed from mm/khugepaged.c~mm-cleanup-kstrto-usage +9 -9
@@ -133,11 +133,11 @@ static ssize_t scan_sleep_millisecs_storstruct kobj_attribute *attr, const char *buf, size_t count) { - unsigned long msecs; + unsigned int msecs;int err; - err =kstrtoul (buf,10 , &msecs); -if (err || msecs >UINT_MAX ) + err =kstrtouint (buf,10 , &msecs); +if (err)return -EINVAL ; khugepaged_scan_sleep_millisecs = msecs;
@@ -161,11 +161,11 @@ static ssize_t alloc_sleep_millisecs_stostruct kobj_attribute *attr, const char *buf, size_t count) { - unsigned long msecs; + unsigned int msecs;int err; - err =kstrtoul (buf,10 , &msecs); -if (err || msecs >UINT_MAX ) + err =kstrtouint (buf,10 , &msecs); +if (err)return -EINVAL ; khugepaged_alloc_sleep_millisecs = msecs;
@@ -188,11 +188,11 @@ static ssize_t pages_to_scan_store(strucstruct kobj_attribute *attr, const char *buf, size_t count) { + unsigned int pages;int err; -unsigned long pages; - err =kstrtoul (buf,10 , &pages); -if (err || !pages || pages >UINT_MAX ) + err =kstrtouint (buf,10 , &pages); +if (err || !pages)return -EINVAL ; khugepaged_pages_to_scan = pages;
mm/ksm.c renamed from mm/ksm.c~mm-cleanup-kstrto-usage +9 -9
@@ -2840,11 +2840,11 @@ static ssize_t sleep_millisecs_store(strstruct kobj_attribute *attr, const char *buf, size_t count) { - unsigned long msecs; + unsigned int msecs;int err; - err =kstrtoul (buf,10 , &msecs); -if (err || msecs >UINT_MAX ) + err =kstrtouint (buf,10 , &msecs); +if (err)return -EINVAL ; ksm_thread_sleep_millisecs = msecs;
@@ -2864,11 +2864,11 @@ static ssize_t pages_to_scan_store(strucstruct kobj_attribute *attr, const char *buf, size_t count) { + unsigned int nr_pages;int err; -unsigned long nr_pages; - err =kstrtoul (buf,10 , &nr_pages); -if (err || nr_pages >UINT_MAX ) + err =kstrtouint (buf,10 , &nr_pages); +if (err)return -EINVAL ; ksm_thread_pages_to_scan = nr_pages;
@@ -2886,11 +2886,11 @@ static ssize_t run_show(struct kobject *static ssize_t run_store (struct kobject *kobj,struct kobj_attribute *attr,const char *buf,size_t count) { +unsigned int flags;int err; -unsigned long flags; - err =kstrtoul (buf,10 , &flags); -if (err || flags >UINT_MAX ) + err =kstrtouint (buf,10 , &flags); +if (err)return -EINVAL ;if (flags >KSM_RUN_UNMERGE )return -EINVAL ;
_
Quoted 2 lines · Andrew Morton
200 patches, based on
2c85ebc57b3e1817b6ce1a6b703928e113a90442.
I haven't actually processed the patches yet, but I have a question for Konstantin wrt b4.
All the patches except for _one_ get a nice little green check-mark next to them when I use 'git am' on this series.
The one that did not was [patch 192/200].
I have no idea why - and it doesn't matter a lot to me, it just stood out as being different. I'm assuming Andrew has started doing patch attestation, and that patch failed. But if so, maybe Konstantin wants to know what went wrong.
Konstantin?
Linus
Quoted 7 lines · Linus Torvalds
All the patches except for _one_ get a nice little green check-mark next to them when I use 'git am' on this series.
The one that did not was [patch 192/200].
I have no idea why
Hmm. It looks like that patch is the only one in the series with the ">From" marker in the commit message, from the silly "clarify that this isn't the first line in a new message in mbox format".
And "b4 am" has turned the single ">" into two, making the stupid marker worse, and actually corrupting the end result.
Coincidence? Or cause?
Linus
Quoted 5 lines · Linus Torvalds
Quoted 5 lines
All the patches except for _one_ get a nice little green check-mark next to them when I use 'git am' on this series.
The one that did not was [patch 192/200].
Quoted 8 lines
Quoted 1 line
I have no idea why
Hmm. It looks like that patch is the only one in the series with the ">From" marker in the commit message, from the silly "clarify that this isn't the first line in a new message in mbox format".
And "b4 am" has turned the single ">" into two, making the stupid marker worse, and actually corrupting the end result.
It's a bug in b4 that I overlooked. Public-inbox emits mboxrd-formatted .mbox files, while Python's mailbox.mbox consumes mboxo only. The main distinction between the two is precisely that mboxrd will convert ">From " into ">>From " in an attempt to avoid corruption during escape/unescape (it didn't end up fixing the problem 100% and mostly introduced incompatibilities like this one).
I have a fix in master/stable-0.6.y and I'll release a 0.6.2 before the end of the week.
Thanks for the report.
-K