
## Memory Allocation Profiling deployment results and future improvements

A low overhead interface provided to profile kernel memory allocations whose goal is to reduce wasteful memory allocations.

It is enabled via CONFIG_MEM_ALLOC_PROFILING and every allocation is accounted via /proc/allocinfo.

It was initially merged in 6.10, and is already in use by Google in a pilot program, operating on over 1,000 servers. It is being prepared to be included in the next android release, based on kernel v6.12.

Real world testing has been performed on 1,251 production machines, with data stored in a central database with visualisation and tracking performed using expressive queries over 0.4 PiB of data, allowing for the identification of the heaviest allocation call sites.

This can be used to see whether allocations correlate to Service Level Obligations like packet latency or packet drops.

An example use case was idle cloud machines which generated large allocations after boot (>10 MiB), where this functionality was used to determine where savings could be made. This resulted in savings of 7 GiB per machine, with 2 GiB of more potential savings identified resulting in less kernel overhead and more memory for guest VMs.

In the future there are plans to use page flags instead of page extensions, differentiating accountable allocations vs. non-accountable and adding 'context capture' in discovered hotspots - i.e. call stacks, timestamps and additional metadata (especially determining who allocated what).

Userspace tooling is under development.

## Towards better memory allocations for device drivers

The page allocator doesn't necessary provide good allocations for device drivers - the buddy allocator is designed to split memory into separate zones, but this does not map to the real world.

In reality, device memory is abstracted by a bus address, possibly obtained by an offset applied by a host bridge. In any case there may not be a correlation between offsets from the bus address to physical address - the zone abstraction breaks down.

Zones have the positive characteristic of having dedicated pools for atomic allocations, the watermark mechanism for memory reclaim under memory pressure, and the ability to replenish these dedicated memory pools.

However the use of arbitrary global physical address ranges established at boot time and only three core zones (DMA, DMA32, normal) being available is a very significant drawback.

The idea being proposed is to dynamically create allocation groups each mapped to a device at device initialisation time and possessing emergency memory pools for atomic allocations. These would be cognizant of the realities of device bus addresses and could be shared between devices.

The idea is that these allocation groups would integrate with the buddy allocator and possess their own watermark mechanism as zones do now.

These would supercede existing coherent pools.

Discussion in the room established that no, not all zones would be eliminated but rather this would be conceived as something in addition to existing zones.

Additionally it was confirmed that this mechanism resembles CMA, albeit without the need for contiguous memory - typically only order-1 or order-2 pages at maximum would be required at any one time.

It was established that it would be important to ensure this memory would be movable so kcompactd could move data around.

Additionally it was confirmed that GFP_ATOMIC would be ensured to continue to function correctly.

Finally a suggestion was made to integrate with the existing mempool implementation for which mm has little insight currently.

## DAMON - Long-term plans for kernel (just works extensible)

DAMON is a data access pattern snapshot generator which indicates how frequently address ranges are accessed and for how long over both virtual and physical address ranges.

It is designed for low overhead which can be bounded, and easy extension.

The userland component of DAMON is DAMOS, and allows for 'access-aware' system optimisation, e.g. a request to 'reclaim memory regions not accessed for greater than 2 minutes'.

The DAMOS tool aims to be a long-term stable userspace tool that users can rely upon, and it is importantly intended to be a convenient tool for people to utilise rather than a raw or difficult to use API.

Future goals include providing a 'user space control plane' - the idea is that the kernel knows many things but not everything, so provide an extensive interface to DAMON via sysfs to be able to manipulate the kernel based on profiling under user control.

The 'user space control plane' is intended to provide something that 'just works' - and to be implemented via DAMON modules, e.g. DAMON_RECLAIM, DAMON_LRU_SORT and similar - the intent being to assist kernel functionality rather than to replace it.

This is a form of 'auto-tuning' taking profiling data and using it to adjust how the kernel does things.

The idea is that this kind of functionality would be easily enabled by config variables of the form CONFIG_DAMON_xxx.

Another intent in the future was to provide a BPF interface to DAMON.

During discussion in the room it was pointed out that it would be important to ensure that integration with PSI would be useful - it was established that functionality in this direction already exists.

## Poison & remedy of vmas instead of guards

The concept is to provide a means by which guard pages can be established in userspace at the page table level rather than at the VMA level.

Guard pages in the context of this functionality are defined as ranges which, when the user attempts to access them, encounter a fatal signal. These are typically established by userland allocator libraries and the system pthread implementation.

The value of doing this at a page table level is we do not need to allocate a new VMA nor have to split existing VMAs up in order to insert these guard VMAs.

This is pertinent, as at scale with many threads and many processes, the number of guard pages, and thus additional VMAs, can grow large and occupy significant, unmoveable, kernel memory as well as requiring the use of contended locks to manipulate.

The proposed solution is to instead permit the establishment of 'poisoned' ranges of memory at the page table level within existing VMAs. This adjusts how fault handling is done in these ranges, but otherwise leaves them exactly equivalent to the rest of the VMA.

The proposed approach is limited to anonymous memory only to avoid some of the difficult questions that arise around how one might correctly implement this for file-backed or shmem memory.

The operation is reversible via a 'remedy' operation which removes these poison markers. Importantly this operation can be performed over existing mappings and leaves them untouched so a user can simply clear an entire range of poison markers without needing to be concerned about non-poison mappings.

The mechanism for doing this is provided by new madvise() operations, which are also designed to be usable via the vector-based process_madvise() interface for easy installation and removal of poison markers in a batch.

If poison markers are established in range that is already mapped, this range is zapped before being replaced.

The markers are torn down in unmap or equivalent, but are left in place on MADV_DONTNEED and fork.

a potential concern was the need to establish an anon_vma even if one did not already exist in order to ensure that page tables get propagated on fork, however there did not appear to be great concern in the room on this issue.

Naming, however, was a concern with objection raised about the use of 'poison/remedy' and subsequently this has been replaced with guard poison/unpoison to avoid confusion.

## Madvise lazy free

There is significant overhead spent in TLB flushing, especially on operations such as MADV_DONTNEED or MADV_FREE (confusingly already referred to as lazyfree within the kernel).

In MADV_DONTNEED, the calling thread is spending 50% of CPU time on TLB flushing, and once you add in TLB flushing on other CPUS this can grow to 90-97% of time taken (assuming a system with ~10 cores - new systems can have hundreds).

Rather than doing this, it is proposed to implement a system that truly defers the TLB flushing operation to a time that suits the kernel.

The proposition is that this mechanism would be exposed via MADV_LAZYFREE, MADV_REUSE methods - the former lazily starting the freeing operation, to be freed at a time convenient for the kernel. The latter saying the region ought now to be available for reuse + so should be immediately TLB flushed.

The functionality would piggy-back on existing lazy TLB code - checking whether the CPU's tlb_gen is less than the mm_struct's - if so then we know to flush the TLB. As a result the implementation would be relatively small.

On reclaim we determine if the mapping is in a lazy free range, look up its tlb_gen, clear its PTE, iterating over CPUs with its mm loaded and if its tlb_gen is less than the mm's generate an Inter-Process Interrupt (IPI), otherwise do nothing, prior to freeing the memory.

An optimisation to this functionality is to maintain a small buffer of flushed ranges and to perform partial flushes on context switch - this provided a 1-2% IPC improvement in testing, even without MADV_LAZYFREE.

Additionally we could in theory move PTEs into a per-process buffer list and reuse them rather than require the use of MADV_REUSE.

## Transitioning get_user_pages (GUP) to folio-based mapping

Significant performance improvements were observed when making use of larger flie-backed folio sizes via GUP - for instance an ~87% improvement in performance when mapping 128 KiB folios utilising mTHP - 28.4us to 3.75us.

The speakers wanted to determine how best to batch these operations, with the concept touted of making use of bcachefs's folio_vec array.

In order to implement vector operations such as this correctly, CoW logic would need to be moved to the GUP implementation which would check for contiguous pages and construct these folio_vec objects.

Questions would arise in doing so as to how one might pin or unpin at this granularity - the overwhelming benefit however is to avoid taking reference counts on folios 'one at a time' which is hugely expensive.

The consensus in the room was that the API to GUP should not be changed, so any solution to the problem of how best to batch contiguous memory to use higher folios would have to be implemented in a transparent way.

It was suggested that the previously proposed phyr data structure could be used instead.

There was also discussion around how further optimisations could be performed - including the future desire to make the struct page data structure so small that duplicating it would be less of a problem.

## Ongoing challenges of large page sizes

Google are intending to release new Pixel products which default to 16 KiB page size, and as a result have been exploring memory management behaviour in this area.

CMA has been found rather wanting, in particular encountering failures to allocate memory arising from its alignment requirements - CMA_MIN_ALIGNMENT_BYTES is based on page size, so for instance 4 KiB pages require 4 MiB alignment, 16 KiB bytes requires 32 MiB alignment.

This results in small allocations actually requiring an actually far larger allocation from CMA, and thereby wasting memory.

In addition, file locks, as shown by /proc/locks increases by 30% at 16 KiB page size.

A specific problem encountered has been in the construction of ELF sections - PROT_NONE guard pages are significantly larger as is padding.

In addition readahead has been problematic - as additional padding has needed to be added to accommodate the larger page size and this has resulted in more block device activity, though the use of sparse files has helped mitigate this.

Additionally fault around results in more PTEs being faulted in and thus increase in RSS and a perception by users that more memory is being used.

The ideal scenario would be to prevent fault around from doing this for padding ranges, equally so for readahead.

In discussion the idea was raised as to whether an API could be established to indicate whether something is a hole or not and if so, return the zero page.

The concept of poison ranges was raised (the previously mentioned proposed guard page interface does not support file-backed ranges yet so wouldn't be useful here currently) - however it was highlighted that we must differentiate between this and padding that should not cause a fatal signal but rather return the zero page.

It was also raised that perhaps the CMA issue is related to pageblock order, which could be adjusted in an arm64 environment.

## mTHP and swap aallocator

The currently implemented swap allocator algorithm is problematic for SSD drives where it can cause a high write amplification factor and thus wear, a problem that is amplified by the swapping out of mTHP-sized pages.

The swap entry allocation algorithm is in effect a bin packing problem, and swap writes are as subject to fragmentation as any other area of memory management.

The focus is on SSD behaviour as in practice modern users are nearly always using SSDs rather than hard drives for swap so how SSDs actually behave is highly relevant. compressed swap is very often used.

The current swap allocator uses a simple cluster-based approach and a brute-force algorithm in finding space to allocate space - if it fails to do so, this naturally results in very high swap failure rates.

The idea proposed is to introduce a new order-aware cluster allocator with a focus on reducing swap device lock contention, intending to eliminate the all too global swap lock.

A concept raised was the idea that perhaps we can try to ensure continuous writes to the SSD and garbage collect manually.

## mTHP swap-out and swap-in

Previously, only PMD-mapped THP was supported in the swap mechanism where the cluster size was equal to the THP page size. This has since been extended to support multiple sizes, which has however resulted in fragmentation, a problem that has been gradually addressed over time.

Additionally, previously once an mTHP page was swapped out, it could no longer be restored at an mTHP granularity. Again, this was addressed in later patches, though only in cases where zswap was not enabled.

On the other hand, zram/zsmalloc is currently heavily optimised for mTHP swap operations - a larger granularity allowing for a higher compression ratio and faster compression and decompression speeds, observing up to 10 times improvement in zram write latency an 7 times improvement in zram read latency.

This is therefore the recommended mode of use when swapping in and out mTHP sized pages.

## Multi-gen LRU updates

The Multi-generational LRU (MGLRU) is an alternative LRU implementation for page aging and reclaim.

It organises pages into  multi-tier, multi-generational LRUs based on access recency. Each LRU gen has a birth timestamp which allows recency comparison across LRUs, and we optimise page generation updates via efficient forward page table scans.

This functionality has been adopted by Google directly. Previously implemented 'kstaled' was a custom kernel thread used for for time-based proactive aging and reclaim, which this replaces.

MGLRU is now used in a portion of Google production, achieved the same memory savings as achieved by kstaled with 5 times less CPU overhead.

From a virtualisation perspective, work is ongoing to extend MGLRU to support efficient KVM secondary MMU aging. A lockless scan can reduce KVM MMU lock contention by ~85%.

3A problem that MGLRU has encountered is that OOM kills can occur when writeback falls behind - there needs to be a smarter means of making decisions around when to wake and to perform better throttling in this scenario.

Another limitation of MGLRU is that it requires a 64-bit architecture - perhaps stuffing data in folio->lru low bits might mitigate this?

Moving forward there is an intent to look at establishing working set reporting for proactive reclaim and aging - providing data with a time component in order to make decisions.

Another idea is to use different heuristics based on different types of workloads - aging/reclaim policies could be specified via BPF, which would be especially useful for workloads that aren't well supported by out-of-the-box MGLRU. This is especially pertinent to hyperscale machines.

It was discussed whether DAMON might be a useful approach for solving the problems addressed by MGLRU, however it was confirmed that MGLRU suits solving Google's problems better.

Moving forward Linus would prefer to make MGLRU the default LRU mechanism - it was suggested that perhaps it might be worth enabling it by default in the Kconfig, only to be disabled by vendors who do not wish to use it (or who use 32-bit systems for instance).

## TAO: THP Allocator Optimisations / Policy zones

A lot of vendors are moving toward larger page sizes, e.g. arm64-based systems are often moving to 16 KiB pages.

The concept proposed in this talk is that a forward-looking OS would favour larger logical pages over 4 KiB pages while also not breaking ABI, treating 4KiB pages as 'legacy'. Experiments suggest that favouring THP-sized pages (including mTHP naturally) results in better overall performance and less metadata overhead vs. competitor approaches such as the use of HVO or memdesc's.

Additionally, it is suggested that the use of 4 KiB page should be restrained as they cause fragmentation which can build up over time and become intractable if left too long.

The idea is that rather than the current THP concepts of splitting pages (turning larger ones into smaller) or collapsing pages (turning smaller ones into larger) we'd refer to these as 'shatter' and 'recover' respectively, and equivalently change how the kernel handles this with a bias towards recovery.

This approach is referred to as the 'THP Allocator Optimisations' or 'TAO'. In the TAO regime we want to reverse the cost of allocation - making 4 KiB more expensive to use than larger pages.

We'd need to adjust migrate type fallback logic to accommodate this, noting that __GFP_MOVABLE is 'stronger' than __GFP_COMP, as the former can make the latter possible by compaction, but not vice-versa.

In determining fallbacks, we could utilise a statistical analysis of the lifetime of unmovable allocations - this however remains a research project at this time.

Memory would be partitioned into 4 KiB pages and THP, which could be based on global limits or tunables perhaps.

Regardless there would be a trade-off between memory utilisation (and thus wastage) vs. system load which would need to be carefully calibrated.

In theory auto-resizing could be done based on memory pressure experienced within each partition - differential pressure would be required to counteract fragmentation, for instance - memory pressure in the 4 KiB partition ought to be able to trigger the OOM killer even if the THP partition experiences none.

Arguably for some platforms, userspace-managed OOM killers would be a better choice.

In discussion within the room there was considerable pushback on the concept that 4 KiB pages might be considered to be 'bad' or 'legacy' and larger page sizes 'not bad'. The point was raised that there are a number of different page sizes that one can use - where does the designation of good/bad end?

In response it was suggested that the distribution of page sizes is something more like a bell curve, with 4 KiB pages right on the left-hand side so the least preferable.

Another commenter suggested that it seems that THP appears to want to try to mimic hugetlb in functionality in that there is an intent to maintain separate 'pools' of memory.

Finally it was pointed out that Google are already leveraging HVO to reduce THP struct page overhead in the data centre so there is a need for approaches such as this.

Looking forward, there is the hope that perhaps we can provide 1 GiB THP support, larger device HMM page sizes, and variable CPU and GPU base page sizing (e.g. 4 KiB vs. 64 KiB).
