Link Training and State Machines
Read a link training state machine and predict what it does when one side misbehaves.
You Will Be Able To
- Explain why a link trains and what each training step establishes.
- Explain why the handshakes count consecutive ordered sets, not a total.
- Predict where a port is when its partner never answers.
- Explain what a timeout does in a training state machine.
- Lesson
- P10.13
- Time
- 30 min
- Runs on
- Your browser
- Check
- 5 questions
Two ports power up on a clean link. 62 clocks later, both are in the working state. Corrupt one ordered set in six on the way, and they never get there. Each falls back to the start 7 times in 3,000 clocks.
- Cycle 0
After reset both ports are in DETECT and send electrical idle (EI). The bench waits 12 clocks there.
- Cycle 1
Both start sending TS1. Each waits until it has received 8 TS1 in a row.
- Cycle 2
Eight TS1 have arrived. Both move on and send TS2. Each waits for 8 TS2 in a row, and sends at least 16 itself.
- Cycle 3
Both send IDLE in CONFIG and wait for 8 IDLE in a row from the other side.
- Cycle 4
Both reach L0, the working state, at clock 62.
Bench run. The bench counts (8 sets in a row, 16 TS2 sent) mirror USB 3.2's Polling rules. The 12-clock wait, the 6-clock delay and the 400-clock timeout are bench values.
Why a Link Trains
Before two ports can exchange data, each must find the other and lock to its signal. They must also agree on the details: polarity, lane numbers, speed and equalization.
They do this by sending ordered sets and counting what they receive. A link training and status state machine (LTSSM) steps through the stages.
USB 3.2 defines twelve LTSSM states (§7.5). Four are for training: Rx.Detect, Polling, Recovery and Hot Reset. U0 is the working state, and U1 to U3 save power.
PCIe uses the same idea with its own names: Detect, Polling, Configuration, Recovery, L0. AMD's PCIe block reports them on its cfg_ltssm_state port (PG213, Table 25).
- Control / FSM
- Control
- Find the partner
DETECT waits a fixed time, then starts sending TS1.
- Lock with TS1
POLL_TS1 waits for 8 TS1 (or TS2) in a row from the partner.
- Confirm with TS2
POLL_TS2 waits for 8 TS2 in a row, and sends at least 16 itself, so the partner can finish too.
- Go to work
CONFIG waits for 8 IDLE in a row, then both ports are in L0.
- Give up and retry
POLL_TS1, POLL_TS2 and CONFIG each return to DETECT after 400 clocks without their condition.
Read the diagram as text
- DETECT: sends EI
- POLL_TS1: sends TS1
- POLL_TS2: sends TS2
- CONFIG: sends IDLE
- L0: working
- Timeout: 400 clocks in a state
- DETECT → POLL_TS1: after 12 clocks
- POLL_TS1 → POLL_TS2: 8 TS1 in a row
- POLL_TS2 → CONFIG: 8 TS2 in a row, 16 sent
- CONFIG → L0: 8 IDLE in a row
- Timeout → DETECT: back to the start
Every count and the timeout are bench values. USB 3.2 uses eight sets in a row and sixteen TS2 sent in Polling (§7.5.4.8, §7.5.4.9), and a 12 ms timer.
Handshakes by Counting
A port moves on only when it has received enough of the right ordered set in a row. One stray set must not count, and one lost set must restart the count.
USB 3.2 leaves Polling.Active after eight consecutive identical TS1 or TS2 sets (§7.5.4.8.2). It leaves Polling.Configuration after eight consecutive TS2, once it has sent sixteen TS2 itself (§7.5.4.9.2).
The bench uses the same counts. It counts the TS2 sent since entering the state, a simplification of USB's rule.
| Run of 3,000 clocks | Both in L0 at clock | Returns to DETECT (A, B) |
|---|---|---|
| Clean | 62 | 0, 0 |
| One set in 50 corrupted | 62 | 0, 0 |
| One set in 6 corrupted | never | 7, 7 |
One set in 6, count_total_not_consecutive on both | 64 | 0, 0 |
never_ts2 on B | never | 7, 7 |
never_ts2 on B and no_timeout on both | never | 0, 0 |
Bench runs. Corruption hits the sets port B receives. The fourth row trains, but on sets that were not consecutive: the rule was broken, not met.
Errors at an unlucky moment are enough. With one set in 25 corrupted, B received a long run of TS2, but before it had sent its own 16. Then one corrupted set restarted B's count, just as A moved on to CONFIG and stopped sending TS2.
B never got 8 more TS2, so both ports timed out. The errors were periodic, so every retry hit the same spot: 6 returns to DETECT and no L0.
With one set in 20 or in 40, the errors fell elsewhere and the link trained at clock 70 and 66.
Timeouts
A port that waits for something that never comes must give up. A timeout is a state change, not an error message: the port returns to the start and tries again.
never_ts2 on port B. It keeps sending TS1. Port A moves on, then waits for TS2 that never comes.- Cycle 2
A has 8 TS1 from B and moves to POLL_TS2. B received 8 TS1 too, but its fault keeps it in POLL_TS1.
- Cycle 3
B has been in POLL_TS1 for 400 clocks: its timeout sends it back to DETECT.
- Cycle 5
A has waited 400 clocks for TS2 and times out too. Both ports start again, and the cycle repeats.
Bench run. In 3,000 clocks each port returned to DETECT 7 times and the link never trained.
USB 3.2 sets a 12 ms timer on entry to Polling.Active. When it expires without the exit condition, a SuperSpeed downstream port goes back to Rx.Detect. After two such timeouts it goes to eSS.Inactive instead, an error state that software must clear (§7.5.4.8.2).
A real LTSSM counts its retries. The bench retries for ever. Table 7-12 lists all the LTSSM timeouts.
Without the timeout, the bench ports wait for ever: after 3,000 clocks A was still in POLL_TS2 and B in POLL_TS1.
Before Training: Electrical Idle, LFPS and Receiver Detection
Before any ordered set, a port must know that a partner is there. In electrical idle the transmitter drives no data.
A transmitter detects a receiver by stepping its common-mode voltage and watching how fast the pin charges. A terminated receiver behind the AC capacitor slows it down (§6.11).
- receiver present
- receiver absent
Read the plot as a table
| Time | receiver present | receiver absent |
|---|---|---|
| 0 s | 0 V | 0 V |
| 500 ns | 16.89 mV | 545.5 mV |
| 1 µs | 19.72 mV | 545.5 mV |
| 1.5 µs | 22.55 mV | 545.5 mV |
| 2 µs | 25.36 mV | 545.5 mV |
ngspice run. The detect resistor is a bench value; the capacitor and the terminations lie inside USB 3.2 Tables 6-18 and 6-22.
At 1 µs the pin had reached 20 mV with a receiver present and 545 mV without one.
Ports then signal across the idle line with LFPS: bursts of a slow square wave. The burst length is the message (§6.9.1, Table 6-30).
| Bursts sent | Detector measured | Read as |
|---|---|---|
| 1000 ns every 10,000 ns | 1000 ns every 10,000 ns | Polling.LFPS |
| 100 ns every 4,000 ns | 100 ns every 4,000 ns | Ping.LFPS |
| 1500 ns every 10,000 ns | 1500 ns every 10,000 ns | not a Polling or Ping burst |
Bench run: a 50 ns square wave; the detector counts a burst until no edge comes for 100 ns. Polling.LFPS is 0.6 to 1.4 µs every 6 to 14 µs; Ping.LFPS 40 to 200 ns (Table 6-30). The 4 µs Ping repeat is a bench value; USB repeats it every 200 ms.
Fallback and the Retry Limit
A port that cannot train at its best capability must try the next one. USB 3.2 gives the example of a Gen 1x2 port falling back to Gen 1x1 (§7.5.4.8.1).
| Partner | Result |
|---|---|
| Handles Gen 2x1 at best (one lane broken) | Trained at Gen 2x1 after 2 attempts |
| Handles Gen 1x1 only | Trained at Gen 1x1 after 4 attempts |
| Never answers | No capability trained after 5 attempts; error state |
Bench model: the port tries Gen 2x2, Gen 2x1, Gen 1x2 and Gen 1x1 in turn. It gives up after two failed tries at Gen 1x1.
Giving up matters as much as retrying. The Timeouts section shows USB 3.2's retry limit.
Low-Power States U1 to U3
A trained link need not stay awake. USB 3.2 defines U1 and U2 as low-power states, U2 saving more with a longer exit, and U3 as suspend (§7.5).
Leaving one costs time (Table 6-30). The LFPS exit burst lasts at least 900 ns from U1, 80 µs from U2 and 80 µs from U3.
| Policy | Idle time in U1 | Idle time in U2 | Average added wait per wake-up |
|---|---|---|---|
| U0 only | 0% | 0% | 0.0 µs |
| U1 after 2 us | 94% | 0% | 0.9 µs |
| U1 after 2 us, U2 after 32 us | 51% | 43% | 36.9 µs |
Bench model: 5,000 idle gaps with a mean of 40 µs. Entry timers and the gap length are bench values; the exit times are Table 6-30's minimums.
The entry timers decide how often traffic pays the long U2 exit.
Equalization During Training
Fast links also tune their equalizers during training. One side changes its transmit taps; the other measures the result and asks for more or less.
PIPE describes the receiver's side (§8.21). The MAC sets RxEqEval. The PHY then reports a direction change, a figure of merit, or both.
This is a handshake too, with a timeout of its own. The details belong to each protocol module.
Try It
Both ports change state on the same clocks because the link is symmetric: same rules, same delay both ways.
Each wait is about 16 clocks. That is 8 sets to count, 6 clocks for the first set to arrive, and a clock to decide.
Change go(0, 0, 100) to go(0, 1, 100). Port B now never sends TS2. A reaches POLL_TS2 and stays there, and both ports are far from L0.
c13 A POLL_TS1 c13 B POLL_TS1 c29 A POLL_TS2 c29 B POLL_TS2 c46 A CONFIG c46 B CONFIG c62 A L0 c62 B L0 both ports in L0 at clock 62Read included file: hs_pkg.sv
`timescale 1ns/1ns
// hs_pkg.sv: shared pure functions, and the bench random generator (read-only).
package hs_pkg;
// xorshift32 (Marsaglia 2003): a linear generator over GF(2), period 2^32 - 1. A zero state is
// replaced by 1, because zero maps to itself.
function automatic [31:0] xs32(input [31:0] s);
reg [31:0] x;
x = (s == 32'd0) ? 32'd1 : s;
x = x ^ (x << 13); x = x ^ (x >> 17); x = x ^ (x << 5);
return x;
endfunction
// A Fibonacci PRBS generator x^n + x^m + 1 (PRBS7: 7,6; PRBS9: 9,5; PRBS15: 15,14; PRBS23: 23,18;
// PRBS31: 31,28). The output bit is s[n-1]; the next state shifts the feedback into bit 0.
function automatic [31:0] prbs_next(input [31:0] s, input int n, input int m);
reg fb;
fb = s[n-1] ^ s[m-1];
return ((s << 1) | {31'd0, fb}) & ((n == 32) ? 32'hffffffff : ((32'd1 << n) - 32'd1));
endfunction
function automatic int ones(input [63:0] v);
int n; n = 0;
for (int i = 0; i < 64; i++) n += v[i];
return n;
endfunction
// GF(16) with x^4 + x + 1, and GF(1024) with x^10 + x^3 + 1: shift-and-add multiply, no tables.
function automatic [3:0] gf16_mul(input [3:0] a, input [3:0] b);
reg [3:0] p, x; p = 4'd0; x = a;
for (int i = 0; i < 4; i++) begin
if (b[i]) p = p ^ x;
x = x[3] ? ({x[2:0], 1'b0} ^ 4'b0011) : {x[2:0], 1'b0};
end
return p;
endfunction
function automatic [3:0] gf16_pow(input int e); // alpha^e, alpha = x
reg [3:0] p; int k; p = 4'd1; k = e % 15; if (k < 0) k += 15;
for (int i = 0; i < k; i++) p = gf16_mul(p, 4'd2);
return p;
endfunction
function automatic int gf16_log(input [3:0] a); // -1 for 0
reg [3:0] p; p = 4'd1;
if (a == 4'd0) return -1;
for (int i = 0; i < 15; i++) begin if (p == a) return i; p = gf16_mul(p, 4'd2); end
return -1;
endfunction
function automatic [9:0] gf1024_mul(input [9:0] a, input [9:0] b);
reg [9:0] p, x; p = 10'd0; x = a;
for (int i = 0; i < 10; i++) begin
if (b[i]) p = p ^ x;
x = x[9] ? ({x[8:0], 1'b0} ^ 10'b0000001001) : {x[8:0], 1'b0};
end
return p;
endfunction
function automatic [9:0] gf1024_pow(input int e);
reg [9:0] p; int k; p = 10'd1; k = e % 1023; if (k < 0) k += 1023;
for (int i = 0; i < k; i++) p = gf1024_mul(p, 10'd2);
return p;
endfunction
endpackage
// hs_rng: the bench's random numbers. Same seed, same numbers, on every engine.
module hs_rng;
int unsigned s = 32'h2545f491;
function automatic void seed(input int unsigned v); s = (v == 0) ? 32'd1 : v; endfunction
function automatic int unsigned next(); s = hs_pkg::xs32(s); return s; endfunction
function automatic int below(input int n); s = hs_pkg::xs32(s); return (n <= 0) ? 0 : int'(s % n); endfunction
function automatic bit bit1(); s = hs_pkg::xs32(s); return s[16]; endfunction
function automatic bit chance_ppm(input int ppm); s = hs_pkg::xs32(s); return (s % 1000000) < ppm; endfunction
function automatic [7:0] byte8(); s = hs_pkg::xs32(s); return s[23:16]; endfunction
endmodule
Read included file: hs_link.sv
`timescale 1ns/1ns
// hs_link.sv: link training, credit flow control and Ack/Nak replay (read-only).
// Every count, delay and timeout here is a bench value, not a specification's.
//
// hs_train_port: a toy state machine in the shape of an LTSSM, one ordered set per clock.
// Ordered sets: 0 EI (electrical idle), 1 TS1, 2 TS2, 3 IDLE, 4 a corrupted set.
// The rule, clock by clock. Clock 0 is the first clock after reset is released; the state is DETECT.
// - tx at clock c is the set chosen at clock c-1 for the state of clock c-1: EI in DETECT, TS1 in
// POLL_TS1, TS2 in POLL_TS2, IDLE in CONFIG and L0 (EI during reset and at clock 0).
// - A decision at clock c uses the sets received at clocks before c: run_ts1 is the number of TS1 or TS2
// received in a row ending at clock c-1, run_ts2 the same for TS2, run_idle for IDLE.
// - time_in_state at clock c is the number of clocks since the state began (0 at its first clock).
// - DETECT: after detect_wait clocks (time_in_state >= detect_wait) go to POLL_TS1.
// POLL_TS1: when run_ts1 >= need_ts1 go to POLL_TS2.
// POLL_TS2: when run_ts2 >= need_ts2 and at least min_ts2_sent TS2 have been sent in this state go to
// CONFIG (the TS2 count at clock c is time_in_state: one TS2 is sent per clock of the state).
// CONFIG: when run_idle >= need_idle go to L0.
// In POLL_TS1, POLL_TS2 and CONFIG, when no transition is due and time_in_state >= timeout, go to
// DETECT and count a retrain. So no state but L0 lasts more than timeout + 1 clocks.
// - A transition decided at clock c takes effect at clock c + 1. Counters hold up to 65535.
// Faults: never_ts2 (never leaves POLL_TS1 for POLL_TS2), count_total_not_consecutive (the run counts
// count every matching set since reset: a bad set does not reset them), no_timeout (never times out).
// hs_train_link: two ports a and b. b receives at clock c what a sent at clock c - 6 (a delay line of 5
// registers), and the reverse; before that they receive EI. When corrupt_every > 0, the set b receives at
// every clock c with c % corrupt_every == 0 is replaced by a corrupted set. up_at is the first clock at
// which both ports are in L0 (-1: not yet). Hold rst high from time 0 (before reset Icarus shows x), and
// read up_at at a negedge: it is written at the posedge. trace = 1 logs "c<clock> A <state>" lines.
//
// hs_fc: credit flow control, stepped once per cycle by step(). The rule, for cycle t (from 0):
// 1. A packet sent in cycle t - delay - 1 arrives: the receiver stores it, or counts an overflow if it
// already holds slots packets.
// 2. An update sent in cycle t - delay - 1 arrives at the transmitter. Cumulative (the default): it
// carries the running limit, slots + packets freed so far. incremental_credits: it means "+1".
// 3. When t % drain_every == drain_every - 1 and the receiver holds a packet, it frees one and sends an
// update, except that every drop_every-th update (0: none) is lost.
// 4. The transmitter always has a packet and sends one when it may: cumulative, while limit - sent > 0;
// incremental, while its credit count > 0; no_credits, always.
// Counters: sent, delivered, overflows, max_fill, last_send. delay is at most 15.
// incremental_credits is "+1 updates with no index": USB 3.2 §7.2.4 also returns one credit at a time
// (LCRD_A..D) but names each credit, so a lost one is noticed and recovered; this twin has no names.
//
// hs_replay: sequence numbers, Ack/Nak and a go-back-N replay buffer of window packets. The rule, for cycle
// t (from 0): a packet sent in cycle t - delay - 1 arrives (marked bad if it was corrupted); an Ack or
// Nak sent in cycle t - delay arrives. In each cycle, in order:
// 1. The receiver takes the arriving packet: a good packet whose number is the next expected one is
// delivered and Acked; a good packet with a lower number is Acked with the last good number; a bad or
// out-of-order packet gets one Nak (carrying the last good number) until a good one arrives
// (nak_every_bad: a Nak every time). If an Ack or Nak was made, one draw from the generator decides
// whether it is corrupted (and dropped) with probability loss_permille / 1000.
// 2. The transmitter: its timer counts up; an arriving Ack or Nak frees every packet up to its number
// (and restarts the timer if that frees any); a Nak rewinds the next packet to send to the oldest
// unacknowledged one and restarts the timer; so does a timer above timeout while packets are
// unacknowledged. Each rewind counts a replay.
// 3. If fewer than window packets are unacknowledged and any are left, the next one is sent; one draw
// decides whether it is corrupted. done_at is the first cycle that ends with every packet
// acknowledged (no_replay: with every packet sent and none in flight).
// Counters: delivered, dup, out_of_order, tx_count, naks, replays, done_at. delay is at most 15.
// Faults: no_replay (the buffer is freed on send), accept_any_seq (delivers any good packet),
// nak_every_bad (a Nak for every bad packet, not one per run: wasteful rather than wrong).
module hs_train_port(input wire clk, input wire rst, input wire [2:0] rx, output reg [2:0] tx = 3'd0, output reg [2:0] state = 3'd0, output reg [15:0] retrains = 16'd0);
localparam EI = 3'd0, TS1 = 3'd1, TS2 = 3'd2, IDL = 3'd3;
localparam DETECT = 3'd0, POLL_TS1 = 3'd1, POLL_TS2 = 3'd2, CONFIG = 3'd3, L0 = 3'd4;
int detect_wait = 12, need_ts1 = 8, need_ts2 = 8, min_ts2_sent = 16, need_idle = 8, timeout = 400;
bit never_ts2 = 0, count_total_not_consecutive = 0, no_timeout = 0;
reg [15:0] run1 = 16'd0, run2 = 16'd0, runi = 16'd0, timer = 16'd0;
wire tmo = (timer >= timeout) && !no_timeout;
wire keep = count_total_not_consecutive;
function automatic [15:0] up(input [15:0] v); return v + (v != 16'hffff); endfunction
always @(posedge clk) if (rst) begin state <= DETECT; tx <= EI; run1 <= 0; run2 <= 0; runi <= 0; timer <= 0; retrains <= 0; end
else begin
run1 <= (rx == TS1 || rx == TS2) ? up(run1) : keep ? run1 : 16'd0;
run2 <= (rx == TS2) ? up(run2) : keep ? run2 : 16'd0;
runi <= (rx == IDL) ? up(runi) : keep ? runi : 16'd0;
timer <= up(timer);
case (state)
DETECT: begin tx <= EI; if (timer >= detect_wait) begin state <= POLL_TS1; timer <= 0; end end
POLL_TS1: begin tx <= TS1;
if (run1 >= need_ts1 && !never_ts2) begin state <= POLL_TS2; timer <= 0; end
else if (tmo) begin state <= DETECT; timer <= 0; retrains <= retrains + 1; end end
POLL_TS2: begin tx <= TS2;
if (run2 >= need_ts2 && timer >= min_ts2_sent) begin state <= CONFIG; timer <= 0; end
else if (tmo) begin state <= DETECT; timer <= 0; retrains <= retrains + 1; end end
CONFIG: begin tx <= IDL;
if (runi >= need_idle) begin state <= L0; timer <= 0; end
else if (tmo) begin state <= DETECT; timer <= 0; retrains <= retrains + 1; end end
default: tx <= IDL;
endcase
end
endmodule
module hs_train_link(input wire clk, input wire rst);
int corrupt_every = 0; int n = 0, up_at = -1; bit trace = 0;
localparam D = 5;
reg [2:0] ab [0:D]; reg [2:0] ba [0:D];
initial for (int i = 0; i <= D; i++) begin ab[i] = 3'd0; ba[i] = 3'd0; end
wire [2:0] atx, btx, ast, bst; wire [15:0] ar, br;
wire [2:0] b_in = (corrupt_every > 0 && n % corrupt_every == 0) ? 3'd4 : ab[D];
hs_train_port a(clk, rst, ba[D], atx, ast, ar);
hs_train_port b(clk, rst, b_in, btx, bst, br);
reg [2:0] ast_q = 0, bst_q = 0;
function automatic string sname(input [2:0] s);
case (s) 3'd0: return "DETECT"; 3'd1: return "POLL_TS1"; 3'd2: return "POLL_TS2"; 3'd3: return "CONFIG"; default: return "L0"; endcase
endfunction
always @(posedge clk) begin
n <= rst ? 0 : n + 1;
ab[0] <= rst ? 3'd0 : atx; ba[0] <= rst ? 3'd0 : btx;
for (int i = 1; i <= D; i++) begin ab[i] <= rst ? 3'd0 : ab[i-1]; ba[i] <= rst ? 3'd0 : ba[i-1]; end
if (rst) up_at = -1;
else if (up_at < 0 && ast == 3'd4 && bst == 3'd4) up_at = n;
if (trace && !rst && ast != ast_q) $display("c%0d A %s", n, sname(ast));
if (trace && !rst && bst != bst_q) $display("c%0d B %s", n, sname(bst));
ast_q <= ast; bst_q <= bst;
end
endmodule
module hs_fc;
int slots = 8, delay = 3, drain_every = 4, drop_every = 0;
bit incremental_credits = 0, no_credits = 0;
bit fv [0:15]; bit rv [0:15]; int rval [0:15];
int t = 0, fill = 0, max_fill = 0, overflows = 0, delivered = 0, sent = 0, freed = 0, consumed = 0, limit = 8, credits = 8, upd = 0, last_send = -1;
function automatic void restart();
if (delay > 15) begin $display("hs_fc: delay %0d clamped to 15", delay); delay = 15; end
t = 0; fill = 0; max_fill = 0; overflows = 0; delivered = 0; sent = 0; freed = 0; consumed = 0; limit = slots; credits = slots; upd = 0; last_send = -1;
for (int i = 0; i < 16; i++) begin fv[i] = 0; rv[i] = 0; rval[i] = 0; end
endfunction
function automatic bit can_send(); return no_credits || (incremental_credits ? credits > 0 : (limit - consumed) > 0); endfunction
function automatic void step();
if (fv[delay]) begin if (fill == slots) overflows++; else fill++; end // arrivals at the receiver
if (fill > max_fill) max_fill = fill;
if (rv[delay]) begin if (incremental_credits) credits++; else limit = rval[delay]; end // updates at the transmitter
for (int i = delay; i > 0; i--) begin fv[i] = fv[i-1]; rv[i] = rv[i-1]; rval[i] = rval[i-1]; end
rv[0] = 0; // the receiver drains and returns
if (t % drain_every == drain_every - 1 && fill > 0) begin
fill--; delivered++; freed++; upd++;
if (!(drop_every > 0 && upd % drop_every == 0)) begin rv[0] = 1; rval[0] = slots + freed; end
end
fv[0] = 0; // the transmitter always has data
if (can_send()) begin fv[0] = 1; sent++; consumed++; credits--; last_send = t; end
t++;
endfunction
endmodule
module hs_replay;
int window = 8, delay = 4, timeout = 40, loss_permille = 0, total = 2000;
bit no_replay = 0, accept_any_seq = 0, nak_every_bad = 0;
hs_rng rng();
bit fv [0:15]; int fseq [0:15]; bit fbad [0:15]; bit rv [0:15]; bit rnak [0:15]; int rseq [0:15];
bit got [0:65535]; bit nak_sent = 0;
int t = 0, base = 0, nxt = 0, expected = 0, delivered = 0, dup = 0, out_of_order = 0, tx_count = 0, naks = 0, replays = 0, timer = 0, done_at = -1;
function automatic void restart(input int pm, input int seed);
if (delay > 15) begin $display("hs_replay: delay %0d clamped to 15", delay); delay = 15; end
if (total > 65536) begin $display("hs_replay: total %0d clamped to 65536", total); total = 65536; end
loss_permille = pm; rng.seed(seed);
t = 0; base = 0; nxt = 0; expected = 0; delivered = 0; dup = 0; out_of_order = 0; tx_count = 0; naks = 0; replays = 0; timer = 0; nak_sent = 0; done_at = -1;
for (int i = 0; i < 16; i++) begin fv[i] = 0; rv[i] = 0; end
for (int i = 0; i < total; i++) got[i] = 0;
endfunction
function automatic bit bad(); return rng.below(1000) < loss_permille; endfunction
function automatic void nak(); rv[0] = 1; rnak[0] = 1; rseq[0] = expected - 1; nak_sent = 1; naks++; endfunction
function automatic void step();
rv[0] = 0; // receiver
if (fv[delay]) begin
if (fbad[delay]) begin if (!nak_sent || nak_every_bad) nak(); end
else if (fseq[delay] == expected || accept_any_seq) begin
if (got[fseq[delay]]) dup++; else begin got[fseq[delay]] = 1; delivered++; end
if (fseq[delay] != expected) out_of_order++;
expected = fseq[delay] + 1; nak_sent = 0; rv[0] = 1; rnak[0] = 0; rseq[0] = fseq[delay];
end
else if (fseq[delay] < expected) begin rv[0] = 1; rnak[0] = 0; rseq[0] = expected - 1; end
else if (!nak_sent || nak_every_bad) nak();
end
if (rv[0] && bad()) rv[0] = 0; // a corrupted Ack or Nak is dropped
timer++; // transmitter
if (rv[delay]) begin
if (rseq[delay] + 1 > base) begin base = rseq[delay] + 1; timer = 0; end
if (rnak[delay] && !no_replay) begin nxt = base; replays++; timer = 0; end
end
if (no_replay) base = nxt;
if (timer > timeout && base < nxt && !no_replay) begin nxt = base; replays++; timer = 0; end
for (int i = delay; i > 0; i--) begin fv[i] = fv[i-1]; fseq[i] = fseq[i-1]; fbad[i] = fbad[i-1]; rv[i] = rv[i-1]; rnak[i] = rnak[i-1]; rseq[i] = rseq[i-1]; end
fv[0] = 0;
if (nxt < total && nxt < base + window) begin fv[0] = 1; fseq[0] = nxt; fbad[0] = bad(); nxt++; tx_count++; end
if (done_at < 0) begin
if (base >= total) done_at = t;
else if (no_replay && nxt >= total) begin reg busy; busy = 0; for (int i = 0; i <= delay; i++) busy = busy | fv[i]; if (!busy) done_at = t; end
end
t++;
endfunction
function automatic void run(input int max_cycles); while (done_at < 0 && t < max_cycles) step(); endfunction
endmodule
Check Yourself
Common Mistakes
Wrong Count matching ordered sets in total instead of in a row.
A total lets corrupted sets slip between good ones; with one set in 6 corrupted, such ports reached L0 at clock 64.
Fix Reset the count on every set that does not match, so only an unbroken run passes.
if (rx == TS1) run1 <= run1 + 1;run1 <= (rx == TS1) ? run1 + 1 : 0;Wrong Leave out the timeout because the partner always answers.
A partner that misbehaves once leaves the port waiting for ever; without timeouts the bench ports stayed in POLL_TS2 and POLL_TS1.
Fix Give every waiting state a timeout that returns to the start, and count the retries.
Wrong Assume both ports step through the states together.
Each port moves on its own counts, so one can move ahead while the other still waits.
Fix Check each port's state and what it sends separately, in both directions.
Wrong Treat link training as something that happens once at power-up.
USB 3.2's Recovery state retrains the link after low-power states and when a port sees the link misbehave (§7.5).
Fix Expect retraining during normal operation, and test the paths back into training.
Remember
- A link trains to find its partner, lock, and agree on settings before it carries data.
- Each handshake waits for a run of identical ordered sets, and a mismatch restarts the count.
- Ports move on their own counts. One can move ahead while the other still waits.
- A timeout returns a stuck port to the start. Without it, one misbehaving partner hangs the link.
- Errors at the wrong moment can stop training even at a low error rate.