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 */
  1. Avolatile merges the reads into a single instruction, making it faster
  2. BCaching makes the device register's value automatically reset to 0
  3. 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.
Practice this topic Back to topic

More OS & Hardware questions

  1. When is polling, in which the CPU repeatedly checks device status instead of using interrupts, advantageous?
  2. In a system where hardware does not keep caches coherent, what must software do before the CPU reads data a device wrote to main memory via DMA?
  3. What is the main role of an IOMMU?
  4. What is the role of a device driver?
  5. Why do typical operating systems prevent applications from directly reading and writing device registers?