162306a36Sopenharmony_ci.. _memory_allocation: 262306a36Sopenharmony_ci 362306a36Sopenharmony_ci======================= 462306a36Sopenharmony_ciMemory Allocation Guide 562306a36Sopenharmony_ci======================= 662306a36Sopenharmony_ci 762306a36Sopenharmony_ciLinux provides a variety of APIs for memory allocation. You can 862306a36Sopenharmony_ciallocate small chunks using `kmalloc` or `kmem_cache_alloc` families, 962306a36Sopenharmony_cilarge virtually contiguous areas using `vmalloc` and its derivatives, 1062306a36Sopenharmony_cior you can directly request pages from the page allocator with 1162306a36Sopenharmony_ci`alloc_pages`. It is also possible to use more specialized allocators, 1262306a36Sopenharmony_cifor instance `cma_alloc` or `zs_malloc`. 1362306a36Sopenharmony_ci 1462306a36Sopenharmony_ciMost of the memory allocation APIs use GFP flags to express how that 1562306a36Sopenharmony_cimemory should be allocated. The GFP acronym stands for "get free 1662306a36Sopenharmony_cipages", the underlying memory allocation function. 1762306a36Sopenharmony_ci 1862306a36Sopenharmony_ciDiversity of the allocation APIs combined with the numerous GFP flags 1962306a36Sopenharmony_cimakes the question "How should I allocate memory?" not that easy to 2062306a36Sopenharmony_cianswer, although very likely you should use 2162306a36Sopenharmony_ci 2262306a36Sopenharmony_ci:: 2362306a36Sopenharmony_ci 2462306a36Sopenharmony_ci kzalloc(<size>, GFP_KERNEL); 2562306a36Sopenharmony_ci 2662306a36Sopenharmony_ciOf course there are cases when other allocation APIs and different GFP 2762306a36Sopenharmony_ciflags must be used. 2862306a36Sopenharmony_ci 2962306a36Sopenharmony_ciGet Free Page flags 3062306a36Sopenharmony_ci=================== 3162306a36Sopenharmony_ci 3262306a36Sopenharmony_ciThe GFP flags control the allocators behavior. They tell what memory 3362306a36Sopenharmony_cizones can be used, how hard the allocator should try to find free 3462306a36Sopenharmony_cimemory, whether the memory can be accessed by the userspace etc. The 3562306a36Sopenharmony_ci:ref:`Documentation/core-api/mm-api.rst <mm-api-gfp-flags>` provides 3662306a36Sopenharmony_cireference documentation for the GFP flags and their combinations and 3762306a36Sopenharmony_cihere we briefly outline their recommended usage: 3862306a36Sopenharmony_ci 3962306a36Sopenharmony_ci * Most of the time ``GFP_KERNEL`` is what you need. Memory for the 4062306a36Sopenharmony_ci kernel data structures, DMAable memory, inode cache, all these and 4162306a36Sopenharmony_ci many other allocations types can use ``GFP_KERNEL``. Note, that 4262306a36Sopenharmony_ci using ``GFP_KERNEL`` implies ``GFP_RECLAIM``, which means that 4362306a36Sopenharmony_ci direct reclaim may be triggered under memory pressure; the calling 4462306a36Sopenharmony_ci context must be allowed to sleep. 4562306a36Sopenharmony_ci * If the allocation is performed from an atomic context, e.g interrupt 4662306a36Sopenharmony_ci handler, use ``GFP_NOWAIT``. This flag prevents direct reclaim and 4762306a36Sopenharmony_ci IO or filesystem operations. Consequently, under memory pressure 4862306a36Sopenharmony_ci ``GFP_NOWAIT`` allocation is likely to fail. Allocations which 4962306a36Sopenharmony_ci have a reasonable fallback should be using ``GFP_NOWARN``. 5062306a36Sopenharmony_ci * If you think that accessing memory reserves is justified and the kernel 5162306a36Sopenharmony_ci will be stressed unless allocation succeeds, you may use ``GFP_ATOMIC``. 5262306a36Sopenharmony_ci * Untrusted allocations triggered from userspace should be a subject 5362306a36Sopenharmony_ci of kmem accounting and must have ``__GFP_ACCOUNT`` bit set. There 5462306a36Sopenharmony_ci is the handy ``GFP_KERNEL_ACCOUNT`` shortcut for ``GFP_KERNEL`` 5562306a36Sopenharmony_ci allocations that should be accounted. 5662306a36Sopenharmony_ci * Userspace allocations should use either of the ``GFP_USER``, 5762306a36Sopenharmony_ci ``GFP_HIGHUSER`` or ``GFP_HIGHUSER_MOVABLE`` flags. The longer 5862306a36Sopenharmony_ci the flag name the less restrictive it is. 5962306a36Sopenharmony_ci 6062306a36Sopenharmony_ci ``GFP_HIGHUSER_MOVABLE`` does not require that allocated memory 6162306a36Sopenharmony_ci will be directly accessible by the kernel and implies that the 6262306a36Sopenharmony_ci data is movable. 6362306a36Sopenharmony_ci 6462306a36Sopenharmony_ci ``GFP_HIGHUSER`` means that the allocated memory is not movable, 6562306a36Sopenharmony_ci but it is not required to be directly accessible by the kernel. An 6662306a36Sopenharmony_ci example may be a hardware allocation that maps data directly into 6762306a36Sopenharmony_ci userspace but has no addressing limitations. 6862306a36Sopenharmony_ci 6962306a36Sopenharmony_ci ``GFP_USER`` means that the allocated memory is not movable and it 7062306a36Sopenharmony_ci must be directly accessible by the kernel. 7162306a36Sopenharmony_ci 7262306a36Sopenharmony_ciYou may notice that quite a few allocations in the existing code 7362306a36Sopenharmony_cispecify ``GFP_NOIO`` or ``GFP_NOFS``. Historically, they were used to 7462306a36Sopenharmony_ciprevent recursion deadlocks caused by direct memory reclaim calling 7562306a36Sopenharmony_ciback into the FS or IO paths and blocking on already held 7662306a36Sopenharmony_ciresources. Since 4.12 the preferred way to address this issue is to 7762306a36Sopenharmony_ciuse new scope APIs described in 7862306a36Sopenharmony_ci:ref:`Documentation/core-api/gfp_mask-from-fs-io.rst <gfp_mask_from_fs_io>`. 7962306a36Sopenharmony_ci 8062306a36Sopenharmony_ciOther legacy GFP flags are ``GFP_DMA`` and ``GFP_DMA32``. They are 8162306a36Sopenharmony_ciused to ensure that the allocated memory is accessible by hardware 8262306a36Sopenharmony_ciwith limited addressing capabilities. So unless you are writing a 8362306a36Sopenharmony_cidriver for a device with such restrictions, avoid using these flags. 8462306a36Sopenharmony_ciAnd even with hardware with restrictions it is preferable to use 8562306a36Sopenharmony_ci`dma_alloc*` APIs. 8662306a36Sopenharmony_ci 8762306a36Sopenharmony_ciGFP flags and reclaim behavior 8862306a36Sopenharmony_ci------------------------------ 8962306a36Sopenharmony_ciMemory allocations may trigger direct or background reclaim and it is 9062306a36Sopenharmony_ciuseful to understand how hard the page allocator will try to satisfy that 9162306a36Sopenharmony_cior another request. 9262306a36Sopenharmony_ci 9362306a36Sopenharmony_ci * ``GFP_KERNEL & ~__GFP_RECLAIM`` - optimistic allocation without _any_ 9462306a36Sopenharmony_ci attempt to free memory at all. The most light weight mode which even 9562306a36Sopenharmony_ci doesn't kick the background reclaim. Should be used carefully because it 9662306a36Sopenharmony_ci might deplete the memory and the next user might hit the more aggressive 9762306a36Sopenharmony_ci reclaim. 9862306a36Sopenharmony_ci 9962306a36Sopenharmony_ci * ``GFP_KERNEL & ~__GFP_DIRECT_RECLAIM`` (or ``GFP_NOWAIT``)- optimistic 10062306a36Sopenharmony_ci allocation without any attempt to free memory from the current 10162306a36Sopenharmony_ci context but can wake kswapd to reclaim memory if the zone is below 10262306a36Sopenharmony_ci the low watermark. Can be used from either atomic contexts or when 10362306a36Sopenharmony_ci the request is a performance optimization and there is another 10462306a36Sopenharmony_ci fallback for a slow path. 10562306a36Sopenharmony_ci 10662306a36Sopenharmony_ci * ``(GFP_KERNEL|__GFP_HIGH) & ~__GFP_DIRECT_RECLAIM`` (aka ``GFP_ATOMIC``) - 10762306a36Sopenharmony_ci non sleeping allocation with an expensive fallback so it can access 10862306a36Sopenharmony_ci some portion of memory reserves. Usually used from interrupt/bottom-half 10962306a36Sopenharmony_ci context with an expensive slow path fallback. 11062306a36Sopenharmony_ci 11162306a36Sopenharmony_ci * ``GFP_KERNEL`` - both background and direct reclaim are allowed and the 11262306a36Sopenharmony_ci **default** page allocator behavior is used. That means that not costly 11362306a36Sopenharmony_ci allocation requests are basically no-fail but there is no guarantee of 11462306a36Sopenharmony_ci that behavior so failures have to be checked properly by callers 11562306a36Sopenharmony_ci (e.g. OOM killer victim is allowed to fail currently). 11662306a36Sopenharmony_ci 11762306a36Sopenharmony_ci * ``GFP_KERNEL | __GFP_NORETRY`` - overrides the default allocator behavior 11862306a36Sopenharmony_ci and all allocation requests fail early rather than cause disruptive 11962306a36Sopenharmony_ci reclaim (one round of reclaim in this implementation). The OOM killer 12062306a36Sopenharmony_ci is not invoked. 12162306a36Sopenharmony_ci 12262306a36Sopenharmony_ci * ``GFP_KERNEL | __GFP_RETRY_MAYFAIL`` - overrides the default allocator 12362306a36Sopenharmony_ci behavior and all allocation requests try really hard. The request 12462306a36Sopenharmony_ci will fail if the reclaim cannot make any progress. The OOM killer 12562306a36Sopenharmony_ci won't be triggered. 12662306a36Sopenharmony_ci 12762306a36Sopenharmony_ci * ``GFP_KERNEL | __GFP_NOFAIL`` - overrides the default allocator behavior 12862306a36Sopenharmony_ci and all allocation requests will loop endlessly until they succeed. 12962306a36Sopenharmony_ci This might be really dangerous especially for larger orders. 13062306a36Sopenharmony_ci 13162306a36Sopenharmony_ciSelecting memory allocator 13262306a36Sopenharmony_ci========================== 13362306a36Sopenharmony_ci 13462306a36Sopenharmony_ciThe most straightforward way to allocate memory is to use a function 13562306a36Sopenharmony_cifrom the kmalloc() family. And, to be on the safe side it's best to use 13662306a36Sopenharmony_ciroutines that set memory to zero, like kzalloc(). If you need to 13762306a36Sopenharmony_ciallocate memory for an array, there are kmalloc_array() and kcalloc() 13862306a36Sopenharmony_cihelpers. The helpers struct_size(), array_size() and array3_size() can 13962306a36Sopenharmony_cibe used to safely calculate object sizes without overflowing. 14062306a36Sopenharmony_ci 14162306a36Sopenharmony_ciThe maximal size of a chunk that can be allocated with `kmalloc` is 14262306a36Sopenharmony_cilimited. The actual limit depends on the hardware and the kernel 14362306a36Sopenharmony_ciconfiguration, but it is a good practice to use `kmalloc` for objects 14462306a36Sopenharmony_cismaller than page size. 14562306a36Sopenharmony_ci 14662306a36Sopenharmony_ciThe address of a chunk allocated with `kmalloc` is aligned to at least 14762306a36Sopenharmony_ciARCH_KMALLOC_MINALIGN bytes. For sizes which are a power of two, the 14862306a36Sopenharmony_cialignment is also guaranteed to be at least the respective size. 14962306a36Sopenharmony_ci 15062306a36Sopenharmony_ciChunks allocated with kmalloc() can be resized with krealloc(). Similarly 15162306a36Sopenharmony_cito kmalloc_array(): a helper for resizing arrays is provided in the form of 15262306a36Sopenharmony_cikrealloc_array(). 15362306a36Sopenharmony_ci 15462306a36Sopenharmony_ciFor large allocations you can use vmalloc() and vzalloc(), or directly 15562306a36Sopenharmony_cirequest pages from the page allocator. The memory allocated by `vmalloc` 15662306a36Sopenharmony_ciand related functions is not physically contiguous. 15762306a36Sopenharmony_ci 15862306a36Sopenharmony_ciIf you are not sure whether the allocation size is too large for 15962306a36Sopenharmony_ci`kmalloc`, it is possible to use kvmalloc() and its derivatives. It will 16062306a36Sopenharmony_citry to allocate memory with `kmalloc` and if the allocation fails it 16162306a36Sopenharmony_ciwill be retried with `vmalloc`. There are restrictions on which GFP 16262306a36Sopenharmony_ciflags can be used with `kvmalloc`; please see kvmalloc_node() reference 16362306a36Sopenharmony_cidocumentation. Note that `kvmalloc` may return memory that is not 16462306a36Sopenharmony_ciphysically contiguous. 16562306a36Sopenharmony_ci 16662306a36Sopenharmony_ciIf you need to allocate many identical objects you can use the slab 16762306a36Sopenharmony_cicache allocator. The cache should be set up with kmem_cache_create() or 16862306a36Sopenharmony_cikmem_cache_create_usercopy() before it can be used. The second function 16962306a36Sopenharmony_cishould be used if a part of the cache might be copied to the userspace. 17062306a36Sopenharmony_ciAfter the cache is created kmem_cache_alloc() and its convenience 17162306a36Sopenharmony_ciwrappers can allocate memory from that cache. 17262306a36Sopenharmony_ci 17362306a36Sopenharmony_ciWhen the allocated memory is no longer needed it must be freed. 17462306a36Sopenharmony_ci 17562306a36Sopenharmony_ciObjects allocated by `kmalloc` can be freed by `kfree` or `kvfree`. Objects 17662306a36Sopenharmony_ciallocated by `kmem_cache_alloc` can be freed with `kmem_cache_free`, `kfree` 17762306a36Sopenharmony_cior `kvfree`, where the latter two might be more convenient thanks to not 17862306a36Sopenharmony_cineeding the kmem_cache pointer. 17962306a36Sopenharmony_ci 18062306a36Sopenharmony_ciThe same rules apply to _bulk and _rcu flavors of freeing functions. 18162306a36Sopenharmony_ci 18262306a36Sopenharmony_ciMemory allocated by `vmalloc` can be freed with `vfree` or `kvfree`. 18362306a36Sopenharmony_ciMemory allocated by `kvmalloc` can be freed with `kvfree`. 18462306a36Sopenharmony_ciCaches created by `kmem_cache_create` should be freed with 18562306a36Sopenharmony_ci`kmem_cache_destroy` only after freeing all the allocated objects first. 186