O'Reilly logo

Beautiful Code by Andy Oram, Greg Wilson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reduced to Even Smaller Bits

As the initial driver core rework was happening, another kernel developer, Al Viro, was working on fixing a number of issues regarding object reference counting in the virtual filesystem layer.

The main problem with structures in multithreaded programs written in the C language is that it's very hard to determine when it is safe to free up any memory used by a structure. The Linux kernel is a massively multithreaded program that must properly handle hostile users as well as large numbers of processors all running at the same time. Because of this, reference counting on any structure that can be found by more than one thread is a necessity.

The struct device structure was one such reference-counted structure. It had a single field that was used to determine when it was safe to free the structure:

	atomic_t          refcount;

When the structure was initialized, this field was set to 1. Whenever any code wished to use the structure, it had to first increment the reference count by calling the function get_ device, which checked that the reference count was valid and incremented the reference count of the structure:

	static inline void get_device(struct device * dev)
	{
	        BUG_ON(!atomic_read(&dev->refcount));
	        atomic_inc(&dev->refcount);
	}

Similarly, when a thread was finished with the structure, it decremented the reference count by calling put_device, which was a bit more complex:

 void put_device(struct device * dev) { if (!atomic_dec_and_lock(&dev->refcount,&device_lock)) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required