Linux uses a rather complicated(for me) driver model, which is built upon the kobject abstratction. There’s a lot of documentation about the linux driver model, and describing it in detail is out of the scope of this post(well, actually I can’t do it : P ).

In short:
kobjects are structs that hold some information(a name, a reference count, a parent pointer etc), and are usually embedded into other structs, typically structs for devices/device drivers(ie struct cdev, for a character device), creating a hieararchy which is ‘exported’ to userspace through the sysfs(mounted on /sys).
The question is how the code that works with kobjects can reference the struct that contains the kobject. The kernel provides a macro, (not surprisingly) called container_of, which does exactly that.
The definition of the macro can be found in include/linux/kernel.h:

/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})

In order to understand what this macro does, we have to be somewhat familiar with the C Preprocessor, and some non-standard GCC extensions:
1)A parenthesis followed by a brace. This is called by the GCC statement expression. It lets us use a compound statement as an expression. Here, we want to use the container_of macro as an expression, but we want to declare a local variable(__mptr) inside the macro, so we need a compound statement.
2)The typeof GCC extension that lets us refer to the type of an expression, and can be used to declare variables.

The previous two extensions let us write safe macros(ie side effects of the operands are calculated only once) that work for any type(some kind of polymorphism), and can be used as expressions.

This macro also uses the offsetof, which computes the byte offset of a field within a structure. Linux uses the compiler-provided offsetof, if the compiler provides one, else it defines the offsetof macro as

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

A few words about offsetof. offsetof is a valid ANSI C macro. Cfaq gives a possible implementation of offsetof(though non-portable) which is a bit different than the one that the kernel defines. I’m not sure about this, but as far as I can understand, the cfaq offsetof subtracts a NULL pointer from the ((type *)0)->member, to ensure that the offset is correct, even if the internal representation of the NULL pointers isn’t actually zero. I guess Linux has good reasons to assume that’s OK to ommit that subtraction.

And the last trick is the ((type *)0) cast. Actually, we pretend that there’s an instance of the struct at address 0. If we tried to reference it, we would be in big trouble, but that never happens. So we trick the compiler and we can legally get the type of the struct member, which is used to declare the __mptr as a pointer to that struct member. It’s also used by offsetof to get the byte offset of the mebmer within the struct(since it uses as a ‘base address’ for the struct the address 0).

Now we can understand(at least partially) what the macro does. It declares a pointer to the member of the struct that ptr points to, and assigns ptr to it. Now __mptr points to the same address as ptr. Then it gets the offset of that mebmer within the struct, and subtracts it from the actual address of the member of the struct ‘instance’(ie __mptr). The (char *)__mptr cast is necessary, so that ‘pointer arithmetic’ will work as intended, ie subtract from __mptr exactly the (size_t) bytes that offsetof ‘returns’.

At this point, I really can’t understand why we couldn’t use the ptr pointer directly. We could ommit the first line, and the macro could be

#define container_of(ptr, type, member) (type *)( (char *)(ptr) - offsetof(type,member) )

ptr is used only once — we don’t need to worry about side effects.
Maybe it’s just good coding practice.

EDIT: Apparently, the first line is there for ‘type checking’. It ensures that type has a member called member(howerver this is done by offsetof macro too, I think), and if ptr isn’t a pointer to the correct type(the type of the member), the compiler will print a warning, which can be useful for debuging.

mmap for Linux drivers

June 26, 2009

Due to an assignment for the Operating Systems Lab, which I’m attending this semester, I started reading about character device drivers for the Linux Kernel. We were a given an incomplete driver, which handled the communication with the hardware, as well as some other issues, and we had to implement the ‘upper layer’ of the driver, which did the communication with the userspace, and handled some locking issues.

Linux Device Drivers(LDD) was very helpful to start with(trying to read kernel code for the first time can be a terrifying experience). However, when I got to the point, where I had to implement the mmap method for the driver, LDD was a bit dated. After some googling and with the help of the Linux Cross Reference, I found out the changes in the Linux Kernel API, and sucessfully implemented mmap(or so I hope :P).

Due to a number of reasons, the nopage method, as well as the populate and the nopfn methods, have been completely removed from the vm_opeartions struct, and the new fault method is used instead for handling page faults.

Besides the changes in the fault handlers, recent kernel releases added another method to map pages to userspace(remap_pfn_range is often used for that purpose). The method is called vm_insert_page, which allows the driver to map a single page to userspace, and can be very useful when you need to map just one page-aligned buffer, which was allocated inside the driver, to userspace.

So, replacing nopage with fault, and using vm_insert_page (simpler code and better suited to the needs of the driver I was writing) instead of remap_pfn_range, did the job.
;)

Btw, in LDD Ch15, it states that it’s not possible to map conventional RAM with remap_pfn_range(ie pages you get from get_free_page) because remap_pfn_range only maps pages with the PG_reserved flag set. However, drivers would manually set the PG_reserved flag to make remap_pfn_range work, although the proper way of remapping ordinary RAM was with the nopage method(described in LDD). Tweaking the PG_reserved flag was considered bad practice, and so Linux 2.6.15 practically removed the PG_reserved flag. A couple of changes were made to the VMA flags as well, including the new vm_insert_page method, and it was made possible to map ‘ordinary’ RAM with remap_pfn_range. Since my knowledge of the memory management in Linux and the VM subsystem is minimal, I can’t explain much more(maybe in another post after a few months ; ).

Follow

Get every new post delivered to your Inbox.

Join 276 other followers