Skip to content

Driver Cache Design Pattern

🎯 Overview

Many hardware drivers should not access hardware on every read.

Instead, a cache mechanism is introduced to improve performance and reduce unnecessary bus traffic.


🧠 Problem

Without cache:

read → hardware access

Issues:

  • High latency
  • Excessive bus usage (I2C/SPI)
  • Poor scalability with multiple users

💡 Solution: Cache + Update Policy

read → cache → (optional hardware update)

🧩 Core Components

1. Cached Data

long value_cached;

2. Timestamp

unsigned long last_update;

3. Update Interval

unsigned int interval_ms;

4. Valid Flag

bool valid;

⚙️ Update Logic

if (!valid)
    update()
else if (now < last_update + interval)
    use cache
else
    update()

🔄 Data Flow

userspace
driver read()
update_if_needed()
cache
(optional) hardware access

🔒 Thread Safety

  • Protect cache with mutex
  • Ensure atomic update + read

🧠 Design Trade-offs

Strategy Pros Cons
Always read Fresh data Slow
Cache Fast Slightly stale

🟡 Modes of Operation

1. No Cache

interval = 0
→ always update

2. Lazy Cache (On-Demand)

update only when read

✔ Most common approach


3. Background Polling

periodic update (timer/workqueue)

✔ Best performance
❌ More complex


⚠️ Important Distinction

Hardware Update vs Driver Cache

Concept Meaning
sensor update period hardware refresh rate
driver cache interval software read policy

These must be treated separately.


🧠 Key Insight

Driver design is not only about accessing hardware.

It is also about:

  • When to access hardware
  • How often to access hardware
  • How to balance performance vs accuracy

🚀 Application

This pattern is widely used in:

  • hwmon drivers
  • battery drivers
  • thermal sensors
  • ADC subsystems
  • network statistics

📌 Summary

Cache = performance
Policy = intelligence