Chapter3:MemoryManagement
cachep = __find_general_cachep(size, flags);
if (unlikely(ZERO_OR_NULL_PTR(cachep)))
return NULL;
return __cache_alloc(cachep, flags);
}
Once__find_general_cachephas found a suitable cache (it iterates over all possiblekmallocsizes
to find a matching cache), the heavy work is delegated to the__cache_allocfunction discussed
above.
Implementationofkfree
kfreeis likewise easy to implement:
mm/slab.c
void kfree(const void *objp)
{
kmem_cache_t *c;
unsigned long flags;
if (unlikely(ZERO_OR_NULL_PTR(objp)))
return;
c = virt_to_cache(objp));
__cache_free(c, (void*)objp);
}
kfreehands over the actual work to the__cache_freefunction also discussed above once the cache
associated with the memory pointer has been found.
3.7 Processor Cache and TLB Control
Caches are crucial in terms of overall system performance, which is why the kernel tries to exploit them
as effectively as possible. It does this primarily by skillfully aligning kernel data in memory. A judicious
mix of normal functions, inline definitions, and macros also helps extract greater performance from the
processor. The compiler optimizations discussed in Appendix C also make their contribution.
However, the above aspects affect the cache only indirectly. Use of the correct alignment for a data
structuredoes indeedhave an effect on the cache but only implicitly — active control of the processor
cache is not necessary.
Nevertheless, the kernel features some commands that act directly on the cache and the TLB of the pro-
cessor. However, they are not intended to boost system efficiency but to maintain the cachecontentsin a
consistent state and to ensure that no entries are incorrect and out-of-date. For example, when a mapping
is removed from the address space of a process, the kernel is responsible for removing the corresponding
entries from the TLBs. If it failed to do so and new data were added at the position previously occupied
by the mapping, a read or write operation to the virtual address would be redirected to the incorrect
location in physical memory.
The hardware implementation of caches and TLBs differs significantly from architecture to architecture.
The kernel must therefore create a view on TLBs and caches that takes adequate account of the different
approaches without neglecting the specific properties of each architecture.