OS & Hardware
When reading a device status register via memory-mapped I/O as above, why is it declared volatile and the region configured as uncached?
#define STATUS (*(volatile unsigned int *)0x40001000)
while ((STATUS & 1) == 0)
; /* wait until the device is ready */
- Avolatile merges the reads into a single instruction, making it faster
- BCaching makes the device register's value automatically reset to 0
- CThe device changes the value, so it must actually be reread every time or changes are missed
Show answer and explanation
Answer: C. The device changes the value, so it must actually be reread every time or changes are missed
Device registers are modified by the device, independently of the program. Without volatile, the compiler may conclude the value cannot change inside the loop, read it once and generate code that waits forever. And if the region were cached, the CPU would keep reading a stale cached value and never see the device's change. volatile forbids eliminating reads, the opposite of merging them, and caching does not reset values to 0.
- A. volatile forbids eliminating reads, the opposite of merging them.
- B. Caching does not reset the value to 0.
- C. Correct. The device changes the value, so every read must really happen.