Sleep and Wake
A sleeping processor has no clock. So it cannot notice the button that should wake it. Some other circuit has to notice, remember and bring the clock back.
You Will Be Able To
- Explain why a sleep request does not stop the clock at once.
- Explain why a wake detector cannot run on the clock that sleep stops.
- Tell the pending bit, which remembers an event, from the pin, which shows a level.
- Lesson
- S5.8
- Time
- 26 min
- Runs on
- Your browser
- Check
- 6 questions
A handheld meter wakes when its button is pressed. In the field it sometimes needs two presses. Its software is sure it is innocent: when it reads the button after a wake, the button is often not even pressed. Where did the first press go?
Before You Start
You need Dividers and Clock Gates: a clock gate, which opens and closes only while its clock is low. You need Power Modes and the Energy of a Sleep: in sleep mode the clock is stopped and every value is kept.
You need Reset and Interrupts in One Picture: an interrupt request, pending and a handler.
This page uses a pending bit as a peripheral has one, and the step by which software clears it. The Anatomy of a Peripheral explains both. Read it first if they are new to you.
| Question | |
|---|---|
| 1 | Software asks for sleep while a bus transfer is in progress. When does the clock stop? |
| 2 | Why can the wake detector not run on the core clock? |
| 3 | What does the pending bit hold, and what does the pin show? |
| 4 | A button is pressed and let go before the handler runs. What does the handler read on the pin? |
| 5 | What happens to stored values during this kind of sleep? |
The Idea: Something Else Must Stay Awake
A program that waits for a button has nothing to do. It could read the button again and again, a million times a second. Every one of those reads costs energy. It is better to stop the clock of the processor until the button is pressed.
That plan has a hole in the middle. A processor with no clock runs no instruction. It cannot look at the button. So the looking must be done by something else: a small circuit whose clock never stops. Call it the wake detector.
The detector has one more job, and it is the heart of this page. A button press is an event: it happens and it ends. By the time the processor runs again, the button may be up. So the detector keeps a pending bit. The bit is set when the press is seen. It stays set until software says "handled". The pin shows what the button does now. The pending bit remembers what happened earlier.
Going to sleep needs care too. Software asks for sleep at a moment of its own choosing. A bus transfer may be half done at that moment. Stop the clock there and the transfer never finishes. So the request only asks. The clock stops when the work in progress is done.
New Words
| Word | Meaning |
|---|---|
| Sleep request | The signal by which the processor says: I have nothing to do, my clock may stop. |
| WFI | An instruction of RISC-V, short for wait for interrupt. Software runs it to raise the sleep request. |
| Bus idle | No transfer is in progress on the bus, and none is being started. |
| Always-on clock | A clock that keeps running while the clock of the processor is stopped. |
| Core clock gate | The clock gate between the always-on clock and the processor. |
| Acknowledge | What software does to say "handled". It clears the pending bit. |
| Wake detector | Logic on the always-on clock that watches a wake source and sets a pending bit when it fires. |
| Wake cause | The record of which wake source fired. Here it is the pending bit. |
A wake source, from the page on power, is something that can wake the chip. The core clock is the clock of the processor.
One Picture: One Sleep and One Wake
- Clock / reset
- Processor
- Bus
- Power
- Pads
- Awake
A clock that never stops feeds a gate. The gate is open, and the processor gets its clock.
- Software asks for sleep
The program has nothing to do and raises a sleep request. This is a request only. A bus transfer may still be in progress.
- The gate closes
Once the bus is idle, the gate closes while the clock is low. The processor gets no more edges. Every flip-flop keeps its value.
- Someone must still listen
A button is pressed. The processor cannot see it: it has no clock. A wake detector on the always-on clock samples the pin and sets a pending bit.
- Pending opens the gate
The pending bit goes to the gate. The gate opens, again while the clock is low. The processor runs on from where it stopped.
- Service and acknowledge
The handler does its work and acknowledges. Only that clears the pending bit. Until then the bit stays 1, whatever the button does.
Read the diagram as text
- Always-on clock: never stopped
- Core clock gate: open, or closed for sleep
- Processor: runs only on the core clock
- Bus: idle, or a transfer in progress
- Wake detector: on the always-on clock; holds the pending bit
- Button pin: shows the level of the button now
- Always-on clock → Core clock gate: clock in
- Core clock gate → Processor: core clock
- Always-on clock → Wake detector: clock
- Processor → Core clock gate: sleep request
- Bus → Core clock gate: bus idle
- Button pin → Wake detector: button level
- Wake detector → Core clock gate: pending
- Processor → Wake detector: acknowledge
The sleep of this page stops one clock and switches no supply off. The lab builds the gate and the detector. Test code plays the processor.
The Smallest Example, Worked by Hand
The gate of the picture follows one rule. It is open unless three things are true together. The sleep request is 1, the bus is idle, and the pending bit is 0. Work through one sleep and one wake with that rule.
| Moment | Sleep request | Bus idle | Pending bit | Gate | Core clock |
|---|---|---|---|---|---|
| Software asks for sleep in the middle of a read | 1 | 0 | 0 | open | runs: the read must finish |
| The read has finished | 1 | 1 | 0 | closed | stopped |
| The button is pressed | 1 | 1 | 0: not seen yet | closed | stopped |
| The detector has seen the press | 1 | 1 | 1 | open | runs again |
| The handler has acknowledged | 0 | 1 | 0 | open | runs |
In the last row the pending bit is 0 again, and the gate stays open. The processor has taken its sleep request back, so the first of the three conditions is gone.
Now the second half of the idea. Suppose the button is pressed for a moment and let go before the handler runs.
| Moment | Button pin | Pending bit |
|---|---|---|
| Asleep, nothing happens | 0 | 0 |
| The button goes down | 1 | 0, then 1 once the detector has sampled it |
| The button goes up again | 0 | 1 |
| The handler reads the pin | 0 | 1 |
| The handler acknowledges | 0 | 0 |
In the fourth row the two disagree, and both are right. The pin says: the button is up now. The pending bit says: it was pressed, and nobody has dealt with that yet.
- Sample 0
Software has asked for sleep. A bus read is still in progress, so the bus is not idle. The core clock keeps running.
- Sample 1
The read has finished and the gate has closed. The count of core clock edges stands at 7.
- Sample 2
The button is pressed. The count is still 7: the processor cannot notice anything.
- Sample 3
The wake detector, on a clock that never stops, has set the pending bit. Still 7 edges.
- Sample 4
The pending bit has opened the gate. The count moves to 8.
- Sample 5
The handler has read the pin and acknowledged. The pending bit is 0 again. The pin is still 1.
Drawn from the six rows of the lab that carry a count of clock edges.
The Rules
Rule 1: A sleep request only asks.
The clock stops when the work in progress has finished: here, when the bus is idle.
Rule 2: The core clock gate changes only while the clock is low.
Sleep must not cut a pulse, and neither must a wake.
Rule 3: A wake detector must not depend on the clock that sleep stops.
It runs on an always-on clock, or on no clock at all.
Rule 4: The detector turns an event into a pending bit.
The pending bit opens the gate.
Rule 5: The pending bit stays 1 until software acknowledges it.
The pin shows only the level now. After a wake, read the cause, not the pin.
Rule 6: The detector listens during the whole way into sleep.
An event that comes while the clock is being stopped must not be lost.
Rule 7: A stopped clock loses no stored value.
Every flip-flop keeps what it held, because its supply stays on.
Sources for These Rules
Rule 2 is the rule of the clock gate, that its enable must be stable while the clock is high: Weste and Harris, CMOS VLSI Design, fourth edition, section 10.3.5.
Rule 7: a flip-flop changes only on a clock edge and keeps its value in between: Harris and Harris, Digital Design and Computer Architecture, ARM edition, section 3.2.3.
Two flip-flops in a row for a pin that changes at any moment: Harris and Harris, Digital Design and Computer Architecture, ARM edition, section 3.5.5.
WFI is an instruction of the RISC-V privileged architecture. That document is not in our reference library. This page says only what the letters stand for and what our lab does with the request.
Rules 1 and 3 to 6 describe our lab chip. Stopping the clock only when the bus is idle, and the wake detector on an always-on clock, are choices of ap_soc.
Now Run It
The lab at the end of this page has the core clock gate and the wake detector of the picture. Test code plays the processor. It raises the sleep request in the middle of a bus read. Later it reads the pin and acknowledges, as a handler would.
WFI request=1 idle=0 pin=0 pending=0 edges=4 cookie=5a
stopped request=1 idle=1 pin=0 pending=0 edges=7 cookie=5a
button request=1 idle=1 pin=1 pending=0 edges=7 cookie=5a
remembered request=1 idle=1 pin=1 pending=1 edges=7 cookie=5a
resumed request=1 idle=1 pin=1 pending=1 edges=8 cookie=5a
handler read=00000001
ack request=0 idle=1 pin=1 pending=0 edges=14 cookie=5aRule 1 at work, in the first two rows. At WFI the request is 1 and idle is 0: a read is in progress. The clock runs on, from 4 edges to 7. It stops only in the row "stopped", where idle is 1.
Rule 3 at work, in the rows "button" and "remembered". The count of core clock edges is 7 in both. Yet the pending bit goes from 0 to 1 between them. A register changed while the core clock stood still, because it is on another clock.
Rule 4 at work, in the row "resumed": the count is 8. Rule 5 at work, in the last row. After the acknowledge the pending bit is 0 and the pin is still 1. The two are different things.
Rule 7 at work, in every row: cookie=5a. The byte was written before the sleep and is unchanged after it.
This lab leaves things out. The processor is test code, so no real interrupt is taken. The detector samples the pin on the always-on clock. A press shorter than one period of that clock could slip between two samples. In this run the board holds the button down until it is acknowledged.
Why It Is Built This Way
| Design choice | The alternative | What the choice buys, and costs |
|---|---|---|
| Stop the clock only when the bus is idle | Stop it on the request | No transfer is cut in half. Sleep starts a few edges later. |
| A detector on an always-on clock | Let the processor poll the pin | The processor can sleep. A small circuit and its clock always use power. |
| A pending bit | Wake on the level of the pin | A short press is not lost, and software can ask what happened. Software must acknowledge. |
| Pending keeps the gate open | Only the handler opens it | A wake event during the way into sleep is not lost. The gate has one more input. |
The Trap: The Press That Left No Level
Back to the meter that needs two presses. Its wake logic had no pending bit. It woke the processor on the level of the pin. The handler then read the pin to see which button it was.
A quick press was over before the handler ran. The handler read a 0, decided that the wake was a false alarm, and went back to sleep. The second press was usually longer. The software was innocent, as it said. The pin had simply moved on.
A second trap sits at the door of sleep. A design switches its detector on only after the gate has closed. A press that ends in those few edges is seen by nobody. The processor is already going down, and the detector is not listening yet.
A third trap is the detector on the wrong clock. Someone clocks it from the core clock, because that is the clock all other logic uses. It works on the bench while the chip is awake. Asleep, it never sees an edge.
At Scale
This section looks ahead. One button and one stopped clock become many wake sources and several depths of sleep.
A register of wake causes
With many sources, each gets a pending bit. Software reads them all after a wake. Two buttons may have fired together.
Asking every block
Here one signal, bus idle, says that work is done. A large chip asks each block with a request and waits for its answer. Request and Acknowledge shows the handshake.
Deeper sleep
When supplies are switched off as well, the wake detector must be in the always-on domain. Power at Chip Level drew that path.
A wake with no clock at all
In the deepest modes even the always-on clock is off. A held level on a pin then starts the clock first. The first practice problem builds that.
Try It
Run the lab. Test code plays the processor: it asks for sleep in the middle of a bus read, and later reads the pin as a handler would.
Change "waits=2" to "waits=0", so that the bus read finishes sooner. At which count of edges does the clock stop now?
Release the button before the handler reads the pin. The quiz below asks what the handler sees.
Names Printed by the Lab
| Name | Meaning |
|---|---|
| WFI | The moment at which test code raises the sleep request, as a WFI instruction would. |
| request | The sleep request. |
| idle | 1 when no bus transfer is in progress. |
| pin | The level of the button pin now. |
| pending | The pending bit of the wake detector. |
| edges | How many rising edges of the core clock the processor side has had so far. |
| cookie | One byte, 5a, written to a register before the sleep. |
| handler read | The word that shows the pin levels, as the handler read it over the bus. Bit 0 is the button. |
| ack | The moment after the handler has acknowledged. |
WFI request=1 idle=0 pin=0 pending=0 edges=4 cookie=5a stopped request=1 idle=1 pin=0 pending=0 edges=7 cookie=5a button request=1 idle=1 pin=1 pending=0 edges=7 cookie=5a remembered request=1 idle=1 pin=1 pending=1 edges=7 cookie=5a resumed request=1 idle=1 pin=1 pending=1 edges=8 cookie=5a handler read=00000001 ack request=0 idle=1 pin=1 pending=0 edges=14 cookie=5aRead included file: ahb_apb_bridge.sv
`timescale 1ns/1ns
// ahb_apb_bridge.sv: an AHB subordinate that turns each accepted transfer into one APB transfer
// (read-only). The address phase is registered when HSEL, HREADY and a NONSEQ or SEQ transfer are
// all present. During SETUP and unfinished ACCESS the bridge keeps HREADYOUT low. A successful APB
// completion ends the AHB data phase with OKAY and HRDATA = PRDATA. A failed APB completion starts
// the two-cycle ERROR (HREADYOUT low then high, HRESP high in both). HWDATA and HWSTRB are data-phase signals the manager holds
// through the wait states, so PWDATA and PSTRB are driven from them directly; PADDR is the aligned
// word address (IHI 0024E 2.1.1 leaves an unaligned PADDR unpredictable). HPROT maps onto PPROT:
// privileged from HPROT[1], instruction from HPROT[0] = 0, and the access is Secure.
// A write therefore costs one setup and one access cycle: two cycles of data phase with no APB wait.
module ahb_apb_bridge (
input logic hclk,
input logic hresetn,
input logic hsel,
input logic [31:0] haddr,
input logic [1:0] htrans,
input logic hwrite,
input logic [3:0] hprot,
input logic [31:0] hwdata,
input logic [3:0] hwstrb,
input logic hready,
output logic hreadyout,
output logic hresp,
output logic [31:0] hrdata,
output logic psel,
output logic penable,
output logic pwrite,
output logic [31:0] paddr,
output logic [31:0] pwdata,
output logic [3:0] pstrb,
output logic [2:0] pprot,
input logic pready,
input logic [31:0] prdata,
input logic pslverr);
localparam int IDLE = 0, SETUP = 1, ACCESS = 2, ERR1 = 3, ERR2 = 4;
bit trace = 0;
int st = IDLE;
logic wr = 0;
logic [31:0] a = 0;
logic [2:0] prot = 0;
wire take = hsel && hready && htrans[1];
assign psel = (st == SETUP || st == ACCESS);
assign penable = (st == ACCESS);
assign pwrite = wr;
assign paddr = {a[31:2], 2'b00}; // APB leaves an unaligned PADDR unpredictable: the word, and PSTRB picks the bytes
assign pwdata = wr ? hwdata : 32'h0;
assign pstrb = wr ? hwstrb : 4'h0;
assign pprot = prot;
assign hreadyout = (st == IDLE || st == ERR2) ? 1'b1 : (st == ACCESS) ? (pready === 1'b1 && pslverr !== 1'b1) : 1'b0;
assign hresp = (st == ERR1 || st == ERR2);
assign hrdata = (st == ACCESS) ? prdata : 32'h0;
always @(posedge hclk or negedge hresetn) begin
if (!hresetn) st <= IDLE;
else begin
case (st)
SETUP: st <= ACCESS;
ACCESS: if (pready === 1'b1) begin
if (trace) $display("apb e%0d: %0s 0x%03h%0s", ($time - 5) / 10, wr ? "write" : "read", a[11:0], pslverr === 1'b1 ? " PSLVERR" : "");
st <= (pslverr === 1'b1) ? ERR1 : IDLE;
end
ERR1: st <= ERR2;
default: st <= IDLE;
endcase
// A new address phase can be taken whenever HREADY is 1: in IDLE, in the last cycle of ERROR,
// or at the edge an access completes with OKAY.
if (take && (st == IDLE || st == ERR2 || (st == ACCESS && pready === 1'b1 && pslverr !== 1'b1))) begin
wr <= hwrite; a <= haddr; prot <= {~hprot[0], 1'b0, hprot[1]}; st <= SETUP;
end
end
end
endmodule
Read included file: io_lab_regs.sv
// Two word registers for the S1 labs. Inputs have already crossed into PCLK.
// The UART model exposes accepted bytes; it does not model the serial shifter.
module io_lab_regs (
input logic pclk, presetn,
input logic psel, penable, pwrite,
input logic [31:0] paddr, pwdata,
input logic [3:0] pstrb,
input logic [15:0] pins,
input logic [31:0] wait_edges,
output logic pready, pslverr,
output logic [31:0] prdata,
output logic uart_selected, gpio_selected,
output logic tx_accepted,
output logic [7:0] tx_byte
);
localparam logic [19:0] UART_PAGE = 20'h10000, GPIO_PAGE = 20'h10001;
logic [31:0] elapsed;
wire tx_word = uart_selected && paddr[11:0] == 12'h000 && pwrite;
wire input_word = gpio_selected && paddr[11:0] == 12'h004 && !pwrite;
assign uart_selected = psel && paddr[31:12] == UART_PAGE;
assign gpio_selected = psel && paddr[31:12] == GPIO_PAGE;
assign prdata = input_word ? {16'b0, pins} : 32'b0;
assign pready = psel && penable && elapsed >= wait_edges;
assign pslverr = pready && !(tx_word || input_word);
assign tx_accepted = tx_word && pready && pstrb[0];
assign tx_byte = pwdata[7:0];
always_ff @(posedge pclk or negedge presetn) begin
if (!presetn) elapsed <= 0;
else if (psel && penable && !pready) elapsed <= elapsed + 1;
else elapsed <= 0;
end
endmodule
Read included file: io_lab.svh
// Include inside the lesson's testbench. One manager, one clock, aligned words.
// The exercise drives only the UART TX and GPIO input registers.
`ifndef AP_SOC_EXTERNAL_HCLK
logic hclk = 0;
always #5 hclk = ~hclk;
`endif
logic hresetn = 0;
logic [31:0] haddr = 0, hwdata = 0;
logic [1:0] htrans = 0;
logic hwrite = 0;
wire hsel = haddr[31:16] == 16'h1000;
wire hready, hresp, psel, penable, pwrite;
wire [31:0] hrdata, paddr, pwdata;
wire [3:0] pstrb;
localparam logic [31:0] TX = 32'h1000_0000, INPUT_WORD = 32'h1000_1004;
logic [15:0] pins = 0; // Stable, already synchronized GPIO inputs.
integer waits = 0;
wire pready, pslverr, uart_selected, gpio_selected, tx_accepted;
wire [31:0] prdata;
wire [7:0] tx_byte;
io_lab_regs registers (
.pclk(hclk), .presetn(hresetn), .psel(psel), .penable(penable),
.pwrite(pwrite), .paddr(paddr), .pwdata(pwdata), .pstrb(pstrb),
.pins(pins), .wait_edges(waits), .pready(pready), .pslverr(pslverr),
.prdata(prdata), .uart_selected(uart_selected), .gpio_selected(gpio_selected),
.tx_accepted(tx_accepted), .tx_byte(tx_byte)
);
ahb_apb_bridge bridge (
.hclk(hclk), .hresetn(hresetn), .hsel(hsel), .haddr(haddr),
.htrans(htrans), .hwrite(hwrite), .hprot(4'b0011), .hwdata(hwdata),
.hwstrb(4'hf), .hready(hready), .hreadyout(hready), .hresp(hresp),
.hrdata(hrdata), .psel(psel), .penable(penable), .pwrite(pwrite),
.paddr(paddr), .pwdata(pwdata), .pstrb(pstrb), .pprot(),
.pready(pready), .prdata(prdata), .pslverr(pslverr)
);
logic [39:0] console_text = 0;
bit trace_bus = 0;
int cycle = 0;
always @(posedge hclk) begin
if (trace_bus) begin
$display("e%0d req=%b window=%b sel=%b gpio=%b uart=%b enable=%b ready=%b hready=%b prdata=%08h hrdata=%08h pwdata=%08h haddr=%08h paddr=%08h hresp=%b",
cycle, htrans[1], hsel, psel, gpio_selected, uart_selected, penable,
pready, hready, prdata, hrdata, pwdata, haddr, paddr, hresp);
cycle++;
end
if (tx_accepted) begin
console_text = {console_text[31:0], tx_byte};
$display("UART TX byte=%02h character=%c", tx_byte, tx_byte);
end
end
task automatic access_word(input bit writing, input logic [31:0] address,
input logic [31:0] data, output logic [31:0] result);
if (address[31:16] != 16'h1000 || address[1:0] != 0)
$fatal(1, "This lab models aligned words in the APB window");
@(negedge hclk);
haddr = address;
hwrite = writing;
htrans = 2'b10;
@(negedge hclk); // The address was accepted on the intervening rising edge.
htrans = 0;
haddr = 0;
hwdata = data;
do @(posedge hclk); while (!hready);
if (hresp) $fatal(1, "Access failed at %08h", address);
result = hrdata;
#1;
endtask
Read included file: sleep_clock.sv
// Clock-only sleep slice. The board holds the button until it is serviced.
// Inputs other than button belong to the ungated reference-clock domain.
module sleep_clock(
input logic ref_clk, reset_n, button, sleep_request, bus_idle, serviced,
output logic pending, output wire core_clk
);
logic sample, synced, previous, enabled;
always_ff @(posedge ref_clk or negedge reset_n) begin
if (!reset_n) begin
{sample, synced, previous} <= 0;
pending <= 0;
end else begin
{previous, synced, sample} <= {synced, sample, button};
if (synced && !previous) pending <= 1;
else if (serviced) pending <= 0;
end
end
// Model a gate which changes its decision only during the low phase.
always_ff @(negedge ref_clk or negedge reset_n)
if (!reset_n) enabled <= 1;
else enabled <= !sleep_request || !bus_idle || pending;
assign core_clk = ref_clk && enabled;
endmodule
Check Yourself
Common Mistakes
Wrong Stop the clock as soon as software asks for sleep.
A transfer in progress would never finish.
Fix Stop it when the work in progress is done.
Wrong Clock the wake detector from the core clock.
It sees no edge while the processor sleeps.
Fix Use a clock that sleep does not stop.
Wrong Read the pin to learn why the chip woke.
The button may be up again by then.
Fix Read the pending bit, then acknowledge it.
Remember
- A sleep request only asks. The clock stops when the work in progress has finished.
- A wake detector runs on a clock that sleep does not stop, and it listens during the whole way into sleep.
- The pending bit remembers an event until software acknowledges it. The pin shows only the level now.
- A stopped clock loses no stored value.