Simvik

Decode a reg property

Turn a reg property's big-endian cells into address and size pairs. A medium embedded C problem (The device tree), run and graded in the browser.

medium · The device tree · device-tree · linux · endianness

A device-tree node's reg property lists its address ranges as 32-bit big-endian cells. How many cells form an address and a size is set by the parent node's #address-cells and #size-cells (1 or 2; with 2, the first cell is the high 32 bits).

For example, with #address-cells = <2> and #size-cells = <1>, reg = <0x0 0x40010000 0x400> is one range: address 0x40010000, size 0x400.

Write dt_reg(prop, len, acells, scells, out, max): prop is the raw property bytes, len its length. Fill out with up to max ranges and return how many there are; return -1 if len is not a whole number of entries.

Starter code

int dt_reg(const uint8_t *prop, int len, int acells, int scells, range_t *out, int max) {
  (void)acells; (void)scells;
  int n = 0;
  for (int i = 0; i + 8 <= len && n < max; i += 8, n++) {
    out[n].addr = prop[i] | prop[i+1] << 8 | prop[i+2] << 16 | (uint32_t)prop[i+3] << 24;
    out[n].size = prop[i+4] | prop[i+5] << 8 | prop[i+6] << 16 | (uint32_t)prop[i+7] << 24;
  }
  return n;
}

Example tests

One range, one cell each

uint8_t p[16];
uint32_t v[] = { 0x40011000, 0x400 };
show(p, cells(p, v, 2), 1, 1);

Expected output:

0x40011000 size 0x400

Two-cell addresses, two ranges

uint8_t p[32];
uint32_t v[] = { 0x0, 0x40010000, 0x400, 0x1, 0x00000000, 0x1000 };
show(p, cells(p, v, 6), 2, 1);

Expected output:

0x40010000 size 0x400
0x100000000 size 0x1000

Learn it first

  • The device tree · Nodes, compatible strings, overlays and how drivers find hardware.