Drivers: Polling, Interrupts or DMA

UART0 has room for one letter. You have four to send and another job waiting. Who should spend the time between letters?

You Will Be Able To

  • Follow the register accesses that deliver one byte to a device.
  • Tell being told when to act from moving the data.
  • Compare processor time with elapsed time for polling, interrupts and DMA.
Lesson
S6.9
Time
26 min
Runs on
Your browser
Check
6 questions

Your console prints "send" every time you ask. Then you switch on a second job, and it misses its deadline. How much of the processor did those four letters borrow?

Before You Start

You need Registers: a device driver talks to a device through its registers. You need The Interrupt Path: a request, a handler and a return.

You need S0.5: a register access crosses the bridge to APB, with a setup phase and an access phase.

Five questions this page answers
Question
1What must a driver find out before it writes a byte to a device?
2What does polling cost the processor?
3What does an interrupt do for the driver, and what does it leave to the handler?
4What does DMA take over, and what does it cost?
5Why can the method with the least processor time finish last?

The Idea: Someone Has to Wait

A device is slow and a processor is fast. UART0 sends a letter down a wire one bit at a time. While it does, it has no room for the next letter. A driver that writes too soon loses a letter.

So between two letters someone has to wait. Three methods differ in who that is, and in who then carries the letter to the device.

MethodWho waits for roomWho carries each letter
PollingThe processor: it asks again and againThe processor
InterruptThe device: it calls when it has roomThe processor, in a handler
DMAA DMA controllerThe DMA controller

None of the three is the best one. Each has a price, and the prices are paid in two different coins. One coin is processor time: clock cycles in which the processor can do nothing else. The other is elapsed time: how long until the last letter is in the device.

New Words

New words on this page
WordMeaning
Room bitA bit in the status register of a device. It is 1 while the device can take one more byte: the device has room.
PollingReading a status register again and again until it gives the answer you wait for. One such read is a poll.
Transmit data registerThe register of UART0 that takes one byte to send.
DMA controllerA block that copies bytes between memory and a device by itself. DMA is short for direct memory access.
Set-up costWhat a method costs once, however many bytes follow.
Processor timeClock cycles in which the processor is occupied by this job. The lab prints it as "busy".
Elapsed timeClock cycles from the start of the job until the device has taken the last byte.

One Picture: Three Methods

Three Ways to Send One MessageStep through the picture. Each step is one method. Watch who waits, and who carries the letters.
  • Processor
  • Peripheral
  • Memory
  • Bus
Three Ways to Send One MessageStep through the picture. Each step is one method. Watch who waits, and who carries the letters. component Processor runs the devicedriver component UART0 room for one letterat a time component Memory holds the message component DMA controller a second manager onthe bus read status, againand againwrite one letterinterrupt: there isroomfour set-up writesread a letterwrite a letter
  1. component Processorruns the device driver
    • read status, again and again → UART0
    • write one letter → UART0
    • four set-up writes → DMA controller
  2. component UART0room for one letter at a time
    • interrupt: there is room → Processor
  3. component DMA controllera second manager on the bus
    • write a letter → UART0
  4. component Memoryholds the message
    • read a letter → DMA controller
  1. Polling

    The driver reads the status register until it says "room". Then it writes one letter. The processor does the waiting and the carrying.

  2. Interrupt

    The driver goes away. UART0 raises an interrupt when it has room, and the handler writes one letter. The device does the waiting. The processor still carries.

  3. DMA

    The driver tells the DMA controller where the message is, where it goes and how long it is. The controller waits for room and carries every letter.

Read the diagram as text
  • Processor: runs the device driver
  • UART0: room for one letter at a time
  • Memory: holds the message
  • DMA controller: a second manager on the bus
  • Processor → UART0: read status, again and again
  • Processor → UART0: write one letter
  • UART0 → Processor: interrupt: there is room
  • Processor → DMA controller: four set-up writes
  • Memory → DMA controller: read a letter
  • DMA controller → UART0: write a letter

One message, three methods. The lab below runs all three with the same four letters.

Read the picture as two questions. Who waits? Who carries? Polling answers "the processor" twice. DMA answers "not the processor" twice. The interrupt is in between.

The Smallest Example, Worked by Hand

Price a message of four letters. Three numbers are enough. One register access keeps the processor for 3 clock cycles. One entry into a handler costs 5. After each letter, UART0 has no room for 12 cycles.

Four letters, priced by hand
MethodWhat the processor doesSumProcessor time
PollingFirst letter: 1 poll and 1 write. Each later letter: 5 polls and 1 write.6 + 18 + 18 + 1860
InterruptEnable the interrupt. For each letter: one entry and one write. Disable the interrupt.3 + 4 x (5 + 3) + 338
DMAFour set-up writes: from, to, how many, start.4 x 312

Where do 5 polls come from? Four polls of 3 cycles fill the 12 cycles without room, and each gets the answer "not yet". The fifth gets "room". So twelve of the sixteen polls bought nothing.

Now look at how each sum grows. Polling pays 18 for every further letter. The interrupt pays 8. DMA pays nothing more: its 12 cycles are a set-up cost.

The Rules

  1. Rule 1: Ask before you write.

    Read the status of the device, or be told. A byte written to a full device is lost.

  2. Rule 2: A poll that answers "not yet" is processor time spent on nothing.

    Polling is cheap only when the device is ready at once.

  3. Rule 3: An interrupt says when. It moves no data.

    The handler still has to write the byte.

  4. Rule 4: Disable a "room" interrupt when nothing is left to send.

    An empty transmitter always has room. Left enabled, it calls the handler for ever.

  5. Rule 5: DMA moves the data. The processor pays the set-up once.

    After the start bit, the processor is free until the job ends.

  6. Rule 6: Count processor time and elapsed time apart.

    A method can win one and lose the other.

Sources for These Rules

Device drivers, serial registers, polling and interrupts: Harris and Harris, Digital Design and Computer Architecture, ARM edition, sections 9.3.2, 9.3.4.2 and 9.3.7.

One register access through the bridge, with its setup and access phases: Arm AMBA AHB Protocol Specification, IHI 0033 issue C, section 3.1. Arm AMBA APB Protocol Specification, IHI 0024 issue E, sections 3.1 and 3.3.

Our own choices for the lab: the registers of UART0, the room for one letter, and the 12 cycles after each letter.

The 5 cycles of a handler entry are measured, not chosen. See "Now Run It".

Now Run It

The lab at the end of this page runs the three methods, one after another, on the same four letters. A bus-functional model stands in for the processor: test code that makes the register accesses and counts the cycles they keep it.

One Register Access Takes Three Clock Edges
  • Processor
  • Bus
  • Peripheral
status readsetupthe answerDriverBridgeUART0
status read→ Bridgesetup→ UART0the answer→ DriverDriverBridgeUART0

A lit wire carries a 1. A pill is a transfer in that cycle.

012clkactivesetupaccessready
Scroll horizontally ↔
  1. Cycle 0

    Edge 5: the bridge takes the address of the status register.

  2. Cycle 1

    Edge 6: the setup phase on APB. The driver waits.

  3. Cycle 2

    Edge 7: the access phase completes. The driver has its answer.

Three rising edges in a row, from the first status read of the lab on Icarus.

That is why one access costs 3. The first status read of the lab takes edges 5, 6 and 7: the address, the setup phase and the access phase.

The 5 cycles of a handler entry come from another lab. In Interrupt Latency the first word of the handler is fetched five clock edges after the event. This lab charges those five for each visit. It does not count the instructions of the handler or the return, so a real visit costs more.

Totals from Icarus. Method 0 is polling, 1 is the interrupt, 2 is DMA.
method=0 text=send polls=16 busy=60 elapsed=61
method=1 text=send polls=0 busy=38 elapsed=75
method=2 text=send polls=0 busy=12 elapsed=70
MethodProcessor cycles for s / e / n / dAfter dProcessor timeFor each letterElapsed time
Polling6 / 18 / 18 / 180601561
Interrupt11 / 8 / 8 / 83389.575
DMA12 / 0 / 0 / 0012370

Rule 2 at work: the row of method 0 has polls=16 for four letters, and busy=60. Rule 3 at work: method 1 has polls=0, yet its processor time is 38, because the handler writes every letter. Rule 5 at work: method 2 costs 12 and nothing for the letters e, n and d.

Rule 4 at work: the interrupt row has 3 more cycles after d. That is the write that disables the interrupt.

This lab leaves things out. Time is measured at the register of UART0, before any bit leaves the pin. For polling and the interrupt, the model has the letters in hand. The DMA controller has to read each one from memory first.

Why It Is Built This Way

A chip offers all three methods because each one wins somewhere. The recorded runs below change one thing at a time.

The situationPollingInterruptDMAWhat it shows
Four letters, 12 cycles without room603812A long message is DMA's case.
One letter, room at the start61412One byte to a ready device: just poll.
Four letters, a device that always has room243812A fast device makes the interrupt the dearest.

Processor time in clock cycles, recorded from the lab. Row 2 has a message of one letter. Row 3 has the 12 cycles set to zero.

MethodIt needsChoose it when
PollingNothing but the status registerThe device is ready at once, or the processor has nothing else to do, as at boot.
InterruptA request wire and a handlerThe device is ready rarely, or at a time nobody can predict.
DMAA DMA controller and a share of the busMany bytes move between a device and memory.

The Trap: The Cheapest Method Finished Last

Back to the second job that missed its deadline. You read the totals, see busy=12 for DMA and call it the fastest. Now put a finger on the other column, elapsed.

Polling: 61. DMA: 70. The interrupt: 75. The order has turned round. Polling kept the processor for almost all of its 61 cycles, and got the letters out first. The interrupt gave the processor back, and paid five cycles of entry before each letter.

So "which method is fastest" is not one question. If the other job misses its deadline, you want processor time back: rule 6 says look at busy. If the console itself is late, look at elapsed. Mix the two columns and you will fix the wrong thing.

One more trap sits in rule 4. After the last letter the transmitter is empty, so it has room, so it asks. A driver that leaves the interrupt enabled is called again at once, with nothing to send, for ever. The board looks frozen, and the handler is the busiest code on it.

At Scale

This page1 device, 4 letters
A large chiphundreds of devices

This section looks ahead. On a chip with a hundred devices, the three methods are the same, and the question becomes whose deadline is at risk.

  1. Find the deadline

    Start at the device. How long can it wait before data is lost? Compare that with the longest time a handler has ever taken to arrive.

  2. Several bytes for each visit

    A device that can store several bytes lets one visit move them all. The entry is paid once. The first byte waits longer.

  3. DMA is a customer too

    DMA frees the processor and loads the bus. DMA follows one copy byte by byte.

  4. What happens on the wire

    This page stops at the register. Serial links follows the bits of a letter on the pin.

Try It

Run the lab. Check the three totals against the hand table.

Add the line gap=0; after initialize(); so that UART0 always has room. Predict the processor time of polling before you run it.

Set MESSAGE_BYTES to 1 and compare the three methods again.

Names Printed by the Lab
NameMeaning
method0 is polling, 1 is the interrupt, 2 is DMA.
textThe letters that UART0 took.
pollsThe number of status reads.
busyProcessor time, in clock cycles.
elapsedElapsed time, in clock cycles.
lettersProcessor time spent up to each of the four letters.
tailProcessor time spent after the last letter.
ENTRY_EDGESThe clock edges charged for one entry into the handler: 5.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: access e5 active=1 setup=0 access=0 ready=1 access e6 active=0 setup=1 access=0 ready=0 access e7 active=0 setup=0 access=1 ready=1 account=0 letters=6,18,18,18 tail=0 method=0 text=send polls=16 busy=60 elapsed=61 account=1 letters=11,8,8,8 tail=3 method=1 text=send polls=0 busy=38 elapsed=75 account=2 letters=12,0,0,0 tail=0 method=2 text=send polls=0 busy=12 elapsed=70
Read included file: ahb_2m.sv
`timescale 1ns/1ns
// ahb_2m.sv: a two-manager interconnect with one shared bus to one subordinate (read-only).
// Each manager is a plain AHB-Lite manager with its own HREADY. The owner drives the shared address
// phase and sees the bus HREADY. A manager that wants the bus but does not own it sees HREADY low, so
// its address phase simply waits; an idle manager sees HREADY high.
// This bench's arbiter changes owner only at an edge where the bus HREADY is high and the owner's
// address phase is IDLE, round robin. It never changes owner while the bus is locked: after a cycle
// with HMASTLOCK and HREADY high, until a cycle with HMASTLOCK low and HREADY high (3.3).
// Switches: lock_ignored (the broken twin: the arbiter does not look at HMASTLOCK); trace.
module ahb_2m (
  input  logic        hclk, hresetn,
  // manager ports 0 and 1
  input  logic [1:0]  htrans0, htrans1,
  input  logic [31:0] haddr0, haddr1, hwdata0, hwdata1,
  input  logic        hwrite0, hwrite1, hmastlock0, hmastlock1,
  input  logic [2:0]  hsize0, hsize1,
  output logic        hready0, hready1,
  // the shared bus
  output logic [1:0]  s_htrans,
  output logic [31:0] s_haddr, s_hwdata,
  output logic        s_hwrite, s_hmastlock,
  output logic [2:0]  s_hsize,
  input  logic        s_hready);
  bit lock_ignored = 0, trace = 0;
  int cycle = -1;
  logic own = 0, downer = 0;            // who drives the address phase; whose data phase runs
  assign s_htrans    = own ? htrans1 : htrans0;
  assign s_haddr     = own ? haddr1 : haddr0;
  assign s_hwrite    = own ? hwrite1 : hwrite0;
  assign s_hsize     = own ? hsize1 : hsize0;
  assign s_hmastlock = own ? hmastlock1 : hmastlock0;
  assign s_hwdata    = downer ? hwdata1 : hwdata0;
  assign hready0 = !own ? s_hready : !htrans0[1];   // the other manager waits while it wants the bus
  assign hready1 =  own ? s_hready : !htrans1[1];
  wire other_req = own ? htrans0[1] : htrans1[1];
  wire locked    = s_hmastlock && !lock_ignored;
  always @(posedge hclk or negedge hresetn) begin
    cycle = cycle + 1;
    if (!hresetn) begin own <= 0; downer <= 0; end
    else begin
      if (s_hready) begin
        downer <= own;
        if (s_htrans == 2'b00 && !locked && other_req) begin
          own <= !own;
          if (trace) $display("arb e%0d: bus to manager %0d", cycle, !own);
        end
      end
    end
  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: s6_io_slice.svh
// Simulation fixture. A transfer task stands in for each manager.
// P4 supplies the two-manager arbitration point and APB bridge.
logic clk = 0, reset_n = 0;
always #5 clk = ~clk;
localparam logic [31:0] UART = 'h10000000, STATUS = UART+4, MASK = UART+8,
                        RX = UART+12, CFG = 'h10006000, RAM = 'h80000000;
logic [31:0] addr[2], data[2];
logic [1:0] trans[2];
logic wr[2];
logic [2:0] size[2];
wire ready[2];
wire [31:0] address, payload, paddr, pwdata, bridge_data;
wire [1:0] transfer;
wire [2:0] bus_size;
wire write_en, bridge_ready, bridge_error, psel, penable, pwrite;

ahb_2m matrix (
  .hclk(clk), .hresetn(reset_n),
  .htrans0(trans[0]), .htrans1(trans[1]), .haddr0(addr[0]), .haddr1(addr[1]),
  .hwrite0(wr[0]), .hwrite1(wr[1]), .hwdata0(data[0]), .hwdata1(data[1]),
  .hmastlock0(1'b0), .hmastlock1(1'b0), .hsize0(size[0]), .hsize1(size[1]),
  .hready0(ready[0]), .hready1(ready[1]), .s_htrans(transfer), .s_haddr(address),
  .s_hwdata(payload), .s_hwrite(write_en), .s_hmastlock(), .s_hsize(bus_size),
  .s_hready(bridge_ready)
);
logic [7:0] rom[0:3], ram[0:3];
logic [31:0] saved_addr;
logic saved_write, saved_active;
wire [31:0] rom_word = {rom[3],rom[2],rom[1],rom[0]};
wire [31:0] bus_read_data = saved_addr < 4 ? rom_word : bridge_data;
wire peripheral = address[31:16] == 16'h1000;
logic [31:0] src, dst, length;
logic launch, mask;
logic done = 0, fault = 0;
int cooldown, gap = 12, rx_count, fault_at = -1;
int cycle = 0, busy_cycles = 0;
bit charge_cpu, log_moves, trace_access;
logic [31:0] console_text;
int tx_count, cpu_at_tx[4];
wire room = cooldown == 0;
wire irq = mask && room;
wire rx_request = rx_count < 4;
wire rx_fault = paddr == RX && rx_count == fault_at;
wire [31:0] prdata = paddr == STATUS ? {31'b0,room} :
                     paddr == RX && rx_request ? {24'b0,rom[rx_count]} : 0;
ahb_apb_bridge bridge (
  .hclk(clk), .hresetn(reset_n), .hsel(peripheral), .haddr(address),
  .htrans(transfer), .hwrite(write_en), .hprot(4'b0011), .hwdata(payload),
  .hwstrb(4'hf), .hready(bridge_ready), .hreadyout(bridge_ready),
  .hresp(bridge_error), .hrdata(bridge_data), .psel(psel), .penable(penable),
  .pwrite(pwrite), .paddr(paddr), .pwdata(pwdata), .pstrb(), .pprot(),
  .pready(1'b1), .prdata(prdata), .pslverr(rx_fault)
);

always @(posedge clk) begin
  cycle <= cycle + 1;
  if (trace_access && (transfer[1] || psel))
    $display("access e%0d active=%b setup=%b access=%b ready=%b",cycle,
             transfer[1],psel && !penable,psel && penable,bridge_ready);
  if (charge_cpu) busy_cycles <= busy_cycles + 1;
  if (bridge_ready) begin
    saved_active <= transfer[1];
    saved_addr <= address;
    saved_write <= write_en;
  end
  if (saved_active && saved_write && saved_addr >= RAM && saved_addr < RAM+4)
    ram[saved_addr-RAM] <= payload[8*saved_addr[1:0] +: 8];
  launch <= 0;
  if (!reset_n) begin
    cooldown <= 0;
    rx_count <= 0;
    console_text <= 0;
    tx_count <= 0;
    mask <= 0;
  end else begin
    if (!room) cooldown <= cooldown-1;
    if (psel && penable && !rx_fault) begin
      if (pwrite) case (paddr)
        UART: begin
          if (!room) $fatal(1,"TX register full");
          if (tx_count < 4) cpu_at_tx[tx_count] <= busy_cycles + int'(charge_cpu);
          tx_count <= tx_count + 1;
          console_text <= {console_text[23:0],pwdata[7:0]};
          cooldown <= gap;
        end
        MASK: mask <= pwdata[0];
        CFG: src <= pwdata;
        CFG+4: dst <= pwdata;
        CFG+8: length <= pwdata;
        CFG+12: launch <= pwdata[0];
      endcase
      else if (paddr == RX && rx_request) rx_count <= rx_count+1;
    end
  end
end

// All bus drives change away from the active edge. Count address arbitration,
// address acceptance and every data-phase wait inside the CPU charge interval.
task automatic access_bus(input int m, input bit writing, input logic [31:0] a, d,
                          output logic [31:0] result, output bit failed);
  @(negedge clk);
  if (m == 0) charge_cpu = 1;
  addr[m] = a;
  wr[m] = writing;
  size[m] = a[31:16] == 16'h1000 ? 2 : 0;
  data[m] = d;
  trans[m] = 2'b10;
  do @(posedge clk); while (!ready[m]);
  @(negedge clk);
  trans[m] = 0;
  do @(posedge clk); while (!bridge_ready);
  failed = bridge_error;
  result = a < 4 ? {24'b0,bus_read_data[8*a[1:0] +: 8]} : bus_read_data;
  if (log_moves && m == 1)
    $display("e%0d cpu_request=%b %s %08h byte=%02h error=%b",cycle,trans[0][1],
             writing ? "write" : " read",a,writing ? d[8*a[1:0] +: 8] : result[7:0],failed);
  #1;
  if (m == 0) charge_cpu = 0;
endtask

task automatic cpu_write(input logic [31:0] a, d);
  logic [31:0] unused;
  bit failed;
  access_bus(0,1,a,d,unused,failed);
  if (failed) $fatal(1,"control write failed");
endtask

task automatic program_channel(input logic [31:0] from_addr,to_addr,count);
  if (!(from_addr == RX || from_addr < 4) ||
      !(to_addr == UART || (to_addr >= RAM && to_addr < RAM+4)))
    $fatal(1,"Use the four-byte ROM or UART RX and the four-byte RAM or UART TX");
  if (count > 4 || (from_addr == RX && count > 4-rx_count) ||
      (from_addr < 4 && count > 4-from_addr) ||
      (to_addr != UART && count > RAM+4-to_addr))
    $fatal(1,"Job would exceed the fixture buffer");
  cpu_write(CFG,from_addr);
  cpu_write(CFG+4,to_addr);
  cpu_write(CFG+8,count);
  cpu_write(CFG+12,1);
endtask

// Behavioral transfer agent, for the documented ROM/RX and RAM/TX routes.
// ROM reads below return a byte extracted from its addressed lane.
initial forever begin : channel
  logic [31:0] a,b,value,unused,byte_count;
  bit failed;
  @(posedge launch);
  done = 0;
  fault = 0;
  a = src;
  b = dst;
  byte_count = length;
  for (int i=0; i<byte_count && !fault; i++) begin
    if (a == RX) wait(rx_request);
    if (b == UART) wait(room);
    access_bus(1,0,a,0,value,failed);
    if (!failed)
      access_bus(1,1,b,{4{value[7:0]}},unused,failed);
    fault = failed;
    if (a != RX) a++;
    if (b != UART) b++;
  end
  done = !fault;
end

task automatic initialize;
  for (int m=0; m<2; m++) begin
    trans[m]=0; wr[m]=0; addr[m]=0; data[m]=0; size[m]=0;
  end
  {rom[0],rom[1],rom[2],rom[3]} = "send";
  for (int i=0; i<4; i++) ram[i]=0;
  repeat (2) @(negedge clk);
  reset_n=1;
endtask

Check Yourself

Predict the outputIn this run UART0 always has room. What is the last row the lab prints?
`timescale 1ns/1ns
module tb;
  `include "s6_io_slice.svh"
  localparam int MESSAGE_BYTES = 4;
  localparam int ENTRY_EDGES = 5;
  initial begin
    initialize();
    gap=0;
    if (MESSAGE_BYTES < 1 || MESSAGE_BYTES > 4)
      $fatal(1,"Choose one to four message bytes");
    for (int method=0; method<3; method++) begin
      logic [31:0] status;
      bit failed;
      int start_cycle, start_busy, reads;
      reset_n=0;
      @(posedge clk); // Every method starts after a sampled peripheral reset.
      @(negedge clk); reset_n=1;
      wait(room);
      @(negedge clk);
      start_cycle=cycle;
      start_busy=busy_cycles;
      reads=0;
      if (method == 2) begin
        program_channel(0,UART,MESSAGE_BYTES);
        wait(done || fault);
        if (fault) $fatal(1,"copy failed");
      end else begin
        if (method == 1) cpu_write(MASK,1);
        for (int i=0; i<MESSAGE_BYTES; i++) begin
          if (method == 0) begin
            do begin
              trace_access=(reads == 0);
              access_bus(0,0,STATUS,0,status,failed);
              if (failed) $fatal(1,"Status read failed");
              trace_access=0;
              reads++;
            end while (!status[0]);
          end else begin
            wait(irq);
            // Entry to the handler: five clock edges, the delay from the request to the first
            // handler word measured in the lab of S6.4 (s63-recordings.json, timer: e0 to e5).
            @(negedge clk); charge_cpu=1;
            repeat (ENTRY_EDGES) @(posedge clk);
            #1 charge_cpu=0;
          end
          cpu_write(UART,{24'b0,rom[i]});
        end
        if (method == 1) cpu_write(MASK,0);
      end
      if (tx_count != MESSAGE_BYTES) $fatal(1,"Incomplete message");
      if (MESSAGE_BYTES == 4)
        $display("account=%0d letters=%0d,%0d,%0d,%0d tail=%0d",method,
               cpu_at_tx[0]-start_busy,cpu_at_tx[1]-cpu_at_tx[0],
               cpu_at_tx[2]-cpu_at_tx[1],cpu_at_tx[3]-cpu_at_tx[2],
               busy_cycles-cpu_at_tx[3]);
      $display("method=%0d text=%0s polls=%0d busy=%0d elapsed=%0d",
               method,console_text,reads,busy_cycles-start_busy,cycle-start_cycle);
    end
    $finish;
  end
endmodule
Read included file: ahb_2m.sv
`timescale 1ns/1ns
// ahb_2m.sv: a two-manager interconnect with one shared bus to one subordinate (read-only).
// Each manager is a plain AHB-Lite manager with its own HREADY. The owner drives the shared address
// phase and sees the bus HREADY. A manager that wants the bus but does not own it sees HREADY low, so
// its address phase simply waits; an idle manager sees HREADY high.
// This bench's arbiter changes owner only at an edge where the bus HREADY is high and the owner's
// address phase is IDLE, round robin. It never changes owner while the bus is locked: after a cycle
// with HMASTLOCK and HREADY high, until a cycle with HMASTLOCK low and HREADY high (3.3).
// Switches: lock_ignored (the broken twin: the arbiter does not look at HMASTLOCK); trace.
module ahb_2m (
  input  logic        hclk, hresetn,
  // manager ports 0 and 1
  input  logic [1:0]  htrans0, htrans1,
  input  logic [31:0] haddr0, haddr1, hwdata0, hwdata1,
  input  logic        hwrite0, hwrite1, hmastlock0, hmastlock1,
  input  logic [2:0]  hsize0, hsize1,
  output logic        hready0, hready1,
  // the shared bus
  output logic [1:0]  s_htrans,
  output logic [31:0] s_haddr, s_hwdata,
  output logic        s_hwrite, s_hmastlock,
  output logic [2:0]  s_hsize,
  input  logic        s_hready);
  bit lock_ignored = 0, trace = 0;
  int cycle = -1;
  logic own = 0, downer = 0;            // who drives the address phase; whose data phase runs
  assign s_htrans    = own ? htrans1 : htrans0;
  assign s_haddr     = own ? haddr1 : haddr0;
  assign s_hwrite    = own ? hwrite1 : hwrite0;
  assign s_hsize     = own ? hsize1 : hsize0;
  assign s_hmastlock = own ? hmastlock1 : hmastlock0;
  assign s_hwdata    = downer ? hwdata1 : hwdata0;
  assign hready0 = !own ? s_hready : !htrans0[1];   // the other manager waits while it wants the bus
  assign hready1 =  own ? s_hready : !htrans1[1];
  wire other_req = own ? htrans0[1] : htrans1[1];
  wire locked    = s_hmastlock && !lock_ignored;
  always @(posedge hclk or negedge hresetn) begin
    cycle = cycle + 1;
    if (!hresetn) begin own <= 0; downer <= 0; end
    else begin
      if (s_hready) begin
        downer <= own;
        if (s_htrans == 2'b00 && !locked && other_req) begin
          own <= !own;
          if (trace) $display("arb e%0d: bus to manager %0d", cycle, !own);
        end
      end
    end
  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: s6_io_slice.svh
// Simulation fixture. A transfer task stands in for each manager.
// P4 supplies the two-manager arbitration point and APB bridge.
logic clk = 0, reset_n = 0;
always #5 clk = ~clk;
localparam logic [31:0] UART = 'h10000000, STATUS = UART+4, MASK = UART+8,
                        RX = UART+12, CFG = 'h10006000, RAM = 'h80000000;
logic [31:0] addr[2], data[2];
logic [1:0] trans[2];
logic wr[2];
logic [2:0] size[2];
wire ready[2];
wire [31:0] address, payload, paddr, pwdata, bridge_data;
wire [1:0] transfer;
wire [2:0] bus_size;
wire write_en, bridge_ready, bridge_error, psel, penable, pwrite;

ahb_2m matrix (
  .hclk(clk), .hresetn(reset_n),
  .htrans0(trans[0]), .htrans1(trans[1]), .haddr0(addr[0]), .haddr1(addr[1]),
  .hwrite0(wr[0]), .hwrite1(wr[1]), .hwdata0(data[0]), .hwdata1(data[1]),
  .hmastlock0(1'b0), .hmastlock1(1'b0), .hsize0(size[0]), .hsize1(size[1]),
  .hready0(ready[0]), .hready1(ready[1]), .s_htrans(transfer), .s_haddr(address),
  .s_hwdata(payload), .s_hwrite(write_en), .s_hmastlock(), .s_hsize(bus_size),
  .s_hready(bridge_ready)
);
logic [7:0] rom[0:3], ram[0:3];
logic [31:0] saved_addr;
logic saved_write, saved_active;
wire [31:0] rom_word = {rom[3],rom[2],rom[1],rom[0]};
wire [31:0] bus_read_data = saved_addr < 4 ? rom_word : bridge_data;
wire peripheral = address[31:16] == 16'h1000;
logic [31:0] src, dst, length;
logic launch, mask;
logic done = 0, fault = 0;
int cooldown, gap = 12, rx_count, fault_at = -1;
int cycle = 0, busy_cycles = 0;
bit charge_cpu, log_moves, trace_access;
logic [31:0] console_text;
int tx_count, cpu_at_tx[4];
wire room = cooldown == 0;
wire irq = mask && room;
wire rx_request = rx_count < 4;
wire rx_fault = paddr == RX && rx_count == fault_at;
wire [31:0] prdata = paddr == STATUS ? {31'b0,room} :
                     paddr == RX && rx_request ? {24'b0,rom[rx_count]} : 0;
ahb_apb_bridge bridge (
  .hclk(clk), .hresetn(reset_n), .hsel(peripheral), .haddr(address),
  .htrans(transfer), .hwrite(write_en), .hprot(4'b0011), .hwdata(payload),
  .hwstrb(4'hf), .hready(bridge_ready), .hreadyout(bridge_ready),
  .hresp(bridge_error), .hrdata(bridge_data), .psel(psel), .penable(penable),
  .pwrite(pwrite), .paddr(paddr), .pwdata(pwdata), .pstrb(), .pprot(),
  .pready(1'b1), .prdata(prdata), .pslverr(rx_fault)
);

always @(posedge clk) begin
  cycle <= cycle + 1;
  if (trace_access && (transfer[1] || psel))
    $display("access e%0d active=%b setup=%b access=%b ready=%b",cycle,
             transfer[1],psel && !penable,psel && penable,bridge_ready);
  if (charge_cpu) busy_cycles <= busy_cycles + 1;
  if (bridge_ready) begin
    saved_active <= transfer[1];
    saved_addr <= address;
    saved_write <= write_en;
  end
  if (saved_active && saved_write && saved_addr >= RAM && saved_addr < RAM+4)
    ram[saved_addr-RAM] <= payload[8*saved_addr[1:0] +: 8];
  launch <= 0;
  if (!reset_n) begin
    cooldown <= 0;
    rx_count <= 0;
    console_text <= 0;
    tx_count <= 0;
    mask <= 0;
  end else begin
    if (!room) cooldown <= cooldown-1;
    if (psel && penable && !rx_fault) begin
      if (pwrite) case (paddr)
        UART: begin
          if (!room) $fatal(1,"TX register full");
          if (tx_count < 4) cpu_at_tx[tx_count] <= busy_cycles + int'(charge_cpu);
          tx_count <= tx_count + 1;
          console_text <= {console_text[23:0],pwdata[7:0]};
          cooldown <= gap;
        end
        MASK: mask <= pwdata[0];
        CFG: src <= pwdata;
        CFG+4: dst <= pwdata;
        CFG+8: length <= pwdata;
        CFG+12: launch <= pwdata[0];
      endcase
      else if (paddr == RX && rx_request) rx_count <= rx_count+1;
    end
  end
end

// All bus drives change away from the active edge. Count address arbitration,
// address acceptance and every data-phase wait inside the CPU charge interval.
task automatic access_bus(input int m, input bit writing, input logic [31:0] a, d,
                          output logic [31:0] result, output bit failed);
  @(negedge clk);
  if (m == 0) charge_cpu = 1;
  addr[m] = a;
  wr[m] = writing;
  size[m] = a[31:16] == 16'h1000 ? 2 : 0;
  data[m] = d;
  trans[m] = 2'b10;
  do @(posedge clk); while (!ready[m]);
  @(negedge clk);
  trans[m] = 0;
  do @(posedge clk); while (!bridge_ready);
  failed = bridge_error;
  result = a < 4 ? {24'b0,bus_read_data[8*a[1:0] +: 8]} : bus_read_data;
  if (log_moves && m == 1)
    $display("e%0d cpu_request=%b %s %08h byte=%02h error=%b",cycle,trans[0][1],
             writing ? "write" : " read",a,writing ? d[8*a[1:0] +: 8] : result[7:0],failed);
  #1;
  if (m == 0) charge_cpu = 0;
endtask

task automatic cpu_write(input logic [31:0] a, d);
  logic [31:0] unused;
  bit failed;
  access_bus(0,1,a,d,unused,failed);
  if (failed) $fatal(1,"control write failed");
endtask

task automatic program_channel(input logic [31:0] from_addr,to_addr,count);
  if (!(from_addr == RX || from_addr < 4) ||
      !(to_addr == UART || (to_addr >= RAM && to_addr < RAM+4)))
    $fatal(1,"Use the four-byte ROM or UART RX and the four-byte RAM or UART TX");
  if (count > 4 || (from_addr == RX && count > 4-rx_count) ||
      (from_addr < 4 && count > 4-from_addr) ||
      (to_addr != UART && count > RAM+4-to_addr))
    $fatal(1,"Job would exceed the fixture buffer");
  cpu_write(CFG,from_addr);
  cpu_write(CFG+4,to_addr);
  cpu_write(CFG+8,count);
  cpu_write(CFG+12,1);
endtask

// Behavioral transfer agent, for the documented ROM/RX and RAM/TX routes.
// ROM reads below return a byte extracted from its addressed lane.
initial forever begin : channel
  logic [31:0] a,b,value,unused,byte_count;
  bit failed;
  @(posedge launch);
  done = 0;
  fault = 0;
  a = src;
  b = dst;
  byte_count = length;
  for (int i=0; i<byte_count && !fault; i++) begin
    if (a == RX) wait(rx_request);
    if (b == UART) wait(room);
    access_bus(1,0,a,0,value,failed);
    if (!failed)
      access_bus(1,1,b,{4{value[7:0]}},unused,failed);
    fault = failed;
    if (a != RX) a++;
    if (b != UART) b++;
  end
  done = !fault;
end

task automatic initialize;
  for (int m=0; m<2; m++) begin
    trans[m]=0; wr[m]=0; addr[m]=0; data[m]=0; size[m]=0;
  end
  {rom[0],rom[1],rom[2],rom[3]} = "send";
  for (int i=0; i<4; i++) ram[i]=0;
  repeat (2) @(negedge clk);
  reset_n=1;
endtask
ConceptWhat must a driver find out before it writes a byte to a device?
ConceptIn the hand example, sixteen polls sent four letters. How many polls got the answer "not yet"?
ConceptUART0 has raised its "room" interrupt. What puts the next letter into UART0?
ConceptWhat does the processor pay for a DMA job of many bytes?
ConceptIn the lab, DMA has the least processor time and polling the least elapsed time. Why can both be true?

Common Mistakes

Wrong Take an interrupt as proof that a byte was delivered.

A "room" interrupt reports space. It moves nothing.

Fix Find the completed write to the data register.

Wrong Use processor time to predict when the last byte arrives.

DMA and the interrupt free the processor and still take time.

Fix Measure elapsed time at the point your deadline names.

Wrong Leave the "room" interrupt enabled after the last byte.

An empty transmitter always has room.

Fix Disable it when the queue is empty, and enable it with the next message.

Remember

  • Between two bytes someone must wait for the device. Polling makes the processor wait.
  • An interrupt moves the waiting to the device. The handler still moves each byte.
  • DMA moves the waiting and the bytes to a DMA controller, for a set-up cost paid once.
  • Processor time and elapsed time are two measures. A method can win one and lose the other.

Practice

Report a problem with this page