Skip to content

Add style guide "Avoid caching hardware state" #85

@kammce

Description

@kammce

This is to prevent developers from creating drivers that waste memory in order to mirror the state of hardware. Such a state that may drift or become stale from the actual hardware state.

For example:

class my_driver : public some_interface {
// typical code
  u32 get_frequency() {
    return m_last_set_frequency; // ❌ bad, retrieving cached value that may be stale.
    // Should perform I/O operations
  }
  u32 m_last_set_frequency;
};

The PROS

  • Lower RAM footprint: Drivers will no longer contain any information about hardware state outside of the information needed for the driver to control their piece of the hardware. As an example: a timer may have a member variable, like an m_index that tells it which counter within the timer it's allowed to use. It may not hold information like the prescaler values as those can be accessed directly from the registers within the device. An exception to this is if a device that allows settings to be set, but doesn't provide a means to acquire that information after the fact. And in order for to implement an interface, such information must be cached.
  • Improved correctness: Its not always easy to understand when a value becomes stale or how often a value needs to be updated. With this method the result is always the answer directly from hardware.

The CONS

  • Increased ROM usage: Returning a cached value requires very little memory and in likely to be inlined.
  • Requires I/O: Returning a cached value is very fast. With this, style guide, we'd may need to perform an I2C transaction to calculate the the operating frequency of the device is.

Offenders of this currently

libhal-arm-mcu contains frequency functions that simply return cached values. Calling any of the cache

What I'm currently thinking

I'm currently on the side of:

  • RAM is more precious than ROM.
  • Library users would probably prefer correctness over performance and if they need to cache information, they get full discretion to do so after any function call.
  • Drivers that accept I/O, SPI, or the like, are already paying to pay for I/O.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions