Linux Kernel Architecture

(Jacob Rumans) #1

Chapter3:MemoryManagement


Destroying Caches


Thekmem_cache_destroyfunction must be invoked to destroy a complete cache in which there are
only unused objects. This function is needed primarily when removing modules that want to return all
memory space allocated to them.^36

Since the implementation itself reveals nothing new, we will confine ourselves to outlining the main steps
needed to remove a cache:

❑ The slabs on theslabs_freelist are scanned successively. The destructor is first invoked for
each object on each slab, and then the slab memory space is returned to the buddy system.
❑ The memory space for the per-CPU caches is freed.
❑ The data are removed from thecache_cachelist.

3.6.5 General Caches


Thekmallocandkfreefunctions must be used to allocate and free memory in the classic sense rather
than objects. These are the kernel equivalents to themallocandfreefunctions from the C standard
library in userspace.^37

I have already noted several times thatkmallocandkfreeare implemented as slab allocator front-ends
and mimic the semantics ofmalloc/freeas best they can. We can therefore deal with their implementa-
tion succinctly.

Implementationofkmalloc


Thebaseofkmallocis an array that groups slab caches for memory areas of graded sizes. The array
entries are instances of thecache_sizesdata structure that is defined as follows:

<slab_def.h>
struct cache_sizes {
size_t cs_size;
kmem_cache_t *cs_cachep;
kmem_cache_t *cs_dmacachep;
#ifdef CONFIG_ZONE_DMA
struct kmem_cache *cs_dmacachep;
#endif
}

sizespecifies the size of the memory area for which the entry is responsible. There are two slab caches
for each size, one of which supplies DMA-suitable memory.

The statically definedmalloc_sizesarray groups the available sizes essentially using powers of 2
between 2^5 =32 and 2^25 =131, 072, depending on the setting ofKMALLOC_MAX_SIZEas discussed above.

(^36) This is not mandatory. If a module wants to obtain persistent memory that is preserved between unloading a module and reload-
ing the next time (assuming, of course, that the system is not rebooted in the meantime), it can retain a cache so that the data it
contains are available for reuse.
(^37) Use ofprintk,kmallocandkfreein userspace programs is an unmistakable sign of too much contact with kernel
programming.

Free download pdf