Bits, Masks and Fields

Registers pack several fields into one word, and several owners share it. Learn to set, clear and insert a field, when read-modify-write is right, and why it destroys a write-1-to-clear register.

You Will Be Able To

  • Build a mask from a shift and a width, and insert a field.
  • Use SET and CLR registers instead of read-modify-write when they exist.
  • Explain why read-modify-write on a write-1-to-clear register loses flags.
Lesson
V0.2
Time
26 min
Runs on
Verilator with C/C++
Check
5 questions

The LED pattern is right, but the heartbeat LED on pin 0 has stopped blinking. Your field update read OUT, changed the LED bits, and wrote the whole word back. In between, an interrupt handler had flipped pin 0, and your write put the old value back.

A 32-Bit Register Cut into FieldsStep through one field update: find the field, build its mask, clear it, insert the new value.
  • Storage
  • Datapath
  • Control / FSM
  • Step
  • Peripheral
  • Data
A 32-Bit Register Cut Into FieldsStep through one field update: find the field, build its mask, clear it, insert the new value. storage Register 32 bits, severalowners datapath Field bits 7 to 4: the LEDs control Mask 0xF << 4 = 0xF0 step Clear value & ~mask step Insert | (v << 4) & mask peripheral Write back one bus write shift and widthones in the fieldAND NOTORstore
  1. storage Register32 bits, several owners
    • shift and width → Field
  2. datapath Fieldbits 7 to 4: the LEDs
    • ones in the field → Mask
  3. control Mask0xF << 4 = 0xF0
    • AND NOT → Clear
  4. step Clearvalue & ~mask
    • OR → Insert
  5. step Insert| (v << 4) & mask
    • store → Write back
  6. peripheral Write backone bus write
  1. Find the field

    A field is named by where it starts (its shift) and how many bits it has (its width).

  2. Build the mask

    Width ones, shifted to the start: four ones at bit 4 make 0xF0.

  3. Clear, then insert

    AND with the inverted mask empties the field; OR puts the new value in.

  4. One write

    The new word goes back in one store, so no other field changes.

Read the diagram as text
  • Register: 32 bits, several owners
  • Field: bits 7 to 4: the LEDs
  • Mask: 0xF << 4 = 0xF0
  • Clear: value & ~mask
  • Insert: | (v << 4) & mask
  • Write back: one bus write
  • Register → Field: shift and width
  • Field → Mask: ones in the field
  • Mask → Clear: AND NOT
  • Clear → Insert: OR
  • Insert → Write back: store

A read-modify-write of one field. Lesson text uses GPIO OUT bits 7 to 4 as the example field.

Before You Start

Read A Register Is an Address first. The GPIO registers come from GPIO; flags and write-1-to-clear from Interrupt Registers in a Peripheral.

The labs of this module are small slices. They use the real addresses and interrupt numbers of ap_soc v1.5, and each page says so. The whole chip runs from module V2 on, and in the guided run of the fundamentals module.

Five questions this page answers
Question
1How do you build a mask and insert a field?
2What is read-modify-write, and when is it safe?
3Why do some blocks have SET and CLR registers?
4What does write-1-to-clear mean?
5Why does read-modify-write destroy a write-1-to-clear register?

The Idea: One Word, Many Owners

A register is 32 bits, and few blocks give each setting a whole word. GPIO OUT holds sixteen pins, one bit each, and different drivers own different pins. A pin-mux register gives each pad a two-bit field. So changing one setting means changing some bits and leaving the rest exactly as they were.

The classic way is read-modify-write: read the word, change your bits, write it back. It is correct when nothing else changes the register in between. It goes wrong in two ways. Something else may change the register in between. Or the register may give written ones a meaning of their own.

New Words

New words on this page
WordMeaning
FieldA group of bits inside a register with one meaning, named by its shift and its width.
MaskA word with ones exactly where the field is, used to clear or pick out the field.
Read-modify-writeRead a register, change some bits in the processor, and write the whole word back.
SET and CLR registersWrite-only helpers: a 1 written to SET sets that bit, a 1 written to CLR clears it, a 0 does nothing.
Write-1-to-clearA register whose bits are flags; writing a 1 to a bit clears that flag, writing a 0 leaves it.

Masks by Hand

Field operations on a 32-bit word
GoalC expressionExample: field at bit 4, width 4, value 0xA
Mask of the field((1u << width) - 1) << shift0xF << 4 = 0xF0
Clear the fieldreg & ~mask0x0F3 & ~0xF0 = 0x003
Insert a value(reg & ~mask) | ((v << shift) & mask)0x003 | 0xA0 = 0x0A3
Read the field(reg & mask) >> shift(0x0A3 & 0xF0) >> 4 = 0xA

Two habits prevent most field bugs. Clear before you insert: OR alone can turn 01 into 11, never 11 into 01. And mask the new value, so an oversized value cannot spill into the next field. One more trap hides in the mask formula. In C, shifting a 32-bit value by 32 has no defined result, so a full-width field needs its own case.

Write-1-to-Clear: When Writing Back Is Wrong

Interrupt flags are often write-1-to-clear. Reading gives the flags that are set. Writing a word clears exactly the flags whose bits are 1 in it. So the word you write is a list of flags to clear, not a new value.

Now apply read-modify-write. Flags read 0b1101: three flags pending. You served the flag in bit 2 and want to clear it. Read gives 1101; OR in bit 2 gives 1101; write it back. Every bit that was 1 is now cleared, so all three flags are gone, and two interrupts were lost without being served.

One acknowledge, two ways (flags in bits 3 to 0)
ReadWrittenFlags after
Read-modify-write110111010000: two pending flags lost
Write only the served bitnot needed01001001: the other two stay pending

The rule comes from the access type in the register description. An ordinary read and write register wants read-modify-write. A write-1-to-clear register wants a write of only the bits you mean. Mixing them up, in either direction, is a classic chip-test bug.

The Rules

  1. Rule 1: Clear, insert, write once.

    Build the mask from shift and width; clear the field, insert the masked value, one store.

  2. Rule 2: Prefer SET and CLR when they exist.

    Each write changes only its own bits, so nothing in between can be lost.

  3. Rule 3: Read the access type first.

    Read and write: read-modify-write. Write-1-to-clear: write only the bits to clear.

Sources for These Rules

The GPIO register set (OUT, SET, CLR, STATUS as write-1-to-clear): docs/soc/ap_soc-facts.md section 6, built in the S7.2 lab.

Shifting a value by its full width has no defined result in C (ISO C11, section 6.5.7).

That clause is not in the reference library; it is common practice.

Now Run It: An Interrupt Between the Read and the Write

The lab shows a 4-bit value on the LEDs of GPIO pins 7 to 4, in two ways. Each way starts from OUT = 0001. The bench plays a handler that toggles pin 0 right after the first bus access of each call. The function leds_rmw reads, changes the field and writes back. The function leds_setclr writes CLR with the zeros of the field and SET with its ones.

Printed by the lab (Verilator with the C over DPI).
leds_rmw(a), OUT starts at 0001
  bus read  10001008 -> 00000001
  (interrupt: OUT bit 0 toggled, OUT = 0000)
  bus write 10001008 <- 000000a1
after leds_rmw:    OUT = 00a1
leds_setclr(a), OUT starts at 0001
  bus write 10001010 <- 00000050
  (interrupt: OUT bit 0 toggled, OUT = 0000)
  bus write 1000100c <- 000000a0
after leds_setclr: OUT = 00a0

Follow the first call. It reads 0001, then the handler clears pin 0, so OUT is 0000. The write puts back a1, with pin 0 at 1 again: the handler's change is lost. Now leds_setclr. CLR 50 clears pins 6 and 4, the handler toggles pin 0, and SET a0 sets pins 7 and 5. OUT ends at 00a0, with the handler's change kept.

Neither function has a bug on its own. The race comes from the gap between a read and a write. SET and CLR have no gap, because they never read.

The Trap: Applying One Habit Everywhere

An engineer who learned read-modify-write applies it to every register. On a write-1-to-clear flag register, it wipes every pending flag, and interrupts vanish only when two arrive close together. The test passes on Monday and fails on Thursday.

An engineer who learned "just write the bit" applies that everywhere too. On an ordinary enable register, writing one bit turns every other enable off. Both habits are right somewhere and wrong somewhere else. The register description says which.

Try It

Run the lab. Find the row where the handler's change to pin 0 is lost.

Start from OUT = 0000 and show the value 5 instead. Predict the last line.

Read leds.c: find the mask and the two lines that clear and insert the field.

RUNVerilator + C/C++ over DPI · simulator service
Edit the code, then run it
Expected: leds_rmw(a), OUT starts at 0001 bus read 10001008 -> 00000001 (interrupt: OUT bit 0 toggled, OUT = 0000) bus write 10001008 <- 000000a1 after leds_rmw: OUT = 00a1 leds_setclr(a), OUT starts at 0001 bus write 10001010 <- 00000050 (interrupt: OUT bit 0 toggled, OUT = 0000) bus write 1000100c <- 000000a0 after leds_setclr: OUT = 00a0
Read included file: hal.h
/* hal.h: register access for chip tests (ASIC Point, SoC Verification V0).
 * Host-native build: every call is one bus transfer, carried to the bench over DPI.
 * On the chip, the same two functions are volatile pointer accesses (lesson V0.1). */
#ifndef HAL_H
#define HAL_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int bus_read(int addr);              /* provided by the bench */
void bus_write(int addr, int data);  /* provided by the bench */
#ifdef __cplusplus
}
#endif
static inline uint32_t reg_read32(uint32_t addr) { return (uint32_t)bus_read((int)addr); }
static inline void reg_write32(uint32_t addr, uint32_t value) { bus_write((int)addr, (int)value); }
#endif
Read included file: leds.h
/* leds.h: the function you write. */
#ifndef LEDS_H
#define LEDS_H
#include "hal.h"
#ifdef __cplusplus
extern "C" {
#endif
void leds_rmw(uint32_t v);
void leds_setclr(uint32_t v);
#ifdef __cplusplus
}
#endif
#endif
Read included file: leds.c
/* leds.c: show a 4-bit value on the LEDs of GPIO pins 7 to 4, two ways. */
#include "leds.h"
#define GPIO_OUT 0x10001008u
#define GPIO_SET 0x1000100Cu
#define GPIO_CLR 0x10001010u
#define LED_SHIFT 4u
#define LED_MASK  (0xFu << LED_SHIFT)

/* Read-modify-write on OUT: read, clear the field, insert the value, write. */
void leds_rmw(uint32_t v) {
  uint32_t out = reg_read32(GPIO_OUT);
  out &= ~LED_MASK;
  out |= (v << LED_SHIFT) & LED_MASK;
  reg_write32(GPIO_OUT, out);
}

/* SET and CLR: each write changes only the bits that are 1 in it. No read. */
void leds_setclr(uint32_t v) {
  reg_write32(GPIO_CLR, (~v << LED_SHIFT) & LED_MASK);
  reg_write32(GPIO_SET, (v << LED_SHIFT) & LED_MASK);
}

Check Yourself

Predict the outputThe lab now starts from OUT = 0000 and shows the value 5. What is the last line it prints?
// The bench plays GPIO OUT, SET and CLR. Right after the first bus access of each call, an "interrupt
// handler" in the bench toggles OUT bit 0, as a handler that blinks pin 0 would.
module tb;
  export "DPI-C" function bus_read;
  export "DPI-C" function bus_write;
  int unsigned n_reads /*verilator public_flat_rw*/, n_writes /*verilator public_flat_rw*/;
  bit trace_on;
  function int bus_read(input int addr);
    int data;
    data = block_read(addr);
    n_reads++;
    if (trace_on) $display("  bus read  %08h -> %08h", addr, data);
    return data;
  endfunction
  function void bus_write(input int addr, input int data);
    n_writes++;
    if (trace_on) $display("  bus write %08h <- %08h", addr, data);
    block_write(addr, data);
  endfunction
  import "DPI-C" context function void leds_rmw(input int unsigned v);
  import "DPI-C" context function void leds_setclr(input int unsigned v);
  bit [15:0] out_reg /*verilator public_flat_rw*/;
  int unsigned accesses /*verilator public_flat_rw*/;
  function void handler_maybe();
    accesses++;
    if (accesses == 1) begin out_reg[0] = ~out_reg[0]; $display("  (interrupt: OUT bit 0 toggled, OUT = %04h)", out_reg); end
  endfunction
  function int block_read(input int addr);
    int data;
    data = (addr == 32'h1000_1008) ? {16'd0, out_reg} : 0;
    $display("  bus read  %08h -> %08h", addr, data);
    handler_maybe();
    return data;
  endfunction
  function void block_write(input int addr, input int data);
    if (addr == 32'h1000_1008) out_reg = data[15:0];
    if (addr == 32'h1000_100C) out_reg = out_reg | data[15:0];
    if (addr == 32'h1000_1010) out_reg = out_reg & ~data[15:0];
    $display("  bus write %08h <- %08h", addr, data);
    handler_maybe();
  endfunction
  initial begin
    out_reg = 16'h0000; accesses = 0;
    $display("leds_rmw(%0h), OUT starts at %04h", 5, out_reg);
    leds_rmw(5);
    $display("after leds_rmw:    OUT = %04h", out_reg);
    out_reg = 16'h0000; accesses = 0;
    $display("leds_setclr(%0h), OUT starts at %04h", 5, out_reg);
    leds_setclr(5);
    $display("after leds_setclr: OUT = %04h", out_reg);
    $finish;
  end
endmodule
Read included file: hal.h
/* hal.h: register access for chip tests (ASIC Point, SoC Verification V0).
 * Host-native build: every call is one bus transfer, carried to the bench over DPI.
 * On the chip, the same two functions are volatile pointer accesses (lesson V0.1). */
#ifndef HAL_H
#define HAL_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int bus_read(int addr);              /* provided by the bench */
void bus_write(int addr, int data);  /* provided by the bench */
#ifdef __cplusplus
}
#endif
static inline uint32_t reg_read32(uint32_t addr) { return (uint32_t)bus_read((int)addr); }
static inline void reg_write32(uint32_t addr, uint32_t value) { bus_write((int)addr, (int)value); }
#endif
Read included file: leds.h
/* leds.h: the function you write. */
#ifndef LEDS_H
#define LEDS_H
#include "hal.h"
#ifdef __cplusplus
extern "C" {
#endif
void leds_rmw(uint32_t v);
void leds_setclr(uint32_t v);
#ifdef __cplusplus
}
#endif
#endif
Read included file: leds.c
/* leds.c: show a 4-bit value on the LEDs of GPIO pins 7 to 4, two ways. */
#include "leds.h"
#define GPIO_OUT 0x10001008u
#define GPIO_SET 0x1000100Cu
#define GPIO_CLR 0x10001010u
#define LED_SHIFT 4u
#define LED_MASK  (0xFu << LED_SHIFT)

/* Read-modify-write on OUT: read, clear the field, insert the value, write. */
void leds_rmw(uint32_t v) {
  uint32_t out = reg_read32(GPIO_OUT);
  out &= ~LED_MASK;
  out |= (v << LED_SHIFT) & LED_MASK;
  reg_write32(GPIO_OUT, out);
}

/* SET and CLR: each write changes only the bits that are 1 in it. No read. */
void leds_setclr(uint32_t v) {
  reg_write32(GPIO_CLR, (~v << LED_SHIFT) & LED_MASK);
  reg_write32(GPIO_SET, (v << LED_SHIFT) & LED_MASK);
}
ConceptWhat does writing 0b0010 to a write-1-to-clear flag register do?
ConceptWhy can a SET register never lose another driver's change?
ConceptFlags read 0b0110 and you served bit 1. Which write is right?
ConceptIn the lab, why does leds_rmw end with OUT = 00a1?

Common Mistakes

Wrong Insert a field with OR only.

OR can set bits but never clear them, so 3 can never become 1.

Fix Clear the field with AND NOT mask, then OR in the new value.

Wrong Read-modify-write a write-1-to-clear register.

Writing back the read value clears every flag that was set.

Fix Write only the bits of the flags you served.

Wrong Write one bit straight into a shared read and write register.

Every other bit becomes 0.

Fix Read, OR in the bit, write back; or use SET and CLR.

Remember

  • A field is a shift and a width; its mask is width ones shifted to the start.
  • Read-modify-write: read, clear the field, insert the masked value, write once.
  • SET and CLR registers avoid the gap between a read and a write.
  • On a write-1-to-clear register, write only the bits to clear; never write back what you read.

Practice

Report a problem with this page