Chapter 7. Getting Hold of Memory

Until now, we have always used kmalloc and kfree for memory allocation. However, sticking to these functions would be a simplistic approach to managing memory. This chapter describes other allocation techniques. We’re not interested yet in how the different architectures actually administer memory. Modules are not involved in issues of segmentation, paging, and so on, since the kernel offers a unified memory-management interface to the drivers. In addition, I won’t describe the internal details of memory management in this chapter, but will defer it to Section 13.1, in Chapter 13.

The Real Story of kmalloc

The kmalloc allocation engine is a powerful tool, and easily learned due to its similarity to malloc. The function is fast--unless it blocks--and it doesn’t clear the memory it obtains; the allocated region still holds its previous content. In the next few sections, I’ll talk in detail about kmalloc, so you can compare it to the memory allocation techniques that I’ll discuss later.

The Priority Argument

The first argument to kmalloc is the size, which I’ll talk about in the next section. The second argument, the priority, is much more interesting, because it causes kmalloc to modify its behavior when it has difficulty finding a page.

The most-used priority, GFP_KERNEL, means that the allocation (internally performed by calling get_free_pages, which explains the name) is performed on behalf of a process running in kernel space. In other words, ...

Get Linux Device Drivers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.