1.. _memory_allocation: 2 3======================= 4Memory Allocation Guide 5======================= 6 7Linux provides a variety of APIs for memory allocation. You can 8allocate small chunks using `kmalloc` or `kmem_cache_alloc` families, 9large virtually contiguous areas using `vmalloc` and its derivatives, 10or you can directly request pages from the page allocator with 11`alloc_pages`. It is also possible to use more specialized allocators, 12for instance `cma_alloc` or `zs_malloc`. 13 14Most of the memory allocation APIs use GFP flags to express how that 15memory should be allocated. The GFP acronym stands for "get free 16pages", the underlying memory allocation function. 17 18Diversity of the allocation APIs combined with the numerous GFP flags 19makes the question "How should I allocate memory?" not that easy to 20answer, although very likely you should use 21 22:: 23 24 kzalloc_obj(<VAR_OR_TYPE>); 25 26if you need memory for an object and 27 28:: 29 30 kzalloc(<size>, GFP_KERNEL); 31 32if you need memory for a buffer. 33 34Of course there are cases when other allocation APIs and different GFP 35flags must be used. 36 37Get Free Page flags 38=================== 39 40The GFP flags control the allocators behavior. They tell what memory 41zones can be used, how hard the allocator should try to find free 42memory, whether the memory can be accessed by the userspace etc. The 43:ref:`Documentation/core-api/mm-api.rst <mm-api-gfp-flags>` provides 44reference documentation for the GFP flags and their combinations and 45here we briefly outline their recommended usage: 46 47 * Most of the time ``GFP_KERNEL`` is what you need. Memory for the 48 kernel data structures, DMAable memory, inode cache, all these and 49 many other allocations types can use ``GFP_KERNEL``. Note, that 50 using ``GFP_KERNEL`` implies ``GFP_RECLAIM``, which means that 51 direct reclaim may be triggered under memory pressure; the calling 52 context must be allowed to sleep. 53 * If the allocation is performed from an atomic context, e.g interrupt 54 handler, use ``GFP_NOWAIT``. This flag prevents direct reclaim and 55 IO or filesystem operations. Consequently, under memory pressure 56 ``GFP_NOWAIT`` allocation is likely to fail. Users of this flag need 57 to provide a suitable fallback to cope with such failures where 58 appropriate. 59 * If you think that accessing memory reserves is justified and the kernel 60 will be stressed unless allocation succeeds, you may use ``GFP_ATOMIC``. 61 * Untrusted allocations triggered from userspace should be a subject 62 of kmem accounting and must have ``__GFP_ACCOUNT`` bit set. There 63 is the handy ``GFP_KERNEL_ACCOUNT`` shortcut for ``GFP_KERNEL`` 64 allocations that should be accounted. 65 * Userspace allocations should use either of the ``GFP_USER``, 66 ``GFP_HIGHUSER`` or ``GFP_HIGHUSER_MOVABLE`` flags. The longer 67 the flag name the less restrictive it is. 68 69 ``GFP_HIGHUSER_MOVABLE`` does not require that allocated memory 70 will be directly accessible by the kernel and implies that the 71 data is movable. 72 73 ``GFP_HIGHUSER`` means that the allocated memory is not movable, 74 but it is not required to be directly accessible by the kernel. An 75 example may be a hardware allocation that maps data directly into 76 userspace but has no addressing limitations. 77 78 ``GFP_USER`` means that the allocated memory is not movable and it 79 must be directly accessible by the kernel. 80 81You may notice that quite a few allocations in the existing code 82specify ``GFP_NOIO`` or ``GFP_NOFS``. Historically, they were used to 83prevent recursion deadlocks caused by direct memory reclaim calling 84back into the FS or IO paths and blocking on already held 85resources. Since 4.12 the preferred way to address this issue is to 86use new scope APIs described in 87:ref:`Documentation/core-api/gfp_mask-from-fs-io.rst <gfp_mask_from_fs_io>`. 88 89Other legacy GFP flags are ``GFP_DMA`` and ``GFP_DMA32``. They are 90used to ensure that the allocated memory is accessible by hardware 91with limited addressing capabilities. So unless you are writing a 92driver for a device with such restrictions, avoid using these flags. 93And even with hardware with restrictions it is preferable to use 94`dma_alloc*` APIs. 95 96GFP flags and reclaim behavior 97------------------------------ 98Memory allocations may trigger direct or background reclaim and it is 99useful to understand how hard the page allocator will try to satisfy that 100or another request. 101 102 * ``GFP_KERNEL & ~__GFP_RECLAIM`` - optimistic allocation without _any_ 103 attempt to free memory at all. The most light weight mode which even 104 doesn't kick the background reclaim. Should be used carefully because it 105 might deplete the memory and the next user might hit the more aggressive 106 reclaim. 107 108 * ``GFP_KERNEL & ~__GFP_DIRECT_RECLAIM`` (or ``GFP_NOWAIT``)- optimistic 109 allocation without any attempt to free memory from the current 110 context but can wake kswapd to reclaim memory if the zone is below 111 the low watermark. Can be used from either atomic contexts or when 112 the request is a performance optimization and there is another 113 fallback for a slow path. 114 115 * ``(GFP_KERNEL|__GFP_HIGH) & ~__GFP_DIRECT_RECLAIM`` (aka ``GFP_ATOMIC``) - 116 non sleeping allocation with an expensive fallback so it can access 117 some portion of memory reserves. Usually used from interrupt/bottom-half 118 context with an expensive slow path fallback. 119 120 * ``GFP_KERNEL`` - both background and direct reclaim are allowed and the 121 **default** page allocator behavior is used. That means that not costly 122 allocation requests are basically no-fail but there is no guarantee of 123 that behavior so failures have to be checked properly by callers 124 (e.g. OOM killer victim is allowed to fail currently). 125 126 * ``GFP_KERNEL | __GFP_NORETRY`` - overrides the default allocator behavior 127 and all allocation requests fail early rather than cause disruptive 128 reclaim (one round of reclaim in this implementation). The OOM killer 129 is not invoked. 130 131 * ``GFP_KERNEL | __GFP_RETRY_MAYFAIL`` - overrides the default allocator 132 behavior and all allocation requests try really hard. The request 133 will fail if the reclaim cannot make any progress. The OOM killer 134 won't be triggered. 135 136 * ``GFP_KERNEL | __GFP_NOFAIL`` - overrides the default allocator behavior 137 and all allocation requests will loop endlessly until they succeed. 138 This might be really dangerous especially for larger orders. 139 140Selecting memory allocator 141========================== 142 143The most straightforward way to allocate memory is to use a function 144from the kmalloc() family. And, to be on the safe side it's best to use 145routines that set memory to zero, like kzalloc(). If you need to 146allocate memory for an array, there are kmalloc_array() and kcalloc() 147helpers. The helpers struct_size(), array_size() and array3_size() can 148be used to safely calculate object sizes without overflowing. 149 150Since 7.0 there are type aware kmalloc-family helpers that let you safely and 151conveniently allocate a single object or arrays of objects with kzalloc_obj() 152and kmalloc_obj() and their array versions kzalloc_objs() and 153kmalloc_objs(). These helpers only need the type of the object that should be 154allocated and the count of elements in the array for the array versions. 155 156As of v7.2, vast majority of the memory allocations use kzalloc_obj(). 157 158The address of a chunk allocated with `kmalloc` is aligned to at least 159ARCH_KMALLOC_MINALIGN bytes. For sizes which are a power of two, the 160alignment is also guaranteed to be at least the respective size. For other 161sizes, the alignment is guaranteed to be at least the largest power-of-two 162divisor of the size. 163 164Chunks allocated with kmalloc() can be resized with krealloc(). Similarly 165to kmalloc_array(): a helper for resizing arrays is provided in the form of 166krealloc_array(). 167 168`kmalloc` always allocates physically contiguous memory and the maximal size of 169a chunk that can be allocated with `kmalloc` is limited by `KMALLOC_MAX_SIZE`, 170which matches the page allocator's MAX_PAGE_ORDER limit. 171 172Internally, the slab allocator differentiates allocations of different orders 173and delegates larger allocations to the page allocator, but for the users of 174`kmalloc` family it is entirely transparent. 175 176For large allocations that do not require physically contiguous memory you can 177use vmalloc() and vzalloc() family. 178 179If you are not sure whether the allocation size is too large for 180`kmalloc`, it is possible to use kvmalloc() and its derivatives. It will 181try to allocate memory with `kmalloc` and if the allocation fails it 182will be retried with `vmalloc`. There are restrictions on which GFP 183flags can be used with `kvmalloc`; please see kvmalloc_node() reference 184documentation. Note that `kvmalloc` may return memory that is not 185physically contiguous. 186 187If you need to allocate many identical objects you can use the slab 188cache allocator. The cache should be set up with kmem_cache_create() or 189kmem_cache_create_usercopy() before it can be used. The second function 190should be used if a part of the cache might be copied to the userspace. 191After the cache is created kmem_cache_alloc() and its convenience 192wrappers can allocate memory from that cache. 193 194When the allocated memory is no longer needed it must be freed. 195 196Objects allocated by `kmalloc` can be freed by `kfree` or `kvfree`. Objects 197allocated by `kmem_cache_alloc` can be freed with `kmem_cache_free`, `kfree` 198or `kvfree`, where the latter two might be more convenient thanks to not 199needing the kmem_cache pointer. 200 201The same rules apply to _bulk and _rcu flavors of freeing functions. 202 203Memory allocated by `vmalloc` can be freed with `vfree` or `kvfree`. 204Memory allocated by `kvmalloc` can be freed with `kvfree`. 205Caches created by `kmem_cache_create` should be freed with 206`kmem_cache_destroy` only after freeing all the allocated objects first. 207