Click here to learn
about this Sponsor:
Home  |  News  |  Articles  |  Polls  |  Forum

Keywords: Match:
Do you volatile? Should you?
by Dr. Kevin P. Dankwardt (Mar. 30 2005)

Foreword -- This article, by veteran Linux trainer Kevin Dankwardt, discusses "volatile," a relatively unknown ANSI-C type modifier that ensures that the compiler generates code to reload a data item each time it is referenced. Volatile must be used with variables that may be altered asynchronously, such as by a signal handler or mapped hardware.



Do you volatile? should you?

by Dr. Kevin P. Dankwardt

Volatile is an ANSI C type modifier that is frequently needed in C code that is part of signal/interrupt handlers, threaded code, and other kernel code, including device drivers. In general, any data that may be undated asynchronously should be declared to be volatile. Incidentally, this issue is not related to CPU caches, except that re-loading of variables into registers may involve cache hits or misses.

Why Use Volatile?

The reason to use volatile is to ensure that the compiler generates code to re-load a data item each time it is referenced in your program. Without volatile, the compiler may generate code that merely re-uses the value it already loaded into a register.

Volatile advises the compiler that the data may be modified in a manner that may not be determinable by the compiler. This could be, for example, when a pointer is mapped to a device's hardware registers. The device may independently change the values unbeknownst to the compiler.

With gcc the -O2 option is normally required to see the effect of not using volatile. Without -O2 or greater optimization, the compiler is likely to re-load registers each time a variable is referenced, anyway. Don't blame the optimizer if a program gets incorrect results because the program does not use volatile where required.

For example, if two threads share a variable, sum, and one or both threads modify it, then the other thread may use a stale value in a register instead of going back to memory to get the new value. Instead, each time the thread references sum, it must be re-loaded. The way to insure this occurs in ANSI C is to declare sum to be volatile.

Example 1.

The use of volatile can be required to get correct answers. For example the program wrong will give incorrect results when it is compiled -O2 and without volatile. This slightly obtuse program is designed to stop after 100 ticks of an interval timer that ticks at 100Hz and print the value of the variable total. The tick count is incremented in the signal handler. When the count gets to 100, the program should terminate. If the tick count does not get to 100 within 10 seconds then an alarm goes off and the program terminates.

By compiling the program as:

gcc -O2 -DVOLATILE=volatile wrong.c -o wrong_v
you will see, (unless your program is preempted for quite a while), that the count gets to 100 and the program terminates as designed. With the program compiled as
gcc -O2 wrong.c -o wrong_nv
you will see, that the count becomes greater than 100 as shown when the handler prints it, but, the while loop does not terminate.

Incidentally, attempts to determine what is happening may thwart your efforts. For example, a function call, such as to printf(), or the use of a breakpoint, in the loop, will likely spill and re-load the registers.

Syntax

The keyword volatile is similar to the const keyword. Volatile is used to modify a type. Thus an int, const int, pointer, etc. may be declared to be volatile. In addition, a point may be declared to be a pointer to volatile. A pointer to volatile means that the data to which the pointer refers is volatile as opposed to the pointer itself. Of course, both the pointer and to which it refers, may be declared to be volatile.

To declare a volatile int do:

volatile int v;

and to declare vp to be a pointer to a volatile int do:

volatile int *vp;

Since deciphering C declarations can be difficult you may want to consult the C declaration chapter in the Sun manual. This manual references the Decoder Flowchart that can be used to help decipher declarations.

In addition, Linux may have the cdecl(1) program that can be used to translate C declarations to English, as for example, in

echo 'explain volatile int *v' | cdecl

which will answer with

declare v as a pointer to volatile int

Reading C declarations is made simpler when you realize that they are written boustrophedonically. Of course, even knowing the definition of boustrophedonically doesn't really help. The idea is that C declarations are interpreted based on the tricky precedence of operators such as "*", "[]", and "()".

Performance Issues

In some sense, volatile is the opposite of register. Thus, one can expect to lose performance. This means don't use volatile when it is not needed.

Example 2.

In our performance example we can see the difference that volatile may make. If we compile this program with and without VOLATILE defined as volatile we see an average number of iterations of almost 5,000 for the volatile case and almost 20,000 for the non-volatile case. Yikes! Remember that we must compile both of them with the -O2 option. (These iteration counts were made on a 400Mhz AMD-K6.)

Linux Examples

The use of the volatile keyword is common in the Linux kernel source. For example, of the 10,607 .c and .h files in the Fedora Core 1, Linux kernel source directory, 1,694 have the string "volatile" in them somewhere. As an example, the file drivers/net/eepro.c uses volatile in three places.

385: volatile s32 cmd_status; /* All command and status fields. */
392: volatile s32 status;
764: volatile s32 *self_test_results;

Generated Code

By examining the code generated by the compiler one can see the difference volatile makes. In this simple example we can see the x86 assembly language when volatile is used and when volatile is not used.

Quiz Yourself

What is volatile in each of the following examples? Are they all legal declarations?

1) volatile int *s1;
2) int* volatile s2;
3) volatile int* volatile s3;
4) const volatile int * volatile s4;
5) volatile int * (*f)(volatile int *);

Check your answers.

Summary

The volatile keyword is relatively unknown. There are times when its use is required for correct operation of C/C++ programs. In general, whenever a variable may be altered asynchronously, such as by a signal handler or mapped hardware, the variable must be declared to be volatile.

Since volatile prevents re-using values in registers, volatile comes with a performance penalty that can be substantial.

Also, since declarations involving volatile can be difficult to decipher you may want to use cdecl(1).




About the author: Kevin Dankwardt is founder and President of K Computing, a training and consulting firm. He has spent most of the last twelve years designing, developing, and delivering technical training for such subjects as Unix system programming, Linux device drivers, real-time programming, and parallel-programming for various organizations world-wide. He received his Ph.D. in Computer Science, in 1988.



Related Stories:

(Click here for further information)


FUEL Database on MontaVista Linux
Whether building a mobile handset, a car navigation system, a package tracking device, or a home entertainment console, developers need capable software systems, including an operating system, development tools, and supporting libraries, to gain maximum benefit from their hardware platform and to meet aggressive time-to-market goals.

Breaking New Ground: The Evolution of Linux Clustering
With a platform comprising a complete Linux distribution, enhanced for clustering, and tailored for HPC, Penguin Computing¿s Scyld Software provides the building blocks for organizations from enterprises to workgroups to deploy, manage, and maintain Linux clusters, regardless of their size.

Data Monitoring with NightStar LX
Unlike ordinary debuggers, NightStar LX doesn¿t leave you stranded in the dark. It¿s more than just a debugger, it¿s a whole suite of integrated diagnostic tools designed for time-critical Linux applications to reduce test time, increase productivity and lower costs. You can debug, monitor, analyze and tune with minimal intrusion, so you see real execution behavior. And that¿s positively illuminating.

Virtualizing Service Provider Networks with Vyatta
This paper highlights Vyatta's unique ability to virtualize networking functions using Vyatta's secure routing software in service provider environments.

High Availability Messaging Solution Using AXIGEN, Heartbeat and DRBD
This white paper discusses a high-availability messaging solution relying on the AXIGEN Mail Server, Heartbeat and DRBD. Solution architecture and implementation, as well as benefits of using AXIGEN for this setup are all presented in detail.

Understanding the Financial Benefits of Open Source
Will open source pay off? Open source is becoming standard within enterprises, often because of cost savings. Find out how much of a financial impact it can have on your organization. Get this methodology and calculator now, compliments of JBoss.

Embedded Hardware and OS Technology Empower PC-Based Platforms
The modern embedded computer is the jack of all trades appearing in many forms.

Data Management for Real-Time Distributed Systems
This paper provides an overview of the network-centric computing model, data distribution services, and distributed data management. It then describes how the SkyBoard integration and synchronization service, coupled with an implementation of the OMG¿s Data Distribution Service (DDS) standard, can be used to create an efficient data distribution, storage, and retrieval system.

7 Advantages of D2D Backup
For decades, tape has been the backup medium of choice. But, now, disk-to-disk (D2D) backup is gaining in favor. Learn why you should make the move in this whitepaper.

 


Got a HOT tip?   please tell us!
Free weekly newsletter
Enter your email...
Click here for a profile of each sponsor:
PLATINUM SPONSORS
GOLD SPONSORS
(Become a sponsor)

ADVERTISEMENT
(Advertise here)

Check out the latest Linux powered...

mobile phones!

other cool
gadgets



BREAKING NEWS

• Hacker-friendly karaoke PMP runs Linux
• Maemo gains KOffice port
• OLPC partners with Amazon, ITU
• "cJTAG" debuts
• First $100 laptop runs Linux
• First Linux on Everest
• Dell ships Ubuntu- and Atom-based netbook
• Smallest x86 board ever?
• MontaVista Vision gains focus
• "Olympics" phone runs Linux
• Android Challenge winners push location awareness
• Atmel-based industrial SBC runs Linux
• Atom squeezes onto Pico-ITX board
• Via frees Chrome graphics driver source
• Webinar dissects Linux multicore migration


Most popular stories -- past 90 days:
• Open source phone goes mass-market
• Updated! Linux Mobile Phones Showcase
• World's cheapest Linux-based laptop?
• Garmin Nav devices run Gnome Linux
• First Atom-based notebook runs Linux
• ARM9 board boots Debian in 0.69 seconds
• Open source camera records geotagged video to SATA HDD
• Linux-friendly Beagle fetches $150
• "PDA phone" runs Linux
• Intel offers $80 "Little Falls" Atom mobo
• Netflix Player runs Linux


DesktopLinux headlines:
• OSCON 2008 presentations, videos posted
• Debian distro named for little green man
• Google spins web browser
• Summit debuts for Linux end users
• "UbuntuLite" reviewed
• Linux in the SME
• Linux: not yet photo-friendly
• Linux to gain anti-virus software
• Linux gains backup utility
• Testing Lenny


Also visit our sister site:


Sign up for LinuxDevices.com's...

news feed

Home  |  News  |  Articles  |  Polls  |  Forum  |  About  |  Contact
 

Ziff Davis Enterprise Home | Contact Us | Advertise | Link to Us | Reprints | Magazine Subscriptions | Newsletters
Tech RSS Feeds | White Papers | ROI Calculators | Tech Podcasts | Tech Video | VARs | Channel News

Baseline | Careers | Channel Insider | CIO Insight | DesktopLinux | DeviceForge | DevSource | eSeminars |
eWEEK | Enterprise Network Security | LinuxDevices | Linux Watch | Microsoft Watch | Mid-market | Networking | PDF Zone |
Publish | Security IT Hub | Strategic Partner | Web Buyer's Guide | Windows for Devices

Developer Shed | Dev Shed | ASP Free | Dev Articles | Dev Hardware | SEO Chat | Tutorialized | Scripts |
Code Walkers | Web Hosters | Dev Mechanic | Dev Archives | igrep

Use of this site is governed by our Terms of Service and Privacy Policy. Except where otherwise specified, the contents of this site are copyright © 1999-2008 Ziff Davis Enterprise Holdings Inc. All Rights Reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff Davis Enterprise is prohibited. Linux is a registered trademark of Linus Torvalds. All other marks are the property of their respective owners.