Linux Kernel Architecture

(Jacob Rumans) #1

Chapter3:MemoryManagement


Physical page frames

Generic kernel code

Buddy system

Standard
Slab, slob, or interface
slub allocator

Convenience
functions

Figure 3-43: Connection between the
buddy system, general-purpose
allocators, and the interface to
generic kernel code.

3.6.2 Memory Management in the Kernel


The general allocation and freeing functions of the kernel have similar names to their equivalents in the
C standard library and are employed in exactly the same way.

❑ kmalloc(size, flags)reserves a memory area ofsizebytes and returns avoidpointer to the
start of the area. If insufficient memory is available (a very improbable situation in the kernel but
one that must always be catered for), a null pointer is the result.
Theflagsargument specifies the area from which memory is to be selected using theGFP_con-
stants discussed in Section 3.5.4, for example,GFP_DMAfor a DMA-suitable memory area.
❑ kfree{*ptr}frees the memory area pointed at by*ptr.

In contrast to the situation in userspace programming, the kernel also includes thepercpu_allocand
percpu_freefunctions to reserve and free the desired memory area for each system CPU (andnotspecif-
ically for the CPU currently active).^27

kmallocis used at thousands of places in the kernel sources, but the pattern is always the same. The
memory area reserved withkmallocis converted to the correct type by means of a typecast and is then
assigned to a pointer variable.

info = (struct cdrom_info *) kmalloc (sizeof (struct cdrom_info), GFP_KERNEL);

The task of setting up and using caches is not especially difficult from the programmer’s point of view. A
suitable cache must first be created withkmem_cache_create, then the objects it contains can be allocated

(^27) Older kernel versions have used the functionsalloc_percpuandfree_percpufor this purpose, but since these functions do
not support CPU hotplugging, they are only supported for compatibility reasons and should not be used in new code.

Free download pdf