Saturday, April 28, 2012

Heap and Stacks

Each program has at least 2 stacks - a user stack and a kernel stack.  Kernel stack is used when user program switch into kernel mode (like making a system call).  Kernel stack operates (growth direction, stack point usage, local variable usage) same way as user stack.  There are slight difference for example, kernel stack is usually limit in size (e.g. 4K or 8K in x86) and thus kernel programming uses as few local variables as possible.  Also stacks of all processes reside in the same kernel address space but in different virtual addresses.

The baisc unit of memory that kernel manages is a physical page frame which never smaller than 4K.  Using the physical page allocator is inefficient for allocating space for small objects and buffers.  In addition, these small objects usually have a short life time and will hit system performance.  Modern OS will use a separated kernel-level memory allocator that communicate with the physical page allocator and is optimized for fast and contiuous allocation and de-allocation of small objects.  This allocator is a consumer of the physical page allocator, in that it ask for pages from the physical page allocator and returns them.  Each page is divided into a number of fixed-length chumk called slabs (from the slab allocator in SUN OS).  Pages containing objects of same size are grouped together and called a cache.

The slab allocator also must keep track of the states of objects in the cache too so that space can be reclaimed.  The reclamation is done by specific function.

Object allocator usually contains mechanism to detect overflow corruption called redzoning.  An arbitrary value will be written at the end of chunk and is checked at release time.  However, this will degrade performance and thus turned off by default.

No comments: