debonair
debonair

Reputation: 2593

Difference between kmalloc and kmem_cache_alloc

What is difference between kmem_cache_alloc and kmalloc() in kernel memory allocation? which one is used when?

Upvotes: 17

Views: 15029

Answers (2)

alex
alex

Reputation: 1461

kmalloc: It uses the generic slab caches available to any kernel code. so your module will share slab cache with other components in kernel.

kmem_cache_alloc: It will allocate objects from a dedicated slab cache created by kmem_cache_create. If you specifically want a better slab cache management dedicated to your module only, that too for a specific type of objects, use kmem_cache_create followed by kmem_cache_alloc. USB/SCSI drivers use this. kmem_cache_create takes sizeof your object you want to create slab of, a name which appears in /proc/slabinfo and flags to govern behavior of your slab cache.

Ref: https://www.mail-archive.com/[email protected]/msg13191.html & LDD

Upvotes: 6

brokenfoot
brokenfoot

Reputation: 11609

Kmalloc - allocates contiguous region from the physical memory. But keep in mind, allocating and free'ing memory is a lot of work.

Kmem_cache_alloc - Here, your process keeps some copies of the some pre-defined size objects pre-allocated. Say you have struct that you know you will be requiring very frequently, so instead of allocating it from the main memory (kmalloc) when you need it, you already keep multiple copies of it allocated & when you want it, it returns the address of the block already allocated (saves a lot of time). Similarly, when you free it, you don't give it back, it actually isn't free'd, it goes back to the allocated pool so that if some process again asks for it, you can return this address of the already allocated struct.

Upvotes: 13

Related Questions