Kmalloc And Malloc Memory Allocation

What are the different issues involved in kernel memory allocation vs user space memory allocation?
ie, how different (logically) would kmalloc be versus malloc?

Some thoughts that come to mind are:

* Kernel time is highly contended, so time of allocation is a real issue (slab cache helps in this?)
* Kernel memory is precious, so not much memory should be wasted (via fragmentation etc)
* Also most kernel memory allocations come in fixed sized chunks, and here too the slab cache helps by caching unused but not garbage collected chunks of memory

For user space (malloc of libc), how is allocation done? Does this use the buddy allocation method (or is it for the kernel). Or just the UNIX style free list and in-use list is maintained?

Answer:

Yes, but you should not care too much about it unless you are trying to write your own kmalloc()/malloc() clone function because kmalloc is for kernel space and malloc is for user land.

Keep in mind that each function use its own header file, one inside the kernel source tree and the other one inside the /usr/include.

Why don't you take a look at both functions?

There are two major differences:

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.

Have a Unix Problem
Unix Forum - Do you have a UNIX Question?

Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books

Return to : - Unix System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.