GPIO
Your script says the lamp is on. The board is dark. Behind one pin sit three different bits, and the script read the wrong one.
You Will Be Able To
- Tell apart the saved output value, the output enable and the sampled pin level.
- Explain how a write of a whole word can undo the work of another writer, and how a command write avoids it.
- Say why an edge cause can be cleared and a level cause cannot.
- Lesson
- S7.2
- Time
- 26 min
- Runs on
- Your browser
- Check
- 6 questions
It is bring-up day. The script prints "lamp on", and the lamp is dark. Later a second lamp goes out by itself, and no line of code switches it off. Both bugs start at the same register.
Before You Start
You need The Anatomy of a Peripheral: a register block, core logic and pad signals. You need S0.4 for one APB write.
The last part uses a sticky flag and an interrupt enable bit, from Interrupt Registers in a Peripheral.
| Question | |
|---|---|
| 1 | Which three bits sit behind one pin, and what does each one answer? |
| 2 | OUT holds 1 and the pin is low. How can that be? |
| 3 | Why does IN show a change of the pin two clocks late? |
| 4 | How can a write of a whole word undo the work of another writer? |
| 5 | Software clears two causes, and the request stays 1. Why? |
The Idea: Three Bits Behind Every Pin
GPIO stands for general-purpose input and output. It is the plainest device on the chip: a row of pins that software can drive or read. A lamp, a button, a chip-enable line for another part: all of them hang on GPIO pins.
One pin needs three bits, because it raises three different questions. What level should the chip drive? Is the chip driving at all? What level is on the pin right now? The three answers can all differ. A pin can hold a saved 1, drive nothing, and read 0 from the board.
The second idea is about sharing. The 16 pins sit in one register, and two pieces of software often own different pins. If each reads the whole word, changes its own bit and writes the word back, one can wipe out the other. The cure is a write that names only the bits to change.
Without the first idea you trust the wrong read. Without the second you lose a pin now and then, and no error is ever reported.
New Words
| Word | Meaning |
|---|---|
| Output driver | The circuit that puts a level on a pin. It can be switched off. |
| Output enable of a pin | The signal that switches the output driver of a pin on. In GPIO it is one register bit for each pin. |
| Released pin | A pin whose driver is off. The chip drives nothing. The board decides the level. |
| Input sampler | Two flip-flops in a row that bring an outside signal onto the clock of the chip. |
| Read-modify-write | Three steps by software: read a whole register, change some bits in the copy, write the whole copy back. |
| Stale copy | A copy of a register that no longer matches it, because someone wrote the register in between. |
| Command write | A write in which a 1 means "act on this bit" and a 0 means "leave this bit alone". |
| Offset | Name | What it does |
|---|---|---|
| 0x00 | DIR | A 1 turns the output driver of that pin on. Reset value 0. |
| 0x04 | IN | Read only: the pin levels, after the input sampler. |
| 0x08 | OUT | The saved output value of each pin. |
| 0x0C | SET | Command write: a 1 sets that bit of OUT. |
| 0x10 | CLR | Command write: a 1 clears that bit of OUT. |
| 0x14 | TGL | Command write: a 1 inverts that bit of OUT. |
| 0x18 | IRQ ENABLE | A 1 lets that pin raise the interrupt request. |
| 0x1C | LEVEL_MODE | A 1 makes that pin a level cause. A 0 makes it an edge cause. |
| 0x20 | ACTIVE_HIGH | A 1 means a high level, or a rising edge, is the event. |
| 0x24 | STATUS | Read: raw status. Write: a 1 clears the sticky flag of that pin. |
| 0x28 | MASKED STATUS | Read only: STATUS AND IRQ ENABLE. |
GPIO is at base 0x10001000, on APB. Bit n of every register belongs to pin n. The names and offsets are our own choices for ap_soc.
One Picture: Out to the Pin and Back
- Memory
- Pads
- Clock / reset
- Peripheral
- The saved value
Software writes the level it wants into OUT. The bit is saved. Nothing reaches the pin yet.
- The driver and its enable
A driver stands between OUT and the pin. The DIR bit is its output enable. With DIR at 0 the driver lets the pin go, whatever OUT holds.
- The pin
With DIR at 1 the driver puts the OUT value on the pin. With DIR at 0 the board decides the level: a switch, a resistor, another chip.
- The way back
The pin can change at any moment, so it is sampled by two flip-flops in a row. IN shows the pin as it was two clock edges ago.
- Three bits, three questions
OUT answers "what would the chip drive?". DIR answers "is it driving?". IN answers "what is on the pin?". Only IN looks at the board.
Read the diagram as text
- OUT bit: the value to drive, saved
- DIR bit: 1 turns the driver on
- Output driver: drives the pin, or lets it go
- Pin: the level on the board
- Input sampler: two flip-flops, one after the other
- IN bit: the pin, two clocks ago
- OUT bit → Output driver: value
- DIR bit → Output driver: output enable
- Output driver → Pin: drive
- Pin → Input sampler: level
- Input sampler → IN bit: sampled level
One pin of the 16 of GPIO. Every pin has the same three bits, at the same bit number in each register.
The Smallest Example, Worked by Hand
A lamp hangs on pin 0. A high pin lights it. The board pulls the pin low when nobody drives it. Follow the three bits of pin 0 through four moments.
| Moment | What software does | OUT bit | DIR bit | Pin | IN bit | Lamp |
|---|---|---|---|---|---|---|
| 1 | Nothing yet. The chip has left reset. | 0 | 0 | low, from the board | 0 | dark |
| 2 | Sets the OUT bit. | 1 | 0 | low, from the board | 0 | dark |
| 3 | Sets the DIR bit. | 1 | 1 | high, from the chip | 0 | lit |
| 4 | Waits two clocks. | 1 | 1 | high, from the chip | 1 | lit |
Moment 2 is the dark lamp of the script. OUT holds 1 and the lamp is dark, because DIR is 0. A script that reads OUT prints "lamp on". Moment 3 has the lamp lit and IN still 0: the input sampler is two clocks behind.
The order of moments 2 and 3 is deliberate. Write OUT first, then DIR. The other way round, the pin drives the old OUT value for a moment.
Now two writers. The foreground code owns the lamp on pin 0. An interrupt handler owns a lamp on pin 3. The table shows the low four bits of OUT.
| Step | Who | What it does | OUT afterwards | Copy held by the foreground code |
|---|---|---|---|---|
| 1 | Foreground | Reads OUT, to switch lamp 0 off. | 0001 | 0001 |
| 2 | Handler | Interrupts, and sets pin 3 with SET. | 1001 | 0001, now stale |
| 3 | Foreground | Clears bit 0 in its copy. | 1001 | 0000 |
| 4 | Foreground | Writes the whole copy to OUT. | 0000 | 0000 |
Step 4 switched lamp 3 off. Neither piece of code is wrong by itself. Both bus writes succeeded. The foreground code wrote back a 0 for pin 3 that it had read before the handler ran.
With a command write, step 4 becomes "write 0001 to CLR". Bit 0 is cleared. Bit 3 is left alone, because its command bit is 0. OUT ends as 1000. The foreground code never needed a copy.
The Rules
Rule 1: OUT is what the chip would drive. DIR decides whether it drives.
After reset every DIR bit is 0, so no pin drives.
Rule 2: Only IN looks at the board.
To learn the level of a pin, read IN. OUT and DIR show only what software wrote.
Rule 3: IN is two clock edges behind the pin.
The input sampler has two flip-flops. A read just after a change returns the old level.
Rule 4: A write of the whole word writes all 16 bits.
It writes back whatever the copy held for the other pins, stale or not.
Rule 5: A command write changes only the bits that are 1.
SET, CLR and TGL act on the register as it is at that clock edge. No copy is involved.
Rule 6: A sticky flag can be cleared. A level cannot.
A level cause stays in STATUS for as long as the pin holds that level.
Sources for These Rules
General-purpose pins, and the synchronizer of two flip-flops: Harris and Harris, Digital Design and Computer Architecture, ARM edition, chapter 9, sections 9.3.2 and 9.3.3, and chapter 3, section 3.5.5.
The edge on which a register write counts: Arm AMBA APB Protocol Specification, IHI 0024 issue E, sections 3.1 and 4.1.
All six rules describe our own GPIO block. The two flip-flops, the reset values and the three command registers are our own choices for ap_soc.
Command registers for set, clear and toggle are common practice in microcontrollers. No specification in our library requires them.
Now Run It
The lab at the end of this page is the GPIO block on APB. Test code, a bus-functional model, stands in for the processor. It also plays the board: a pin that the chip does not drive is low. Each row is one read of IN, with DIR and OUT printed beside it.
reset oe=0000 out=0000 in=0000
preload oe=0000 out=0001 in=0000
drive oe=0001 out=0001 in=0000
settled oe=0001 out=0001 in=0001
both lamps oe=0009 out=0009 in=0001
stale store oe=0009 out=0000 in=0009
masked toggle oe=0009 out=0008 in=0009
cleared bits oe=0009 out=0000 in=0008Rule 1 at work: the row "preload" has out=0001 with oe=0000. The value is saved and the lamp is dark. Rule 3 at work: "drive" has oe=0001 and still in=0000. One read later, "settled" has in=0001.
Rule 4 at work: "both lamps" has out=0009. Then the foreground code writes its old copy back, and "stale store" has out=0000. Pin 3 went dark with it.
Rule 5 at work: the lab sets both pins again and writes 1 to TGL. The row "masked toggle" has out=0008: pin 0 changed and pin 3 did not. Then a write of 8 to CLR gives out=0000 in "cleared bits".
This lab leaves things out. The board is ideal: a real pin has a voltage, a load and a rise time. The two flip-flops are shown as plain logic. What can go wrong inside them is in the two-flop synchronizer.
Pins as Interrupt Causes
A button on a pin should not need polling. So each pin can be a cause of the one interrupt request of GPIO. The registers are those of Interrupt Registers in a Peripheral, 16 bits wide.
In the next run two buttons are pressed together, on pins 1 and 2. Pin 1 is an edge cause: its rise sets a sticky flag. Pin 2 is a level cause. Both are enabled. The exit check at the end of the page runs this code.
sample pad=0006 meta=0006 in=0000 irq=0
sample pad=0006 meta=0006 in=0006 irq=1
sample pad=0006 meta=0006 in=0006 irq=1
pressed status=0006 irq=1
acknowledged status=0004 irq=1
released status=0000 irq=0Rule 3 at work: in the first row pad and meta are 0006, and in is still 0000. One edge later in is 0006 and irq rises.
Rule 6 at work: the handler writes 1 to both bits of STATUS. The row "acknowledged" still has status=0004 and irq=1. The flag of pin 1 is gone. Pin 2 is a level, and the button is still down. Only in "released" does the request fall.
Why It Is Built This Way
| Design choice | The alternative | What the choice buys, and costs |
|---|---|---|
| A DIR bit beside each OUT bit | Every pin always drives | A pin can be an input, or shared with another chip. Each pin costs one more flip-flop. |
| Every driver off after reset | Drivers on, at 0 | The chip cannot fight another driver on the board before software runs. Software must turn each output on. |
| Two flip-flops on the way in | Read the pin directly | A pin that changes near a clock edge does not upset the logic. Every read is two clocks old. |
| SET, CLR and TGL registers | Read-modify-write, with interrupts switched off round it | One write, no copy, no lost pin. Three more addresses to decode. |
The Trap: The Lamp That Went Out by Itself
Back to the second bug of bring-up day. A lamp on pin 3 goes dark now and then. No line of code switches it off. A search for writes of 0 to pin 3 finds nothing.
It is the stale store of the hand table. The foreground code toggles its own lamp by read-modify-write. Once in a long while the handler runs between its read and its write. The write then puts back an old 0 for pin 3.
This bug is hard to see for two reasons. It needs an interrupt in a gap of a few instructions, so it is rare. And both writes complete without error: the bus has nothing to report. The fix is not more care. It is rule 5: use SET, CLR or TGL, and the gap is gone.
One warning comes with TGL. A driver that is not sure its write arrived may send it again. A second SET or CLR does no harm. A second TGL puts the pin back where it was.
At Scale
This section looks ahead. A real chip has hundreds of pins, and few of them are plain GPIO for long.
Pins are shared
One pin can serve GPIO or another device. A selector in front of the pad decides. Pads and Pin Multiplexing is about that.
More settings for each pin
Real pads add a pull resistor, a drive strength and an input enable. Each is one more bit for each pin, in registers like DIR.
Wake-up
A button must be seen while the chip sleeps and its clock is stopped. Rule 6 of the anatomy page then bites: some small circuit must stay awake.
Build one
To write the command registers yourself, try Set, Clear, Toggle in the practice below. Two Writers, One Lost Bit gives you the stale store to find on a waveform.
Try It
Run the lab. In each row oe is the DIR register, out is the OUT register and in is the IN register, in hexadecimal.
Find the row in which out is 0001 and the lamp is still dark. Which column tells you why?
Replace the write of saved ^ 1 to BASE + 8 by a write of 1 to BASE + 'h10. Predict the row "stale store" before you run it.
Names Printed by the Lab
| Name | Meaning |
|---|---|
| oe | The output enables of the 16 pins: the DIR register. |
| out | The OUT register. |
| in | The value that software reads from the IN register. |
| reset, preload, drive, settled | Four moments of pin 0: after reset, after OUT is written, after DIR is written, one read later. |
| both lamps, stale store | After the handler set pin 3, and after the foreground code wrote its old copy back. |
| masked toggle, cleared bits | After a TGL command on pin 0, and after a CLR command on pin 3. |
reset oe=0000 out=0000 in=0000 preload oe=0000 out=0001 in=0000 drive oe=0001 out=0001 in=0000 settled oe=0001 out=0001 in=0001 both lamps oe=0009 out=0009 in=0001 stale store oe=0009 out=0000 in=0009 masked toggle oe=0009 out=0008 in=0009 cleared bits oe=0009 out=0000 in=0008Read included file: soc-s71-gpio.sv
// Digital GPIO bank. The mux, pad driver and board live outside this block.
module ap_gpio_bank (
input logic pclk, presetn, psel, penable, pwrite,
input logic [11:0] offset,
input logic [31:0] pwdata,
input logic [3:0] pstrb,
input logic [15:0] pad_in,
output logic [15:0] pad_out, pad_oe,
output logic pready, pslverr, irq,
output logic [31:0] prdata
);
localparam DIR=12'h000, IN_WORD=12'h004, OUT_WORD=12'h008,
SET_BITS=12'h00c, CLR_BITS=12'h010, TGL_BITS=12'h014,
IRQ_ENABLE=12'h018, LEVEL_MODE=12'h01c, ACTIVE_HIGH=12'h020,
STATUS=12'h024, MASKED_STATUS=12'h028;
logic [15:0] sample_meta, sample, previous, edge_latch;
logic [15:0] irq_enable, level_mode, active_high;
wire [15:0] lanes = {{8{pstrb[1]}}, {8{pstrb[0]}}};
wire [15:0] selected = pwdata[15:0] & lanes;
wire [15:0] active = ~(sample ^ active_high);
wire [15:0] arrivals = (sample ^ previous) & active & ~level_mode;
wire [15:0] status = (edge_latch & ~level_mode) | (level_mode & active);
assign irq = |(status & irq_enable);
assign pready = 1'b1;
logic valid;
always_comb begin
valid = 1;
prdata = '0;
case (offset)
DIR: prdata[15:0] = pad_oe;
IN_WORD: begin prdata[15:0] = sample; valid = !pwrite; end
OUT_WORD: prdata[15:0] = pad_out;
IRQ_ENABLE: prdata[15:0] = irq_enable;
LEVEL_MODE: prdata[15:0] = level_mode;
ACTIVE_HIGH: prdata[15:0] = active_high;
STATUS: prdata[15:0] = status;
MASKED_STATUS: begin prdata[15:0] = status & irq_enable; valid = !pwrite; end
SET_BITS, CLR_BITS, TGL_BITS: valid = pwrite;
default: valid = 0;
endcase
end
assign pslverr = psel && penable && !valid;
wire wr = psel && penable && pready && pwrite && valid;
wire [15:0] clear_edges = wr && offset == STATUS ? selected : '0;
always_ff @(posedge pclk or negedge presetn) begin
if (!presetn) begin
sample_meta <= 0;
sample <= 0;
previous <= 0;
edge_latch <= 0;
irq_enable <= 0;
level_mode <= 0;
active_high <= '1;
pad_out <= 0;
pad_oe <= 0;
end else begin
sample_meta <= pad_in;
sample <= sample_meta;
previous <= sample;
edge_latch <= (edge_latch & ~clear_edges & ~level_mode) | arrivals;
if (wr) begin
case (offset)
DIR: pad_oe <= (pad_oe & ~lanes) | selected;
OUT_WORD: pad_out <= (pad_out & ~lanes) | selected;
SET_BITS: pad_out <= pad_out | selected;
CLR_BITS: pad_out <= pad_out & ~selected;
TGL_BITS: pad_out <= pad_out ^ selected;
IRQ_ENABLE: irq_enable <= (irq_enable & ~lanes) | selected;
LEVEL_MODE: level_mode <= (level_mode & ~lanes) | selected;
ACTIVE_HIGH: active_high <= (active_high & ~lanes) | selected;
default: ;
endcase
end
end
end
endmodule
Read included file: apb_tasks.svh
// apb_tasks.svh: the requester side of the bench, as tasks for the stimulus (read-only).
// apb_write(addr, data, strb, prot) and apb_read(addr, prot) run one transfer and leave the bus
// IDLE; q_write / q_read queue transfers and apb_run() sends the queue back to back with PSEL held
// high (ACCESS goes straight to SETUP). Each transfer prints one log line at its completion edge:
// e3-e4 WRITE 0x0100 data=0x11223344 strb=1111 waits=0 OKAY
// (setup edge - completion edge). The result of a read is in prdata_q and pslverr_q; the results
// of a queue are in rdv[i] and errv[i]. `cycle` counts rising edges from 0.
int cycle = -1;
always @(posedge pclk) cycle = cycle + 1;
bit quiet = 0;
// Requester bugs, for the broken twins:
bit move_in_wait = 0; // PADDR moves by 4 in the first wait cycle
bit enable_stuck = 0; // PENABLE stays 1 into the next queued transfer (no setup cycle)
bit strb_on_read = 0; // PSTRB = 1111 on reads
bit skip_setup = 0; // PSEL and PENABLE rise together
int give_up = 24; // the bench stops waiting after this many wait cycles
// APB5 wake-up (IHI 0024E 3.7), off by default: with wake_lead >= 0 the requester raises PWAKEUP
// wake_lead cycles before PSEL of a transfer that starts from IDLE, and lowers it after the last
// transfer of a run completes. Broken twin: wake_drop_in_wait lowers PWAKEUP in the first wait cycle.
// The wake-up request is wake_req; a bench built with wake copies it onto PWAKEUP.
int wake_lead = -1;
bit wake_drop_in_wait = 0;
logic wake_req = 0;
logic [31:0] prdata_q = 0;
logic pslverr_q = 0;
int waits_q = 0;
bit stuck_now = 0;
bit q_wr [0:63];
logic [31:0] q_addr [0:63], q_data [0:63], rdv [0:63];
logic [3:0] q_strb [0:63];
logic [2:0] q_prot [0:63];
bit errv [0:63];
int qn = 0;
// A text waveform for the trace blocks: one line per rising edge with the values sampled there.
bit watch = 0;
int wave_edge = -1;
always @(posedge pclk) begin
wave_edge = wave_edge + 1;
`ifdef APB_DECODER
if (watch) $display("wave e%0d: psel=%b pselx=%b penable=%b pwrite=%b paddr=%h pwdata=%h pstrb=%b pready=%b prdata=%h pslverr=%b",
wave_edge, psel, pselx, penable, pwrite, paddr, pwdata, pstrb, pready, prdata, pslverr);
`else
if (watch) $display("wave e%0d: psel=%b penable=%b pwrite=%b paddr=%h pwdata=%h pstrb=%b pready=%b prdata=%h pslverr=%b",
wave_edge, psel, penable, pwrite, paddr, pwdata, pstrb, pready, prdata, pslverr);
`endif
end
// One transfer: SETUP for one cycle, then ACCESS until PREADY. last = 0 keeps PSEL high for the
// next transfer.
task automatic apb_xfer(input bit wr, input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb,
input logic [2:0] prot, input bit last);
int s_edge, w;
if (wake_lead >= 0 && !psel) begin
if (!wake_req) begin wake_req = 1; repeat (wake_lead) begin @(posedge pclk); #1; end end
end
paddr = addr; pwrite = wr; pwdata = wr ? data : 32'h0;
pstrb = wr ? strb : (strb_on_read ? 4'hf : 4'h0);
pprot = prot; psel = 1;
s_edge = cycle + 1;
if (skip_setup || stuck_now) penable = 1;
else begin
penable = 0;
@(posedge pclk); #1 penable = 1;
end
stuck_now = 0;
w = 0;
@(posedge pclk);
while (pready !== 1'b1 && w < give_up) begin
w++;
#1 if (move_in_wait && w == 1) paddr = addr + 4;
if (wake_drop_in_wait && w == 1) wake_req = 0;
@(posedge pclk);
end
prdata_q = prdata; pslverr_q = (pslverr === 1'b1); waits_q = w;
#1;
if (!quiet) begin
if (w >= give_up) $display("e%0d-e%0d %0s 0x%04h no PREADY after %0d wait cycles, the bench gives up", s_edge, cycle, wr ? "WRITE" : "READ ", addr[15:0], w);
else if (wr) $display("e%0d-e%0d WRITE 0x%04h data=0x%08h strb=%b waits=%0d %0s", s_edge, cycle, addr[15:0], data, strb, w, pslverr_q ? "PSLVERR" : "OKAY");
else $display("e%0d-e%0d READ 0x%04h data=0x%08h waits=%0d %0s", s_edge, cycle, addr[15:0], prdata_q, w, pslverr_q ? "PSLVERR" : "OKAY");
end
if (last) begin
psel = 0; penable = 0; pwrite = 0; pstrb = 0;
if (wake_lead >= 0) wake_req = 0;
end else begin
penable = enable_stuck ? 1 : 0;
stuck_now = enable_stuck;
end
endtask
task automatic apb_write(input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb = 4'hf, input logic [2:0] prot = 3'b000);
apb_xfer(1, addr, data, strb, prot, 1);
endtask
task automatic apb_read(input logic [31:0] addr, input logic [2:0] prot = 3'b000);
apb_xfer(0, addr, 0, 0, prot, 1);
endtask
// The queue: transfers sent back to back by apb_run().
task automatic q_write(input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb = 4'hf, input logic [2:0] prot = 3'b000);
q_wr[qn] = 1; q_addr[qn] = addr; q_data[qn] = data; q_strb[qn] = strb; q_prot[qn] = prot; qn++;
endtask
task automatic q_read(input logic [31:0] addr, input logic [2:0] prot = 3'b000);
q_wr[qn] = 0; q_addr[qn] = addr; q_data[qn] = 0; q_strb[qn] = 0; q_prot[qn] = prot; qn++;
endtask
task automatic apb_run();
for (int i = 0; i < qn; i++) begin
apb_xfer(q_wr[i], q_addr[i], q_data[i], q_strb[i], q_prot[i], i == qn - 1);
rdv[i] = prdata_q; errv[i] = pslverr_q;
end
qn = 0;
endtask
task automatic idle(input int n);
repeat (n) @(posedge pclk);
#1;
endtask
Check Yourself
Common Mistakes
Wrong Read OUT to prove that the pin is high.
OUT is a saved value. With DIR at 0 nothing drives the pin.
Fix Check DIR, then read IN two clocks later.
Wrong Change one pin by reading OUT and writing the whole word back.
Another writer can change OUT between the read and the write.
Fix Use SET, CLR or TGL on the one bit.
Wrong Keep clearing a level cause in STATUS.
The pin still holds the level, so the bit comes straight back.
Fix Remove the cause on the board, or switch off its enable bit until it is gone.
Remember
- OUT is the saved value, DIR switches the driver on, and IN is the pin as it was two clocks ago.
- Only IN looks at the board. A saved 1 in OUT proves nothing about the pin.
- A read-modify-write can put back a stale bit of another writer. SET, CLR and TGL change only the bits that are 1.
- An edge cause leaves a sticky flag that software clears. A level cause lasts as long as the pin holds the level.