Sunday, 14 February 2016

SL[OAU]B Allocator in linux Kernel

In linux kernel many kernel structures are created and destroyed in run time span of the kernel.
Without any special handling of  memory allocation/free for these very commonly used structures, over period of time, it will lead to memory fragmentation. Due to memory fragmentation it becomes difficult to get free contiguous memory of large size.

To avoid the above situation, pool of memory can be reserved which is used to allocate memory for these frequenctly used kernel strcutures. Remaining part of main memory remains unfragmented that can be used for catering the memory request of larger sizes..

SL[OAU] Allocator is framework provided by the linux kernel to facilatate the above goal.
It allowes to reserve pool of memory which will be used to cater the memory reqeust for structures(objects) of different sizes.


SLAB is contiguous free memory of 1 or more physical pages. It is used to allocate memory for particuler structure only for which it is created.
Ex. Slab for object 'struct task' is used to allocate memory request only for type 'struct task', not for any other types or size. When same allocated memory is freed, it is returned back to the same slab.
If the page size is 4KB, size of 'struct task' is 1KB, this slab can allocated memory for 4 objects of 'struct task'

SLAB Allocator:
 > It stores the meta data at the beginning of the page. Meta data contains the details of the free objects
 > After the metadat, slab objects are allocated.
 > If the page becomes full, new page is requested from main memory pool and this new page is used for new allocations
 > Any of the page of the slab becomes free, same can be returned to main memory pool for critical situations

Slab can full, partial full or empty.

Slab Allocator use cache colouring to maximise the HW cache performance.Cache Colouring means slabs leave small amount of memory of size which is in multiple of cache line size. After this space objects are allocated.
This essentially means that  different objects from multiple slabs do not map to same cache line
They occupy different cache lines and it will lead to more cache hits.


How Cache 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.
Kmalloc - allocates contiguous region from the physical memory. But keep in mind, allocating and free'ing memory is a lot of work.

No comments:

Post a Comment