もともと、Linux Kernelのソースコードの一部なので、GPLv2扱いになる(はずの認識)。
https://www.kernel.org/doc/html/latest/index.html
Licensing documentation
The following describes the license of the Linux kernel source code (GPLv2), how to properly mark the license of individual files in the source tree, as well as links to the full license text.
https://www.kernel.org/doc/html/latest/process/license-rules.html#kernel-licensing
Memory Allocation Guide
Linux provides a variety of APIs for memory allocation. You can allocate small chunks using
kmalloc
orkmem_cache_alloc
families, large virtually contiguous areas usingvmalloc
and its derivatives, or you can directly request pages from the page allocator withalloc_pages
. It is also possible to use more specialized allocators, for instancecma_alloc
orzs_malloc
.
Linuxはメモリ確保のために様々なAPIを提供しています。小さいチャンクを確保する場合には、kmalloc
やkmem_cache_alloc
familiyを用いることができます。vmalloc
とその派生を利用すると、大きな仮想的連続領域を確保できます。また、alloc_pages
を用いるとpage allocatorから直接ページを要求することもできます。また、更に特別なallocatorとして、sma_alloc
やzs_malloc
などを用いることもできます。
.
Most of the memory allocation APIs use GFP flags to express how that memory should be allocated. The GFP acronym stands for "get free pages", the underlying memory allocation function.
ほとんどのメモリ割り当てAPIでは、GFP flagを利用して、そのメモリの割り当て方法を表現しています。GFPという語は、基になるメモリ割り当て機能である"get free pages"の略です。
.
Diversity of the allocation APIs combined with the numerous GFP flags makes the question "How should I allocate memory?" not that easy to answer, although very likely you should use 'kzalloc(, GFP_KERNEL);'
多数のGFPフラグと組み合わせられた割り当てAPIが多様化しているため、"どのメモリ確保関数を使えばいいのか?」を答えるのは簡単ではありませんが、おそらず、kzalloc(<size>, GFP_KERNEL)」
が利用できるでしょう。
Of course there are cases when other allocation APIs and different GFP flags must be used.
もちろん、他の割り当てAPIと異なるGFPフラグを使用する必要がある場合もあります。
Get Free Page flags
The GFP flags control the allocators behavior. They tell what memory zones can be used, how hard the allocator should try to find free memory, whether the memory can be accessed by the userspace etc. The
Documentation/core-api/mm-api.rst <mm-api-gfp-flags>
provides reference documentation for the GFP flags and their combinations and here we briefly outline their recommended usage:
GFP flagは、allocatorの動作を制御します。使用できるメモリゾーン、アロケータがどのように空きメモリを探そうとするのか、アロケータが空きメモリを探すのにどれだけ苦労するのか、メモリがユーザースペースからアクセスできるのかなどを表現します。Documentation/core-api/mm-api.rst <mm-api-gfp-flags>
には、GFP glagsに関するリファレンスドキュメントと、それらの組み合わせ方法、更に、推奨される使い方のアウトラインなどが提供されます。
.
- Most of the time
GFP_KERNEL
is what you need. Memory for the kernel data structures, DMAable memory, inode cache, all these and many other allocations types can useGFP_KERNEL
. Note, that usingGFP_KERNEL
impliesGFP_RECLAIM
, which means that direct reclaim may be triggered under memory pressure; the calling context must be allowed to sleep.
- ほとんどの場合、あなたにとって必要なのは
GFP_KERNEL
です。カーネルデータ構造、DMAで処理可能なメモリ、inode cache、その他全部のaallocation typeでは、GFP_KERNEL‘を用いることができます。‘GFP_KERNEL
を用いる事は、‘GFP_RECLAIM`を意味する事に注意してください。これは、メモリー不足の状態では、直接再利用がトリガーされる可能性があることを意味します。呼び出しているコンテキストはスリープすることが許可されている必要があります。
- If the allocation is performed from an atomic context, e.g interrupt handler, use
GFP_NOWAIT
. This flag prevents direct reclaim and IO or filesystem operations. Consequently, under memory pressureGFP_NOWAIT
allocation is likely to fail. Allocations which have a reasonable fallback should be usingGFP_NOWARN
.
- allocatorがatomic context上で動作するのであれば、例えば割り込みハンドラー等の場合、
GFP_NOWAIT
を利用してください。このフラグは、直接再利用やIO, ファイルシステム操作を防ぎます。その結果、メモリ不足の状態では、「GFP_NOWAIT」の割り当てに失敗するかもしれません。適切なフォールバックがある割り当てでは、GFP_NOWARM
を使用する必要があります。
- If you think that accessing memory reserves is justified and the kernel will be stressed unless allocation succeeds, you may use
GFP_ATOMIC
.
- メモリ予約のアクセスが正当化され、カーネルにストレスがかからないという場合においては、
GFP_ATOMIC
を用いることもできます。
- Untrusted allocations triggered from userspace should be a subject of kmem accounting and must have
__GFP_ACCOUNT
bit set. There is the handyGFP_KERNEL_ACCOUNT
shortcut forGFP_KERNEL
allocations that should be accounted.
- ユーザースペースからトリガーされた、信用ならない割り当てについては、kmem accountingの対象とする必要があり、
__GPF_ACCOUNT
bitが必要です。GFP_KERNEL_ACCOUNT
ショートカットは、GFP_KERNEL
割り当てのときに便利です。
- Userspace allocations should use either of the
GFP_USER
,
GFP_HIGHUSER
orGFP_HIGHUSER_MOVABLE
flags. The longer the flag name the less restrictive it is.
GFP_HIGHUSER_MOVABLE
does not require that allocated memory will be directly accessible by the kernel and implies that the data is movable.
GFP_HIGHUSER
means that the allocated memory is not movable, but it is not required to be directly accessible by the kernel. An example may be a hardware allocation that maps data directly into userspace but has no addressing limitations.
GFP_USER
means that the allocated memory is not movable and it must be directly accessible by the kernel.
- ユーザースペースの確保には、
GFP_USER
,GFTP_HIGHUSER{
あるいは、GFP_HIGHUSER_MOVABLE
flagを用います。長いフラグ名ほど、制限が緩和されます。
‘GFP_HIGHUSER_MOVALBLEは、kernelから確保されたメモリへの直接参照を要求せず、dataは可搬性があります。
GHP_HIGHUSERは、確保したデータは可搬性がないが、カーネルから直接アクセスされることもありません。例えば、ハードウェアallocationによって、userspaceが直接マッピングされたが、addressingに制限がないような場合です。‘GFP_USER
は、確保されたメモリは可搬性もなく、kernelが直接参照することを意味します。
You may notice that quite a few allocations in the existing code specify GFP_NOIO
or GFP_NOFS
. Historically, they were used to prevent recursion deadlocks caused by direct memory reclaim calling back into the FS or IO paths and blocking on already held resources. Since 4.12 the preferred way to address this issue is to use new scope APIs described in
Documentation/core-api/gfp_mask-from-fs-io.rst <gfp_mask_from_fs_io>
.
既に存在するコードにおいて、特にGFP_NOIO
やGFP_NOFS
が存在するいくつかのallocationを見つけることができるかもしれません。歴史的には、それらはFSやIOパスへの直接的なメモリ再利用コールバックと、すでに保持されているリソースのブロックによって引き起こされる再帰的デッドロックを防止するために使用されていました。4.12以後、この問題に対処するための推奨方法については、Documentation/core-api/gfp_mask-from-fs-io.rst <gfp_mask_from_fs_io>
.に記載されている新しいscope APIを用いる事です。
.
Other legacy GFP flags are
GFP_DMA
andGFP_DMA32
. They are used to ensure that the allocated memory is accessible by hardware with limited addressing capabilities. So unless you are writing a driver for a device with such restrictions, avoid using these flags. And even with hardware with restrictions it is preferable to usedma_alloc*
APIs.
その他のレガシーGFPフラグは「GFP_DMA」および「GFP_DMA32」です。 それらは、割り当てられたメモリが、限定されたアドレス指定機能を持つハードウェアからアクセス可能であることを保証するために使用されます。 したがって、そのような制限のあるデバイス用のドライバーを作成しているのでない限り、これらのフラグの使用は避けてください。 また、ハードウェアに制限がある場合でも、 dma_alloc *
APIを使用することをお勧めします。
Selecting memory allocator
The most straightforward way to allocate memory is to use a function from the kmalloc() family. And, to be on the safe side it's best to use routines that set memory to zero, like kzalloc(). If you need to allocate memory for an array, there are kmalloc_array() and kcalloc() helpers. The helpers struct_size(), array_size() and array3_size() can be used to safely calculate object sizes without overflowing.
メモリを割り当てる最も簡単な方法は、kmalloc()ファミリーの関数を使用することです。安全のために、kzalloc()のようにメモリをゼロに設定するルーチンを使用するのが最善です。配列にメモリを割り当てる必要がある場合は、kmalloc_array()およびkcalloc()ヘルパーを利用することもできます。gヘルパーは、struct_size()、array_size()、array3_size()を使用して、オーバーフローすることなくオブジェクトサイズを安全に計算できます。
.
The maximal size of a chunk that can be allocated with
kmalloc
is limited. The actual limit depends on the hardware and the kernel configuration, but it is a good practice to usekmalloc
for objects smaller than page size.
kmalloc
で割り当て可能なチャンクの最大サイズには制限があります。 実際の制限はハードウェアとカーネル構成によって異なりますが、ページサイズより小さいオブジェクトには「kmalloc」を使用することをお勧めします。
.
The address of a chunk allocated with
kmalloc
is aligned to at least ARCH_KMALLOC_MINALIGN bytes. For sizes which are a power of two, the alignment is also guaranteed to be at least the respective size.
kmalloc
で割り当てられたチャンクのアドレスは、少なくともARCH_KMALLOC_MINALIGNバイトに揃えられます。 2の累乗のサイズの場合、配置は少なくともそれぞれのサイズであることが保証されます。
.
For large allocations you can use vmalloc() and vzalloc(), or directly request pages from the page allocator. The memory allocated by
vmalloc
and related functions is not physically contiguous.
大きな割り当ての場合は、vmalloc()とvzalloc()を使用するか、ページアロケータから直接ページを要求できます。 vmalloc
と関連する関数によって割り当てられたメモリは、物理的に連続していません。
.
If you are not sure whether the allocation size is too large for
kmalloc
, it is possible to use kvmalloc() and its derivatives. It will try to allocate memory withkmalloc
and if the allocation fails it will be retried withvmalloc
. There are restrictions on which GFP flags can be used withkvmalloc
; please see kvmalloc_node() reference documentation. Note thatkvmalloc
may return memory that is not physically contiguous.
割り当てサイズが「kmalloc」に対して大きすぎるかどうかわからない場合、kvmalloc()とその派生クラスを使用できます。 kmalloc
でメモリを割り当てようとし、割り当てが失敗した場合は vmalloc
で再試行されます。 kvmalloc
で使用できるGFPフラグには制限があります。 kvmalloc_node()のリファレンスドキュメントをご覧ください。 kvmalloc
では物理的に連続していないメモリを返す可能性があることに注意してください。
If you need to allocate many identical objects you can use the slab cache allocator. The cache should be set up with kmem_cache_create() or kmem_cache_create_usercopy() before it can be used. The second function should be used if a part of the cache might be copied to the userspace. After the cache is created kmem_cache_alloc() and its convenience wrappers can allocate memory from that cache.
同一のオブジェクトを多数割り当てる必要がある場合は、slab cache allocatorが利用できます。キャッシュは利用する前に、kmem_cache_create()やkmem_cache_create_usercopy()で設定する必要があります。2番目の関数は、キャッシュの一部がユーザースペースにコピーされる可能性がある場合に使用する必要があります。キャッシュが作成された後、kmem_cache_alloc()と便利なラッパー関数は、キャッシュからメモリを割り当てることができます。
When the allocated memory is no longer needed it must be freed. You can use kvfree() for the memory allocated with
kmalloc
,vmalloc
andkvmalloc
. The slab caches should be freed with kmem_cache_free(). And don't forget to destroy the cache with kmem_cache_destroy().
割り当てたメモリが不要になったら、解放する必要がありまsう。kmalloc
, vmalloc
そして、kvmalloc
で確保したメモリには、kvfree()
を使うことができます。slab cacheは、kmem_cache_free()によってfreeできます。また、kmem_cache_destroy()によってキャッシュを破壊する事も忘れないでください。