Linux Kernel – Implications of Using Pointers

gcclinuxlinux-kernelpointers

So far I was under the perspective that while working in the kernel code, working with memory implies working with long integers and not pointers because dereferencing pointers shouldn't be done in the kernel code:

A quote on the topic from LDD3:

Although, conceptually, addresses are pointers, memory administration
is often better accomplished by using an unsigned integer type; the
kernel treats physical memory like a huge array, and a memory address
is just an indexinto the array. Furthermore, a pointer is easily
dereferenced; when dealing directly with memory addresses, you
almost never want to dereference them in this manner. Using an integer
type prevents this dereferencing, thus avoiding bugs. Therefore,
generic memory addresses in the kernel are usually unsigned long ,
exploiting the fact that pointers and long integers are always the
same size, at least on all the platforms currently supported by Linux.

However, I see that there are pointers (source)

char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);

And I'm successful at dereferencing them and getting expected results:

printk(KERN_INFO "%s:%i  %x \n", __FILE__, __LINE__,*hwbuf);

Questions:

  1. What memory address is allocated when char *hwbuf s run in
    the kernel? When I say "what memory" I mean if the address is an actual physical address in RAM or something else?
  2. Is it sensible that different parts of the kernel act differently on pointer dereferencing given the relationship that code has on MMU initialization? By this I mean early kernel code deals with physical addresses, driver code deals with some form of virtual addresses?
  3. What are the basis for not dereferencing pointers in kernel code?

Best Answer

There's a key difference between managing memory as a resource (when you don't care what's inside and shouldn't even look), and using memory to do something else (when the contents are the whole point).

... memory administration is often better accomplished ...

The quote is talking about managing memory addressing and maps, where you're treating memory as some opaque resource to be managed.

The code you posted isn't managing memory as a resource, it's using some memory to do non-memory-management-related stuff (specifically DMA to an audio device).

Related Topic