Dynamic Memory: kmalloc() (Slideshow)

For a much greater documentation of kernel memory allocation see Mel Gorman’s wonderful guide

Dynamic Memory: kmalloc()

Kernel heap implementation

  • Similar to userspace malloc()

  • ⟶ Easy to use

#include <linux/slab.h>
#include <linux/gfp.h>

void *kmalloc(size_t size, gfp_t flags);
void *kzalloc(size_t size, gfp_t flags)
void kfree(const void *);
  • Memory internally/transparently managed as set of pages

  • Pages are not necessarily contiguous

  • size greater than page size might be more difficult to allocate

  • kzalloc() initializes memory with all zeroes

Dynamic Memory: Flags

Many flags to govern behaviour

  • GFP_KERNEL: most commonly used

    • Might block (triggers swap activity, …)

    • can only be called in process context

  • GFP_ATOMIC: for use in non-process context

    • Scarce resource

    • ⟶ use is discouraged

    • ⟶ later

Documentation

kmalloc

kfree

kzalloc