Kernel Korner - Allocating Memory in the Kernel
With a little understanding, getting a hold of memory in the kernel is demystified and not too much more difficult to do than it is in user space. A few simple rules of thumb can go a long way:
Decide whether you can sleep (that is, whether the call to kmalloc() can block). If you are in an interrupt handler, in a bottom half, or if you hold a lock, you cannot. If you are in process context and do not hold a lock, you probably can.
If you can sleep, specify GFP_KERNEL.
If you cannot sleep, specify GFP_ATOMIC.
If you need DMA-capable memory (for example, for an ISA or broken PCI device), specify GFP_DMA.
Always check for and handle a NULL return value from kmalloc().
Do not leak memory; make sure you call kfree() somewhere.
Ensure that you do not race and call kfree() multiple times and that you never access a block of memory after you free it.
For more information, check out these files in your kernel source tree.
include/linux/gfp.h: home of the allocation flags.
include/linux/slab.h: definitions of kmalloc(), et al.
mm/page_alloc.c: page allocation functions.
mm/slab.c: implementation of kmalloc(), et al.
Robert Love (email@example.com) is a kernel hacker at MontaVista Software and a student at the University of Florida. He is the author of Linux Kernel Development. Robert enjoys fine wine and lives in Gainesville, Florida.
|Geek Hide-away in Guatemala - Stay for Free!||Nov 26, 2015|
|Microsoft and Linux: True Romance or Toxic Love?||Nov 25, 2015|
|Non-Linux FOSS: Install Windows? Yeah, Open Source Can Do That.||Nov 24, 2015|
|Cipher Security: How to harden TLS and SSH||Nov 23, 2015|
|Web Stores Held Hostage||Nov 19, 2015|
|diff -u: What's New in Kernel Development||Nov 17, 2015|
- Cipher Security: How to harden TLS and SSH
- Microsoft and Linux: True Romance or Toxic Love?
- Non-Linux FOSS: Install Windows? Yeah, Open Source Can Do That.
- Geek Hide-away in Guatemala - Stay for Free!
- Firefox's New Feature for Tighter Security
- Web Stores Held Hostage
- PuppetLabs Introduces Application Orchestration
- It's a Bird. It's Another Bird!
- diff -u: What's New in Kernel Development
- IBM LinuxONE Provides New Options for Linux Deployment