different of linux kmalloc malloc vmmalloc

来源:互联网 发布:绿色傲剑数据 编辑:程序博客网 时间:2024/04/28 17:14

kmalloc vmalloc malloc difference?

kmalloc returns physically contiguous memory, malloc does
not guarantee anything about the physical memory mapping.
The other main difference is that kmalloc'ed memory is
reserved and locked, it cannot be swapped. malloc does not
actually allocate physical memory. Physical memory gets
mapped later, during use.
Memory is subject to fragmentation. You may have many megabytes
of free memory left, but a 8K kmalloc (on a 4k page machine)
can still fail. Things like the buddy allocator help but
can't always guarantee large unfragmented blocks.
If you don't need contiguous mapping in kernel space, you
can use vmalloc to avoid the fragmentation problem, at the
cost of some MMU overhead.
Userspace memory (via malloc) is virtual - immediately after
the call, the same non-writable zero page is mapped into every
4K block of your memory region. Only when you write to a page,
a physical memory page is mapped for you at that location.
If swap is enabled, that page may be 'borrowed' from some other
process, after the contents are deposited in the swap file.
You only need to worry about using physically contiguous memory if
the buffer will be accessed by a DMA device on a physically addressed
bus (like PCI). The trouble is that many system calls have no way to
know whether their buffer will eventually be passed to a DMA device:
once you pass the buffer to another kernel subsystem, you really cannot
know where it is going to go. Even if the kernel does not use the
buffer for DMA [i]today,[/i] a future development might do so.
vmalloc is often slower than kmalloc, because it may have to remap
the buffer space into a virtually contiguous range. kmalloc never
remaps, though if not called with GFP_ATOMIC kmalloc can block.
kmalloc is limited in the size of buffer it can provide: 128 KBytes.
If you need a really big buffer, you have to use vmalloc or some other
mechanism like reserving high memory at boot.
vmalloc() is very rarely used, because the kernel rarely uses virtual
memory. kmalloc() is what is typically used, but you have to know what
the consequences of the different flags are and you need a strategy for
dealing with what happens when it fails - particularly if you're in an
interrupt handler
kmalloc allocates physically contiguous memory, memory which
pages are laid consecutively in physical RAM. vmalloc allocates
memory which is contiguous in kernel virtual memory space (that means
pages allocated that way are not contiguous in RAM, but the kernel
sees them as one block).
kmalloc is the preffered way, as long as you don't need very big
areas. The trouble is, if you want to do DMA from/to some hardware
device, you'll need to use kmalloc, and you'll probably need bigger
chunk. The solution is to allocate memory as soon as possible, before
memory gets fragmented.

 

 

原创粉丝点击