volatile: is NOT a frill, is increasingly necessary

John Mashey mash at mips.COM
Mon Apr 4 15:11:48 AEST 1988


(Cross-posted to unix.wizards: see comments at ned)

In article <1988Mar30.110820.23882 at light.uucp> bvs at light.UUCP (Bakul Shah) writes:
>You must be able to tell a compiler that certain variables have side
>effects *IF* you are using a highly optimizing compiler and you do one or
>more of the following:
	(a good list)

I've just been catching up with this.  Let's try some data in place of theory.

1) I grepped both UMIPS kernels (BSD & V).  Each has about 200
"volatile" declarations.  Most of this was in device drivers, but
there were a few other places. 

2) Did we do this for fun?  NO.  We just couldn't globally optimize huge
pieces of the kernel, until:
	a) Our compiler team put in volatile, and until
	b) We got volatile to act completely right. [nontrivial]

	We [the OS group] had just BARRELS of fun when we turned on -O
	before volatile was right.  Every device driver, and various other
	things broke.  This was 2 years ago, and I've mercifully forgotten
	many of the details, but I still remember this one (a structure
	not unusual in drivers):

	/* touch device until ready */
	register struct device_stuff *p;  int junk;

	while (p->status != READY)
		junk = p->control;		/* or something like that */

	The first time we tried that, the optimizer generated a single
	fetch of p->status [and never went back].  Then we declared
	p volatile , and at least the loop was there, but the compiler
	had noticed junk was never used, so it eliminated junk from any
	of its tables, and that wiped out the whole reference
	inside the loop....until the optimizer got fixed to be very, very
	careful to make exactly the right number of memory references
	for volatile variables [no more, no less].

3) With volatile, it is relatively easy to import device drivers,
usually by declaring all of the pointers to device structures to be
(volatile *), and still be able to use a serious global optimizer.
Otherwise, good luck.  Hopefully, more drivers will start being written
with volatile declarations.

4) It is easy enough to #define volatile away if you need to deal
with a compiler that doesn't support it.   I suppose there's some
way to do this with a #pragma, volatile seems cleaner.

5) Perhaps UNIX kernel code is "an unusual case".  I'd be curious if
there is anyone out there, who:
	a) Globally optimizes their UNIX kernels, including drivers, but
	b) Uses something other than volatile. (how?)
-- 
-john mashey	DISCLAIMER: <generic disclaimer, I speak for me only, etc>
UUCP: 	{ames,decwrl,prls,pyramid}!mips!mash  OR  mash at mips.com
DDD:  	408-991-0253 or 408-720-1700, x253
USPS: 	MIPS Computer Systems, 930 E. Arques, Sunnyvale, CA 94086



More information about the Comp.unix.wizards mailing list