18c2ecf20Sopenharmony_ci.. _memory_allocation:
28c2ecf20Sopenharmony_ci
38c2ecf20Sopenharmony_ci=======================
48c2ecf20Sopenharmony_ciMemory Allocation Guide
58c2ecf20Sopenharmony_ci=======================
68c2ecf20Sopenharmony_ci
78c2ecf20Sopenharmony_ciLinux provides a variety of APIs for memory allocation. You can
88c2ecf20Sopenharmony_ciallocate small chunks using `kmalloc` or `kmem_cache_alloc` families,
98c2ecf20Sopenharmony_cilarge virtually contiguous areas using `vmalloc` and its derivatives,
108c2ecf20Sopenharmony_cior you can directly request pages from the page allocator with
118c2ecf20Sopenharmony_ci`alloc_pages`. It is also possible to use more specialized allocators,
128c2ecf20Sopenharmony_cifor instance `cma_alloc` or `zs_malloc`.
138c2ecf20Sopenharmony_ci
148c2ecf20Sopenharmony_ciMost of the memory allocation APIs use GFP flags to express how that
158c2ecf20Sopenharmony_cimemory should be allocated. The GFP acronym stands for "get free
168c2ecf20Sopenharmony_cipages", the underlying memory allocation function.
178c2ecf20Sopenharmony_ci
188c2ecf20Sopenharmony_ciDiversity of the allocation APIs combined with the numerous GFP flags
198c2ecf20Sopenharmony_cimakes the question "How should I allocate memory?" not that easy to
208c2ecf20Sopenharmony_cianswer, although very likely you should use
218c2ecf20Sopenharmony_ci
228c2ecf20Sopenharmony_ci::
238c2ecf20Sopenharmony_ci
248c2ecf20Sopenharmony_ci  kzalloc(<size>, GFP_KERNEL);
258c2ecf20Sopenharmony_ci
268c2ecf20Sopenharmony_ciOf course there are cases when other allocation APIs and different GFP
278c2ecf20Sopenharmony_ciflags must be used.
288c2ecf20Sopenharmony_ci
298c2ecf20Sopenharmony_ciGet Free Page flags
308c2ecf20Sopenharmony_ci===================
318c2ecf20Sopenharmony_ci
328c2ecf20Sopenharmony_ciThe GFP flags control the allocators behavior. They tell what memory
338c2ecf20Sopenharmony_cizones can be used, how hard the allocator should try to find free
348c2ecf20Sopenharmony_cimemory, whether the memory can be accessed by the userspace etc. The
358c2ecf20Sopenharmony_ci:ref:`Documentation/core-api/mm-api.rst <mm-api-gfp-flags>` provides
368c2ecf20Sopenharmony_cireference documentation for the GFP flags and their combinations and
378c2ecf20Sopenharmony_cihere we briefly outline their recommended usage:
388c2ecf20Sopenharmony_ci
398c2ecf20Sopenharmony_ci  * Most of the time ``GFP_KERNEL`` is what you need. Memory for the
408c2ecf20Sopenharmony_ci    kernel data structures, DMAable memory, inode cache, all these and
418c2ecf20Sopenharmony_ci    many other allocations types can use ``GFP_KERNEL``. Note, that
428c2ecf20Sopenharmony_ci    using ``GFP_KERNEL`` implies ``GFP_RECLAIM``, which means that
438c2ecf20Sopenharmony_ci    direct reclaim may be triggered under memory pressure; the calling
448c2ecf20Sopenharmony_ci    context must be allowed to sleep.
458c2ecf20Sopenharmony_ci  * If the allocation is performed from an atomic context, e.g interrupt
468c2ecf20Sopenharmony_ci    handler, use ``GFP_NOWAIT``. This flag prevents direct reclaim and
478c2ecf20Sopenharmony_ci    IO or filesystem operations. Consequently, under memory pressure
488c2ecf20Sopenharmony_ci    ``GFP_NOWAIT`` allocation is likely to fail. Allocations which
498c2ecf20Sopenharmony_ci    have a reasonable fallback should be using ``GFP_NOWARN``.
508c2ecf20Sopenharmony_ci  * If you think that accessing memory reserves is justified and the kernel
518c2ecf20Sopenharmony_ci    will be stressed unless allocation succeeds, you may use ``GFP_ATOMIC``.
528c2ecf20Sopenharmony_ci  * Untrusted allocations triggered from userspace should be a subject
538c2ecf20Sopenharmony_ci    of kmem accounting and must have ``__GFP_ACCOUNT`` bit set. There
548c2ecf20Sopenharmony_ci    is the handy ``GFP_KERNEL_ACCOUNT`` shortcut for ``GFP_KERNEL``
558c2ecf20Sopenharmony_ci    allocations that should be accounted.
568c2ecf20Sopenharmony_ci  * Userspace allocations should use either of the ``GFP_USER``,
578c2ecf20Sopenharmony_ci    ``GFP_HIGHUSER`` or ``GFP_HIGHUSER_MOVABLE`` flags. The longer
588c2ecf20Sopenharmony_ci    the flag name the less restrictive it is.
598c2ecf20Sopenharmony_ci
608c2ecf20Sopenharmony_ci    ``GFP_HIGHUSER_MOVABLE`` does not require that allocated memory
618c2ecf20Sopenharmony_ci    will be directly accessible by the kernel and implies that the
628c2ecf20Sopenharmony_ci    data is movable.
638c2ecf20Sopenharmony_ci
648c2ecf20Sopenharmony_ci    ``GFP_HIGHUSER`` means that the allocated memory is not movable,
658c2ecf20Sopenharmony_ci    but it is not required to be directly accessible by the kernel. An
668c2ecf20Sopenharmony_ci    example may be a hardware allocation that maps data directly into
678c2ecf20Sopenharmony_ci    userspace but has no addressing limitations.
688c2ecf20Sopenharmony_ci
698c2ecf20Sopenharmony_ci    ``GFP_USER`` means that the allocated memory is not movable and it
708c2ecf20Sopenharmony_ci    must be directly accessible by the kernel.
718c2ecf20Sopenharmony_ci
728c2ecf20Sopenharmony_ciYou may notice that quite a few allocations in the existing code
738c2ecf20Sopenharmony_cispecify ``GFP_NOIO`` or ``GFP_NOFS``. Historically, they were used to
748c2ecf20Sopenharmony_ciprevent recursion deadlocks caused by direct memory reclaim calling
758c2ecf20Sopenharmony_ciback into the FS or IO paths and blocking on already held
768c2ecf20Sopenharmony_ciresources. Since 4.12 the preferred way to address this issue is to
778c2ecf20Sopenharmony_ciuse new scope APIs described in
788c2ecf20Sopenharmony_ci:ref:`Documentation/core-api/gfp_mask-from-fs-io.rst <gfp_mask_from_fs_io>`.
798c2ecf20Sopenharmony_ci
808c2ecf20Sopenharmony_ciOther legacy GFP flags are ``GFP_DMA`` and ``GFP_DMA32``. They are
818c2ecf20Sopenharmony_ciused to ensure that the allocated memory is accessible by hardware
828c2ecf20Sopenharmony_ciwith limited addressing capabilities. So unless you are writing a
838c2ecf20Sopenharmony_cidriver for a device with such restrictions, avoid using these flags.
848c2ecf20Sopenharmony_ciAnd even with hardware with restrictions it is preferable to use
858c2ecf20Sopenharmony_ci`dma_alloc*` APIs.
868c2ecf20Sopenharmony_ci
878c2ecf20Sopenharmony_ciGFP flags and reclaim behavior
888c2ecf20Sopenharmony_ci------------------------------
898c2ecf20Sopenharmony_ciMemory allocations may trigger direct or background reclaim and it is
908c2ecf20Sopenharmony_ciuseful to understand how hard the page allocator will try to satisfy that
918c2ecf20Sopenharmony_cior another request.
928c2ecf20Sopenharmony_ci
938c2ecf20Sopenharmony_ci  * ``GFP_KERNEL & ~__GFP_RECLAIM`` - optimistic allocation without _any_
948c2ecf20Sopenharmony_ci    attempt to free memory at all. The most light weight mode which even
958c2ecf20Sopenharmony_ci    doesn't kick the background reclaim. Should be used carefully because it
968c2ecf20Sopenharmony_ci    might deplete the memory and the next user might hit the more aggressive
978c2ecf20Sopenharmony_ci    reclaim.
988c2ecf20Sopenharmony_ci
998c2ecf20Sopenharmony_ci  * ``GFP_KERNEL & ~__GFP_DIRECT_RECLAIM`` (or ``GFP_NOWAIT``)- optimistic
1008c2ecf20Sopenharmony_ci    allocation without any attempt to free memory from the current
1018c2ecf20Sopenharmony_ci    context but can wake kswapd to reclaim memory if the zone is below
1028c2ecf20Sopenharmony_ci    the low watermark. Can be used from either atomic contexts or when
1038c2ecf20Sopenharmony_ci    the request is a performance optimization and there is another
1048c2ecf20Sopenharmony_ci    fallback for a slow path.
1058c2ecf20Sopenharmony_ci
1068c2ecf20Sopenharmony_ci  * ``(GFP_KERNEL|__GFP_HIGH) & ~__GFP_DIRECT_RECLAIM`` (aka ``GFP_ATOMIC``) -
1078c2ecf20Sopenharmony_ci    non sleeping allocation with an expensive fallback so it can access
1088c2ecf20Sopenharmony_ci    some portion of memory reserves. Usually used from interrupt/bottom-half
1098c2ecf20Sopenharmony_ci    context with an expensive slow path fallback.
1108c2ecf20Sopenharmony_ci
1118c2ecf20Sopenharmony_ci  * ``GFP_KERNEL`` - both background and direct reclaim are allowed and the
1128c2ecf20Sopenharmony_ci    **default** page allocator behavior is used. That means that not costly
1138c2ecf20Sopenharmony_ci    allocation requests are basically no-fail but there is no guarantee of
1148c2ecf20Sopenharmony_ci    that behavior so failures have to be checked properly by callers
1158c2ecf20Sopenharmony_ci    (e.g. OOM killer victim is allowed to fail currently).
1168c2ecf20Sopenharmony_ci
1178c2ecf20Sopenharmony_ci  * ``GFP_KERNEL | __GFP_NORETRY`` - overrides the default allocator behavior
1188c2ecf20Sopenharmony_ci    and all allocation requests fail early rather than cause disruptive
1198c2ecf20Sopenharmony_ci    reclaim (one round of reclaim in this implementation). The OOM killer
1208c2ecf20Sopenharmony_ci    is not invoked.
1218c2ecf20Sopenharmony_ci
1228c2ecf20Sopenharmony_ci  * ``GFP_KERNEL | __GFP_RETRY_MAYFAIL`` - overrides the default allocator
1238c2ecf20Sopenharmony_ci    behavior and all allocation requests try really hard. The request
1248c2ecf20Sopenharmony_ci    will fail if the reclaim cannot make any progress. The OOM killer
1258c2ecf20Sopenharmony_ci    won't be triggered.
1268c2ecf20Sopenharmony_ci
1278c2ecf20Sopenharmony_ci  * ``GFP_KERNEL | __GFP_NOFAIL`` - overrides the default allocator behavior
1288c2ecf20Sopenharmony_ci    and all allocation requests will loop endlessly until they succeed.
1298c2ecf20Sopenharmony_ci    This might be really dangerous especially for larger orders.
1308c2ecf20Sopenharmony_ci
1318c2ecf20Sopenharmony_ciSelecting memory allocator
1328c2ecf20Sopenharmony_ci==========================
1338c2ecf20Sopenharmony_ci
1348c2ecf20Sopenharmony_ciThe most straightforward way to allocate memory is to use a function
1358c2ecf20Sopenharmony_cifrom the kmalloc() family. And, to be on the safe side it's best to use
1368c2ecf20Sopenharmony_ciroutines that set memory to zero, like kzalloc(). If you need to
1378c2ecf20Sopenharmony_ciallocate memory for an array, there are kmalloc_array() and kcalloc()
1388c2ecf20Sopenharmony_cihelpers. The helpers struct_size(), array_size() and array3_size() can
1398c2ecf20Sopenharmony_cibe used to safely calculate object sizes without overflowing.
1408c2ecf20Sopenharmony_ci
1418c2ecf20Sopenharmony_ciThe maximal size of a chunk that can be allocated with `kmalloc` is
1428c2ecf20Sopenharmony_cilimited. The actual limit depends on the hardware and the kernel
1438c2ecf20Sopenharmony_ciconfiguration, but it is a good practice to use `kmalloc` for objects
1448c2ecf20Sopenharmony_cismaller than page size.
1458c2ecf20Sopenharmony_ci
1468c2ecf20Sopenharmony_ciThe address of a chunk allocated with `kmalloc` is aligned to at least
1478c2ecf20Sopenharmony_ciARCH_KMALLOC_MINALIGN bytes.  For sizes which are a power of two, the
1488c2ecf20Sopenharmony_cialignment is also guaranteed to be at least the respective size.
1498c2ecf20Sopenharmony_ci
1508c2ecf20Sopenharmony_ciFor large allocations you can use vmalloc() and vzalloc(), or directly
1518c2ecf20Sopenharmony_cirequest pages from the page allocator. The memory allocated by `vmalloc`
1528c2ecf20Sopenharmony_ciand related functions is not physically contiguous.
1538c2ecf20Sopenharmony_ci
1548c2ecf20Sopenharmony_ciIf you are not sure whether the allocation size is too large for
1558c2ecf20Sopenharmony_ci`kmalloc`, it is possible to use kvmalloc() and its derivatives. It will
1568c2ecf20Sopenharmony_citry to allocate memory with `kmalloc` and if the allocation fails it
1578c2ecf20Sopenharmony_ciwill be retried with `vmalloc`. There are restrictions on which GFP
1588c2ecf20Sopenharmony_ciflags can be used with `kvmalloc`; please see kvmalloc_node() reference
1598c2ecf20Sopenharmony_cidocumentation. Note that `kvmalloc` may return memory that is not
1608c2ecf20Sopenharmony_ciphysically contiguous.
1618c2ecf20Sopenharmony_ci
1628c2ecf20Sopenharmony_ciIf you need to allocate many identical objects you can use the slab
1638c2ecf20Sopenharmony_cicache allocator. The cache should be set up with kmem_cache_create() or
1648c2ecf20Sopenharmony_cikmem_cache_create_usercopy() before it can be used. The second function
1658c2ecf20Sopenharmony_cishould be used if a part of the cache might be copied to the userspace.
1668c2ecf20Sopenharmony_ciAfter the cache is created kmem_cache_alloc() and its convenience
1678c2ecf20Sopenharmony_ciwrappers can allocate memory from that cache.
1688c2ecf20Sopenharmony_ci
1698c2ecf20Sopenharmony_ciWhen the allocated memory is no longer needed it must be freed. You can
1708c2ecf20Sopenharmony_ciuse kvfree() for the memory allocated with `kmalloc`, `vmalloc` and
1718c2ecf20Sopenharmony_ci`kvmalloc`. The slab caches should be freed with kmem_cache_free(). And
1728c2ecf20Sopenharmony_cidon't forget to destroy the cache with kmem_cache_destroy().
173