The Watchdog

The board still blinks its heartbeat, but the control output has been stuck since lunch. Follow the write that keeps the chip alive. What did the heartbeat actually prove?

You Will Be Able To

  • Explain what a watchdog is and why it must work without the processor.
  • Follow a missed kick and an early kick through the warning to the reset.
  • Decide who may kick, who may arm, and why nobody may disarm.
Lesson
S6.11
Time
25 min
Runs on
Your browser
Check
6 questions

Picture a controller on a roof where nobody can reach the reset button. Its program stops halfway through updating an output. Which part of the chip can notice, if the processor never runs another instruction?

Before You Start

You need Registers: a write to a register can be a command. You need Timers: The Machine Timer: a counter that software cannot hold up.

You need S0.8: what reset does to a processor. Reset Sources lists the watchdog as one cause of a reset.

Five questions this page answers
Question
1What is a watchdog, and why does it have a counter of its own?
2What is a kick, and what should software have checked before it kicks?
3Why is a kick that comes too early treated as a fault?
4What happens, in order, after a fault?
5Why can software not switch the watchdog off?

The Idea: Prove You Are Alive, or Be Reset

Software gets stuck. A loop waits for a bit that never comes, or a pointer goes wild. On your desk you press reset. On a roof, in a car or in a pump, nobody is there to press it.

So the chip presses it. A watchdog is a counter that counts down on its own. Healthy software must write to it again and again, each time before it reaches zero. That write is a kick. If the kicks stop, the counter runs out and the watchdog resets the chip.

The point of the design is in the word "own". The watchdog asks nothing of the processor. A stuck program cannot argue with it, and a dead handler cannot veto the recovery.

That leaves one weakness, and it is in software. A kick proves only that the kick ran. The whole craft of using a watchdog is to make the kick prove more than that.

New Words

New words on this page
WordMeaning
WatchdogA counter that resets the chip unless software restarts it in time.
KickThe register write that restarts the watchdog counter. Also called service.
TimeoutThe counter reached zero because no kick came.
Service windowThe part of the count in which a kick is accepted. A kick before it opens is a fault.
Early warningAn interrupt that the watchdog raises at a fault, before it asks for a reset.
Grace periodThe time between the early warning and the reset request.
Armed watchdogA watchdog that has been started and is counting. To arm it is to start it.
Unlock keyA fixed value that must be written before a protected register accepts a command.

One Picture: Counter, Kick, Window, Warning, Reset

A Counter That Software Must Keep AliveStep through the picture. It builds the watchdog from a bare counter to the reset it can force.
  • Processor
  • Clock / reset
  • Control / FSM
  • Bus
  • Debug
A Counter That Software Must Keep AliveStep through the picture. It builds the watchdog from a bare counter to the reset it can force. component Software kicks when its work isdone component Watchdogcounter counts down on itsown component Window check was the kick tooearly? component Early warning an interrupt, source6 component Reset request after the graceperiod kick: a register writecount left at the kickreached 0too earlytwo more ticks
  1. component Watchdog countercounts down on its own
    • count left at the kick → Window check
    • reached 0 → Early warning
  2. component Softwarekicks when its work is done
    • kick: a register write → Watchdog counter
  3. component Window checkwas the kick too early?
    • too early → Early warning
  4. component Early warningan interrupt, source 6
    • two more ticks → Reset request
  5. component Reset requestafter the grace period
  1. A counter of its own

    The watchdog counts down from 6, one tick at a time. It does this whether the processor runs or not.

  2. The kick

    Healthy software writes to the service register before the counter runs out. The counter goes back to 6.

  3. The window

    A kick counts only when 3 ticks or fewer are left. A kick that comes sooner means that software is spinning, not working.

  4. The warning

    A missed kick or an early kick raises the early warning. A handler gets a short time to save what it knows.

  5. The reset

    Two ticks later the watchdog asks for a reset. Nothing that software does in between can stop it.

Read the diagram as text
  • Software: kicks when its work is done
  • Watchdog counter: counts down on its own
  • Window check: was the kick too early?
  • Early warning: an interrupt, source 6
  • Reset request: after the grace period
  • Software → Watchdog counter: kick: a register write
  • Watchdog counter → Window check: count left at the kick
  • Watchdog counter → Early warning: reached 0
  • Window check → Early warning: too early
  • Early warning → Reset request: two more ticks

The watchdog of ap_soc. The lab below is this picture. Its numbers, 6 and 3 and 2, are small so that you can count them.

The Smallest Example, Worked by Hand

The counter starts at 6. The service window opens when 3 ticks are left. After a fault, the grace period is 2 ticks. Here are three histories, tick by tick.

Three histories, by hand
HistoryTicks left, one tick at a timeWhat happens
A healthy kick6, 5, 4, 3, kick, 6The kick comes with 3 left, inside the window. The counter goes back to 6.
A missed kick6, 5, 4, 3, 2, 1, 0Timeout: the early warning rises. Two ticks later, the reset request.
An early kick6, 5, kickFive are left and the window is closed. The early warning rises at once. Two ticks later, the reset request.
What a kick does
Ticks left at the kickResultWhy
6, 5 or 4Early warningThe window is not open yet.
3, 2 or 1The counter goes back to 6The kick is inside the window.
0, after a faultNothingThe warning is already up. A kick cannot take it back.

The Rules

  1. Rule 1: The watchdog counts on its own.

    It needs no instruction from the processor to reach zero.

  2. Rule 2: A kick inside the window restarts the counter.

    Here: with 3, 2 or 1 ticks left.

  3. Rule 3: A kick before the window is a fault.

    Software that kicks too fast is spinning, not working.

  4. Rule 4: After a fault the warning comes first, and the reset follows.

    No write stops the reset once the warning is up.

  5. Rule 5: Arming needs privilege and two keys. Disarming needs a reset.

    A stuck program must not be able to silence its own witness.

  6. Rule 6: Kick only on proof that the work was done.

    A kick from a timer handler proves that the timer works.

Sources for These Rules

The edge on which the kick counts: Arm AMBA APB Protocol Specification, IHI 0024 issue E, section 3.1.

Rules 1 to 5 describe our own watchdog. Our own choices for ap_soc: the count of 6, the window at 3 and the grace period of 2. The two keys and the lock after arming are ours too.

Rule 6 is practice. No specification in our library sets rules for a watchdog.

Now Run It

The lab at the end of this page has the watchdog behind the bridge to APB. Test code, a bus-functional model, stands in for the processor. It also supplies the ticks, so each history is short.

Printed by the lab on Icarus. The names are listed with the lab.
untrusted arm=0
one wrong key arm=0
armed left=6 irq=0 reset=0
healthy before left=3 irq=0 reset=0
setup addr=10003008 sel=1 enable=0 data=00000001
access addr=10003008 sel=1 enable=1 data=00000001
healthy after left=6 irq=0 reset=0
disable attempt armed=1
bench halt left=6 irq=0 reset=0
production halt left=2 irq=0 reset=0
hung left=0 irq=1 reset=0
grace left=0 irq=1 reset=0
restart left=0 irq=1 reset=1
early arm left=6 irq=0 reset=0
early before left=5 irq=0 reset=0
early after left=0 irq=1 reset=0
early restart left=0 irq=1 reset=1

Rule 5 at work: the first two rows have arm=0. One writer had the keys and no privilege. The other had privilege and one wrong key. Lower down, "disable attempt armed=1" is a privileged write of 0 that changed nothing.

Rule 2 at work: "healthy before" has left=3, and "healthy after" has left=6. The two rows between them are the kick itself, at its setup and access edge.

A Missed Kick
0123momentproduction halthunggracerestartleft20irqreset
Scroll horizontally ↔

Moments of the lab run on Icarus, by name. The columns are not evenly spaced in time.

Rules 1 and 4 at work: at "hung" the counter is at 0 and irq=1. At "grace" one tick has passed and reset is still 0. At "restart" reset=1. No software ran in between.

An Early Kick
0123momentearly armearly beforeearly afterearly restartleft650irqreset
Scroll horizontally ↔

Moments of the lab run on Icarus, by name. The columns are not evenly spaced in time.

Rule 3 at work: "early before" has left=5. The kick completes as a bus transfer, and "early after" shows irq=1 and left=0.

This lab leaves things out. The early warning is not sent on to the interrupt controller, where it is source 6. The reset request is not sent on to the clock and reset unit. The lab stops at the two wires.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
A service windowAny kick before zero is acceptedA program stuck in a loop that kicks is caught. Software must now time its kick.
A warning before the resetReset at onceA handler can save a record of what went wrong. The reset comes two ticks later.
The reset does not wait for the handlerThe handler ends the grace periodA dead handler cannot hold up the recovery. A slow handler loses its record.
No way to disarmAn enable bit in a registerA wild write cannot switch the watchdog off. Development needs another way to pause it.
Two keys and privilege to armOne write to armA stray write does not start it by accident. The keys are public: they stop mistakes, not attackers.

That "other way to pause" is in the recording. A debugger that stops the processor also stops the kicks. On a development board the watchdog freezes: "bench halt" still has left=6. On a shipped unit it keeps counting: "production halt" has left=2. A unit in the field must not have a pause that a fault could reach.

The Trap: A Heartbeat That Proves Nothing

Back to the board with the blinking heartbeat and the stuck output. Its watchdog is armed and never fires. How?

The kick sits in a timer handler. Every few milliseconds the timer interrupts, the handler kicks, and the handler returns to a main loop that hangs. The interrupt still works, so the kicks still come, perfectly timed. The window does not help: these kicks are on time.

Rule 6 is the cure. Let each piece of work report that it finished: the sensor read, the output update. Let one supervisor collect the reports, and kick only when all are fresh. Then a kick means "the work was done", and a stuck loop stops the kicks.

At Scale

This page1 watchdog, 1 program
A car controllera watchdog for each processor, and one outside the chip

This section looks ahead. On a large chip the watchdog is the last line of a longer defence.

  1. Which clock survives

    A watchdog on the same clock as the processor stops with it. Give it a clock that keeps running when the main clock fails.

  2. Why did we reset

    After the reset, boot code reads the reset cause register. A watchdog reset in the field is a fault report. Reset Sources has that register.

  3. Sleep

    A sleeping processor sends no kicks. Either it wakes in time to kick inside the window, or the watchdog is designed to pause in sleep.

  4. A second watchdog

    Safety designs add a watchdog in another chip. It catches the faults that take the first one down with them.

Try It

Run the lab. Find the three histories: a healthy kick, a missed kick and an early kick.

Find elapse(1) just before the row "early before" and change it to elapse(3). Predict the next two rows.

Names Printed by the Lab
NameMeaning
arm, armed1 when the watchdog has been started.
leftThe ticks left in the watchdog counter.
irqThe early warning.
resetThe reset request.
setup, accessThe kick, a write to the service register, at the two clock edges of its APB transfer.
bench halt, production haltA debugger has stopped the processor: once on a development board, once on a shipped unit.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: untrusted arm=0 one wrong key arm=0 armed left=6 irq=0 reset=0 healthy before left=3 irq=0 reset=0 setup addr=10003008 sel=1 enable=0 data=00000001 access addr=10003008 sel=1 enable=1 data=00000001 healthy after left=6 irq=0 reset=0 disable attempt armed=1 bench halt left=6 irq=0 reset=0 production halt left=2 irq=0 reset=0 hung left=0 irq=1 reset=0 grace left=0 irq=1 reset=0 restart left=0 irq=1 reset=1 early arm left=6 irq=0 reset=0 early before left=5 irq=0 reset=0 early after left=0 irq=1 reset=0 early restart left=0 irq=1 reset=1
Read 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: time_bus_bfm.svh
// One manager issues aligned words. The P4 bridge and local time slice share HCLK.
// Only the lesson's implemented, always-ready register words are accessed.
logic clk = 0, reset_n = 0;
always #5 clk = ~clk;
logic [31:0] haddr = 0, hwdata = 0;
logic hwrite = 0;
logic [1:0] htrans = 0;
wire bridge_window = haddr[31:16] == 16'h1000;
wire [31:0] local_data, bridge_data, paddr, pwdata, prdata;
wire bridge_ready, hresp, psel, penable, pwrite;
logic bridge_response;
wire hready = !bridge_response || bridge_ready;
logic [31:0] result;
bit trace_access = 0;

always_ff @(posedge clk) begin
  if (!reset_n) bridge_response <= 0;
  else if (hready) bridge_response <= htrans[1] && bridge_window;
end
ahb_apb_bridge bridge (
  .hclk(clk), .hresetn(reset_n), .hsel(bridge_window), .haddr, .htrans, .hwrite,
  .hprot(4'b0011), .hwdata, .hwstrb(4'hf), .hready, .hreadyout(bridge_ready),
  .hresp, .hrdata(bridge_data), .psel, .penable, .pwrite, .paddr, .pwdata,
  .pstrb(), .pprot(), .pready(1'b1), .prdata, .pslverr(1'b0)
);
always @(posedge clk)
  if (trace_access && psel)
    if (penable) $display("access addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);
    else $display("setup addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);

task automatic bus_word(input bit wr, input logic [31:0] addr, data,
                        output logic [31:0] sample);
  if (!modeled_word(wr,addr))
    $fatal(1,"This target slice does not model that word operation at %08h",addr);
  @(negedge clk);
  haddr = addr;
  hwrite = wr;
  htrans = 2'b10;
  @(negedge clk);
  haddr = 0;
  htrans = 0;
  hwdata = data;
  do @(posedge clk); while (!hready);
  if (bridge_response && hresp) $fatal(1,"Bus error at %08h",addr);
  sample = bridge_response ? bridge_data : local_data;
  @(negedge clk);
endtask
task automatic apb_word(input bit wr, input logic [31:0] addr, data);
  bus_word(wr,addr,data,result);
endtask
Read included file: watchdog_demo.svh
`include "time_bus_bfm.svh"
assign local_data = 0;
localparam DOG = 32'h1000_3000;
logic tick = 0, debug_halt = 0, dev_mode = 0, privileged = 1;
wire armed, irq, reset_req;
wire [3:0] remaining;
assign prdata = {25'b0,reset_req,irq,armed,remaining};
watchdog_supervisor dog(
  .clk, .reset_n, .tick, .debug_halt, .dev_mode, .privileged,
  .psel(psel && paddr[31:12] == DOG[31:12]), .penable, .pwrite,
  .offset(paddr[11:0]), .pwdata, .armed, .irq, .reset_req, .remaining
);
function automatic bit modeled_word(input bit wr, input logic [31:0] addr);
  return wr && (addr == DOG || addr == DOG+4 || addr == DOG+8);
endfunction
task automatic sample(input string label_text);
  $display("%s left=%0d irq=%b reset=%b",label_text,remaining,irq,reset_req);
endtask
task automatic elapse(input integer ticks);
  tick = 1;
  repeat (ticks) @(negedge clk);
  tick = 0;
endtask
task automatic configure;
  apb_word(1,DOG,'h51);
  apb_word(1,DOG,'ha2);
  apb_word(1,DOG+4,1);
endtask
Read included file: watchdog_supervisor.sv
// ap_soc teaching policy. Input tick is an enable from the supervision clock.
// A privileged boot writer may arm once. Reset request persists until reset.
module watchdog_supervisor (
  input logic clk, reset_n, tick, debug_halt, dev_mode, privileged,
  input logic psel, penable, pwrite,
  input logic [11:0] offset,
  input logic [31:0] pwdata,
  output logic armed, irq, reset_req,
  output logic [3:0] remaining
);
  localparam KEY = 0, CONTROL = 4, SERVICE = 8;
  localparam RELOAD = 6, OPEN = 3;
  logic first_key, unlocked;
  logic [1:0] grace;
  wire write_word = psel && penable && pwrite;
  wire arm = write_word && privileged && unlocked && offset == CONTROL && pwdata == 1;
  wire kick = write_word && offset == SERVICE && pwdata == 1;

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      first_key <= 0;
      unlocked <= 0;
      armed <= 0;
      remaining <= 0;
      irq <= 0;
      reset_req <= 0;
      grace <= 0;
    end else begin
      if (write_word) begin
        first_key <= privileged && offset == KEY && pwdata == 'h51;
        unlocked <= privileged && first_key && offset == KEY && pwdata == 'ha2;
      end
      if (!armed && arm) begin
        armed <= 1;
        remaining <= RELOAD;
      end else if (armed && !reset_req && !(dev_mode && debug_halt)) begin
        if (irq) begin
          if (tick && grace == 1) reset_req <= 1;
          else if (tick) grace <= grace - 1'b1;
        end else if ((kick && remaining > OPEN) || (tick && remaining == 1 && !kick)) begin
          irq <= 1;
          grace <= 2;
          remaining <= 0;
        end else if (kick) remaining <= RELOAD;
        else if (tick) remaining <= remaining - 1'b1;
      end
    end
  end
endmodule

Check Yourself

Predict the outputIn this run the watchdog is armed, five ticks pass, and then software kicks. What does the lab print?
`timescale 1ns/1ns
module tb;
  `include "watchdog_demo.svh"

  initial begin
    repeat (2) @(negedge clk);
    reset_n = 1;
    configure;
    elapse(5);
    apb_word(1,DOG+8,1);
    sample("service");
    $finish;
  end
endmodule
Read 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: time_bus_bfm.svh
// One manager issues aligned words. The P4 bridge and local time slice share HCLK.
// Only the lesson's implemented, always-ready register words are accessed.
logic clk = 0, reset_n = 0;
always #5 clk = ~clk;
logic [31:0] haddr = 0, hwdata = 0;
logic hwrite = 0;
logic [1:0] htrans = 0;
wire bridge_window = haddr[31:16] == 16'h1000;
wire [31:0] local_data, bridge_data, paddr, pwdata, prdata;
wire bridge_ready, hresp, psel, penable, pwrite;
logic bridge_response;
wire hready = !bridge_response || bridge_ready;
logic [31:0] result;
bit trace_access = 0;

always_ff @(posedge clk) begin
  if (!reset_n) bridge_response <= 0;
  else if (hready) bridge_response <= htrans[1] && bridge_window;
end
ahb_apb_bridge bridge (
  .hclk(clk), .hresetn(reset_n), .hsel(bridge_window), .haddr, .htrans, .hwrite,
  .hprot(4'b0011), .hwdata, .hwstrb(4'hf), .hready, .hreadyout(bridge_ready),
  .hresp, .hrdata(bridge_data), .psel, .penable, .pwrite, .paddr, .pwdata,
  .pstrb(), .pprot(), .pready(1'b1), .prdata, .pslverr(1'b0)
);
always @(posedge clk)
  if (trace_access && psel)
    if (penable) $display("access addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);
    else $display("setup addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);

task automatic bus_word(input bit wr, input logic [31:0] addr, data,
                        output logic [31:0] sample);
  if (!modeled_word(wr,addr))
    $fatal(1,"This target slice does not model that word operation at %08h",addr);
  @(negedge clk);
  haddr = addr;
  hwrite = wr;
  htrans = 2'b10;
  @(negedge clk);
  haddr = 0;
  htrans = 0;
  hwdata = data;
  do @(posedge clk); while (!hready);
  if (bridge_response && hresp) $fatal(1,"Bus error at %08h",addr);
  sample = bridge_response ? bridge_data : local_data;
  @(negedge clk);
endtask
task automatic apb_word(input bit wr, input logic [31:0] addr, data);
  bus_word(wr,addr,data,result);
endtask
Read included file: watchdog_demo.svh
`include "time_bus_bfm.svh"
assign local_data = 0;
localparam DOG = 32'h1000_3000;
logic tick = 0, debug_halt = 0, dev_mode = 0, privileged = 1;
wire armed, irq, reset_req;
wire [3:0] remaining;
assign prdata = {25'b0,reset_req,irq,armed,remaining};
watchdog_supervisor dog(
  .clk, .reset_n, .tick, .debug_halt, .dev_mode, .privileged,
  .psel(psel && paddr[31:12] == DOG[31:12]), .penable, .pwrite,
  .offset(paddr[11:0]), .pwdata, .armed, .irq, .reset_req, .remaining
);
function automatic bit modeled_word(input bit wr, input logic [31:0] addr);
  return wr && (addr == DOG || addr == DOG+4 || addr == DOG+8);
endfunction
task automatic sample(input string label_text);
  $display("%s left=%0d irq=%b reset=%b",label_text,remaining,irq,reset_req);
endtask
task automatic elapse(input integer ticks);
  tick = 1;
  repeat (ticks) @(negedge clk);
  tick = 0;
endtask
task automatic configure;
  apb_word(1,DOG,'h51);
  apb_word(1,DOG,'ha2);
  apb_word(1,DOG+4,1);
endtask
Read included file: watchdog_supervisor.sv
// ap_soc teaching policy. Input tick is an enable from the supervision clock.
// A privileged boot writer may arm once. Reset request persists until reset.
module watchdog_supervisor (
  input logic clk, reset_n, tick, debug_halt, dev_mode, privileged,
  input logic psel, penable, pwrite,
  input logic [11:0] offset,
  input logic [31:0] pwdata,
  output logic armed, irq, reset_req,
  output logic [3:0] remaining
);
  localparam KEY = 0, CONTROL = 4, SERVICE = 8;
  localparam RELOAD = 6, OPEN = 3;
  logic first_key, unlocked;
  logic [1:0] grace;
  wire write_word = psel && penable && pwrite;
  wire arm = write_word && privileged && unlocked && offset == CONTROL && pwdata == 1;
  wire kick = write_word && offset == SERVICE && pwdata == 1;

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      first_key <= 0;
      unlocked <= 0;
      armed <= 0;
      remaining <= 0;
      irq <= 0;
      reset_req <= 0;
      grace <= 0;
    end else begin
      if (write_word) begin
        first_key <= privileged && offset == KEY && pwdata == 'h51;
        unlocked <= privileged && first_key && offset == KEY && pwdata == 'ha2;
      end
      if (!armed && arm) begin
        armed <= 1;
        remaining <= RELOAD;
      end else if (armed && !reset_req && !(dev_mode && debug_halt)) begin
        if (irq) begin
          if (tick && grace == 1) reset_req <= 1;
          else if (tick) grace <= grace - 1'b1;
        end else if ((kick && remaining > OPEN) || (tick && remaining == 1 && !kick)) begin
          irq <= 1;
          grace <= 2;
          remaining <= 0;
        end else if (kick) remaining <= RELOAD;
        else if (tick) remaining <= remaining - 1'b1;
      end
    end
  end
endmodule
ConceptWhy does a watchdog have a counter of its own?
ConceptWhat should software have checked before it kicks?
ConceptWhy is a kick that comes too early a fault?
ConceptWhat happens, in order, after a missed kick?
ConceptWhy can software not switch the watchdog off?

Common Mistakes

Wrong Kick from any regular interrupt.

A handler can keep running while the real work hangs.

Fix Kick only when the supervised work has reported that it finished.

Wrong Kick as often as possible, to be safe.

A kick before the window opens is a fault.

Fix Kick once for each round of work, inside the window.

Wrong Expect a processor stopped by a debugger to pause every watchdog.

A shipped unit keeps counting while the processor is stopped.

Fix Find out the halt policy of the unit before you attach a debugger.

Remember

  • A watchdog is a counter of its own that resets the chip unless software kicks it in time.
  • A kick too early is a fault as well as a kick too late.
  • After a fault comes a warning, then a grace period, then a reset that software cannot stop.
  • A kick should prove that the work was done, not that an interrupt still fires.

Practice

Report a problem with this page