Chapter3:MemoryManagement
In addition to easily identified cache names such asunix_sock(for domain sockets, i.e., objects of type
struct unix_sock), there are other fields calledkmalloc-size. (Machines that provide DMA memory
also include caches for DMA allocations, but these are not present in the above example.) These are the
basis of thekmallocfunction in which the kernel provides slab caches for various memory sizes that, with
few exceptions, are in power-of-2 steps between 2^5 =32 (for machines with 4 KiB page size), respective
64 (for all other machines), and 2^25 bytes. The upper bound can also be considerably smaller and is set by
KMALLOC_MAX_SIZE, which, in turn, is computed based on the page size of the system and the maximally
allowed allocation order:
<slab.h>
#define KMALLOC_SHIFT_HIGH ((MAX_ORDER + PAGE_SHIFT - 1) <= 25? \
(MAX_ORDER + PAGE_SHIFT - 1) : 25)
#define KMALLOC_MAX_SIZE (1UL << KMALLOC_SHIFT_HIGH)
#define KMALLOC_MAX_ORDER (KMALLOC_SHIFT_HIGH - PAGE_SHIFT)
Each timekmallocis invoked, the kernel finds the most suitable cache and allocates one of its objects to
satisfy the request for memory as best it can (if no cache fits exactly, larger objects are always allocated
but never smaller objects).
The difference between the slab allocator and cache outlined above quickly disappears in the concrete
implementation, so much so that both terms are used synonymously in the further course of the book.
Section 3.6.5 looks at the details ofkmallocafter discussing the implementation of the slab allocator.
3.6.3 The Principle of Slab Allocation
The slab allocator is made up of a closely interwoven network of data and memory structures that is not
easy to untangle at first sight. It is therefore important to obtain an overview of the relationships between
the structures before moving on to examine the implementation.
Basically, the slab cache consists of the two components shown in Figure 3-44: a cache object to hold the
management data and slabs to hold the managed objects.
Each cache is responsible for just one object type, instances ofstruct unix_sock, for example, or general
buffers. The number of slabs in each cache varies according to the number of pages used, the object size,
and the number of objects managed. Section 3.6.4 goes into the details of how cache sizes are calculated.
All caches in the system are also kept in a doubly linked list. This gives the kernel the opportunity to
traverse all caches one after the other; this is necessary, for example, when shrinking cache memory
because of an impending memory shortage.
Fine Structureof the Cache
If we look more closely at the cache structure, we note further details of importance. Figure 3-45 provides
an overview of the cache components.