1cd7198fcSTobin C. Harding.. _memory_allocation:
2acf0f57aSMatthew Wilcox
352272c92SMike Rapoport=======================
452272c92SMike RapoportMemory Allocation Guide
552272c92SMike Rapoport=======================
652272c92SMike Rapoport
752272c92SMike RapoportLinux provides a variety of APIs for memory allocation. You can
852272c92SMike Rapoportallocate small chunks using `kmalloc` or `kmem_cache_alloc` families,
952272c92SMike Rapoportlarge virtually contiguous areas using `vmalloc` and its derivatives,
1052272c92SMike Rapoportor you can directly request pages from the page allocator with
1152272c92SMike Rapoport`alloc_pages`. It is also possible to use more specialized allocators,
1252272c92SMike Rapoportfor instance `cma_alloc` or `zs_malloc`.
1352272c92SMike Rapoport
1452272c92SMike RapoportMost of the memory allocation APIs use GFP flags to express how that
1552272c92SMike Rapoportmemory should be allocated. The GFP acronym stands for "get free
1652272c92SMike Rapoportpages", the underlying memory allocation function.
1752272c92SMike Rapoport
1852272c92SMike RapoportDiversity of the allocation APIs combined with the numerous GFP flags
1952272c92SMike Rapoportmakes the question "How should I allocate memory?" not that easy to
2052272c92SMike Rapoportanswer, although very likely you should use
2152272c92SMike Rapoport
2252272c92SMike Rapoport::
2352272c92SMike Rapoport
2452272c92SMike Rapoport  kzalloc(<size>, GFP_KERNEL);
2552272c92SMike Rapoport
2652272c92SMike RapoportOf course there are cases when other allocation APIs and different GFP
2752272c92SMike Rapoportflags must be used.
2852272c92SMike Rapoport
2952272c92SMike RapoportGet Free Page flags
3052272c92SMike Rapoport===================
3152272c92SMike Rapoport
3252272c92SMike RapoportThe GFP flags control the allocators behavior. They tell what memory
3352272c92SMike Rapoportzones can be used, how hard the allocator should try to find free
3452272c92SMike Rapoportmemory, whether the memory can be accessed by the userspace etc. The
3552272c92SMike Rapoport:ref:`Documentation/core-api/mm-api.rst <mm-api-gfp-flags>` provides
3652272c92SMike Rapoportreference documentation for the GFP flags and their combinations and
3752272c92SMike Rapoporthere we briefly outline their recommended usage:
3852272c92SMike Rapoport
3952272c92SMike Rapoport  * Most of the time ``GFP_KERNEL`` is what you need. Memory for the
4052272c92SMike Rapoport    kernel data structures, DMAable memory, inode cache, all these and
4152272c92SMike Rapoport    many other allocations types can use ``GFP_KERNEL``. Note, that
4252272c92SMike Rapoport    using ``GFP_KERNEL`` implies ``GFP_RECLAIM``, which means that
4352272c92SMike Rapoport    direct reclaim may be triggered under memory pressure; the calling
4452272c92SMike Rapoport    context must be allowed to sleep.
4552272c92SMike Rapoport  * If the allocation is performed from an atomic context, e.g interrupt
4652272c92SMike Rapoport    handler, use ``GFP_NOWAIT``. This flag prevents direct reclaim and
4752272c92SMike Rapoport    IO or filesystem operations. Consequently, under memory pressure
48*b745fdefSDave Martin    ``GFP_NOWAIT`` allocation is likely to fail. Users of this flag need
49*b745fdefSDave Martin    to provide a suitable fallback to cope with such failures where
50*b745fdefSDave Martin    appropriate.
5152272c92SMike Rapoport  * If you think that accessing memory reserves is justified and the kernel
5252272c92SMike Rapoport    will be stressed unless allocation succeeds, you may use ``GFP_ATOMIC``.
5352272c92SMike Rapoport  * Untrusted allocations triggered from userspace should be a subject
5452272c92SMike Rapoport    of kmem accounting and must have ``__GFP_ACCOUNT`` bit set. There
5552272c92SMike Rapoport    is the handy ``GFP_KERNEL_ACCOUNT`` shortcut for ``GFP_KERNEL``
5652272c92SMike Rapoport    allocations that should be accounted.
5752272c92SMike Rapoport  * Userspace allocations should use either of the ``GFP_USER``,
5852272c92SMike Rapoport    ``GFP_HIGHUSER`` or ``GFP_HIGHUSER_MOVABLE`` flags. The longer
5952272c92SMike Rapoport    the flag name the less restrictive it is.
6052272c92SMike Rapoport
6152272c92SMike Rapoport    ``GFP_HIGHUSER_MOVABLE`` does not require that allocated memory
6252272c92SMike Rapoport    will be directly accessible by the kernel and implies that the
6352272c92SMike Rapoport    data is movable.
6452272c92SMike Rapoport
6552272c92SMike Rapoport    ``GFP_HIGHUSER`` means that the allocated memory is not movable,
6652272c92SMike Rapoport    but it is not required to be directly accessible by the kernel. An
6752272c92SMike Rapoport    example may be a hardware allocation that maps data directly into
6852272c92SMike Rapoport    userspace but has no addressing limitations.
6952272c92SMike Rapoport
7052272c92SMike Rapoport    ``GFP_USER`` means that the allocated memory is not movable and it
7152272c92SMike Rapoport    must be directly accessible by the kernel.
7252272c92SMike Rapoport
7352272c92SMike RapoportYou may notice that quite a few allocations in the existing code
7452272c92SMike Rapoportspecify ``GFP_NOIO`` or ``GFP_NOFS``. Historically, they were used to
7552272c92SMike Rapoportprevent recursion deadlocks caused by direct memory reclaim calling
7652272c92SMike Rapoportback into the FS or IO paths and blocking on already held
7752272c92SMike Rapoportresources. Since 4.12 the preferred way to address this issue is to
7852272c92SMike Rapoportuse new scope APIs described in
7952272c92SMike Rapoport:ref:`Documentation/core-api/gfp_mask-from-fs-io.rst <gfp_mask_from_fs_io>`.
8052272c92SMike Rapoport
8152272c92SMike RapoportOther legacy GFP flags are ``GFP_DMA`` and ``GFP_DMA32``. They are
8252272c92SMike Rapoportused to ensure that the allocated memory is accessible by hardware
8352272c92SMike Rapoportwith limited addressing capabilities. So unless you are writing a
8452272c92SMike Rapoportdriver for a device with such restrictions, avoid using these flags.
8552272c92SMike RapoportAnd even with hardware with restrictions it is preferable to use
8652272c92SMike Rapoport`dma_alloc*` APIs.
8752272c92SMike Rapoport
8800bafa57SMike RapoportGFP flags and reclaim behavior
8900bafa57SMike Rapoport------------------------------
9000bafa57SMike RapoportMemory allocations may trigger direct or background reclaim and it is
9100bafa57SMike Rapoportuseful to understand how hard the page allocator will try to satisfy that
9200bafa57SMike Rapoportor another request.
9300bafa57SMike Rapoport
9400bafa57SMike Rapoport  * ``GFP_KERNEL & ~__GFP_RECLAIM`` - optimistic allocation without _any_
9500bafa57SMike Rapoport    attempt to free memory at all. The most light weight mode which even
9600bafa57SMike Rapoport    doesn't kick the background reclaim. Should be used carefully because it
9700bafa57SMike Rapoport    might deplete the memory and the next user might hit the more aggressive
9800bafa57SMike Rapoport    reclaim.
9900bafa57SMike Rapoport
10000bafa57SMike Rapoport  * ``GFP_KERNEL & ~__GFP_DIRECT_RECLAIM`` (or ``GFP_NOWAIT``)- optimistic
10100bafa57SMike Rapoport    allocation without any attempt to free memory from the current
10200bafa57SMike Rapoport    context but can wake kswapd to reclaim memory if the zone is below
10300bafa57SMike Rapoport    the low watermark. Can be used from either atomic contexts or when
10400bafa57SMike Rapoport    the request is a performance optimization and there is another
10500bafa57SMike Rapoport    fallback for a slow path.
10600bafa57SMike Rapoport
10700bafa57SMike Rapoport  * ``(GFP_KERNEL|__GFP_HIGH) & ~__GFP_DIRECT_RECLAIM`` (aka ``GFP_ATOMIC``) -
10800bafa57SMike Rapoport    non sleeping allocation with an expensive fallback so it can access
10900bafa57SMike Rapoport    some portion of memory reserves. Usually used from interrupt/bottom-half
11000bafa57SMike Rapoport    context with an expensive slow path fallback.
11100bafa57SMike Rapoport
11200bafa57SMike Rapoport  * ``GFP_KERNEL`` - both background and direct reclaim are allowed and the
11300bafa57SMike Rapoport    **default** page allocator behavior is used. That means that not costly
11400bafa57SMike Rapoport    allocation requests are basically no-fail but there is no guarantee of
11500bafa57SMike Rapoport    that behavior so failures have to be checked properly by callers
11600bafa57SMike Rapoport    (e.g. OOM killer victim is allowed to fail currently).
11700bafa57SMike Rapoport
11800bafa57SMike Rapoport  * ``GFP_KERNEL | __GFP_NORETRY`` - overrides the default allocator behavior
11900bafa57SMike Rapoport    and all allocation requests fail early rather than cause disruptive
12000bafa57SMike Rapoport    reclaim (one round of reclaim in this implementation). The OOM killer
12100bafa57SMike Rapoport    is not invoked.
12200bafa57SMike Rapoport
12300bafa57SMike Rapoport  * ``GFP_KERNEL | __GFP_RETRY_MAYFAIL`` - overrides the default allocator
12400bafa57SMike Rapoport    behavior and all allocation requests try really hard. The request
12500bafa57SMike Rapoport    will fail if the reclaim cannot make any progress. The OOM killer
12600bafa57SMike Rapoport    won't be triggered.
12700bafa57SMike Rapoport
12800bafa57SMike Rapoport  * ``GFP_KERNEL | __GFP_NOFAIL`` - overrides the default allocator behavior
12900bafa57SMike Rapoport    and all allocation requests will loop endlessly until they succeed.
13000bafa57SMike Rapoport    This might be really dangerous especially for larger orders.
13100bafa57SMike Rapoport
13252272c92SMike RapoportSelecting memory allocator
13352272c92SMike Rapoport==========================
13452272c92SMike Rapoport
13552272c92SMike RapoportThe most straightforward way to allocate memory is to use a function
136094ef1c9SChris Packhamfrom the kmalloc() family. And, to be on the safe side it's best to use
137094ef1c9SChris Packhamroutines that set memory to zero, like kzalloc(). If you need to
138094ef1c9SChris Packhamallocate memory for an array, there are kmalloc_array() and kcalloc()
1391c16b3d5SChris Packhamhelpers. The helpers struct_size(), array_size() and array3_size() can
1401c16b3d5SChris Packhambe used to safely calculate object sizes without overflowing.
14152272c92SMike Rapoport
14252272c92SMike RapoportThe maximal size of a chunk that can be allocated with `kmalloc` is
14352272c92SMike Rapoportlimited. The actual limit depends on the hardware and the kernel
14452272c92SMike Rapoportconfiguration, but it is a good practice to use `kmalloc` for objects
14552272c92SMike Rapoportsmaller than page size.
14652272c92SMike Rapoport
14759bb4798SVlastimil BabkaThe address of a chunk allocated with `kmalloc` is aligned to at least
14859bb4798SVlastimil BabkaARCH_KMALLOC_MINALIGN bytes. For sizes which are a power of two, the
149ad59baa3SVlastimil Babkaalignment is also guaranteed to be at least the respective size. For other
150ad59baa3SVlastimil Babkasizes, the alignment is guaranteed to be at least the largest power-of-two
151ad59baa3SVlastimil Babkadivisor of the size.
15259bb4798SVlastimil Babka
153f0dbd2bdSBartosz GolaszewskiChunks allocated with kmalloc() can be resized with krealloc(). Similarly
154f0dbd2bdSBartosz Golaszewskito kmalloc_array(): a helper for resizing arrays is provided in the form of
155f0dbd2bdSBartosz Golaszewskikrealloc_array().
156f0dbd2bdSBartosz Golaszewski
157094ef1c9SChris PackhamFor large allocations you can use vmalloc() and vzalloc(), or directly
158094ef1c9SChris Packhamrequest pages from the page allocator. The memory allocated by `vmalloc`
159094ef1c9SChris Packhamand related functions is not physically contiguous.
16052272c92SMike Rapoport
16152272c92SMike RapoportIf you are not sure whether the allocation size is too large for
162094ef1c9SChris Packham`kmalloc`, it is possible to use kvmalloc() and its derivatives. It will
163094ef1c9SChris Packhamtry to allocate memory with `kmalloc` and if the allocation fails it
164094ef1c9SChris Packhamwill be retried with `vmalloc`. There are restrictions on which GFP
165094ef1c9SChris Packhamflags can be used with `kvmalloc`; please see kvmalloc_node() reference
166094ef1c9SChris Packhamdocumentation. Note that `kvmalloc` may return memory that is not
167094ef1c9SChris Packhamphysically contiguous.
16852272c92SMike Rapoport
16952272c92SMike RapoportIf you need to allocate many identical objects you can use the slab
170094ef1c9SChris Packhamcache allocator. The cache should be set up with kmem_cache_create() or
171094ef1c9SChris Packhamkmem_cache_create_usercopy() before it can be used. The second function
172094ef1c9SChris Packhamshould be used if a part of the cache might be copied to the userspace.
173094ef1c9SChris PackhamAfter the cache is created kmem_cache_alloc() and its convenience
174094ef1c9SChris Packhamwrappers can allocate memory from that cache.
17552272c92SMike Rapoport
176ae65a521SVlastimil BabkaWhen the allocated memory is no longer needed it must be freed.
177ae65a521SVlastimil Babka
178ae65a521SVlastimil BabkaObjects allocated by `kmalloc` can be freed by `kfree` or `kvfree`. Objects
179ae65a521SVlastimil Babkaallocated by `kmem_cache_alloc` can be freed with `kmem_cache_free`, `kfree`
180ae65a521SVlastimil Babkaor `kvfree`, where the latter two might be more convenient thanks to not
181ae65a521SVlastimil Babkaneeding the kmem_cache pointer.
182ae65a521SVlastimil Babka
183ae65a521SVlastimil BabkaThe same rules apply to _bulk and _rcu flavors of freeing functions.
184ae65a521SVlastimil Babka
185ae65a521SVlastimil BabkaMemory allocated by `vmalloc` can be freed with `vfree` or `kvfree`.
186ae65a521SVlastimil BabkaMemory allocated by `kvmalloc` can be freed with `kvfree`.
187ae65a521SVlastimil BabkaCaches created by `kmem_cache_create` should be freed with
188ae65a521SVlastimil Babka`kmem_cache_destroy` only after freeing all the allocated objects first.
189