incoming
Subsystems (107)
Andrew Morton
maintainer147 patches, based on 7d2a07b769330c34b4deabeed939325c77a7ec2f.
Subsystems affected by this patch series:
mm/slub
mm/memory-hotplug
mm/rmap
mm/ioremap
mm/highmem
mm/cleanups
mm/secretmem
mm/kfence
mm/damon
alpha
percpu
procfs
misc
core-kernel
MAINTAINERS
lib
bitops
checkpatch
epoll
init
nilfs2
coredump
fork
pids
criu
kconfig
selftests
ipc
mm/vmscan
scripts
Subsystem: mm/slub
Vlastimil Babka <[email protected]>:
Patch series "SLUB: reduce irq disabled scope and make it RT compatible", v6:
mm, slub: don't call flush_all() from slab_debug_trace_open()
mm, slub: allocate private object map for debugfs listings
mm, slub: allocate private object map for validate_slab_cache()
mm, slub: don't disable irq for debug_check_no_locks_freed()
mm, slub: remove redundant unfreeze_partials() from put_cpu_partial() mm, slub: extract get_partial() from new_slab_objects()
mm, slub: dissolve new_slab_objects() into ___slab_alloc()
mm, slub: return slab page from get_partial() and set c->page afterwards mm, slub: restructure new page checks in ___slab_alloc()
mm, slub: simplify kmem_cache_cpu and tid setup
mm, slub: move disabling/enabling irqs to ___slab_alloc()
mm, slub: do initial checks in ___slab_alloc() with irqs enabled
mm, slub: move disabling irqs closer to get_partial() in ___slab_alloc() mm, slub: restore irqs around calling new_slab()
mm, slub: validate slab from partial list or page allocator before making it cpu slab mm, slub: check new pages with restored irqs
mm, slub: stop disabling irqs around get_partial()
mm, slub: move reset of c->page and freelist out of deactivate_slab() mm, slub: make locking in deactivate_slab() irq-safe
mm, slub: call deactivate_slab() without disabling irqs
mm, slub: move irq control into unfreeze_partials()
mm, slub: discard slabs in unfreeze_partials() without irqs disabled mm, slub: detach whole partial list at once in unfreeze_partials()
mm, slub: separate detaching of partial list in unfreeze_partials() from unfreezing mm, slub: only disable irq with spin_lock in __unfreeze_partials()
mm, slub: don't disable irqs in slub_cpu_dead()
mm, slab: split out the cpu offline variant of flush_slab()
Sebastian Andrzej Siewior <[email protected]>:
mm: slub: move flush_cpu_slab() invocations __free_slab() invocations out of IRQ context
mm: slub: make object_map_lock a raw_spinlock_t
Vlastimil Babka <[email protected]>:
mm, slub: make slab_lock() disable irqs with PREEMPT_RT
mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg mm, slub: use migrate_disable() on PREEMPT_RT
mm, slub: convert kmem_cpu_slab protection to local_lock
Subsystem: mm/memory-hotplug
David Hildenbrand <[email protected]>:
Patch series "memory-hotplug.rst: complete admin-guide overhaul", v3:
memory-hotplug.rst: remove locking details from admin-guide memory-hotplug.rst: complete admin-guide overhaul
Mike Rapoport <[email protected]>:
Patch series "mm: remove pfn_valid_within() and CONFIG_HOLES_IN_ZONE":
mm: remove pfn_valid_within() and CONFIG_HOLES_IN_ZONE
mm: memory_hotplug: cleanup after removal of pfn_valid_within()
David Hildenbrand <[email protected]>:
Patch series "mm/memory_hotplug: preparatory patches for new online policy and memory":
mm/memory_hotplug: use "unsigned long" for PFN in zone_for_pfn_range() mm/memory_hotplug: remove nid parameter from arch_remove_memory() mm/memory_hotplug: remove nid parameter from remove_memory() and friends
ACPI: memhotplug: memory resources cannot be enabled yet
Patch series "mm/memory_hotplug: "auto-movable" online policy and memory groups", v3:
mm: track present early pages per zone
mm/memory_hotplug: introduce "auto-movable" online policy drivers/base/memory: introduce "memory groups" to logically group memory blocks mm/memory_hotplug: track present pages in memory groups
ACPI: memhotplug: use a single static memory group for a single memory device dax/kmem: use a single static memory group for a single probed unit
virtio-mem: use a single dynamic memory group for a single virtio-mem device mm/memory_hotplug: memory group aware "auto-movable" online policy mm/memory_hotplug: improved dynamic memory group aware "auto-movable" online policy
Miaohe Lin <[email protected]>:
Patch series "Cleanup and fixups for memory hotplug":
mm/memory_hotplug: use helper zone_is_zone_device() to simplify the code
Subsystem: mm/rmap
Muchun Song <[email protected]>:
mm: remove redundant compound_head() calling
Subsystem: mm/ioremap
Christoph Hellwig <[email protected]>:
riscv: only select GENERIC_IOREMAP if MMU support is enabled
Patch series "small ioremap cleanups":
mm: move ioremap_page_range to vmalloc.c
mm: don't allow executable ioremap mappings
Weizhao Ouyang <[email protected]>:
mm/early_ioremap.c: remove redundant early_ioremap_shutdown()
Subsystem: mm/highmem
Sebastian Andrzej Siewior <[email protected]>:
highmem: don't disable preemption on RT in kmap_atomic()
Subsystem: mm/cleanups
Changbin Du <[email protected]>:
mm: in_irq() cleanup
Muchun Song <[email protected]>:
mm: introduce PAGEFLAGS_MASK to replace ((1UL << NR_PAGEFLAGS) - 1)
Subsystem: mm/secretmem
Jordy Zomer <[email protected]>:
mm/secretmem: use refcount_t instead of atomic_t
Subsystem: mm/kfence
Marco Elver <[email protected]>:
kfence: show cpu and timestamp in alloc/free info
kfence: test: fail fast if disabled at boot
Subsystem: mm/damon
SeongJae Park <[email protected]>:
Patch series "Introduce Data Access MONitor (DAMON)", v34:
mm: introduce Data Access MONitor (DAMON)
mm/damon/core: implement region-based sampling
mm/damon: adaptively adjust regions mm/idle_page_tracking: make PG_idle reusable
mm/damon: implement primitives for the virtual memory address spaces mm/damon: add a tracepoint
mm/damon: implement a debugfs-based user space interface mm/damon/dbgfs: export kdamond pid to the user space mm/damon/dbgfs: support multiple contexts
Documentation: add documents for DAMON
mm/damon: add kunit tests
mm/damon: add user space selftests
MAINTAINERS: update for DAMON
Subsystem: alpha
Randy Dunlap <[email protected]>:
alpha: agp: make empty macros use do-while-0 style
alpha: pci-sysfs: fix all kernel-doc warnings
Subsystem: percpu
Greg Kroah-Hartman <[email protected]>:
percpu: remove export of pcpu_base_addr
Subsystem: procfs
Feng Zhou <[email protected]>:
fs/proc/kcore.c: add mmap interface
Christoph Hellwig <[email protected]>:
proc: stop using seq_get_buf in proc_task_name
Ohhoon Kwon <[email protected]>:
connector: send event on write to /proc/[pid]/comm
Subsystem: misc
Colin Ian King <[email protected]>:
arch: Kconfig: fix spelling mistake "seperate" -> "separate"
Andy Shevchenko <[email protected]>:
include/linux/once.h: fix trivia typo Not -> Note
Daniel Lezcano <[email protected]>:
Patch series "Add Hz macros", v3:
units: change from 'L' to 'UL'
units: add the HZ macros thermal/drivers/devfreq_cooling: use HZ macros
devfreq: use HZ macros iio/drivers/as73211: use HZ macros hwmon/drivers/mr75203: use HZ macros iio/drivers/hid-sensor: use HZ macros i2c/drivers/ov02q10: use HZ macros mtd/drivers/nand: use HZ macros phy/drivers/stm32: use HZ macros
Subsystem: core-kernel
Yang Yang <[email protected]>:
kernel/acct.c: use dedicated helper to access rlimit values
Pavel Skripkin <[email protected]>:
profiling: fix shift-out-of-bounds bugs
Subsystem: MAINTAINERS
Nathan Chancellor <[email protected]>:
MAINTAINERS: update ClangBuiltLinux mailing list Documentation/llvm: update mailing list Documentation/llvm: update IRC location
Subsystem: lib
Geert Uytterhoeven <[email protected]>:
Patch series "math: RATIONAL and RATIONAL_KUNIT_TEST improvements":
math: make RATIONAL tristate
math: RATIONAL_KUNIT_TEST should depend on RATIONAL instead of selecting it
Matteo Croce <[email protected]>:
Patch series "lib/string: optimized mem* functions", v2:
lib/string: optimized memcpy
lib/string: optimized memmove
lib/string: optimized memset
Daniel Latypov <[email protected]>:
lib/test: convert test_sort.c to use KUnit
Randy Dunlap <[email protected]>:
lib/dump_stack: correct kernel-doc notation
lib/iov_iter.c: fix kernel-doc warnings
Subsystem: bitops
Yury Norov <[email protected]>:
Patch series "Resend bitmap patches":
bitops: protect find_first_{,zero}_bit properly
bitops: move find_bit_*_le functions from le.h to find.h
include: move find.h from asm_generic to linux
arch: remove GENERIC_FIND_FIRST_BIT entirely
lib: add find_first_and_bit()
cpumask: use find_first_and_bit()
all: replace find_next{,_zero}_bit with find_first{,_zero}_bit where appropriate
tools: sync tools/bitmap with mother linux
cpumask: replace cpumask_next_* with cpumask_first_* where appropriate include/linux: move for_each_bit() macros from bitops.h to find.h
find: micro-optimize for_each_{set,clear}_bit()
bitops: replace for_each_*_bit_from() with for_each_*_bit() where appropriate
Andy Shevchenko <[email protected]>:
tools: rename bitmap_alloc() to bitmap_zalloc()
Yury Norov <[email protected]>:
mm/percpu: micro-optimize pcpu_is_populated()
bitmap: unify find_bit operations
lib: bitmap: add performance test for bitmap_print_to_pagebuf
vsprintf: rework bitmap_list_string
Subsystem: checkpatch
Joe Perches <[email protected]>:
checkpatch: support wide strings
Mimi Zohar <[email protected]>:
checkpatch: make email address check case insensitive
Joe Perches <[email protected]>:
checkpatch: improve GIT_COMMIT_ID test
Subsystem: epoll
Nicholas Piggin <[email protected]>:
fs/epoll: use a per-cpu counter for user's watches count
Subsystem: init
Rasmus Villemoes <[email protected]>:
init: move usermodehelper_enable() to populate_rootfs()
Kefeng Wang <[email protected]>:
trap: cleanup trap_init()
Subsystem: nilfs2
Nanyong Sun <[email protected]>:
Patch series "nilfs2: fix incorrect usage of kobject":
nilfs2: fix memory leak in nilfs_sysfs_create_device_group
nilfs2: fix NULL pointer in nilfs_##name##_attr_release
nilfs2: fix memory leak in nilfs_sysfs_create_##name##_group
nilfs2: fix memory leak in nilfs_sysfs_delete_##name##_group
nilfs2: fix memory leak in nilfs_sysfs_create_snapshot_group
nilfs2: fix memory leak in nilfs_sysfs_delete_snapshot_group
Zhen Lei <[email protected]>:
nilfs2: use refcount_dec_and_lock() to fix potential UAF
Subsystem: coredump
David Oberhollenzer <[email protected]>:
fs/coredump.c: log if a core dump is aborted due to changed file permissions
QiuXi <[email protected]>:
coredump: fix memleak in dump_vma_snapshot()
Subsystem: fork
Christoph Hellwig <[email protected]>:
kernel/fork.c: unexport get_{mm,task}_exe_file
Subsystem: pids
Takahiro Itazuri <[email protected]>:
pid: cleanup the stale comment mentioning pidmap_init().
Subsystem: criu
Cyrill Gorcunov <[email protected]>:
prctl: allow to setup brk for et_dyn executables
Subsystem: kconfig
Zenghui Yu <[email protected]>:
configs: remove the obsolete CONFIG_INPUT_POLLDEV
Lukas Bulwahn <[email protected]>:
Kconfig.debug: drop selecting non-existing HARDLOCKUP_DETECTOR_ARCH
Subsystem: selftests
Greg Thelen <[email protected]>:
selftests/memfd: remove unused variable
Subsystem: ipc
Rafael Aquini <[email protected]>:
ipc: replace costly bailout check in sysvipc_find_ipc()
Subsystem: mm/vmscan
Randy Dunlap <[email protected]>:
mm/workingset: correct kernel-doc notations
Subsystem: scripts
Randy Dunlap <[email protected]>:
scripts: check_extable: fix typo in user error message
a/Documentation/admin-guide/mm/damon/index.rst | 15 a/Documentation/admin-guide/mm/damon/start.rst | 114 + a/Documentation/admin-guide/mm/damon/usage.rst | 112 + a/Documentation/admin-guide/mm/index.rst | 1 a/Documentation/admin-guide/mm/memory-hotplug.rst | 842 ++++++----- a/Documentation/dev-tools/kfence.rst | 98 - a/Documentation/kbuild/llvm.rst | 5 a/Documentation/vm/damon/api.rst | 20 a/Documentation/vm/damon/design.rst | 166 ++ a/Documentation/vm/damon/faq.rst | 51 a/Documentation/vm/damon/index.rst | 30 a/Documentation/vm/index.rst | 1 a/MAINTAINERS | 17 a/arch/Kconfig | 2 a/arch/alpha/include/asm/agp.h | 4 a/arch/alpha/include/asm/bitops.h | 2 a/arch/alpha/kernel/pci-sysfs.c | 12 a/arch/arc/Kconfig | 1 a/arch/arc/include/asm/bitops.h | 1 a/arch/arc/kernel/traps.c | 5 a/arch/arm/configs/dove_defconfig | 1 a/arch/arm/configs/pxa_defconfig | 1 a/arch/arm/include/asm/bitops.h | 1 a/arch/arm/kernel/traps.c | 5 a/arch/arm64/Kconfig | 1 a/arch/arm64/include/asm/bitops.h | 1 a/arch/arm64/mm/mmu.c | 3 a/arch/csky/include/asm/bitops.h | 1 a/arch/h8300/include/asm/bitops.h | 1 a/arch/h8300/kernel/traps.c | 4 a/arch/hexagon/include/asm/bitops.h | 1 a/arch/hexagon/kernel/traps.c | 4 a/arch/ia64/include/asm/bitops.h | 2 a/arch/ia64/mm/init.c | 3 a/arch/m68k/include/asm/bitops.h | 2 a/arch/mips/Kconfig | 1 a/arch/mips/configs/lemote2f_defconfig | 1 a/arch/mips/configs/pic32mzda_defconfig | 1 a/arch/mips/configs/rt305x_defconfig | 1 a/arch/mips/configs/xway_defconfig | 1 a/arch/mips/include/asm/bitops.h | 1 a/arch/nds32/kernel/traps.c | 5 a/arch/nios2/kernel/traps.c | 5 a/arch/openrisc/include/asm/bitops.h | 1 a/arch/openrisc/kernel/traps.c | 5 a/arch/parisc/configs/generic-32bit_defconfig | 1 a/arch/parisc/include/asm/bitops.h | 2 a/arch/parisc/kernel/traps.c | 4 a/arch/powerpc/include/asm/bitops.h | 2 a/arch/powerpc/include/asm/cputhreads.h | 2 a/arch/powerpc/kernel/traps.c | 5 a/arch/powerpc/mm/mem.c | 3 a/arch/powerpc/platforms/pasemi/dma_lib.c | 4 a/arch/powerpc/platforms/pseries/hotplug-memory.c | 9 a/arch/riscv/Kconfig | 2 a/arch/riscv/include/asm/bitops.h | 1 a/arch/riscv/kernel/traps.c | 5 a/arch/s390/Kconfig | 1 a/arch/s390/include/asm/bitops.h | 1 a/arch/s390/kvm/kvm-s390.c | 2 a/arch/s390/mm/init.c | 3 a/arch/sh/include/asm/bitops.h | 1 a/arch/sh/mm/init.c | 3 a/arch/sparc/include/asm/bitops_32.h | 1 a/arch/sparc/include/asm/bitops_64.h | 2 a/arch/um/kernel/trap.c | 4 a/arch/x86/Kconfig | 1 a/arch/x86/configs/i386_defconfig | 1 a/arch/x86/configs/x86_64_defconfig | 1 a/arch/x86/include/asm/bitops.h | 2 a/arch/x86/kernel/apic/vector.c | 4 a/arch/x86/mm/init_32.c | 3 a/arch/x86/mm/init_64.c | 3 a/arch/x86/um/Kconfig | 1 a/arch/xtensa/include/asm/bitops.h | 1 a/block/blk-mq.c | 2 a/drivers/acpi/acpi_memhotplug.c | 46 a/drivers/base/memory.c | 231 ++- a/drivers/base/node.c | 2 a/drivers/block/rnbd/rnbd-clt.c | 2 a/drivers/dax/kmem.c | 43 a/drivers/devfreq/devfreq.c | 2 a/drivers/dma/ti/edma.c | 2 a/drivers/gpu/drm/etnaviv/etnaviv_gpu.c | 4 a/drivers/hwmon/ltc2992.c | 3 a/drivers/hwmon/mr75203.c | 2 a/drivers/iio/adc/ad7124.c | 2 a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c | 3 a/drivers/iio/light/as73211.c | 3 a/drivers/infiniband/hw/irdma/hw.c | 16 a/drivers/media/cec/core/cec-core.c | 2 a/drivers/media/i2c/ov02a10.c | 2 a/drivers/media/mc/mc-devnode.c | 2 a/drivers/mmc/host/renesas_sdhi_core.c | 2 a/drivers/mtd/nand/raw/intel-nand-controller.c | 2 a/drivers/net/virtio_net.c | 2 a/drivers/pci/controller/dwc/pci-dra7xx.c | 2 a/drivers/phy/st/phy-stm32-usbphyc.c | 2 a/drivers/scsi/lpfc/lpfc_sli.c | 10 a/drivers/soc/fsl/qbman/bman_portal.c | 2 a/drivers/soc/fsl/qbman/qman_portal.c | 2 a/drivers/soc/ti/k3-ringacc.c | 4 a/drivers/thermal/devfreq_cooling.c | 2 a/drivers/tty/n_tty.c | 2 a/drivers/virt/acrn/ioreq.c | 3 a/drivers/virtio/virtio_mem.c | 26 a/fs/coredump.c | 15 a/fs/eventpoll.c | 18 a/fs/f2fs/segment.c | 8 a/fs/nilfs2/sysfs.c | 26 a/fs/nilfs2/the_nilfs.c | 9 a/fs/ocfs2/cluster/heartbeat.c | 2 a/fs/ocfs2/dlm/dlmdomain.c | 4 a/fs/ocfs2/dlm/dlmmaster.c | 18 a/fs/ocfs2/dlm/dlmrecovery.c | 2 a/fs/ocfs2/dlm/dlmthread.c | 2 a/fs/proc/array.c | 18 a/fs/proc/base.c | 5 a/fs/proc/kcore.c | 73 a/include/asm-generic/bitops.h | 1 a/include/asm-generic/bitops/find.h | 198 -- a/include/asm-generic/bitops/le.h | 64 a/include/asm-generic/early_ioremap.h | 6 a/include/linux/bitmap.h | 34 a/include/linux/bitops.h | 34 a/include/linux/cpumask.h | 46 a/include/linux/damon.h | 290 +++ a/include/linux/find.h | 134 + a/include/linux/highmem-internal.h | 27 a/include/linux/memory.h | 55 a/include/linux/memory_hotplug.h | 40 a/include/linux/mmzone.h | 19 a/include/linux/once.h | 2 a/include/linux/page-flags.h | 17 a/include/linux/page_ext.h | 2 a/include/linux/page_idle.h | 6 a/include/linux/pagemap.h | 7 a/include/linux/sched/user.h | 3 a/include/linux/slub_def.h | 6 a/include/linux/threads.h | 2 a/include/linux/units.h | 10 a/include/linux/vmalloc.h | 3 a/include/trace/events/damon.h | 43 a/include/trace/events/mmflags.h | 2 a/include/trace/events/page_ref.h | 4 a/init/initramfs.c | 2 a/init/main.c | 3 a/init/noinitramfs.c | 2 a/ipc/util.c | 16 a/kernel/acct.c | 2 a/kernel/fork.c | 2 a/kernel/profile.c | 21 a/kernel/sys.c | 7 a/kernel/time/clocksource.c | 4 a/kernel/user.c | 25 a/lib/Kconfig | 3 a/lib/Kconfig.debug | 9 a/lib/dump_stack.c | 3 a/lib/find_bit.c | 21 a/lib/find_bit_benchmark.c | 21 a/lib/genalloc.c | 2 a/lib/iov_iter.c | 8 a/lib/math/Kconfig | 2 a/lib/math/rational.c | 3 a/lib/string.c | 130 + a/lib/test_bitmap.c | 37 a/lib/test_printf.c | 2 a/lib/test_sort.c | 40 a/lib/vsprintf.c | 26 a/mm/Kconfig | 15 a/mm/Makefile | 4 a/mm/compaction.c | 20 a/mm/damon/Kconfig | 68 a/mm/damon/Makefile | 5 a/mm/damon/core-test.h | 253 +++ a/mm/damon/core.c | 748 ++++++++++ a/mm/damon/dbgfs-test.h | 126 + a/mm/damon/dbgfs.c | 631 ++++++++ a/mm/damon/vaddr-test.h | 329 ++++ a/mm/damon/vaddr.c | 672 +++++++++ a/mm/early_ioremap.c | 5 a/mm/highmem.c | 2 a/mm/ioremap.c | 25 a/mm/kfence/core.c | 3 a/mm/kfence/kfence.h | 2 a/mm/kfence/kfence_test.c | 3 a/mm/kfence/report.c | 19 a/mm/kmemleak.c | 2 a/mm/memory_hotplug.c | 396 ++++- a/mm/memremap.c | 5 a/mm/page_alloc.c | 27 a/mm/page_ext.c | 12 a/mm/page_idle.c | 10 a/mm/page_isolation.c | 7 a/mm/page_owner.c | 14 a/mm/percpu.c | 36 a/mm/rmap.c | 6 a/mm/secretmem.c | 9 a/mm/slab_common.c | 2 a/mm/slub.c | 1023 +++++++++----- a/mm/vmalloc.c | 24 a/mm/workingset.c | 2 a/net/ncsi/ncsi-manage.c | 4 a/scripts/check_extable.sh | 2 a/scripts/checkpatch.pl | 93 - a/tools/include/linux/bitmap.h | 4 a/tools/perf/bench/find-bit-bench.c | 2 a/tools/perf/builtin-c2c.c | 6 a/tools/perf/builtin-record.c | 2 a/tools/perf/tests/bitmap.c | 2 a/tools/perf/tests/mem2node.c | 2 a/tools/perf/util/affinity.c | 4 a/tools/perf/util/header.c | 4 a/tools/perf/util/metricgroup.c | 2 a/tools/perf/util/mmap.c | 4 a/tools/testing/selftests/damon/Makefile | 7 a/tools/testing/selftests/damon/_chk_dependency.sh | 28 a/tools/testing/selftests/damon/debugfs_attrs.sh | 75 + a/tools/testing/selftests/kvm/dirty_log_perf_test.c | 2 a/tools/testing/selftests/kvm/dirty_log_test.c | 4 a/tools/testing/selftests/kvm/x86_64/vmx_dirty_log_test.c | 2 a/tools/testing/selftests/memfd/memfd_test.c | 2 b/MAINTAINERS | 2 b/tools/include/asm-generic/bitops.h | 1 b/tools/include/linux/bitmap.h | 7 b/tools/include/linux/find.h | 81 + b/tools/lib/find_bit.c | 20 227 files changed, 6695 insertions(+), 1875 deletions(-)
Andrew Morton
maintainerPATCH 1/147 mm, slub: don't call flush_all() from slab_debug_trace_open()
From: Vlastimil Babka <[email protected]>
Subject: mm, slub: don't call flush_all() from slab_debug_trace_open()
Patch series "SLUB: reduce irq disabled scope and make it RT compatible", v6.
This series was initially inspired by Mel's pcplist local_lock rewrite, and also interest to better understand SLUB's locking and the new primitives and RT variants and implications. It makes SLUB compatible with PREEMPT_RT and generally more preemption-friendly, apparently without significant regressions, as the fast paths are not affected.
The main changes to SLUB by this series:
* irq disabling is now only done for minimum amount of time needed to protect the strict kmem_cache_cpu fields, and as part of spin lock, local lock and bit lock operations to make them irq-safe
* SLUB is fully PREEMPT_RT compatible
The series should now be sufficiently tested in both RT and !RT configs, mainly thanks to Mike.
The RFC/v1 version also got basic performance screening by Mel that didn't show major regressions. Mike's testing with hackbench of v2 on !RT reported negligible differences [6]:
virgin(ish) tip
5.13.0.g60ab3ed-tip
7,320.67 msec task-clock # 7.792 CPUs utilized ( +- 0.31% )
221,215 context-switches # 0.030 M/sec ( +- 3.97% )
16,234 cpu-migrations # 0.002 M/sec ( +- 4.07% )
13,233 page-faults # 0.002 M/sec ( +- 0.91% )
27,592,205,252 cycles # 3.769 GHz ( +- 0.32% )
8,309,495,040 instructions # 0.30 insn per cycle ( +- 0.37% )
1,555,210,607 branches # 212.441 M/sec ( +- 0.42% )
5,484,209 branch-misses # 0.35% of all branches ( +- 2.13% ) 0.93949 +- 0.00423 seconds time elapsed ( +- 0.45% )
0.94608 +- 0.00384 seconds time elapsed ( +- 0.41% ) (repeat)
0.94422 +- 0.00410 seconds time elapsed ( +- 0.43% )5.13.0.g60ab3ed-tip +slub-local-lock-v2r3
7,343.57 msec task-clock # 7.776 CPUs utilized ( +- 0.44% )
223,044 context-switches # 0.030 M/sec ( +- 3.02% )
16,057 cpu-migrations # 0.002 M/sec ( +- 4.03% )
13,164 page-faults # 0.002 M/sec ( +- 0.97% )
27,684,906,017 cycles # 3.770 GHz ( +- 0.45% )
8,323,273,871 instructions # 0.30 insn per cycle ( +- 0.28% )
1,556,106,680 branches # 211.901 M/sec ( +- 0.31% )
5,463,468 branch-misses # 0.35% of all branches ( +- 1.33% ) 0.94440 +- 0.00352 seconds time elapsed ( +- 0.37% )
0.94830 +- 0.00228 seconds time elapsed ( +- 0.24% ) (repeat)
0.93813 +- 0.00440 seconds time elapsed ( +- 0.47% ) (repeat)RT configs showed some throughput regressions, but that's expected tradeoff for the preemption improvements through the RT mutex. It didn't prevent the v2 to be incorporated to the 5.13 RT tree [7], leading to testing exposure and bugfixes.
Before the series, SLUB is lockless in both allocation and free fast paths, but elsewhere, it's disabling irqs for considerable periods of time
- especially in allocation slowpath and the bulk allocation, where IRQs are re-enabled only when a new page from the page allocator is needed, and the context allows blocking. The irq disabled sections can then include deactivate_slab() which walks a full freelist and frees the slab back to page allocator or unfreeze_partials() going through a list of percpu partial slabs. The RT tree currently has some patches mitigating these, but we can do much better in mainline too.
Patches 1-6 are straightforward improvements or cleanups that could exist outside of this series too, but are prerequsities.
Patches 7-9 are also preparatory code changes without functional changes, but not so useful without the rest of the series.
Patch 10 simplifies the fast paths on systems with preemption, based on (hopefully correct) observation that the current loops to verify tid are unnecessary.
Patches 11-20 focus on reducing irq disabled scope in the allocation slowpath.
Patch 11 moves disabling of irqs into ___slab_alloc() from its callers, which are the allocation slowpath, and bulk allocation. Instead these callers only disable preemption to stabilize the cpu. The following patches then gradually reduce the scope of disabled irqs in ___slab_alloc() and the functions called from there. As of patch 14, the re-enabling of irqs based on gfp flags before calling the page allocator is removed from allocate_slab(). As of patch 17, it's possible to reach the page allocator (in case of existing slabs depleted) without disabling and re-enabling irqs a single time.
Patches 21-26 reduce the scope of disabled irqs in functions related to unfreezing percpu partial slab.
Patch 27 is preparatory. Patch 28 is adopted from the RT tree and converts the flushing of percpu slabs on all cpus from using IPI to workqueue, so that the processing isn't happening with irqs disabled in the IPI handler. The flushing is not performance critical so it should be acceptable.
Patch 29 also comes from RT tree and makes object_map_lock RT compatible.
Patch 30 make slab_lock irq-safe on RT where we cannot rely on having irq disabled from the list_lock spin lock usage.
Patch 31 changes kmem_cache_cpu->partial handling in put_cpu_partial() from cmpxchg loop to a short irq disabled section, which is used by all other code modifying the field. This addresses a theoretical race scenario pointed out by Jann, and makes the critical section safe wrt with RT local_lock semantics after the conversion in patch 35.
Patch 32 changes preempt disable to migrate disable, so that the nested list_lock spinlock is safe to take on RT. Because migrate_disable() is a function call even on !RT, a small set of private wrappers is introduced to keep using the cheaper preempt_disable() on !PREEMPT_RT configurations. As of this patch, SLUB should be already compatible with RT's lock semantics.
Finally, patch 33 changes irq disabled sections that protect kmem_cache_cpu fields in the slow paths, with a local lock. However on PREEMPT_RT it means the lockless fast paths can now preempt slow paths which don't expect that, so the local lock has to be taken also in the fast paths and they are no longer lockless. RT folks seem to not mind this tradeoff. The patch also updates the locking documentation in the file's comment.
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://git.kernel.org/pub/scm/linux/kernel/git/rt/linux-rt-devel.git/tree/patches/0001-mm-sl-au-b-Change-list_lock-to-raw_spinlock_t.patch?h=linux-5.12.y-rt-patches
[3] https://git.kernel.org/pub/scm/linux/kernel/git/rt/linux-rt-devel.git/tree/patches/0004-mm-slub-Move-discard_slab-invocations-out-of-IRQ-off.patch?h=linux-5.12.y-rt-patches
[4] https://git.kernel.org/pub/scm/linux/kernel/git/rt/linux-rt-devel.git/tree/patches/0005-mm-slub-Move-flush_cpu_slab-invocations-__free_slab-.patch?h=linux-5.12.y-rt-patches
[5] https://lore.kernel.org/lkml/[email protected]/
[6] https://lore.kernel.org/lkml/[email protected]
[7] https://lore.kernel.org/linux-rt-users/[email protected]/
[8] https://lore.kernel.org/lkml/[email protected]/
[9] https://lore.kernel.org/lkml/[email protected]/
[10] https://lore.kernel.org/lkml/[email protected]/
[11] https://lore.kernel.org/all/[email protected]/
[12] https://lore.kernel.org/all/[email protected]/
[13] https://lore.kernel.org/all/[email protected]/
[14] https://lore.kernel.org/linux-mm/[email protected]/
[15] https://lore.kernel.org/linux-mm/CAHk-=wjRfFtnQ5p42s_5Uv8i0U5YKSBpTH++_ZMKZyyvYicYmQ@mail.gmail.com/
[16] https://lore.kernel.org/all/871r6j526m.ffs@tglx/
This patch (of 33):
slab_debug_trace_open() can only be called on caches with SLAB_STORE_USER flag and as with all slub debugging flags, such caches avoid cpu or percpu partial slabs altogether, so there's nothing to flush.
---
mm/slub.c | 3 --- 1 file changed, 3 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-dont-call-flush_all-from-slab_debug_trace_open +0 -3
@@ -5825,9 +5825,6 @@ static int slab_debug_trace_open(structif (!alloc_loc_track (t,PAGE_SIZE /sizeof (struct location ),GFP_KERNEL ))return -ENOMEM ; -/* Push back cpu slabs */ -flush_all (s); -for_each_kmem_cache_node (s, node, n) {unsigned long flags;struct page *page;
_
Andrew Morton
maintainerPATCH 2/147 mm, slub: allocate private object map for debugfs listings
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: allocate private object map for debugfs listings
Slub has a static spinlock protected bitmap for marking which objects are on freelist when it wants to list them, for situations where dynamically allocating such map can lead to recursion or locking issues, and on-stack bitmap would be too large.
The handlers of debugfs files alloc_traces and free_traces also currently use this shared bitmap, but their syscall context makes it straightforward to allocate a private map before entering locked sections, so switch these processing paths to use a private bitmap.
---
mm/slub.c | 44 +++++++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 15 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-allocate-private-object-map-for-debugfs-listings +29 -15
@@ -454,6 +454,18 @@ static inline bool cmpxchg_double_slab(sstatic unsigned long object_map[BITS_TO_LONGS (MAX_OBJS_PER_PAGE )];static DEFINE_SPINLOCK (object_map_lock); +static void __fill_map (unsigned long *obj_map,struct kmem_cache *s, +struct page *page) +{ +void *addr =page_address (page); +void *p; + +bitmap_zero (obj_map, page->objects); + +for (p = page->freelist; p; p =get_freepointer (s, p)) +set_bit (__obj_to_index (s, addr, p), obj_map); +} +#if IS_ENABLED (CONFIG_KUNIT )static bool slab_add_kunit_errors (void ) {
@@ -483,17 +495,11 @@ static inline bool slab_add_kunit_errorsstatic unsigned long *get_map (struct kmem_cache *s,struct page *page) __acquires(&object_map_lock) { -void *p; -void *addr =page_address (page); -VM_BUG_ON (!irqs_disabled ());spin_lock (&object_map_lock); -bitmap_zero (object_map, page->objects); - -for (p = page->freelist; p; p =get_freepointer (s, p)) -set_bit (__obj_to_index (s, addr, p), object_map); +__fill_map (object_map, s, page);return object_map; }
@@ -4879,17 +4885,17 @@ static int add_location(struct loc_track }static void process_slab (struct loc_track *t,struct kmem_cache *s, -struct page *page,enum track_item alloc) +struct page *page,enum track_item alloc, +unsigned long *obj_map) {void *addr =page_address (page);void *p; -unsigned long *map; - map =get_map (s, page); +__fill_map (obj_map, s, page); +for_each_object (p, s, addr, page->objects) -if (!test_bit (__obj_to_index (s, addr, p), map)) +if (!test_bit (__obj_to_index (s, addr, p), obj_map))add_location (t, s,get_track (s, p, alloc)); -put_map (map); }#endif /* CONFIG_DEBUG_FS */ #endif /* CONFIG_SLUB_DEBUG */
@@ -5816,14 +5822,21 @@ static int slab_debug_trace_open(structstruct loc_track *t =__seq_open_private (filep, &slab_debugfs_sops,sizeof (struct loc_track ));struct kmem_cache *s =file_inode (filep)->i_private; +unsigned long *obj_map; + + obj_map =bitmap_alloc (oo_objects (s->oo),GFP_KERNEL ); +if (!obj_map) +return -ENOMEM ;if (strcmp (filep->f_path.dentry->d_name.name,"alloc_traces" ) ==0 ) alloc =TRACK_ALLOC ;else alloc =TRACK_FREE ; -if (!alloc_loc_track (t,PAGE_SIZE /sizeof (struct location ),GFP_KERNEL )) +if (!alloc_loc_track (t,PAGE_SIZE /sizeof (struct location ),GFP_KERNEL )) { +bitmap_free (obj_map);return -ENOMEM ; + }for_each_kmem_cache_node (s, node, n) {unsigned long flags;
@@ -5834,12 +5847,13 @@ static int slab_debug_trace_open(structspin_lock_irqsave (&n->list_lock, flags);list_for_each_entry (page, &n->partial, slab_list) -process_slab (t, s, page, alloc); +process_slab (t, s, page, alloc, obj_map);list_for_each_entry (page, &n->full, slab_list) -process_slab (t, s, page, alloc); +process_slab (t, s, page, alloc, obj_map);spin_unlock_irqrestore (&n->list_lock, flags); } +bitmap_free (obj_map);return 0 ; }
_
Andrew Morton
maintainerPATCH 3/147 mm, slub: allocate private object map for validate_slab_cache()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: allocate private object map for validate_slab_cache()
validate_slab_cache() is called either to handle a sysfs write, or from a self-test context. In both situations it's straightforward to preallocate a private object bitmap instead of grabbing the shared static one meant for critical sections, so let's do that.
---
mm/slub.c | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-allocate-private-object-map-for-validate_slab_cache +15 -9
@@ -4679,11 +4679,11 @@ static int count_total(struct page *page#endif #ifdef CONFIG_SLUB_DEBUG -static void validate_slab (struct kmem_cache *s,struct page *page) +static void validate_slab (struct kmem_cache *s,struct page *page, +unsigned long *obj_map) {void *p;void *addr =page_address (page); -unsigned long *map;slab_lock (page);
@@ -4691,21 +4691,20 @@ static void validate_slab(struct kmem_ca goto unlock;/* Now we know that a valid freelist exists */ - map =get_map (s, page); +__fill_map (obj_map, s, page);for_each_object (p, s, addr, page->objects) { -u8 val =test_bit (__obj_to_index (s, addr, p), map) ? +u8 val =test_bit (__obj_to_index (s, addr, p), obj_map) ?SLUB_RED_INACTIVE :SLUB_RED_ACTIVE ;if (!check_object (s, page, p, val))break ; } -put_map (map); unlock:slab_unlock (page); }static int validate_slab_node (struct kmem_cache *s, -struct kmem_cache_node *n) +struct kmem_cache_node *n,unsigned long *obj_map) {unsigned long count =0 ;struct page *page;
@@ -4714,7 +4713,7 @@ static int validate_slab_node(struct kmespin_lock_irqsave (&n->list_lock, flags);list_for_each_entry (page, &n->partial, slab_list) { -validate_slab (s, page); +validate_slab (s, page, obj_map); count++; }if (count != n->nr_partial) {
@@ -4727,7 +4726,7 @@ static int validate_slab_node(struct kme goto out;list_for_each_entry (page, &n->full, slab_list) { -validate_slab (s, page); +validate_slab (s, page, obj_map); count++; }if (count !=atomic_long_read (&n->nr_slabs)) {
@@ -4746,10 +4745,17 @@ long validate_slab_cache(struct kmem_cacint node;unsigned long count =0 ;struct kmem_cache_node *n; +unsigned long *obj_map; + + obj_map =bitmap_alloc (oo_objects (s->oo),GFP_KERNEL ); +if (!obj_map) +return -ENOMEM ;flush_all (s);for_each_kmem_cache_node (s, node, n) - count +=validate_slab_node (s, n); + count +=validate_slab_node (s, n, obj_map); + +bitmap_free (obj_map);return count; }
_
Andrew Morton
maintainerPATCH 4/147 mm, slub: don't disable irq for debug_check_no_locks_freed()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: don't disable irq for debug_check_no_locks_freed()
In slab_free_hook() we disable irqs around the debug_check_no_locks_freed() call, which is unnecessary, as irqs are already being disabled inside the call. This seems to be leftover from the past where there were more calls inside the irq disabled sections. Remove the irq disable/enable operations.
Mel noted:
Quoted 1 line
Looks like it was needed for kmemcheck which went away back in 4.15
---
mm/slub.c | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-dont-disable-irq-for-debug_check_no_locks_freed +1 -13
@@ -1591,20 +1591,8 @@ static __always_inline bool slab_free_ho {kmemleak_free_recursive (x, s->flags); -/* -* Trouble is that we may no longer disable interrupts in the fast path -* So in order to make the debug calls that expect irqs to be -* disabled we need to disable interrupts temporarily. -*/ -#ifdef CONFIG_LOCKDEP - { -unsigned long flags; +debug_check_no_locks_freed (x, s->object_size); -local_irq_save (flags); -debug_check_no_locks_freed (x, s->object_size); -local_irq_restore (flags); - } -#endif if (!(s->flags &SLAB_DEBUG_OBJECTS ))debug_check_no_obj_freed (x, s->object_size);
_
Andrew Morton
maintainerPATCH 5/147 mm, slub: remove redundant unfreeze_partials() from put_cpu_partial()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: remove redundant unfreeze_partials() from put_cpu_partial()
Commit d6e0b7fa1186 ("slub: make dead caches discard free slabs immediately") introduced cpu partial flushing for kmemcg caches, based on setting the target cpu_partial to 0 and adding a flushing check in put_cpu_partial(). This code that sets cpu_partial to 0 was later moved by c9fc586403e7 ("slab: introduce __kmemcg_cache_deactivate()") and ultimately removed by 9855609bde03 ("mm: memcg/slab: use a single set of kmem_caches for all accounted allocations"). However the check and flush in put_cpu_partial() was never removed, although it's effectively a dead code. So this patch removes it.
Note that d6e0b7fa1186 also added preempt_disable()/enable() to unfreeze_partials() which could be thus also considered unnecessary. But further patches will rely on it, so keep it.
---
mm/slub.c | 7 ------- 1 file changed, 7 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-remove-redundant-unfreeze_partials-from-put_cpu_partial +0 -7
@@ -2466,13 +2466,6 @@ static void put_cpu_partial(struct kmem_ } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page) != oldpage); -if (unlikely (!slub_cpu_partial (s))) { -unsigned long flags; - -local_irq_save (flags); -unfreeze_partials (s,this_cpu_ptr (s->cpu_slab)); -local_irq_restore (flags); - }preempt_enable ();#endif /* CONFIG_SLUB_CPU_PARTIAL */ }
_
Andrew Morton
maintainerPATCH 6/147 mm, slub: extract get_partial() from new_slab_objects()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: extract get_partial() from new_slab_objects()
The later patches will need more fine grained control over individual actions in ___slab_alloc(), the only caller of new_slab_objects(), so this is a first preparatory step with no functional change.
This adds a goto label that appears unnecessary at this point, but will be useful for later changes.
---
mm/slub.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-extract-get_partial-from-new_slab_objects +6 -6
@@ -2613,17 +2613,12 @@ slab_out_of_memory(struct kmem_cache *s,static inline void *new_slab_objects (struct kmem_cache *s,gfp_t flags,int node,struct kmem_cache_cpu **pc) { -void *freelist; +void *freelist =NULL ;struct kmem_cache_cpu *c = *pc;struct page *page;WARN_ON_ONCE (s->ctor && (flags & __GFP_ZERO)); - freelist =get_partial (s, flags, node, c); - -if (freelist) -return freelist; - page =new_slab (s, flags, node);if (page) { c =raw_cpu_ptr (s->cpu_slab);
@@ -2787,6 +2782,10 @@ new_slab: goto redo; } + freelist =get_partial (s, gfpflags, node, c); +if (freelist) + goto check_new_page; + freelist =new_slab_objects (s, gfpflags, node, &c);if (unlikely (!freelist)) {
@@ -2794,6 +2793,7 @@ new_slab:return NULL ; } +check_new_page: page = c->page;if (likely (!kmem_cache_debug (s) &&pfmemalloc_match (page, gfpflags))) goto load_freelist;
_
Andrew Morton
maintainerPATCH 7/147 mm, slub: dissolve new_slab_objects() into ___slab_alloc()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: dissolve new_slab_objects() into ___slab_alloc()
The later patches will need more fine grained control over individual actions in ___slab_alloc(), the only caller of new_slab_objects(), so dissolve it there. This is a preparatory step with no functional change.
The only minor change is moving WARN_ON_ONCE() for using a constructor together with __GFP_ZERO to new_slab(), which makes it somewhat less frequent, but still able to catch a development change introducing a systematic misuse.
---
mm/slub.c | 50 ++++++++++++++++++-------------------------------- 1 file changed, 18 insertions(+), 32 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-dissolve-new_slab_objects-into-___slab_alloc +18 -32
@@ -1885,6 +1885,8 @@ static struct page *new_slab(struct kmemif (unlikely (flags &GFP_SLAB_BUG_MASK )) flags =kmalloc_fix_flags (flags); +WARN_ON_ONCE (s->ctor && (flags & __GFP_ZERO)); +return allocate_slab (s, flags & (GFP_RECLAIM_MASK |GFP_CONSTRAINT_MASK ), node); }
@@ -2610,36 +2612,6 @@ slab_out_of_memory(struct kmem_cache *s,#endif } -static inline void *new_slab_objects (struct kmem_cache *s,gfp_t flags, -int node,struct kmem_cache_cpu **pc) -{ -void *freelist =NULL ; -struct kmem_cache_cpu *c = *pc; -struct page *page; - -WARN_ON_ONCE (s->ctor && (flags & __GFP_ZERO)); - - page =new_slab (s, flags, node); -if (page) { - c =raw_cpu_ptr (s->cpu_slab); -if (c->page) -flush_slab (s, c); - -/* -* No other reference to the page yet so we can -* muck around with it freely without cmpxchg -*/ - freelist = page->freelist; - page->freelist =NULL ; - -stat (s,ALLOC_SLAB ); - c->page = page; - *pc = c; - } - -return freelist; -} -static inline bool pfmemalloc_match (struct page *page,gfp_t gfpflags) {if (unlikely (PageSlabPfmemalloc (page)))
@@ -2786,13 +2758,27 @@ new_slab:if (freelist) goto check_new_page; - freelist =new_slab_objects (s, gfpflags, node, &c); + page =new_slab (s, gfpflags, node); -if (unlikely (!freelist)) { +if (unlikely (!page)) {slab_out_of_memory (s, gfpflags, node);return NULL ; } + c =raw_cpu_ptr (s->cpu_slab); +if (c->page) +flush_slab (s, c); + +/* +* No other reference to the page yet so we can +* muck around with it freely without cmpxchg +*/ + freelist = page->freelist; + page->freelist =NULL ; + +stat (s,ALLOC_SLAB ); + c->page = page; + check_new_page: page = c->page;if (likely (!kmem_cache_debug (s) &&pfmemalloc_match (page, gfpflags)))
_
Andrew Morton
maintainerPATCH 8/147 mm, slub: return slab page from get_partial() and set c->page afterwards
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: return slab page from get_partial() and set c->page afterwards
The function get_partial() finds a suitable page on a partial list, acquires and returns its freelist and assigns the page pointer to kmem_cache_cpu. In later patch we will need more control over the kmem_cache_cpu.page assignment, so instead of passing a kmem_cache_cpu pointer, pass a pointer to a pointer to a page that get_partial() can fill and the caller can assign the kmem_cache_cpu.page pointer. No functional change as all of this still happens with disabled IRQs.
---
mm/slub.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-return-slab-page-from-get_partial-and-set-c-page-afterwards +11 -10
@@ -2017,7 +2017,7 @@ static inline bool pfmemalloc_match(stru* Try to allocate a partial slab from a specific node. */ static void *get_partial_node (struct kmem_cache *s,struct kmem_cache_node *n, -struct kmem_cache_cpu *c,gfp_t flags) +struct page **ret_page,gfp_t flags) {struct page *page, *page2;void *object =NULL ;
@@ -2046,7 +2046,7 @@ static void *get_partial_node(struct kme available += objects;if (!object) { - c->page = page; + *ret_page = page;stat (s,ALLOC_FROM_PARTIAL ); object = t; }else {
@@ -2066,7 +2066,7 @@ static void *get_partial_node(struct kme* Get a page from somewhere. Search in increasing NUMA distances. */ static void *get_any_partial (struct kmem_cache *s,gfp_t flags, -struct kmem_cache_cpu *c) +struct page **ret_page) {#ifdef CONFIG_NUMA struct zonelist *zonelist;
@@ -2108,7 +2108,7 @@ static void *get_any_partial(struct kmemif (n &&cpuset_zone_allowed (zone, flags) && n->nr_partial > s->min_partial) { - object =get_partial_node (s, n, c, flags); + object =get_partial_node (s, n, ret_page, flags);if (object) {/* * Don't check read_mems_allowed_retry()
@@ -2130,7 +2130,7 @@ static void *get_any_partial(struct kmem* Get a partial page, lock it and return it. */ static void *get_partial (struct kmem_cache *s,gfp_t flags,int node, -struct kmem_cache_cpu *c) +struct page **ret_page) {void *object;int searchnode = node;
@@ -2138,11 +2138,11 @@ static void *get_partial(struct kmem_cacif (node ==NUMA_NO_NODE ) searchnode =numa_mem_id (); - object =get_partial_node (s,get_node (s, searchnode), c, flags); + object =get_partial_node (s,get_node (s, searchnode), ret_page, flags);if (object || node !=NUMA_NO_NODE )return object; -return get_any_partial (s, flags, c); +return get_any_partial (s, flags, ret_page); }#ifdef CONFIG_PREEMPTION
@@ -2754,9 +2754,11 @@ new_slab: goto redo; } - freelist =get_partial (s, gfpflags, node, c); -if (freelist) + freelist =get_partial (s, gfpflags, node, &page); +if (freelist) { + c->page = page; goto check_new_page; + } page =new_slab (s, gfpflags, node);
@@ -2780,7 +2782,6 @@ new_slab: c->page = page; check_new_page: - page = c->page;if (likely (!kmem_cache_debug (s) &&pfmemalloc_match (page, gfpflags))) goto load_freelist;
_
Andrew Morton
maintainerPATCH 9/147 mm, slub: restructure new page checks in ___slab_alloc()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: restructure new page checks in ___slab_alloc()
When we allocate slab object from a newly acquired page (from node's partial list or page allocator), we usually also retain the page as a new percpu slab. There are two exceptions - when pfmemalloc status of the page doesn't match our gfp flags, or when the cache has debugging enabled.
The current code for these decisions is not easy to follow, so restructure it and add comments. The new structure will also help with the following changes. No functional change.
---
mm/slub.c | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-restructure-new-page-checks-in-___slab_alloc +22 -6
@@ -2782,13 +2782,29 @@ new_slab: c->page = page; check_new_page: -if (likely (!kmem_cache_debug (s) &&pfmemalloc_match (page, gfpflags))) - goto load_freelist; -/* Only entered in the debug case */ -if (kmem_cache_debug (s) && - !alloc_debug_processing (s, page, freelist, addr)) - goto new_slab;/* Slab failed checks. Next slab needed */ +if (kmem_cache_debug (s)) { +if (!alloc_debug_processing (s, page, freelist, addr)) +/* Slab failed checks. Next slab needed */ + goto new_slab; +else +/* +* For debug case, we don't load freelist so that all +* allocations go through alloc_debug_processing() +*/ + goto return_single; + } + +if (unlikely (!pfmemalloc_match (page, gfpflags))) +/* +* For !pfmemalloc_match() case we don't load freelist so that +* we don't make further mismatched allocations easier. +*/ + goto return_single; + + goto load_freelist; + +return_single:deactivate_slab (s, page,get_freepointer (s, freelist), c);return freelist;
_
Andrew Morton
maintainerPATCH 10/147 mm, slub: simplify kmem_cache_cpu and tid setup
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: simplify kmem_cache_cpu and tid setup
In slab_alloc_node() and do_slab_free() fastpaths we need to guarantee that our kmem_cache_cpu pointer is from the same cpu as the tid value. Currently that's done by reading the tid first using this_cpu_read(), then the kmem_cache_cpu pointer and verifying we read the same tid using the pointer and plain READ_ONCE().
This can be simplified to just fetching kmem_cache_cpu pointer and then reading tid using the pointer. That guarantees they are from the same cpu. We don't need to read the tid using this_cpu_read() because the value will be validated by this_cpu_cmpxchg_double(), making sure we are on the correct cpu and the freelist didn't change by anyone preempting us since reading the tid.
---
mm/slub.c | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-simplify-kmem_cache_cpu-and-tid-setup +9 -13
@@ -2882,15 +2882,14 @@ redo:* reading from one cpu area. That does not matter as long * as we end up on the original cpu again when doing the cmpxchg. * -* We should guarantee that tid and kmem_cache are retrieved on -* the same cpu. It could be different if CONFIG_PREEMPTION so we need -* to check if it is matched or not. +* We must guarantee that tid and kmem_cache_cpu are retrieved on the +* same cpu. We read first the kmem_cache_cpu pointer and use it to read +* the tid. If we are preempted and switched to another cpu between the +* two reads, it's OK as the two are still associated with the same cpu +* and cmpxchg later will validate the cpu. */ -do { - tid =this_cpu_read (s->cpu_slab->tid); - c =raw_cpu_ptr (s->cpu_slab); - }while (IS_ENABLED (CONFIG_PREEMPTION ) && -unlikely (tid !=READ_ONCE (c->tid))); + c =raw_cpu_ptr (s->cpu_slab); + tid =READ_ONCE (c->tid);/* * Irqless object alloc/free algorithm used here depends on sequence
@@ -3164,11 +3163,8 @@ redo:* data is retrieved via this pointer. If we are on the same cpu * during the cmpxchg then the free will succeed. */ -do { - tid =this_cpu_read (s->cpu_slab->tid); - c =raw_cpu_ptr (s->cpu_slab); - }while (IS_ENABLED (CONFIG_PREEMPTION ) && -unlikely (tid !=READ_ONCE (c->tid))); + c =raw_cpu_ptr (s->cpu_slab); + tid =READ_ONCE (c->tid);/* Same with comment on barrier() in slab_alloc_node() */ barrier ();
_
Andrew Morton
maintainerPATCH 11/147 mm, slub: move disabling/enabling irqs to ___slab_alloc()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: move disabling/enabling irqs to ___slab_alloc()
Currently __slab_alloc() disables irqs around the whole ___slab_alloc(). This includes cases where this is not needed, such as when the allocation ends up in the page allocator and has to awkwardly enable irqs back based on gfp flags. Also the whole kmem_cache_alloc_bulk() is executed with irqs disabled even when it hits the __slab_alloc() slow path, and long periods with disabled interrupts are undesirable.
As a first step towards reducing irq disabled periods, move irq handling into ___slab_alloc(). Callers will instead prevent the s->cpu_slab percpu pointer from becoming invalid via get_cpu_ptr(), thus preempt_disable(). This does not protect against modification by an irq handler, which is still done by disabled irq for most of ___slab_alloc(). As a small immediate benefit, slab_out_of_memory() from ___slab_alloc() is now called with irqs enabled.
kmem_cache_alloc_bulk() disables irqs for its fastpath and then re-enables them before calling ___slab_alloc(), which then disables them at its discretion. The whole kmem_cache_alloc_bulk() operation also disables preemption.
When ___slab_alloc() calls new_slab() to allocate a new page, re-enable preemption, because new_slab() will re-enable interrupts in contexts that allow blocking (this will be improved by later patches).
The patch itself will thus increase overhead a bit due to disabled preemption (on configs where it matters) and increased disabling/enabling irqs in kmem_cache_alloc_bulk(), but that will be gradually improved in the following patches.
Note in __slab_alloc() we need to change the #ifdef CONFIG_PREEMPT guard to CONFIG_PREEMPT_COUNT to make sure preempt disable/enable is properly paired in all configurations. On configs without involuntary preemption and debugging the re-read of kmem_cache_cpu pointer is still compiled out as it was before.
---
mm/slub.c | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-move-disabling-enabling-irqs-to-___slab_alloc +24 -12
@@ -2670,7 +2670,7 @@ static inline void *get_freelist(struct* we need to allocate a new slab. This is the slowest path since it involves * a call to the page allocator and the setup of a new slab. * -* Version of __slab_alloc to use when we know that interrupts are +* Version of __slab_alloc to use when we know that preemption is * already disabled (which is the case for bulk allocation). */ static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
@@ -2678,9 +2678,11 @@ static void *___slab_alloc(struct kmem_c {void *freelist;struct page *page; +unsigned long flags;stat (s,ALLOC_SLOWPATH ); +local_irq_save (flags); page = c->page;if (!page) {/*
@@ -2743,6 +2745,7 @@ load_freelist:VM_BUG_ON (!c->page->frozen); c->freelist =get_freepointer (s, freelist); c->tid =next_tid (c->tid); +local_irq_restore (flags);return freelist; new_slab:
@@ -2760,14 +2763,16 @@ new_slab: goto check_new_page; } +put_cpu_ptr (s->cpu_slab); page =new_slab (s, gfpflags, node); + c =get_cpu_ptr (s->cpu_slab);if (unlikely (!page)) { +local_irq_restore (flags);slab_out_of_memory (s, gfpflags, node);return NULL ; } - c =raw_cpu_ptr (s->cpu_slab);if (c->page)flush_slab (s, c);
@@ -2807,31 +2812,33 @@ check_new_page: return_single:deactivate_slab (s, page,get_freepointer (s, freelist), c); +local_irq_restore (flags);return freelist; }/* -* Another one that disabled interrupt and compensates for possible -* cpu changes by refetching the per cpu area pointer. +* A wrapper for ___slab_alloc() for contexts where preemption is not yet +* disabled. Compensates for possible cpu changes by refetching the per cpu area +* pointer. */ static void *__slab_alloc (struct kmem_cache *s,gfp_t gfpflags,int node,unsigned long addr,struct kmem_cache_cpu *c) {void *p; -unsigned long flags; -local_irq_save (flags); -#ifdef CONFIG_PREEMPTION +#ifdef CONFIG_PREEMPT_COUNT /* * We may have been preempted and rescheduled on a different -* cpu before disabling interrupts. Need to reload cpu area +* cpu before disabling preemption. Need to reload cpu area * pointer. */ - c =this_cpu_ptr (s->cpu_slab); + c =get_cpu_ptr (s->cpu_slab);#endif p =___slab_alloc (s, gfpflags, node, addr, c); -local_irq_restore (flags); +#ifdef CONFIG_PREEMPT_COUNT +put_cpu_ptr (s->cpu_slab); +#endif return p; }
@@ -3359,8 +3366,8 @@ int kmem_cache_alloc_bulk(struct kmem_ca* IRQs, which protects against PREEMPT and interrupts * handlers invoking normal fastpath. */ + c =get_cpu_ptr (s->cpu_slab);local_irq_disable (); - c =this_cpu_ptr (s->cpu_slab);for (i =0 ; i < size; i++) {void *object =kfence_alloc (s, s->object_size, flags);
@@ -3381,6 +3388,8 @@ int kmem_cache_alloc_bulk(struct kmem_ca*/ c->tid =next_tid (c->tid); +local_irq_enable (); +/* * Invoking slow path likely have side-effect * of re-populating per CPU c->freelist
@@ -3393,6 +3402,8 @@ int kmem_cache_alloc_bulk(struct kmem_ca c =this_cpu_ptr (s->cpu_slab);maybe_wipe_obj_freeptr (s, p[i]); +local_irq_disable (); +continue ;/* goto for-loop */ } c->freelist =get_freepointer (s, object);
@@ -3401,6 +3412,7 @@ int kmem_cache_alloc_bulk(struct kmem_ca } c->tid =next_tid (c->tid);local_irq_enable (); +put_cpu_ptr (s->cpu_slab);/* * memcg and kmem_cache debug support and memory initialization.
@@ -3410,7 +3422,7 @@ int kmem_cache_alloc_bulk(struct kmem_ca slab_want_init_on_alloc(flags, s));return i; error: -local_irq_enable (); +put_cpu_ptr (s->cpu_slab);slab_post_alloc_hook (s, objcg, flags, i, p, false);__kmem_cache_free_bulk (s, i, p);return 0 ;
_
Andrew Morton
maintainerPATCH 12/147 mm, slub: do initial checks in ___slab_alloc() with irqs enabled
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: do initial checks in ___slab_alloc() with irqs enabled
As another step of shortening irq disabled sections in ___slab_alloc(), delay disabling irqs until we pass the initial checks if there is a cached percpu slab and it's suitable for our allocation.
Now we have to recheck c->page after actually disabling irqs as an allocation in irq handler might have replaced it.
Because we call pfmemalloc_match() as one of the checks, we might hit VM_BUG_ON_PAGE(!PageSlab(page)) in PageSlabPfmemalloc in case we get interrupted and the page is freed. Thus introduce a pfmemalloc_match_unsafe() variant that lacks the PageSlab check.
---
include/linux/page-flags.h | 9 +++++ mm/slub.c | 54 +++++++++++++++++++++++++++++------ 2 files changed, 54 insertions(+), 9 deletions(-)
include/linux/page-flags.h renamed from include/linux/page-flags.h~mm-slub-do-initial-checks-in-___slab_alloc-with-irqs-enabled +9 -0
@@ -815,6 +815,15 @@ static inline int PageSlabPfmemalloc(strreturn PageActive (page); } +/* +* A version of PageSlabPfmemalloc() for opportunistic checks where the page +* might have been freed under us and not be a PageSlab anymore. +*/ +static inline int __PageSlabPfmemalloc (struct page *page) +{ +return PageActive (page); +} +static inline void SetPageSlabPfmemalloc (struct page *page) {VM_BUG_ON_PAGE (!PageSlab (page), page);
mm/slub.c renamed from mm/slub.c~mm-slub-do-initial-checks-in-___slab_alloc-with-irqs-enabled +45 -9
102 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 13/147 mm, slub: move disabling irqs closer to get_partial() in ___slab_alloc()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: move disabling irqs closer to get_partial() in ___slab_alloc()
Continue reducing the irq disabled scope. Check for per-cpu partial slabs with first with irqs enabled and then recheck with irqs disabled before grabbing the slab page. Mostly preparatory for the following patches.
---
mm/slub.c | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-move-disabling-irqs-closer-to-get_partial-in-___slab_alloc +25 -9
@@ -2706,11 +2706,6 @@ reread_page:if (unlikely (node !=NUMA_NO_NODE && !node_isset (node, slab_nodes))) node =NUMA_NO_NODE ; -local_irq_save (flags); -if (unlikely (c->page)) { -local_irq_restore (flags); - goto reread_page; - } goto new_slab; } redo:
@@ -2751,6 +2746,7 @@ redo:if (!freelist) { c->page =NULL ; +local_irq_restore (flags);stat (s,DEACTIVATE_BYPASS ); goto new_slab; }
@@ -2780,12 +2776,19 @@ deactivate_slab: goto reread_page; }deactivate_slab (s, page, c->freelist, c); +local_irq_restore (flags); new_slab: -lockdep_assert_irqs_disabled (); -if (slub_percpu_partial (c)) { +local_irq_save (flags); +if (unlikely (c->page)) { +local_irq_restore (flags); + goto reread_page; + } +if (unlikely (!slub_percpu_partial (c))) + goto new_objects;/* stolen by an IRQ handler */ + page = c->page =slub_percpu_partial (c);slub_set_percpu_partial (c, page);local_irq_restore (flags);
@@ -2793,6 +2796,16 @@ new_slab: goto redo; } +local_irq_save (flags); +if (unlikely (c->page)) { +local_irq_restore (flags); + goto reread_page; + } + +new_objects: + +lockdep_assert_irqs_disabled (); + freelist =get_partial (s, gfpflags, node, &page);if (freelist) { c->page = page;
@@ -2825,15 +2838,18 @@ new_slab: check_new_page:if (kmem_cache_debug (s)) { -if (!alloc_debug_processing (s, page, freelist, addr)) +if (!alloc_debug_processing (s, page, freelist, addr)) {/* Slab failed checks. Next slab needed */ + c->page =NULL ; +local_irq_restore (flags); goto new_slab; -else + }else {/* * For debug case, we don't load freelist so that all * allocations go through alloc_debug_processing() */ goto return_single; + } }if (unlikely (!pfmemalloc_match (page, gfpflags)))
_
Andrew Morton
maintainerPATCH 14/147 mm, slub: restore irqs around calling new_slab()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: restore irqs around calling new_slab()
allocate_slab() currently re-enables irqs before calling to the page allocator. It depends on gfpflags_allow_blocking() to determine if it's safe to do so. Now we can instead simply restore irq before calling it through new_slab(). The other caller early_kmem_cache_node_alloc() is unaffected by this.
---
mm/slub.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-restore-irqs-around-calling-new_slab +2 -6
@@ -1809,9 +1809,6 @@ static struct page *allocate_slab(struct flags &= gfp_allowed_mask; -if (gfpflags_allow_blocking (flags)) -local_irq_enable (); - flags |= s->allocflags;/*
@@ -1870,8 +1867,6 @@ static struct page *allocate_slab(struct page->frozen =1 ; out: -if (gfpflags_allow_blocking (flags)) -local_irq_disable ();if (!page)return NULL ;
@@ -2812,16 +2807,17 @@ new_objects: goto check_new_page; } +local_irq_restore (flags);put_cpu_ptr (s->cpu_slab); page =new_slab (s, gfpflags, node); c =get_cpu_ptr (s->cpu_slab);if (unlikely (!page)) { -local_irq_restore (flags);slab_out_of_memory (s, gfpflags, node);return NULL ; } +local_irq_save (flags);if (c->page)flush_slab (s, c);
_
Andrew Morton
maintainerPATCH 15/147 mm, slub: validate slab from partial list or page allocator before making it cpu slab
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: validate slab from partial list or page allocator before making it cpu slab
When we obtain a new slab page from node partial list or page allocator, we assign it to kmem_cache_cpu, perform some checks, and if they fail, we undo the assignment.
In order to allow doing the checks without irq disabled, restructure the code so that the checks are done first, and kmem_cache_cpu.page assignment only after they pass.
---
mm/slub.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-validate-slab-from-partial-list-or-page-allocator-before-making-it-cpu-slab +9 -8
@@ -2802,10 +2802,8 @@ new_objects:lockdep_assert_irqs_disabled (); freelist =get_partial (s, gfpflags, node, &page); -if (freelist) { - c->page = page; +if (freelist) goto check_new_page; - }local_irq_restore (flags);put_cpu_ptr (s->cpu_slab);
@@ -2818,9 +2816,6 @@ new_objects: }local_irq_save (flags); -if (c->page) -flush_slab (s, c); -/* * No other reference to the page yet so we can * muck around with it freely without cmpxchg
@@ -2829,14 +2824,12 @@ new_objects: page->freelist =NULL ;stat (s,ALLOC_SLAB ); - c->page = page; check_new_page:if (kmem_cache_debug (s)) {if (!alloc_debug_processing (s, page, freelist, addr)) {/* Slab failed checks. Next slab needed */ - c->page =NULL ;local_irq_restore (flags); goto new_slab; }else {
@@ -2855,10 +2848,18 @@ check_new_page:*/ goto return_single; +if (unlikely (c->page)) +flush_slab (s, c); + c->page = page; + goto load_freelist; return_single: +if (unlikely (c->page)) +flush_slab (s, c); + c->page = page; +deactivate_slab (s, page,get_freepointer (s, freelist), c);local_irq_restore (flags);return freelist;
_
Andrew Morton
maintainerPATCH 16/147 mm, slub: check new pages with restored irqs
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: check new pages with restored irqs
Building on top of the previous patch, re-enable irqs before checking new pages. alloc_debug_processing() is now called with enabled irqs so we need to remove VM_BUG_ON(!irqs_disabled()); in check_slab() - there doesn't seem to be a need for it anyway.
---
mm/slub.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-check-new-pages-with-restored-irqs +3 -5
@@ -1009,8 +1009,6 @@ static int check_slab(struct kmem_cache {int maxobj; -VM_BUG_ON (!irqs_disabled ()); -if (!PageSlab (page)) {slab_err (s, page,"Not a valid slab page" );return 0 ;
@@ -2802,10 +2800,10 @@ new_objects:lockdep_assert_irqs_disabled (); freelist =get_partial (s, gfpflags, node, &page); +local_irq_restore (flags);if (freelist) goto check_new_page; -local_irq_restore (flags);put_cpu_ptr (s->cpu_slab); page =new_slab (s, gfpflags, node); c =get_cpu_ptr (s->cpu_slab);
@@ -2815,7 +2813,6 @@ new_objects:return NULL ; } -local_irq_save (flags);/* * No other reference to the page yet so we can * muck around with it freely without cmpxchg
@@ -2830,7 +2827,6 @@ check_new_page:if (kmem_cache_debug (s)) {if (!alloc_debug_processing (s, page, freelist, addr)) {/* Slab failed checks. Next slab needed */ -local_irq_restore (flags); goto new_slab; }else {/*
@@ -2848,6 +2844,7 @@ check_new_page:*/ goto return_single; +local_irq_save (flags);if (unlikely (c->page))flush_slab (s, c); c->page = page;
@@ -2856,6 +2853,7 @@ check_new_page: return_single: +local_irq_save (flags);if (unlikely (c->page))flush_slab (s, c); c->page = page;
_
Andrew Morton
maintainerPATCH 17/147 mm, slub: stop disabling irqs around get_partial()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: stop disabling irqs around get_partial()
The function get_partial() does not need to have irqs disabled as a whole. It's sufficient to convert spin_lock operations to their irq saving/restoring versions.
As a result, it's now possible to reach the page allocator from the slab allocator without disabling and re-enabling interrupts on the way.
---
mm/slub.c | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-stop-disabling-irqs-around-get_partial +8 -14
@@ -2010,11 +2010,12 @@ static inline bool pfmemalloc_match(stru* Try to allocate a partial slab from a specific node. */ static void *get_partial_node (struct kmem_cache *s,struct kmem_cache_node *n, -struct page **ret_page,gfp_t flags) +struct page **ret_page,gfp_t gfpflags) {struct page *page, *page2;void *object =NULL ;unsigned int available =0 ; +unsigned long flags;int objects;/*
@@ -2026,11 +2027,11 @@ static void *get_partial_node(struct kmeif (!n || !n->nr_partial)return NULL ; -spin_lock (&n->list_lock); +spin_lock_irqsave (&n->list_lock, flags);list_for_each_entry_safe (page, page2, &n->partial, slab_list) {void *t; -if (!pfmemalloc_match (page, flags)) +if (!pfmemalloc_match (page, gfpflags))continue ; t =acquire_slab (s, n, page, object ==NULL , &objects);
@@ -2051,7 +2052,7 @@ static void *get_partial_node(struct kmebreak ; } -spin_unlock (&n->list_lock); +spin_unlock_irqrestore (&n->list_lock, flags);return object; }
@@ -2779,8 +2780,10 @@ new_slab:local_irq_restore (flags); goto reread_page; } -if (unlikely (!slub_percpu_partial (c))) +if (unlikely (!slub_percpu_partial (c))) { +local_irq_restore (flags); goto new_objects;/* stolen by an IRQ handler */ + } page = c->page =slub_percpu_partial (c);slub_set_percpu_partial (c, page);
@@ -2789,18 +2792,9 @@ new_slab: goto redo; } -local_irq_save (flags); -if (unlikely (c->page)) { -local_irq_restore (flags); - goto reread_page; - } - new_objects: -lockdep_assert_irqs_disabled (); - freelist =get_partial (s, gfpflags, node, &page); -local_irq_restore (flags);if (freelist) goto check_new_page;
_
Andrew Morton
maintainerPATCH 18/147 mm, slub: move reset of c->page and freelist out of deactivate_slab()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: move reset of c->page and freelist out of deactivate_slab()
deactivate_slab() removes the cpu slab by merging the cpu freelist with slab's freelist and putting the slab on the proper node's list. It also sets the respective kmem_cache_cpu pointers to NULL.
By extracting the kmem_cache_cpu operations from the function, we can make it not dependent on disabled irqs.
Also if we return a single free pointer from ___slab_alloc, we no longer have to assign kmem_cache_cpu.page before deactivation or care if somebody preempted us and assigned a different page to our kmem_cache_cpu in the process.
---
mm/slub.c | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-move-reset-of-c-page-and-freelist-out-of-deactivate_slab +18 -13
@@ -2209,10 +2209,13 @@ static void init_kmem_cache_cpus(struct }/* -* Remove the cpu slab +* Finishes removing the cpu slab. Merges cpu's freelist with page's freelist, +* unfreezes the slabs and puts it on the proper list. +* Assumes the slab has been already safely taken away from kmem_cache_cpu +* by the caller. */ static void deactivate_slab (struct kmem_cache *s,struct page *page, -void *freelist,struct kmem_cache_cpu *c) +void *freelist) {enum slab_modes {M_NONE ,M_PARTIAL ,M_FULL ,M_FREE };struct kmem_cache_node *n =get_node (s,page_to_nid (page));
@@ -2341,9 +2344,6 @@ redo:discard_slab (s, page);stat (s,FREE_SLAB ); } - - c->page =NULL ; - c->freelist =NULL ; }/*
@@ -2468,10 +2468,16 @@ static void put_cpu_partial(struct kmem_static inline void flush_slab (struct kmem_cache *s,struct kmem_cache_cpu *c) { -stat (s,CPUSLAB_FLUSH ); -deactivate_slab (s, c->page, c->freelist, c); +void *freelist = c->freelist; +struct page *page = c->page; + c->page =NULL ; + c->freelist =NULL ; c->tid =next_tid (c->tid); + +deactivate_slab (s, page, freelist); + +stat (s,CPUSLAB_FLUSH ); }/*
@@ -2769,7 +2775,10 @@ deactivate_slab:local_irq_restore (flags); goto reread_page; } -deactivate_slab (s, page, c->freelist, c); + freelist = c->freelist; + c->page =NULL ; + c->freelist =NULL ; +deactivate_slab (s, page, freelist);local_irq_restore (flags); new_slab:
@@ -2848,11 +2857,7 @@ check_new_page: return_single:local_irq_save (flags); -if (unlikely (c->page)) -flush_slab (s, c); - c->page = page; - -deactivate_slab (s, page,get_freepointer (s, freelist), c); +deactivate_slab (s, page,get_freepointer (s, freelist));local_irq_restore (flags);return freelist; }
_
Andrew Morton
maintainerPATCH 19/147 mm, slub: make locking in deactivate_slab() irq-safe
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: make locking in deactivate_slab() irq-safe
deactivate_slab() now no longer touches the kmem_cache_cpu structure, so it will be possible to call it with irqs enabled. Just convert the spin_lock calls to their irq saving/restoring variants to make it irq-safe.
Note we now have to use cmpxchg_double_slab() for irq-safe slab_lock(), because in some situations we don't take the list_lock, which would disable irqs.
---
mm/slub.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-make-locking-in-deactivate_slab-irq-safe +5 -4
@@ -2223,6 +2223,7 @@ static void deactivate_slab(struct kmem_enum slab_modes l =M_NONE , m =M_NONE ;void *nextfree, *freelist_iter, *freelist_tail;int tail =DEACTIVATE_TO_HEAD ; +unsigned long flags =0 ;struct page new;struct page old;
@@ -2298,7 +2299,7 @@ redo:* that acquire_slab() will see a slab page that * is frozen */ -spin_lock (&n->list_lock); +spin_lock_irqsave (&n->list_lock, flags); } }else { m =M_FULL ;
@@ -2309,7 +2310,7 @@ redo:* slabs from diagnostic functions will not see * any frozen slabs. */ -spin_lock (&n->list_lock); +spin_lock_irqsave (&n->list_lock, flags); } }
@@ -2326,14 +2327,14 @@ redo: } l = m; -if (!__cmpxchg_double_slab (s, page, +if (!cmpxchg_double_slab (s, page, old.freelist, old.counters, new.freelist, new.counters,"unfreezing slab" )) goto redo;if (lock) -spin_unlock (&n->list_lock); +spin_unlock_irqrestore (&n->list_lock, flags);if (m ==M_PARTIAL )stat (s, tail);
_
Andrew Morton
maintainerPATCH 20/147 mm, slub: call deactivate_slab() without disabling irqs
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: call deactivate_slab() without disabling irqs
The function is now safe to be called with irqs enabled, so move the calls outside of irq disabled sections.
When called from ___slab_alloc() -> flush_slab() we have irqs disabled, so to reenable them before deactivate_slab() we need to open-code flush_slab() in ___slab_alloc() and reenable irqs after modifying the kmem_cache_cpu fields. But that means a IRQ handler meanwhile might have assigned a new page to kmem_cache_cpu.page so we have to retry the whole check.
The remaining callers of flush_slab() are the IPI handler which has disabled irqs anyway, and slub_cpu_dead() which will be dealt with in the following patch.
---
mm/slub.c | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-call-deactivate_slab-without-disabling-irqs +19 -5
@@ -2779,8 +2779,8 @@ deactivate_slab: freelist = c->freelist; c->page =NULL ; c->freelist =NULL ; -deactivate_slab (s, page, freelist);local_irq_restore (flags); +deactivate_slab (s, page, freelist); new_slab:
@@ -2848,18 +2848,32 @@ check_new_page:*/ goto return_single; +retry_load_page: +local_irq_save (flags); -if (unlikely (c->page)) -flush_slab (s, c); +if (unlikely (c->page)) { +void *flush_freelist = c->freelist; +struct page *flush_page = c->page; + + c->page =NULL ; + c->freelist =NULL ; + c->tid =next_tid (c->tid); + +local_irq_restore (flags); + +deactivate_slab (s, flush_page, flush_freelist); + +stat (s,CPUSLAB_FLUSH ); + + goto retry_load_page; + } c->page = page; goto load_freelist; return_single: -local_irq_save (flags);deactivate_slab (s, page,get_freepointer (s, freelist)); -local_irq_restore (flags);return freelist; }
_
Andrew Morton
maintainerPATCH 21/147 mm, slub: move irq control into unfreeze_partials()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: move irq control into unfreeze_partials()
unfreeze_partials() can be optimized so that it doesn't need irqs disabled for the whole time. As the first step, move irq control into the function and remove it from the put_cpu_partial() caller.
---
mm/slub.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-move-irq-control-into-unfreeze_partials +7 -6
@@ -2350,9 +2350,8 @@ redo:/* * Unfreeze all the cpu partial slabs. * -* This function must be called with interrupts disabled -* for the cpu using c (or some other guarantee must be there -* to guarantee no concurrent accesses). +* This function must be called with preemption or migration +* disabled with c local to the cpu. */ static void unfreeze_partials (struct kmem_cache *s,struct kmem_cache_cpu *c)
@@ -2360,6 +2359,9 @@ static void unfreeze_partials(struct kme#ifdef CONFIG_SLUB_CPU_PARTIAL struct kmem_cache_node *n =NULL , *n2 =NULL ;struct page *page, *discard_page =NULL ; +unsigned long flags; + +local_irq_save (flags);while ((page =slub_percpu_partial (c))) {struct page new;
@@ -2412,6 +2414,8 @@ static void unfreeze_partials(struct kmediscard_slab (s, page); stat(s, FREE_SLAB); } + +local_irq_restore (flags);#endif /* CONFIG_SLUB_CPU_PARTIAL */ }
@@ -2439,14 +2443,11 @@ static void put_cpu_partial(struct kmem_ pobjects = oldpage->pobjects; pages = oldpage->pages;if (drain && pobjects >slub_cpu_partial (s)) { -unsigned long flags;/* * partial array is full. Move the existing * set to the per node partial list. */ -local_irq_save (flags);unfreeze_partials (s,this_cpu_ptr (s->cpu_slab)); -local_irq_restore (flags); oldpage =NULL ; pobjects =0 ; pages =0 ;
_
Andrew Morton
maintainerPATCH 22/147 mm, slub: discard slabs in unfreeze_partials() without irqs disabled
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: discard slabs in unfreeze_partials() without irqs disabled
No need for disabled irqs when discarding slabs, so restore them before discarding.
---
mm/slub.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/slub.c renamed from mm/slub.c~mm-slub-discard-slabs-in-unfreeze_partials-without-irqs-disabled +2 -1
@@ -2406,6 +2406,8 @@ static void unfreeze_partials(struct kmeif (n)spin_unlock (&n->list_lock); +local_irq_restore (flags); +while (discard_page) { page = discard_page; discard_page = discard_page->next;
@@ -2415,7 +2417,6 @@ static void unfreeze_partials(struct kme stat(s, FREE_SLAB); } -local_irq_restore (flags);#endif /* CONFIG_SLUB_CPU_PARTIAL */ }
_
Andrew Morton
maintainerPATCH 23/147 mm, slub: detach whole partial list at once in unfreeze_partials()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: detach whole partial list at once in unfreeze_partials()
Instead of iterating through the live percpu partial list, detach it from the kmem_cache_cpu at once. This is simpler and will allow further optimization.
---
mm/slub.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-detach-whole-partial-list-at-once-in-unfreeze_partials +7 -3
@@ -2358,16 +2358,20 @@ static void unfreeze_partials(struct kme {#ifdef CONFIG_SLUB_CPU_PARTIAL struct kmem_cache_node *n =NULL , *n2 =NULL ; -struct page *page, *discard_page =NULL ; +struct page *page, *partial_page, *discard_page =NULL ;unsigned long flags;local_irq_save (flags); -while ((page =slub_percpu_partial (c))) { + partial_page =slub_percpu_partial (c); + c->partial =NULL ; + +while (partial_page) {struct page new;struct page old; -slub_set_percpu_partial (c, page); + page = partial_page; + partial_page = page->next; n2 =get_node (s,page_to_nid (page));if (n != n2) {
_
Andrew Morton
maintainerPATCH 24/147 mm, slub: separate detaching of partial list in unfreeze_partials() from unfreezing
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: separate detaching of partial list in unfreeze_partials() from unfreezing
Unfreezing partial list can be split to two phases - detaching the list from struct kmem_cache_cpu, and processing the list. The whole operation does not need to be protected by disabled irqs. Restructure the code to separate the detaching (with disabled irqs) and unfreezing (with irq disabling to be reduced in the next patch).
Also, unfreeze_partials() can be called from another cpu on behalf of a cpu that is being offlined, where disabling irqs on the local cpu has no sense, so restructure the code as follows:
- __unfreeze_partials() is the bulk of unfreeze_partials() that processes the detached percpu partial list
- unfreeze_partials() detaches list from current cpu with irqs disabled and calls __unfreeze_partials()
- unfreeze_partials_cpu() is to be called for the offlined cpu so it needs no irq disabling, and is called from __flush_cpu_slab()
- flush_cpu_slab() is for the local cpu thus it needs to call unfreeze_partials(). So it can't simply call __flush_cpu_slab(smp_processor_id()) anymore and we have to open-code the proper calls.
---
mm/slub.c | 73 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 51 insertions(+), 22 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-separate-detaching-of-partial-list-in-unfreeze_partials-from-unfreezing +51 -22
@@ -2347,25 +2347,15 @@ redo: } } -/* -* Unfreeze all the cpu partial slabs. -* -* This function must be called with preemption or migration -* disabled with c local to the cpu. -*/ -static void unfreeze_partials (struct kmem_cache *s, -struct kmem_cache_cpu *c) -{#ifdef CONFIG_SLUB_CPU_PARTIAL +static void __unfreeze_partials (struct kmem_cache *s,struct page *partial_page) +{struct kmem_cache_node *n =NULL , *n2 =NULL ; -struct page *page, *partial_page, *discard_page =NULL ; +struct page *page, *discard_page =NULL ;unsigned long flags;local_irq_save (flags); - partial_page =slub_percpu_partial (c); - c->partial =NULL ; -while (partial_page) {struct page new;struct page old;
@@ -2420,10 +2410,45 @@ static void unfreeze_partials(struct kmediscard_slab (s, page); stat(s, FREE_SLAB); } +} -#endif /* CONFIG_SLUB_CPU_PARTIAL */ +/* +* Unfreeze all the cpu partial slabs. +*/ +static void unfreeze_partials (struct kmem_cache *s) +{ +struct page *partial_page; +unsigned long flags; + +local_irq_save (flags); + partial_page =this_cpu_read (s->cpu_slab->partial); +this_cpu_write (s->cpu_slab->partial,NULL ); +local_irq_restore (flags); + +if (partial_page) +__unfreeze_partials (s, partial_page); +} + +static void unfreeze_partials_cpu (struct kmem_cache *s, +struct kmem_cache_cpu *c) +{ +struct page *partial_page; + + partial_page =slub_percpu_partial (c); + c->partial =NULL ; + +if (partial_page) +__unfreeze_partials (s, partial_page); } +#else /* CONFIG_SLUB_CPU_PARTIAL */ + +static inline void unfreeze_partials (struct kmem_cache *s) { } +static inline void unfreeze_partials_cpu (struct kmem_cache *s, +struct kmem_cache_cpu *c) { } + +#endif /* CONFIG_SLUB_CPU_PARTIAL */ +/* * Put a page that was just frozen (in __slab_free|get_partial_node) into a * partial page slot if available.
@@ -2452,7 +2477,7 @@ static void put_cpu_partial(struct kmem_* partial array is full. Move the existing * set to the per node partial list. */ -unfreeze_partials (s,this_cpu_ptr (s->cpu_slab)); +unfreeze_partials (s); oldpage =NULL ; pobjects =0 ; pages =0 ;
@@ -2487,11 +2512,6 @@ static inline void flush_slab(struct kmestat (s,CPUSLAB_FLUSH ); } -/* -* Flush cpu slab. -* -* Called from IPI handler with interrupts disabled. -*/ static inline void __flush_cpu_slab (struct kmem_cache *s,int cpu) {struct kmem_cache_cpu *c =per_cpu_ptr (s->cpu_slab, cpu);
@@ -2499,14 +2519,23 @@ static inline void __flush_cpu_slab(struif (c->page)flush_slab (s, c); -unfreeze_partials (s, c); +unfreeze_partials_cpu (s, c); } +/* +* Flush cpu slab. +* +* Called from IPI handler with interrupts disabled. +*/ static void flush_cpu_slab (void *d) {struct kmem_cache *s = d; +struct kmem_cache_cpu *c =this_cpu_ptr (s->cpu_slab); + +if (c->page) +flush_slab (s, c); -__flush_cpu_slab (s,smp_processor_id ()); +unfreeze_partials (s); }static bool has_cpu_slab (int cpu,void *info)
_
Andrew Morton
maintainerPATCH 25/147 mm, slub: only disable irq with spin_lock in __unfreeze_partials()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: only disable irq with spin_lock in __unfreeze_partials()
__unfreeze_partials() no longer needs to have irqs disabled, except for making the spin_lock operations irq-safe, so convert the spin_locks operations and remove the separate irq handling.
---
mm/slub.c | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-only-disable-irq-with-spin_lock-in-__unfreeze_partials +4 -8
@@ -2352,9 +2352,7 @@ static void __unfreeze_partials(struct k {struct kmem_cache_node *n =NULL , *n2 =NULL ;struct page *page, *discard_page =NULL ; -unsigned long flags; - -local_irq_save (flags); +unsigned long flags =0 ;while (partial_page) {struct page new;
@@ -2366,10 +2364,10 @@ static void __unfreeze_partials(struct k n2 =get_node (s,page_to_nid (page));if (n != n2) {if (n) -spin_unlock (&n->list_lock); +spin_unlock_irqrestore (&n->list_lock, flags); n = n2; -spin_lock (&n->list_lock); +spin_lock_irqsave (&n->list_lock, flags); } do {
@@ -2398,9 +2396,7 @@ static void __unfreeze_partials(struct k }if (n) -spin_unlock (&n->list_lock); - -local_irq_restore (flags); +spin_unlock_irqrestore (&n->list_lock, flags);while (discard_page) { page = discard_page;
_
Andrew Morton
maintainerPATCH 26/147 mm, slub: don't disable irqs in slub_cpu_dead()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: don't disable irqs in slub_cpu_dead()
slub_cpu_dead() cleans up for an offlined cpu from another cpu and calls only functions that are now irq safe, so we don't need to disable irqs anymore.
---
mm/slub.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-dont-disable-irqs-in-slub_cpu_dead +1 -5
@@ -2554,14 +2554,10 @@ static void flush_all(struct kmem_cachestatic int slub_cpu_dead (unsigned int cpu) {struct kmem_cache *s; -unsigned long flags;mutex_lock (&slab_mutex); -list_for_each_entry (s, &slab_caches, list) { -local_irq_save (flags); +list_for_each_entry (s, &slab_caches, list)__flush_cpu_slab (s, cpu); -local_irq_restore (flags); - }mutex_unlock (&slab_mutex);return 0 ; }
_
Andrew Morton
maintainerPATCH 27/147 mm, slab: split out the cpu offline variant of flush_slab()
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slab: split out the cpu offline variant of flush_slab()
flush_slab() is called either as part IPI handler on given live cpu, or as a cleanup on behalf of another cpu that went offline. The first case needs to protect updating the kmem_cache_cpu fields with disabled irqs. Currently the whole call happens with irqs disabled by the IPI handler, but the following patch will change from IPI to workqueue, and flush_slab() will have to disable irqs (to be replaced with a local lock later) in the critical part.
To prepare for this change, replace the call to flush_slab() for the dead cpu handling with an opencoded variant that will not disable irqs nor take a local lock.
---
mm/slub.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slab-split-out-the-cpu-offline-variant-of-flush_slab +10 -2
@@ -2511,9 +2511,17 @@ static inline void flush_slab(struct kmestatic inline void __flush_cpu_slab (struct kmem_cache *s,int cpu) {struct kmem_cache_cpu *c =per_cpu_ptr (s->cpu_slab, cpu); +void *freelist = c->freelist; +struct page *page = c->page; -if (c->page) -flush_slab (s, c); + c->page =NULL ; + c->freelist =NULL ; + c->tid =next_tid (c->tid); + +if (page) { +deactivate_slab (s, page, freelist); +stat (s,CPUSLAB_FLUSH ); + }unfreeze_partials_cpu (s, c); }
_
Andrew Morton
maintainerPATCH 28/147 mm: slub: move flush_cpu_slab() invocations __free_slab() invocations out of IRQ context
In reply to Andrew MortonFrom: Sebastian Andrzej Siewior <[email protected]>
Subject: mm: slub: move flush_cpu_slab() invocations __free_slab() invocations out of IRQ context
flush_all() flushes a specific SLAB cache on each CPU (where the cache is present). The deactivate_slab()/__free_slab() invocation happens within IPI handler and is problematic for PREEMPT_RT.
The flush operation is not a frequent operation or a hot path. The per-CPU flush operation can be moved to within a workqueue.
Because a workqueue handler, unlike IPI handler, does not disable irqs, flush_slab() now has to disable them for working with the kmem_cache_cpu fields. deactivate_slab() is safe to call with irqs enabled.
---
mm/slab_common.c | 2 mm/slub.c | 94 +++++++++++++++++++++++++++++++++++++-------- 2 files changed, 80 insertions(+), 16 deletions(-)
mm/slab_common.c renamed from mm/slab_common.c~mm-slub-move-flush_cpu_slab-invocations-__free_slab-invocations-out-of-irq-context +2 -0
@@ -502,6 +502,7 @@ void kmem_cache_destroy(struct kmem_cachif (unlikely (!s))return ; +cpus_read_lock ();mutex_lock (&slab_mutex); s->refcount--;
@@ -516,6 +517,7 @@ void kmem_cache_destroy(struct kmem_cach } out_unlock:mutex_unlock (&slab_mutex); +cpus_read_unlock (); }EXPORT_SYMBOL (kmem_cache_destroy);
mm/slub.c renamed from mm/slub.c~mm-slub-move-flush_cpu_slab-invocations-__free_slab-invocations-out-of-irq-context +78 -16
160 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 29/147 mm: slub: make object_map_lock a raw_spinlock_t
In reply to Andrew MortonFrom: Sebastian Andrzej Siewior <[email protected]>
Subject: mm: slub: make object_map_lock a raw_spinlock_t
The variable object_map is protected by object_map_lock. The lock is always acquired in debug code and within already atomic context
Make object_map_lock a raw_spinlock_t.
---
mm/slub.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-make-object_map_lock-a-raw_spinlock_t +3 -3
@@ -452,7 +452,7 @@ static inline bool cmpxchg_double_slab(s#ifdef CONFIG_SLUB_DEBUG static unsigned long object_map[BITS_TO_LONGS (MAX_OBJS_PER_PAGE )]; -static DEFINE_SPINLOCK (object_map_lock); +static DEFINE_RAW_SPINLOCK (object_map_lock);static void __fill_map (unsigned long *obj_map,struct kmem_cache *s,struct page *page)
@@ -497,7 +497,7 @@ static unsigned long *get_map(struct kme {VM_BUG_ON (!irqs_disabled ()); -spin_lock (&object_map_lock); +raw_spin_lock (&object_map_lock);__fill_map (object_map, s, page);
@@ -507,7 +507,7 @@ static unsigned long *get_map(struct kme static void put_map(unsigned long *map) __releases(&object_map_lock) {VM_BUG_ON (map != object_map); -spin_unlock (&object_map_lock); +raw_spin_unlock (&object_map_lock); }static inline unsigned int size_from_object (struct kmem_cache *s)
_
Andrew Morton
maintainerPATCH 30/147 mm, slub: make slab_lock() disable irqs with PREEMPT_RT
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: make slab_lock() disable irqs with PREEMPT_RT
We need to disable irqs around slab_lock() (a bit spinlock) to make it irq-safe. Most calls to slab_lock() are nested under spin_lock_irqsave() which doesn't disable irqs on PREEMPT_RT, so add explicit disabling with PREEMPT_RT. The exception is cmpxchg_double_slab() which already disables irqs, so use a __slab_[un]lock() variant without irq disable there.
slab_[un]lock() thus needs a flags pointer parameter, which is unused on !RT. free_debug_processing() now has two flags variables, which looks odd, but only one is actually used - the one used in spin_lock_irqsave() on !RT and the one used in slab_lock() on RT.
As a result, __cmpxchg_double_slab() and cmpxchg_double_slab() become effectively identical on RT, as both will disable irqs, which is necessary on RT as most callers of this function also rely on irqsaving lock operations. Thus, assert that irqs are already disabled in __cmpxchg_double_slab() only on !RT and also change the VM_BUG_ON assertion to the more standard lockdep_assert one.
---
mm/slub.c | 58 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 41 insertions(+), 17 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-make-slab_lock-disable-irqs-with-preempt_rt +41 -17
@@ -359,25 +359,44 @@ static inline unsigned int oo_objects(st/* * Per slab locking using the pagelock */ -static __always_inline void slab_lock(struct page *page) +static __always_inline void __slab_lock(struct page *page) {VM_BUG_ON_PAGE (PageTail (page), page);bit_spin_lock (PG_locked, &page->flags); } -static __always_inline void slab_unlock(struct page *page) +static __always_inline void __slab_unlock(struct page *page) {VM_BUG_ON_PAGE (PageTail (page), page);__bit_spin_unlock (PG_locked, &page->flags); } -/* Interrupts must be disabled (for the fallback code to work right) */ +static __always_inline void slab_lock(struct page *page, unsigned long *flags) +{ +if (IS_ENABLED (CONFIG_PREEMPT_RT )) +local_irq_save (*flags); +__slab_lock (page); +} + +static __always_inline void slab_unlock(struct page *page, unsigned long *flags) +{ +__slab_unlock (page); +if (IS_ENABLED (CONFIG_PREEMPT_RT )) +local_irq_restore (*flags); +} + +/* +* Interrupts must be disabled (for the fallback code to work right), typically +* by an _irqsave() lock variant. Except on PREEMPT_RT where locks are different +* so we disable interrupts as part of slab_[un]lock(). +*/ static inline bool __cmpxchg_double_slab (struct kmem_cache *s,struct page *page,void *freelist_old,unsigned long counters_old,void *freelist_new,unsigned long counters_new,const char *n) { -VM_BUG_ON (!irqs_disabled ()); +if (!IS_ENABLED (CONFIG_PREEMPT_RT )) +lockdep_assert_irqs_disabled ();#if defined(CONFIG_HAVE_CMPXCHG_DOUBLE ) && \ defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE )if (s->flags & __CMPXCHG_DOUBLE) {
@@ -388,15 +407,18 @@ static inline bool __cmpxchg_double_slab } else#endif { -slab_lock (page); +/* init to 0 to prevent spurious warnings */ +unsigned long flags =0 ; + +slab_lock (page, &flags);if (page->freelist == freelist_old && page->counters == counters_old) { page->freelist = freelist_new; page->counters = counters_new; -slab_unlock (page); +slab_unlock (page, &flags);return true; } -slab_unlock (page); +slab_unlock (page, &flags); }cpu_relax ();
@@ -427,16 +449,16 @@ static inline bool cmpxchg_double_slab(sunsigned long flags;local_irq_save (flags); -slab_lock (page); +__slab_lock (page);if (page->freelist == freelist_old && page->counters == counters_old) { page->freelist = freelist_new; page->counters = counters_new; -slab_unlock (page); +__slab_unlock (page);local_irq_restore (flags);return true; } -slab_unlock (page); +__slab_unlock (page);local_irq_restore (flags); }
@@ -1269,11 +1291,11 @@ static noinline int free_debug_processinstruct kmem_cache_node *n =get_node (s,page_to_nid (page));void *object = head;int cnt =0 ; -unsigned long flags; +unsigned long flags, flags2;int ret =0 ;spin_lock_irqsave (&n->list_lock, flags); -slab_lock (page); +slab_lock (page, &flags2);if (s->flags &SLAB_CONSISTENCY_CHECKS ) {if (!check_slab (s, page))
@@ -1306,7 +1328,7 @@ out:slab_err (s, page,"Bulk freelist count(%d) invalid(%d)\n" , bulk_cnt, cnt); -slab_unlock (page); +slab_unlock (page, &flags2);spin_unlock_irqrestore (&n->list_lock, flags);if (!ret)slab_fix (s,"Object at 0x%p not freed" , object);
@@ -4087,11 +4109,12 @@ static void list_slab_objects(struct kme {#ifdef CONFIG_SLUB_DEBUG void *addr =page_address (page); +unsigned long flags;unsigned long *map;void *p;slab_err (s, page, text, s->name); -slab_lock (page); +slab_lock (page, &flags); map =get_map (s, page);for_each_object (p, s, addr, page->objects) {
@@ -4102,7 +4125,7 @@ static void list_slab_objects(struct kme } }put_map (map); -slab_unlock (page); +slab_unlock (page, &flags);#endif }
@@ -4834,8 +4857,9 @@ static void validate_slab(struct kmem_ca {void *p;void *addr =page_address (page); +unsigned long flags; -slab_lock (page); +slab_lock (page, &flags);if (!check_slab (s, page) || !on_freelist (s, page,NULL )) goto unlock;
@@ -4850,7 +4874,7 @@ static void validate_slab(struct kmem_cabreak ; } unlock: -slab_unlock (page); +slab_unlock (page, &flags); } static int validate_slab_node(struct kmem_cache *s,
_
Andrew Morton
maintainerPATCH 31/147 mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
Jann Horn reported [1] the following theoretically possible race:
task A: put_cpu_partial() calls preempt_disable()
task A: oldpage = this_cpu_read(s->cpu_slab->partial)
interrupt: kfree() reaches unfreeze_partials() and discards the page task B (on another CPU): reallocates page as page cache
task A: reads page->pages and page->pobjects, which are actually halves of the pointer page->lru.prev
task B (on another CPU): frees page
interrupt: allocates page as SLUB page and places it on the percpu partial list task A: this_cpu_cmpxchg() succeeds
which would cause page->pages and page->pobjects to end up containing halves of pointers that would then influence when put_cpu_partial() happens and show up in root-only sysfs files. Maybe that's acceptable, I don't know. But there should probably at least be a comment for now to point out that we're reading union fields of a page that might be in a completely different state.
Additionally, the this_cpu_cmpxchg() approach in put_cpu_partial() is only safe against s->cpu_slab->partial manipulation in ___slab_alloc() if the latter disables irqs, otherwise a __slab_free() in an irq handler could call put_cpu_partial() in the middle of ___slab_alloc() manipulating ->partial and corrupt it. This becomes an issue on RT after a local_lock is introduced in later patch. The fix means taking the local_lock also in put_cpu_partial() on RT.
After debugging this issue, Mike Galbraith suggested [2] that to avoid different locking schemes on RT and !RT, we can just protect put_cpu_partial() with disabled irqs (to be converted to local_lock_irqsave() later) everywhere. This should be acceptable as it's not a fast path, and moving the actual partial unfreezing outside of the irq disabled section makes it short, and with the retry loop gone the code can be also simplified. In addition, the race reported by Jann should no longer be possible.
[1] https://lore.kernel.org/lkml/CAG48ez1mvUuXwg0YPH5ANzhQLpbphqk-ZS+jbRz+H66fvm4FcA@mail.gmail.com/
[2] https://lore.kernel.org/linux-rt-users/[email protected]/
---
mm/slub.c | 83 ++++++++++++++++++++++++++++------------------------ 1 file changed, 45 insertions(+), 38 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-protect-put_cpu_partial-with-disabled-irqs-instead-of-cmpxchg +45 -38
@@ -2025,7 +2025,12 @@ static inline void *acquire_slab(structreturn freelist; } +#ifdef CONFIG_SLUB_CPU_PARTIAL static void put_cpu_partial (struct kmem_cache *s,struct page *page,int drain); +#else +static inline void put_cpu_partial (struct kmem_cache *s,struct page *page, +int drain) { } +#endif static inline bool pfmemalloc_match (struct page *page,gfp_t gfpflags);/*
@@ -2459,14 +2464,6 @@ static void unfreeze_partials_cpu(struct__unfreeze_partials (s, partial_page); } -#else /* CONFIG_SLUB_CPU_PARTIAL */ - -static inline void unfreeze_partials (struct kmem_cache *s) { } -static inline void unfreeze_partials_cpu (struct kmem_cache *s, -struct kmem_cache_cpu *c) { } - -#endif /* CONFIG_SLUB_CPU_PARTIAL */ -/* * Put a page that was just frozen (in __slab_free|get_partial_node) into a * partial page slot if available.
@@ -2476,46 +2473,56 @@ static inline void unfreeze_partials_cpu*/ static void put_cpu_partial (struct kmem_cache *s,struct page *page,int drain) { -#ifdef CONFIG_SLUB_CPU_PARTIAL struct page *oldpage; -int pages; -int pobjects; +struct page *page_to_unfreeze =NULL ; +unsigned long flags; +int pages =0 ; +int pobjects =0 ; -preempt_disable (); -do { - pages =0 ; - pobjects =0 ; - oldpage =this_cpu_read (s->cpu_slab->partial); +local_irq_save (flags); + + oldpage =this_cpu_read (s->cpu_slab->partial); -if (oldpage) { +if (oldpage) { +if (drain && oldpage->pobjects >slub_cpu_partial (s)) { +/* +* Partial array is full. Move the existing set to the +* per node partial list. Postpone the actual unfreezing +* outside of the critical section. +*/ + page_to_unfreeze = oldpage; + oldpage =NULL ; + }else { pobjects = oldpage->pobjects; pages = oldpage->pages; -if (drain && pobjects >slub_cpu_partial (s)) { -/* -* partial array is full. Move the existing -* set to the per node partial list. -*/ -unfreeze_partials (s); - oldpage =NULL ; - pobjects =0 ; - pages =0 ; -stat (s,CPU_PARTIAL_DRAIN ); - } } + } - pages++; - pobjects += page->objects - page->inuse; + pages++; + pobjects += page->objects - page->inuse; - page->pages = pages; - page->pobjects = pobjects; - page->next = oldpage; - - }while (this_cpu_cmpxchg (s->cpu_slab->partial, oldpage, page) - != oldpage); -preempt_enable (); -#endif /* CONFIG_SLUB_CPU_PARTIAL */ + page->pages = pages; + page->pobjects = pobjects; + page->next = oldpage; + +this_cpu_write (s->cpu_slab->partial, page); + +local_irq_restore (flags); + +if (page_to_unfreeze) { +__unfreeze_partials (s, page_to_unfreeze); +stat (s,CPU_PARTIAL_DRAIN ); + } } +#else /* CONFIG_SLUB_CPU_PARTIAL */ + +static inline void unfreeze_partials (struct kmem_cache *s) { } +static inline void unfreeze_partials_cpu (struct kmem_cache *s, +struct kmem_cache_cpu *c) { } + +#endif /* CONFIG_SLUB_CPU_PARTIAL */ +static inline void flush_slab (struct kmem_cache *s,struct kmem_cache_cpu *c) {unsigned long flags;
_
Re: [patch 031/147] mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
Quoted 30 lines · Andrew Morton
From: Vlastimil Babka <[email protected]>
Subject: mm, slub: protectput_cpu_partial()with disabled irqs instead of cmpxchgJann Horn reported [1] the following theoretically possible race:
task A:
put_cpu_partial()callspreempt_disable()
task A: oldpage =this_cpu_read(s->cpu_slab->partial)
interrupt:kfree()reachesunfreeze_partials()and discards the page task B (on another CPU): reallocates page as page cache
task A: readspage->pagesandpage->pobjects, which are actually halves of the pointerpage->lru.prev
task B (on another CPU): frees page
interrupt: allocates page as SLUB page and places it on the percpu partial list task A:this_cpu_cmpxchg()succeedswhich would cause
page->pagesandpage->pobjectsto end up containing halves of pointers that would then influence whenput_cpu_partial()happens and show up in root-only sysfs files. Maybe that's acceptable, I don't know. But there should probably at least be a comment for now to point out that we're reading union fields of a page that might be in a completely different state.Additionally, the
this_cpu_cmpxchg()approach input_cpu_partial()is only safe againsts->cpu_slab->partialmanipulation in___slab_alloc()if the latter disables irqs, otherwise a__slab_free()in an irq handler could callput_cpu_partial()in the middle of___slab_alloc()manipulating ->partial and corrupt it. This becomes an issue on RT after alocal_lockis introduced in later patch. The fix means taking thelocal_lockalso input_cpu_partial()on RT.
Quoted 8 lines
After debugging this issue, Mike Galbraith suggested [2] that to avoid different locking schemes on RT and !RT, we can just protect
put_cpu_partial()with disabled irqs (to be converted tolocal_lock_irqsave()later) everywhere. This should be acceptable as it's not a fast path, and moving the actual partial unfreezing outside of the irq disabled section makes it short, and with the retry loop gone the code can be also simplified. In addition, the race reported by Jann should no longer be possible.
Based on my microbench[0] measurement changing preempt_disable to local_irq_save will cost us 11 cycles (TSC). I'm not against the change, I just want people to keep this in mind.
On my E5-1650 v4 @ 3.60GHz:
- preempt_disable(+enable) cost: 11 cycles(tsc) 3.161 ns
- local_irq_save (+restore) cost: 22 cycles(tsc) 6.331 ns
Notice the non-save/restore variant is superfast:
- local_irq_disable(+enable) cost: 6 cycles(tsc) 1.844 ns
[0] https://github.com/netoptimizer/prototype-kernel/blob/master/kernel/lib/time_bench_sample.c
Quoted 139 lines
[1] https://lore.kernel.org/lkml/CAG48ez1mvUuXwg0YPH5ANzhQLpbphqk-ZS+jbRz+H66fvm4FcA@mail.gmail.com/
[2] https://lore.kernel.org/linux-rt-users/[email protected]/Reported-by Jann Horn <[email protected]>Suggested-by Mike Galbraith <[email protected]>Signed-off-by Vlastimil Babka <[email protected]>Cc Christoph Lameter <[email protected]>Cc David Rientjes <[email protected]>Cc Jesper Dangaard Brouer <[email protected]>Cc Joonsoo Kim <[email protected]>Cc Mel Gorman <[email protected]>Cc Pekka Enberg <[email protected]>Cc Qian Cai <[email protected]>Cc Sebastian Andrzej Siewior <[email protected]>Cc Thomas Gleixner <[email protected]>Signed-off-by Andrew Morton <[email protected]>---
mm/slub.c | 83 ++++++++++++++++++++++++++++------------------------ 1 file changed, 45 insertions(+), 38 deletions(-)mm/slub.c renamed from mm/slub.c~mm-slub-protect-put_cpu_partial-with-disabled-irqs-instead-of-cmpxchg +45
-38@@ -2025,7 +2025,12 @@ static inline void *acquire_slab(structreturn freelist; } +#ifdef CONFIG_SLUB_CPU_PARTIAL static void put_cpu_partial (struct kmem_cache *s,struct page *page,int drain); +#else +static inline void put_cpu_partial (struct kmem_cache *s,struct page *page, +int drain) { } +#endif static inline bool pfmemalloc_match (struct page *page,gfp_t gfpflags);/* @@ -2459,14 +2464,6 @@ static void unfreeze_partials_cpu(struct__unfreeze_partials (s, partial_page); } -#else /* CONFIG_SLUB_CPU_PARTIAL */ - -static inline void unfreeze_partials (struct kmem_cache *s) { } -static inline void unfreeze_partials_cpu (struct kmem_cache *s, -struct kmem_cache_cpu *c) { } - -#endif /* CONFIG_SLUB_CPU_PARTIAL */ -/* * Put a page that was just frozen (in __slab_free|get_partial_node) into a * partial page slot if available. @@ -2476,46 +2473,56 @@ static inline void unfreeze_partials_cpu*/ static void put_cpu_partial (struct kmem_cache *s,struct page *page,int drain) { -#ifdef CONFIG_SLUB_CPU_PARTIAL struct page *oldpage; -int pages; -int pobjects; +struct page *page_to_unfreeze =NULL ; +unsigned long flags; +int pages =0 ; +int pobjects =0 ; -preempt_disable (); -do { - pages =0 ; - pobjects =0 ; - oldpage =this_cpu_read (s->cpu_slab->partial); +local_irq_save (flags); + + oldpage =this_cpu_read (s->cpu_slab->partial); -if (oldpage) { +if (oldpage) { +if (drain && oldpage->pobjects >slub_cpu_partial (s)) { +/* +* Partial array is full. Move the existing set to the +* per node partial list. Postpone the actual unfreezing +* outside of the critical section. +*/ + page_to_unfreeze = oldpage; + oldpage =NULL ; + }else { pobjects = oldpage->pobjects; pages = oldpage->pages; -if (drain && pobjects >slub_cpu_partial (s)) { -/* -* partial array is full. Move the existing -* set to the per node partial list. -*/ -unfreeze_partials (s); - oldpage =NULL ; - pobjects =0 ; - pages =0 ; -stat (s,CPU_PARTIAL_DRAIN ); - } } + } - pages++; - pobjects += page->objects - page->inuse; + pages++; + pobjects += page->objects - page->inuse; - page->pages = pages; - page->pobjects = pobjects; - page->next = oldpage; - - }while (this_cpu_cmpxchg (s->cpu_slab->partial, oldpage, page) - != oldpage); -preempt_enable (); -#endif /* CONFIG_SLUB_CPU_PARTIAL */ + page->pages = pages; + page->pobjects = pobjects; + page->next = oldpage; + +this_cpu_write (s->cpu_slab->partial, page); + +local_irq_restore (flags); + +if (page_to_unfreeze) { +__unfreeze_partials (s, page_to_unfreeze); +stat (s,CPU_PARTIAL_DRAIN ); + } } +#else /* CONFIG_SLUB_CPU_PARTIAL */ + +static inline void unfreeze_partials (struct kmem_cache *s) { } +static inline void unfreeze_partials_cpu (struct kmem_cache *s, +struct kmem_cache_cpu *c) { } + +#endif /* CONFIG_SLUB_CPU_PARTIAL */ +static inline void flush_slab (struct kmem_cache *s,struct kmem_cache_cpu *c) {unsigned long flags;
Quoted 2 lines
_
$ uname -a Linux broadwell 5.14.0-net-next+ #612 SMP PREEMPT Wed Sep 8 10:10:04 CEST 2021 x86_64 x86_64 x86_64 GNU/Linux
My config:
$ zcat /proc/config.gz | grep PREE # CONFIG_PREEMPT_NONE is not set # CONFIG_PREEMPT_VOLUNTARY is not set CONFIG_PREEMPT=y CONFIG_PREEMPT_COUNT=y CONFIG_PREEMPTION=y CONFIG_PREEMPT_DYNAMIC=y CONFIG_PREEMPT_RCU=y CONFIG_HAVE_PREEMPT_DYNAMIC=y CONFIG_PREEMPT_NOTIFIERS=y # CONFIG_DEBUG_PREEMPT is not set # CONFIG_PREEMPT_TRACER is not set # CONFIG_PREEMPTIRQ_DELAY_TEST is not set
Re: [patch 031/147] mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
Quoted 42 lines · Jesper Dangaard Brouer
Quoted 30 lines · Andrew Morton
From: Vlastimil Babka <[email protected]>
Subject: mm, slub: protectput_cpu_partial()with disabled irqs instead of cmpxchgJann Horn reported [1] the following theoretically possible race:
task A:
put_cpu_partial()callspreempt_disable()
task A: oldpage =this_cpu_read(s->cpu_slab->partial)
interrupt:kfree()reachesunfreeze_partials()and discards the page task B (on another CPU): reallocates page as page cache
task A: readspage->pagesandpage->pobjects, which are actually halves of the pointerpage->lru.prev
task B (on another CPU): frees page
interrupt: allocates page as SLUB page and places it on the percpu partial list task A:this_cpu_cmpxchg()succeedswhich would cause
page->pagesandpage->pobjectsto end up containing halves of pointers that would then influence whenput_cpu_partial()happens and show up in root-only sysfs files. Maybe that's acceptable, I don't know. But there should probably at least be a comment for now to point out that we're reading union fields of a page that might be in a completely different state.Additionally, the
this_cpu_cmpxchg()approach input_cpu_partial()is only safe againsts->cpu_slab->partialmanipulation in___slab_alloc()if the latter disables irqs, otherwise a__slab_free()in an irq handler could callput_cpu_partial()in the middle of___slab_alloc()manipulating ->partial and corrupt it. This becomes an issue on RT after alocal_lockis introduced in later patch. The fix means taking thelocal_lockalso input_cpu_partial()on RT.Quoted 8 lines
After debugging this issue, Mike Galbraith suggested [2] that to avoid different locking schemes on RT and !RT, we can just protect
put_cpu_partial()with disabled irqs (to be converted tolocal_lock_irqsave()later) everywhere. This should be acceptable as it's not a fast path, and moving the actual partial unfreezing outside of the irq disabled section makes it short, and with the retry loop gone the code can be also simplified. In addition, the race reported by Jann should no longer be possible.
Quoted 3 lines
Based on my microbench[0] measurement changing
preempt_disabletolocal_irq_savewill cost us 11 cycles (TSC). I'm not against the change, I just want people to keep this in mind.
OK, but this is not a fast path for every allocation/free, so it gets amortized. Also it eliminates a this_cpu_cmpxchg loop, and I'd expect cmpxchg to be expensive too?
Quoted 6 lines
On my E5-1650 v4 @ 3.60GHz:
-preempt_disable(+enable)cost: 11 cycles(tsc) 3.161 ns
-local_irq_save(+restore) cost: 22 cycles(tsc) 6.331 nsNotice the non-save/restore variant is superfast:
-local_irq_disable(+enable)cost: 6 cycles(tsc) 1.844 ns
It actually surprises me that it's that cheap, and would have expected changing the irq state would be the costly part, not the saving/restoring. Incidentally, would you know what's the cost of save+restore when the irqs are already disabled, so it's effectively a no-op?
Thanks,
Vlastimil
Re: [patch 031/147] mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
Quoted 55 lines · Vlastimil Babka
Quoted 42 lines · Jesper Dangaard Brouer
Quoted 30 lines · Andrew Morton
From: Vlastimil Babka <[email protected]>
Subject: mm, slub: protectput_cpu_partial()with disabled irqs instead of cmpxchgJann Horn reported [1] the following theoretically possible race:
task A:
put_cpu_partial()callspreempt_disable()
task A: oldpage =this_cpu_read(s->cpu_slab->partial)
interrupt:kfree()reachesunfreeze_partials()and discards the page task B (on another CPU): reallocates page as page cache
task A: readspage->pagesandpage->pobjects, which are actually halves of the pointerpage->lru.prev
task B (on another CPU): frees page
interrupt: allocates page as SLUB page and places it on the percpu partial list task A:this_cpu_cmpxchg()succeedswhich would cause
page->pagesandpage->pobjectsto end up containing halves of pointers that would then influence whenput_cpu_partial()happens and show up in root-only sysfs files. Maybe that's acceptable, I don't know. But there should probably at least be a comment for now to point out that we're reading union fields of a page that might be in a completely different state.Additionally, the
this_cpu_cmpxchg()approach input_cpu_partial()is only safe againsts->cpu_slab->partialmanipulation in___slab_alloc()if the latter disables irqs, otherwise a__slab_free()in an irq handler could callput_cpu_partial()in the middle of___slab_alloc()manipulating ->partial and corrupt it. This becomes an issue on RT after alocal_lockis introduced in later patch. The fix means taking thelocal_lockalso input_cpu_partial()on RT.Quoted 8 lines
After debugging this issue, Mike Galbraith suggested [2] that to avoid different locking schemes on RT and !RT, we can just protect
put_cpu_partial()with disabled irqs (to be converted tolocal_lock_irqsave()later) everywhere. This should be acceptable as it's not a fast path, and moving the actual partial unfreezing outside of the irq disabled section makes it short, and with the retry loop gone the code can be also simplified. In addition, the race reported by Jann should no longer be possible.Quoted 3 lines
Based on my microbench[0] measurement changing
preempt_disabletolocal_irq_savewill cost us 11 cycles (TSC). I'm not against the change, I just want people to keep this in mind.OK, but this is not a fast path for every allocation/free, so it gets amortized. Also it eliminates a
this_cpu_cmpxchgloop, and I'd expect cmpxchg to be expensive too?Quoted 4 lines
On my E5-1650 v4 @ 3.60GHz:
-preempt_disable(+enable)cost: 11 cycles(tsc) 3.161 ns
-local_irq_save(+restore) cost: 22 cycles(tsc) 6.331 ns
Quoted 7 lines
Quoted 2 lines
Notice the non-save/restore variant is superfast:
-local_irq_disable(+enable)cost: 6 cycles(tsc) 1.844 nsIt actually surprises me that it's that cheap, and would have expected changing the irq state would be the costly part, not the saving/restoring. Incidentally, would you know what's the cost of save+restore when the irqs are already disabled, so it's effectively a no-op?
It surprises me as well. That would imply that protecting short RCU sections using
local_irq_disablelocal_irq_enable
instead of via
preempt_disablepreempt_enable
would actually be very beneficial.
Are the numbers trustworthy? :)
Signature · 3 lines
Thanks, David / dhildenb
Re: [patch 031/147] mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
Quoted 70 lines · David Hildenbrand
Quoted 55 lines · Vlastimil Babka
Quoted 42 lines · Jesper Dangaard Brouer
Quoted 30 lines · Andrew Morton
From: Vlastimil Babka <[email protected]>
Subject: mm, slub: protectput_cpu_partial()with disabled irqs instead of cmpxchgJann Horn reported [1] the following theoretically possible race:
task A:
put_cpu_partial()callspreempt_disable()
task A: oldpage =this_cpu_read(s->cpu_slab->partial)
interrupt:kfree()reachesunfreeze_partials()and discards the page task B (on another CPU): reallocates page as page cache
task A: readspage->pagesandpage->pobjects, which are actually halves of the pointerpage->lru.prev
task B (on another CPU): frees page
interrupt: allocates page as SLUB page and places it on the percpu partial list task A:this_cpu_cmpxchg()succeedswhich would cause
page->pagesandpage->pobjectsto end up containing halves of pointers that would then influence whenput_cpu_partial()happens and show up in root-only sysfs files. Maybe that's acceptable, I don't know. But there should probably at least be a comment for now to point out that we're reading union fields of a page that might be in a completely different state.Additionally, the
this_cpu_cmpxchg()approach input_cpu_partial()is only safe againsts->cpu_slab->partialmanipulation in___slab_alloc()if the latter disables irqs, otherwise a__slab_free()in an irq handler could callput_cpu_partial()in the middle of___slab_alloc()manipulating ->partial and corrupt it. This becomes an issue on RT after alocal_lockis introduced in later patch. The fix means taking thelocal_lockalso input_cpu_partial()on RT.Quoted 8 lines
After debugging this issue, Mike Galbraith suggested [2] that to avoid different locking schemes on RT and !RT, we can just protect
put_cpu_partial()with disabled irqs (to be converted tolocal_lock_irqsave()later) everywhere. This should be acceptable as it's not a fast path, and moving the actual partial unfreezing outside of the irq disabled section makes it short, and with the retry loop gone the code can be also simplified. In addition, the race reported by Jann should no longer be possible.Quoted 3 lines
Based on my microbench[0] measurement changing
preempt_disabletolocal_irq_savewill cost us 11 cycles (TSC). I'm not against the change, I just want people to keep this in mind.OK, but this is not a fast path for every allocation/free, so it gets amortized. Also it eliminates a
this_cpu_cmpxchgloop, and I'd expect cmpxchg to be expensive too?Quoted 4 lines
On my E5-1650 v4 @ 3.60GHz:
-preempt_disable(+enable)cost: 11 cycles(tsc) 3.161 ns
-local_irq_save(+restore) cost: 22 cycles(tsc) 6.331 nsQuoted 7 lines
Quoted 2 lines
Notice the non-save/restore variant is superfast:
-local_irq_disable(+enable)cost: 6 cycles(tsc) 1.844 nsIt actually surprises me that it's that cheap, and would have expected changing the irq state would be the costly part, not the saving/restoring. Incidentally, would you know what's the cost of save+restore when the irqs are already disabled, so it's effectively a no-op?
It surprises me as well. That would imply that protecting short RCU sections using
local_irq_disablelocal_irq_enable
Quoted 9 lines
instead of via
preempt_disablepreempt_enablewould actually be very beneficial.
Are the numbers trustworthy? :)
.. and especially did the benchmark consider side effects of enabling/disabling interrupts (pipeline flushes etc ..)?
Signature · 3 lines
Thanks, David / dhildenb
Re: [patch 031/147] mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
Quoted 72 lines · David Hildenbrand
Quoted 71 lines · David Hildenbrand
Quoted 56 lines · Vlastimil Babka
Quoted 43 lines · Jesper Dangaard Brouer
Quoted 31 lines · Andrew Morton
From: Vlastimil Babka <[email protected]>
Subject: mm, slub: protectput_cpu_partial()with disabled irqs instead of cmpxchgJann Horn reported [1] the following theoretically possible race:
task A:
put_cpu_partial()callspreempt_disable()
task A: oldpage =this_cpu_read(s->cpu_slab->partial)
interrupt:kfree()reachesunfreeze_partials()and discards the page task B (on another CPU): reallocates page as page cache
task A: readspage->pagesandpage->pobjects, which are actually halves of the pointerpage->lru.prev
task B (on another CPU): frees page
interrupt: allocates page as SLUB page and places it on the percpu partial list task A:this_cpu_cmpxchg()succeedswhich would cause
page->pagesandpage->pobjectsto end up containing halves of pointers that would then influence whenput_cpu_partial()happens and show up in root-only sysfs files. Maybe that's acceptable, I don't know. But there should probably at least be a comment for now to point out that we're reading union fields of a page that might be in a completely different state.Additionally, the
this_cpu_cmpxchg()approach input_cpu_partial()is only safe againsts->cpu_slab->partialmanipulation in___slab_alloc()if the latter disables irqs, otherwise a__slab_free()in an irq handler could callput_cpu_partial()in the middle of___slab_alloc()manipulating ->partial and corrupt it. This becomes an issue on RT after alocal_lock
is introduced in later patch. The fix means taking thelocal_lockalso input_cpu_partial()on RT.Quoted 8 lines
After debugging this issue, Mike Galbraith suggested [2] that to avoid different locking schemes on RT and !RT, we can just protect
put_cpu_partial()with disabled irqs (to be converted tolocal_lock_irqsave()later) everywhere. This should be acceptable as it's not a fast path, and moving the actual partial unfreezing outside of the irq disabled section makes it short, and with the retry loop gone the code can be also simplified. In addition, the race reported by Jann should no longer be possible.Quoted 3 lines
Based on my microbench[0] measurement changing
preempt_disabletolocal_irq_savewill cost us 11 cycles (TSC). I'm not against the change, I just want people to keep this in mind.OK, but this is not a fast path for every allocation/free, so it gets amortized. Also it eliminates a
this_cpu_cmpxchgloop, and I'd expect cmpxchg to be expensive too?Quoted 4 lines
On my E5-1650 v4 @ 3.60GHz:
- preempt_disable(+enable) cost: 11 cycles(tsc) 3.161 ns
-local_irq_save(+restore) cost: 22 cycles(tsc) 6.331 nsQuoted 7 lines
Quoted 2 lines
Notice the non-save/restore variant is superfast:
-local_irq_disable(+enable)cost: 6 cycles(tsc) 1.844 nsIt actually surprises me that it's that cheap, and would have expected changing the irq state would be the costly part, not the saving/restoring. Incidentally, would you know what's the cost of save+restore when the irqs are already disabled, so it's effectively a no-op?
It surprises me as well. That would imply that protecting short RCU sections using
local_irq_disablelocal_irq_enable
Quoted 6 lines
Quoted 6 lines
instead of via
preempt_disablepreempt_enablewould actually be very beneficial.
Please don't draw this as a general conclusion.
As Linus describe in details, the IRQ disable/enable will be very micro-arch specific.
The preempt_disable/enable will likely be more stable/consistent across micro-archs. Keep an eye out for kernel config options when juding preempt_disable/enable performance [1]
Quoted 6 lines
Quoted 3 lines
Are the numbers trustworthy? :)
.. and especially did the benchmark consider side effects of enabling/disabling interrupts (pipeline flushes etc ..)?
Of-cause not, this is a microbenchmark... they are per definition not trustworthy :-P
-Jesper
Re: [patch 031/147] mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
Quoted 94 lines · Jesper Dangaard Brouer
Quoted 91 lines · David Hildenbrand
Quoted 90 lines · David Hildenbrand
Quoted 72 lines · Vlastimil Babka
Quoted 59 lines · Jesper Dangaard Brouer
Quoted 43 lines · Andrew Morton
From: Vlastimil Babka <[email protected]>
Subject: mm, slub: protectput_cpu_partial()with disabled irqs instead of cmpxchgJann Horn reported [1] the following theoretically possible race:
task A:
put_cpu_partial()callspreempt_disable()task A: oldpage =this_cpu_read(s->cpu_slab->partial)
interrupt:kfree()reachesunfreeze_partials()and discards
the page
task B (on another CPU): reallocates page as page cache task A: readspage->pagesandpage->pobjects, which are actually halves of the pointerpage->lru.prev
task B (on another CPU): frees page
interrupt: allocates page as SLUB page and places it on the
percpu partial list
task A:this_cpu_cmpxchg()succeedswhich would cause
page->pagesandpage->pobjectsto end up
containing
halves of pointers that would then influence whenput_cpu_partial()
happens and show up in root-only sysfs files. Maybe that's
acceptable,
I don't know. But there should probably at least be a comment
for now
to point out that we're reading union fields of a page that
might be
in a completely different state.Additionally, the
this_cpu_cmpxchg()approach input_cpu_partial()is only
safe againsts->cpu_slab->partialmanipulation in___slab_alloc()if the
latter disables irqs, otherwise a__slab_free()in an irq handler could
callput_cpu_partial()in the middle of___slab_alloc()manipulating ->partial and corrupt it. This becomes an issue on RT after alocal_lock
is introduced in later patch. The fix means taking thelocal_lockalso input_cpu_partial()on RT.Quoted 12 lines
After debugging this issue, Mike Galbraith suggested [2] that to avoid different locking schemes on RT and !RT, we can just protect
put_cpu_partial()with disabled irqs (to be converted tolocal_lock_irqsave()later) everywhere. This should be acceptable as it's
not a fast path, and moving the actual partial unfreezing outside of the
irq disabled section makes it short, and with the retry loop gone the code
can be also simplified. In addition, the race reported by Jann should no
longer be possible.Quoted 3 lines
Based on my microbench[0] measurement changing
preempt_disabletolocal_irq_savewill cost us 11 cycles (TSC). I'm not against the change, I just want people to keep this in mind.OK, but this is not a fast path for every allocation/free, so it gets amortized. Also it eliminates a
this_cpu_cmpxchgloop, and I'd expect cmpxchg to be expensive too?Quoted 4 lines
On my E5-1650 v4 @ 3.60GHz:
- preempt_disable(+enable) cost: 11 cycles(tsc) 3.161 ns
-local_irq_save(+restore) cost: 22 cycles(tsc) 6.331 nsQuoted 8 lines
Quoted 2 lines
Notice the non-save/restore variant is superfast:
-local_irq_disable(+enable)cost: 6 cycles(tsc) 1.844 nsIt actually surprises me that it's that cheap, and would have expected changing the irq state would be the costly part, not the saving/restoring.
Incidentally, would you know what's the cost of save+restore when the irqs are already disabled, so it's effectively a no-op?It surprises me as well. That would imply that protecting short RCU sections using
local_irq_disablelocal_irq_enableinstead of via
Quoted 8 lines
Quoted 4 lines
Quoted 4 lines
preempt_disablepreempt_enablewould actually be very beneficial.
Please don't draw this as a general conclusion.
As Linus describe in details, the IRQ disable/enable will be very micro-arch specific.
Sure: but especially for modern micro-archs, this might be very relevant.
I actually stumbled over this exact question 1 month ago, that's why your comment caught my attention. I looked for CLI/STI cycle numbers and didn't really find a trusted source. I merely only found [1], which made it look like incrementing/decrementing some counter would actually be much faster most of the time.
[1] https://www.agner.org/optimize/instruction_tables.pdf
Quoted 14 lines
The preempt_disable/enable will likely be more stable/consistent across micro-archs.
Keep an eye out for kernel config options when juding preempt_disable/enable performance [1]Quoted 4 lines
Quoted 3 lines
Are the numbers trustworthy? :)
Quoted 6 lines
Quoted 3 lines
.. and especially did the benchmark consider side effects of enabling/disabling interrupts (pipeline flushes etc ..)?
Of-cause not, this is a microbenchmark... they are per definition not trustworthy :-P
:)
Signature · 3 lines
Thanks, David / dhildenb
Re: [patch 031/147] mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
In reply to Vlastimil BabkaQuoted 43 lines · Vlastimil Babka
Quoted 42 lines · Jesper Dangaard Brouer
Quoted 38 lines · Andrew Morton
From: Vlastimil Babka <[email protected]>
Subject: mm, slub: protectput_cpu_partial()with disabled irqs instead of cmpxchgJann Horn reported [1] the following theoretically possible race:
task A:
put_cpu_partial()callspreempt_disable()
task A: oldpage =this_cpu_read(s->cpu_slab->partial)
interrupt:kfree()reachesunfreeze_partials()and discards the page task B (on another CPU): reallocates page as page cache
task A: readspage->pagesandpage->pobjects, which are actually halves of the pointerpage->lru.prev
task B (on another CPU): frees page
interrupt: allocates page as SLUB page and places it on the percpu partial list task A:this_cpu_cmpxchg()succeedswhich would cause
page->pagesandpage->pobjectsto end up containing halves of pointers that would then influence whenput_cpu_partial()happens and show up in root-only sysfs files. Maybe that's acceptable, I don't know. But there should probably at least be a comment for now to point out that we're reading union fields of a page that might be in a completely different state.Additionally, the
this_cpu_cmpxchg()approach input_cpu_partial()is only safe againsts->cpu_slab->partialmanipulation in___slab_alloc()if the latter disables irqs, otherwise a__slab_free()in an irq handler could callput_cpu_partial()in the middle of___slab_alloc()manipulating ->partial and corrupt it. This becomes an issue on RT after alocal_lockis introduced in later patch. The fix means taking thelocal_lockalso input_cpu_partial()on RT.After debugging this issue, Mike Galbraith suggested [2] that to avoid different locking schemes on RT and !RT, we can just protect
put_cpu_partial()with disabled irqs (to be converted tolocal_lock_irqsave()later) everywhere. This should be acceptable as it's not a fast path, and moving the actual partial unfreezing outside of the irq disabled section makes it short, and with the retry loop gone the code can be also simplified. In addition, the race reported by Jann should no longer be possible.
Quoted 7 lines
Quoted 3 lines
Based on my microbench[0] measurement changing
preempt_disabletolocal_irq_savewill cost us 11 cycles (TSC). I'm not against the change, I just want people to keep this in mind.OK, but this is not a fast path for every allocation/free, so it gets amortized. Also it eliminates a
this_cpu_cmpxchgloop, and I'd expect cmpxchg to be expensive too?
Added tests for this:
- this_cpu_cmpxchg cost: 5 cycles(tsc) 1.581 ns
- cmpxchg cost: 18 cycles(tsc) 5.006 ns
Quoted 11 lines
Quoted 6 lines
On my E5-1650 v4 @ 3.60GHz:
-preempt_disable(+enable)cost: 11 cycles(tsc) 3.161 ns
-local_irq_save(+restore) cost: 22 cycles(tsc) 6.331 nsNotice the non-save/restore variant is superfast:
-local_irq_disable(+enable)cost: 6 cycles(tsc) 1.844 nsIt actually surprises me that it's that cheap, and would have expected changing the irq state would be the costly part, not the saving/restoring. Incidentally, would you know what's the cost of save+restore when the irqs are already disabled, so it's effectively a no-op?
The non-save variant simply translated onto CLI and STI, which seems to be very fast.
The cost of save+restore when the irqs are already disabled is the same (did a quick test). Cannot remember who told me, but (apparently) the expensive part is reading the CPU FLAGS.
I did a quick test with:
/** Loop to measure **/
for (i = 0; i < rec->loops; i++) {
local_irq_save(flags);
loops_cnt++;
barrier();
//local_irq_restore(flags);
local_irq_enable();
}Doing a save + enable: This cost 21 cycles(tsc) 6.015 ns. (Cost before was 22 cycles)
This confirms reading the CPU FLAGS seems to be the expensive part.
--Jesper
Re: [patch 031/147] mm, slub: protect put_cpu_partial() with disabled irqs instead of cmpxchg
Quoted 3 lines · Jesper Dangaard Brouer
The non-save variant simply translated onto CLI and STI, which seems to be very fast.
It will depend on the microarchitecture.
Happily:
Quoted 2 lines
The cost of save+restore when the irqs are already disabled is the same (did a quick test).
The really expensive part used to be P4. 'popf' was hundreds of cycles if any of the non-arithmetic bits changed, iirc.
P4 used to be a big headache just because of things like that - straightforward code ran very well, but anything a bit more special took forever because it flushed the pipeline.
So some of our optimizations may be historic because of things like that. We don't really need to worry about the P4 glass jaws any more, but it *used* to be much quicker to do 'preempt_disable()' that just does an add to a memory location than it was to disable interrupts.
Quoted 2 lines
Cannot remember who told me, but (apparently) the expensive part is reading the CPU FLAGS.
Again, it ends up being very dependent on the uarch.
Reading and writing the flags register is somewhat expensive because it's not really "one" register in hardware any more (even if that was obviously the historical implementation).
These days, the arithmetic flags are generally multiple renamed registers, and then the other flags are a separate system register (possibly multiple bits spread out).
The cost of doing those flag reads and writes are hard to really specify, because in an OoO architecture a lot of it ends up being "how much of that can be done in parallel, and what's the pipeline serialization cost". Doing a loop with rdtsc is not necessarily AT ALL indicative of the cost when there is other real code around it.
The cost _could_ be much smaller, in case there is little serialization with normal other code. Or, it could be much bigger than what a rdtsc shows, because if it's a hard pipeline flush, then a tight loop with those things won't have any real work to flush, while in "real code" there may be hundreds of instructions in flight and doing the flush is very expensive.
The good news is that afaik, all the modern x86 CPU microarchitectures do reasonably well. And while a "pushf/cli/popf" sequence is probably more cycles than an add/subtract one in a benchmark, if the preempt counter is not otherwise needed, and is cold in the cache, then the pushf/cli/popf may be *much* cheaper than a cache miss.
So the only way to really tell would be to run real benchmarks of real loads on multiple different microarchitectures.
I'm pretty sure the actual result is: "you can't measure the 10-cycle difference on any modern core because it can actually go either way".
But "I'm pretty sure" and "reality" are not the same thing.
These days, pipeline flushes and cache misses (and then as a very particularly bad case - cache line pingpong issues) are almost the only thing that matters.
And the most common reason by far for the pipeline flushes are branch mispredicts, but see above: the system bits in the flags register _have_ been cause of them in the past, so it's not entirely impossible.
Linus
Andrew Morton
maintainerPATCH 32/147 mm, slub: use migrate_disable() on PREEMPT_RT
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: use migrate_disable() on PREEMPT_RT
We currently use preempt_disable() (directly or via get_cpu_ptr()) to stabilize the pointer to kmem_cache_cpu. On PREEMPT_RT this would be incompatible with the list_lock spinlock. We can use migrate_disable() instead, but that increases overhead on !PREEMPT_RT as it's an unconditional function call.
In order to get the best available mechanism on both PREEMPT_RT and !PREEMPT_RT, introduce private slub_get_cpu_ptr() and slub_put_cpu_ptr() wrappers and use them.
---
mm/slub.c | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-)
mm/slub.c renamed from mm/slub.c~mm-slub-use-migrate_disable-on-preempt_rt +30 -9
@@ -118,6 +118,26 @@* the fast path and disables lockless freelists. */ +/* +* We could simply use migrate_disable()/enable() but as long as it's a +* function call even on !PREEMPT_RT, use inline preempt_disable() there. +*/ +#ifndef CONFIG_PREEMPT_RT +#define slub_get_cpu_ptr (var) get_cpu_ptr(var) +#define slub_put_cpu_ptr (var) put_cpu_ptr(var) +#else +#define slub_get_cpu_ptr (var) \ +({ \ + migrate_disable(); \ + this_cpu_ptr(var); \ +}) +#define slub_put_cpu_ptr (var) \ +do { \ + (void)(var); \ + migrate_enable(); \ +} while (0) +#endif +#ifdef CONFIG_SLUB_DEBUG #ifdef CONFIG_SLUB_DEBUG_ON DEFINE_STATIC_KEY_TRUE (slub_debug_enabled);
@@ -2852,7 +2872,7 @@ redo:if (unlikely (!pfmemalloc_match_unsafe (page, gfpflags))) goto deactivate_slab; -/* must check again c->page in case IRQ handler changed it */ +/* must check again c->page in case we got preempted and it changed */ local_irq_save (flags);if (unlikely (page != c->page)) {local_irq_restore (flags);
@@ -2911,7 +2931,8 @@ new_slab: }if (unlikely (!slub_percpu_partial (c))) {local_irq_restore (flags); - goto new_objects;/* stolen by an IRQ handler */ +/* we were preempted and partial list got empty */ + goto new_objects; } page = c->page =slub_percpu_partial (c);
@@ -2927,9 +2948,9 @@ new_objects:if (freelist) goto check_new_page; -put_cpu_ptr (s->cpu_slab); +slub_put_cpu_ptr (s->cpu_slab); page =new_slab (s, gfpflags, node); - c =get_cpu_ptr (s->cpu_slab); + c =slub_get_cpu_ptr (s->cpu_slab);if (unlikely (!page)) {slab_out_of_memory (s, gfpflags, node);
@@ -3012,12 +3033,12 @@ static void *__slab_alloc(struct kmem_ca* cpu before disabling preemption. Need to reload cpu area * pointer. */ - c =get_cpu_ptr (s->cpu_slab); + c =slub_get_cpu_ptr (s->cpu_slab);#endif p =___slab_alloc (s, gfpflags, node, addr, c);#ifdef CONFIG_PREEMPT_COUNT -put_cpu_ptr (s->cpu_slab); +slub_put_cpu_ptr (s->cpu_slab);#endif return p; }
@@ -3546,7 +3567,7 @@ int kmem_cache_alloc_bulk(struct kmem_ca* IRQs, which protects against PREEMPT and interrupts * handlers invoking normal fastpath. */ - c =get_cpu_ptr (s->cpu_slab); + c =slub_get_cpu_ptr (s->cpu_slab);local_irq_disable ();for (i =0 ; i < size; i++) {
@@ -3592,7 +3613,7 @@ int kmem_cache_alloc_bulk(struct kmem_ca } c->tid =next_tid (c->tid);local_irq_enable (); -put_cpu_ptr (s->cpu_slab); +slub_put_cpu_ptr (s->cpu_slab);/* * memcg and kmem_cache debug support and memory initialization.
@@ -3602,7 +3623,7 @@ int kmem_cache_alloc_bulk(struct kmem_ca slab_want_init_on_alloc(flags, s));return i; error: -put_cpu_ptr (s->cpu_slab); +slub_put_cpu_ptr (s->cpu_slab);slab_post_alloc_hook (s, objcg, flags, i, p, false);__kmem_cache_free_bulk (s, i, p);return 0 ;
_
Andrew Morton
maintainerPATCH 33/147 mm, slub: convert kmem_cpu_slab protection to local_lock
In reply to Andrew MortonFrom: Vlastimil Babka <[email protected]>
Subject: mm, slub: convert kmem_cpu_slab protection to local_lock
Embed local_lock into struct kmem_cpu_slab and use the irq-safe versions of local_lock instead of plain local_irq_save/restore. On !PREEMPT_RT that's equivalent, with better lockdep visibility. On PREEMPT_RT that means better preemption.
However, the cost on PREEMPT_RT is the loss of lockless fast paths which only work with cpu freelist. Those are designed to detect and recover from being preempted by other conflicting operations (both fast or slow path), but the slow path operations assume they cannot be preempted by a fast path operation, which is guaranteed naturally with disabled irqs. With local locks on PREEMPT_RT, the fast paths now also need to take the local lock to avoid races.
In the allocation fastpath slab_alloc_node() we can just defer to the slowpath __slab_alloc() which also works with cpu freelist, but under the local lock. In the free fastpath do_slab_free() we have to add a new local lock protected version of freeing to the cpu freelist, as the existing slowpath only works with the page freelist.
Also update the comment about locking scheme in SLUB to reflect changes done by this series.
[ Mike Galbraith <[email protected]>: use local_lock() without irq in PREEMPT_RT
scope; debugging of RT crashes resulting in put_cpu_partial() locking changes ]
---
include/linux/slub_def.h | 6 + mm/slub.c | 146 ++++++++++++++++++++++++++++--------- 2 files changed, 117 insertions(+), 35 deletions(-)
include/linux/slub_def.h renamed from include/linux/slub_def.h~mm-slub-convert-kmem_cpu_slab-protection-to-local_lock +6 -0
@@ -10,6 +10,7 @@#include <linux/kfence.h> #include <linux/kobject.h> #include <linux/reciprocal_div.h> +#include <linux/local_lock.h> enum stat_item {ALLOC_FASTPATH ,/* Allocation from cpu slab */
@@ -40,6 +41,10 @@ enum stat_item {CPU_PARTIAL_DRAIN ,/* Drain cpu partial to node partial */ NR_SLUB_STAT_ITEMS }; +/* +* When changing the layout, make sure freelist and tid are still compatible +* with this_cpu_cmpxchg_double() alignment requirements. +*/ struct kmem_cache_cpu {void **freelist;/* Pointer to next available object */ unsigned long tid;/* Globally unique transaction id */
@@ -47,6 +52,7 @@ struct kmem_cache_cpu {#ifdef CONFIG_SLUB_CPU_PARTIAL struct page *partial;/* Partially allocated frozen slabs */ #endif +local_lock_t lock;/* Protects the fields above */ #ifdef CONFIG_SLUB_STATS unsigned stat[NR_SLUB_STAT_ITEMS ];#endif
mm/slub.c renamed from mm/slub.c~mm-slub-convert-kmem_cpu_slab-protection-to-local_lock +111 -35
330 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 34/147 memory-hotplug.rst: remove locking details from admin-guide
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: memory-hotplug.rst: remove locking details from admin-guide
Patch series "memory-hotplug.rst: complete admin-guide overhaul", v3.
This patch (of 2):
We have the same content at Documentation/core-api/memory-hotplug.rst and it doesn't fit into the admin-guide. The documentation was accidentially duplicated when merging.
---
Documentation/admin-guide/mm/memory-hotplug.rst | 39 -------------- 1 file changed, 39 deletions(-)
Documentation/admin-guide/mm/memory-hotplug.rst renamed from Documentation/admin-guide/mm/memory-hotplug.rst~memory-hotplugrst-remove-locking-details-from-admin-guide +0 -39
@@ -415,45 +415,6 @@ Need more implementation yet.... - Guard from remove if not yet. -Locking Internals -================= - -When adding/removing memory that uses memory block devices (i.e. ordinary RAM), -the device_hotplug_lock should be held to: - -- synchronize against online/offline requests (e.g. via sysfs). This way, memory - block devices can only be accessed (.online/.state attributes) by user - space once memory has been fully added. And when removing memory, we - know nobody is in critical sections. -- synchronize against CPU hotplug and similar (e.g. relevant for ACPI and PPC) - -Especially, there is a possible lock inversion that is avoided using -device_hotplug_lock when adding memory and user space tries to online that -memory faster than expected: - -- device_online() will first take the device_lock(), followed by - mem_hotplug_lock -- add_memory_resource() will first take the mem_hotplug_lock, followed by - the device_lock() (while creating the devices, during bus_add_device()). - -As the device is visible to user space before taking the device_lock(), this -can result in a lock inversion. - -onlining/offlining of memory should be done via device_online()/ -device_offline() - to make sure it is properly synchronized to actions -via sysfs. Holding device_hotplug_lock is advised (to e.g. protect online_type) - -When adding/removing/onlining/offlining memory or adding/removing -heterogeneous/device memory, we should always hold the mem_hotplug_lock in -write mode to serialise memory hotplug (e.g. access to global/zone -variables). - -In addition, mem_hotplug_lock (in contrast to device_hotplug_lock) in read -mode allows for a quite efficient get_online_mems/put_online_mems -implementation, so code accessing memory can protect from that memory -vanishing. - - Future Work ===========
_
Andrew Morton
maintainerPATCH 35/147 memory-hotplug.rst: complete admin-guide overhaul
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: memory-hotplug.rst: complete admin-guide overhaul
The memory hot(un)plug documentation is outdated and incomplete. Most of the content dates back to 2007, so it's time for a major overhaul.
Let's rewrite, reorganize and update most parts of the documentation. In addition to memory hot(un)plug, also add some details regarding ZONE_MOVABLE, with memory hotunplug being one of its main consumers.
Drop the file history, that information can more reliably be had from the git log.
The style of the document is also properly fixed that e.g., "restview" renders it cleanly now.
In the future, we might add some more details about virt users like virtio-mem, the XEN balloon, the Hyper-V balloon and ppc64 dlpar.
---
Documentation/admin-guide/mm/memory-hotplug.rst | 803 ++++++++------ 1 file changed, 476 insertions(+), 327 deletions(-)
Documentation/admin-guide/mm/memory-hotplug.rst renamed from Documentation/admin-guide/mm/memory-hotplug.rst~memory-hotplugrst-complete-admin-guide-overhaul +476 -327
@@ -1,427 +1,576 @@ .. _admin_guide_memory_hotplug: -============== -Memory Hotplug -============== - -:Created: Jul 28 2007 -:Updated: Add some details about locking internals: Aug 20 2018 - -This document is about memory hotplug including how-to-use and current status. -Because Memory Hotplug is still under development, contents of this text will -be changed often. +================== +Memory Hot(Un)Plug +================== + +This document describes generic Linux support for memory hot(un)plug with +a focus on System RAM, including ZONE_MOVABLE support. .. contents:: :local: -.. note:: +Introduction +============ - (1) x86_64's has special implementation for memory hotplug. - This text does not describe it. - (2) This text assumes that sysfs is mounted at ``/sys``. +Memory hot(un)plug allows for increasing and decreasing the size of physical +memory available to a machine at runtime. In the simplest case, it consists of +physically plugging or unplugging a DIMM at runtime, coordinated with the +operating system. + +Memory hot(un)plug is used for various purposes: + +- The physical memory available to a machine can be adjusted at runtime, up- or + downgrading the memory capacity. This dynamic memory resizing, sometimes + referred to as "capacity on demand", is frequently used with virtual machines + and logical partitions. + +- Replacing hardware, such as DIMMs or whole NUMA nodes, without downtime. One + example is replacing failing memory modules. + +- Reducing energy consumption either by physically unplugging memory modules or + by logically unplugging (parts of) memory modules from Linux. + +Further, the basic memory hot(un)plug infrastructure in Linux is nowadays also +used to expose persistent memory, other performance-differentiated memory and +reserved memory regions as ordinary system RAM to Linux. + +Linux only supports memory hot(un)plug on selected 64 bit architectures, such as +x86_64, arm64, ppc64, s390x and ia64. + +Memory Hot(Un)Plug Granularity +------------------------------ + +Memory hot(un)plug in Linux uses the SPARSEMEM memory model, which divides the +physical memory address space into chunks of the same size: memory sections. The +size of a memory section is architecture dependent. For example, x86_64 uses +128 MiB and ppc64 uses 16 MiB. +Memory sections are combined into chunks referred to as "memory blocks". The +size of a memory block is architecture dependent and corresponds to the smallest +granularity that can be hot(un)plugged. The default size of a memory block is +the same as memory section size, unless an architecture specifies otherwise. -Introduction -============ +All memory blocks have the same size. -Purpose of memory hotplug -------------------------- +Phases of Memory Hotplug +------------------------ -Memory Hotplug allows users to increase/decrease the amount of memory. -Generally, there are two purposes. +Memory hotplug consists of two phases: -(A) For changing the amount of memory. - This is to allow a feature like capacity on demand. -(B) For installing/removing DIMMs or NUMA-nodes physically. - This is to exchange DIMMs/NUMA-nodes, reduce power consumption, etc. +(1) Adding the memory to Linux +(2) Onlining memory blocks -(A) is required by highly virtualized environments and (B) is required by -hardware which supports memory power management. +In the first phase, metadata, such as the memory map ("memmap") and page tables +for the direct mapping, is allocated and initialized, and memory blocks are +created; the latter also creates sysfs files for managing newly created memory +blocks. -Linux memory hotplug is designed for both purpose. +In the second phase, added memory is exposed to the page allocator. After this +phase, the memory is visible in memory statistics, such as free and total +memory, of the system. -Phases of memory hotplug ------------------------- +Phases of Memory Hotunplug +-------------------------- -There are 2 phases in Memory Hotplug: +Memory hotunplug consists of two phases: - 1) Physical Memory Hotplug phase - 2) Logical Memory Hotplug phase. +(1) Offlining memory blocks +(2) Removing the memory from Linux -The First phase is to communicate hardware/firmware and make/erase -environment for hotplugged memory. Basically, this phase is necessary -for the purpose (B), but this is good phase for communication between -highly virtualized environments too. - -When memory is hotplugged, the kernel recognizes new memory, makes new memory -management tables, and makes sysfs files for new memory's operation. - -If firmware supports notification of connection of new memory to OS, -this phase is triggered automatically. ACPI can notify this event. If not, -"probe" operation by system administration is used instead. -(see :ref:`memory_hotplug_physical_mem`). - -Logical Memory Hotplug phase is to change memory state into -available/unavailable for users. Amount of memory from user's view is -changed by this phase. The kernel makes all memory in it as free pages -when a memory range is available. - -In this document, this phase is described as online/offline. - -Logical Memory Hotplug phase is triggered by write of sysfs file by system -administrator. For the hot-add case, it must be executed after Physical Hotplug -phase by hand. -(However, if you writes udev's hotplug scripts for memory hotplug, these -phases can be execute in seamless way.) - -Unit of Memory online/offline operation ---------------------------------------- - -Memory hotplug uses SPARSEMEM memory model which allows memory to be divided -into chunks of the same size. These chunks are called "sections". The size of -a memory section is architecture dependent. For example, power uses 16MiB, ia64 -uses 1GiB. +In the fist phase, memory is "hidden" from the page allocator again, for +example, by migrating busy memory to other memory locations and removing all +relevant free pages from the page allocator After this phase, the memory is no +longer visible in memory statistics of the system. -Memory sections are combined into chunks referred to as "memory blocks". The -size of a memory block is architecture dependent and represents the logical -unit upon which memory online/offline operations are to be performed. The -default size of a memory block is the same as memory section size unless an -architecture specifies otherwise. (see :ref:`memory_hotplug_sysfs_files`.) +In the second phase, the memory blocks are removed and metadata is freed. -To determine the size (in bytes) of a memory block please read this file:: +Memory Hotplug Notifications +============================ - /sys/devices/system/memory/block_size_bytes +There are various ways how Linux is notified about memory hotplug events such +that it can start adding hotplugged memory. This description is limited to +systems that support ACPI; mechanisms specific to other firmware interfaces or +virtual machines are not described. -Kernel Configuration -==================== +ACPI Notifications +------------------ -To use memory hotplug feature, kernel must be compiled with following -config options. +Platforms that support ACPI, such as x86_64, can support memory hotplug +notifications via ACPI. -- For all memory hotplug: - - Memory model -> Sparse Memory (``CONFIG_SPARSEMEM``) - - Allow for memory hot-add (``CONFIG_MEMORY_HOTPLUG``) +In general, a firmware supporting memory hotplug defines a memory class object +HID "PNP0C80". When notified about hotplug of a new memory device, the ACPI +driver will hotplug the memory to Linux. -- To enable memory removal, the following are also necessary: - - Allow for memory hot remove (``CONFIG_MEMORY_HOTREMOVE``) - - Page Migration (``CONFIG_MIGRATION``) +If the firmware supports hotplug of NUMA nodes, it defines an object _HID +"ACPI0004", "PNP0A05", or "PNP0A06". When notified about an hotplug event, all +assigned memory devices are added to Linux by the ACPI driver. -- For ACPI memory hotplug, the following are also necessary: - - Memory hotplug (under ACPI Support menu) (``CONFIG_ACPI_HOTPLUG_MEMORY``) - - This option can be kernel module. +Similarly, Linux can be notified about requests to hotunplug a memory device or +a NUMA node via ACPI. The ACPI driver will try offlining all relevant memory +blocks, and, if successful, hotunplug the memory from Linux. -- As a related configuration, if your box has a feature of NUMA-node hotplug - via ACPI, then this option is necessary too. +Manual Probing +-------------- - - ACPI0004,PNP0A05 and PNP0A06 Container Driver (under ACPI Support menu) - (``CONFIG_ACPI_CONTAINER``). +On some architectures, the firmware may not be able to notify the operating +system about a memory hotplug event. Instead, the memory has to be manually +probed from user space. - This option can be kernel module too. +The probe interface is located at:: + /sys/devices/system/memory/probe -.. _memory_hotplug_sysfs_files: +Only complete memory blocks can be probed. Individual memory blocks are probed +by providing the physical start address of the memory block:: -sysfs files for memory hotplug -============================== + % echo addr > /sys/devices/system/memory/probe -All memory blocks have their device information in sysfs. Each memory block -is described under ``/sys/devices/system/memory`` as:: +Which results in a memory block for the range [addr, addr + memory_block_size) +being created. - /sys/devices/system/memory/memoryXXX +.. note:: -where XXX is the memory block id. + Using the probe interface is discouraged as it is easy to crash the kernel, + because Linux cannot validate user input; this interface might be removed in + the future. + +Onlining and Offlining Memory Blocks +==================================== + +After a memory block has been created, Linux has to be instructed to actually +make use of that memory: the memory block has to be "online". + +Before a memory block can be removed, Linux has to stop using any memory part of +the memory block: the memory block has to be "offlined". + +The Linux kernel can be configured to automatically online added memory blocks +and drivers automatically trigger offlining of memory blocks when trying +hotunplug of memory. Memory blocks can only be removed once offlining succeeded +and drivers may trigger offlining of memory blocks when attempting hotunplug of +memory. -For the memory block covered by the sysfs directory. It is expected that all -memory sections in this range are present and no memory holes exist in the -range. Currently there is no way to determine if there is a memory hole, but -the existence of one should not affect the hotplug capabilities of the memory -block. +Onlining Memory Blocks Manually +------------------------------- -For example, assume 1GiB memory block size. A device for a memory starting at -0x100000000 is ``/sys/device/system/memory/memory4``:: +If auto-onlining of memory blocks isn't enabled, user-space has to manually +trigger onlining of memory blocks. Often, udev rules are used to automate this +task in user space. - (0x100000000 / 1Gib = 4) +Onlining of a memory block can be triggered via:: -This device covers address range [0x100000000 ... 0x140000000) + % echo online > /sys/devices/system/memory/memoryXXX/state -Under each memory block, you can see 5 files: +Or alternatively:: -- ``/sys/devices/system/memory/memoryXXX/phys_index`` -- ``/sys/devices/system/memory/memoryXXX/phys_device`` -- ``/sys/devices/system/memory/memoryXXX/state`` -- ``/sys/devices/system/memory/memoryXXX/removable`` -- ``/sys/devices/system/memory/memoryXXX/valid_zones`` + % echo 1 > /sys/devices/system/memory/memoryXXX/online -=================== ============================================================ -``phys_index`` read-only and contains memory block id, same as XXX. -``state`` read-write +The kernel will select the target zone automatically, usually defaulting to +``ZONE_NORMAL`` unless ``movablecore=1`` has been specified on the kernel +command line or if the memory block would intersect the ZONE_MOVABLE already. - - at read: contains online/offline state of memory. - - at write: user can specify "online_kernel", +One can explicitly request to associate an offline memory block with +ZONE_MOVABLE by:: - "online_movable", "online", "offline" command - which will be performed on all sections in the block. -``phys_device`` read-only: legacy interface only ever used on s390x to - expose the covered storage increment. -``removable`` read-only: legacy interface that indicated whether a memory - block was likely to be offlineable or not. Newer kernel - versions return "1" if and only if the kernel supports - memory offlining. -``valid_zones`` read-only: designed to show by which zone memory provided by - a memory block is managed, and to show by which zone memory - provided by an offline memory block could be managed when - onlining. - - The first column shows it`s default zone. - - "memory6/valid_zones: Normal Movable" shows this memoryblock - can be onlined to ZONE_NORMAL by default and to ZONE_MOVABLE - by online_movable. - - "memory7/valid_zones: Movable Normal" shows this memoryblock - can be onlined to ZONE_MOVABLE by default and to ZONE_NORMAL - by online_kernel. -=================== ============================================================ + % echo online_movable > /sys/devices/system/memory/memoryXXX/state -.. note:: +Or one can explicitly request a kernel zone (usually ZONE_NORMAL) by:: - These directories/files appear after physical memory hotplug phase. + % echo online_kernel > /sys/devices/system/memory/memoryXXX/state -If CONFIG_NUMA is enabled the memoryXXX/ directories can also be accessed -via symbolic links located in the ``/sys/devices/system/node/node*`` directories. +In any case, if onlining succeeds, the state of the memory block is changed to +be "online". If it fails, the state of the memory block will remain unchanged +and the above commands will fail. + +Onlining Memory Blocks Automatically +------------------------------------ + +The kernel can be configured to try auto-onlining of newly added memory blocks. +If this feature is disabled, the memory blocks will stay offline until +explicitly onlined from user space. -For example:: +The configured auto-online behavior can be observed via:: - /sys/devices/system/node/node0/memory9 -> ../../memory/memory9 + % cat /sys/devices/system/memory/auto_online_blocks -A backlink will also be created:: +Auto-onlining can be enabled by writing ``online``, ``online_kernel`` or +``online_movable`` to that file, like:: - /sys/devices/system/memory/memory9/node0 -> ../../node/node0 + % echo online > /sys/devices/system/memory/auto_online_blocks -.. _memory_hotplug_physical_mem: +Modifying the auto-online behavior will only affect all subsequently added +memory blocks only. -Physical memory hot-add phase -============================= +.. note:: -Hardware(Firmware) Support --------------------------- + In corner cases, auto-onlining can fail. The kernel won't retry. Note that + auto-onlining is not expected to fail in default configurations. -On x86_64/ia64 platform, memory hotplug by ACPI is supported. +.. note:: -In general, the firmware (ACPI) which supports memory hotplug defines -memory class object of _HID "PNP0C80". When a notify is asserted to PNP0C80, -Linux's ACPI handler does hot-add memory to the system and calls a hotplug udev -script. This will be done automatically. - -But scripts for memory hotplug are not contained in generic udev package(now). -You may have to write it by yourself or online/offline memory by hand. -Please see :ref:`memory_hotplug_how_to_online_memory` and -:ref:`memory_hotplug_how_to_offline_memory`. - -If firmware supports NUMA-node hotplug, and defines an object _HID "ACPI0004", -"PNP0A05", or "PNP0A06", notification is asserted to it, and ACPI handler -calls hotplug code for all of objects which are defined in it. -If memory device is found, memory hotplug code will be called. - -Notify memory hot-add event by hand ------------------------------------ - -On some architectures, the firmware may not notify the kernel of a memory -hotplug event. Therefore, the memory "probe" interface is supported to -explicitly notify the kernel. This interface depends on -CONFIG_ARCH_MEMORY_PROBE and can be configured on powerpc, sh, and x86 -if hotplug is supported, although for x86 this should be handled by ACPI -notification. + DLPAR on ppc64 ignores the ``offline`` setting and will still online added + memory blocks; if onlining fails, memory blocks are removed again. -Probe interface is located at:: +Offlining Memory Blocks +----------------------- - /sys/devices/system/memory/probe +In the current implementation, Linux's memory offlining will try migrating all +movable pages off the affected memory block. As most kernel allocations, such as +page tables, are unmovable, page migration can fail and, therefore, inhibit +memory offlining from succeeding. -You can tell the physical address of new memory to the kernel by:: +Having the memory provided by memory block managed by ZONE_MOVABLE significantly +increases memory offlining reliability; still, memory offlining can fail in +some corner cases. - % echo start_address_of_new_memory > /sys/devices/system/memory/probe +Further, memory offlining might retry for a long time (or even forever), until +aborted by the user. -Then, [start_address_of_new_memory, start_address_of_new_memory + -memory_block_size] memory range is hot-added. In this case, hotplug script is -not called (in current implementation). You'll have to online memory by -yourself. Please see :ref:`memory_hotplug_how_to_online_memory`. +Offlining of a memory block can be triggered via:: -Logical Memory hot-add phase -============================ + % echo offline > /sys/devices/system/memory/memoryXXX/state -State of memory ---------------- +Or alternatively:: -To see (online/offline) state of a memory block, read 'state' file:: + % echo 0 > /sys/devices/system/memory/memoryXXX/online + +If offlining succeeds, the state of the memory block is changed to be "offline". +If it fails, the state of the memory block will remain unchanged and the above +commands will fail, for example, via:: + + bash: echo: write error: Device or resource busy + +or via:: + + bash: echo: write error: Invalid argument + +Observing the State of Memory Blocks +------------------------------------ + +The state (online/offline/going-offline) of a memory block can be observed +either via:: % cat /sys/device/system/memory/memoryXXX/state +Or alternatively (1/0) via:: -- If the memory block is online, you'll read "online". -- If the memory block is offline, you'll read "offline". + % cat /sys/device/system/memory/memoryXXX/online +For an online memory block, the managing zone can be observed via:: -.. _memory_hotplug_how_to_online_memory: + % cat /sys/device/system/memory/memoryXXX/valid_zones -How to online memory --------------------- +Configuring Memory Hot(Un)Plug +============================== -When the memory is hot-added, the kernel decides whether or not to "online" -it according to the policy which can be read from "auto_online_blocks" file:: +There are various ways how system administrators can configure memory +hot(un)plug and interact with memory blocks, especially, to online them. - % cat /sys/devices/system/memory/auto_online_blocks +Memory Hot(Un)Plug Configuration via Sysfs +------------------------------------------ -The default depends on the CONFIG_MEMORY_HOTPLUG_DEFAULT_ONLINE kernel config -option. If it is disabled the default is "offline" which means the newly added -memory is not in a ready-to-use state and you have to "online" the newly added -memory blocks manually. Automatic onlining can be requested by writing "online" -to "auto_online_blocks" file:: +Some memory hot(un)plug properties can be configured or inspected via sysfs in:: - % echo online > /sys/devices/system/memory/auto_online_blocks + /sys/devices/system/memory/ -This sets a global policy and impacts all memory blocks that will subsequently -be hotplugged. Currently offline blocks keep their state. It is possible, under -certain circumstances, that some memory blocks will be added but will fail to -online. User space tools can check their "state" files -(``/sys/devices/system/memory/memoryXXX/state``) and try to online them manually. - -If the automatic onlining wasn't requested, failed, or some memory block was -offlined it is possible to change the individual block's state by writing to the -"state" file:: +The following files are currently defined: - % echo online > /sys/devices/system/memory/memoryXXX/state +====================== ========================================================= +``auto_online_blocks`` read-write: set or get the default state of new memory + blocks; configure auto-onlining. -This onlining will not change the ZONE type of the target memory block, -If the memory block doesn't belong to any zone an appropriate kernel zone -(usually ZONE_NORMAL) will be used unless movable_node kernel command line -option is specified when ZONE_MOVABLE will be used. + The default value depends on the + CONFIG_MEMORY_HOTPLUG_DEFAULT_ONLINE kernel configuration + option. -You can explicitly request to associate it with ZONE_MOVABLE by:: + See the ``state`` property of memory blocks for details. +``block_size_bytes`` read-only: the size in bytes of a memory block. +``probe`` write-only: add (probe) selected memory blocks manually + from user space by supplying the physical start address. - % echo online_movable > /sys/devices/system/memory/memoryXXX/state + Availability depends on the CONFIG_ARCH_MEMORY_PROBE + kernel configuration option. +``uevent`` read-write: generic udev file for device subsystems. +====================== ========================================================= -.. note:: current limit: this memory block must be adjacent to ZONE_MOVABLE +.. note:: -Or you can explicitly request a kernel zone (usually ZONE_NORMAL) by:: + When the CONFIG_MEMORY_FAILURE kernel configuration option is enabled, two + additional files ``hard_offline_page`` and ``soft_offline_page`` are available + to trigger hwpoisoning of pages, for example, for testing purposes. Note that + this functionality is not really related to memory hot(un)plug or actual + offlining of memory blocks. + +Memory Block Configuration via Sysfs +------------------------------------ + +Each memory block is represented as a memory block device that can be +onlined or offlined. All memory blocks have their device information located in +sysfs. Each present memory block is listed under +``/sys/devices/system/memory`` as:: - % echo online_kernel > /sys/devices/system/memory/memoryXXX/state + /sys/devices/system/memory/memoryXXX -.. note:: current limit: this memory block must be adjacent to ZONE_NORMAL +where XXX is the memory block id; the number of digits is variable. -An explicit zone onlining can fail (e.g. when the range is already within -and existing and incompatible zone already). +A present memory block indicates that some memory in the range is present; +however, a memory block might span memory holes. A memory block spanning memory +holes cannot be offlined. -After this, memory block XXX's state will be 'online' and the amount of -available memory will be increased. +For example, assume 1 GiB memory block size. A device for a memory starting at +0x100000000 is ``/sys/device/system/memory/memory4``:: -This may be changed in future. + (0x100000000 / 1Gib = 4) -Logical memory remove -===================== +This device covers address range [0x100000000 ... 0x140000000) -Memory offline and ZONE_MOVABLE -------------------------------- +The following files are currently defined: -Memory offlining is more complicated than memory online. Because memory offline -has to make the whole memory block be unused, memory offline can fail if -the memory block includes memory which cannot be freed. - -In general, memory offline can use 2 techniques. - -(1) reclaim and free all memory in the memory block. -(2) migrate all pages in the memory block. - -In the current implementation, Linux's memory offline uses method (2), freeing -all pages in the memory block by page migration. But not all pages are -migratable. Under current Linux, migratable pages are anonymous pages and -page caches. For offlining a memory block by migration, the kernel has to -guarantee that the memory block contains only migratable pages. - -Now, a boot option for making a memory block which consists of migratable pages -is supported. By specifying "kernelcore=" or "movablecore=" boot option, you can -create ZONE_MOVABLE...a zone which is just used for movable pages. -(See also Documentation/admin-guide/kernel-parameters.rst) - -Assume the system has "TOTAL" amount of memory at boot time, this boot option -creates ZONE_MOVABLE as following. - -1) When kernelcore=YYYY boot option is used, - Size of memory not for movable pages (not for offline) is YYYY. - Size of memory for movable pages (for offline) is TOTAL-YYYY. - -2) When movablecore=ZZZZ boot option is used, - Size of memory not for movable pages (not for offline) is TOTAL - ZZZZ. - Size of memory for movable pages (for offline) is ZZZZ. +=================== ============================================================ +``online`` read-write: simplified interface to trigger onlining / + offlining and to observe the state of a memory block. + When onlining, the zone is selected automatically. +``phys_device`` read-only: legacy interface only ever used on s390x to + expose the covered storage increment. +``phys_index`` read-only: the memory block id (XXX). +``removable`` read-only: legacy interface that indicated whether a memory + block was likely to be offlineable or not. Nowadays, the + kernel return ``1`` if and only if it supports memory + offlining. +``state`` read-write: advanced interface to trigger onlining / + offlining and to observe the state of a memory block. + + When writing, ``online``, ``offline``, ``online_kernel`` and + ``online_movable`` are supported. + + ``online_movable`` specifies onlining to ZONE_MOVABLE. + ``online_kernel`` specifies onlining to the default kernel + zone for the memory block, such as ZONE_NORMAL. + ``online`` let's the kernel select the zone automatically. + + When reading, ``online``, ``offline`` and ``going-offline`` + may be returned. +``uevent`` read-write: generic uevent file for devices. +``valid_zones`` read-only: when a block is online, shows the zone it + belongs to; when a block is offline, shows what zone will + manage it when the block will be onlined. + + For online memory blocks, ``DMA``, ``DMA32``, ``Normal``, + ``Movable`` and ``none`` may be returned. ``none`` indicates + that memory provided by a memory block is managed by + multiple zones or spans multiple nodes; such memory blocks + cannot be offlined. ``Movable`` indicates ZONE_MOVABLE. + Other values indicate a kernel zone. + + For offline memory blocks, the first column shows the + zone the kernel would select when onlining the memory block + right now without further specifying a zone. + + Availability depends on the CONFIG_MEMORY_HOTREMOVE + kernel configuration option. +=================== ============================================================ .. note:: - Unfortunately, there is no information to show which memory block belongs - to ZONE_MOVABLE. This is TBD. + If the CONFIG_NUMA kernel configuration option is enabled, the memoryXXX/ + directories can also be accessed via symbolic links located in the + ``/sys/devices/system/node/node*`` directories. + + For example:: + + /sys/devices/system/node/node0/memory9 -> ../../memory/memory9 + + A backlink will also be created:: + + /sys/devices/system/memory/memory9/node0 -> ../../node/node0 + +Command Line Parameters +----------------------- + +Some command line parameters affect memory hot(un)plug handling. The following +command line parameters are relevant: + +======================== ======================================================= +``memhp_default_state`` configure auto-onlining by essentially setting + ``/sys/devices/system/memory/auto_online_blocks``. +``movablecore`` configure automatic zone selection of the kernel. When + set, the kernel will default to ZONE_MOVABLE, unless + other zones can be kept contiguous. +======================== ======================================================= + +Module Parameters +------------------ + +Instead of additional command line parameters or sysfs files, the +``memory_hotplug`` subsystem now provides a dedicated namespace for module +parameters. Module parameters can be set via the command line by predicating +them with ``memory_hotplug.`` such as:: + + memory_hotplug.memmap_on_memory=1 + +and they can be observed (and some even modified at runtime) via:: + + /sys/modules/memory_hotplug/parameters/ + +The following module parameters are currently defined: + +======================== ======================================================= +``memmap_on_memory`` read-write: Allocate memory for the memmap from the + added memory block itself. Even if enabled, actual + support depends on various other system properties and + should only be regarded as a hint whether the behavior + would be desired. + + While allocating the memmap from the memory block + itself makes memory hotplug less likely to fail and + keeps the memmap on the same NUMA node in any case, it + can fragment physical memory in a way that huge pages + in bigger granularity cannot be formed on hotplugged + memory. +======================== ======================================================= + +ZONE_MOVABLE +============ + +ZONE_MOVABLE is an important mechanism for more reliable memory offlining. +Further, having system RAM managed by ZONE_MOVABLE instead of one of the +kernel zones can increase the number of possible transparent huge pages and +dynamically allocated huge pages. + +Most kernel allocations are unmovable. Important examples include the memory +map (usually 1/64ths of memory), page tables, and kmalloc(). Such allocations +can only be served from the kernel zones. + +Most user space pages, such as anonymous memory, and page cache pages are +movable. Such allocations can be served from ZONE_MOVABLE and the kernel zones. + +Only movable allocations are served from ZONE_MOVABLE, resulting in unmovable +allocations being limited to the kernel zones. Without ZONE_MOVABLE, there is +absolutely no guarantee whether a memory block can be offlined successfully. + +Zone Imbalances +--------------- + +Having too much system RAM managed by ZONE_MOVABLE is called a zone imbalance, +which can harm the system or degrade performance. As one example, the kernel +might crash because it runs out of free memory for unmovable allocations, +although there is still plenty of free memory left in ZONE_MOVABLE. - Memory offlining can fail when dissolving a free huge page on ZONE_MOVABLE - and the feature of freeing unused vmemmap pages associated with each hugetlb - page is enabled. - - This can happen when we have plenty of ZONE_MOVABLE memory, but not enough - kernel memory to allocate vmemmmap pages. We may even be able to migrate - huge page contents, but will not be able to dissolve the source huge page. - This will prevent an offline operation and is unfortunate as memory offlining - is expected to succeed on movable zones. Users that depend on memory hotplug - to succeed for movable zones should carefully consider whether the memory - savings gained from this feature are worth the risk of possibly not being - able to offline memory in certain situations. +Usually, MOVABLE:KERNEL ratios of up to 3:1 or even 4:1 are fine. Ratios of 63:1 +are definitely impossible due to the overhead for the memory map. + +Actual safe zone ratios depend on the workload. Extreme cases, like excessive +long-term pinning of pages, might not be able to deal with ZONE_MOVABLE at all. .. note:: - Techniques that rely on long-term pinnings of memory (especially, RDMA and - vfio) are fundamentally problematic with ZONE_MOVABLE and, therefore, memory - hot remove. Pinned pages cannot reside on ZONE_MOVABLE, to guarantee that - memory can still get hot removed - be aware that pinning can fail even if - there is plenty of free memory in ZONE_MOVABLE. In addition, using - ZONE_MOVABLE might make page pinning more expensive, because pages have to be - migrated off that zone first. -.. _memory_hotplug_how_to_offline_memory: + CMA memory part of a kernel zone essentially behaves like memory in + ZONE_MOVABLE and similar considerations apply, especially when combining + CMA with ZONE_MOVABLE. -How to offline memory ---------------------- +ZONE_MOVABLE Sizing Considerations +---------------------------------- -You can offline a memory block by using the same sysfs interface that was used -in memory onlining:: +We usually expect that a large portion of available system RAM will actually +be consumed by user space, either directly or indirectly via the page cache. In +the normal case, ZONE_MOVABLE can be used when allocating such pages just fine. - % echo offline > /sys/devices/system/memory/memoryXXX/state +With that in mind, it makes sense that we can have a big portion of system RAM +managed by ZONE_MOVABLE. However, there are some things to consider when using +ZONE_MOVABLE, especially when fine-tuning zone ratios: + +- Having a lot of offline memory blocks. Even offline memory blocks consume + memory for metadata and page tables in the direct map; having a lot of offline + memory blocks is not a typical case, though. + +- Memory ballooning without balloon compaction is incompatible with + ZONE_MOVABLE. Only some implementations, such as virtio-balloon and + pseries CMM, fully support balloon compaction. + + Further, the CONFIG_BALLOON_COMPACTION kernel configuration option might be + disabled. In that case, balloon inflation will only perform unmovable + allocations and silently create a zone imbalance, usually triggered by + inflation requests from the hypervisor. + +- Gigantic pages are unmovable, resulting in user space consuming a + lot of unmovable memory. + +- Huge pages are unmovable when an architectures does not support huge + page migration, resulting in a similar issue as with gigantic pages. + +- Page tables are unmovable. Excessive swapping, mapping extremely large + files or ZONE_DEVICE memory can be problematic, although only really relevant + in corner cases. When we manage a lot of user space memory that has been + swapped out or is served from a file/persistent memory/... we still need a lot + of page tables to manage that memory once user space accessed that memory. + +- In certain DAX configurations the memory map for the device memory will be + allocated from the kernel zones. + +- KASAN can have a significant memory overhead, for example, consuming 1/8th of + the total system memory size as (unmovable) tracking metadata. + +- Long-term pinning of pages. Techniques that rely on long-term pinnings + (especially, RDMA and vfio/mdev) are fundamentally problematic with + ZONE_MOVABLE, and therefore, memory offlining. Pinned pages cannot reside + on ZONE_MOVABLE as that would turn these pages unmovable. Therefore, they + have to be migrated off that zone while pinning. Pinning a page can fail + even if there is plenty of free memory in ZONE_MOVABLE. + + In addition, using ZONE_MOVABLE might make page pinning more expensive, + because of the page migration overhead. + +By default, all the memory configured at boot time is managed by the kernel +zones and ZONE_MOVABLE is not used. + +To enable ZONE_MOVABLE to include the memory present at boot and to control the +ratio between movable and kernel zones there are two command line options: +``kernelcore=`` and ``movablecore=``. See +Documentation/admin-guide/kernel-parameters.rst for their description. + +Memory Offlining and ZONE_MOVABLE +--------------------------------- + +Even with ZONE_MOVABLE, there are some corner cases where offlining a memory +block might fail: + +- Memory blocks with memory holes; this applies to memory blocks present during + boot and can apply to memory blocks hotplugged via the XEN balloon and the + Hyper-V balloon. + +- Mixed NUMA nodes and mixed zones within a single memory block prevent memory + offlining; this applies to memory blocks present during boot only. + +- Special memory blocks prevented by the system from getting offlined. Examples + include any memory available during boot on arm64 or memory blocks spanning + the crashkernel area on s390x; this usually applies to memory blocks present + during boot only. + +- Memory blocks overlapping with CMA areas cannot be offlined, this applies to + memory blocks present during boot only. + +- Concurrent activity that operates on the same physical memory area, such as + allocating gigantic pages, can result in temporary offlining failures. + +- Out of memory when dissolving huge pages, especially when freeing unused + vmemmap pages associated with each hugetlb page is enabled. + + Offlining code may be able to migrate huge page contents, but may not be able + to dissolve the source huge page because it fails allocating (unmovable) pages + for the vmemmap, because the system might not have free memory in the kernel + zones left. + + Users that depend on memory offlining to succeed for movable zones should + carefully consider whether the memory savings gained from this feature are + worth the risk of possibly not being able to offline memory in certain + situations. + +Further, when running into out of memory situations while migrating pages, or +when still encountering permanently unmovable pages within ZONE_MOVABLE +(-> BUG), memory offlining will keep retrying until it eventually succeeds. + +When offlining is triggered from user space, the offlining context can be +terminated by sending a fatal signal. A timeout based offlining can easily be +implemented via:: -If offline succeeds, the state of the memory block is changed to be "offline". -If it fails, some error core (like -EBUSY) will be returned by the kernel. -Even if a memory block does not belong to ZONE_MOVABLE, you can try to offline -it. If it doesn't contain 'unmovable' memory, you'll get success. - -A memory block under ZONE_MOVABLE is considered to be able to be offlined -easily. But under some busy state, it may return -EBUSY. Even if a memory -block cannot be offlined due to -EBUSY, you can retry offlining it and may be -able to offline it (or not). (For example, a page is referred to by some kernel -internal call and released soon.) - -Consideration: - Memory hotplug's design direction is to make the possibility of memory - offlining higher and to guarantee unplugging memory under any situation. But - it needs more work. Returning -EBUSY under some situation may be good because - the user can decide to retry more or not by himself. Currently, memory - offlining code does some amount of retry with 120 seconds timeout. - -Physical memory remove -====================== - -Need more implementation yet.... - - Notification completion of remove works by OS to firmware. - - Guard from remove if not yet. - - -Future Work -=========== - - - allowing memory hot-add to ZONE_MOVABLE. maybe we need some switch like - sysctl or new control file. - - showing memory block and physical device relationship. - - test and make it better memory offlining. - - support HugeTLB page migration and offlining. - - memmap removing at memory offline. - - physical remove memory. + % timeout $TIMEOUT offline_block | failure_handling
_
Andrew Morton
maintainerPATCH 36/147 mm: remove pfn_valid_within() and CONFIG_HOLES_IN_ZONE
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: mm: remove pfn_valid_within() and CONFIG_HOLES_IN_ZONE
Patch series "mm: remove pfn_valid_within() and CONFIG_HOLES_IN_ZONE".
After recent updates to freeing unused parts of the memory map, no architecture can have holes in the memory map within a pageblock. This makes pfn_valid_within() check and CONFIG_HOLES_IN_ZONE configuration option redundant.
The first patch removes them both in a mechanical way and the second patch simplifies memory_hotplug::test_pages_in_a_zone() that had pfn_valid_within() surrounded by more logic than simple if.
This patch (of 2):
After recent changes in freeing of the unused parts of the memory map and rework of pfn_valid() in arm and arm64 there are no architectures that can have holes in the memory map within a pageblock and so nothing can enable CONFIG_HOLES_IN_ZONE which guards non trivial implementation of pfn_valid_within().
With that, pfn_valid_within() is always hardwired to 1 and can be completely removed.
Remove calls to pfn_valid_within() and CONFIG_HOLES_IN_ZONE.
---
drivers/base/node.c | 2 -- include/linux/mmzone.h | 12 ------------ mm/Kconfig | 3 --- mm/compaction.c | 20 +++++++------------- mm/memory_hotplug.c | 4 ---- mm/page_alloc.c | 24 ++---------------------- mm/page_isolation.c | 7 +------ mm/page_owner.c | 14 +------------- 8 files changed, 11 insertions(+), 75 deletions(-)
drivers/base/node.c renamed from drivers/base/node.c~mm-remove-pfn_valid_within-and-config_holes_in_zone +0 -2
@@ -768,8 +768,6 @@ int unregister_cpu_under_node(unsigned i#ifdef CONFIG_MEMORY_HOTPLUG_SPARSE static int __ref get_nid_for_pfn (unsigned long pfn) { -if (!pfn_valid_within (pfn)) -return -1 ;#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT if (system_state <SYSTEM_RUNNING )return early_pfn_to_nid (pfn);
include/linux/mmzone.h renamed from include/linux/mmzone.h~mm-remove-pfn_valid_within-and-config_holes_in_zone +0 -12
@@ -1525,18 +1525,6 @@ void sparse_init(void);#define subsection_map_init (_pfn, _nr_pages) do {} while (0)#endif /* CONFIG_SPARSEMEM */ -/* -* If it is possible to have holes within a MAX_ORDER_NR_PAGES, then we -* need to check pfn validity within that MAX_ORDER_NR_PAGES block. -* pfn_valid_within() should be used in this case; we optimise this away -* when we have no holes within a MAX_ORDER_NR_PAGES block. -*/ -#ifdef CONFIG_HOLES_IN_ZONE -#define pfn_valid_within (pfn) pfn_valid(pfn) -#else -#define pfn_valid_within (pfn) (1) -#endif -#endif /* !__GENERATING_BOUNDS.H */ #endif /* !__ASSEMBLY__ */ #endif /* _LINUX_MMZONE_H */
mm/compaction.c renamed from mm/compaction.c~mm-remove-pfn_valid_within-and-config_holes_in_zone +7 -13
@@ -306,16 +306,14 @@ __reset_isolation_pfn(struct zone *zone,* is necessary for the block to be a migration source/target. */ do { - if (pfn_valid_within(pfn)) { - if (check_source && PageLRU(page)) { - clear_pageblock_skip(page); - return true; - } + if (check_source && PageLRU(page)) { + clear_pageblock_skip(page); + return true; + } - if (check_target && PageBuddy(page)) { - clear_pageblock_skip(page); - return true; - } + if (check_target && PageBuddy(page)) { + clear_pageblock_skip(page); + return true; } page += (1 << PAGE_ALLOC_COSTLY_ORDER);
@@ -585,8 +583,6 @@ static unsigned long isolate_freepages_bbreak ; nr_scanned++; -if (!pfn_valid_within (blockpfn)) - goto isolate_fail;/* * For compound pages such as THP and hugetlbfs, we can save
@@ -885,8 +881,6 @@ isolate_migratepages_block(struct compaccond_resched (); } -if (!pfn_valid_within (low_pfn)) - goto isolate_fail; nr_scanned++; page =pfn_to_page (low_pfn);
mm/Kconfig renamed from mm/Kconfig~mm-remove-pfn_valid_within-and-config_holes_in_zone +0 -3
@@ -96,9 +96,6 @@ config HAVE_FAST_GUP depends on MMU bool -config HOLES_IN_ZONE - bool - # Don't discard allocated memory used to track "memory" and "reserved" memblocks # after early boot, so it can still be used to test for validity of memory. # Also, memblocks are updated with memory hot(un)plug.
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-remove-pfn_valid_within-and-config_holes_in_zone +0 -4
@@ -1308,10 +1308,6 @@ struct zone *test_pages_in_a_zone(unsignfor (; pfn < sec_end_pfn && pfn < end_pfn; pfn +=MAX_ORDER_NR_PAGES ) { i =0 ; -/* This is just a CONFIG_HOLES_IN_ZONE check.*/ -while ((i <MAX_ORDER_NR_PAGES ) && - !pfn_valid_within (pfn + i)) - i++;if (i ==MAX_ORDER_NR_PAGES || pfn + i >= end_pfn)continue ;/* Check if we got outside of the zone */
mm/page_alloc.c renamed from mm/page_alloc.c~mm-remove-pfn_valid_within-and-config_holes_in_zone +2 -22
@@ -594,8 +594,6 @@ static int page_outside_zone_boundaries(static int page_is_consistent (struct zone *zone,struct page *page) { -if (!pfn_valid_within (page_to_pfn (page))) -return 0 ;if (zone !=page_zone (page))return 0 ;
@@ -1025,16 +1023,12 @@ buddy_merge_likely(unsigned long pfn, unif (order >=MAX_ORDER -2 )return false; -if (!pfn_valid_within (buddy_pfn)) -return false; - combined_pfn = buddy_pfn & pfn; higher_page = page + (combined_pfn - pfn); buddy_pfn =__find_buddy_pfn (combined_pfn, order +1 ); higher_buddy = higher_page + (buddy_pfn - combined_pfn); -return pfn_valid_within (buddy_pfn) && -page_is_buddy (higher_page, higher_buddy, order +1 ); +return page_is_buddy (higher_page, higher_buddy, order +1 ); }/*
@@ -1095,8 +1089,6 @@ continue_merging: buddy_pfn =__find_buddy_pfn (pfn, order); buddy = page + (buddy_pfn - pfn); -if (!pfn_valid_within (buddy_pfn)) - goto done_merging;if (!page_is_buddy (page, buddy, order)) goto done_merging;/*
@@ -1754,9 +1746,7 @@ void __init memblock_free_pages(struct p/* * Check that the whole (or subset of) a pageblock given by the interval of * [start_pfn, end_pfn) is valid and within the same zone, before scanning it -* with the migration of free compaction scanner. The scanners then need to -* use only pfn_valid_within() check for arches that allow holes within -* pageblocks. +* with the migration of free compaction scanner. * * Return struct page pointer of start_pfn, or NULL if checks were not passed. *
@@ -1872,8 +1862,6 @@ static inline void __init pgdat_init_rep*/ static inline bool __init deferred_pfn_valid (unsigned long pfn) { -if (!pfn_valid_within (pfn)) -return false;if (!(pfn & (pageblock_nr_pages -1 )) && !pfn_valid (pfn))return false;return true;
@@ -2520,11 +2508,6 @@ static int move_freepages(struct zone *zint pages_moved =0 ;for (pfn = start_pfn; pfn <= end_pfn;) { -if (!pfn_valid_within (pfn)) { - pfn++; -continue ; - } - page =pfn_to_page (pfn);if (!PageBuddy (page)) {/*
@@ -8828,9 +8811,6 @@ struct page *has_unmovable_pages(struct }for (; iter < pageblock_nr_pages - offset; iter++) { -if (!pfn_valid_within (pfn + iter)) -continue ; - page =pfn_to_page (pfn + iter);/*
mm/page_isolation.c renamed from mm/page_isolation.c~mm-remove-pfn_valid_within-and-config_holes_in_zone +1 -6
@@ -93,8 +93,7 @@ static void unset_migratetype_isolate(st buddy_pfn =__find_buddy_pfn (pfn, order); buddy = page + (buddy_pfn - pfn); -if (pfn_valid_within (buddy_pfn) && - !is_migrate_isolate_page (buddy)) { +if (!is_migrate_isolate_page (buddy)) {__isolate_free_page (page, order); isolated_page = true; }
@@ -250,10 +249,6 @@ __test_page_isolated_in_pageblock(unsignstruct page *page;while (pfn < end_pfn) { -if (!pfn_valid_within (pfn)) { - pfn++; -continue ; - } page =pfn_to_page (pfn);if (PageBuddy (page))/*
mm/page_owner.c renamed from mm/page_owner.c~mm-remove-pfn_valid_within-and-config_holes_in_zone +1 -13
@@ -276,9 +276,6 @@ void pagetypeinfo_showmixedcount_print(s pageblock_mt =get_pageblock_migratetype (page);for (; pfn < block_end_pfn; pfn++) { -if (!pfn_valid_within (pfn)) -continue ; -/* The pageblock is online, no need to recheck. */ page =pfn_to_page (pfn);
@@ -479,10 +476,6 @@ read_page_owner(struct file *file, charcontinue ; } -/* Check for holes within a MAX_ORDER area */ -if (!pfn_valid_within (pfn)) -continue ; - page =pfn_to_page (pfn);if (PageBuddy (page)) {unsigned long freepage_order =buddy_order_unsafe (page);
@@ -560,14 +553,9 @@ static void init_pages_in_zone(pg_data_t block_end_pfn =min (block_end_pfn, end_pfn);for (; pfn < block_end_pfn; pfn++) { -struct page *page; +struct page *page =pfn_to_page (pfn);struct page_ext *page_ext; -if (!pfn_valid_within (pfn)) -continue ; - - page =pfn_to_page (pfn); -if (page_zone (page) != zone)continue ;
_
Andrew Morton
maintainerPATCH 37/147 mm: memory_hotplug: cleanup after removal of pfn_valid_within()
In reply to Andrew MortonFrom: Mike Rapoport <[email protected]>
Subject: mm: memory_hotplug: cleanup after removal of pfn_valid_within()
When test_pages_in_a_zone() used pfn_valid_within() is has some logic surrounding pfn_valid_within() checks.
Since pfn_valid_within() is gone, this logic can be removed.
---
mm/memory_hotplug.c | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-)
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-cleanup-after-removal-of-pfn_valid_within +3 -6
@@ -1298,7 +1298,7 @@ struct zone *test_pages_in_a_zone(unsignunsigned long pfn, sec_end_pfn;struct zone *zone =NULL ;struct page *page; -int i; +for (pfn = start_pfn, sec_end_pfn =SECTION_ALIGN_UP (start_pfn +1 ); pfn < end_pfn; pfn = sec_end_pfn, sec_end_pfn +=PAGES_PER_SECTION ) {
@@ -1307,13 +1307,10 @@ struct zone *test_pages_in_a_zone(unsigncontinue ;for (; pfn < sec_end_pfn && pfn < end_pfn; pfn +=MAX_ORDER_NR_PAGES ) { - i =0 ; -if (i ==MAX_ORDER_NR_PAGES || pfn + i >= end_pfn) -continue ;/* Check if we got outside of the zone */ -if (zone && !zone_spans_pfn (zone, pfn + i)) +if (zone && !zone_spans_pfn (zone, pfn))return NULL ; - page =pfn_to_page (pfn + i); + page =pfn_to_page (pfn);if (zone &&page_zone (page) != zone)return NULL ; zone =page_zone (page);
_
Andrew Morton
maintainerPATCH 38/147 mm/memory_hotplug: use "unsigned long" for PFN in zone_for_pfn_range()
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm/memory_hotplug: use "unsigned long" for PFN in zone_for_pfn_range()
Patch series "mm/memory_hotplug: preparatory patches for new online policy and memory"
These are all cleanups and one fix previously sent as part of [1]:
[PATCH v1 00/12] mm/memory_hotplug: "auto-movable" online policy and memory groups.
These patches make sense even without the other series, therefore I pulled them out to make the other series easier to digest.
[1] https://lkml.kernel.org/r/[email protected]
This patch (of 4):
Checkpatch complained on a follow-up patch that we are using "unsigned" here, which defaults to "unsigned int" and checkpatch is correct.
As we will search for a fitting zone using the wrong pfn, we might end up onlining memory to one of the special kernel zones, such as ZONE_DMA, which can end badly as the onlined memory does not satisfy properties of these zones.
Use "unsigned long" instead, just as we do in other places when handling PFNs. This can bite us once we have physical addresses in the range of multiple TB.
---
include/linux/memory_hotplug.h | 4 ++-- mm/memory_hotplug.c | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-)
include/linux/memory_hotplug.h renamed from include/linux/memory_hotplug.h~mm-memory_hotplug-use-unsigned-long-for-pfn-in-zone_for_pfn_range +2 -2
@@ -339,8 +339,8 @@ extern void sparse_remove_section(struct unsigned long map_offset, struct vmem_altmap *altmap);extern struct page *sparse_decode_mem_map (unsigned long coded_mem_map,unsigned long pnum); -extern struct zone *zone_for_pfn_range (int online_type,int nid,unsigned start_pfn, -unsigned long nr_pages); +extern struct zone *zone_for_pfn_range (int online_type,int nid, +unsigned long start_pfn,unsigned long nr_pages);extern int arch_create_linear_mapping (int nid,u64 start,u64 size,struct mhp_params *params);void arch_remove_linear_mapping (u64 start,u64 size);
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-use-unsigned-long-for-pfn-in-zone_for_pfn_range +2 -2
@@ -708,8 +708,8 @@ static inline struct zone *default_zone_return movable_node_enabled ? movable_zone : kernel_zone; } -struct zone *zone_for_pfn_range (int online_type,int nid,unsigned start_pfn, -unsigned long nr_pages) +struct zone *zone_for_pfn_range (int online_type,int nid, +unsigned long start_pfn,unsigned long nr_pages) {if (online_type ==MMOP_ONLINE_KERNEL )return default_kernel_zone_for_pfn (nid, start_pfn, nr_pages);
_
Andrew Morton
maintainerPATCH 39/147 mm/memory_hotplug: remove nid parameter from arch_remove_memory()
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm/memory_hotplug: remove nid parameter from arch_remove_memory()
The parameter is unused, let's remove it.
---
arch/arm64/mm/mmu.c | 3 +-- arch/ia64/mm/init.c | 3 +-- arch/powerpc/mm/mem.c | 3 +-- arch/s390/mm/init.c | 3 +-- arch/sh/mm/init.c | 3 +-- arch/x86/mm/init_32.c | 3 +-- arch/x86/mm/init_64.c | 3 +-- include/linux/memory_hotplug.h | 3 +-- mm/memory_hotplug.c | 4 ++-- mm/memremap.c | 5 +---- 10 files changed, 11 insertions(+), 22 deletions(-)
arch/arm64/mm/mmu.c renamed from arch/arm64/mm/mmu.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -2
@@ -1502,8 +1502,7 @@ int arch_add_memory(int nid, u64 start,return ret; } -void arch_remove_memory (int nid,u64 start,u64 size, -struct vmem_altmap *altmap) +void arch_remove_memory (u64 start,u64 size,struct vmem_altmap *altmap) {unsigned long start_pfn = start >>PAGE_SHIFT ;unsigned long nr_pages = size >>PAGE_SHIFT ;
arch/ia64/mm/init.c renamed from arch/ia64/mm/init.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -2
@@ -484,8 +484,7 @@ int arch_add_memory(int nid, u64 start,return ret; } -void arch_remove_memory (int nid,u64 start,u64 size, -struct vmem_altmap *altmap) +void arch_remove_memory (u64 start,u64 size,struct vmem_altmap *altmap) {unsigned long start_pfn = start >>PAGE_SHIFT ;unsigned long nr_pages = size >>PAGE_SHIFT ;
arch/powerpc/mm/mem.c renamed from arch/powerpc/mm/mem.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -2
@@ -119,8 +119,7 @@ int __ref arch_add_memory(int nid, u64 sreturn rc; } -void __ref arch_remove_memory (int nid,u64 start,u64 size, -struct vmem_altmap *altmap) +void __ref arch_remove_memory (u64 start,u64 size,struct vmem_altmap *altmap) {unsigned long start_pfn = start >>PAGE_SHIFT ;unsigned long nr_pages = size >>PAGE_SHIFT ;
arch/s390/mm/init.c renamed from arch/s390/mm/init.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -2
@@ -306,8 +306,7 @@ int arch_add_memory(int nid, u64 start,return rc; } -void arch_remove_memory (int nid,u64 start,u64 size, -struct vmem_altmap *altmap) +void arch_remove_memory (u64 start,u64 size,struct vmem_altmap *altmap) {unsigned long start_pfn = start >>PAGE_SHIFT ;unsigned long nr_pages = size >>PAGE_SHIFT ;
arch/sh/mm/init.c renamed from arch/sh/mm/init.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -2
@@ -414,8 +414,7 @@ int arch_add_memory(int nid, u64 start,return ret; } -void arch_remove_memory (int nid,u64 start,u64 size, -struct vmem_altmap *altmap) +void arch_remove_memory (u64 start,u64 size,struct vmem_altmap *altmap) {unsigned long start_pfn =PFN_DOWN (start);unsigned long nr_pages = size >>PAGE_SHIFT ;
arch/x86/mm/init_32.c renamed from arch/x86/mm/init_32.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -2
@@ -801,8 +801,7 @@ int arch_add_memory(int nid, u64 start,return __add_pages (nid, start_pfn, nr_pages, params); } -void arch_remove_memory (int nid,u64 start,u64 size, -struct vmem_altmap *altmap) +void arch_remove_memory (u64 start,u64 size,struct vmem_altmap *altmap) {unsigned long start_pfn = start >>PAGE_SHIFT ;unsigned long nr_pages = size >>PAGE_SHIFT ;
arch/x86/mm/init_64.c renamed from arch/x86/mm/init_64.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -2
@@ -1255,8 +1255,7 @@ kernel_physical_mapping_remove(unsignedremove_pagetable (start, end, true,NULL ); } -void __ref arch_remove_memory (int nid,u64 start,u64 size, -struct vmem_altmap *altmap) +void __ref arch_remove_memory (u64 start,u64 size,struct vmem_altmap *altmap) {unsigned long start_pfn = start >>PAGE_SHIFT ;unsigned long nr_pages = size >>PAGE_SHIFT ;
include/linux/memory_hotplug.h renamed from include/linux/memory_hotplug.h~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -2
@@ -130,8 +130,7 @@ static inline bool movable_node_is_enablreturn movable_node_enabled; } -extern void arch_remove_memory (int nid,u64 start,u64 size, -struct vmem_altmap *altmap); +extern void arch_remove_memory (u64 start,u64 size,struct vmem_altmap *altmap);extern void __remove_pages (unsigned long start_pfn,unsigned long nr_pages,struct vmem_altmap *altmap);
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +2 -2
@@ -1106,7 +1106,7 @@ int __ref add_memory_resource(int nid, s/* create memory block devices after memory was added */ ret =create_memory_block_devices (start, size, mhp_altmap.alloc);if (ret) { -arch_remove_memory (nid, start, size,NULL ); +arch_remove_memory (start, size,NULL ); goto error; }
@@ -1886,7 +1886,7 @@ static int __ref try_remove_memory(int nmem_hotplug_begin (); -arch_remove_memory (nid, start, size, altmap); +arch_remove_memory (start, size, altmap);if (IS_ENABLED (CONFIG_ARCH_KEEP_MEMBLOCK )) {memblock_free (start, size);
mm/memremap.c renamed from mm/memremap.c~mm-memory_hotplug-remove-nid-parameter-from-arch_remove_memory +1 -4
@@ -140,14 +140,11 @@ static void pageunmap_range(struct dev_p {struct range *range = &pgmap->ranges[range_id];struct page *first_page; -int nid;/* make sure to access a memmap that was actually initialized */ first_page =pfn_to_page (pfn_first (pgmap, range_id));/* pages are dead and unused, undo the arch mapping */ - nid =page_to_nid (first_page); -mem_hotplug_begin ();remove_pfn_range_from_zone (page_zone (first_page),PHYS_PFN (range->start),PHYS_PFN (range_len (range)));
@@ -155,7 +152,7 @@ static void pageunmap_range(struct dev_p__remove_pages (PHYS_PFN (range->start),PHYS_PFN (range_len (range)),NULL ); }else { -arch_remove_memory (nid, range->start,range_len (range), +arch_remove_memory (range->start,range_len (range),pgmap_altmap (pgmap));kasan_remove_zero_shadow (__va (range->start),range_len (range)); }
_
Andrew Morton
maintainerPATCH 40/147 mm/memory_hotplug: remove nid parameter from remove_memory() and friends
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm/memory_hotplug: remove nid parameter from remove_memory() and friends
There is only a single user remaining. We can simply lookup the nid only used for node offlining purposes when walking our memory blocks. We don't expect to remove multi-nid ranges; and if we'd ever do, we most probably don't care about removing multi-nid ranges that actually result in empty nodes.
If ever required, we can detect the "multi-nid" scenario and simply try offlining all online nodes.
---
arch/powerpc/platforms/pseries/hotplug-memory.c | 9 ++-- drivers/acpi/acpi_memhotplug.c | 7 --- drivers/dax/kmem.c | 3 - drivers/virtio/virtio_mem.c | 4 +- include/linux/memory_hotplug.h | 10 ++--- mm/memory_hotplug.c | 28 ++++++++------ 6 files changed, 30 insertions(+), 31 deletions(-)
arch/powerpc/platforms/pseries/hotplug-memory.c renamed from arch/powerpc/platforms/pseries/hotplug-memory.c~mm-memory_hotplug-remove-nid-parameter-from-remove_memory-and-friends +4 -5
@@ -284,7 +284,7 @@ static int pseries_remove_memblock(unsig {unsigned long block_sz, start_pfn;int sections_per_block; -int i, nid; +int i; start_pfn = base >>PAGE_SHIFT ;
@@ -295,10 +295,9 @@ static int pseries_remove_memblock(unsig block_sz =pseries_memory_block_size (); sections_per_block = block_sz /MIN_MEMORY_BLOCK_SIZE ; - nid =memory_add_physaddr_to_nid (base);for (i =0 ; i < sections_per_block; i++) { -__remove_memory (nid, base,MIN_MEMORY_BLOCK_SIZE ); +__remove_memory (base,MIN_MEMORY_BLOCK_SIZE ); base +=MIN_MEMORY_BLOCK_SIZE ; }
@@ -385,7 +384,7 @@ static int dlpar_remove_lmb(struct drmem block_sz =pseries_memory_block_size (); -__remove_memory (mem_block->nid, lmb->base_addr, block_sz); +__remove_memory (lmb->base_addr, block_sz);put_device (&mem_block->dev);/* Update memory regions for memory remove */
@@ -658,7 +657,7 @@ static int dlpar_add_lmb(struct drmem_lm rc =dlpar_online_lmb (lmb);if (rc) { -__remove_memory (nid, lmb->base_addr, block_sz); +__remove_memory (lmb->base_addr, block_sz);invalidate_lmb_associativity_index (lmb); }else { lmb->flags |=DRCONF_MEM_ASSIGNED ;
drivers/acpi/acpi_memhotplug.c renamed from drivers/acpi/acpi_memhotplug.c~mm-memory_hotplug-remove-nid-parameter-from-remove_memory-and-friends +1 -6
@@ -239,19 +239,14 @@ static int acpi_memory_enable_device(strstatic void acpi_memory_remove_memory (struct acpi_memory_device *mem_device) { -acpi_handle handle = mem_device->device->handle;struct acpi_memory_info *info, *n; -int nid =acpi_get_node (handle);list_for_each_entry_safe (info, n, &mem_device->res_list, list) {if (!info->enabled)continue ; -if (nid ==NUMA_NO_NODE ) - nid =memory_add_physaddr_to_nid (info->start_addr); -acpi_unbind_memory_blocks (info); -__remove_memory (nid, info->start_addr, info->length); +__remove_memory (info->start_addr, info->length);list_del (&info->list);kfree (info); }
drivers/dax/kmem.c renamed from drivers/dax/kmem.c~mm-memory_hotplug-remove-nid-parameter-from-remove_memory-and-friends +1 -2
@@ -156,8 +156,7 @@ static void dev_dax_kmem_remove(struct dif (rc)continue ; - rc =remove_memory (dev_dax->target_node, range.start, -range_len (&range)); + rc =remove_memory (range.start,range_len (&range));if (rc ==0 ) {release_resource (data->res[i]);kfree (data->res[i]);
drivers/virtio/virtio_mem.c renamed from drivers/virtio/virtio_mem.c~mm-memory_hotplug-remove-nid-parameter-from-remove_memory-and-friends +2 -2
@@ -677,7 +677,7 @@ static int virtio_mem_remove_memory(strudev_dbg (&vm->vdev->dev,"removing memory: 0x%llx - 0x%llx\n" , addr, addr + size -1 ); - rc =remove_memory (vm->nid, addr, size); + rc =remove_memory (addr, size);if (!rc) {atomic64_sub (size, &vm->offline_size);/*
@@ -720,7 +720,7 @@ static int virtio_mem_offline_and_remove"offlining and removing memory: 0x%llx - 0x%llx\n" , addr, addr + size - 1); - rc =offline_and_remove_memory (vm->nid, addr, size); + rc =offline_and_remove_memory (addr, size);if (!rc) {atomic64_sub (size, &vm->offline_size);/*
include/linux/memory_hotplug.h renamed from include/linux/memory_hotplug.h~mm-memory_hotplug-remove-nid-parameter-from-remove_memory-and-friends +5 -5
@@ -292,9 +292,9 @@ static inline void pgdat_resize_init(strextern void try_offline_node (int nid);extern int offline_pages (unsigned long start_pfn,unsigned long nr_pages); -extern int remove_memory (int nid,u64 start,u64 size); -extern void __remove_memory (int nid,u64 start,u64 size); -extern int offline_and_remove_memory (int nid,u64 start,u64 size); +extern int remove_memory (u64 start,u64 size); +extern void __remove_memory (u64 start,u64 size); +extern int offline_and_remove_memory (u64 start,u64 size);#else static inline void try_offline_node (int nid) {}
@@ -304,12 +304,12 @@ static inline int offline_pages(unsigned return -EINVAL; } -static inline int remove_memory (int nid,u64 start,u64 size) +static inline int remove_memory (u64 start,u64 size) {return -EBUSY ; } -static inline void __remove_memory (int nid,u64 start,u64 size) {} +static inline void __remove_memory (u64 start,u64 size) {}#endif /* CONFIG_MEMORY_HOTREMOVE */ extern void set_zone_contiguous (struct zone *zone);
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-remove-nid-parameter-from-remove_memory-and-friends +17 -11
@@ -1739,7 +1739,9 @@ failed_removal:static int check_memblock_offlined_cb (struct memory_block *mem,void *arg) {int ret = !is_memblock_offlined (mem); +int *nid = arg; + *nid = mem->nid;if (unlikely (ret)) {phys_addr_t beginpa, endpa;
@@ -1832,12 +1834,12 @@ void try_offline_node(int nid) }EXPORT_SYMBOL (try_offline_node); -static int __ref try_remove_memory (int nid,u64 start,u64 size) +static int __ref try_remove_memory (u64 start,u64 size) { -int rc =0 ;struct vmem_altmap mhp_altmap = {};struct vmem_altmap *altmap =NULL ;unsigned long nr_vmemmap_pages; +int rc =0 , nid =NUMA_NO_NODE ;BUG_ON (check_hotplug_memory_range (start, size));
@@ -1845,8 +1847,12 @@ static int __ref try_remove_memory(int n* All memory blocks must be offlined before removing memory. Check * whether all memory blocks in question are offline and return error * if this is not the case. +* +* While at it, determine the nid. Note that if we'd have mixed nodes, +* we'd only try to offline the last determined one -- which is good +* enough for the cases we care about. */ - rc =walk_memory_blocks (start, size,NULL , check_memblock_offlined_cb); + rc =walk_memory_blocks (start, size, &nid, check_memblock_offlined_cb);if (rc)return rc;
@@ -1895,7 +1901,8 @@ static int __ref try_remove_memory(int nrelease_mem_region_adjustable (start, size); -try_offline_node (nid); +if (nid !=NUMA_NO_NODE ) +try_offline_node (nid);mem_hotplug_done ();return 0 ;
@@ -1903,7 +1910,6 @@ static int __ref try_remove_memory(int n/** * __remove_memory - Remove memory if every memory block is offline -* @nid: the node ID * @start: physical address of the region to remove * @size: size of the region to remove *
@@ -1911,14 +1917,14 @@ static int __ref try_remove_memory(int n* and online/offline operations before this call, as required by * try_offline_node(). */ -void __remove_memory (int nid,u64 start,u64 size) +void __remove_memory (u64 start,u64 size) {/* * trigger BUG() if some memory is not offlined prior to calling this * function */ -if (try_remove_memory (nid, start, size)) +if (try_remove_memory (start, size))BUG (); }
@@ -1926,12 +1932,12 @@ void __remove_memory(int nid, u64 start,* Remove memory if every memory block is offline, otherwise return -EBUSY is * some memory is not offline */ -int remove_memory (int nid,u64 start,u64 size) +int remove_memory (u64 start,u64 size) {int rc;lock_device_hotplug (); - rc =try_remove_memory (nid, start, size); + rc =try_remove_memory (start, size);unlock_device_hotplug ();return rc;
@@ -1991,7 +1997,7 @@ static int try_reonline_memory_block(str* unplugged all memory (so it's no longer in use) and want to offline + remove * that memory. */ -int offline_and_remove_memory (int nid,u64 start,u64 size) +int offline_and_remove_memory (u64 start,u64 size) {const unsigned long mb_count = size /memory_block_size_bytes ();uint8_t *online_types, *tmp;
@@ -2027,7 +2033,7 @@ int offline_and_remove_memory(int nid, u* This cannot fail as it cannot get onlined in the meantime. */ if (!rc) { - rc =try_remove_memory (nid, start, size); + rc =try_remove_memory (start, size);if (rc)pr_err ("%s: Failed to remove memory: %d" , __func__, rc); }
_
Andrew Morton
maintainerPATCH 41/147 ACPI: memhotplug: memory resources cannot be enabled yet
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: ACPI: memhotplug: memory resources cannot be enabled yet
We allocate + initialize everything from scratch. In case enabling the device fails, we free all memory resourcs.
---
drivers/acpi/acpi_memhotplug.c | 4 ---- 1 file changed, 4 deletions(-)
drivers/acpi/acpi_memhotplug.c renamed from drivers/acpi/acpi_memhotplug.c~acpi-memhotplug-memory-resources-cannot-be-enabled-yet +0 -4
@@ -182,10 +182,6 @@ static int acpi_memory_enable_device(str* (i.e. memory-hot-remove function) */ list_for_each_entry (info, &mem_device->res_list, list) { -if (info->enabled) {/* just sanity check...*/ - num_enabled++; -continue ; - }/* * If the memory block size is zero, please ignore it. * Don't try to do the following memory hotplug flowchart.
_
Andrew Morton
maintainerPATCH 42/147 mm: track present early pages per zone
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm: track present early pages per zone
Patch series "mm/memory_hotplug: "auto-movable" online policy and memory groups", v3.
I. Goal
The goal of this series is improving in-kernel auto-online support. It tackles the fundamental problems that:
1) We can create zone imbalances when onlining all memory blindly to ZONE_MOVABLE, in the worst case crashing the system. We have to know upfront how much memory we are going to hotplug such that we can safely enable auto-onlining of all hotplugged memory to ZONE_MOVABLE via "online_movable". This is far from practical and only applicable in limited setups -- like inside VMs under the RHV/oVirt hypervisor which will never hotplug more than 3 times the boot memory (and the limitation is only in place due to the Linux limitation).
2) We see more setups that implement dynamic VM resizing, hot(un)plugging memory to resize VM memory. In these setups, we might hotplug a lot of memory, but it might happen in various small steps in both directions (e.g., 2 GiB -> 8 GiB -> 4 GiB -> 16 GiB ...). virtio-mem is the primary driver of this upstream right now, performing such dynamic resizing NUMA-aware via multiple virtio-mem devices.
Onlining all hotplugged memory to ZONE_NORMAL means we basically have no hotunplug guarantees. Onlining all to ZONE_MOVABLE means we can easily run into zone imbalances when growing a VM. We want a mixture, and we want as much memory as reasonable/configured in ZONE_MOVABLE. Details regarding zone imbalances can be found at [1].
3) Memory devices consist of 1..X memory block devices, however, the kernel doesn't really track the relationship. Consequently, also user space has no idea. We want to make per-device decisions.
As one example, for memory hotunplug it doesn't make sense to use a mixture of zones within a single DIMM: we want all MOVABLE if possible, otherwise all !MOVABLE, because any !MOVABLE part will easily block the whole DIMM from getting hotunplugged.
As another example, virtio-mem operates on individual units that span 1..X memory blocks. Similar to a DIMM, we want a unit to either be all MOVABLE or !MOVABLE. A "unit" can be thought of like a DIMM, however, all units of a virtio-mem device logically belong together and are managed (added/removed) by a single driver. We want as much memory of a virtio-mem device to be MOVABLE as possible.
4) We want memory onlining to be done right from the kernel while adding memory, not triggered by user space via udev rules; for example, this is reqired for fast memory hotplug for drivers that add individual memory blocks, like virito-mem. We want a way to configure a policy in the kernel and avoid implementing advanced policies in user space.
The auto-onlining support we have in the kernel is not sufficient. All we have is a) online everything MOVABLE (online_movable) b) online everything !MOVABLE (online_kernel) c) keep zones contiguous (online). This series allows configuring c) to mean instead "online movable if possible according to the coniguration, driven by a maximum MOVABLE:KERNEL ratio" -- a new onlining policy.
II. Approach
This series does 3 things:
1) Introduces the "auto-movable" online policy that initially operates on individual memory blocks only. It uses a maximum MOVABLE:KERNEL ratio to make a decision whether a memory block will be onlined to ZONE_MOVABLE or not. However, in the basic form, hotplugged KERNEL memory does not allow for more MOVABLE memory (details in the patches). CMA memory is treated like MOVABLE memory.
2) Introduces static (e.g., DIMM) and dynamic (e.g., virtio-mem) memory groups and uses group information to make decisions in the "auto-movable" online policy across memory blocks of a single memory device (modeled as memory group). More details can be found in patch #3 or in the DIMM example below.
3) Maximizes ZONE_MOVABLE memory within dynamic memory groups, by allowing ZONE_NORMAL memory within a dynamic memory group to allow for more ZONE_MOVABLE memory within the same memory group. The target use case is dynamic VM resizing using virtio-mem. See the virtio-mem example below.
I remember that the basic idea of using a ratio to implement a policy in the kernel was once mentioned by Vitaly Kuznetsov, but I might be wrong (I lost the pointer to that discussion).
For me, the main use case is using it along with virtio-mem (and DIMMs / ppc64 dlpar where necessary) for dynamic resizing of VMs, increasing the amount of memory we can hotunplug reliably again if we might eventually hotplug a lot of memory to a VM.
III. Target Usage
The target usage will be:
1) Linux boots with "mhp_default_online_type=offline"
2) User space (e.g., systemd unit) configures memory onlining (according to a config file and system properties), for example:
* Setting memory_hotplug.online_policy=auto-movable
* Setting memory_hotplug.auto_movable_ratio=301
* Setting memory_hotplug.auto_movable_numa_aware=true
3) User space enabled auto onlining via "echo online > /sys/devices/system/memory/auto_online_blocks"
4) User space triggers manual onlining of all already-offline memory blocks (go over offline memory blocks and set them to "online")
IV. Example
For DIMMs, hotplugging 4 GiB DIMMs to a 4 GiB VM with a configured ratio of 301% results in the following layout:
Memory block 0-15: DMA32 (early) Memory block 32-47: Normal (early) Memory block 48-79: Movable (DIMM 0) Memory block 80-111: Movable (DIMM 1) Memory block 112-143: Movable (DIMM 2) Memory block 144-275: Normal (DIMM 3) Memory block 176-207: Normal (DIMM 4) ... all Normal (-> hotplugged Normal memory does not allow for more Movable memory)
For virtio-mem, using a simple, single virtio-mem device with a 4 GiB VM will result in the following layout:
Memory block 0-15: DMA32 (early) Memory block 32-47: Normal (early) Memory block 48-143: Movable (virtio-mem, first 12 GiB) Memory block 144: Normal (virtio-mem, next 128 MiB) Memory block 145-147: Movable (virtio-mem, next 384 MiB) Memory block 148: Normal (virtio-mem, next 128 MiB) Memory block 149-151: Movable (virtio-mem, next 384 MiB) ... Normal/Movable mixture as above (-> hotplugged Normal memory allows for more Movable memory within the same device)
Which gives us maximum flexibility when dynamically growing/shrinking a VM in smaller steps.
V. Doc Update
I'll update the memory-hotplug.rst documentation, once the overhaul [1] is usptream. Until then, details can be found in patch #2.
VI. Future Work
1) Use memory groups for ppc64 dlpar
2) Being able to specify a portion of (early) kernel memory that will be excluded from the ratio. Like "128 MiB globally/per node" are excluded.
This might be helpful when starting VMs with extremely small memory footprint (e.g., 128 MiB) and hotplugging memory later -- not wanting the first hotplugged units getting onlined to ZONE_MOVABLE. One alternative would be a trigger to not consider ZONE_DMA memory in the ratio. We'll have to see if this is really rrequired.
3) Indicate to user space that MOVABLE might be a bad idea -- especially relevant when memory ballooning without support for balloon compaction is active.
This patch (of 9):
For implementing a new memory onlining policy, which determines when to online memory blocks to ZONE_MOVABLE semi-automatically, we need the number of present early (boot) pages -- present pages excluding hotplugged pages. Let's track these pages per zone.
Pass a page instead of the zone to adjust_present_page_count(), similar as adjust_managed_page_count() and derive the zone from the page.
It's worth noting that a memory block to be offlined/onlined is either completely "early" or "not early". add_memory() and friends can only add complete memory blocks and we only online/offline complete (individual) memory blocks.
---
drivers/base/memory.c | 14 +++++++------- include/linux/memory_hotplug.h | 2 +- include/linux/mmzone.h | 7 +++++++ mm/memory_hotplug.c | 14 +++++++++++--- mm/page_alloc.c | 3 +++ 5 files changed, 29 insertions(+), 11 deletions(-)
drivers/base/memory.c renamed from drivers/base/memory.c~mm-track-present-early-pages-per-zone +7 -7
@@ -205,7 +205,8 @@ static int memory_block_online(struct me* now already properly populated. */ if (nr_vmemmap_pages) -adjust_present_page_count (zone, nr_vmemmap_pages); +adjust_present_page_count (pfn_to_page (start_pfn), + nr_vmemmap_pages);return ret; }
@@ -215,24 +216,23 @@ static int memory_block_offline(struct munsigned long start_pfn =section_nr_to_pfn (mem->start_section_nr);unsigned long nr_pages =PAGES_PER_SECTION * sections_per_block;unsigned long nr_vmemmap_pages = mem->nr_vmemmap_pages; -struct zone *zone;int ret;/* * Unaccount before offlining, such that unpopulated zone and kthreads * can properly be torn down in offline_pages(). */ -if (nr_vmemmap_pages) { - zone =page_zone (pfn_to_page (start_pfn)); -adjust_present_page_count (zone, -nr_vmemmap_pages); - } +if (nr_vmemmap_pages) +adjust_present_page_count (pfn_to_page (start_pfn), + -nr_vmemmap_pages); ret =offline_pages (start_pfn + nr_vmemmap_pages, nr_pages - nr_vmemmap_pages);if (ret) {/* offline_pages() failed. Account back. */ if (nr_vmemmap_pages) -adjust_present_page_count (zone, nr_vmemmap_pages); +adjust_present_page_count (pfn_to_page (start_pfn), + nr_vmemmap_pages);return ret; }
include/linux/memory_hotplug.h renamed from include/linux/memory_hotplug.h~mm-track-present-early-pages-per-zone +1 -1
@@ -95,7 +95,7 @@ static inline void zone_seqlock_init(strextern int zone_grow_free_lists (struct zone *zone,unsigned long new_nr_pages);extern int zone_grow_waitqueues (struct zone *zone,unsigned long nr_pages);extern int add_one_highpage (struct page *page,int pfn,int bad_ppro); -extern void adjust_present_page_count (struct zone *zone,long nr_pages); +extern void adjust_present_page_count (struct page *page,long nr_pages);/* VM interface that may be used by firmware interface */ extern int mhp_init_memmap_on_memory (unsigned long pfn,unsigned long nr_pages,struct zone *zone);
include/linux/mmzone.h renamed from include/linux/mmzone.h~mm-track-present-early-pages-per-zone +7 -0
@@ -540,6 +540,10 @@ struct zone {* is calculated as: * present_pages = spanned_pages - absent_pages(pages in holes); * +* present_early_pages is present pages existing within the zone +* located on memory available since early boot, excluding hotplugged +* memory. +* * managed_pages is present pages managed by the buddy system, which * is calculated as (reserved_pages includes pages allocated by the * bootmem allocator):
@@ -572,6 +576,9 @@ struct zone {atomic_long_t managed_pages;unsigned long spanned_pages;unsigned long present_pages; +#if defined(CONFIG_MEMORY_HOTPLUG ) +unsigned long present_early_pages; +#endif #ifdef CONFIG_CMA unsigned long cma_pages;#endif
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-track-present-early-pages-per-zone +11 -3
@@ -724,8 +724,16 @@ struct zone *zone_for_pfn_range(int onli* This function should only be called by memory_block_{online,offline}, * and {online,offline}_pages. */ -void adjust_present_page_count (struct zone *zone,long nr_pages) +void adjust_present_page_count (struct page *page,long nr_pages) { +struct zone *zone =page_zone (page); + +/* +* We only support onlining/offlining/adding/removing of complete +* memory blocks; therefore, either all is either early or hotplugged. +*/ +if (early_section (__pfn_to_section (page_to_pfn (page)))) + zone->present_early_pages += nr_pages; zone->present_pages += nr_pages; zone->zone_pgdat->node_present_pages += nr_pages; }
@@ -826,7 +834,7 @@ int __ref online_pages(unsigned long pfn }online_pages_range (pfn, nr_pages); -adjust_present_page_count (zone, nr_pages); +adjust_present_page_count (pfn_to_page (pfn), nr_pages);node_states_set_node (nid, &arg);if (need_zonelists_rebuild)
@@ -1697,7 +1705,7 @@ int __ref offline_pages(unsigned long st/* removal success */ adjust_managed_page_count (pfn_to_page (start_pfn), -nr_pages); -adjust_present_page_count (zone, -nr_pages); +adjust_present_page_count (pfn_to_page (start_pfn), -nr_pages);/* reinitialise watermarks and update pcp limits */ init_per_zone_wmark_min ();
mm/page_alloc.c renamed from mm/page_alloc.c~mm-track-present-early-pages-per-zone +3 -0
@@ -7254,6 +7254,9 @@ static void __init calculate_node_totalp zone->zone_start_pfn =0 ; zone->spanned_pages = size; zone->present_pages = real_size; +#if defined(CONFIG_MEMORY_HOTPLUG ) + zone->present_early_pages = real_size; +#endif totalpages += size; realtotalpages += real_size;
_
Andrew Morton
maintainerPATCH 43/147 mm/memory_hotplug: introduce "auto-movable" online policy
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm/memory_hotplug: introduce "auto-movable" online policy
When onlining without specifying a zone (using "online" instead of "online_kernel" or "online_movable"), we currently select a zone such that existing zones are kept contiguous. This online policy made sense in the past, where contiguous zones where required.
We'd like to implement smarter policies, however:
* User space has little insight. As one example, it has no idea which memory blocks logically belong together (e.g., to a DIMM or to a virtio-mem device).
* Drivers that add memory in separate memory blocks, especially virtio-mem, want memory to get onlined right from the kernel when adding.
So we really want to have onlining to differing zones managed in the kernel, configured by user space.
We see more and more cases where we might eventually hotplug a lot of memory in the future (e.g., eventually grow a 2 GiB VM to 64 GiB), however:
* Resizing happens dynamically, in smaller steps in both directions (e.g., 2 GiB -> 8 GiB -> 4 GiB -> 16 GiB ...)
* We still want as much flexibility as possible, especially, hotunplugging as much memory as possible later.
We can really only use "online_movable" if we know that the amount of memory we are going to hotplug upfront, and we know that it won't result in a zone imbalance. So in our example, a 2 GiB VM that could grow to 64 GiB could currently not use "online_movable", and instead, "online_kernel" would have to be used, resulting in worse (no) memory hotunplug reliability.
Let's add a new "auto-movable" online policy that considers the current zone ratios (global, per-node) to determine, whether we a memory block can be onlined to ZONE_MOVABLE:
MOVABLE : KERNEL
However, internally we'll only consider the following ratio for now:
MOVABLE : KERNEL_EARLY
For now, we don't allow for hotplugged KERNEL memory to allow for more MOVABLE memory, because there is no coordination across memory devices. In follow-up patches, we will allow for more KERNEL memory within a memory device to allow for more MOVABLE memory within the same memory device -- which only makes sense for special memory device types.
We base our calculation on "present pages", see the code comments for details. Hotplugged memory will get online to ZONE_MOVABLE if the configured ratio allows for it. Depending on the setup, this can result in fragmented zones, which can make compaction slower and dynamic allocation of gigantic pages when not using CMA less reliable (... which is already pretty unreliable).
The old policy will be the default and called "contig-zones". In follow-up patches, our new policy will use additional information, such as memory groups, to make even smarter decisions across memory blocks.
Configuration:
* memory_hotplug.online_policy is used to switch between both polices and defaults to "contig-zones".
* memory_hotplug.auto_movable_ratio defines the maximum ratio is in percent and defaults to "301" -- allowing e.g., most 8 GiB machines to grow to 32 GiB and have all hotplugged memory in ZONE_MOVABLE. The additional percent accounts for a handful of lost present pages (e.g., firmware allocations). User space is expected to adjust this ratio when enabling the new "auto-movable" policy, though.
* memory_hotplug.auto_movable_numa_aware considers numa node stats in addition to global stats, and defaults to "true".
Note: just like the old policy, the new policy won't take things like unmovable huge pages or memory ballooning that doesn't support balloon compaction into account. User space has to configure onlining accordingly.
---
mm/memory_hotplug.c | 191 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 191 insertions(+)
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-introduce-auto-movable-online-policy +191 -0
@@ -52,6 +52,73 @@ module_param(memmap_on_memory, bool, 044MODULE_PARM_DESC (memmap_on_memory,"Enable memmap on memory for memory hotplug" );#endif +enum { +ONLINE_POLICY_CONTIG_ZONES =0 , +ONLINE_POLICY_AUTO_MOVABLE , +}; + +const char *online_policy_to_str[] = { + [ONLINE_POLICY_CONTIG_ZONES ] ="contig-zones" , + [ONLINE_POLICY_AUTO_MOVABLE ] ="auto-movable" , +}; + +static int set_online_policy (const char *val,const struct kernel_param *kp) +{ +int ret =sysfs_match_string (online_policy_to_str, val); + +if (ret <0 ) +return ret; + *((int *)kp->arg) = ret; +return 0 ; +} + +static int get_online_policy (char *buffer,const struct kernel_param *kp) +{ +return sprintf (buffer,"%s\n" , online_policy_to_str[*((int *)kp->arg)]); +} + +/* +* memory_hotplug.online_policy: configure online behavior when onlining without +* specifying a zone (MMOP_ONLINE) +* +* "contig-zones": keep zone contiguous +* "auto-movable": online memory to ZONE_MOVABLE if the configuration +* (auto_movable_ratio, auto_movable_numa_aware) allows for it +*/ +static int online_policy__read_mostly =ONLINE_POLICY_CONTIG_ZONES ; +static const struct kernel_param_ops online_policy_ops = { + .set = set_online_policy, + .get = get_online_policy, +}; +module_param_cb (online_policy, &online_policy_ops, &online_policy,0644 ); +MODULE_PARM_DESC (online_policy, +"Set the online policy (\"contig-zones\", \"auto-movable\") " +"Default: \"contig-zones\"" ); + +/* +* memory_hotplug.auto_movable_ratio: specify maximum MOVABLE:KERNEL ratio +* +* The ratio represent an upper limit and the kernel might decide to not +* online some memory to ZONE_MOVABLE -- e.g., because hotplugged KERNEL memory +* doesn't allow for more MOVABLE memory. +*/ +static unsigned int auto_movable_ratio__read_mostly =301 ; +module_param (auto_movable_ratio, uint,0644 ); +MODULE_PARM_DESC (auto_movable_ratio, +"Set the maximum ratio of MOVABLE:KERNEL memory in the system " +"in percent for \"auto-movable\" online policy. Default: 301" ); + +/* +* memory_hotplug.auto_movable_numa_aware: consider numa node stats +*/ +#ifdef CONFIG_NUMA +static bool auto_movable_numa_aware__read_mostly = true; +module_param (auto_movable_numa_aware, bool,0644 ); +MODULE_PARM_DESC (auto_movable_numa_aware, +"Consider numa node stats in addition to global stats in " +"\"auto-movable\" online policy. Default: true" ); +#endif /* CONFIG_NUMA */ +/* * online_page_callback contains pointer to current page onlining function. * Initially it is generic_online_page(). If it is required it could be
@@ -663,6 +730,61 @@ void __ref move_pfn_range_to_zone(structset_zone_contiguous (zone); } +struct auto_movable_stats { +unsigned long kernel_early_pages; +unsigned long movable_pages; +}; + +static void auto_movable_stats_account_zone (struct auto_movable_stats *stats, +struct zone *zone) +{ +if (zone_idx (zone) ==ZONE_MOVABLE ) { + stats->movable_pages += zone->present_pages; + }else { + stats->kernel_early_pages += zone->present_early_pages; +#ifdef CONFIG_CMA +/* +* CMA pages (never on hotplugged memory) behave like +* ZONE_MOVABLE. +*/ + stats->movable_pages += zone->cma_pages; + stats->kernel_early_pages -= zone->cma_pages; +#endif /* CONFIG_CMA */ + } +} + +static bool auto_movable_can_online_movable (int nid,unsigned long nr_pages) +{ +struct auto_movable_stats stats = {}; +unsigned long kernel_early_pages, movable_pages; +pg_data_t *pgdat =NODE_DATA (nid); +struct zone *zone; +int i; + +/* Walk all relevant zones and collect MOVABLE vs. KERNEL stats. */ +if (nid ==NUMA_NO_NODE ) { +/* TODO: cache values */ +for_each_populated_zone (zone) +auto_movable_stats_account_zone (&stats, zone); + }else { +for (i =0 ; i <MAX_NR_ZONES ; i++) { + zone = pgdat->node_zones + i; +if (populated_zone (zone)) +auto_movable_stats_account_zone (&stats, zone); + } + } + + kernel_early_pages = stats.kernel_early_pages; + movable_pages = stats.movable_pages; + +/* +* Test if we could online the given number of pages to ZONE_MOVABLE +* and still stay in the configured ratio. +*/ + movable_pages += nr_pages; +return movable_pages <= (auto_movable_ratio * kernel_early_pages) /100 ; +} +/* * Returns a default kernel memory zone for the given pfn range. * If no kernel zone covers this pfn range it will automatically go
@@ -684,6 +806,72 @@ static struct zone *default_kernel_zone_return &pgdat->node_zones[ZONE_NORMAL ]; } +/* +* Determine to which zone to online memory dynamically based on user +* configuration and system stats. We care about the following ratio: +* +* MOVABLE : KERNEL +* +* Whereby MOVABLE is memory in ZONE_MOVABLE and KERNEL is memory in +* one of the kernel zones. CMA pages inside one of the kernel zones really +* behaves like ZONE_MOVABLE, so we treat them accordingly. +* +* We don't allow for hotplugged memory in a KERNEL zone to increase the +* amount of MOVABLE memory we can have, so we end up with: +* +* MOVABLE : KERNEL_EARLY +* +* Whereby KERNEL_EARLY is memory in one of the kernel zones, available sinze +* boot. We base our calculation on KERNEL_EARLY internally, because: +* +* a) Hotplugged memory in one of the kernel zones can sometimes still get +* hotunplugged, especially when hot(un)plugging individual memory blocks. +* There is no coordination across memory devices, therefore "automatic" +* hotunplugging, as implemented in hypervisors, could result in zone +* imbalances. +* b) Early/boot memory in one of the kernel zones can usually not get +* hotunplugged again (e.g., no firmware interface to unplug, fragmented +* with unmovable allocations). While there are corner cases where it might +* still work, it is barely relevant in practice. +* +* We rely on "present pages" instead of "managed pages", as the latter is +* highly unreliable and dynamic in virtualized environments, and does not +* consider boot time allocations. For example, memory ballooning adjusts the +* managed pages when inflating/deflating the balloon, and balloon compaction +* can even migrate inflated pages between zones. +* +* Using "present pages" is better but some things to keep in mind are: +* +* a) Some memblock allocations, such as for the crashkernel area, are +* effectively unused by the kernel, yet they account to "present pages". +* Fortunately, these allocations are comparatively small in relevant setups +* (e.g., fraction of system memory). +* b) Some hotplugged memory blocks in virtualized environments, esecially +* hotplugged by virtio-mem, look like they are completely present, however, +* only parts of the memory block are actually currently usable. +* "present pages" is an upper limit that can get reached at runtime. As +* we base our calculations on KERNEL_EARLY, this is not an issue. +*/ +static struct zone *auto_movable_zone_for_pfn (int nid,unsigned long pfn, +unsigned long nr_pages) +{ +if (!auto_movable_ratio) + goto kernel_zone; + +if (!auto_movable_can_online_movable (NUMA_NO_NODE , nr_pages)) + goto kernel_zone; + +#ifdef CONFIG_NUMA +if (auto_movable_numa_aware && + !auto_movable_can_online_movable (nid, nr_pages)) + goto kernel_zone; +#endif /* CONFIG_NUMA */ + +return &NODE_DATA (nid)->node_zones[ZONE_MOVABLE ]; +kernel_zone: +return default_kernel_zone_for_pfn (nid, pfn, nr_pages); +} +static inline struct zone *default_zone_for_pfn (int nid,unsigned long start_pfn,unsigned long nr_pages) {
@@ -717,6 +905,9 @@ struct zone *zone_for_pfn_range(int onliif (online_type ==MMOP_ONLINE_MOVABLE )return &NODE_DATA (nid)->node_zones[ZONE_MOVABLE ]; +if (online_policy ==ONLINE_POLICY_AUTO_MOVABLE ) +return auto_movable_zone_for_pfn (nid, start_pfn, nr_pages); +return default_zone_for_pfn (nid, start_pfn, nr_pages); }
_
Andrew Morton
maintainerPATCH 44/147 drivers/base/memory: introduce "memory groups" to logically group memory blocks
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: drivers/base/memory: introduce "memory groups" to logically group memory blocks
In our "auto-movable" memory onlining policy, we want to make decisions across memory blocks of a single memory device. Examples of memory devices include ACPI memory devices (in the simplest case a single DIMM) and virtio-mem. For now, we don't have a connection between a single memory block device and the real memory device. Each memory device consists of 1..X memory block devices.
Let's logically group memory blocks belonging to the same memory device in "memory groups". Memory groups can span multiple physical ranges and a memory group itself does not contain any information regarding physical ranges, only properties (e.g., "max_pages") necessary for improved memory onlining.
Introduce two memory group types:
1) Static memory group: E.g., a single ACPI memory device, consisting of 1..X memory resources. A memory group consists of 1..Y memory blocks. The whole group is added/removed in one go. If any part cannot get offlined, the whole group cannot be removed.
2) Dynamic memory group: E.g., a single virtio-mem device. Memory is dynamically added/removed in a fixed granularity, called a "unit", consisting of 1..X memory blocks. A unit is added/removed in one go. If any part of a unit cannot get offlined, the whole unit cannot be removed.
In case of 1) we usually want either all memory managed by ZONE_MOVABLE or none. In case of 2) we usually want to have as many units as possible managed by ZONE_MOVABLE. We want a single unit to be of the same type.
For now, memory groups are an internal concept that is not exposed to user space; we might want to change that in the future, though.
add_memory() users can specify a mgid instead of a nid when passing the MHP_NID_IS_MGID flag.
---
drivers/base/memory.c | 159 ++++++++++++++++++++++++++++++- include/linux/memory.h | 46 ++++++++ include/linux/memory_hotplug.h | 5 mm/memory_hotplug.c | 11 +- 4 files changed, 215 insertions(+), 6 deletions(-)
drivers/base/memory.c renamed from drivers/base/memory.c~drivers-base-memory-introduce-memory-groups-to-logically-group-memory-blocks +155 -4
@@ -82,6 +82,11 @@ static struct bus_type memory_subsys = {*/ static DEFINE_XARRAY (memory_blocks); +/* +* Memory groups, indexed by memory group id (mgid). +*/ +static DEFINE_XARRAY_FLAGS(memory_groups, XA_FLAGS_ALLOC); +static BLOCKING_NOTIFIER_HEAD (memory_chain);int register_memory_notifier (struct notifier_block *nb)
@@ -634,7 +639,8 @@ int register_memory(struct memory_block }static int init_memory_block (unsigned long block_id,unsigned long state, -unsigned long nr_vmemmap_pages) +unsigned long nr_vmemmap_pages, +struct memory_group *group) {struct memory_block *mem;int ret =0 ;
@@ -652,6 +658,12 @@ static int init_memory_block(unsigned lo mem->state = state; mem->nid =NUMA_NO_NODE ; mem->nr_vmemmap_pages = nr_vmemmap_pages; +INIT_LIST_HEAD (&mem->group_next); + +if (group) { + mem->group = group; +list_add (&mem->group_next, &group->memory_blocks); + } ret =register_memory (mem);
@@ -671,7 +683,7 @@ static int add_memory_block(unsigned lonif (section_count ==0 )return 0 ;return init_memory_block (memory_block_id (base_section_nr), -MEM_ONLINE ,0 ); +MEM_ONLINE ,0 ,NULL ); }static void unregister_memory (struct memory_block *memory)
@@ -681,6 +693,11 @@ static void unregister_memory(struct memWARN_ON (xa_erase (&memory_blocks, memory->dev.id) ==NULL ); +if (memory->group) { +list_del (&memory->group_next); + memory->group =NULL ; + } +/* drop the ref. we got via find_memory_block() */ put_device (&memory->dev);device_unregister (&memory->dev);
@@ -694,7 +711,8 @@ static void unregister_memory(struct mem* Called under device_hotplug_lock. */ int create_memory_block_devices (unsigned long start,unsigned long size, -unsigned long vmemmap_pages) +unsigned long vmemmap_pages, +struct memory_group *group) {const unsigned long start_block_id =pfn_to_block_id (PFN_DOWN (start));unsigned long end_block_id =pfn_to_block_id (PFN_DOWN (start + size));
@@ -707,7 +725,8 @@ int create_memory_block_devices(unsignedreturn -EINVAL ;for (block_id = start_block_id; block_id != end_block_id; block_id++) { - ret =init_memory_block (block_id,MEM_OFFLINE , vmemmap_pages); + ret =init_memory_block (block_id,MEM_OFFLINE , vmemmap_pages, + group);if (ret)break ; }
@@ -891,3 +910,135 @@ int for_each_memory_block(void *arg, walreturn bus_for_each_dev (&memory_subsys,NULL , &cb_data, for_each_memory_block_cb); } + +/* +* This is an internal helper to unify allocation and initialization of +* memory groups. Note that the passed memory group will be copied to a +* dynamically allocated memory group. After this call, the passed +* memory group should no longer be used. +*/ +static int memory_group_register (struct memory_group group) +{ +struct memory_group *new_group; +uint32_t mgid; +int ret; + +if (!node_possible (group.nid)) +return -EINVAL ; + + new_group =kzalloc (sizeof (group),GFP_KERNEL ); +if (!new_group) +return -ENOMEM ; + *new_group = group; +INIT_LIST_HEAD (&new_group->memory_blocks); + + ret =xa_alloc (&memory_groups, &mgid, new_group, xa_limit_31b, +GFP_KERNEL ); +if (ret) { +kfree (new_group); +return ret; + } +return mgid; +} + +/** +* memory_group_register_static() - Register a static memory group. +* @nid: The node id. +* @max_pages: The maximum number of pages we'll have in this static memory +* group. +* +* Register a new static memory group and return the memory group id. +* All memory in the group belongs to a single unit, such as a DIMM. All +* memory belonging to a static memory group is added in one go to be removed +* in one go -- it's static. +* +* Returns an error if out of memory, if the node id is invalid, if no new +* memory groups can be registered, or if max_pages is invalid (0). Otherwise, +* returns the new memory group id. +*/ +int memory_group_register_static (int nid,unsigned long max_pages) +{ +struct memory_group group = { + .nid = nid, + .s = { + .max_pages = max_pages, + }, + }; + +if (!max_pages) +return -EINVAL ; +return memory_group_register (group); +} +EXPORT_SYMBOL_GPL (memory_group_register_static); + +/** +* memory_group_register_dynamic() - Register a dynamic memory group. +* @nid: The node id. +* @unit_pages: Unit in pages in which is memory added/removed in this dynamic +* memory group. +* +* Register a new dynamic memory group and return the memory group id. +* Memory within a dynamic memory group is added/removed dynamically +* in unit_pages. +* +* Returns an error if out of memory, if the node id is invalid, if no new +* memory groups can be registered, or if unit_pages is invalid (0, not a +* power of two, smaller than a single memory block). Otherwise, returns the +* new memory group id. +*/ +int memory_group_register_dynamic (int nid,unsigned long unit_pages) +{ +struct memory_group group = { + .nid = nid, + .is_dynamic = true, + .d = { + .unit_pages = unit_pages, + }, + }; + +if (!unit_pages || !is_power_of_2 (unit_pages) || + unit_pages <PHYS_PFN (memory_block_size_bytes ())) +return -EINVAL ; +return memory_group_register (group); +} +EXPORT_SYMBOL_GPL (memory_group_register_dynamic); + +/** +* memory_group_unregister() - Unregister a memory group. +* @mgid: the memory group id +* +* Unregister a memory group. If any memory block still belongs to this +* memory group, unregistering will fail. +* +* Returns -EINVAL if the memory group id is invalid, returns -EBUSY if some +* memory blocks still belong to this memory group and returns 0 if +* unregistering succeeded. +*/ +int memory_group_unregister (int mgid) +{ +struct memory_group *group; + +if (mgid <0 ) +return -EINVAL ; + + group =xa_load (&memory_groups, mgid); +if (!group) +return -EINVAL ; +if (!list_empty (&group->memory_blocks)) +return -EBUSY ; +xa_erase (&memory_groups, mgid); +kfree (group); +return 0 ; +} +EXPORT_SYMBOL_GPL (memory_group_unregister); + +/* +* This is an internal helper only to be used in core memory hotplug code to +* lookup a memory group. We don't care about locking, as we don't expect a +* memory group to get unregistered while adding memory to it -- because +* the group and the memory is managed by the same driver. +*/ +struct memory_group *memory_group_find_by_id (int mgid) +{ +return xa_load (&memory_groups, mgid); +}
include/linux/memory.h renamed from include/linux/memory.h~drivers-base-memory-introduce-memory-groups-to-logically-group-memory-blocks +45 -1
70 lines not on this page · raw message
include/linux/memory_hotplug.h renamed from include/linux/memory_hotplug.h~drivers-base-memory-introduce-memory-groups-to-logically-group-memory-blocks +5 -0
@@ -50,6 +50,11 @@ typedef int __bitwise mhp_t;* Only selected architectures support it with SPARSE_VMEMMAP. */ #define MHP_MEMMAP_ON_MEMORY ((__force mhp_t)BIT(1)) +/* +* The nid field specifies a memory group id (mgid) instead. The memory group +* implies the node id (nid). +*/ +#define MHP_NID_IS_MGID ((__force mhp_t)BIT(2))/* * Extended parameters for memory hotplug:
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~drivers-base-memory-introduce-memory-groups-to-logically-group-memory-blocks +10 -1
@@ -1258,6 +1258,7 @@ int __ref add_memory_resource(int nid, s {struct mhp_params params = { .pgprot =pgprot_mhp (PAGE_KERNEL ) };struct vmem_altmap mhp_altmap = {}; +struct memory_group *group =NULL ;u64 start, size;bool new_node = false;int ret;
@@ -1269,6 +1270,13 @@ int __ref add_memory_resource(int nid, sif (ret)return ret; +if (mhp_flags &MHP_NID_IS_MGID ) { + group =memory_group_find_by_id (nid); +if (!group) +return -EINVAL ; + nid = group->nid; + } +if (!node_possible (nid)) {WARN (1 ,"node %d was absent from the node_possible_map\n" , nid);return -EINVAL ;
@@ -1303,7 +1311,8 @@ int __ref add_memory_resource(int nid, s goto error;/* create memory block devices after memory was added */ - ret =create_memory_block_devices (start, size, mhp_altmap.alloc); + ret =create_memory_block_devices (start, size, mhp_altmap.alloc, + group);if (ret) {arch_remove_memory (start, size,NULL ); goto error;
_
Andrew Morton
maintainerPATCH 45/147 mm/memory_hotplug: track present pages in memory groups
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm/memory_hotplug: track present pages in memory groups
Let's track all present pages in each memory group. Especially, track memory present in ZONE_MOVABLE and memory present in one of the kernel zones (which really only is ZONE_NORMAL right now as memory groups only apply to hotplugged memory) separately within a memory group, to prepare for making smart auto-online decision for individual memory blocks within a memory group based on group statistics.
---
drivers/base/memory.c | 10 +++++----- include/linux/memory.h | 6 ++++++ include/linux/memory_hotplug.h | 13 +++++++++---- mm/memory_hotplug.c | 19 ++++++++++++++----- 4 files changed, 34 insertions(+), 14 deletions(-)
drivers/base/memory.c renamed from drivers/base/memory.c~mm-memory_hotplug-track-present-pages-in-memory-groups +5 -5
@@ -198,7 +198,7 @@ static int memory_block_online(struct me } ret =online_pages (start_pfn + nr_vmemmap_pages, - nr_pages - nr_vmemmap_pages, zone); + nr_pages - nr_vmemmap_pages, zone, mem->group);if (ret) {if (nr_vmemmap_pages)mhp_deinit_memmap_on_memory (start_pfn, nr_vmemmap_pages);
@@ -210,7 +210,7 @@ static int memory_block_online(struct me* now already properly populated. */ if (nr_vmemmap_pages) -adjust_present_page_count (pfn_to_page (start_pfn), +adjust_present_page_count (pfn_to_page (start_pfn), mem->group, nr_vmemmap_pages);return ret;
@@ -228,16 +228,16 @@ static int memory_block_offline(struct m* can properly be torn down in offline_pages(). */ if (nr_vmemmap_pages) -adjust_present_page_count (pfn_to_page (start_pfn), +adjust_present_page_count (pfn_to_page (start_pfn), mem->group, -nr_vmemmap_pages); ret =offline_pages (start_pfn + nr_vmemmap_pages, - nr_pages - nr_vmemmap_pages); + nr_pages - nr_vmemmap_pages, mem->group);if (ret) {/* offline_pages() failed. Account back. */ if (nr_vmemmap_pages)adjust_present_page_count (pfn_to_page (start_pfn), - nr_vmemmap_pages); + mem->group, nr_vmemmap_pages);return ret; }
include/linux/memory.h renamed from include/linux/memory.h~mm-memory_hotplug-track-present-pages-in-memory-groups +6 -0
@@ -27,6 +27,10 @@* struct memory_group - a logical group of memory blocks * @nid: The node id for all memory blocks inside the memory group. * @blocks: List of all memory blocks belonging to this memory group. +* @present_kernel_pages: Present (online) memory outside ZONE_MOVABLE of this +* memory group. +* @present_movable_pages: Present (online) memory in ZONE_MOVABLE of this +* memory group. * @is_dynamic: The memory group type: static vs. dynamic * @s.max_pages: Valid with &memory_group.is_dynamic == false. The maximum * number of pages we'll have in this static memory group.
@@ -48,6 +52,8 @@ struct memory_group { int nid; struct list_head memory_blocks; + unsigned long present_kernel_pages; + unsigned long present_movable_pages; bool is_dynamic; union { struct {
include/linux/memory_hotplug.h renamed from include/linux/memory_hotplug.h~mm-memory_hotplug-track-present-pages-in-memory-groups +9 -4
@@ -12,6 +12,7 @@ struct zone;struct pglist_data ;struct mem_section ;struct memory_block ; +struct memory_group ;struct resource ;struct vmem_altmap ;
@@ -100,13 +101,15 @@ static inline void zone_seqlock_init(strextern int zone_grow_free_lists (struct zone *zone,unsigned long new_nr_pages);extern int zone_grow_waitqueues (struct zone *zone,unsigned long nr_pages);extern int add_one_highpage (struct page *page,int pfn,int bad_ppro); -extern void adjust_present_page_count (struct page *page,long nr_pages); +extern void adjust_present_page_count (struct page *page, +struct memory_group *group, +long nr_pages);/* VM interface that may be used by firmware interface */ extern int mhp_init_memmap_on_memory (unsigned long pfn,unsigned long nr_pages,struct zone *zone);extern void mhp_deinit_memmap_on_memory (unsigned long pfn,unsigned long nr_pages);extern int online_pages (unsigned long pfn,unsigned long nr_pages, -struct zone *zone); +struct zone *zone,struct memory_group *group);extern struct zone *test_pages_in_a_zone (unsigned long start_pfn,unsigned long end_pfn); extern void __offline_isolated_pages(unsigned long start_pfn,
@@ -296,7 +299,8 @@ static inline void pgdat_resize_init(str#ifdef CONFIG_MEMORY_HOTREMOVE extern void try_offline_node (int nid); -extern int offline_pages (unsigned long start_pfn,unsigned long nr_pages); +extern int offline_pages (unsigned long start_pfn,unsigned long nr_pages, +struct memory_group *group);extern int remove_memory (u64 start,u64 size);extern void __remove_memory (u64 start,u64 size);extern int offline_and_remove_memory (u64 start,u64 size);
@@ -304,7 +308,8 @@ extern int offline_and_remove_memory(u64#else static inline void try_offline_node (int nid) {} -static inline int offline_pages (unsigned long start_pfn,unsigned long nr_pages) +static inline int offline_pages (unsigned long start_pfn,unsigned long nr_pages, +struct memory_group *group) {return -EINVAL ; }
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-track-present-pages-in-memory-groups +14 -5
@@ -915,9 +915,11 @@ struct zone *zone_for_pfn_range(int onli* This function should only be called by memory_block_{online,offline}, * and {online,offline}_pages. */ -void adjust_present_page_count (struct page *page,long nr_pages) +void adjust_present_page_count (struct page *page,struct memory_group *group, +long nr_pages) {struct zone *zone =page_zone (page); +const bool movable =zone_idx (zone) ==ZONE_MOVABLE ;/* * We only support onlining/offlining/adding/removing of complete
@@ -927,6 +929,11 @@ void adjust_present_page_count(struct pa zone->present_early_pages += nr_pages; zone->present_pages += nr_pages; zone->zone_pgdat->node_present_pages += nr_pages; + +if (group && movable) + group->present_movable_pages += nr_pages; +else if (group && !movable) + group->present_kernel_pages += nr_pages; } int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,
@@ -972,7 +979,8 @@ void mhp_deinit_memmap_on_memory(unsignekasan_remove_zero_shadow (__va (PFN_PHYS (pfn)),PFN_PHYS (nr_pages)); } -int __ref online_pages (unsigned long pfn,unsigned long nr_pages,struct zone *zone) +int __ref online_pages (unsigned long pfn,unsigned long nr_pages, +struct zone *zone,struct memory_group *group) {unsigned long flags;int need_zonelists_rebuild =0 ;
@@ -1025,7 +1033,7 @@ int __ref online_pages(unsigned long pfn }online_pages_range (pfn, nr_pages); -adjust_present_page_count (pfn_to_page (pfn), nr_pages); +adjust_present_page_count (pfn_to_page (pfn), group, nr_pages);node_states_set_node (nid, &arg);if (need_zonelists_rebuild)
@@ -1769,7 +1777,8 @@ static int count_system_ram_pages_cb(unsreturn 0 ; } -int __ref offline_pages (unsigned long start_pfn,unsigned long nr_pages) +int __ref offline_pages (unsigned long start_pfn,unsigned long nr_pages, +struct memory_group *group) {const unsigned long end_pfn = start_pfn + nr_pages;unsigned long pfn, system_ram_pages =0 ;
@@ -1905,7 +1914,7 @@ int __ref offline_pages(unsigned long st/* removal success */ adjust_managed_page_count (pfn_to_page (start_pfn), -nr_pages); -adjust_present_page_count (pfn_to_page (start_pfn), -nr_pages); +adjust_present_page_count (pfn_to_page (start_pfn), group, -nr_pages);/* reinitialise watermarks and update pcp limits */ init_per_zone_wmark_min ();
_
Andrew Morton
maintainerPATCH 46/147 ACPI: memhotplug: use a single static memory group for a single memory device
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: ACPI: memhotplug: use a single static memory group for a single memory device
Let's group all memory we add for a single memory device - we want a single node for that (which also seems to be the sane thing to do).
We won't care for now about memory that was already added to the system (e.g., via e820) -- usually *all* memory of a memory device was already added and we'll fail acpi_memory_enable_device().
---
drivers/acpi/acpi_memhotplug.c | 35 ++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-)
drivers/acpi/acpi_memhotplug.c renamed from drivers/acpi/acpi_memhotplug.c~acpi-memhotplug-use-a-single-static-memory-group-for-a-single-memory-device +30 -5
@@ -54,6 +54,7 @@ struct acpi_memory_info {struct acpi_memory_device {struct acpi_device *device;struct list_head res_list; +int mgid; }; static acpi_status
@@ -169,12 +170,33 @@ static void acpi_unbind_memory_blocks(ststatic int acpi_memory_enable_device (struct acpi_memory_device *mem_device) {acpi_handle handle = mem_device->device->handle; +mhp_t mhp_flags =MHP_NID_IS_MGID ;int result, num_enabled =0 ;struct acpi_memory_info *info; -mhp_t mhp_flags =MHP_NONE ; -int node; +u64 total_length =0 ; +int node, mgid; node =acpi_get_node (handle); + +list_for_each_entry (info, &mem_device->res_list, list) { +if (!info->length) +continue ; +/* We want a single node for the whole memory group */ +if (node <0 ) + node =memory_add_physaddr_to_nid (info->start_addr); + total_length += info->length; + } + +if (!total_length) { +dev_err (&mem_device->device->dev,"device is empty\n" ); +return -EINVAL ; + } + + mgid =memory_group_register_static (node,PFN_UP (total_length)); +if (mgid <0 ) +return mgid; + mem_device->mgid = mgid; +/* * Tell the VM there is more memory here... * Note: Assume that this function returns zero on success
@@ -188,12 +210,10 @@ static int acpi_memory_enable_device(str*/ if (!info->length)continue ; -if (node <0 ) - node =memory_add_physaddr_to_nid (info->start_addr);if (mhp_supports_memmap_on_memory (info->length)) mhp_flags |=MHP_MEMMAP_ON_MEMORY ; - result =__add_memory (node, info->start_addr, info->length, + result =__add_memory (mgid, info->start_addr, info->length, mhp_flags);/*
@@ -253,6 +273,10 @@ static void acpi_memory_device_free(struif (!mem_device)return ; +/* In case we succeeded adding *some* memory, unregistering fails. */ +if (mem_device->mgid >=0 ) +memory_group_unregister (mem_device->mgid); +acpi_memory_free_device_resources (mem_device); mem_device->device->driver_data =NULL ;kfree (mem_device);
@@ -273,6 +297,7 @@ static int acpi_memory_device_add(structINIT_LIST_HEAD (&mem_device->res_list); mem_device->device = device; + mem_device->mgid =-1 ;sprintf (acpi_device_name (device),"%s" ,ACPI_MEMORY_DEVICE_NAME );sprintf (acpi_device_class (device),"%s" ,ACPI_MEMORY_DEVICE_CLASS ); device->driver_data = mem_device;
_
Andrew Morton
maintainerPATCH 47/147 dax/kmem: use a single static memory group for a single probed unit
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: dax/kmem: use a single static memory group for a single probed unit
Although dax/kmem users often disable auto-onlining and instead online memory manually (usually to ZONE_MOVABLE), there is still value in having auto-onlining be aware of the relationship of memory blocks.
Let's treat one probed unit as a single static memory device, similar to a single ACPI memory device.
---
drivers/dax/kmem.c | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-)
drivers/dax/kmem.c renamed from drivers/dax/kmem.c~dax-kmem-use-a-single-static-memory-group-for-a-single-probed-unit +32 -8
@@ -37,15 +37,16 @@ static int dax_kmem_range(struct dev_daxstruct dax_kmem_data {const char *res_name; +int mgid;struct resource *res[]; };static int dev_dax_kmem_probe (struct dev_dax *dev_dax) {struct device *dev = &dev_dax->dev; +unsigned long total_len =0 ;struct dax_kmem_data *data; -int rc = -ENOMEM ; -int i, mapped =0 ; +int i, rc, mapped =0 ;int numa_node;/*
@@ -61,24 +62,44 @@ static int dev_dax_kmem_probe(struct devreturn -EINVAL ; } +for (i =0 ; i < dev_dax->nr_range; i++) { +struct range range; + + rc =dax_kmem_range (dev_dax, i, &range); +if (rc) { +dev_info (dev,"mapping%d: %#llx-%#llx too small after alignment\n" , + i, range.start, range.end); +continue ; + } + total_len +=range_len (&range); + } + +if (!total_len) { +dev_warn (dev,"rejecting DAX region without any memory after alignment\n" ); +return -EINVAL ; + } + data =kzalloc (struct_size (data, res, dev_dax->nr_range),GFP_KERNEL );if (!data)return -ENOMEM ; + rc = -ENOMEM ; data->res_name =kstrdup (dev_name (dev),GFP_KERNEL );if (!data->res_name) goto err_res_name; + rc =memory_group_register_static (numa_node, total_len); +if (rc <0 ) + goto err_reg_mgid; + data->mgid = rc; +for (i =0 ; i < dev_dax->nr_range; i++) {struct resource *res;struct range range; rc =dax_kmem_range (dev_dax, i, &range); -if (rc) { -dev_info (dev,"mapping%d: %#llx-%#llx too small after alignment\n" , - i, range.start, range.end); +if (rc)continue ; - }/* Region is permanently reserved if hotremove fails. */ res =request_mem_region (range.start,range_len (&range), data->res_name);
@@ -108,8 +129,8 @@ static int dev_dax_kmem_probe(struct dev* Ensure that future kexec'd kernels will not treat * this as RAM automatically. */ - rc =add_memory_driver_managed (numa_node, range.start, -range_len (&range), kmem_name,MHP_NONE ); + rc =add_memory_driver_managed (data->mgid, range.start, +range_len (&range), kmem_name,MHP_NID_IS_MGID );if (rc) { dev_warn(dev, "mapping%d: %#llx-%#llx memory add failed\n",
@@ -129,6 +150,8 @@ static int dev_dax_kmem_probe(struct devreturn 0 ; err_request_mem: +memory_group_unregister (data->mgid); +err_reg_mgid:kfree (data->res_name); err_res_name:kfree (data);
@@ -171,6 +194,7 @@ static void dev_dax_kmem_remove(struct d }if (success >= dev_dax->nr_range) { +memory_group_unregister (data->mgid);kfree (data->res_name);kfree (data);dev_set_drvdata (dev,NULL );
_
Andrew Morton
maintainerPATCH 48/147 virtio-mem: use a single dynamic memory group for a single virtio-mem device
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: virtio-mem: use a single dynamic memory group for a single virtio-mem device
Let's use a single dynamic memory group.
---
drivers/virtio/virtio_mem.c | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-)
drivers/virtio/virtio_mem.c renamed from drivers/virtio/virtio_mem.c~virtio-mem-use-a-single-dynamic-memory-group-for-a-single-virtio-mem-device +19 -3
@@ -143,6 +143,8 @@ struct virtio_mem {* add_memory_driver_managed(). */ const char *resource_name; +/* Memory group identification. */ +int mgid;/* * We don't want to add too much memory if it's not getting onlined,
@@ -626,8 +628,8 @@ static int virtio_mem_add_memory(struct addr + size - 1);/* Memory might get onlined immediately. */ atomic64_add (size, &vm->offline_size); - rc =add_memory_driver_managed (vm->nid, addr, size, vm->resource_name, -MHP_MERGE_RESOURCE ); + rc =add_memory_driver_managed (vm->mgid, addr, size, vm->resource_name, +MHP_MERGE_RESOURCE |MHP_NID_IS_MGID );if (rc) {atomic64_sub (size, &vm->offline_size);dev_warn (&vm->vdev->dev,"adding memory failed: %d\n" , rc);
@@ -2569,6 +2571,7 @@ static bool virtio_mem_has_memory_added(static int virtio_mem_probe (struct virtio_device *vdev) {struct virtio_mem *vm; +uint64_t unit_pages;int rc;BUILD_BUG_ON (sizeof (struct virtio_mem_req ) !=24 );
@@ -2603,6 +2606,16 @@ static int virtio_mem_probe(struct virtiif (rc) goto out_del_vq; +/* use a single dynamic memory group to cover the whole memory device */ +if (vm->in_sbm) + unit_pages =PHYS_PFN (memory_block_size_bytes ()); +else + unit_pages =PHYS_PFN (vm->bbm.bb_size); + rc =memory_group_register_dynamic (vm->nid, unit_pages); +if (rc <0 ) + goto out_del_resource; + vm->mgid = rc; +/* * If we still have memory plugged, we have to unplug all memory first. * Registering our parent resource makes sure that this memory isn't
@@ -2617,7 +2630,7 @@ static int virtio_mem_probe(struct virti vm->memory_notifier.notifier_call = virtio_mem_memory_notifier_cb; rc =register_memory_notifier (&vm->memory_notifier);if (rc) - goto out_del_resource; + goto out_unreg_group; rc =register_virtio_mem_device (vm);if (rc) goto out_unreg_mem;
@@ -2631,6 +2644,8 @@ static int virtio_mem_probe(struct virtireturn 0 ; out_unreg_mem:unregister_memory_notifier (&vm->memory_notifier); +out_unreg_group: +memory_group_unregister (vm->mgid); out_del_resource:virtio_mem_delete_resource (vm); out_del_vq:
@@ -2695,6 +2710,7 @@ static void virtio_mem_remove(struct vir }else {virtio_mem_delete_resource (vm);kfree_const (vm->resource_name); +memory_group_unregister (vm->mgid); }/* remove all tracking data - no locking needed */
_
Andrew Morton
maintainerPATCH 49/147 mm/memory_hotplug: memory group aware "auto-movable" online policy
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm/memory_hotplug: memory group aware "auto-movable" online policy
Use memory groups to improve our "auto-movable" onlining policy:
1. For static memory groups (e.g., a DIMM), online a memory block MOVABLE only if all other memory blocks in the group are either MOVABLE or could be onlined MOVABLE. A DIMM will either be MOVABLE or not, not a mixture.
2. For dynamic memory groups (e.g., a virtio-mem device), online a memory block MOVABLE only if all other memory blocks inside the current unit are either MOVABLE or could be onlined MOVABLE. For a virtio-mem device with a device block size with 512 MiB, all 128 MiB memory blocks wihin a 512 MiB unit will either be MOVABLE or not, not a mixture.
We have to pass the memory group to zone_for_pfn_range() to take the memory group into account.
Note: for now, there seems to be no compelling reason to make this behavior configurable.
---
drivers/base/memory.c | 18 ++++++----- include/linux/memory_hotplug.h | 3 + mm/memory_hotplug.c | 48 +++++++++++++++++++++++++++++-- 3 files changed, 57 insertions(+), 12 deletions(-)
drivers/base/memory.c renamed from drivers/base/memory.c~mm-memory_hotplug-memory-group-aware-auto-movable-online-policy +10 -8
@@ -182,7 +182,8 @@ static int memory_block_online(struct mestruct zone *zone;int ret; - zone =zone_for_pfn_range (mem->online_type, mem->nid, start_pfn, nr_pages); + zone =zone_for_pfn_range (mem->online_type, mem->nid, mem->group, + start_pfn, nr_pages);/* * Although vmemmap pages have a different lifecycle than the pages
@@ -379,12 +380,13 @@ static ssize_t phys_device_show(struct d#ifdef CONFIG_MEMORY_HOTREMOVE static int print_allowed_zone (char *buf,int len,int nid, +struct memory_group *group,unsigned long start_pfn,unsigned long nr_pages,int online_type,struct zone *default_zone) {struct zone *zone; - zone =zone_for_pfn_range (online_type, nid, start_pfn, nr_pages); + zone =zone_for_pfn_range (online_type, nid, group, start_pfn, nr_pages);if (zone == default_zone)return 0 ;
@@ -397,9 +399,10 @@ static ssize_t valid_zones_show(struct dstruct memory_block *mem =to_memory_block (dev);unsigned long start_pfn =section_nr_to_pfn (mem->start_section_nr);unsigned long nr_pages =PAGES_PER_SECTION * sections_per_block; +struct memory_group *group = mem->group;struct zone *default_zone; +int nid = mem->nid;int len =0 ; -int nid;/* * Check the existing zone. Make sure that we do that only on the
@@ -418,14 +421,13 @@ static ssize_t valid_zones_show(struct d goto out; } - nid = mem->nid; - default_zone =zone_for_pfn_range (MMOP_ONLINE , nid, start_pfn, - nr_pages); + default_zone =zone_for_pfn_range (MMOP_ONLINE , nid, group, + start_pfn, nr_pages); len +=sysfs_emit_at (buf, len,"%s" , default_zone->name); - len +=print_allowed_zone (buf, len, nid, start_pfn, nr_pages, + len +=print_allowed_zone (buf, len, nid, group, start_pfn, nr_pages,MMOP_ONLINE_KERNEL , default_zone); - len +=print_allowed_zone (buf, len, nid, start_pfn, nr_pages, + len +=print_allowed_zone (buf, len, nid, group, start_pfn, nr_pages,MMOP_ONLINE_MOVABLE , default_zone); out: len +=sysfs_emit_at (buf, len,"\n" );
include/linux/memory_hotplug.h renamed from include/linux/memory_hotplug.h~mm-memory_hotplug-memory-group-aware-auto-movable-online-policy +2 -1
@@ -349,7 +349,8 @@ extern void sparse_remove_section(structextern struct page *sparse_decode_mem_map (unsigned long coded_mem_map,unsigned long pnum);extern struct zone *zone_for_pfn_range (int online_type,int nid, -unsigned long start_pfn,unsigned long nr_pages); +struct memory_group *group,unsigned long start_pfn, +unsigned long nr_pages);extern int arch_create_linear_mapping (int nid,u64 start,u64 size,struct mhp_params *params);void arch_remove_linear_mapping (u64 start,u64 size);
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-memory-group-aware-auto-movable-online-policy +45 -3
71 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 50/147 mm/memory_hotplug: improved dynamic memory group aware "auto-movable" online policy
In reply to Andrew MortonFrom: David Hildenbrand <[email protected]>
Subject: mm/memory_hotplug: improved dynamic memory group aware "auto-movable" online policy
Currently, the "auto-movable" online policy does not allow for hotplugged KERNEL (ZONE_NORMAL) memory to increase the amount of MOVABLE memory we can have, primarily, because there is no coordiantion across memory devices and we don't want to create zone-imbalances accidentially when unplugging memory.
However, within a single memory device it's different. Let's allow for KERNEL memory within a dynamic memory group to allow for more MOVABLE within the same memory group. The only thing we have to take care of is that the managing driver avoids zone imbalances by unplugging MOVABLE memory first, otherwise there can be corner cases where unplug of memory could result in (accidential) zone imbalances.
virtio-mem is the only user of dynamic memory groups and recently added support for prioritizing unplug of ZONE_MOVABLE over ZONE_NORMAL, so we don't need a new toggle to enable it for dynamic memory groups.
We limit this handling to dynamic memory groups, because:
* We want to keep the runtime overhead for collecting stats when onlining a single memory block small. We tend to have only a handful of dynamic memory groups, but we can have quite some static memory groups (e.g., 256 DIMMs).
* It doesn't make too much sense for static memory groups, as we try onlining all applicable memory blocks either completely to ZONE_MOVABLE or not. In ordinary operation, we won't have a mixture of zones within a static memory group.
When adding memory to a dynamic memory group, we'll first online memory to ZONE_MOVABLE as long as early KERNEL memory allows for it. Then, we'll online the next unit(s) to ZONE_NORMAL, until we can online the next unit(s) to ZONE_MOVABLE.
For a simple virtio-mem device with a MOVABLE:KERNEL ratio of 3:1, it will result in a layout like:
[M][M][M][M][M][M][M][M][N][M][M][M][N][M][M][M]... ^ movable memory due to early kernel memory
^ allows for more movable memory ... ^-----^ ... here ^ allows for more movable memory ... ^-----^ ... here
While the created layout is sub-optimal when it comes to contiguous zones, it gives us the maximum flexibility when dynamically growing/shrinking a device; we can grow small VMs really big in small steps, and still shrink reliably to e.g., 1/4 of the maximum VM size in this example, removing full memory blocks along with meta data more reliably.
Mark dynamic memory groups in the xarray such that we can efficiently iterate over them when collecting stats. In usual setups, we have one virtio-mem device per NUMA node, and usually only a small number of NUMA nodes.
Note: for now, there seems to be no compelling reason to make this behavior configurable.
---
drivers/base/memory.c | 30 +++++++++++++++++++ include/linux/memory.h | 3 + mm/memory_hotplug.c | 60 ++++++++++++++++++++++++++++++++++++--- 3 files changed, 89 insertions(+), 4 deletions(-)
drivers/base/memory.c renamed from drivers/base/memory.c~mm-memory_hotplug-improved-dynamic-memory-group-aware-auto-movable-online-policy +30 -0
@@ -86,6 +86,7 @@ static DEFINE_XARRAY(memory_blocks);* Memory groups, indexed by memory group id (mgid). */ static DEFINE_XARRAY_FLAGS(memory_groups, XA_FLAGS_ALLOC); +#define MEMORY_GROUP_MARK_DYNAMIC XA_MARK_1static BLOCKING_NOTIFIER_HEAD (memory_chain);
@@ -939,6 +940,8 @@ static int memory_group_register(structif (ret) {kfree (new_group);return ret; + }else if (group.is_dynamic) { +xa_set_mark (&memory_groups, mgid,MEMORY_GROUP_MARK_DYNAMIC ); }return mgid; }
@@ -1044,3 +1047,30 @@ struct memory_group *memory_group_find_b {return xa_load (&memory_groups, mgid); } + +/* +* This is an internal helper only to be used in core memory hotplug code to +* walk all dynamic memory groups excluding a given memory group, either +* belonging to a specific node, or belonging to any node. +*/ +int walk_dynamic_memory_groups (int nid,walk_memory_groups_func_t func, +struct memory_group *excluded,void *arg) +{ +struct memory_group *group; +unsigned long index; +int ret =0 ; + +xa_for_each_marked (&memory_groups, index, group, +MEMORY_GROUP_MARK_DYNAMIC ) { +if (group == excluded) +continue ; +#ifdef CONFIG_NUMA +if (nid !=NUMA_NO_NODE && group->nid != nid) +continue ; +#endif /* CONFIG_NUMA */ + ret =func (group, arg); +if (ret) +break ; + } +return ret; +}
include/linux/memory.h renamed from include/linux/memory.h~mm-memory_hotplug-improved-dynamic-memory-group-aware-auto-movable-online-policy +3 -0
@@ -146,6 +146,9 @@ extern int memory_group_register_static(extern int memory_group_register_dynamic (int nid,unsigned long unit_pages);extern int memory_group_unregister (int mgid);struct memory_group *memory_group_find_by_id (int mgid); +typedef int (*walk_memory_groups_func_t )(struct memory_group *,void *); +int walk_dynamic_memory_groups (int nid,walk_memory_groups_func_t func, +struct memory_group *excluded,void *arg);#endif /* CONFIG_MEMORY_HOTPLUG_SPARSE */ #ifdef CONFIG_MEMORY_HOTPLUG
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-improved-dynamic-memory-group-aware-auto-movable-online-policy +56 -4
91 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 51/147 mm/memory_hotplug: use helper zone_is_zone_device() to simplify the code
In reply to Andrew MortonFrom: Miaohe Lin <[email protected]>
Subject: mm/memory_hotplug: use helper zone_is_zone_device() to simplify the code
Patch series "Cleanup and fixups for memory hotplug".
This series contains cleanup to use helper function to simplify the code. Also we fix some potential bugs. More details can be found in the respective changelogs.
This patch (of 3):
Use helper zone_is_zone_device() to simplify the code and remove some explicit CONFIG_ZONE_DEVICE codes.
---
mm/memory_hotplug.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-use-helper-zone_is_zone_device-to-simplify-the-code +1 -3
@@ -477,15 +477,13 @@ void __ref remove_pfn_range_from_zone(st sizeof(struct page) * cur_nr_pages); } -#ifdef CONFIG_ZONE_DEVICE /* * Zone shrinking code cannot properly deal with ZONE_DEVICE. So * we will not try to shrink the zones - which is okay as * set_zone_contiguous() cannot deal with ZONE_DEVICE either way. */ -if (zone_idx (zone) ==ZONE_DEVICE ) +if (zone_is_zone_device (zone))return ; -#endif clear_zone_contiguous (zone);
_
Andrew Morton
maintainerPATCH 52/147 mm: remove redundant compound_head() calling
In reply to Andrew MortonFrom: Muchun Song <[email protected]>
Subject: mm: remove redundant compound_head() calling
There is a READ_ONCE() in the macro of compound_head(), which will prevent compiler from optimizing the code when there are more than once calling of it in a function. Remove the redundant calling of compound_head() from page_to_index() and page_add_file_rmap() for better code generation.
---
include/linux/pagemap.h | 7 +++---- mm/rmap.c | 6 ++++-- 2 files changed, 7 insertions(+), 6 deletions(-)
include/linux/pagemap.h renamed from include/linux/pagemap.h~mm-remove-redundant-compound_head-calling +3 -4
@@ -521,18 +521,17 @@ static inline struct page *read_mapping_*/ static inline pgoff_t page_to_index (struct page *page) { -pgoff_t pgoff; +struct page *head;if (likely (!PageTransTail (page)))return page->index; + head =compound_head (page);/* * We don't initialize ->index for tail pages: calculate based on * head page */ - pgoff =compound_head (page)->index; - pgoff += page -compound_head (page); -return pgoff; +return head->index + page - head; }extern pgoff_t hugetlb_basepage_index (struct page *page);
mm/rmap.c renamed from mm/rmap.c~mm-remove-redundant-compound_head-calling +4 -2
@@ -1230,11 +1230,13 @@ void page_add_file_rmap(struct page *pag nr_pages); }else {if (PageTransCompound (page) &&page_mapping (page)) { +struct page *head =compound_head (page); +VM_WARN_ON_ONCE (!PageLocked (page)); -SetPageDoubleMap (compound_head (page)); +SetPageDoubleMap (head);if (PageMlocked (page)) -clear_page_mlock (compound_head (page)); +clear_page_mlock (head); }if (!atomic_inc_and_test (&page->_mapcount)) goto out;
_
Andrew Morton
maintainerPATCH 53/147 riscv: only select GENERIC_IOREMAP if MMU support is enabled
In reply to Andrew MortonFrom: Christoph Hellwig <[email protected]>
Subject: riscv: only select GENERIC_IOREMAP if MMU support is enabled
nommu ioremap is an inline stub in asm-generic/io.h.
---
arch/riscv/Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/riscv/Kconfig renamed from arch/riscv/Kconfig~riscv-only-select-generic_ioremap-if-mmu-support-is-enabled +1 -1
@@ -48,7 +48,7 @@ config RISCV select GENERIC_CLOCKEVENTS_BROADCAST if SMP select GENERIC_EARLY_IOREMAP select GENERIC_GETTIMEOFDAY if HAVE_GENERIC_VDSO - select GENERIC_IOREMAP + select GENERIC_IOREMAP if MMU select GENERIC_IRQ_MULTI_HANDLER select GENERIC_IRQ_SHOW select GENERIC_LIB_DEVMEM_IS_ALLOWED
_
Andrew Morton
maintainerPATCH 54/147 mm: move ioremap_page_range to vmalloc.c
In reply to Andrew MortonFrom: Christoph Hellwig <[email protected]>
Subject: mm: move ioremap_page_range to vmalloc.c
Patch series "small ioremap cleanups".
The first patch moves a little code around the vmalloc/ioremap boundary following a bigger move by Nick earlier. The second enforces non-executable mapping on ioremap just like we do for vmap. No driver currently uses executable mappings anyway, as they should.
This patch (of 2):
This keeps it together with the implementation, and to remove the vmap_range wrapper.
---
include/linux/vmalloc.h | 3 --- mm/Makefile | 3 ++- mm/ioremap.c | 25 ------------------------- mm/vmalloc.c | 22 +++++++++++++++++----- 4 files changed, 19 insertions(+), 34 deletions(-)
include/linux/vmalloc.h renamed from include/linux/vmalloc.h~mm-move-ioremap_page_range-to-vmallocc +0 -3
@@ -225,9 +225,6 @@ static inline bool is_vm_area_hugepages( }#ifdef CONFIG_MMU -int vmap_range (unsigned long addr,unsigned long end, -phys_addr_t phys_addr,pgprot_t prot, -unsigned int max_page_shift);void vunmap_range (unsigned long addr,unsigned long end);static inline void set_vm_flush_reset_perms (void *addr) {
mm/ioremap.c renamed from mm/ioremap.c~mm-move-ioremap_page_range-to-vmallocc +0 -25
@@ -8,33 +8,9 @@*/ #include <linux/vmalloc.h> #include <linux/mm.h> -#include <linux/sched.h> #include <linux/io.h> #include <linux/export.h> -#include <asm/cacheflush.h> -#include "pgalloc-track.h" - -#ifdef CONFIG_HAVE_ARCH_HUGE_VMAP -static unsigned int __ro_after_init iomap_max_page_shift =BITS_PER_LONG -1 ; - -static int __init set_nohugeiomap (char *str) -{ - iomap_max_page_shift =PAGE_SHIFT ; -return 0 ; -} -early_param ("nohugeiomap" , set_nohugeiomap); -#else /* CONFIG_HAVE_ARCH_HUGE_VMAP */ -static const unsigned int iomap_max_page_shift =PAGE_SHIFT ; -#endif /* CONFIG_HAVE_ARCH_HUGE_VMAP */ - -int ioremap_page_range (unsigned long addr, -unsigned long end,phys_addr_t phys_addr,pgprot_t prot) -{ -return vmap_range (addr, end, phys_addr, prot, iomap_max_page_shift); -} - -#ifdef CONFIG_GENERIC_IOREMAP void __iomem *ioremap_prot (phys_addr_t addr,size_t size,unsigned long prot) {unsigned long offset, vaddr;
@@ -71,4 +47,3 @@ void iounmap(volatile void __iomem *addrvunmap ((void *)((unsigned long )addr &PAGE_MASK )); }EXPORT_SYMBOL (iounmap); -#endif /* CONFIG_GENERIC_IOREMAP */
mm/Makefile renamed from mm/Makefile~mm-move-ioremap_page_range-to-vmallocc +2 -1
@@ -38,7 +38,7 @@ mmu-y := nommu.o mmu-$(CONFIG_MMU) := highmem.o memory.o mincore.o \ mlock.o mmap.o mmu_gather.o mprotect.o mremap.o \ msync.o page_vma_mapped.o pagewalk.o \ - pgtable-generic.o rmap.o vmalloc.o ioremap.o + pgtable-generic.o rmap.o vmalloc.o ifdef CONFIG_CROSS_MEMORY_ATTACH
@@ -128,3 +128,4 @@ obj-$(CONFIG_PTDUMP_CORE) += ptdump.o obj-$(CONFIG_PAGE_REPORTING) += page_reporting.o obj-$(CONFIG_IO_MAPPING) += io-mapping.o obj-$(CONFIG_HAVE_BOOTMEM_INFO_NODE) += bootmem_info.o +obj-$(CONFIG_GENERIC_IOREMAP) += ioremap.o
mm/vmalloc.c renamed from mm/vmalloc.c~mm-move-ioremap_page_range-to-vmallocc +17 -5
@@ -44,6 +44,19 @@#include "internal.h" #include "pgalloc-track.h" +#ifdef CONFIG_HAVE_ARCH_HUGE_VMAP +static unsigned int __ro_after_init ioremap_max_page_shift =BITS_PER_LONG -1 ; + +static int __init set_nohugeiomap (char *str) +{ + ioremap_max_page_shift =PAGE_SHIFT ; +return 0 ; +} +early_param ("nohugeiomap" , set_nohugeiomap); +#else /* CONFIG_HAVE_ARCH_HUGE_VMAP */ +static const unsigned int ioremap_max_page_shift =PAGE_SHIFT ; +#endif /* CONFIG_HAVE_ARCH_HUGE_VMAP */ +#ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC static bool __ro_after_init vmap_allow_huge = true;
@@ -298,15 +311,14 @@ static int vmap_range_noflush(unsigned lreturn err; } -int vmap_range (unsigned long addr,unsigned long end, -phys_addr_t phys_addr,pgprot_t prot, -unsigned int max_page_shift) +int ioremap_page_range (unsigned long addr,unsigned long end, +phys_addr_t phys_addr,pgprot_t prot) {int err; - err =vmap_range_noflush (addr, end, phys_addr, prot, max_page_shift); + err =vmap_range_noflush (addr, end, phys_addr, prot, + ioremap_max_page_shift);flush_cache_vmap (addr, end); -return err; }
_
Andrew Morton
maintainerPATCH 55/147 mm: don't allow executable ioremap mappings
In reply to Andrew MortonFrom: Christoph Hellwig <[email protected]>
Subject: mm: don't allow executable ioremap mappings
There is no need to execute from iomem (and most platforms it is impossible anyway), so add the pgprot_nx() call similar to vmap.
---
mm/vmalloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/vmalloc.c renamed from mm/vmalloc.c~mm-dont-allow-executable-ioremap-mappings +1 -1
@@ -316,7 +316,7 @@ int ioremap_page_range(unsigned long add {int err; - err =vmap_range_noflush (addr, end, phys_addr, prot, + err =vmap_range_noflush (addr, end, phys_addr,pgprot_nx (prot), ioremap_max_page_shift);flush_cache_vmap (addr, end);return err;
_
Andrew Morton
maintainerPATCH 56/147 mm/early_ioremap.c: remove redundant early_ioremap_shutdown()
In reply to Andrew MortonFrom: Weizhao Ouyang <[email protected]>
Subject: mm/early_ioremap.c: remove redundant early_ioremap_shutdown()
early_ioremap_reset() reserved a weak function so that architectures can provide a specific cleanup. Now no architectures use it, remove this redundant function.
---
include/asm-generic/early_ioremap.h | 6 ------ mm/early_ioremap.c | 5 ----- 2 files changed, 11 deletions(-)
include/asm-generic/early_ioremap.h renamed from include/asm-generic/early_ioremap.h~mm-early_ioremapc-remove-redundant-early_ioremap_shutdown +0 -6
@@ -19,12 +19,6 @@ extern void *early_memremap_prot(resourcextern void early_iounmap (void __iomem *addr,unsigned long size);extern void early_memunmap (void *addr,unsigned long size); -/* -* Weak function called by early_ioremap_reset(). It does nothing, but -* architectures may provide their own version to do any needed cleanups. -*/ -extern void early_ioremap_shutdown (void ); -#if defined(CONFIG_GENERIC_EARLY_IOREMAP ) && defined(CONFIG_MMU )/* Arch-specific initialization */ extern void early_ioremap_init (void );
mm/early_ioremap.c renamed from mm/early_ioremap.c~mm-early_ioremapc-remove-redundant-early_ioremap_shutdown +0 -5
@@ -38,13 +38,8 @@ pgprot_t __init __weak early_memremap_pgreturn prot; } -void __init __weak early_ioremap_shutdown (void ) -{ -} -void __init early_ioremap_reset (void ) { -early_ioremap_shutdown (); after_paging_init =1 ; }
_
Andrew Morton
maintainerPATCH 57/147 highmem: don't disable preemption on RT in kmap_atomic()
In reply to Andrew MortonFrom: Sebastian Andrzej Siewior <[email protected]>
Subject: highmem: don't disable preemption on RT in kmap_atomic()
kmap_atomic() disables preemption and pagefaults for historical reasons. The conversion to kmap_local(), which only disables migration, cannot be done wholesale because quite some call sites need to be updated to accommodate with the changed semantics.
On PREEMPT_RT enabled kernels the kmap_atomic() semantics are problematic due to the implicit disabling of preemption which makes it impossible to acquire 'sleeping' spinlocks within the kmap atomic sections.
PREEMPT_RT replaces the preempt_disable() with a migrate_disable() for more than a decade. It could be argued that this is a justification to do this unconditionally, but PREEMPT_RT covers only a limited number of architectures and it disables some functionality which limits the coverage further.
Limit the replacement to PREEMPT_RT for now.
---
include/linux/highmem-internal.h | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-)
include/linux/highmem-internal.h renamed from include/linux/highmem-internal.h~highmem-dont-disable-preemption-on-rt-in-kmap_atomic +22 -5
@@ -90,7 +90,11 @@ static inline void __kunmap_local(void *static inline void *kmap_atomic_prot (struct page *page,pgprot_t prot) { -preempt_disable (); +if (IS_ENABLED (CONFIG_PREEMPT_RT )) +migrate_disable (); +else +preempt_disable (); +pagefault_disable ();return __kmap_local_page_prot (page, prot); }
@@ -102,7 +106,11 @@ static inline void *kmap_atomic(struct pstatic inline void *kmap_atomic_pfn (unsigned long pfn) { -preempt_disable (); +if (IS_ENABLED (CONFIG_PREEMPT_RT )) +migrate_disable (); +else +preempt_disable (); +pagefault_disable ();return __kmap_local_pfn_prot (pfn, kmap_prot); }
@@ -111,7 +119,10 @@ static inline void __kunmap_atomic(void {kunmap_local_indexed (addr);pagefault_enable (); -preempt_enable (); +if (IS_ENABLED (CONFIG_PREEMPT_RT )) +migrate_enable (); +else +preempt_enable (); }unsigned int __nr_free_highpages (void );
@@ -179,7 +190,10 @@ static inline void __kunmap_local(void *static inline void *kmap_atomic (struct page *page) { -preempt_disable (); +if (IS_ENABLED (CONFIG_PREEMPT_RT )) +migrate_disable (); +else +preempt_disable ();pagefault_disable ();return page_address (page); }
@@ -200,7 +214,10 @@ static inline void __kunmap_atomic(voidkunmap_flush_on_unmap (addr);#endif pagefault_enable (); -preempt_enable (); +if (IS_ENABLED (CONFIG_PREEMPT_RT )) +migrate_enable (); +else +preempt_enable (); }static inline unsigned int nr_free_highpages (void ) {return 0 ; }
_
Andrew Morton
maintainerPATCH 58/147 mm: in_irq() cleanup
In reply to Andrew MortonFrom: Changbin Du <[email protected]>
Subject: mm: in_irq() cleanup
Replace the obsolete and ambiguos macro in_irq() with new macro in_hardirq().
---
mm/highmem.c | 2 +- mm/kmemleak.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)
mm/highmem.c renamed from mm/highmem.c~mm-in_irq-cleanup +1 -1
@@ -436,7 +436,7 @@ EXPORT_SYMBOL(zero_user_segments);static inline int kmap_local_idx_push (void ) { -WARN_ON_ONCE (in_irq () && !irqs_disabled ()); +WARN_ON_ONCE (in_hardirq () && !irqs_disabled ()); current->kmap_ctrl.idx +=KM_INCR ;BUG_ON (current->kmap_ctrl.idx >=KM_MAX_IDX );return current->kmap_ctrl.idx -1 ;
mm/kmemleak.c renamed from mm/kmemleak.c~mm-in_irq-cleanup +1 -1
@@ -598,7 +598,7 @@ static struct kmemleak_object *create_ob object->checksum =0 ;/* task information */ -if (in_irq ()) { +if (in_hardirq ()) { object->pid =0 ;strncpy (object->comm,"hardirq" ,sizeof (object->comm)); }else if (in_serving_softirq ()) {
_
Andrew Morton
maintainerPATCH 59/147 mm: introduce PAGEFLAGS_MASK to replace ((1UL << NR_PAGEFLAGS) - 1)
In reply to Andrew MortonFrom: Muchun Song <[email protected]>
Subject: mm: introduce PAGEFLAGS_MASK to replace ((1UL << NR_PAGEFLAGS) - 1)
Instead of hard-coding ((1UL << NR_PAGEFLAGS) - 1) everywhere, introducing PAGEFLAGS_MASK to make the code clear to get the page flags.
---
include/linux/page-flags.h | 4 +++- include/trace/events/page_ref.h | 4 ++-- lib/test_printf.c | 2 +- lib/vsprintf.c | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-)
include/linux/page-flags.h renamed from include/linux/page-flags.h~mm-introduce-pageflags_mask-to-replace-1ul-nr_pageflags-1 +3 -1
@@ -178,6 +178,8 @@ enum pageflags { PG_reported = PG_uptodate, }; +#define PAGEFLAGS_MASK ((1UL << NR_PAGEFLAGS) - 1) +#ifndef __GENERATING_BOUNDS_Hstatic inline unsigned long _compound_head (const struct page *page)
@@ -868,7 +870,7 @@ static inline void ClearPageSlabPfmemall* alloc-free cycle to prevent from reusing the page. */ #define PAGE_FLAGS_CHECK_AT_PREP \ - (((1UL << NR_PAGEFLAGS) - 1) & ~__PG_HWPOISON) + (PAGEFLAGS_MASK & ~__PG_HWPOISON)#define PAGE_FLAGS_PRIVATE \ (1UL << PG_private | 1UL << PG_private_2)
include/trace/events/page_ref.h renamed from include/trace/events/page_ref.h~mm-introduce-pageflags_mask-to-replace-1ul-nr_pageflags-1 +2 -2
@@ -38,7 +38,7 @@ DECLARE_EVENT_CLASS(page_ref_mod_templatTP_printk ("pfn=0x%lx flags=%s count=%d mapcount=%d mapping=%p mt=%d val=%d" , __entry->pfn, -show_page_flags (__entry->flags & ((1UL <<NR_PAGEFLAGS ) -1 )), +show_page_flags (__entry->flags &PAGEFLAGS_MASK ), __entry->count, __entry->mapcount, __entry->mapping, __entry->mt, __entry->val)
@@ -88,7 +88,7 @@ DECLARE_EVENT_CLASS(page_ref_mod_and_tesTP_printk ("pfn=0x%lx flags=%s count=%d mapcount=%d mapping=%p mt=%d val=%d ret=%d" , __entry->pfn, -show_page_flags (__entry->flags & ((1UL <<NR_PAGEFLAGS ) -1 )), +show_page_flags (__entry->flags &PAGEFLAGS_MASK ), __entry->count, __entry->mapcount, __entry->mapping, __entry->mt, __entry->val, __entry->ret)
lib/test_printf.c renamed from lib/test_printf.c~mm-introduce-pageflags_mask-to-replace-1ul-nr_pageflags-1 +1 -1
@@ -614,7 +614,7 @@ page_flags_test(int section, int node, ibool append = false;int i; - flags &=BIT (NR_PAGEFLAGS ) -1 ; + flags &=PAGEFLAGS_MASK ;if (flags) { page_flags |= flags;snprintf (cmp_buf + size,BUF_SIZE - size,"%s" , name);
lib/vsprintf.c renamed from lib/vsprintf.c~mm-introduce-pageflags_mask-to-replace-1ul-nr_pageflags-1 +1 -1
@@ -2019,7 +2019,7 @@ static const struct page_flags_fields pfstatic char *format_page_flags (char *buf,char *end,unsigned long flags) { -unsigned long main_flags = flags & (BIT (NR_PAGEFLAGS ) -1 ); +unsigned long main_flags = flags &PAGEFLAGS_MASK ;bool append = false;int i;
_
Andrew Morton
maintainerPATCH 60/147 mm/secretmem: use refcount_t instead of atomic_t
In reply to Andrew MortonFrom: Jordy Zomer <[email protected]>
Subject: mm/secretmem: use refcount_t instead of atomic_t
When a secret memory region is active, memfd_secret disables hibernation. One of the goals is to keep the secret data from being written to persistent-storage.
It accomplishes this by maintaining a reference count to secretmem_users. Once this reference is held your system can not be hibernated due to the check in hibernation_available(). However, because secretmem_users is of type atomic_t, reference counter overflows are possible.
As you can see there's an atomic_inc for each memfd that is opened in the memfd_secret syscall. If a local attacker succeeds to open 2^32 memfd's, the counter will wrap around to 0. This implies that you may hibernate again, even though there are still regions of this secret memory, thereby bypassing the security check.
In an attempt to fix this I have used refcount_t instead of atomic_t which prevents reference counter overflows.
---
mm/secretmem.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
mm/secretmem.c renamed from mm/secretmem.c~mm-secretmem-use-refcount_t-instead-of-atomic_t +5 -4
@@ -18,6 +18,7 @@#include <linux/secretmem.h> #include <linux/set_memory.h> #include <linux/sched/signal.h> +#include <linux/refcount.h> #include <uapi/linux/magic.h>
@@ -40,11 +41,11 @@ module_param_named(enable, secretmem_enaMODULE_PARM_DESC (secretmem_enable,"Enable secretmem and memfd_secret(2) system call" ); -static atomic_t secretmem_users; +static refcount_t secretmem_users;bool secretmem_active (void ) { -return !!atomic_read (&secretmem_users); +return !!refcount_read (&secretmem_users); }static vm_fault_t secretmem_fault (struct vm_fault *vmf)
@@ -103,7 +104,7 @@ static const struct vm_operations_structstatic int secretmem_release (struct inode *inode,struct file *file) { -atomic_dec (&secretmem_users); +refcount_dec (&secretmem_users);return 0 ; }
@@ -217,7 +218,7 @@ SYSCALL_DEFINE1(memfd_secret, unsigned i file->f_flags |=O_LARGEFILE ;fd_install (fd, file); -atomic_inc (&secretmem_users); +refcount_inc (&secretmem_users);return fd; err_put_fd:
_
Andrew Morton
maintainerPATCH 61/147 kfence: show cpu and timestamp in alloc/free info
In reply to Andrew MortonFrom: Marco Elver <[email protected]>
Subject: kfence: show cpu and timestamp in alloc/free info
Record cpu and timestamp on allocations and frees, and show them in reports. Upon an error, this can help correlate earlier messages in the kernel log via allocation and free timestamps.
---
Documentation/dev-tools/kfence.rst | 98 ++++++++++++++------------- mm/kfence/core.c | 3 mm/kfence/kfence.h | 2 mm/kfence/report.c | 19 +++-- 4 files changed, 71 insertions(+), 51 deletions(-)
Documentation/dev-tools/kfence.rst renamed from Documentation/dev-tools/kfence.rst~kfence-show-cpu-and-timestamp-in-alloc-free-info +53 -45
@@ -65,25 +65,27 @@ Error reports A typical out-of-bounds access looks like this:: ================================================================== - BUG: KFENCE: out-of-bounds read in test_out_of_bounds_read+0xa3/0x22b + BUG: KFENCE: out-of-bounds read in test_out_of_bounds_read+0xa6/0x234 - Out-of-bounds read at 0xffffffffb672efff (1B left of kfence-#17): - test_out_of_bounds_read+0xa3/0x22b - kunit_try_run_case+0x51/0x85 + Out-of-bounds read at 0xffff8c3f2e291fff (1B left of kfence-#72): + test_out_of_bounds_read+0xa6/0x234 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - kfence-#17 [0xffffffffb672f000-0xffffffffb672f01f, size=32, cache=kmalloc-32] allocated by task 507: - test_alloc+0xf3/0x25b - test_out_of_bounds_read+0x98/0x22b - kunit_try_run_case+0x51/0x85 + kfence-#72: 0xffff8c3f2e292000-0xffff8c3f2e29201f, size=32, cache=kmalloc-32 + + allocated by task 484 on cpu 0 at 32.919330s: + test_alloc+0xfe/0x738 + test_out_of_bounds_read+0x9b/0x234 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - CPU: 4 PID: 107 Comm: kunit_try_catch Not tainted 5.8.0-rc6+ #7 - Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1 04/01/2014 + CPU: 0 PID: 484 Comm: kunit_try_catch Not tainted 5.13.0-rc3+ #7 + Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014 ================================================================== The header of the report provides a short summary of the function involved in
@@ -96,30 +98,32 @@ Use-after-free accesses are reported as: ================================================================== BUG: KFENCE: use-after-free read in test_use_after_free_read+0xb3/0x143 - Use-after-free read at 0xffffffffb673dfe0 (in kfence-#24): + Use-after-free read at 0xffff8c3f2e2a0000 (in kfence-#79): test_use_after_free_read+0xb3/0x143 - kunit_try_run_case+0x51/0x85 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - kfence-#24 [0xffffffffb673dfe0-0xffffffffb673dfff, size=32, cache=kmalloc-32] allocated by task 507: - test_alloc+0xf3/0x25b + kfence-#79: 0xffff8c3f2e2a0000-0xffff8c3f2e2a001f, size=32, cache=kmalloc-32 + + allocated by task 488 on cpu 2 at 33.871326s: + test_alloc+0xfe/0x738 test_use_after_free_read+0x76/0x143 - kunit_try_run_case+0x51/0x85 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - freed by task 507: + freed by task 488 on cpu 2 at 33.871358s: test_use_after_free_read+0xa8/0x143 - kunit_try_run_case+0x51/0x85 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - CPU: 4 PID: 109 Comm: kunit_try_catch Tainted: G W 5.8.0-rc6+ #7 - Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1 04/01/2014 + CPU: 2 PID: 488 Comm: kunit_try_catch Tainted: G B 5.13.0-rc3+ #7 + Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014 ================================================================== KFENCE also reports on invalid frees, such as double-frees::
@@ -127,30 +131,32 @@ KFENCE also reports on invalid frees, su ================================================================== BUG: KFENCE: invalid free in test_double_free+0xdc/0x171 - Invalid free of 0xffffffffb6741000: + Invalid free of 0xffff8c3f2e2a4000 (in kfence-#81): test_double_free+0xdc/0x171 - kunit_try_run_case+0x51/0x85 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - kfence-#26 [0xffffffffb6741000-0xffffffffb674101f, size=32, cache=kmalloc-32] allocated by task 507: - test_alloc+0xf3/0x25b + kfence-#81: 0xffff8c3f2e2a4000-0xffff8c3f2e2a401f, size=32, cache=kmalloc-32 + + allocated by task 490 on cpu 1 at 34.175321s: + test_alloc+0xfe/0x738 test_double_free+0x76/0x171 - kunit_try_run_case+0x51/0x85 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - freed by task 507: + freed by task 490 on cpu 1 at 34.175348s: test_double_free+0xa8/0x171 - kunit_try_run_case+0x51/0x85 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - CPU: 4 PID: 111 Comm: kunit_try_catch Tainted: G W 5.8.0-rc6+ #7 - Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1 04/01/2014 + CPU: 1 PID: 490 Comm: kunit_try_catch Tainted: G B 5.13.0-rc3+ #7 + Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014 ================================================================== KFENCE also uses pattern-based redzones on the other side of an object's guard
@@ -160,23 +166,25 @@ These are reported on frees:: ================================================================== BUG: KFENCE: memory corruption in test_kmalloc_aligned_oob_write+0xef/0x184 - Corrupted memory at 0xffffffffb6797ff9 [ 0xac . . . . . . ] (in kfence-#69): + Corrupted memory at 0xffff8c3f2e33aff9 [ 0xac . . . . . . ] (in kfence-#156): test_kmalloc_aligned_oob_write+0xef/0x184 - kunit_try_run_case+0x51/0x85 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - kfence-#69 [0xffffffffb6797fb0-0xffffffffb6797ff8, size=73, cache=kmalloc-96] allocated by task 507: - test_alloc+0xf3/0x25b + kfence-#156: 0xffff8c3f2e33afb0-0xffff8c3f2e33aff8, size=73, cache=kmalloc-96 + + allocated by task 502 on cpu 7 at 42.159302s: + test_alloc+0xfe/0x738 test_kmalloc_aligned_oob_write+0x57/0x184 - kunit_try_run_case+0x51/0x85 + kunit_try_run_case+0x61/0xa0 kunit_generic_run_threadfn_adapter+0x16/0x30 - kthread+0x137/0x160 + kthread+0x176/0x1b0 ret_from_fork+0x22/0x30 - CPU: 4 PID: 120 Comm: kunit_try_catch Tainted: G W 5.8.0-rc6+ #7 - Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1 04/01/2014 + CPU: 7 PID: 502 Comm: kunit_try_catch Tainted: G B 5.13.0-rc3+ #7 + Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-2 04/01/2014 ================================================================== For such errors, the address where the corruption occurred as well as the
mm/kfence/core.c renamed from mm/kfence/core.c~kfence-show-cpu-and-timestamp-in-alloc-free-info +3 -0
@@ -20,6 +20,7 @@#include <linux/moduleparam.h> #include <linux/random.h> #include <linux/rcupdate.h> +#include <linux/sched/clock.h> #include <linux/sched/sysctl.h> #include <linux/seq_file.h> #include <linux/slab.h>
@@ -196,6 +197,8 @@ static noinline void metadata_update_sta*/ track->num_stack_entries =stack_trace_save (track->stack_entries,KFENCE_STACK_DEPTH ,1 ); track->pid =task_pid_nr (current); + track->cpu =raw_smp_processor_id (); + track->ts_nsec =local_clock ();/* Same source as printk timestamps. */ /* * Pairs with READ_ONCE() in
mm/kfence/kfence.h renamed from mm/kfence/kfence.h~kfence-show-cpu-and-timestamp-in-alloc-free-info +2 -0
@@ -36,6 +36,8 @@ enum kfence_object_state {/* Alloc/free tracking information. */ struct kfence_track {pid_t pid; +int cpu; +u64 ts_nsec;int num_stack_entries;unsigned long stack_entries[KFENCE_STACK_DEPTH ]; };
mm/kfence/report.c renamed from mm/kfence/report.c~kfence-show-cpu-and-timestamp-in-alloc-free-info +13 -6
@@ -9,6 +9,7 @@#include <linux/kernel.h> #include <linux/lockdep.h> +#include <linux/math.h> #include <linux/printk.h> #include <linux/sched/debug.h> #include <linux/seq_file.h>
@@ -100,6 +101,13 @@ static void kfence_print_stack(struct se bool show_alloc) {const struct kfence_track *track = show_alloc ? &meta->alloc_track : &meta->free_track; +u64 ts_sec = track->ts_nsec; +unsigned long rem_nsec =do_div (ts_sec,NSEC_PER_SEC ); + +/* Timestamp matches printk timestamp format. */ +seq_con_printf (seq,"%s by task %d on cpu %d at %lu.%06lus:\n" , + show_alloc ?"allocated" :"freed" , track->pid, + track->cpu, (unsigned long )ts_sec, rem_nsec /1000 );if (track->num_stack_entries) {/* Skip allocation/free internals stack. */
@@ -126,15 +134,14 @@ void kfence_print_object(struct seq_filereturn ; } -seq_con_printf (seq, -"kfence-#%td [0x%p-0x%p" -", size=%d, cache=%s] allocated by task %d:\n" , - meta - kfence_metadata, (void *)start, (void *)(start + size -1 ), size, - (cache && cache->name) ? cache->name :"<destroyed>" , meta->alloc_track.pid); +seq_con_printf (seq,"kfence-#%td: 0x%p-0x%p, size=%d, cache=%s\n\n" , + meta - kfence_metadata, (void *)start, (void *)(start + size -1 ), + size, (cache && cache->name) ? cache->name :"<destroyed>" ); +kfence_print_stack (seq, meta, true);if (meta->state ==KFENCE_OBJECT_FREED ) { -seq_con_printf (seq,"\nfreed by task %d:\n" , meta->free_track.pid); +seq_con_printf (seq,"\n" );kfence_print_stack (seq, meta, false); } }
_
Andrew Morton
maintainerPATCH 62/147 kfence: test: fail fast if disabled at boot
In reply to Andrew MortonFrom: Marco Elver <[email protected]>
Subject: kfence: test: fail fast if disabled at boot
Fail kfence_test fast if KFENCE was disabled at boot, instead of each test case trying several seconds to allocate from KFENCE and failing. KUnit will fail all test cases if kunit_suite::init returns an error.
Even if KFENCE was disabled, we still want the test to fail, so that CI systems that parse KUnit output will alert on KFENCE being disabled (accidentally or otherwise).
---
mm/kfence/kfence_test.c | 3 +++ 1 file changed, 3 insertions(+)
mm/kfence/kfence_test.c renamed from mm/kfence/kfence_test.c~kfence-test-fail-fast-if-disabled-at-boot +3 -0
@@ -789,6 +789,9 @@ static int test_init(struct kunit *test)unsigned long flags;int i; +if (!__kfence_pool) +return -EINVAL ; +spin_lock_irqsave (&observed.lock, flags);for (i =0 ; i <ARRAY_SIZE (observed.lines); i++) observed.lines[i][0 ] ='\0' ;
_
Andrew Morton
maintainerPATCH 63/147 mm: introduce Data Access MONitor (DAMON)
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm: introduce Data Access MONitor (DAMON)
Patch series "Introduce Data Access MONitor (DAMON)", v34.
Introduction
============
DAMON is a data access monitoring framework for the Linux kernel. The core mechanisms of DAMON called 'region based sampling' and 'adaptive regions adjustment' (refer to 'mechanisms.rst' in the 11th patch of this patchset for the detail) make it
- accurate (The monitored information is useful for DRAM level memory management. It might not appropriate for Cache-level accuracy, though.),
- light-weight (The monitoring overhead is low enough to be applied online while making no impact on the performance of the target workloads.), and
- scalable (the upper-bound of the instrumentation overhead is controllable regardless of the size of target workloads.).
Using this framework, therefore, several memory management mechanisms such as reclamation and THP can be optimized to aware real data access patterns. Experimental access pattern aware memory management optimization works that incurring high instrumentation overhead will be able to have another try.
Though DAMON is for kernel subsystems, it can be easily exposed to the user space by writing a DAMON-wrapper kernel subsystem. Then, user space users who have some special workloads will be able to write personalized tools or applications for deeper understanding and specialized optimizations of their systems.
DAMON is also merged in two public Amazon Linux kernel trees that based on v5.4.y[1] and v5.10.y[2].
[1] https://github.com/amazonlinux/linux/tree/amazon-5.4.y/master/mm/damon
[2] https://github.com/amazonlinux/linux/tree/amazon-5.10.y/master/mm/damon
The userspace tool[1] is available, released under GPLv2, and actively being maintained. I am also planning to implement another basic user interface in perf[2]. Also, the basic test suite for DAMON is available under GPLv2[3].
[1] https://github.com/awslabs/damo
[2] https://lore.kernel.org/linux-mm/[email protected]/
[3] https://github.com/awslabs/damon-tests
Long-term Plan
--------------
DAMON is a part of a project called Data Access-aware Operating System (DAOS). As the name implies, I want to improve the performance and efficiency of systems using fine-grained data access patterns. The optimizations are for both kernel and user spaces. I will therefore modify or create kernel subsystems, export some of those to user space and implement user space library / tools. Below shows the layers and components for the project.
---------------------------------------------------------------------------
Primitives: PTE Accessed bit, PG_idle, rmap, (Intel CMT), ...
Framework: DAMON
Features: DAMOS, virtual addr, physical addr, ...
Applications: DAMON-debugfs, (DARC), ...
^^^^^^^^^^^^^^^^^^^^^^^ KERNEL SPACE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Raw Interface: debugfs, (sysfs), (damonfs), tracepoints, (sys_damon), ...
vvvvvvvvvvvvvvvvvvvvvvv USER SPACE vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Library: (libdamon), ...
Tools: DAMO, (perf), ...
---------------------------------------------------------------------------
The components in parentheses or marked as '...' are not implemented yet but in the future plan. IOW, those are the TODO tasks of DAOS project. For more detail, please refer to the plans:
https://lore.kernel.org/linux-mm/[email protected]/
Evaluations
===========
We evaluated DAMON's overhead, monitoring quality and usefulness using 24 realistic workloads on my QEMU/KVM based virtual machine running a kernel that v24 DAMON patchset is applied.
DAMON is lightweight. It increases system memory usage by 0.39% and slows target workloads down by 1.16%.
DAMON is accurate and useful for memory management optimizations. An experimental DAMON-based operation scheme for THP, namely 'ethp', removes 76.15% of THP memory overheads while preserving 51.25% of THP speedup. Another experimental DAMON-based 'proactive reclamation' implementation, 'prcl', reduces 93.38% of residential sets and 23.63% of system memory footprint while incurring only 1.22% runtime overhead in the best case (parsec3/freqmine).
NOTE that the experimental THP optimization and proactive reclamation are not for production but only for proof of concepts.
Please refer to the official document[1] or "Documentation/admin-guide/mm:
Add a document for DAMON" patch in this patchset for detailed evaluation setup and results.
[1] https://damonitor.github.io/doc/html/latest-damon/admin-guide/mm/damon/eval.html
Real-world User Story
=====================
In summary, DAMON has used on production systems and proved its usefulness.
DAMON as a profiler
-------------------
We analyzed characteristics of a large scale production systems of our customers using DAMON. The systems utilize 70GB DRAM and 36 CPUs. From this, we were able to find interesting things below.
There were obviously different access pattern under idle workload and active workload. Under the idle workload, it accessed large memory regions with low frequency, while the active workload accessed small memory regions with high freuqnecy.
DAMON found a 7GB memory region that showing obviously high access frequency under the active workload. We believe this is the performance-effective working set and need to be protected.
There was a 4KB memory region that showing highest access frequency under not only active but also idle workloads. We think this must be a hottest code section like thing that should never be paged out.
For this analysis, DAMON used only 0.3-1% of single CPU time. Because we used recording-based analysis, it consumed about 3-12 MB of disk space per 20 minutes. This is only small amount of disk space, but we can further reduce the disk usage by using non-recording-based DAMON features. I'd like to argue that only DAMON can do such detailed analysis (finding 4KB highest region in 70GB memory) with the light overhead.
DAMON as a system optimization tool
-----------------------------------
We also found below potential performance problems on the systems and made DAMON-based solutions.
The system doesn't want to make the workload suffer from the page reclamation and thus it utilizes enough DRAM but no swap device. However, we found the system is actively reclaiming file-backed pages, because the system has intensive file IO. The file IO turned out to be not performance critical for the workload, but the customer wanted to ensure performance critical file-backed pages like code section to not mistakenly be evicted.
Using direct IO should or mlock() would be a straightforward solution, but modifying the user space code is not easy for the customer. Alternatively, we could use DAMON-based operation scheme[1]. By using it, we can ask DAMON to track access frequency of each region and make 'process_madvise(MADV_WILLNEED)[2]' call for regions having specific size and access frequency for a time interval.
We also found the system is having high number of TLB misses. We tried 'always' THP enabled policy and it greatly reduced TLB misses, but the page reclamation also been more frequent due to the THP internal fragmentation caused memory bloat. We could try another DAMON-based operation scheme that applies 'MADV_HUGEPAGE' to memory regions having
Quoted 1 line
=2MB size and high access frequency, while applying '
MADV_NOHUGEPAGE' to
regions having <2MB size and low access frequency.
We do not own the systems so we only reported the analysis results and possible optimization solutions to the customers. The customers satisfied about the analysis results and promised to try the optimization guides.
[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://lore.kernel.org/linux-api/[email protected]/
Comparison with Idle Page Tracking
==================================
Idle Page Tracking allows users to set and read idleness of pages using a bitmap file which represents each page with each bit of the file. One recommended usage of it is working set size detection. Users can do that by
1. find PFN of each page for workloads in interest,
2. set all the pages as idle by doing writes to the bitmap file,
3. wait until the workload accesses its working set, and
4. read the idleness of the pages again and count pages became not idle.
NOTE: While Idle Page Tracking is for user space users, DAMON is primarily designed for kernel subsystems though it can easily exposed to the user space. Hence, this section only assumes such user space use of DAMON.
For what use cases Idle Page Tracking would be better?
------------------------------------------------------
1. Flexible usecases other than hotness monitoring.
Because Idle Page Tracking allows users to control the primitive (Page idleness) by themselves, Idle Page Tracking users can do anything they want. Meanwhile, DAMON is primarily designed to monitor the hotness of each memory region. For this, DAMON asks users to provide sampling interval and aggregation interval. For the reason, there could be some use case that using Idle Page Tracking is simpler.
2. Physical memory monitoring.
Idle Page Tracking receives PFN range as input, so natively supports physical memory monitoring.
DAMON is designed to be extensible for multiple address spaces and use cases by implementing and using primitives for the given use case. Therefore, by theory, DAMON has no limitation in the type of target address space as long as primitives for the given address space exists. However, the default primitives introduced by this patchset supports only virtual address spaces.
Therefore, for physical memory monitoring, you should implement your own primitives and use it, or simply use Idle Page Tracking.
Nonetheless, RFC patchsets[1] for the physical memory address space primitives is already available. It also supports user memory same to Idle Page Tracking.
[1] https://lore.kernel.org/linux-mm/[email protected]/
For what use cases DAMON is better?
-----------------------------------
1. Hotness Monitoring.
Idle Page Tracking let users know only if a page frame is accessed or not. For hotness check, the user should write more code and use more memory. DAMON do that by itself.
2. Low Monitoring Overhead
DAMON receives user's monitoring request with one step and then provide the results. So, roughly speaking, DAMON require only O(1) user/kernel context switches.
In case of Idle Page Tracking, however, because the interface receives contiguous page frames, the number of user/kernel context switches increases as the monitoring target becomes complex and huge. As a result, the context switch overhead could be not negligible.
Moreover, DAMON is born to handle with the monitoring overhead. Because the core mechanism is pure logical, Idle Page Tracking users might be able to implement the mechanism on their own, but it would be time consuming and the user/kernel context switching will still more frequent than that of DAMON. Also, the kernel subsystems cannot use the logic in this case.
3. Page granularity working set size detection.
Until v22 of this patchset, this was categorized as the thing Idle Page Tracking could do better, because DAMON basically maintains additional metadata for each of the monitoring target regions. So, in the page granularity working set size detection use case, DAMON would incur (number of monitoring target pages * size of metadata) memory overhead. Size of the single metadata item is about 54 bytes, so assuming 4KB pages, about 1.3% of monitoring target pages will be additionally used.
All essential metadata for Idle Page Tracking are embedded in 'struct page' and page table entries. Therefore, in this use case, only one counter variable for working set size accounting is required if Idle Page Tracking is used.
There are more details to consider, but roughly speaking, this is true in most cases.
However, the situation changed from v23. Now DAMON supports arbitrary types of monitoring targets, which don't use the metadata. Using that, DAMON can do the working set size detection with no additional space overhead but less user-kernel context switch. A first draft for the implementation of monitoring primitives for this usage is available in a DAMON development tree[1]. An RFC patchset for it based on this patchset will also be available soon.
Since v24, the arbitrary type support is dropped from this patchset because this patchset doesn't introduce real use of the type. You can still get it from the DAMON development tree[2], though.
[1] https://github.com/sjp38/linux/tree/damon/pgidle_hack
[2] https://github.com/sjp38/linux/tree/damon/master
4. More future usecases
While Idle Page Tracking has tight coupling with base primitives (PG_Idle and page table Accessed bits), DAMON is designed to be extensible for many use cases and address spaces. If you need some special address type or want to use special h/w access check primitives, you can write your own primitives for that and configure DAMON to use those. Therefore, if your use case could be changed a lot in future, using DAMON could be better.
Can I use both Idle Page Tracking and DAMON?
--------------------------------------------
Yes, though using them concurrently for overlapping memory regions could result in interference to each other. Nevertheless, such use case would be rare or makes no sense at all. Even in the case, the noise would bot be really significant. So, you can choose whatever you want depending on the characteristics of your use cases.
More Information
================
We prepared a showcase web site[1] that you can get more information. There are
- the official documentations[2],
- the heatmap format dynamic access pattern of various realistic workloads for heap area[3], mmap()-ed area[4], and stack[5] area,
- the dynamic working set size distribution[6] and chronological working set size changes[7], and
- the latest performance test results[8].
[1] https://damonitor.github.io/_index
[2] https://damonitor.github.io/doc/html/latest-damon
[3] https://damonitor.github.io/test/result/visual/latest/rec.heatmap.0.png.html
[4] https://damonitor.github.io/test/result/visual/latest/rec.heatmap.1.png.html
[5] https://damonitor.github.io/test/result/visual/latest/rec.heatmap.2.png.html
[6] https://damonitor.github.io/test/result/visual/latest/rec.wss_sz.png.html
[7] https://damonitor.github.io/test/result/visual/latest/rec.wss_time.png.html
[8] https://damonitor.github.io/test/result/perf/latest/html/index.html
Baseline and Complete Git Trees
===============================
The patches are based on the latest -mm tree, specifically v5.14-rc1-mmots-2021-07-15-18-47 of https://github.com/hnaz/linux-mm. You can also clone the complete git tree:
$ git clone git://github.com/sjp38/linux -b damon/patches/v34
The web is also available:
https://github.com/sjp38/linux/releases/tag/damon/patches/v34
Development Trees
-----------------
There are a couple of trees for entire DAMON patchset series and features for future release.
- For latest release: https://github.com/sjp38/linux/tree/damon/master
- For next release: https://github.com/sjp38/linux/tree/damon/next
Long-term Support Trees
-----------------------
For people who want to test DAMON but using LTS kernels, there are another couple of trees based on two latest LTS kernels respectively and containing the 'damon/master' backports.
- For v5.4.y: https://github.com/sjp38/linux/tree/damon/for-v5.4.y
- For v5.10.y: https://github.com/sjp38/linux/tree/damon/for-v5.10.y
Amazon Linux Kernel Trees
-------------------------
DAMON is also merged in two public Amazon Linux kernel trees that based on v5.4.y[1] and v5.10.y[2].
[1] https://github.com/amazonlinux/linux/tree/amazon-5.4.y/master/mm/damon
[2] https://github.com/amazonlinux/linux/tree/amazon-5.10.y/master/mm/damon
Git Tree for Diff of Patches
============================
For easy review of diff between different versions of each patch, I prepared a git tree containing all versions of the DAMON patchset series:
https://github.com/sjp38/damon-patches
You can clone it and use 'diff' for easy review of changes between different versions of the patchset. For example:
$ git clone https://github.com/sjp38/damon-patches && cd damon-patches $ diff -u damon/v33 damon/v34
Sequence Of Patches
===================
First three patches implement the core logics of DAMON. The 1st patch introduces basic sampling based hotness monitoring for arbitrary types of targets. Following two patches implement the core mechanisms for control of overhead and accuracy, namely regions based sampling (patch 2) and adaptive regions adjustment (patch 3).
Now the essential parts of DAMON is complete, but it cannot work unless someone provides monitoring primitives for a specific use case. The following two patches make it just work for virtual address spaces monitoring. The 4th patch makes 'PG_idle' can be used by DAMON and the 5th patch implements the virtual memory address space specific monitoring primitives using page table Accessed bits and the 'PG_idle' page flag.
Now DAMON just works for virtual address space monitoring via the kernel space api. To let the user space users can use DAMON, following four patches add interfaces for them. The 6th patch adds a tracepoint for monitoring results. The 7th patch implements a DAMON application kernel module, namely damon-dbgfs, that simply wraps DAMON and exposes DAMON interface to the user space via the debugfs interface. The 8th patch further exports pid of monitoring thread (kdamond) to user space for easier cpu usage accounting, and the 9th patch makes the debugfs interface to support multiple contexts.
Three patches for maintainability follows. The 10th patch adds documentations for both the user space and the kernel space. The 11th patch provides unit tests (based on the kunit) while the 12th patch adds user space tests (based on the kselftest).
Finally, the last patch (13th) updates the MAINTAINERS file.
This patch (of 13):
DAMON is a data access monitoring framework for the Linux kernel. The core mechanisms of DAMON make it
- accurate (the monitoring output is useful enough for DRAM level performance-centric memory management; It might be inappropriate for CPU cache levels, though),
- light-weight (the monitoring overhead is normally low enough to be applied online), and
- scalable (the upper-bound of the overhead is in constant range regardless of the size of target workloads).
Using this framework, hence, we can easily write efficient kernel space data access monitoring applications. For example, the kernel's memory management mechanisms can make advanced decisions using this. Experimental data access aware optimization works that incurring high access monitoring overhead could again be implemented on top of this.
Due to its simple and flexible interface, providing user space interface would be also easy. Then, user space users who have some special workloads can write personalized applications for better understanding and optimizations of their workloads and systems.
===
Nevertheless, this commit is defining and implementing only basic access check part without the overhead-accuracy handling core logic. The basic access check is as below.
The output of DAMON says what memory regions are how frequently accessed for a given duration. The resolution of the access frequency is controlled by setting ``sampling interval`` and ``aggregation interval``. In detail, DAMON checks access to each page per ``sampling interval`` and aggregates the results. In other words, counts the number of the accesses to each region. After each ``aggregation interval`` passes, DAMON calls callback functions that previously registered by users so that users can read the aggregated results and then clears the results. This can be described in below simple pseudo-code::
init()
while monitoring_on:
for page in monitoring_target:
if accessed(page):
nr_accesses[page] += 1
if time() % aggregation_interval == 0:
for callback in user_registered_callbacks:
callback(monitoring_target, nr_accesses)
for page in monitoring_target:
nr_accesses[page] = 0
if time() % update_interval == 0:
update()
sleep(sampling interval)
The target regions constructed at the beginning of the monitoring and updated after each ``regions_update_interval``, because the target regions could be dynamically changed (e.g., mmap() or memory hotplug). The monitoring overhead of this mechanism will arbitrarily increase as the size of the target workload grows.
The basic monitoring primitives for actual access check and dynamic target regions construction aren't in the core part of DAMON. Instead, it allows users to implement their own primitives that are optimized for their use case and configure DAMON to use those. In other words, users cannot use current version of DAMON without some additional works.
Following commits will implement the core mechanisms for the overhead-accuracy control and default primitives implementations.
---
include/linux/damon.h | 167 ++++++++++++++++++++ mm/Kconfig | 2 mm/Makefile | 1 mm/damon/Kconfig | 15 + mm/damon/Makefile | 3 mm/damon/core.c | 320 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 508 insertions(+)
include/linux/damon.h new file +167 -0
@@ -0,0 +1,167 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* DAMON api +* +* Author: SeongJae Park <[email protected]> +*/ + +#ifndef _DAMON_H_ +#define _DAMON_H_ + +#include <linux/mutex.h> +#include <linux/time64.h> +#include <linux/types.h> + +struct damon_ctx ; + +/** +* struct damon_primitive Monitoring primitives for given use cases. +* +* @init: Initialize primitive-internal data structures. +* @update: Update primitive-internal data structures. +* @prepare_access_checks: Prepare next access check of target regions. +* @check_accesses: Check the accesses to target regions. +* @reset_aggregated: Reset aggregated accesses monitoring results. +* @target_valid: Determine if the target is valid. +* @cleanup: Clean up the context. +* +* DAMON can be extended for various address spaces and usages. For this, +* users should register the low level primitives for their target address +* space and usecase via the &damon_ctx.primitive. Then, the monitoring thread +* (&damon_ctx.kdamond) calls @init and @prepare_access_checks before starting +* the monitoring, @update after each &damon_ctx.primitive_update_interval, and +* @check_accesses, @target_valid and @prepare_access_checks after each +* &damon_ctx.sample_interval. Finally, @reset_aggregated is called after each +* &damon_ctx.aggr_interval. +* +* @init should initialize primitive-internal data structures. For example, +* this could be used to construct proper monitoring target regions and link +* those to @damon_ctx.target. +* @update should update the primitive-internal data structures. For example, +* this could be used to update monitoring target regions for current status. +* @prepare_access_checks should manipulate the monitoring regions to be +* prepared for the next access check. +* @check_accesses should check the accesses to each region that made after the +* last preparation and update the number of observed accesses of each region. +* @reset_aggregated should reset the access monitoring results that aggregated +* by @check_accesses. +* @target_valid should check whether the target is still valid for the +* monitoring. +* @cleanup is called from @kdamond just before its termination. +*/ +struct damon_primitive { +void (*init)(struct damon_ctx *context); +void (*update)(struct damon_ctx *context); +void (*prepare_access_checks)(struct damon_ctx *context); +void (*check_accesses)(struct damon_ctx *context); +void (*reset_aggregated)(struct damon_ctx *context); +bool (*target_valid)(void *target); +void (*cleanup)(struct damon_ctx *context); +}; + +/* +* struct damon_callback Monitoring events notification callbacks. +* +* @before_start: Called before starting the monitoring. +* @after_sampling: Called after each sampling. +* @after_aggregation: Called after each aggregation. +* @before_terminate: Called before terminating the monitoring. +* @private: User private data. +* +* The monitoring thread (&damon_ctx.kdamond) calls @before_start and +* @before_terminate just before starting and finishing the monitoring, +* respectively. Therefore, those are good places for installing and cleaning +* @private. +* +* The monitoring thread calls @after_sampling and @after_aggregation for each +* of the sampling intervals and aggregation intervals, respectively. +* Therefore, users can safely access the monitoring results without additional +* protection. For the reason, users are recommended to use these callback for +* the accesses to the results. +* +* If any callback returns non-zero, monitoring stops. +*/ +struct damon_callback { +void *private; + +int (*before_start)(struct damon_ctx *context); +int (*after_sampling)(struct damon_ctx *context); +int (*after_aggregation)(struct damon_ctx *context); +int (*before_terminate)(struct damon_ctx *context); +}; + +/** +* struct damon_ctx - Represents a context for each monitoring. This is the +* main interface that allows users to set the attributes and get the results +* of the monitoring. +* +* @sample_interval: The time between access samplings. +* @aggr_interval: The time between monitor results aggregations. +* @primitive_update_interval: The time between monitoring primitive updates. +* +* For each @sample_interval, DAMON checks whether each region is accessed or +* not. It aggregates and keeps the access information (number of accesses to +* each region) for @aggr_interval time. DAMON also checks whether the target +* memory regions need update (e.g., by ``mmap()`` calls from the application, +* in case of virtual memory monitoring) and applies the changes for each +* @primitive_update_interval. All time intervals are in micro-seconds. +* Please refer to &struct damon_primitive and &struct damon_callback for more +* detail. +* +* @kdamond: Kernel thread who does the monitoring. +* @kdamond_stop: Notifies whether kdamond should stop. +* @kdamond_lock: Mutex for the synchronizations with @kdamond. +* +* For each monitoring context, one kernel thread for the monitoring is +* created. The pointer to the thread is stored in @kdamond. +* +* Once started, the monitoring thread runs until explicitly required to be +* terminated or every monitoring target is invalid. The validity of the +* targets is checked via the &damon_primitive.target_valid of @primitive. The +* termination can also be explicitly requested by writing non-zero to +* @kdamond_stop. The thread sets @kdamond to NULL when it terminates. +* Therefore, users can know whether the monitoring is ongoing or terminated by +* reading @kdamond. Reads and writes to @kdamond and @kdamond_stop from +* outside of the monitoring thread must be protected by @kdamond_lock. +* +* Note that the monitoring thread protects only @kdamond and @kdamond_stop via +* @kdamond_lock. Accesses to other fields must be protected by themselves. +* +* @primitive: Set of monitoring primitives for given use cases. +* @callback: Set of callbacks for monitoring events notifications. +* +* @target: Pointer to the user-defined monitoring target. +*/ +struct damon_ctx { +unsigned long sample_interval; +unsigned long aggr_interval; +unsigned long primitive_update_interval; + +/* private: internal use only */ +struct timespec64 last_aggregation; +struct timespec64 last_primitive_update; + +/* public: */ +struct task_struct *kdamond; +bool kdamond_stop; +struct mutex kdamond_lock; + +struct damon_primitive primitive; +struct damon_callback callback; + +void *target; +}; + +#ifdef CONFIG_DAMON + +struct damon_ctx *damon_new_ctx (void ); +void damon_destroy_ctx (struct damon_ctx *ctx); +int damon_set_attrs (struct damon_ctx *ctx,unsigned long sample_int, +unsigned long aggr_int,unsigned long primitive_upd_int); + +int damon_start (struct damon_ctx **ctxs,int nr_ctxs); +int damon_stop (struct damon_ctx **ctxs,int nr_ctxs); + +#endif /* CONFIG_DAMON */ + +#endif /* _DAMON_H */
mm/damon/core.c new file +320 -0
320 lines not on this page · raw message
mm/damon/Kconfig new file +15 -0
@@ -0,0 +1,15 @@ +# SPDX-License-Identifier: GPL-2.0-only + +menu "Data Access Monitoring" + +config DAMON + bool "DAMON: Data Access Monitoring Framework" + help + This builds a framework that allows kernel subsystems to monitor + access frequency of each memory region. The information can be useful + for performance-centric DRAM level memory management. + + See https://damonitor.github.io/doc/html/latest-damon/index.html for + more information. + +endmenu
mm/damon/Makefile new file +3 -0
@@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-2.0 + +obj-$(CONFIG_DAMON) := core.o
mm/Kconfig renamed from mm/Kconfig~mm-introduce-data-access-monitor-damon +2 -0
@@ -886,4 +886,6 @@ config IO_MAPPING config SECRETMEM def_bool ARCH_HAS_SET_DIRECT_MAP && !EMBEDDED +source "mm/damon/Kconfig" + endmenu
mm/Makefile renamed from mm/Makefile~mm-introduce-data-access-monitor-damon +1 -0
@@ -118,6 +118,7 @@ obj-$(CONFIG_CMA_SYSFS) += cma_sysfs.o obj-$(CONFIG_USERFAULTFD) += userfaultfd.o obj-$(CONFIG_IDLE_PAGE_TRACKING) += page_idle.o obj-$(CONFIG_DEBUG_PAGE_REF) += debug_page_ref.o +obj-$(CONFIG_DAMON) += damon/ obj-$(CONFIG_HARDENED_USERCOPY) += usercopy.o obj-$(CONFIG_PERCPU_STATS) += percpu-stats.o obj-$(CONFIG_ZONE_DEVICE) += memremap.o
_
Andrew Morton
maintainerPATCH 64/147 mm/damon/core: implement region-based sampling
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon/core: implement region-based sampling
To avoid the unbounded increase of the overhead, DAMON groups adjacent pages that are assumed to have the same access frequencies into a region. As long as the assumption (pages in a region have the same access frequencies) is kept, only one page in the region is required to be checked. Thus, for each ``sampling interval``,
1. the 'prepare_access_checks' primitive picks one page in each region,
2. waits for one ``sampling interval``,
3. checks whether the page is accessed meanwhile, and
4. increases the access count of the region if so.
Therefore, the monitoring overhead is controllable by adjusting the number of regions. DAMON allows both the underlying primitives and user callbacks to adjust regions for the trade-off. In other words, this commit makes DAMON to use not only time-based sampling but also space-based sampling.
This scheme, however, cannot preserve the quality of the output if the assumption is not guaranteed. Next commit will address this problem.
---
include/linux/damon.h | 77 ++++++++++++++++++++- mm/damon/core.c | 143 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 213 insertions(+), 7 deletions(-)
include/linux/damon.h renamed from include/linux/damon.h~mm-damon-core-implement-region-based-sampling +74 -3
@@ -12,6 +12,48 @@#include <linux/time64.h> #include <linux/types.h> +/** +* struct damon_addr_range - Represents an address region of [@start, @end). +* @start: Start address of the region (inclusive). +* @end: End address of the region (exclusive). +*/ +struct damon_addr_range { +unsigned long start; +unsigned long end; +}; + +/** +* struct damon_region - Represents a monitoring target region. +* @ar: The address range of the region. +* @sampling_addr: Address of the sample for the next access check. +* @nr_accesses: Access frequency of this region. +* @list: List head for siblings. +*/ +struct damon_region { +struct damon_addr_range ar; +unsigned long sampling_addr; +unsigned int nr_accesses; +struct list_head list; +}; + +/** +* struct damon_target - Represents a monitoring target. +* @id: Unique identifier for this target. +* @regions_list: Head of the monitoring target regions of this target. +* @list: List head for siblings. +* +* Each monitoring context could have multiple targets. For example, a context +* for virtual memory address spaces could have multiple target processes. The +* @id of each target should be unique among the targets of the context. For +* example, in the virtual address monitoring context, it could be a pidfd or +* an address of an mm_struct. +*/ +struct damon_target { +unsigned long id; +struct list_head regions_list; +struct list_head list; +}; +struct damon_ctx ;/**
@@ -36,7 +78,7 @@ struct damon_ctx;* * @init should initialize primitive-internal data structures. For example, * this could be used to construct proper monitoring target regions and link -* those to @damon_ctx.target. +* those to @damon_ctx.adaptive_targets. * @update should update the primitive-internal data structures. For example, * this could be used to update monitoring target regions for current status. * @prepare_access_checks should manipulate the monitoring regions to be
@@ -130,7 +172,7 @@ struct damon_callback {* @primitive: Set of monitoring primitives for given use cases. * @callback: Set of callbacks for monitoring events notifications. * -* @target: Pointer to the user-defined monitoring target. +* @region_targets: Head of monitoring targets (&damon_target) list. */ struct damon_ctx {unsigned long sample_interval;
@@ -149,11 +191,40 @@ struct damon_ctx {struct damon_primitive primitive;struct damon_callback callback; -void *target; +struct list_head region_targets; }; +#define damon_next_region (r) \ + (container_of(r->list.next, struct damon_region, list)) + +#define damon_prev_region (r) \ + (container_of(r->list.prev, struct damon_region, list)) + +#define damon_for_each_region (r, t) \ + list_for_each_entry(r, &t->regions_list, list) + +#define damon_for_each_region_safe (r, next, t) \ + list_for_each_entry_safe(r, next, &t->regions_list, list) + +#define damon_for_each_target (t, ctx) \ + list_for_each_entry(t, &(ctx)->region_targets, list) + +#define damon_for_each_target_safe (t, next, ctx) \ + list_for_each_entry_safe(t, next, &(ctx)->region_targets, list) +#ifdef CONFIG_DAMON +struct damon_region *damon_new_region (unsigned long start,unsigned long end); +inline void damon_insert_region (struct damon_region *r, +struct damon_region *prev,struct damon_region *next); +void damon_add_region (struct damon_region *r,struct damon_target *t); +void damon_destroy_region (struct damon_region *r); + +struct damon_target *damon_new_target (unsigned long id); +void damon_add_target (struct damon_ctx *ctx,struct damon_target *t); +void damon_free_target (struct damon_target *t); +void damon_destroy_target (struct damon_target *t); +struct damon_ctx *damon_new_ctx (void );void damon_destroy_ctx (struct damon_ctx *ctx); int damon_set_attrs(struct damon_ctx *ctx, unsigned long sample_int,
mm/damon/core.c renamed from mm/damon/core.c~mm-damon-core-implement-region-based-sampling +139 -4
197 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 65/147 mm/damon: adaptively adjust regions
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon: adaptively adjust regions
Even somehow the initial monitoring target regions are well constructed to fulfill the assumption (pages in same region have similar access frequencies), the data access pattern can be dynamically changed. This will result in low monitoring quality. To keep the assumption as much as possible, DAMON adaptively merges and splits each region based on their access frequency.
For each ``aggregation interval``, it compares the access frequencies of adjacent regions and merges those if the frequency difference is small. Then, after it reports and clears the aggregated access frequency of each region, it splits each region into two or three regions if the total number of regions will not exceed the user-specified maximum number of regions after the split.
In this way, DAMON provides its best-effort quality and minimal overhead while keeping the upper-bound overhead that users set.
---
include/linux/damon.h | 30 +++-- mm/damon/core.c | 224 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 237 insertions(+), 17 deletions(-)
include/linux/damon.h renamed from include/linux/damon.h~mm-damon-adaptively-adjust-regions +22 -8
@@ -12,6 +12,9 @@#include <linux/time64.h> #include <linux/types.h> +/* Minimal region size. Every damon_region is aligned by this. */ +#define DAMON_MIN_REGION PAGE_SIZE +/** * struct damon_addr_range - Represents an address region of [@start, @end). * @start: Start address of the region (inclusive).
@@ -39,6 +42,7 @@ struct damon_region {/** * struct damon_target - Represents a monitoring target. * @id: Unique identifier for this target. +* @nr_regions: Number of monitoring target regions of this target. * @regions_list: Head of the monitoring target regions of this target. * @list: List head for siblings. *
@@ -50,6 +54,7 @@ struct damon_region {*/ struct damon_target {unsigned long id; +unsigned int nr_regions;struct list_head regions_list;struct list_head list; };
@@ -85,6 +90,8 @@ struct damon_ctx;* prepared for the next access check. * @check_accesses should check the accesses to each region that made after the * last preparation and update the number of observed accesses of each region. +* It should also return max number of observed accesses that made as a result +* of its update. The value will be used for regions adjustment threshold. * @reset_aggregated should reset the access monitoring results that aggregated * by @check_accesses. * @target_valid should check whether the target is still valid for the
@@ -95,7 +102,7 @@ struct damon_primitive {void (*init)(struct damon_ctx *context);void (*update)(struct damon_ctx *context);void (*prepare_access_checks)(struct damon_ctx *context); -void (*check_accesses)(struct damon_ctx *context); +unsigned int (*check_accesses)(struct damon_ctx *context);void (*reset_aggregated)(struct damon_ctx *context);bool (*target_valid)(void *target);void (*cleanup)(struct damon_ctx *context);
@@ -172,7 +179,9 @@ struct damon_callback {* @primitive: Set of monitoring primitives for given use cases. * @callback: Set of callbacks for monitoring events notifications. * -* @region_targets: Head of monitoring targets (&damon_target) list. +* @min_nr_regions: The minimum number of adaptive monitoring regions. +* @max_nr_regions: The maximum number of adaptive monitoring regions. +* @adaptive_targets: Head of monitoring targets (&damon_target) list. */ struct damon_ctx {unsigned long sample_interval;
@@ -191,7 +200,9 @@ struct damon_ctx {struct damon_primitive primitive;struct damon_callback callback; -struct list_head region_targets; +unsigned long min_nr_regions; +unsigned long max_nr_regions; +struct list_head adaptive_targets; };#define damon_next_region (r) \
@@ -207,28 +218,31 @@ struct damon_ctx { list_for_each_entry_safe(r, next, &t->regions_list, list)#define damon_for_each_target (t, ctx) \ - list_for_each_entry(t, &(ctx)->region_targets, list) + list_for_each_entry(t, &(ctx)->adaptive_targets, list)#define damon_for_each_target_safe (t, next, ctx) \ - list_for_each_entry_safe(t, next, &(ctx)->region_targets, list) + list_for_each_entry_safe(t, next, &(ctx)->adaptive_targets, list)#ifdef CONFIG_DAMON struct damon_region *damon_new_region (unsigned long start,unsigned long end);inline void damon_insert_region (struct damon_region *r, -struct damon_region *prev,struct damon_region *next); +struct damon_region *prev,struct damon_region *next, +struct damon_target *t);void damon_add_region (struct damon_region *r,struct damon_target *t); -void damon_destroy_region (struct damon_region *r); +void damon_destroy_region (struct damon_region *r,struct damon_target *t);struct damon_target *damon_new_target (unsigned long id);void damon_add_target (struct damon_ctx *ctx,struct damon_target *t);void damon_free_target (struct damon_target *t);void damon_destroy_target (struct damon_target *t); +unsigned int damon_nr_regions (struct damon_target *t);struct damon_ctx *damon_new_ctx (void );void damon_destroy_ctx (struct damon_ctx *ctx);int damon_set_attrs (struct damon_ctx *ctx,unsigned long sample_int, -unsigned long aggr_int,unsigned long primitive_upd_int); +unsigned long aggr_int,unsigned long primitive_upd_int, +unsigned long min_nr_reg,unsigned long max_nr_reg);int damon_start (struct damon_ctx **ctxs,int nr_ctxs);int damon_stop (struct damon_ctx **ctxs,int nr_ctxs);
mm/damon/core.c renamed from mm/damon/core.c~mm-damon-adaptively-adjust-regions +215 -9
340 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 66/147 mm/idle_page_tracking: make PG_idle reusable
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/idle_page_tracking: make PG_idle reusable
PG_idle and PG_young allow the two PTE Accessed bit users, Idle Page Tracking and the reclaim logic concurrently work while not interfering with each other. That is, when they need to clear the Accessed bit, they set PG_young to represent the previous state of the bit, respectively. And when they need to read the bit, if the bit is cleared, they further read the PG_young to know whether the other has cleared the bit meanwhile or not.
For yet another user of the PTE Accessed bit, we could add another page flag, or extend the mechanism to use the flags. For the DAMON usecase, however, we don't need to do that just yet. IDLE_PAGE_TRACKING and DAMON are mutually exclusive, so there's only ever going to be one user of the current set of flags.
In this commit, we split out the CONFIG options to allow for the use of PG_young and PG_idle outside of idle page tracking.
In the next commit, DAMON's reference implementation of the virtual memory address space monitoring primitives will use it.
---
include/linux/page-flags.h | 4 ++-- include/linux/page_ext.h | 2 +- include/linux/page_idle.h | 6 +++--- include/trace/events/mmflags.h | 2 +- mm/Kconfig | 10 +++++++++- mm/page_ext.c | 12 +++++++++++- mm/page_idle.c | 10 ---------- 7 files changed, 27 insertions(+), 19 deletions(-)
include/linux/page_ext.h renamed from include/linux/page_ext.h~mm-idle_page_tracking-make-pg_idle-reusable +1 -1
@@ -19,7 +19,7 @@ struct page_ext_operations {enum page_ext_flags {PAGE_EXT_OWNER ,PAGE_EXT_OWNER_ALLOCATED , -#if defined(CONFIG_IDLE_PAGE_TRACKING ) && !defined(CONFIG_64BIT ) +#if defined(CONFIG_PAGE_IDLE_FLAG ) && !defined(CONFIG_64BIT )PAGE_EXT_YOUNG ,PAGE_EXT_IDLE ,#endif
include/linux/page-flags.h renamed from include/linux/page-flags.h~mm-idle_page_tracking-make-pg_idle-reusable +2 -2
@@ -131,7 +131,7 @@ enum pageflags {#ifdef CONFIG_MEMORY_FAILURE PG_hwpoison, /* hardware poisoned page. Don't touch */#endif -#if defined(CONFIG_IDLE_PAGE_TRACKING ) && defined(CONFIG_64BIT ) +#if defined(CONFIG_PAGE_IDLE_FLAG ) && defined(CONFIG_64BIT ) PG_young, PG_idle,#endif
@@ -441,7 +441,7 @@ PAGEFLAG_FALSE(HWPoison)#define __PG_HWPOISON 0#endif -#if defined(CONFIG_IDLE_PAGE_TRACKING ) && defined(CONFIG_64BIT ) +#if defined(CONFIG_PAGE_IDLE_FLAG ) && defined(CONFIG_64BIT ) TESTPAGEFLAG(Young, young, PF_ANY) SETPAGEFLAG(Young, young, PF_ANY)TESTCLEARFLAG (Young, young,PF_ANY )
include/linux/page_idle.h renamed from include/linux/page_idle.h~mm-idle_page_tracking-make-pg_idle-reusable +3 -3
@@ -6,7 +6,7 @@#include <linux/page-flags.h> #include <linux/page_ext.h> -#ifdef CONFIG_IDLE_PAGE_TRACKING +#ifdef CONFIG_PAGE_IDLE_FLAG #ifdef CONFIG_64BIT static inline bool page_is_young (struct page *page)
@@ -106,7 +106,7 @@ static inline void clear_page_idle(struc }#endif /* CONFIG_64BIT */ -#else /* !CONFIG_IDLE_PAGE_TRACKING */ +#else /* !CONFIG_PAGE_IDLE_FLAG */ static inline bool page_is_young (struct page *page) {
@@ -135,6 +135,6 @@ static inline void clear_page_idle(struc { } -#endif /* CONFIG_IDLE_PAGE_TRACKING */ +#endif /* CONFIG_PAGE_IDLE_FLAG */ #endif /* _LINUX_MM_PAGE_IDLE_H */
include/trace/events/mmflags.h renamed from include/trace/events/mmflags.h~mm-idle_page_tracking-make-pg_idle-reusable +1 -1
@@ -75,7 +75,7 @@#define IF_HAVE_PG_HWPOISON (flag,string)#endif -#if defined(CONFIG_IDLE_PAGE_TRACKING ) && defined(CONFIG_64BIT ) +#if defined(CONFIG_PAGE_IDLE_FLAG ) && defined(CONFIG_64BIT )#define IF_HAVE_PG_IDLE (flag,string) ,{1UL << flag, string}#else #define IF_HAVE_PG_IDLE (flag,string)
mm/Kconfig renamed from mm/Kconfig~mm-idle_page_tracking-make-pg_idle-reusable +9 -1
@@ -739,10 +739,18 @@ config DEFERRED_STRUCT_PAGE_INIT lifetime of the system until these kthreads finish the initialisation. +config PAGE_IDLE_FLAG + bool + select PAGE_EXTENSION if !64BIT + help + This adds PG_idle and PG_young flags to 'struct page'. PTE Accessed + bit writers can set the state of the bit in the flags so that PTE + Accessed bit readers may avoid disturbance. + config IDLE_PAGE_TRACKING bool "Enable idle page tracking" depends on SYSFS && MMU - select PAGE_EXTENSION if !64BIT + select PAGE_IDLE_FLAG help This feature allows to estimate the amount of user pages that have not been touched during a given period of time. This information can
mm/page_ext.c renamed from mm/page_ext.c~mm-idle_page_tracking-make-pg_idle-reusable +11 -1
@@ -58,11 +58,21 @@* can utilize this callback to initialize the state of it correctly. */ +#if defined(CONFIG_PAGE_IDLE_FLAG ) && !defined(CONFIG_64BIT ) +static bool need_page_idle (void ) +{ +return true; +} +struct page_ext_operations page_idle_ops = { + .need = need_page_idle, +}; +#endif +static struct page_ext_operations *page_ext_ops[] = { #ifdef CONFIG_PAGE_OWNER &page_owner_ops, #endif -#if defined(CONFIG_IDLE_PAGE_TRACKING) && !defined(CONFIG_64BIT) +#if defined(CONFIG_PAGE_IDLE_FLAG) && !defined(CONFIG_64BIT) &page_idle_ops, #endif };
mm/page_idle.c renamed from mm/page_idle.c~mm-idle_page_tracking-make-pg_idle-reusable +0 -10
@@ -207,16 +207,6 @@ static const struct attribute_group page .name = "page_idle", }; -#ifndef CONFIG_64BIT -static bool need_page_idle (void ) -{ -return true; -} -struct page_ext_operations page_idle_ops = { - .need = need_page_idle, -}; -#endif -static int __init page_idle_init (void ) {int err;
_
Andrew Morton
maintainerPATCH 67/147 mm/damon: implement primitives for the virtual memory address spaces
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon: implement primitives for the virtual memory address spaces
This commit introduces a reference implementation of the address space specific low level primitives for the virtual address space, so that users of DAMON can easily monitor the data accesses on virtual address spaces of specific processes by simply configuring the implementation to be used by DAMON.
The low level primitives for the fundamental access monitoring are defined in two parts:
1. Identification of the monitoring target address range for the address space.
2. Access check of specific address range in the target space.
The reference implementation for the virtual address space does the works as below.
PTE Accessed-bit Based Access Check
-----------------------------------
The implementation uses PTE Accessed-bit for basic access checks. That is, it clears the bit for the next sampling target page and checks whether it is set again after one sampling period. This could disturb the reclaim logic. DAMON uses ``PG_idle`` and ``PG_young`` page flags to solve the conflict, as Idle page tracking does.
VMA-based Target Address Range Construction
-------------------------------------------
Only small parts in the super-huge virtual address space of the processes are mapped to physical memory and accessed. Thus, tracking the unmapped address regions is just wasteful. However, because DAMON can deal with some level of noise using the adaptive regions adjustment mechanism, tracking every mapping is not strictly required but could even incur a high overhead in some cases. That said, too huge unmapped areas inside the monitoring target should be removed to not take the time for the adaptive mechanism.
For the reason, this implementation converts the complex mappings to three distinct regions that cover every mapped area of the address space. Also, the two gaps between the three regions are the two biggest unmapped areas in the given address space. The two biggest unmapped areas would be the gap between the heap and the uppermost mmap()-ed region, and the gap between the lowermost mmap()-ed region and the stack in most of the cases. Because these gaps are exceptionally huge in usual address spaces, excluding these will be sufficient to make a reasonable trade-off. Below shows this in detail::
<heap>
<BIG UNMAPPED REGION 1>
<uppermost mmap()-ed region>
(small mmap()-ed regions and munmap()-ed regions) <lowermost mmap()-ed region>
<BIG UNMAPPED REGION 2>
<stack>
---
include/linux/damon.h | 13 mm/damon/Kconfig | 8 mm/damon/Makefile | 1 mm/damon/vaddr.c | 665 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 687 insertions(+)
include/linux/damon.h renamed from include/linux/damon.h~mm-damon-implement-primitives-for-the-virtual-memory-address-spaces +13 -0
@@ -249,4 +249,17 @@ int damon_stop(struct damon_ctx **ctxs,#endif /* CONFIG_DAMON */ +#ifdef CONFIG_DAMON_VADDR + +/* Monitoring primitives for virtual memory address spaces */ +void damon_va_init (struct damon_ctx *ctx); +void damon_va_update (struct damon_ctx *ctx); +void damon_va_prepare_access_checks (struct damon_ctx *ctx); +unsigned int damon_va_check_accesses (struct damon_ctx *ctx); +bool damon_va_target_valid (void *t); +void damon_va_cleanup (struct damon_ctx *ctx); +void damon_va_set_primitives (struct damon_ctx *ctx); + +#endif /* CONFIG_DAMON_VADDR */ +#endif /* _DAMON_H */
mm/damon/Kconfig renamed from mm/damon/Kconfig~mm-damon-implement-primitives-for-the-virtual-memory-address-spaces +8 -0
@@ -12,4 +12,12 @@ config DAMON See https://damonitor.github.io/doc/html/latest-damon/index.html for more information. +config DAMON_VADDR + bool "Data access monitoring primitives for virtual address spaces" + depends on DAMON && MMU + select PAGE_IDLE_FLAG + help + This builds the default data access monitoring primitives for DAMON + that works for virtual address spaces. + endmenu
mm/damon/Makefile renamed from mm/damon/Makefile~mm-damon-implement-primitives-for-the-virtual-memory-address-spaces +1 -0
@@ -1,3 +1,4 @@ # SPDX-License-Identifier: GPL-2.0 obj-$(CONFIG_DAMON) := core.o +obj-$(CONFIG_DAMON_VADDR) += vaddr.o
mm/damon/vaddr.c new file +665 -0
665 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 68/147 mm/damon: add a tracepoint
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon: add a tracepoint
This commit adds a tracepoint for DAMON. It traces the monitoring results of each region for each aggregation interval. Using this, DAMON can easily integrated with tracepoints supporting tools such as perf.
---
include/trace/events/damon.h | 43 +++++++++++++++++++++++++++++++++ mm/damon/core.c | 7 ++++- 2 files changed, 49 insertions(+), 1 deletion(-)
include/trace/events/damon.h new file +43 -0
@@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#undef TRACE_SYSTEM +#define TRACE_SYSTEM damon + +#if !defined(_TRACE_DAMON_H) || defined(TRACE_HEADER_MULTI_READ ) +#define _TRACE_DAMON_H + +#include <linux/damon.h> +#include <linux/types.h> +#include <linux/tracepoint.h> + +TRACE_EVENT (damon_aggregated, + + TP_PROTO(struct damon_target *t, struct damon_region *r, + unsigned int nr_regions), + +TP_ARGS (t, r, nr_regions), + +TP_STRUCT__entry ( + __field(unsigned long, target_id) + __field(unsigned int, nr_regions) + __field(unsigned long, start) + __field(unsigned long, end) + __field(unsigned int, nr_accesses) + ), + +TP_fast_assign ( + __entry->target_id = t->id; + __entry->nr_regions = nr_regions; + __entry->start = r->ar.start; + __entry->end = r->ar.end; + __entry->nr_accesses = r->nr_accesses; + ), + +TP_printk ("target_id=%lu nr_regions=%u %lu-%lu: %u" , + __entry->target_id, __entry->nr_regions, + __entry->start, __entry->end, __entry->nr_accesses) +); + +#endif /* _TRACE_DAMON_H */ + +/* This part must be outside protection */ +#include <trace/define_trace.h>
mm/damon/core.c renamed from mm/damon/core.c~mm-damon-add-a-tracepoint +6 -1
@@ -13,6 +13,9 @@#include <linux/random.h> #include <linux/slab.h> +#define CREATE_TRACE_POINTS +#include <trace/events/damon.h> +/* Get a random number in [l, r) */ #define damon_rand (l, r) (l + prandom_u32_max(r - l))
@@ -387,8 +390,10 @@ static void kdamond_reset_aggregated(strdamon_for_each_target (t, c) {struct damon_region *r; -damon_for_each_region (r, t) +damon_for_each_region (r, t) { +trace_damon_aggregated (t, r,damon_nr_regions (t)); r->nr_accesses =0 ; + } } }
_
Andrew Morton
maintainerPATCH 69/147 mm/damon: implement a debugfs-based user space interface
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon: implement a debugfs-based user space interface
DAMON is designed to be used by kernel space code such as the memory management subsystems, and therefore it provides only kernel space API. That said, letting the user space control DAMON could provide some benefits to them. For example, it will allow user space to analyze their specific workloads and make their own special optimizations.
For such cases, this commit implements a simple DAMON application kernel module, namely 'damon-dbgfs', which merely wraps the DAMON api and exports those to the user space via the debugfs.
'damon-dbgfs' exports three files, ``attrs``, ``target_ids``, and ``monitor_on`` under its debugfs directory, ``<debugfs>/damon/``.
Attributes
----------
Users can read and write the ``sampling interval``, ``aggregation interval``, ``regions update interval``, and min/max number of monitoring target regions by reading from and writing to the ``attrs`` file. For example, below commands set those values to 5 ms, 100 ms, 1,000 ms, 10, 1000 and check it again::
# cd <debugfs>/damon
# echo 5000 100000 1000000 10 1000 > attrs
# cat attrs
5000 100000 1000000 10 1000Target IDs
----------
Some types of address spaces supports multiple monitoring target. For example, the virtual memory address spaces monitoring can have multiple processes as the monitoring targets. Users can set the targets by writing relevant id values of the targets to, and get the ids of the current targets by reading from the ``target_ids`` file. In case of the virtual address spaces monitoring, the values should be pids of the monitoring target processes. For example, below commands set processes having pids 42 and 4242 as the monitoring targets and check it again::
# cd <debugfs>/damon
# echo 42 4242 > target_ids
# cat target_ids
42 4242Note that setting the target ids doesn't start the monitoring.
Turning On/Off
--------------
Setting the files as described above doesn't incur effect unless you explicitly start the monitoring. You can start, stop, and check the current status of the monitoring by writing to and reading from the ``monitor_on`` file. Writing ``on`` to the file starts the monitoring of the targets with the attributes. Writing ``off`` to the file stops those. DAMON also stops if every targets are invalidated (in case of the virtual memory monitoring, target processes are invalidated when terminated). Below example commands turn on, off, and check the status of DAMON::
# cd <debugfs>/damon
# echo on > monitor_on
# echo off > monitor_on
# cat monitor_on
offPlease note that you cannot write to the above-mentioned debugfs files while the monitoring is turned on. If you write to the files while DAMON is running, an error code such as ``-EBUSY`` will be returned.
---
include/linux/damon.h | 3 mm/damon/Kconfig | 9 mm/damon/Makefile | 1 mm/damon/core.c | 47 ++++ mm/damon/dbgfs.c | 397 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 457 insertions(+)
include/linux/damon.h renamed from include/linux/damon.h~mm-damon-implement-a-debugfs-based-user-space-interface +3 -0
@@ -240,9 +240,12 @@ unsigned int damon_nr_regions(struct damstruct damon_ctx *damon_new_ctx (void );void damon_destroy_ctx (struct damon_ctx *ctx); +int damon_set_targets (struct damon_ctx *ctx, +unsigned long *ids,ssize_t nr_ids);int damon_set_attrs (struct damon_ctx *ctx,unsigned long sample_int,unsigned long aggr_int,unsigned long primitive_upd_int,unsigned long min_nr_reg,unsigned long max_nr_reg); +int damon_nr_running_ctxs (void );int damon_start (struct damon_ctx **ctxs,int nr_ctxs);int damon_stop (struct damon_ctx **ctxs,int nr_ctxs);
mm/damon/core.c renamed from mm/damon/core.c~mm-damon-implement-a-debugfs-based-user-space-interface +47 -0
59 lines not on this page · raw message
mm/damon/dbgfs.c new file +397 -0
397 lines not on this page · raw message
mm/damon/Kconfig renamed from mm/damon/Kconfig~mm-damon-implement-a-debugfs-based-user-space-interface +9 -0
@@ -20,4 +20,13 @@ config DAMON_VADDR This builds the default data access monitoring primitives for DAMON that works for virtual address spaces. +config DAMON_DBGFS + bool "DAMON debugfs interface" + depends on DAMON_VADDR && DEBUG_FS + help + This builds the debugfs interface for DAMON. The user space admins + can use the interface for arbitrary data access monitoring. + + If unsure, say N. + endmenu
mm/damon/Makefile renamed from mm/damon/Makefile~mm-damon-implement-a-debugfs-based-user-space-interface +1 -0
@@ -2,3 +2,4 @@ obj-$(CONFIG_DAMON) := core.o obj-$(CONFIG_DAMON_VADDR) += vaddr.o +obj-$(CONFIG_DAMON_DBGFS) += dbgfs.o
_
Andrew Morton
maintainerPATCH 70/147 mm/damon/dbgfs: export kdamond pid to the user space
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon/dbgfs: export kdamond pid to the user space
For CPU usage accounting, knowing pid of the monitoring thread could be helpful. For example, users could use cpuaccount cgroups with the pid.
This commit therefore exports the pid of currently running monitoring thread to the user space via 'kdamond_pid' file in the debugfs directory.
---
mm/damon/dbgfs.c | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-)
mm/damon/dbgfs.c renamed from mm/damon/dbgfs.c~mm-damon-dbgfs-export-kdamond-pid-to-the-user-space +35 -2
@@ -239,6 +239,32 @@ out:return ret; } +static ssize_t dbgfs_kdamond_pid_read (struct file *file, +char __user *buf,size_t count,loff_t *ppos) +{ +struct damon_ctx *ctx = file->private_data; +char *kbuf; +ssize_t len; + + kbuf =kmalloc (count,GFP_KERNEL ); +if (!kbuf) +return -ENOMEM ; + +mutex_lock (&ctx->kdamond_lock); +if (ctx->kdamond) + len =scnprintf (kbuf, count,"%d\n" , ctx->kdamond->pid); +else + len =scnprintf (kbuf, count,"none\n" ); +mutex_unlock (&ctx->kdamond_lock); +if (!len) + goto out; + len =simple_read_from_buffer (buf, count, ppos, kbuf, len); + +out: +kfree (kbuf); +return len; +} +static int damon_dbgfs_open (struct inode *inode,struct file *file) { file->private_data = inode->i_private;
@@ -258,10 +284,17 @@ static const struct file_operations targ .write = dbgfs_target_ids_write, }; +static const struct file_operations kdamond_pid_fops = { + .open = damon_dbgfs_open, + .read = dbgfs_kdamond_pid_read, +}; +static void dbgfs_fill_ctx_dir (struct dentry *dir,struct damon_ctx *ctx) { -const char *const file_names[] = {"attrs" ,"target_ids" }; -const struct file_operations *fops[] = {&attrs_fops, &target_ids_fops}; +const char *const file_names[] = {"attrs" ,"target_ids" , +"kdamond_pid" }; +const struct file_operations *fops[] = {&attrs_fops, &target_ids_fops, + &kdamond_pid_fops};int i;for (i =0 ; i <ARRAY_SIZE (file_names); i++)
_
Andrew Morton
maintainerPATCH 71/147 mm/damon/dbgfs: support multiple contexts
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon/dbgfs: support multiple contexts
In some use cases, users would want to run multiple monitoring context. For example, if a user wants a high precision monitoring and dedicating multiple CPUs for the job is ok, because DAMON creates one monitoring thread per one context, the user can split the monitoring target regions into multiple small regions and create one context for each region. Or, someone might want to simultaneously monitor different address spaces, e.g., both virtual address space and physical address space.
The DAMON's API allows such usage, but 'damon-dbgfs' does not. Therefore, only kernel space DAMON users can do multiple contexts monitoring.
This commit allows the user space DAMON users to use multiple contexts monitoring by introducing two new 'damon-dbgfs' debugfs files, 'mk_context' and 'rm_context'. Users can create a new monitoring context by writing the desired name of the new context to 'mk_context'. Then, a new directory with the name and having the files for setting of the context ('attrs', 'target_ids' and 'record') will be created under the debugfs directory. Writing the name of the context to remove to 'rm_context' will remove the related context and directory.
---
mm/damon/dbgfs.c | 195 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 193 insertions(+), 2 deletions(-)
mm/damon/dbgfs.c renamed from mm/damon/dbgfs.c~mm-damon-dbgfs-support-multiple-contexts +193 -2
@@ -18,6 +18,7 @@static struct damon_ctx **dbgfs_ctxs;static int dbgfs_nr_ctxs;static struct dentry **dbgfs_dirs; +static DEFINE_MUTEX (damon_dbgfs_lock);/* * Returns non-empty string on success, negative error code otherwise.
@@ -328,6 +329,186 @@ static struct damon_ctx *dbgfs_new_ctx(vreturn ctx; } +static void dbgfs_destroy_ctx (struct damon_ctx *ctx) +{ +damon_destroy_ctx (ctx); +} + +/* +* Make a context of @name and create a debugfs directory for it. +* +* This function should be called while holding damon_dbgfs_lock. +* +* Returns 0 on success, negative error code otherwise. +*/ +static int dbgfs_mk_context (char *name) +{ +struct dentry *root, **new_dirs, *new_dir; +struct damon_ctx **new_ctxs, *new_ctx; + +if (damon_nr_running_ctxs ()) +return -EBUSY ; + + new_ctxs =krealloc (dbgfs_ctxs,sizeof (*dbgfs_ctxs) * + (dbgfs_nr_ctxs +1 ),GFP_KERNEL ); +if (!new_ctxs) +return -ENOMEM ; + dbgfs_ctxs = new_ctxs; + + new_dirs =krealloc (dbgfs_dirs,sizeof (*dbgfs_dirs) * + (dbgfs_nr_ctxs +1 ),GFP_KERNEL ); +if (!new_dirs) +return -ENOMEM ; + dbgfs_dirs = new_dirs; + + root = dbgfs_dirs[0 ]; +if (!root) +return -ENOENT ; + + new_dir =debugfs_create_dir (name, root); + dbgfs_dirs[dbgfs_nr_ctxs] = new_dir; + + new_ctx =dbgfs_new_ctx (); +if (!new_ctx) { +debugfs_remove (new_dir); + dbgfs_dirs[dbgfs_nr_ctxs] =NULL ; +return -ENOMEM ; + } + + dbgfs_ctxs[dbgfs_nr_ctxs] = new_ctx; +dbgfs_fill_ctx_dir (dbgfs_dirs[dbgfs_nr_ctxs], + dbgfs_ctxs[dbgfs_nr_ctxs]); + dbgfs_nr_ctxs++; + +return 0 ; +} + +static ssize_t dbgfs_mk_context_write (struct file *file, +const char __user *buf,size_t count,loff_t *ppos) +{ +char *kbuf; +char *ctx_name; +ssize_t ret = count; +int err; + + kbuf =user_input_str (buf, count, ppos); +if (IS_ERR (kbuf)) +return PTR_ERR (kbuf); + ctx_name =kmalloc (count +1 ,GFP_KERNEL ); +if (!ctx_name) { +kfree (kbuf); +return -ENOMEM ; + } + +/* Trim white space */ +if (sscanf (kbuf,"%s" , ctx_name) !=1 ) { + ret = -EINVAL ; + goto out; + } + +mutex_lock (&damon_dbgfs_lock); + err =dbgfs_mk_context (ctx_name); +if (err) + ret = err; +mutex_unlock (&damon_dbgfs_lock); + +out: +kfree (kbuf); +kfree (ctx_name); +return ret; +} + +/* +* Remove a context of @name and its debugfs directory. +* +* This function should be called while holding damon_dbgfs_lock. +* +* Return 0 on success, negative error code otherwise. +*/ +static int dbgfs_rm_context (char *name) +{ +struct dentry *root, *dir, **new_dirs; +struct damon_ctx **new_ctxs; +int i, j; + +if (damon_nr_running_ctxs ()) +return -EBUSY ; + + root = dbgfs_dirs[0 ]; +if (!root) +return -ENOENT ; + + dir =debugfs_lookup (name, root); +if (!dir) +return -ENOENT ; + + new_dirs =kmalloc_array (dbgfs_nr_ctxs -1 ,sizeof (*dbgfs_dirs), +GFP_KERNEL ); +if (!new_dirs) +return -ENOMEM ; + + new_ctxs =kmalloc_array (dbgfs_nr_ctxs -1 ,sizeof (*dbgfs_ctxs), +GFP_KERNEL ); +if (!new_ctxs) { +kfree (new_dirs); +return -ENOMEM ; + } + +for (i =0 , j =0 ; i < dbgfs_nr_ctxs; i++) { +if (dbgfs_dirs[i] == dir) { +debugfs_remove (dbgfs_dirs[i]); +dbgfs_destroy_ctx (dbgfs_ctxs[i]); +continue ; + } + new_dirs[j] = dbgfs_dirs[i]; + new_ctxs[j++] = dbgfs_ctxs[i]; + } + +kfree (dbgfs_dirs); +kfree (dbgfs_ctxs); + + dbgfs_dirs = new_dirs; + dbgfs_ctxs = new_ctxs; + dbgfs_nr_ctxs--; + +return 0 ; +} + +static ssize_t dbgfs_rm_context_write (struct file *file, +const char __user *buf,size_t count,loff_t *ppos) +{ +char *kbuf; +ssize_t ret = count; +int err; +char *ctx_name; + + kbuf =user_input_str (buf, count, ppos); +if (IS_ERR (kbuf)) +return PTR_ERR (kbuf); + ctx_name =kmalloc (count +1 ,GFP_KERNEL ); +if (!ctx_name) { +kfree (kbuf); +return -ENOMEM ; + } + +/* Trim white space */ +if (sscanf (kbuf,"%s" , ctx_name) !=1 ) { + ret = -EINVAL ; + goto out; + } + +mutex_lock (&damon_dbgfs_lock); + err =dbgfs_rm_context (ctx_name); +if (err) + ret = err; +mutex_unlock (&damon_dbgfs_lock); + +out: +kfree (kbuf); +kfree (ctx_name); +return ret; +} +static ssize_t dbgfs_monitor_on_read (struct file *file,char __user *buf,size_t count,loff_t *ppos) {
@@ -370,6 +551,14 @@ static ssize_t dbgfs_monitor_on_write(streturn ret; } +static const struct file_operations mk_contexts_fops = { + .write = dbgfs_mk_context_write, +}; + +static const struct file_operations rm_contexts_fops = { + .write = dbgfs_rm_context_write, +}; +static const struct file_operations monitor_on_fops = { .read = dbgfs_monitor_on_read, .write = dbgfs_monitor_on_write,
@@ -378,8 +567,10 @@ static const struct file_operations monistatic int __init __damon_dbgfs_init (void ) {struct dentry *dbgfs_root; -const char *const file_names[] = {"monitor_on" }; -const struct file_operations *fops[] = {&monitor_on_fops}; +const char *const file_names[] = {"mk_contexts" ,"rm_contexts" , +"monitor_on" }; +const struct file_operations *fops[] = {&mk_contexts_fops, + &rm_contexts_fops, &monitor_on_fops};int i; dbgfs_root =debugfs_create_dir ("damon" ,NULL );
_
Andrew Morton
maintainerPATCH 72/147 Documentation: add documents for DAMON
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: Documentation: add documents for DAMON
This commit adds documents for DAMON under Documentation/admin-guide/mm/damon/ and Documentation/vm/damon/.
---
Documentation/admin-guide/mm/damon/index.rst | 15 + Documentation/admin-guide/mm/damon/start.rst | 114 +++++++++++ Documentation/admin-guide/mm/damon/usage.rst | 112 +++++++++++ Documentation/admin-guide/mm/index.rst | 1 Documentation/vm/damon/api.rst | 20 ++ Documentation/vm/damon/design.rst | 166 +++++++++++++++++ Documentation/vm/damon/faq.rst | 51 +++++ Documentation/vm/damon/index.rst | 30 +++ Documentation/vm/index.rst | 1 9 files changed, 510 insertions(+)
Documentation/admin-guide/mm/damon/index.rst new file +15 -0
@@ -0,0 +1,15 @@ +.. SPDX-License-Identifier: GPL-2.0 + +======================== +Monitoring Data Accesses +======================== + +:doc:`DAMON </vm/damon/index>` allows light-weight data access monitoring. +Using DAMON, users can analyze the memory access patterns of their systems and +optimize those. + +.. toctree:: + :maxdepth: 2 + + start + usage
Documentation/admin-guide/mm/damon/start.rst new file +114 -0
114 lines not on this page · raw message
Documentation/admin-guide/mm/damon/usage.rst new file +112 -0
112 lines not on this page · raw message
Documentation/admin-guide/mm/index.rst renamed from Documentation/admin-guide/mm/index.rst~documentation-add-documents-for-damon +1 -0
@@ -27,6 +27,7 @@ the Linux memory management. concepts cma_debugfs + damon/index hugetlbpage idle_page_tracking ksm
Documentation/vm/damon/api.rst new file +20 -0
@@ -0,0 +1,20 @@ +.. SPDX-License-Identifier: GPL-2.0 + +============= +API Reference +============= + +Kernel space programs can use every feature of DAMON using below APIs. All you +need to do is including ``damon.h``, which is located in ``include/linux/`` of +the source tree. + +Structures +========== + +.. kernel-doc:: include/linux/damon.h + + +Functions +========= + +.. kernel-doc:: mm/damon/core.c
Documentation/vm/damon/design.rst new file +166 -0
166 lines not on this page · raw message
Documentation/vm/damon/faq.rst new file +51 -0
51 lines not on this page · raw message
Documentation/vm/damon/index.rst new file +30 -0
@@ -0,0 +1,30 @@ +.. SPDX-License-Identifier: GPL-2.0 + +========================== +DAMON: Data Access MONitor +========================== + +DAMON is a data access monitoring framework subsystem for the Linux kernel. +The core mechanisms of DAMON (refer to :doc:`design` for the detail) make it + + - *accurate* (the monitoring output is useful enough for DRAM level memory + management; It might not appropriate for CPU Cache levels, though), + - *light-weight* (the monitoring overhead is low enough to be applied online), + and + - *scalable* (the upper-bound of the overhead is in constant range regardless + of the size of target workloads). + +Using this framework, therefore, the kernel's memory management mechanisms can +make advanced decisions. Experimental memory management optimization works +that incurring high data accesses monitoring overhead could implemented again. +In user space, meanwhile, users who have some special workloads can write +personalized applications for better understanding and optimizations of their +workloads and systems. + +.. toctree:: + :maxdepth: 2 + + faq + design + api + plans
Documentation/vm/index.rst renamed from Documentation/vm/index.rst~documentation-add-documents-for-damon +1 -0
@@ -32,6 +32,7 @@ descriptions of data structures and algo arch_pgtable_helpers balance cleancache + damon/index free_page_reporting frontswap highmem
_
Andrew Morton
maintainerPATCH 73/147 mm/damon: add kunit tests
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon: add kunit tests
This commit adds kunit based unit tests for the core and the virtual address spaces monitoring primitives of DAMON.
---
mm/damon/Kconfig | 36 ++++ mm/damon/core-test.h | 253 ++++++++++++++++++++++++++++++ mm/damon/core.c | 7 mm/damon/dbgfs-test.h | 126 +++++++++++++++ mm/damon/dbgfs.c | 2 mm/damon/vaddr-test.h | 329 ++++++++++++++++++++++++++++++++++++++++ mm/damon/vaddr.c | 7 7 files changed, 760 insertions(+)
mm/damon/core.c renamed from mm/damon/core.c~mm-damon-add-kunit-tests +7 -0
@@ -16,6 +16,11 @@#define CREATE_TRACE_POINTS #include <trace/events/damon.h> +#ifdef CONFIG_DAMON_KUNIT_TEST +#undef DAMON_MIN_REGION +#define DAMON_MIN_REGION 1 +#endif +/* Get a random number in [l, r) */ #define damon_rand (l, r) (l + prandom_u32_max(r - l))
@@ -711,3 +716,5 @@ static int kdamond_fn(void *data)do_exit (0 ); } + +#include "core-test.h"
mm/damon/core-test.h new file +253 -0
253 lines not on this page · raw message
mm/damon/dbgfs.c renamed from mm/damon/dbgfs.c~mm-damon-add-kunit-tests +2 -0
@@ -619,3 +619,5 @@ static int __init damon_dbgfs_init(void) }module_init (damon_dbgfs_init); + +#include "dbgfs-test.h"
mm/damon/dbgfs-test.h new file +126 -0
126 lines not on this page · raw message
mm/damon/Kconfig renamed from mm/damon/Kconfig~mm-damon-add-kunit-tests +36 -0
@@ -12,6 +12,18 @@ config DAMON See https://damonitor.github.io/doc/html/latest-damon/index.html for more information. +config DAMON_KUNIT_TEST + bool "Test for damon" if !KUNIT_ALL_TESTS + depends on DAMON && KUNIT=y + default KUNIT_ALL_TESTS + help + This builds the DAMON Kunit test suite. + + For more information on KUnit and unit tests in general, please refer + to the KUnit documentation. + + If unsure, say N. + config DAMON_VADDR bool "Data access monitoring primitives for virtual address spaces" depends on DAMON && MMU
@@ -20,6 +32,18 @@ config DAMON_VADDR This builds the default data access monitoring primitives for DAMON that works for virtual address spaces. +config DAMON_VADDR_KUNIT_TEST + bool "Test for DAMON primitives" if !KUNIT_ALL_TESTS + depends on DAMON_VADDR && KUNIT=y + default KUNIT_ALL_TESTS + help + This builds the DAMON virtual addresses primitives Kunit test suite. + + For more information on KUnit and unit tests in general, please refer + to the KUnit documentation. + + If unsure, say N. + config DAMON_DBGFS bool "DAMON debugfs interface" depends on DAMON_VADDR && DEBUG_FS
@@ -29,4 +53,16 @@ config DAMON_DBGFS If unsure, say N. +config DAMON_DBGFS_KUNIT_TEST + bool "Test for damon debugfs interface" if !KUNIT_ALL_TESTS + depends on DAMON_DBGFS && KUNIT=y + default KUNIT_ALL_TESTS + help + This builds the DAMON debugfs interface Kunit test suite. + + For more information on KUnit and unit tests in general, please refer + to the KUnit documentation. + + If unsure, say N. + endmenu
mm/damon/vaddr.c renamed from mm/damon/vaddr.c~mm-damon-add-kunit-tests +7 -0
@@ -18,6 +18,11 @@#include <linux/sched/mm.h> #include <linux/slab.h> +#ifdef CONFIG_DAMON_VADDR_KUNIT_TEST +#undef DAMON_MIN_REGION +#define DAMON_MIN_REGION 1 +#endif +/* Get a random number in [l, r) */ #define damon_rand (l, r) (l + prandom_u32_max(r - l))
@@ -663,3 +668,5 @@ void damon_va_set_primitives(struct damo ctx->primitive.target_valid = damon_va_target_valid; ctx->primitive.cleanup =NULL ; } + +#include "vaddr-test.h"
mm/damon/vaddr-test.h new file +329 -0
329 lines not on this page · raw message
_
Andrew Morton
maintainerPATCH 74/147 mm/damon: add user space selftests
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: mm/damon: add user space selftests
This commit adds a simple user space tests for DAMON. The tests are using kselftest framework.
---
tools/testing/selftests/damon/Makefile | 7 + tools/testing/selftests/damon/_chk_dependency.sh | 28 ++++ tools/testing/selftests/damon/debugfs_attrs.sh | 75 +++++++++++++ 3 files changed, 110 insertions(+)
tools/testing/selftests/damon/_chk_dependency.sh new file +28 -0
@@ -0,0 +1,28 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 + +# Kselftest framework requirement - SKIP code is 4. +ksft_skip=4 + +DBGFS=/sys/kernel/debug/damon + +if [ $EUID -ne 0 ]; +then + echo "Run as root" + exit $ksft_skip +fi + +if [ ! -d "$DBGFS" ] +then + echo "$DBGFS not found" + exit $ksft_skip +fi + +for f in attrs target_ids monitor_on +do + if [ ! -f "$DBGFS/$f" ] + then + echo "$f not found" + exit 1 + fi +done
tools/testing/selftests/damon/debugfs_attrs.sh new file +75 -0
75 lines not on this page · raw message
tools/testing/selftests/damon/Makefile new file +7 -0
@@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 +# Makefile for damon selftests + +TEST_FILES = _chk_dependency.sh +TEST_PROGS = debugfs_attrs.sh + +include ../lib.mk
_
Andrew Morton
maintainerPATCH 75/147 MAINTAINERS: update for DAMON
In reply to Andrew MortonFrom: SeongJae Park <[email protected]>
Subject: MAINTAINERS: update for DAMON
This commit updates MAINTAINERS file for DAMON related files.
---
MAINTAINERS | 11 +++++++++++ 1 file changed, 11 insertions(+)
MAINTAINERS renamed from MAINTAINERS~maintainers-update-for-damon +11 -0
@@ -5125,6 +5125,17 @@ F: net/ax25/ax25_out.c F: net/ax25/ax25_timer.c F: net/ax25/sysctl_net_ax25.c +DATA ACCESS MONITOR +M: SeongJae Park <[email protected]> +L: [email protected] +S: Maintained +F: Documentation/admin-guide/mm/damon/ +F: Documentation/vm/damon/ +F: include/linux/damon.h +F: include/trace/events/damon.h +F: mm/damon/ +F: tools/testing/selftests/damon/ + DAVICOM FAST ETHERNET (DMFE) NETWORK DRIVER L: [email protected] S: Orphan
_
Andrew Morton
maintainerPATCH 76/147 alpha: agp: make empty macros use do-while-0 style
In reply to Andrew MortonFrom: Randy Dunlap <[email protected]>
Subject: alpha: agp: make empty macros use do-while-0 style
Copy these macros from ia64/include/asm/agp.h to avoid the "empty-body" in 'if' statment warning.
drivers/char/agp/generic.c: In function 'agp_generic_destroy_page':../drivers/char/agp/generic.c:1265:42: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
1265 | unmap_page_from_agp(page);
---
arch/alpha/include/asm/agp.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/alpha/include/asm/agp.h renamed from arch/alpha/include/asm/agp.h~alpha-agp-make-empty-macros-use-do-while-0-style +2 -2
@@ -6,8 +6,8 @@/* dummy for now */ -#define map_page_into_agp (page) -#define unmap_page_from_agp(page) +#define map_page_into_agp (page) do { } while (0) +#define unmap_page_from_agp (page) do { } while (0)#define flush_agp_cache () mb()/* GATT allocation. Returns/accepts GATT kernel virtual address. */
_