Object-oriented design patterns in the kernel, part 1
Posted Jun 4, 2011 7:14 UTC (Sat) by
chad.netzer (subscriber, #4257)
In reply to:
Object-oriented design patterns in the kernel, part 1 by daglwn
Parent article:
Object-oriented design patterns in the kernel, part 1
> There is nothing magical about the kernel. It's software.
This got me thinking about something else. There are about 5000 uses of kmalloc() in the linux kernel, but kmalloc() takes a flag argument. So, to replace these uses with idiomatic C++ would require widespread use of placement new().
However, using placement new requires care when deleting objects. So, rather than just using delete, you have to both manually call the class destructor, and then operator delete() with the right arguments to invoke the proper delete function (I suppose the kernel C++ stdlib could kludge the delete operator so that it works for placement new; now you are writing non-conformant C++)
ie.
struct T *p = kmalloc(sizeof(struct T), GFP_KERNEL | GFP_DMA);
some_init_function(p);
kfree(p);
becomes something like:
T *p = new (GFP_KERNEL | GFP_DMA) T;
p->~T();
operator delete(p, GFP_KERNEL | GFP_DMA); // Or whatever it takes to match the call signature
This unorthodox usage is necessary because the kernel is not just like other software. Not when it comes to things like memory allocation. And what about a std::vector of struct *T? How do you allocate those objects with the right memory flags?
Perhaps there is an elegant solution to this, most likely by eschewing bare pointers in the kernel and always using some templated smart pointer class. A fairly radical change for kernel development. What are your thoughts on it?
(
Log in to post comments)