Kernel Korner - Allocating Memory in the Kernel

In this article, Robert offers a refresher on kernel memory allocation and how it has changed for the 2.6 kernel.
Conclusion

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.

Robert Love (rml@tech9.net) 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.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Kernel flags

Anonymous's picture

Hi, i see in my aircraft linux system flag 7 and flag 0 from 2 different kernel versions. What are they? Pls help. Thks

Free Dummies Books
Continuous Engineering

Learn:

  • What continuous engineering is
  • How to continuously improve complex product designs
  • How to anticipate and respond to markets and clients
  • How to get the most out of your engineering resources

Get your free book now

Sponsored by IBM

Free Dummies Books
Service Virtualization

Learn to:

  • Define service virtualization
  • Select the most beneficial services to virtualize
  • Improve your traditional approach to testing
  • Deliver higher-quality software faster

Get your free book now

Sponsored by IBM