Finding the Bottleneck and Sizing Buffers

A queue holds what was offered and not yet served. Its depth comes from the largest such backlog. More depth buys time, never rate: for rate you must find the stage that sets it.

You Will Be Able To

  • Work out the backlog of a queue, slot by slot, from what is offered and what is served.
  • Size a queue from the largest backlog of a run that lost nothing.
  • Tell a problem that a deeper queue fixes from one that only a faster stage fixes.
Lesson
S8.8
Time
28 min
Runs on
Your browser
Check
5 questions

It is the first receive test, and it almost works. The sender sends the letters A to F. Memory holds A, B, C, D and F. If the path were simply too slow, why did F get through?

Before You Start

You need Throughput, Latency and Back-Pressure: a stage, and why a full stage loses data from a source that cannot wait.

You need Serial Peripherals: The UART: the receive queue of UART0, and an overrun.

You need DMA: a DMA moves one byte with each write.

Five questions this page answers
Question
1What is the backlog of a queue at one moment?
2How deep must a queue be to lose nothing?
3Why is a queue that overflowed no guide to the right depth?
4What can a deeper queue not fix?
5A burst of five letters, a write slot every second slot: what does the queue of five places report?

The Idea: A Queue Buys Time

A serial line does not wait. Its bytes come when they come, often several in a row, and then nothing for a while. Memory takes bytes at its own pace. Between the two sits a queue.

What the queue holds at any moment is easy to say. It is everything that was offered so far, less everything that was served so far. That difference is the backlog. While bytes arrive faster than they are served, the backlog grows. When the arrivals stop, it shrinks.

So the question "how deep must the queue be?" has an exact answer. It must hold the largest backlog that ever occurs. One place less, and a byte is lost at that moment.

A queue only moves work in time. It does not do any work. If bytes arrive faster than they are served for good, the backlog grows for good, and no depth is enough. Then the path needs more service, and the first job is to find the stage that limits it. That stage is the bottleneck stage, or the bottleneck for short.

New Words

New words on this page
WordMeaning
BacklogThe items offered so far, less the items served so far. It is what a queue must hold at that moment.
Arrival burstA run of items that arrive faster than they are served. This page calls it a burst.
Service of a queueThe taking of an item out of a queue by the next stage. Here, one write to SRAM serves one byte.
Write slotA slot in which the DMA may write one byte to SRAM. In the lab it comes every second slot.
Depth of a queueThe number of places of a queue.
Peak backlogThe highest value that the backlog reaches during a run. This page also says the largest backlog, or the peak.
Bottleneck stageThe stage of a path whose rate limits the rate of the whole path. This page calls it the bottleneck.

One Picture: Offered, Served and What Waits

What a Queue Is ForStep through the picture. It follows a burst into a queue, and ends at the stage that decides how fast the queue drains.
  • Peripheral
  • Bus
  • Memory
  • Debug
What a Queue Is ForStep through the picture. It follows a burst into a queue, and ends at the stage that decides how fast the queue drains. component UART0 offers a byte inevery slot of a burst component Queue a fixed number ofplaces; holds what wasoffered and not yetserved component DMA write slot one byte, everysecond slot component SRAM where the bytes mustend up component Lost a byte that arrivesat a full queue offeredthe oldest bytesavedno place
  1. component UART0offers a byte in every slot of a burst
    • offered → Queue
  2. component Queuea fixed number of places; holds what was offered and not yet served
    • the oldest byte → DMA write slot
    • no place → Lost
  3. component DMA write slotone byte, every second slot
    • saved → SRAM
  4. component SRAMwhere the bytes must end up
  5. component Losta byte that arrives at a full queue
  1. A burst

    For a while, UART0 offers a byte in every slot. That is faster than memory takes them.

  2. Service

    The DMA gets a write slot every second slot. Each write slot saves one byte, the oldest.

  3. The backlog

    The queue holds the difference: everything offered so far, less everything saved so far.

  4. A full queue

    If the difference grows past the number of places, the next byte has nowhere to go. It is lost.

  5. The stage that sets the rate

    Here the write slots decide how fast the queue drains. A deeper queue does not add a single write slot.

Read the diagram as text
  • UART0: offers a byte in every slot of a burst
  • Queue: a fixed number of places; holds what was offered and not yet served
  • DMA write slot: one byte, every second slot
  • SRAM: where the bytes must end up
  • Lost: a byte that arrives at a full queue
  • UART0 → Queue: offered
  • Queue → DMA write slot: the oldest byte
  • DMA write slot → SRAM: saved
  • Queue → Lost: no place

The receive path of the lab. The queue holds the backlog. The write slots of the DMA set the rate.

The Smallest Example, Worked by Hand

Take four letters, A to D. One arrives in each of slots 1 to 4. The DMA has a write slot in every even slot. No simulator yet. Two rules of this queue matter. A write slot saves the oldest byte that was already waiting. A byte that arrives in a slot cannot be saved in that same slot.

Four letters, slot by slot
SlotArrivesWrite slotOffered so farSaved so farBacklog
1Ano101
2Byes: saves A211
3Cno312
4Dyes: saves B422
5noneno422
6noneyes: saves C431
7noneno431
8noneyes: saves D440

The last column is the fourth column less the fifth, in every row. Its largest value is 2. So a queue of two places carries this burst and loses nothing.

Look at the average and you would miss it. Over the eight slots, four bytes arrive and four write slots come. Arrivals equal service. Yet for four slots the sender was twice as fast as the memory, and two bytes had to wait somewhere.

The Rules

  1. Rule 1: The backlog is what was offered less what was served.

    Count both from the start of the run. The queue holds the difference.

  2. Rule 2: A queue must hold the largest backlog.

    With one place less, a byte is lost at the moment of the peak.

  3. Rule 3: Take the largest backlog from a run that lost nothing.

    A queue that overflowed never shows more than its own depth. The bytes it lost are not in its level.

  4. Rule 4: Service that is not used is gone.

    A write slot that finds the queue empty saves nothing, and cannot be kept for later.

  5. Rule 5: A queue buys time, not rate.

    If arrivals exceed service for good, the backlog grows for good and any queue fills.

  6. Rule 6: The bottleneck sets the rate of the path.

    Making another stage wider or faster changes nothing. Find the bottleneck by changing one thing and measuring again.

Sources for These Rules

Throughput as work done in a given time, and the stage that limits a path: Patterson and Hennessy, Computer Organization and Design, ARM edition, sections 1.6 and 4.5.

The depth of a queue from the arithmetic of a burst is worked through in R5.3.

Rules 1 to 5 are arithmetic on counts, stated in our own words. The word bottleneck is common practice.

The pace of one write slot in two, the three depths and the two other ways to copy are choices of our lab.

Now Run It

The lab at the end of this page sends six letters, A to F, in slots 1 to 6. The DMA has a write slot in every even slot, and each write slot is one write of one byte. The rows below come from a queue of five places, which is deep enough to lose nothing.

TransientOffered, Saved, and the Gap Between ThemRecorded after each slot, from the queue of five places. Compare the bytes offered so far with the bytes saved so far.
  • Offered by UART0 so far
  • Saved in SRAM so far
  • Waiting in the queue
01 B2 B3 B4 B5 B6 B7 BBytes24681012Receive slot02 B4 B6 B8 BBytes510Receive slot
  1. Receive slot 1Offered by UART0 so far = 1 B · Saved in SRAM so far = 0 B · Waiting in the queue = 1 B

    A is offered. Nothing has been saved yet: one byte waits.

  2. Receive slot 5Offered by UART0 so far = 5 B · Saved in SRAM so far = 2 B · Waiting in the queue = 3 B

    Five offered, two saved. Three bytes wait: C, D and E.

  3. Receive slot 6Offered by UART0 so far = 6 B · Saved in SRAM so far = 3 B · Waiting in the queue = 3 B

    The last letter arrives as one is saved. The gap is still three, its largest value.

  4. Receive slot 12Offered by UART0 so far = 6 B · Saved in SRAM so far = 6 B · Waiting in the queue = 0 B

    Six offered, six saved. The queue is empty.

Read the plot as a table
Receive slotOffered by UART0 so farSaved in SRAM so farWaiting in the queue
11 B0 B1 B
22 B1 B1 B
44 B2 B2 B
55 B2 B3 B
66 B3 B3 B
86 B4 B2 B
106 B5 B1 B
126 B6 B0 B

Recorded by the lab. The lines join samples taken once for each slot. The distance between the two upper lines is the backlog, drawn again as the third line.

Printed by the lab on Icarus, after each slot, for the queue of five places.
slot=1 offered=1 saved=0 level=1
slot=2 offered=2 saved=1 level=1
slot=3 offered=3 saved=1 level=2
slot=4 offered=4 saved=2 level=2
slot=5 offered=5 saved=2 level=3
slot=6 offered=6 saved=3 level=3
slot=7 offered=6 saved=3 level=3
slot=8 offered=6 saved=4 level=2
slot=9 offered=6 saved=4 level=2
slot=10 offered=6 saved=5 level=1
slot=11 offered=6 saved=5 level=1
slot=12 offered=6 saved=6 level=0

Rule 1 at work, in every row: level is offered less saved. In row slot=5 that is 5 less 2: three bytes wait, and they are C, D and E.

The same six letters also go through a queue of two places and one of three, in the same run.

One row for each of the three queues. SRAM lists the letters that reached memory.
depth=2 peak=2 lost=1 SRAM=ABCDF
depth=3 peak=3 lost=0 SRAM=ABCDEF
depth=5 peak=3 lost=0 SRAM=ABCDEF

Rules 2 and 3, in these three rows. The queue of five places peaked at 3 and lost nothing, so 3 is the largest backlog. The queue of three places agrees. The queue of two places lost E, and its own peak says 2: a number that is no use for sizing.

That row also answers the opening question. After slot 4, C and D fill both places. Slot 5 has no write slot, so E finds no place. In slot 6 a write slot saves C, and F takes the place that C left.

The last slot in which a byte was saved, for two other ways to copy the same six letters.
CPU bytes=6 last_slot=24
wide RAM bytes=6 last_slot=12

Rule 4, in the row "CPU". Here a processor copies the bytes and manages to use only every other write slot. The slots it missed are gone: the last byte is saved in slot 24, not 12.

Rule 6, in the row "wide RAM". The memory port is twice as wide, and the last byte is still saved in slot 12. The DMA writes one byte with each write, so the second half of the port stays empty. The memory was not the bottleneck.

This lab leaves things out. No processor and no serial line are here. The pace is set by a bus write to a word at 10006010. That word exists only in this lab: it is not a register of the DMA. The "CPU" row is a schedule that we chose, not a measured program. One slot is one clock period of 10 ns, so one byte every second slot is 50 million bytes a second.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
A queue sized for the largest backlogA queue sized from the average ratesNo byte of an allowed burst is lost. Someone must state the worst burst and the worst gap in service.
A DMA that uses every write slotA copy loop in softwareNo service is wasted, and the copy ends in half the time here. A short transfer may not repay the set-up.
A wider memory portThe port as it isNothing, until some block pairs two bytes into one write. That block is a practice problem of this lesson.

Service decides the depth as much as the burst does. With one write slot in three, the same six letters give these rows:

The same lab with a slower pace: one write slot every third slot.
depth=2 peak=2 lost=2 SRAM=ABCF
depth=3 peak=3 lost=1 SRAM=ABCDF
depth=5 peak=4 lost=0 SRAM=ABCDEF

The largest backlog is now 4, and the queue of three places loses a byte. Nothing about the sender changed.

The Trap: Sizing from a Queue That Overflowed

A team lost bytes with a queue of two places. They read its fill level in the lab: it never went above two. So they concluded that two places were needed, and that the fault was elsewhere.

A queue cannot show a level above its own depth. The byte that did not fit was dropped, and a dropped byte is in no counter of the queue. Rule 3 says where to look: count what was offered, at the source, and take away what was served.

A second trap is the average. Six bytes in twelve slots, six write slots in twelve slots: the two rates match, and someone removes the queue. The average hid slots 1 to 6, where the sender was twice as fast.

The third is to buy the wrong thing. A deeper queue is cheap, so it is tried first. If every frame brings more than the service can carry, the deeper queue only loses its first byte a little later.

At Scale

This page1 queue, 1 write slot in 2
A phone chiphundreds of queues on shared memory

This section looks ahead. A hundred blocks share one memory, and service is no longer a tidy slot in two.

  1. The worst gap in service

    On a shared bus the write slots come when the arbiter gives them. Size against the longest gap it can leave, not the usual one.

  2. The worst overlap

    Put the longest gap in service under the densest allowed burst. Add the bytes that are already on their way when the sender is told to stop.

  3. Two kinds of waiting

    A request can wait for the bus, and then wait for the memory. Measure the two apart: they have different owners.

  4. Back-pressure in place of depth

    Where the source can wait, a short queue and a "not now" do the job of a deep queue. Where it cannot, depth is the only cure.

Try It

Run the lab. In the rows that start with "slot", check that level is offered minus saved in every row.

Change BURST from 6 to 5. Predict the row of the queue of two places before you run it.

Change the pace from 2 to 3 in the line that calls apb_write. Which of the three queues still loses nothing?

Names Printed by the Lab
NameMeaning
slotOne clock period of the lab. A byte can arrive in a slot, and a byte can be saved in a slot.
offered, savedBytes that UART0 has offered so far, and bytes that have been written to SRAM so far.
levelBytes that wait in the queue of five places after the slot.
depth, peak, lostFor one of three queues: its number of places, its fullest level, and the bytes it lost.
SRAMThe letters that reached memory through that queue, in order.
last_slotThe slot in which the last byte was saved, for two other ways to copy.
wave, WRITEThe first three rows: the bus write that sets the pace of the lab.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: wave e1: psel=1 penable=0 pwrite=1 paddr=10006010 pwdata=00000002 pstrb=1111 pready=1 prdata=00000000 pslverr=0 wave e2: psel=1 penable=1 pwrite=1 paddr=10006010 pwdata=00000002 pstrb=1111 pready=1 prdata=00000000 pslverr=0 e1-e2 WRITE 0x6010 data=0x00000002 strb=1111 waits=0 OKAY slot=1 offered=1 saved=0 level=1 slot=2 offered=2 saved=1 level=1 slot=3 offered=3 saved=1 level=2 slot=4 offered=4 saved=2 level=2 slot=5 offered=5 saved=2 level=3 slot=6 offered=6 saved=3 level=3 slot=7 offered=6 saved=3 level=3 slot=8 offered=6 saved=4 level=2 slot=9 offered=6 saved=4 level=2 slot=10 offered=6 saved=5 level=1 slot=11 offered=6 saved=5 level=1 slot=12 offered=6 saved=6 level=0 CPU bytes=6 last_slot=24 wide RAM bytes=6 last_slot=12 depth=2 peak=2 lost=1 SRAM=ABCDF depth=3 peak=3 lost=0 SRAM=ABCDEF depth=5 peak=3 lost=0 SRAM=ABCDEF
Read included file: soc-s85-rx.sv
// Byte queue at the UART receive boundary. A grant commits its oldest byte to
// the DMA sink. A simultaneous departure frees a slot before admission.
module ap_rx_queue #(parameter int DEPTH = 3) (
  input logic clk, reset, arrival, grant,
  input logic [7:0] rx_byte,
  output logic [7:0] oldest,
  output logic transfer, overflow,
  output integer level
);
  logic [7:0] slots [0:DEPTH-1];
  integer head, tail;
  assign oldest = slots[head];
  assign transfer = grant && level != 0;
  assign overflow = arrival && level == DEPTH && !transfer;
  wire enqueue = arrival && !overflow;

  always_ff @(posedge clk) begin
    if (reset) begin
      head <= 0;
      tail <= 0;
      level <= 0;
    end else begin
      if (transfer)
        head <= head == DEPTH-1 ? 0 : head+1;
      if (enqueue) begin
        slots[tail] <= rx_byte;
        tail <= tail == DEPTH-1 ? 0 : tail+1;
      end
      level <= level + int'(enqueue) - int'(transfer);
    end
  end
endmodule
Read included file: apb_tasks.svh
// apb_tasks.svh: the requester side of the bench, as tasks for the stimulus (read-only).
// apb_write(addr, data, strb, prot) and apb_read(addr, prot) run one transfer and leave the bus
// IDLE; q_write / q_read queue transfers and apb_run() sends the queue back to back with PSEL held
// high (ACCESS goes straight to SETUP). Each transfer prints one log line at its completion edge:
//   e3-e4 WRITE 0x0100 data=0x11223344 strb=1111 waits=0 OKAY
// (setup edge - completion edge). The result of a read is in prdata_q and pslverr_q; the results
// of a queue are in rdv[i] and errv[i]. `cycle` counts rising edges from 0.
int cycle = -1;
always @(posedge pclk) cycle = cycle + 1;
bit quiet = 0;
// Requester bugs, for the broken twins:
bit move_in_wait = 0;   // PADDR moves by 4 in the first wait cycle
bit enable_stuck = 0;   // PENABLE stays 1 into the next queued transfer (no setup cycle)
bit strb_on_read = 0;   // PSTRB = 1111 on reads
bit skip_setup   = 0;   // PSEL and PENABLE rise together
int give_up      = 24;  // the bench stops waiting after this many wait cycles
// APB5 wake-up (IHI 0024E 3.7), off by default: with wake_lead >= 0 the requester raises PWAKEUP
// wake_lead cycles before PSEL of a transfer that starts from IDLE, and lowers it after the last
// transfer of a run completes. Broken twin: wake_drop_in_wait lowers PWAKEUP in the first wait cycle.
// The wake-up request is wake_req; a bench built with wake copies it onto PWAKEUP.
int wake_lead    = -1;
bit wake_drop_in_wait = 0;
logic wake_req = 0;

logic [31:0] prdata_q = 0;
logic        pslverr_q = 0;
int          waits_q = 0;
bit          stuck_now = 0;
bit          q_wr [0:63];
logic [31:0] q_addr [0:63], q_data [0:63], rdv [0:63];
logic [3:0]  q_strb [0:63];
logic [2:0]  q_prot [0:63];
bit          errv [0:63];
int          qn = 0;

// A text waveform for the trace blocks: one line per rising edge with the values sampled there.
bit watch = 0;
int wave_edge = -1;
always @(posedge pclk) begin
  wave_edge = wave_edge + 1;
`ifdef APB_DECODER
  if (watch) $display("wave e%0d: psel=%b pselx=%b penable=%b pwrite=%b paddr=%h pwdata=%h pstrb=%b pready=%b prdata=%h pslverr=%b",
                      wave_edge, psel, pselx, penable, pwrite, paddr, pwdata, pstrb, pready, prdata, pslverr);
`else
  if (watch) $display("wave e%0d: psel=%b penable=%b pwrite=%b paddr=%h pwdata=%h pstrb=%b pready=%b prdata=%h pslverr=%b",
                      wave_edge, psel, penable, pwrite, paddr, pwdata, pstrb, pready, prdata, pslverr);
`endif
end

// One transfer: SETUP for one cycle, then ACCESS until PREADY. last = 0 keeps PSEL high for the
// next transfer.
task automatic apb_xfer(input bit wr, input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb,
                        input logic [2:0] prot, input bit last);
  int s_edge, w;
  if (wake_lead >= 0 && !psel) begin
    if (!wake_req) begin wake_req = 1; repeat (wake_lead) begin @(posedge pclk); #1; end end
  end
  paddr = addr; pwrite = wr; pwdata = wr ? data : 32'h0;
  pstrb = wr ? strb : (strb_on_read ? 4'hf : 4'h0);
  pprot = prot; psel = 1;
  s_edge = cycle + 1;
  if (skip_setup || stuck_now) penable = 1;
  else begin
    penable = 0;
    @(posedge pclk); #1 penable = 1;
  end
  stuck_now = 0;
  w = 0;
  @(posedge pclk);
  while (pready !== 1'b1 && w < give_up) begin
    w++;
    #1 if (move_in_wait && w == 1) paddr = addr + 4;
    if (wake_drop_in_wait && w == 1) wake_req = 0;
    @(posedge pclk);
  end
  prdata_q = prdata; pslverr_q = (pslverr === 1'b1); waits_q = w;
  #1;
  if (!quiet) begin
    if (w >= give_up) $display("e%0d-e%0d %0s 0x%04h no PREADY after %0d wait cycles, the bench gives up", s_edge, cycle, wr ? "WRITE" : "READ ", addr[15:0], w);
    else if (wr) $display("e%0d-e%0d WRITE 0x%04h data=0x%08h strb=%b waits=%0d %0s", s_edge, cycle, addr[15:0], data, strb, w, pslverr_q ? "PSLVERR" : "OKAY");
    else $display("e%0d-e%0d READ  0x%04h data=0x%08h waits=%0d %0s", s_edge, cycle, addr[15:0], prdata_q, w, pslverr_q ? "PSLVERR" : "OKAY");
  end
  if (last) begin
    psel = 0; penable = 0; pwrite = 0; pstrb = 0;
    if (wake_lead >= 0) wake_req = 0;
  end else begin
    penable = enable_stuck ? 1 : 0;
    stuck_now = enable_stuck;
  end
endtask

task automatic apb_write(input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb = 4'hf, input logic [2:0] prot = 3'b000);
  apb_xfer(1, addr, data, strb, prot, 1);
endtask
task automatic apb_read(input logic [31:0] addr, input logic [2:0] prot = 3'b000);
  apb_xfer(0, addr, 0, 0, prot, 1);
endtask

// The queue: transfers sent back to back by apb_run().
task automatic q_write(input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb = 4'hf, input logic [2:0] prot = 3'b000);
  q_wr[qn] = 1; q_addr[qn] = addr; q_data[qn] = data; q_strb[qn] = strb; q_prot[qn] = prot; qn++;
endtask
task automatic q_read(input logic [31:0] addr, input logic [2:0] prot = 3'b000);
  q_wr[qn] = 0; q_addr[qn] = addr; q_data[qn] = 0; q_strb[qn] = 0; q_prot[qn] = prot; qn++;
endtask
task automatic apb_run();
  for (int i = 0; i < qn; i++) begin
    apb_xfer(q_wr[i], q_addr[i], q_data[i], q_strb[i], q_prot[i], i == qn - 1);
    rdv[i] = prdata_q; errv[i] = pslverr_q;
  end
  qn = 0;
endtask

task automatic idle(input int n);
  repeat (n) @(posedge pclk);
  #1;
endtask

Check Yourself

Predict the outputIn this run the burst has five letters, A to E, in slots 1 to 5. What is the last row? Its form is: depth=5 peak=. lost=. SRAM=.....
`timescale 1ns/1ns
module tb;
  logic pclk = 0;
  always #5 pclk = ~pclk;
  logic psel=0, penable=0, pwrite=0;
  logic [31:0] paddr=0, pwdata=0;
  logic [3:0] pstrb=0;
  logic [2:0] pprot=0;
  localparam logic [31:0] CONTROL = 32'h1000_6010;
  wire pready = 1;
  wire pslverr = paddr != CONTROL;
  logic [31:0] control_word = 0;
  wire [31:0] prdata = control_word;
  always @(posedge pclk)
    if (psel && penable && pready && !pslverr && pwrite && pstrb == 4'hf)
      control_word <= pwdata;
  `include "apb_tasks.svh"

  localparam int BURST = 5;
  logic reset=1, arrival=0, grant=0;
  logic [7:0] rx_byte;
  wire [7:0] oldest[3];
  wire transfer[3], overflow[3];
  wire signed [31:0] level[3];
  // Two depth-five comparison paths: processor service misses alternate grants;
  // a double-width RAM keeps the same byte-wide DMA requester.
  wire [7:0] compare_byte[2];
  wire compare_transfer[2], compare_drop[2];
  integer comparison_count[2], last_commit[2];
  logic cpu_turn=0;
  for(genvar k=0;k<2;k++) begin: compare_paths
    localparam int PATH = k;
    ap_rx_queue #(.DEPTH(5)) queue (.clk(pclk), .reset(reset),
      .arrival(arrival), .rx_byte(rx_byte), .grant(PATH==0 ? grant && cpu_turn : grant),
      .oldest(compare_byte[PATH]), .transfer(compare_transfer[PATH]), .overflow(compare_drop[PATH]), .level());
  end
  logic [15:0] wide_sram[32];
  logic [7:0] cpu_sram[32];
  int offered=0, saved[3], lost[3], peak[3];
  logic [7:0] sram[3][32];
  for(genvar i=0;i<3;i++) begin: paths
    ap_rx_queue #(.DEPTH(i==0 ? 2 : i==1 ? 3 : 5)) queue
      (.clk(pclk), .oldest(oldest[i]), .transfer(transfer[i]),
       .overflow(overflow[i]), .level(level[i]), .*);
  end
  initial begin
    @(negedge pclk);
    watch = 1;
    apb_write(CONTROL, 2); // Service period in receive slots.
    watch=0;
    for (int i=0;i<3;i++) begin
      saved[i]=0; lost[i]=0; peak[i]=0;
    end
    for (int k=0;k<2;k++) begin
      comparison_count[k]=0; last_commit[k]=0;
    end
    for (int slot=1; slot<=2*BURST*control_word; slot++) begin
      @(negedge pclk);
      reset=0;
      arrival=slot<=BURST;
      rx_byte=8'h40+slot;
      grant=(slot % control_word)==0;
      cpu_turn=(slot % (2*control_word))==0;
      @(posedge pclk);
      if (arrival) offered++;
      for (int k=0;k<2;k++)
        if (compare_transfer[k]) begin
          if (k==0) cpu_sram[comparison_count[k]]=compare_byte[k];
          else wide_sram[comparison_count[k]][7:0]=compare_byte[k];
          comparison_count[k]++;
          last_commit[k]=slot;
        end
      for (int i=0;i<3;i++) begin
        if (overflow[i]) lost[i]++;
        if (transfer[i]) begin
          sram[i][saved[i]]=oldest[i];
          saved[i]++;
        end
      end
      #1;
      for (int i=0;i<3;i++)
        if (level[i]>peak[i]) peak[i]=level[i];
      if (slot<=2*BURST) $display("slot=%0d offered=%0d saved=%0d level=%0d",slot,offered,saved[2],level[2]);
    end
    $display("CPU bytes=%0d last_slot=%0d",comparison_count[0],last_commit[0]);
    $display("wide RAM bytes=%0d last_slot=%0d",comparison_count[1],last_commit[1]);
    for (int i=0;i<3;i++) begin
      $write("depth=%0d peak=%0d lost=%0d SRAM=",i==0?2:i==1?3:5,peak[i],lost[i]);
      for (int j=0;j<saved[i];j++) $write("%c",sram[i][j]);
      $display("");
    end
    $finish;
  end
endmodule
Read included file: soc-s85-rx.sv
// Byte queue at the UART receive boundary. A grant commits its oldest byte to
// the DMA sink. A simultaneous departure frees a slot before admission.
module ap_rx_queue #(parameter int DEPTH = 3) (
  input logic clk, reset, arrival, grant,
  input logic [7:0] rx_byte,
  output logic [7:0] oldest,
  output logic transfer, overflow,
  output integer level
);
  logic [7:0] slots [0:DEPTH-1];
  integer head, tail;
  assign oldest = slots[head];
  assign transfer = grant && level != 0;
  assign overflow = arrival && level == DEPTH && !transfer;
  wire enqueue = arrival && !overflow;

  always_ff @(posedge clk) begin
    if (reset) begin
      head <= 0;
      tail <= 0;
      level <= 0;
    end else begin
      if (transfer)
        head <= head == DEPTH-1 ? 0 : head+1;
      if (enqueue) begin
        slots[tail] <= rx_byte;
        tail <= tail == DEPTH-1 ? 0 : tail+1;
      end
      level <= level + int'(enqueue) - int'(transfer);
    end
  end
endmodule
Read included file: apb_tasks.svh
// apb_tasks.svh: the requester side of the bench, as tasks for the stimulus (read-only).
// apb_write(addr, data, strb, prot) and apb_read(addr, prot) run one transfer and leave the bus
// IDLE; q_write / q_read queue transfers and apb_run() sends the queue back to back with PSEL held
// high (ACCESS goes straight to SETUP). Each transfer prints one log line at its completion edge:
//   e3-e4 WRITE 0x0100 data=0x11223344 strb=1111 waits=0 OKAY
// (setup edge - completion edge). The result of a read is in prdata_q and pslverr_q; the results
// of a queue are in rdv[i] and errv[i]. `cycle` counts rising edges from 0.
int cycle = -1;
always @(posedge pclk) cycle = cycle + 1;
bit quiet = 0;
// Requester bugs, for the broken twins:
bit move_in_wait = 0;   // PADDR moves by 4 in the first wait cycle
bit enable_stuck = 0;   // PENABLE stays 1 into the next queued transfer (no setup cycle)
bit strb_on_read = 0;   // PSTRB = 1111 on reads
bit skip_setup   = 0;   // PSEL and PENABLE rise together
int give_up      = 24;  // the bench stops waiting after this many wait cycles
// APB5 wake-up (IHI 0024E 3.7), off by default: with wake_lead >= 0 the requester raises PWAKEUP
// wake_lead cycles before PSEL of a transfer that starts from IDLE, and lowers it after the last
// transfer of a run completes. Broken twin: wake_drop_in_wait lowers PWAKEUP in the first wait cycle.
// The wake-up request is wake_req; a bench built with wake copies it onto PWAKEUP.
int wake_lead    = -1;
bit wake_drop_in_wait = 0;
logic wake_req = 0;

logic [31:0] prdata_q = 0;
logic        pslverr_q = 0;
int          waits_q = 0;
bit          stuck_now = 0;
bit          q_wr [0:63];
logic [31:0] q_addr [0:63], q_data [0:63], rdv [0:63];
logic [3:0]  q_strb [0:63];
logic [2:0]  q_prot [0:63];
bit          errv [0:63];
int          qn = 0;

// A text waveform for the trace blocks: one line per rising edge with the values sampled there.
bit watch = 0;
int wave_edge = -1;
always @(posedge pclk) begin
  wave_edge = wave_edge + 1;
`ifdef APB_DECODER
  if (watch) $display("wave e%0d: psel=%b pselx=%b penable=%b pwrite=%b paddr=%h pwdata=%h pstrb=%b pready=%b prdata=%h pslverr=%b",
                      wave_edge, psel, pselx, penable, pwrite, paddr, pwdata, pstrb, pready, prdata, pslverr);
`else
  if (watch) $display("wave e%0d: psel=%b penable=%b pwrite=%b paddr=%h pwdata=%h pstrb=%b pready=%b prdata=%h pslverr=%b",
                      wave_edge, psel, penable, pwrite, paddr, pwdata, pstrb, pready, prdata, pslverr);
`endif
end

// One transfer: SETUP for one cycle, then ACCESS until PREADY. last = 0 keeps PSEL high for the
// next transfer.
task automatic apb_xfer(input bit wr, input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb,
                        input logic [2:0] prot, input bit last);
  int s_edge, w;
  if (wake_lead >= 0 && !psel) begin
    if (!wake_req) begin wake_req = 1; repeat (wake_lead) begin @(posedge pclk); #1; end end
  end
  paddr = addr; pwrite = wr; pwdata = wr ? data : 32'h0;
  pstrb = wr ? strb : (strb_on_read ? 4'hf : 4'h0);
  pprot = prot; psel = 1;
  s_edge = cycle + 1;
  if (skip_setup || stuck_now) penable = 1;
  else begin
    penable = 0;
    @(posedge pclk); #1 penable = 1;
  end
  stuck_now = 0;
  w = 0;
  @(posedge pclk);
  while (pready !== 1'b1 && w < give_up) begin
    w++;
    #1 if (move_in_wait && w == 1) paddr = addr + 4;
    if (wake_drop_in_wait && w == 1) wake_req = 0;
    @(posedge pclk);
  end
  prdata_q = prdata; pslverr_q = (pslverr === 1'b1); waits_q = w;
  #1;
  if (!quiet) begin
    if (w >= give_up) $display("e%0d-e%0d %0s 0x%04h no PREADY after %0d wait cycles, the bench gives up", s_edge, cycle, wr ? "WRITE" : "READ ", addr[15:0], w);
    else if (wr) $display("e%0d-e%0d WRITE 0x%04h data=0x%08h strb=%b waits=%0d %0s", s_edge, cycle, addr[15:0], data, strb, w, pslverr_q ? "PSLVERR" : "OKAY");
    else $display("e%0d-e%0d READ  0x%04h data=0x%08h waits=%0d %0s", s_edge, cycle, addr[15:0], prdata_q, w, pslverr_q ? "PSLVERR" : "OKAY");
  end
  if (last) begin
    psel = 0; penable = 0; pwrite = 0; pstrb = 0;
    if (wake_lead >= 0) wake_req = 0;
  end else begin
    penable = enable_stuck ? 1 : 0;
    stuck_now = enable_stuck;
  end
endtask

task automatic apb_write(input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb = 4'hf, input logic [2:0] prot = 3'b000);
  apb_xfer(1, addr, data, strb, prot, 1);
endtask
task automatic apb_read(input logic [31:0] addr, input logic [2:0] prot = 3'b000);
  apb_xfer(0, addr, 0, 0, prot, 1);
endtask

// The queue: transfers sent back to back by apb_run().
task automatic q_write(input logic [31:0] addr, input logic [31:0] data, input logic [3:0] strb = 4'hf, input logic [2:0] prot = 3'b000);
  q_wr[qn] = 1; q_addr[qn] = addr; q_data[qn] = data; q_strb[qn] = strb; q_prot[qn] = prot; qn++;
endtask
task automatic q_read(input logic [31:0] addr, input logic [2:0] prot = 3'b000);
  q_wr[qn] = 0; q_addr[qn] = addr; q_data[qn] = 0; q_strb[qn] = 0; q_prot[qn] = prot; qn++;
endtask
task automatic apb_run();
  for (int i = 0; i < qn; i++) begin
    apb_xfer(q_wr[i], q_addr[i], q_data[i], q_strb[i], q_prot[i], i == qn - 1);
    rdv[i] = prdata_q; errv[i] = pslverr_q;
  end
  qn = 0;
endtask

task automatic idle(input int n);
  repeat (n) @(posedge pclk);
  #1;
endtask

ConceptWhat is the backlog of a queue at one moment?
ConceptHow deep must a queue be to lose nothing?
ConceptWhy is a queue that overflowed no guide to the right depth?
ConceptWhat can a deeper queue not fix?

Common Mistakes

Wrong Size a queue from average rates.

A burst can lead the service by several items while the averages match.

Fix Find the largest backlog, slot by slot.

Wrong Read the right depth from a queue that lost data.

Lost items never appear in its level.

Fix Count what was offered and what was served, from a run that lost nothing.

Wrong Expect twice the rate from a port twice as wide.

A stage that sends one byte with each write leaves the other half empty.

Fix Find the bottleneck first, and widen that.

Remember

  • Backlog is what was offered less what was served.
  • A queue must hold the largest backlog, taken from a run that lost nothing.
  • Service that is not used is gone.
  • A queue buys time, not rate. For rate, find the bottleneck by changing one thing.

Practice

Report a problem with this page