The Interrupt Controller: A PLIC

A processor has one wire for interrupts from devices. A chip has many devices. The interrupt controller stands between them: it chooses one request and tells the handler whose it is.

You Will Be Able To

  • Say what an interrupt controller is for, and what a gateway does with a request.
  • Predict which request wins from the pending bits, the enable bits, the priorities and the threshold.
  • Explain what a claim and a completion do, and why the device is served between them.
Lesson
S6.3
Time
28 min
Runs on
Your browser
Check
6 questions

A byte waits in UART0. At the same moment three other devices raise their wires too. The processor has one wire for all of them, and that wire can only say yes.

Before You Start

You need S0.8: an interrupt request, pending and the handler. You need Registers: a read can have a side effect.

You need Level, Edge and Write-1-to-Clear: a device keeps its request high until its cause is removed.

Five questions this page answers
Question
1Why does a chip put an interrupt controller between its devices and the processor?
2What does a gateway do with a request wire that stays high?
3Which requests compete, and which one wins?
4What does the threshold decide?
5What do a claim and a completion each do, and what must the handler do between them?

The Idea: Choose One, and Say Which

In S0.8 one timer had one wire to the processor. A chip has many devices, and the processor still has one wire for them. Someone must join the wires, and a plain OR gate is not enough.

An OR gate loses two things. It loses the order: an urgent request and a trivial one look the same. And it loses the name: the handler would have to ask every device in turn. An interrupt controller keeps both. It picks the most urgent request, and it hands the handler the number of the device that made it.

It also keeps count, in a small way. A device holds its wire high for as long as it needs service. That must become one request, not one for every clock. So each wire enters through a gateway, which passes one request on and then waits until the handler says it has finished.

The controller on this page follows the RISC-V design named PLIC, the platform-level interrupt controller. Ours is called ap_plic.

New Words

New words on this page
WordMeaning
Interrupt controllerThe block that takes the request wires of many devices and drives one wire to the processor.
PLICPlatform-level interrupt controller: the RISC-V kind of interrupt controller.
Source IDThe number of one request wire into the controller. Each such wire is called a source. IDs start at 1, and 0 means "none".
GatewayThe entrance of one source. It passes one request on, then waits until the handler has finished.
Source priorityA number that software gives each source. A higher number is more urgent. 0 means "never". Priority for short.
ThresholdA number that software gives the controller. The wire to the processor is 1 only for a priority above it.
ClaimA read of the claim and complete word. It returns the ID of the winner and clears its pending bit.
CompletionA write of an ID to the same word. It tells the gateway of that source to open again.

Three words you know are used again here, each for one source of the controller. A pending bit is 1 from the moment a gateway passes a request until a claim takes it. An enable bit lets the source compete. To mask a source is to clear that bit.

One Picture: Four Requests, One Answer

Four Devices, One Wire, One QuestionStep through the picture. It follows four requests into the controller and one answer out of it.
  • Peripheral
  • Bus
  • Memory
  • Processor
Four Devices, One Wire, One QuestionStep through the picture. It follows four requests into the controller and one answer out of it. component UART0 source 1, priority 5 component GPIO source 2, priority 5 component Timer and PWM source 3, priority 2 component SPI source 4, priority 7,not enabled component Gateways one for each source:pass one request,then wait component The choice pending, enabled,highest priority,lowest ID component Claim and completeword read it to claim, writeit to complete component Processor sees one wire request 1request 2request 3request 4pending bitsinterrupt wire: 1 ifthe winner is abovethe thresholdthe ID of the winnera completion reopensone gateway
  1. component UART0source 1, priority 5
    • request 1 → Gateways
  2. component GPIOsource 2, priority 5
    • request 2 → Gateways
  3. component Timer and PWMsource 3, priority 2
    • request 3 → Gateways
  4. component SPIsource 4, priority 7, not enabled
    • request 4 → Gateways
  5. component Gatewaysone for each source: pass one request, then wait
    • pending bits → The choice
  6. component The choicepending, enabled, highest priority, lowest ID
    • interrupt wire: 1 if the winner is above the threshold → Processor
    • the ID of the winner → Claim and complete word
  7. component Processorsees one wire
  8. component Claim and complete wordread it to claim, write it to complete
    • a completion reopens one gateway → Gateways
  1. Four requests

    Each device raises its own wire. Each wire enters the controller through its own gateway. The gateway passes one request on and sets a pending bit for it.

  2. The choice

    Only pending sources that are enabled compete. SPI is not enabled, so it waits. Of the rest, the highest priority wins. UART0 and GPIO tie at 5, and the lower ID wins: UART0.

  3. The wire

    Software gives the controller one more number, the threshold. The wire to the processor is 1 only if the priority of the winner is above it. With the threshold at 5 the wire stays 0. At 4 it goes to 1.

  4. The claim

    The wire says only "someone". The handler reads the claim and complete word. The read returns 1, the ID of UART0, and clears its pending bit.

  5. The completion

    The handler serves UART0. Then it writes the same ID, 1, to the same word. That reopens the gateway of source 1, and UART0 may ask again.

Read the diagram as text
  • UART0: source 1, priority 5
  • GPIO: source 2, priority 5
  • Timer and PWM: source 3, priority 2
  • SPI: source 4, priority 7, not enabled
  • Gateways: one for each source: pass one request, then wait
  • The choice: pending, enabled, highest priority, lowest ID
  • Claim and complete word: read it to claim, write it to complete
  • Processor: sees one wire
  • UART0 → Gateways: request 1
  • GPIO → Gateways: request 2
  • Timer and PWM → Gateways: request 3
  • SPI → Gateways: request 4
  • Gateways → The choice: pending bits
  • The choice → Processor: interrupt wire: 1 if the winner is above the threshold
  • The choice → Claim and complete word: the ID of the winner
  • Claim and complete word → Gateways: a completion reopens one gateway

The lab of this page: ap_plic with four of its sixteen sources in use. The priorities and the enable bits are set by the test code.

Software reaches the controller through registers, like any device. These are the ones this page uses. The controller sits at address 0x0C00_0000.

Registers of ap_plic used on this page
OffsetRegisterAccess type
4 times the IDPriority of that source, 0 to 7RW
0x2000Enable bits. Bit 1 is source 1, bit 2 is source 2, and so onRW
0x20_0000Threshold, 0 to 7RW
0x20_0004Claim and complete worda read claims, a write completes

The Smallest Example, Worked by Hand

Four devices ask at the same moment. Software has set them up like this.

The four sources of the example
Source IDDevicePriorityEnabledAsking
1UART05yesyes
2GPIO5yesyes
3Timer and PWM2yesyes
4SPI7noyes

Now follow the handler. The pending bits are written for sources 4, 3, 2, 1, from left to right. Work out the winner in each row before you read it.

Six steps, by hand
StepWhat the handler doesWho competesWinnerWire to the processorPending bits afterwards
1Nothing yet. The threshold is 5.1, 2, 31: it ties with 2, and has the lower ID0: priority 5 is not above 51111
2Writes 4 to the threshold1, 2, 311: priority 5 is above 41111
3Claims, and reads 12, 321: priority 5 is above 41110
4Claims, and reads 2330: priority 2 is not above 41100
5Claims, and reads 3nobodynone01000
6Claims, and reads 0nobodynone01000

Three things in that table surprise people. SPI has the highest priority and is never chosen, because it is not enabled. Its pending bit stays 1 the whole time. The claim in step 5 returns the timer although the wire is 0. And a claim with nothing to return is not an error: it reads 0.

The Rules

These are the rules of ap_plic. Where another controller of the same kind may differ, the rule says so.

  1. Rule 1: A gateway passes one request at a time.

    It sets the pending bit of its source. It passes nothing more until a completion names that source.

  2. Rule 2: A source competes only if it is pending, enabled and has a priority above 0.

    Masking a source does not clear its pending bit. The request waits.

  3. Rule 3: The highest priority wins. On a tie, the lowest ID wins.

    The order of arrival plays no part.

  4. Rule 4: The wire is 1 only if the priority of the winner is above the threshold.

    Equal is not above. A threshold of 0 lets every competing source through.

  5. Rule 5: A claim returns the ID of the winner and clears its pending bit.

    It returns 0 if nobody competes. In this chip a claim does not look at the threshold. That is our choice.

  6. Rule 6: A completion reopens one gateway.

    The handler writes the ID it claimed. If the request wire of that source is still 1, a new request is passed at once.

Sources for These Rules

Every rule above is read from our own controller, ap_plic, and each row on this page is recorded from it.

The words gateway, priority, threshold, claim and completion, and the shape of the design, are those of the RISC-V PLIC specification. Our reference library does not hold that document. So this page states no rule as a rule of that specification. Treat the names as RISC-V facts.

Why devices interrupt at all: Harris and Harris, Digital Design and Computer Architecture, ARM edition, section 9.3.7.

The bus read behind a claim: Arm AMBA AHB Protocol Specification, IHI 0033 issue C. See sections 3.1 and 4.2 to 4.3.

Three-bit priorities, sixteen sources, the register offsets and the source numbers of the devices are our own choices for ap_soc.

Now Run It

The lab at the end of this page runs the six steps on ap_plic, and then goes on to a completion. Test code, a bus-functional model, plays the handler and the four devices.

Printed by the lab. The four-bit values are written for sources 4, 3, 2, 1. The names are listed with the lab.
arrival level=1111 pending=1111 busy=1111 irq=0
threshold level=1111 pending=1111 busy=1111 irq=1
bus address_phase=1 data_phase=0 addr=0c200004 read_id=0
bus address_phase=0 data_phase=1 addr=0c200004 read_id=1
claim id=1 pending=1110 busy=1111 irq=1 tick=2
claim id=2 pending=1100 busy=1111 irq=0 tick=4
claim id=3 pending=1000 busy=1111 irq=0 tick=6
claim id=0 pending=1000 busy=1111 irq=0 tick=8
complete level=1111 pending=1000 busy=1110 irq=0 tick=10
again level=1111 pending=1001 busy=1111 irq=1 tick=11
claim id=1 pending=1000 busy=1111 irq=0 tick=13
drained level=1110 pending=1000 busy=1110 irq=0

Rule 4 at work: the "arrival" row has irq=0 with four requests pending, and the "threshold" row has irq=1. Nothing changed but the threshold. Rule 3 at work: the first claim returns 1 and the second returns 2.

Rule 5 at work: the third claim returns 3 while irq is 0, and the fourth returns 0. Look at the pending bits beside each claim. One bit falls each time, and the left bit, SPI, never does.

The two rows that start with "bus" are the first claim on the bus. The read returns its ID in the data phase. That read is the claim. There is no other signal.

Rule 1 at work: after four claims, busy is still 1111. Every gateway is waiting. Now the handler makes a mistake on purpose.

Claims and One Early Completion, RecordedEach mark is one finished bus transfer of the handler, placed at the clock tick the lab printed.
012345678910111213clkclaimcompleteagain
Scroll horizontally ↔
  1. Cycle 2

    A claim returns ID 1.

  2. Cycle 4

    A claim returns ID 2.

  3. Cycle 6

    A claim returns ID 3.

  4. Cycle 8

    A claim returns 0: nothing is left to claim.

  5. Cycle 10

    The handler completes ID 1 while UART0 still holds its wire high.

  6. Cycle 11

    One tick later the reopened gateway has passed a new request for UART0.

  7. Cycle 13

    A claim returns ID 1.

Built from the recorded rows. The lane named "again" marks the tick at which the pending bit of UART0 is set a second time.

Rule 6 at work: the "complete" row reopens the gateway of source 1, and busy becomes 1110. UART0 still holds its wire high. One tick later, in the "again" row, pending is 1001 and irq is 1. The handler has been called back for a byte it had not finished with.

The second time, the test code makes UART0 go quiet first and completes afterwards. The "drained" row has irq=0, and the pending bit of UART0 stays 0.

This lab leaves things out. No processor is here: the wire named irq ends in the test code. The four request wires are driven by the test code, not by real devices.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
A gateway for each sourcePass the level straight to the pending bitA device that holds its wire high makes one request, not a stream. The handler must complete, or the source stays shut.
Priorities in registersA fixed order built into the chipSoftware decides what is urgent for this product. It must set every priority at start-up: after reset they are all 0.
Enable bits beside the prioritiesSet the priority to 0 to silence a sourceA source can be silenced and brought back without forgetting its priority.
One thresholdClear many enable bits and set them againOne write silences everything at or below a level. It is quick to do inside a handler.
Claim by a readA second set of wires that carries the IDThe processor needs one wire only. The cost: the read has a side effect, like an RC field.
The lowest ID wins a tieThe source that asked first winsThe answer can be worked out from the registers alone. A source with a high ID can wait a long time.

The Trap: Complete First, Serve Later

The "again" row is the most common fault in a new handler. The code claims, completes at once to "free the controller", and only then reads the byte from UART0. The gateway opens while the wire is still high. The handler runs twice for one byte, and the second time it finds nothing to do.

On a busy system that doubles the interrupt load of every device served this way. Nothing fails. The product is only slow, and the counters of interrupts are twice what the traffic explains. Serve the device, see its request fall, then complete.

A second trap comes from the claim being a read. A debugger that shows the claim word has made a claim. The pending bit is cleared, and the real handler reads 0. It is the read-to-clear fault of the Registers page, in another place.

A third: a claim that returns 0 means "nothing that competes". It does not mean "no device is asking". SPI asked through this whole run.

At Scale

This page4 sources, 1 processor
A large chiphundreds of sources, several processors

This section looks ahead. A large chip has hundreds of sources and several processors. The six rules stay the same.

  1. More than one processor

    A PLIC can serve several processors. Each one gets its own enable bits, threshold and claim word, and one source can be offered to several. This is a RISC-V fact.

  2. A tie rule is not a waiting-time promise

    The lowest ID always wins a tie, so a high ID can starve. Fairer ways to choose are in arbiters.

  3. One pending bit cannot count

    A pending bit holds one request. If bytes are lost, count them at the device, not at the controller.

  4. The whole path

    The next page, The Interrupt Path, follows one request from a device through this controller to the handler and back.

Try It

Run the lab. Read the four claims in order and say why each ID came out.

Change the enable bits from 01110 to 11110, which lets SPI compete. Predict the first claim, and the wire in the "arrival" row.

Move the line that makes UART0 go quiet to just before the first completion. Predict the row marked "again".

Names Printed by the Lab
NameMeaning
levelThe four request wires, source 4 on the left and source 1 on the right.
pendingThe four pending bits, in the same order.
busyOne bit for each gateway: 1 while it waits for a completion.
irqThe one wire to the processor.
tickClock edges counted from the write that set the threshold to 4.
address_phase, data_phase, read_idIn a row that starts with "bus": the two halves of one AHB read, and the ID it returns.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: arrival level=1111 pending=1111 busy=1111 irq=0 threshold level=1111 pending=1111 busy=1111 irq=1 bus address_phase=1 data_phase=0 addr=0c200004 read_id=0 bus address_phase=0 data_phase=1 addr=0c200004 read_id=1 claim id=1 pending=1110 busy=1111 irq=1 tick=2 claim id=2 pending=1100 busy=1111 irq=0 tick=4 claim id=3 pending=1000 busy=1111 irq=0 tick=6 claim id=0 pending=1000 busy=1111 irq=0 tick=8 complete level=1111 pending=1000 busy=1110 irq=0 tick=10 again level=1111 pending=1001 busy=1111 irq=1 tick=11 claim id=1 pending=1000 busy=1111 irq=0 tick=13 drained level=1110 pending=1000 busy=1110 irq=0
Read included file: ahb_pkg.sv
`timescale 1ns/1ns
// ahb_pkg.sv: the encodings and the arithmetic of a burst (read-only).
// The memory, the driver, the checker and the lesson text all use these functions, so they never
// disagree about the address of a beat or the lanes it uses.
package ahb_pkg;
  localparam logic [1:0] IDLE = 2'b00, BUSY = 2'b01, NONSEQ = 2'b10, SEQ = 2'b11;
  localparam logic [2:0] SINGLE = 3'b000, INCR = 3'b001, WRAP4 = 3'b010, INCR4 = 3'b011,
                         WRAP8 = 3'b100, INCR8 = 3'b101, WRAP16 = 3'b110, INCR16 = 3'b111;
  localparam logic OKAY = 1'b0, ERROR = 1'b1;

  function automatic string trans_name(input logic [1:0] t);
    case (t) IDLE: return "IDLE"; BUSY: return "BUSY"; NONSEQ: return "NONSEQ"; default: return "SEQ"; endcase
  endfunction
  function automatic string burst_name(input logic [2:0] b);
    case (b)
      SINGLE: return "SINGLE"; INCR: return "INCR"; WRAP4: return "WRAP4"; INCR4: return "INCR4";
      WRAP8: return "WRAP8"; INCR8: return "INCR8"; WRAP16: return "WRAP16"; default: return "INCR16";
    endcase
  endfunction
  function automatic string resp_name(input logic r);
    return r ? "ERROR" : "OKAY";
  endfunction
  // s when c is 1, else the empty string (a string-typed result prints the same on every simulator).
  function automatic string opt(input bit c, input string s);
    if (c) return s;
    return "";
  endfunction

  // Beats in a burst: 1 for SINGLE, 4, 8 or 16 for the fixed bursts, 0 for INCR (undefined length).
  function automatic int beats_of(input logic [2:0] b);
    case (b) SINGLE: return 1; INCR: return 0; WRAP4, INCR4: return 4; WRAP8, INCR8: return 8; default: return 16; endcase
  endfunction
  function automatic bit is_wrap(input logic [2:0] b);
    return b == WRAP4 || b == WRAP8 || b == WRAP16;
  endfunction

  // The address of the beat after the one at a: the size in bytes further on; a wrapping burst
  // returns to the start of its window (beats x size bytes, aligned to that total) at the window's end.
  function automatic int unsigned next_addr(input int unsigned a, input logic [2:0] size, input logic [2:0] b);
    int unsigned nb = 1 << size;
    int unsigned window = nb * beats_of(b);
    int unsigned base;
    if (!is_wrap(b)) return a + nb;
    base = (a / window) * window;
    if (a + nb >= base + window) return base;
    return a + nb;
  endfunction

  // The address of beat n of a burst that starts at start.
  function automatic int unsigned beat_addr(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int unsigned a = start;
    for (int k = 0; k < n; k++) a = next_addr(a, size, b);
    return a;
  endfunction

  // The lanes a transfer at address a uses on a bus of bus_bytes bytes, packed as {upper, lower}.
  // Every AHB transfer is aligned to its size, so it uses size bytes from its own lane upwards.
  function automatic logic [15:0] beat_lanes(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    int lower = a % bus_bytes;
    int upper = lower + (1 << size) - 1;
    if (upper > bus_bytes - 1) upper = bus_bytes - 1;
    return {upper[7:0], lower[7:0]};
  endfunction

  // The strobe of a transfer: a 1 for every lane it uses (bit l is lane l).
  function automatic logic [63:0] beat_strb(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    logic [15:0] lanes = beat_lanes(a, size, bus_bytes);
    logic [63:0] s = 0;
    for (int l = lanes[7:0]; l <= lanes[15:8]; l++) s[l] = 1'b1;
    return s;
  endfunction

  function automatic bit aligned(input int unsigned a, input logic [2:0] size);
    return (a % (1 << size)) == 0;
  endfunction

  // True when an incrementing burst of n beats (n is used only for INCR) crosses a 1 KB boundary.
  function automatic bit crosses_1k(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int beats = beats_of(b) ? beats_of(b) : n;
    if (is_wrap(b) || beats < 2) return 0;
    return (start / 1024) != ((start + beats * (1 << size) - 1) / 1024);
  endfunction
endpackage
Read included file: irq_word_bfm.svh
// Single aligned words, always-ready target, one outstanding request.
// htrans[1] marks address acceptance; active marks its following data phase.
import ahb_pkg::IDLE;
import ahb_pkg::NONSEQ;
logic clk = 0, reset_n = 0;
always #5 clk = !clk;
integer edge_no = 0;
logic [1:0] htrans = IDLE;
logic hwrite = 0, active = 0, write_en = 0;
logic [31:0] haddr = 0, addr = 0, wdata = 0;
wire [31:0] rdata;
always @(posedge clk) begin
  edge_no <= edge_no + 1;
  active <= htrans[1];
  if (htrans[1]) begin
    addr <= haddr;
    write_en <= hwrite;
  end
end
task automatic word(input bit wr, input logic [31:0] target, payload,
                    output logic [31:0] result);
  @(negedge clk);
  htrans = NONSEQ;
  haddr = target;
  hwrite = wr;
  @(negedge clk);
  htrans = IDLE;
  wdata = payload;
  @(posedge clk);
  result = rdata;
  #1;
endtask
Read included file: ap_irq_map.svh
// ap_soc external interrupt sources: the ID each device has at ap_plic.
// ID 0 means "no interrupt". IDs 7 to 16 are spare inputs with no device.
// The single home of these numbers; docs/soc/ap_soc-facts.md quotes this file.
localparam int UART0_ID = 1, GPIO_ID = 2, TIMER_ID = 3, SPI_ID = 4, DMA_ID = 5, WATCHDOG_ID = 6;
Read included file: ap_plic.sv
// One machine context, synchronous level sources. Register-side interface:
// commit pulses once at a successful word transfer's data edge.
module ap_plic #(parameter integer SOURCES = 16) (
  input logic clk, reset_n, commit, write_en,
  input logic [21:0] offset,
  input logic [31:0] wdata,
  input logic [SOURCES:1] level_irq,
  output logic [31:0] rdata,
  output logic notify_irq
);
  localparam ENABLE = 'h2000, THRESHOLD = 'h200000, CLAIM = 'h200004;
  logic [2:0] weight [1:SOURCES];
  logic [2:0] threshold, best;
  logic [SOURCES:1] pending, busy, enabled;
  integer winner;

  always_comb begin
    best = 0;
    winner = 0;
    for (int id = 1; id <= SOURCES; id++) begin
      if (pending[id] && enabled[id] && weight[id] > best) begin
        best = weight[id];
        winner = id;
      end
    end
    notify_irq = best > threshold;
    rdata = 0;
    for (int id = 1; id <= SOURCES; id++) begin
      if (offset == 4*id) rdata = weight[id];
      if (offset == 'h1000 + 4*(id/32)) rdata[id%32] = pending[id];
      if (offset == ENABLE + 4*(id/32)) rdata[id%32] = enabled[id];
    end
    case (offset)
      THRESHOLD: rdata = threshold;
      CLAIM: rdata = winner;
    endcase
  end

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      pending <= '0;
      busy <= '0;
      enabled <= '0;
      threshold <= 0;
      for (int id = 1; id <= SOURCES; id++) weight[id] <= 0;
    end else begin
      for (int id = 1; id <= SOURCES; id++) begin
        if (level_irq[id] && !busy[id]) begin
          pending[id] <= 1;
          busy[id] <= 1;
        end
        if (commit && write_en && offset == 4*id) weight[id] <= wdata[2:0];
        if (commit && write_en && offset == ENABLE + 4*(id/32))
          enabled[id] <= wdata[id%32];
        if (commit && offset == CLAIM) begin
          if (!write_en && winner == id) pending[id] <= 0;
          if (write_en && enabled[id] && wdata == id && busy[id] && !pending[id]) busy[id] <= 0;
        end
      end
      if (commit && write_en && offset == THRESHOLD) threshold <= wdata[2:0];
    end
  end
endmodule

Check Yourself

Predict the outputIn this run the test code makes GPIO go quiet, not UART0, before the last completion of ID 1. What is the last row?
module tb;
  `include "irq_word_bfm.svh"
  `include "ap_irq_map.svh"
  localparam BASE = 32'h0c000000, CLAIM = BASE+'h200004;  // ap_plic, and its claim and complete word
  logic [4:1] level_irq = 0;   // the request wires of sources 4, 3, 2, 1
  logic [31:0] value;
  wire notify_irq;             // the one wire to the processor
  // word(1, address, data, value) is one bus write. word(0, address, 0, value) is one bus read.
  ap_plic #(.SOURCES(4)) dut(.offset(addr[21:0]),.commit(active && addr[31:22]==BASE[31:22]),.*);
  bit trace_claim = 0;
  integer service_start;
  always @(posedge clk) if (trace_claim && (htrans[1] || active))
    $display("bus address_phase=%b data_phase=%b addr=%08h read_id=%0d",htrans[1],active,
             htrans[1] ? haddr : addr,active ? rdata : 0);
  task automatic show(input string event_name);
    if (event_name=="complete" || event_name=="again")
      $display("%s level=%b pending=%b busy=%b irq=%b tick=%0d",event_name,level_irq,dut.pending,dut.busy,notify_irq,edge_no-service_start);
    else
      $display("%s level=%b pending=%b busy=%b irq=%b",event_name,level_irq,dut.pending,dut.busy,notify_irq);
  endtask
  task automatic claim;
    word(0,CLAIM,0,value);
    $display("claim id=%0d pending=%b busy=%b irq=%b tick=%0d",value,dut.pending,dut.busy,notify_irq,edge_no-service_start);
  endtask
  initial begin
    @(negedge clk); reset_n = 1;
    word(1,BASE+4*UART0_ID,5,value);   // one priority word for each source
    word(1,BASE+4*GPIO_ID,5,value);
    word(1,BASE+4*TIMER_ID,2,value);
    word(1,BASE+4*SPI_ID,7,value);
    word(1,BASE+'h2000,'b01110,value); // enable IDs 1 to 3; SPI stays disabled
    word(1,BASE+'h200000,5,value);     // threshold = 5
    @(negedge clk); level_irq = 4'b1111; // all four devices ask at once
    @(negedge clk); show("arrival");
    word(1,BASE+'h200000,4,value); show("threshold");   // threshold = 4
    service_start = edge_no;
    trace_claim = 1; claim(); trace_claim = 0;
    claim(); claim(); claim();
    word(1,CLAIM,UART0_ID,value); show("complete");    // complete too early: UART0 still asks
    @(posedge clk); #1; show("again");
    claim();
    @(negedge clk); level_irq[GPIO_ID] = 0;         // the device is served and goes quiet
    word(1,CLAIM,UART0_ID,value);                    // now complete
    @(posedge clk); #1; show("drained");
    $finish;
  end
endmodule
Read included file: ahb_pkg.sv
`timescale 1ns/1ns
// ahb_pkg.sv: the encodings and the arithmetic of a burst (read-only).
// The memory, the driver, the checker and the lesson text all use these functions, so they never
// disagree about the address of a beat or the lanes it uses.
package ahb_pkg;
  localparam logic [1:0] IDLE = 2'b00, BUSY = 2'b01, NONSEQ = 2'b10, SEQ = 2'b11;
  localparam logic [2:0] SINGLE = 3'b000, INCR = 3'b001, WRAP4 = 3'b010, INCR4 = 3'b011,
                         WRAP8 = 3'b100, INCR8 = 3'b101, WRAP16 = 3'b110, INCR16 = 3'b111;
  localparam logic OKAY = 1'b0, ERROR = 1'b1;

  function automatic string trans_name(input logic [1:0] t);
    case (t) IDLE: return "IDLE"; BUSY: return "BUSY"; NONSEQ: return "NONSEQ"; default: return "SEQ"; endcase
  endfunction
  function automatic string burst_name(input logic [2:0] b);
    case (b)
      SINGLE: return "SINGLE"; INCR: return "INCR"; WRAP4: return "WRAP4"; INCR4: return "INCR4";
      WRAP8: return "WRAP8"; INCR8: return "INCR8"; WRAP16: return "WRAP16"; default: return "INCR16";
    endcase
  endfunction
  function automatic string resp_name(input logic r);
    return r ? "ERROR" : "OKAY";
  endfunction
  // s when c is 1, else the empty string (a string-typed result prints the same on every simulator).
  function automatic string opt(input bit c, input string s);
    if (c) return s;
    return "";
  endfunction

  // Beats in a burst: 1 for SINGLE, 4, 8 or 16 for the fixed bursts, 0 for INCR (undefined length).
  function automatic int beats_of(input logic [2:0] b);
    case (b) SINGLE: return 1; INCR: return 0; WRAP4, INCR4: return 4; WRAP8, INCR8: return 8; default: return 16; endcase
  endfunction
  function automatic bit is_wrap(input logic [2:0] b);
    return b == WRAP4 || b == WRAP8 || b == WRAP16;
  endfunction

  // The address of the beat after the one at a: the size in bytes further on; a wrapping burst
  // returns to the start of its window (beats x size bytes, aligned to that total) at the window's end.
  function automatic int unsigned next_addr(input int unsigned a, input logic [2:0] size, input logic [2:0] b);
    int unsigned nb = 1 << size;
    int unsigned window = nb * beats_of(b);
    int unsigned base;
    if (!is_wrap(b)) return a + nb;
    base = (a / window) * window;
    if (a + nb >= base + window) return base;
    return a + nb;
  endfunction

  // The address of beat n of a burst that starts at start.
  function automatic int unsigned beat_addr(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int unsigned a = start;
    for (int k = 0; k < n; k++) a = next_addr(a, size, b);
    return a;
  endfunction

  // The lanes a transfer at address a uses on a bus of bus_bytes bytes, packed as {upper, lower}.
  // Every AHB transfer is aligned to its size, so it uses size bytes from its own lane upwards.
  function automatic logic [15:0] beat_lanes(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    int lower = a % bus_bytes;
    int upper = lower + (1 << size) - 1;
    if (upper > bus_bytes - 1) upper = bus_bytes - 1;
    return {upper[7:0], lower[7:0]};
  endfunction

  // The strobe of a transfer: a 1 for every lane it uses (bit l is lane l).
  function automatic logic [63:0] beat_strb(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    logic [15:0] lanes = beat_lanes(a, size, bus_bytes);
    logic [63:0] s = 0;
    for (int l = lanes[7:0]; l <= lanes[15:8]; l++) s[l] = 1'b1;
    return s;
  endfunction

  function automatic bit aligned(input int unsigned a, input logic [2:0] size);
    return (a % (1 << size)) == 0;
  endfunction

  // True when an incrementing burst of n beats (n is used only for INCR) crosses a 1 KB boundary.
  function automatic bit crosses_1k(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int beats = beats_of(b) ? beats_of(b) : n;
    if (is_wrap(b) || beats < 2) return 0;
    return (start / 1024) != ((start + beats * (1 << size) - 1) / 1024);
  endfunction
endpackage
Read included file: irq_word_bfm.svh
// Single aligned words, always-ready target, one outstanding request.
// htrans[1] marks address acceptance; active marks its following data phase.
import ahb_pkg::IDLE;
import ahb_pkg::NONSEQ;
logic clk = 0, reset_n = 0;
always #5 clk = !clk;
integer edge_no = 0;
logic [1:0] htrans = IDLE;
logic hwrite = 0, active = 0, write_en = 0;
logic [31:0] haddr = 0, addr = 0, wdata = 0;
wire [31:0] rdata;
always @(posedge clk) begin
  edge_no <= edge_no + 1;
  active <= htrans[1];
  if (htrans[1]) begin
    addr <= haddr;
    write_en <= hwrite;
  end
end
task automatic word(input bit wr, input logic [31:0] target, payload,
                    output logic [31:0] result);
  @(negedge clk);
  htrans = NONSEQ;
  haddr = target;
  hwrite = wr;
  @(negedge clk);
  htrans = IDLE;
  wdata = payload;
  @(posedge clk);
  result = rdata;
  #1;
endtask
Read included file: ap_irq_map.svh
// ap_soc external interrupt sources: the ID each device has at ap_plic.
// ID 0 means "no interrupt". IDs 7 to 16 are spare inputs with no device.
// The single home of these numbers; docs/soc/ap_soc-facts.md quotes this file.
localparam int UART0_ID = 1, GPIO_ID = 2, TIMER_ID = 3, SPI_ID = 4, DMA_ID = 5, WATCHDOG_ID = 6;
Read included file: ap_plic.sv
// One machine context, synchronous level sources. Register-side interface:
// commit pulses once at a successful word transfer's data edge.
module ap_plic #(parameter integer SOURCES = 16) (
  input logic clk, reset_n, commit, write_en,
  input logic [21:0] offset,
  input logic [31:0] wdata,
  input logic [SOURCES:1] level_irq,
  output logic [31:0] rdata,
  output logic notify_irq
);
  localparam ENABLE = 'h2000, THRESHOLD = 'h200000, CLAIM = 'h200004;
  logic [2:0] weight [1:SOURCES];
  logic [2:0] threshold, best;
  logic [SOURCES:1] pending, busy, enabled;
  integer winner;

  always_comb begin
    best = 0;
    winner = 0;
    for (int id = 1; id <= SOURCES; id++) begin
      if (pending[id] && enabled[id] && weight[id] > best) begin
        best = weight[id];
        winner = id;
      end
    end
    notify_irq = best > threshold;
    rdata = 0;
    for (int id = 1; id <= SOURCES; id++) begin
      if (offset == 4*id) rdata = weight[id];
      if (offset == 'h1000 + 4*(id/32)) rdata[id%32] = pending[id];
      if (offset == ENABLE + 4*(id/32)) rdata[id%32] = enabled[id];
    end
    case (offset)
      THRESHOLD: rdata = threshold;
      CLAIM: rdata = winner;
    endcase
  end

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      pending <= '0;
      busy <= '0;
      enabled <= '0;
      threshold <= 0;
      for (int id = 1; id <= SOURCES; id++) weight[id] <= 0;
    end else begin
      for (int id = 1; id <= SOURCES; id++) begin
        if (level_irq[id] && !busy[id]) begin
          pending[id] <= 1;
          busy[id] <= 1;
        end
        if (commit && write_en && offset == 4*id) weight[id] <= wdata[2:0];
        if (commit && write_en && offset == ENABLE + 4*(id/32))
          enabled[id] <= wdata[id%32];
        if (commit && offset == CLAIM) begin
          if (!write_en && winner == id) pending[id] <= 0;
          if (write_en && enabled[id] && wdata == id && busy[id] && !pending[id]) busy[id] <= 0;
        end
      end
      if (commit && write_en && offset == THRESHOLD) threshold <= wdata[2:0];
    end
  end
endmodule
ConceptWhat does an interrupt controller give the handler that an OR gate cannot?
ConceptA device holds its request wire high for a hundred clocks. How many requests does its gateway pass before a completion?
ConceptSources 2 and 3 are pending and enabled, both with priority 6. Source 4 is pending with priority 7 and not enabled. Who wins?
ConceptThe winner has priority 4 and the threshold is 4. What is the wire to the processor?
ConceptIn which order must a handler work?

Common Mistakes

Wrong Complete before the device has been served.

The gateway opens while the request wire is still high.

Fix Serve the device, let its request fall, then complete.

Wrong Expect the highest priority to win always.

A source that is not enabled does not compete.

Fix Check the enable bit first, then the priority, then the ID.

Wrong Read the claim word to see who is waiting.

The read is a claim. It clears a pending bit.

Fix Read the pending bits. That read has no side effect.

Remember

  • An interrupt controller joins many request wires into one, and keeps the order and the name.
  • A gateway turns a wire that stays high into one request, until a completion reopens it.
  • Pending and enabled sources compete. The highest priority wins, and the lowest ID wins a tie.
  • The threshold gates the wire to the processor. In ap_plic it does not gate a claim.
  • Claim, serve the device, then complete. Completing early brings the same request back.

Practice

Report a problem with this page