Link Training

A 10 Gb/s signal comes out of a backplane badly worn. Before any data flows, each receiver tells the far transmitter how to shape its signal. See the frame that carries those requests.

You Will Be Able To

  • Name the four parts of a training frame.
  • Read a coefficient update field and a status report field.
  • Follow one tap through request, status and hold.
  • Explain how the two ports agree to switch to data.
Lesson
P11.38
Time
40 min
Runs on
Your browser
Check
5 questions

A request is not a command sent once. It stays on the line until the answer comes back.

One Tap, Nine FramesThe partner asks for a change of c(0). The port moves the tap once and reports it. A hold clears the report.
012345678frame123456789request for c(0)holdincrementholdincrementholddecrementholdc(0)30313231status of c(0)not_updatedupdatednot_updatedupdatednot_updatedupdatednot_updated
Scroll horizontally ↔
  1. Cycle 0

    The partner holds. The tap rests at 30 and reports not_updated.

  2. Cycle 1

    An increment arrives. The tap moves one step and reports updated.

  3. Cycle 2

    The request is still there. The tap does not move again.

  4. Cycle 3

    The partner has seen the report. It sends a hold, and the status goes back to not_updated.

  5. Cycle 4

    Only now may the partner ask again.

Bench run of a private model of Figure 72-6, in steps of the bench.

A backplane channel smears each bit into its neighbours. Every slot and every trace length does it differently.

A transmitter can undo part of the damage: it mixes each bit with its two neighbours.

Three taps set how much: c(−1), c(0) and c(+1). They are the pre-cursor, main and post-cursor taps.

The transmitter cannot see what arrives. The far receiver can.

So the receiver steers the transmitter of its partner. That is the startup protocol of 10GBASE-KR (72.6.10.1).

The standard does not say how a receiver decides what to ask for (72.6.10.2.3).

The Training Frame

During training a port sends one frame after another, with no gap.

PartOctetsUIHow it is sent
Frame marker432FFFF0000h: 16 UI high, then 16 UI low
Coefficient update1612816 DME cells of 8 UI
Status report1612816 DME cells of 8 UI
Training pattern5124,0964,094 bits of PRBS11, then two zeros
One frame5484,384425.1 ns at 10.3125 GBd

IEEE Std 802.3-2022 72.6.10.2 and Figure 72-2. The last cell is bench arithmetic.

The frame marker is 16 UI high, then 16 UI low. No other part of a frame has that pattern (72.6.10.2.1).

One long level proves nothing: a status cell and a run of the pattern can hold one for 19 UI.

The two fields after it are the control channel.

The pattern lets the receiver measure the channel. It has 2,048 ones and as many zeros, the two pad zeros included.

The Control Channel: Slow and Safe

The channel is not equalized yet. Fast bits may not arrive. So the control channel is sent slowly.

It uses the DME code of P11.37, at a quarter of the line rate (72.6.10.2).

One bit is one cell of 8 UI. The level changes at the start of every cell.

A second change in the middle of the cell is a 1. No change there is a 0 (72.6.10.2.2).

So a field of 16 bits takes 128 UI.

A cell that starts without a change is a coding violation. Then the port ignores both fields of that frame.

The frameWhat the port does with the control channel
the first frame, no frame lock yetignores it
the second frame, as sentreads it: update 0000h, status 8013h
one level wrong in the update fieldignores it
one level wrong in the status fieldignores it
the frame as sent againreads it: update 0000h, status 8013h

Bench run of a private model. The line is a model: one level for each half of a cell.

The Two Fields

The first field carries requests. It is for the transmitter at the other end.

CellsNameValues
15, 14Reservedsent as 0, ignored
13Preset1: go to the setting with no equalization
12Initialize1: go to the starting setting
11 to 6Reservedsent as 0, ignored
5, 4Request for c(+1)00 hold, 01 increment, 10 decrement, 11 reserved
3, 2Request for c(0)the same codes
1, 0Request for c(−1)the same codes

IEEE Std 802.3-2022 Table 72-4. Cell 15 is sent first.

The second field carries answers. It reports on the taps of the port that sends it.

CellsNameValues
15Receiver ready1: my receiver is tuned and ready for data
14 to 6Reservedsent as 0, ignored
5, 4Status of c(+1)00 not_updated, 01 updated, 10 minimum, 11 maximum
3, 2Status of c(0)the same codes
1, 0Status of c(−1)the same codes

IEEE Std 802.3-2022 Table 72-5. Cell 15 is sent first.

In the example the update field is 0021h: c(+1) down, c(−1) up.

The status field is 8013h: receiver ready, c(+1) updated, c(−1) at its maximum.

One Request, One Answer

Each tap has a small state machine. Its state is the status it reports (72.6.10.2.5).

One Tap of the TransmitterEach of the three taps has this little machine. Its state is what the status field reports.
  • Control / FSM
  • Control
One tap of the transmitterEach of the three taps has this little machine. Its state is what the status field reports. control NOT_UPDATED waits for a request control UPDATE_COEFF work out the newvalue control MAXIMUM tap at its top limit control UPDATED tap at the new value control MINIMUM tap at its bottom limit inc, dec, preset orinitializenew value at or abovethe topin betweenat or below thebottomholdholdhold
  1. control NOT_UPDATEDwaits for a request
    • inc, dec, preset or initialize → UPDATE_COEFF
  2. control UPDATE_COEFFwork out the new value
    • new value at or above the top → MAXIMUM
    • in between → UPDATED
    • at or below the bottom → MINIMUM
  3. control MAXIMUMtap at its top limit
    • hold → NOT_UPDATED
  4. control UPDATEDtap at the new value
    • hold → NOT_UPDATED
  5. control MINIMUMtap at its bottom limit
    • hold → NOT_UPDATED
  1. Rest

    The tap reports not_updated. Only here does it act on a request.

  2. Work out

    A request arrives. The port works out the value it would give.

  3. Report

    It reports updated, or the limit the tap has reached or already stood at.

  4. Release

    The report stays until a hold arrives. Then the tap rests again.

Read the diagram as text
  • NOT_UPDATED: waits for a request
  • UPDATE_COEFF: work out the new value
  • MAXIMUM: tap at its top limit
  • UPDATED: tap at the new value
  • MINIMUM: tap at its bottom limit
  • NOT_UPDATED → UPDATE_COEFF: inc, dec, preset or initialize
  • UPDATE_COEFF → MAXIMUM: new value at or above the top
  • UPDATE_COEFF → UPDATED: in between
  • UPDATE_COEFF → MINIMUM: at or below the bottom
  • MAXIMUM → NOT_UPDATED: hold
  • UPDATED → NOT_UPDATED: hold
  • MINIMUM → NOT_UPDATED: hold

Our own drawing of IEEE Std 802.3-2022 Figure 72-6.

The partner keeps its request until a status other than not_updated comes back.

Then it sends hold, and waits for not_updated. Only then may it ask again (72.6.10.2.3.3).

A partner does not know the limits of this transmitter. The status tells it.

TapRequestBeforeAfterStatus reported
c(−1)decrement−2−3updated
c(−1)decrement−3−4updated
c(−1)decrement−4−5updated
c(−1)decrement−5−6minimum
c(−1)decrement−6−6minimum
c(+1)increment−8−7updated
c(+1)increment−7−6updated
c(+1)increment−6−5updated
c(+1)increment−5−4updated
c(+1)increment−4−3updated
c(+1)increment−3−2updated
c(+1)increment−2−1updated
c(+1)increment−10maximum
c(+1)increment00maximum

Bench run of a private model. Bench limits: c(−1) from −6 to 0, c(+1) from −15 to 0. A hold follows every row.

A tap that reaches its limit reports the limit, not updated. So does a tap that already stands there.

Preset and Initialize

Preset switches equalization off: c(−1) and c(+1) go to zero and c(0) to its maximum (72.6.10.2.3.1).

Initialize goes back to the setting a port starts training with (72.6.10.2.3.2).

The tap numbers below are bench values.

The update field saysc(−1), c(0), c(+1)Status of the three taps
after reset−2, 30, −8all not_updated
preset0, 40, 0all maximum
preset still set0, 40, 0all maximum
all hold0, 40, 0all not_updated
initialize−2, 30, −8all updated
all hold−2, 30, −8all not_updated
preset and initialize together0, 40, 0all maximum

Bench run of a private model, row after row. The tap values are bench values, in steps.

While preset is still set, the status stays. A hold needs both bits at 0.

If several things are asked at once, preset wins, then initialize, then the step (72.6.10.3.4).

Frame Lock

A receiver must find the frames first. It tests a place in the bit stream for the marker (72.6.10.4.1).

Frame Lock on Twenty MarkersEach frame brings one marker. It matches FFFF0000h or it does not.
012345678910111213141516171819frame1234567891011121314151617181920markergoodbadgoodbadgoodbadgoodbadgoodframe_lock
Scroll horizontally ↔
  1. Cycle 0

    One good marker is not enough.

  2. Cycle 1

    A bad marker without lock starts the count again.

  3. Cycle 3

    Two good markers in a row: frame lock.

  4. Cycle 9

    Four bad markers in a row. The lock holds.

  5. Cycle 15

    The fifth bad marker in a row takes the lock away.

  6. Cycle 17

    Two good markers bring it back.

Bench run of a private model of Figure 72-4. The hunt for the right bit position is left out.

Two good markers in a row give frame_lock. Five bad ones in a row take it away.

The model here reads the control channel only in frame lock.

From Training to Data

Each port must know that both receivers are content. The receiver ready bit says so.

From Training Frames to DataThe training state diagram of one port. Each port runs its own copy.
  • Control / FSM
  • Control
From training frames to dataThe training state diagram of one port. Each port runs its own copy. control SEND_TRAINING send frames, both readyflags 0 control TRAIN_LOCAL my receiver tunes thepartner control TRAIN_REMOTE I send receiver ready control LINK_READY wait_timer: 100 to 300frames control SEND_DATA signal_detect is true control TRAINING_FAILURE max_wait_timer ran out frame_lockrx_trainedremote_rx_readywait_timer donelock lostlock lost or nottrained500 ms
  1. control SEND_TRAININGsend frames, both ready flags 0
    • frame_lock → TRAIN_LOCAL
    • 500 ms → TRAINING_FAILURE
  2. control TRAIN_LOCALmy receiver tunes the partner
    • rx_trained → TRAIN_REMOTE
    • lock lost → SEND_TRAINING
  3. control TRAIN_REMOTEI send receiver ready
    • remote_rx_ready → LINK_READY
    • lock lost or not trained → SEND_TRAINING
  4. control LINK_READYwait_timer: 100 to 300 frames
    • wait_timer done → SEND_DATA
  5. control SEND_DATAsignal_detect is true
  6. control TRAINING_FAILUREmax_wait_timer ran out
  1. Send

    The port sends training frames and waits for frame lock on the frames it gets.

  2. Tune

    Its receiver asks the partner for tap changes until it is content.

  3. Say ready

    The port sets receiver ready in its status field and waits for the partner to do the same.

  4. Linger

    Both are ready. The port sends 100 to 300 more frames, so the partner surely sees its ready bit.

  5. Data

    The port switches from training frames to data.

  6. Too slow

    If 500 ms pass before LINK_READY, training has failed. The same holds in TRAIN_LOCAL and TRAIN_REMOTE.

Read the diagram as text
  • SEND_TRAINING: send frames, both ready flags 0
  • TRAIN_LOCAL: my receiver tunes the partner
  • TRAIN_REMOTE: I send receiver ready
  • LINK_READY: wait_timer: 100 to 300 frames
  • SEND_DATA: signal_detect is true
  • TRAINING_FAILURE: max_wait_timer ran out
  • SEND_TRAINING → TRAIN_LOCAL: frame_lock
  • TRAIN_LOCAL → TRAIN_REMOTE: rx_trained
  • TRAIN_REMOTE → LINK_READY: remote_rx_ready
  • LINK_READY → SEND_DATA: wait_timer done
  • TRAIN_LOCAL → SEND_TRAINING: lock lost
  • TRAIN_REMOTE → SEND_TRAINING: lock lost or not trained
  • SEND_TRAINING → TRAINING_FAILURE: 500 ms

Our own drawing of IEEE Std 802.3-2022 Figure 72-5. INITIALIZE and the exit for training switched off by management are left out.

A port believes the partner only after three frames in a row with receiver ready (72.6.10.3.1).

Then it lingers: wait_timer is 100 to 300 frames, 42.5 to 127.5 µs.

Without that, a port could stop sending frames before its partner has counted to three.

The whole of it must fit in max_wait_timer: 500 ms, about 1,176,000 frames (72.6.10.3.2).

FramePortEnters
2Port ATRAIN_LOCAL
2Port BTRAIN_LOCAL
8Port BTRAIN_REMOTE
12Port ALINK_READY
15Port BLINK_READY
112Port ASEND_DATA
115Port BSEND_DATA

Bench run: two private models back to back, with bench receivers. A asks B for five changes, B asks A for three. The wait timer is 100 frames here.

Port A enters LINK_READY straight from TRAIN_LOCAL. Its partner was ready already, and transitions take no time.

Now give port B a fault: its taps move, but its status never leaves not_updated.

FramePortEnters
2Port ATRAIN_LOCAL
2Port BTRAIN_LOCAL
8Port BTRAIN_REMOTE
5000Port ATRAINING_FAILURE
5000Port BTRAINING_FAILURE

The same run with the twin status_never_updates as port B. The time limit is a bench value: 5,000 frames, not 500 ms.

Port A asks for its preset for ever. Neither port reaches LINK_READY.

The PAM4 Generation

The PAM4 lanes of P11.35 keep the frame idea and the handshake. The frame grew, and the fields and the state diagram changed (136.8.11).

10GBASE-KR (Clause 72)PAM4 lanes (136.8.11)
Frame4,384 UI16,672 UI
Marker16 UI high, 16 UI low16 symbols of 3, then 16 of 0
Control channeltwo fields of 16 DME cellsthe same size, between levels 0 and 3
Pattern4,094 bits of PRBS11 and 2 zeros16,382 symbols from PRBS13 and 2 zeros
Tapsc(−1), c(0), c(+1), all in one fieldc(−2) to c(1), one at a time, picked by a select field
Starting pointspreset and initializethree presets: the initial condition request
Requestshold, increment, decrementalso "no equalization" for one tap
Statusnot_updated, updated, minimum, maximumalso "not supported" and "equalization limit"; the select is echoed
New in the fieldsmodulation and precoding request, receiver frame lock, a parity bit
State diagramFigure 72-5Figure 136-7: both ends must report frame lock, and the partner must have left PAM2
Lost frame lockback to SEND_TRAININGno way back to the first state
max_wait_timer500 ms, from the reset3 s, from TRAIN_LOCAL; then a hold-off of 80 ms before the failure
wait_timer100 to 300 frames25 µs to 125 µs: about 40 to 200 frames

IEEE Std 802.3-2022 72.6.10 and 136.8.11 (Figures 136-3 and 136-7, Tables 136-9 and 136-10). The frame sizes are bench arithmetic.

Training starts in PAM2: only levels 0 and 3.

A receiver then asks for PAM4, or for PAM4 with precoding (136.8.11.2.2).

That request is how the precoder of P11.35 gets switched on.

The mode a port sends when it enters LINK_READY is the mode its data will use (136.8.11.7.5).

Try It

eth_kr_tx is a bench model of the sender. A level is 0 or 1.

The marker is 16 ones and 16 zeros. It ends on level 0.

eth_kr_fields packs the fields. Here the update field asks c(+1) down and c(−1) up.

cells turns 16 bits into 16 cells, with two levels printed for each cell.

Cell 15 is a 0: the levels are 11. Cell 5 is a 1: the level changes in the middle.

A field with two 1 bits has 18 transitions: 16 at the cell starts and 2 in the middle.

Reading a frame is not in the readable library. It is part of the practice problem.

Change the status field to receiver ready alone. Predict its number of transitions.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: frame marker, 32 UI: 11111111111111110000000000000000 coefficient update field 0021 its 16 cells, 32 halves: 11001100110011001100101100110010 18 transitions; the line ends at level 0 status report field 8013 its 16 cells, 32 halves: 10110011001100110011001011001010 20 transitions; the line ends at level 0 training pattern: 2048 ones in 4094 bits, then two zeros one frame: 4384 UI, 548 octets
Read 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_code.sv
`timescale 1ns/1ns
// hs_code.sv: line codes, CRCs and scramblers (read-only).

// ---------------------------------------------------------------------------------------------
// hs_8b10b: 8b/10b encoder and decoder with running disparity and the 12 K codes.
// code[9:0] = {a,b,c,d,e,i,f,g,h,j}; bit a (code[9]) goes on the wire first. rd: 0 = RD-, 1 = RD+.
//   encode(d, k, rd_in) -> {rd_out, code[9:0]}            (11 bits)
//   decode(code, rd_in) -> {rd_out, disp_err, code_err, k, d[7:0]}   (12 bits)
//   enc(d, k) / dec(code): the same, with the running disparity kept in rd_tx / rd_rx
// A K request for a byte that is not one of the 12 K codes is encoded as data and counted in bad_k.
// Decoder: code_err = the code is in neither column of the table; disp_err = it is a valid code
// only in the other column. rd_out follows the sub-block rule on the received bits.
// Faults: no_rd (always the RD- column), a7_never (never the alternate D.x.A7),
//         keep_rd_on_unbalanced (the 4b sub-block is chosen with the disparity from before the 6b one),
//         no_balanced_flip (D.07 and D.x.3 keep their RD- form at RD+), dec_no_disp_check.
module hs_8b10b;
  bit no_rd = 0, a7_never = 0, keep_rd_on_unbalanced = 0, no_balanced_flip = 0, dec_no_disp_check = 0;
  bit trace = 0;
  bit rd_tx = 0, rd_rx = 0;
  int bad_k = 0, symbols = 0, code_errs = 0, disp_errs = 0;
  bit last_k = 0, last_code_err = 0, last_disp_err = 0;
  bit valid_m [0:1023]; bit valid_p [0:1023]; bit [8:0] kd [0:1023]; bit built = 0;
  function automatic [5:0] t6(input [4:0] x);   // 5b/6b, RD- column, abcdei
    case (x)
      5'd0: return 6'b100111;  5'd1: return 6'b011101;  5'd2: return 6'b101101;  5'd3: return 6'b110001;
      5'd4: return 6'b110101;  5'd5: return 6'b101001;  5'd6: return 6'b011001;  5'd7: return 6'b111000;
      5'd8: return 6'b111001;  5'd9: return 6'b100101;  5'd10: return 6'b010101; 5'd11: return 6'b110100;
      5'd12: return 6'b001101; 5'd13: return 6'b101100; 5'd14: return 6'b011100; 5'd15: return 6'b010111;
      5'd16: return 6'b011011; 5'd17: return 6'b100011; 5'd18: return 6'b010011; 5'd19: return 6'b110010;
      5'd20: return 6'b001011; 5'd21: return 6'b101010; 5'd22: return 6'b011010; 5'd23: return 6'b111010;
      5'd24: return 6'b110011; 5'd25: return 6'b100110; 5'd26: return 6'b010110; 5'd27: return 6'b110110;
      5'd28: return 6'b001110; 5'd29: return 6'b101110; 5'd30: return 6'b011110; default: return 6'b101011;
    endcase
  endfunction
  function automatic [3:0] t4d(input [2:0] y);  // 3b/4b data, RD- column, fghj (y = 7 is P7)
    case (y)
      3'd0: return 4'b1011; 3'd1: return 4'b1001; 3'd2: return 4'b0101; 3'd3: return 4'b1100;
      3'd4: return 4'b1101; 3'd5: return 4'b1010; 3'd6: return 4'b0110; default: return 4'b1110;
    endcase
  endfunction
  function automatic [3:0] t4k(input [2:0] y);  // 3b/4b for K codes, RD- form before the flip
    case (y)
      3'd0: return 4'b1011; 3'd1: return 4'b0110; 3'd2: return 4'b1010; 3'd3: return 4'b1100;
      3'd4: return 4'b1101; 3'd5: return 4'b0101; 3'd6: return 4'b1001; default: return 4'b0111;
    endcase
  endfunction
  function automatic bit k_ok(input [7:0] d);
    return d[4:0] == 5'd28 || d == 8'hf7 || d == 8'hfb || d == 8'hfd || d == 8'hfe;
  endfunction
  function automatic int n6(input [5:0] v); return v[0] + v[1] + v[2] + v[3] + v[4] + v[5]; endfunction
  function automatic int n4(input [3:0] v); return v[0] + v[1] + v[2] + v[3]; endfunction
  // running disparity at the end of a sub-block (more ones: +; more zeros: -; 000111 and 0011: +; 111000 and 1100: -)
  function automatic bit rd6(input [5:0] v, input bit rd);
    return (n6(v) > 3) ? 1'b1 : (n6(v) < 3) ? 1'b0 : (v == 6'b000111) ? 1'b1 : (v == 6'b111000) ? 1'b0 : rd;
  endfunction
  function automatic bit rd4(input [3:0] v, input bit rd);
    return (n4(v) > 2) ? 1'b1 : (n4(v) < 2) ? 1'b0 : (v == 4'b0011) ? 1'b1 : (v == 4'b1100) ? 1'b0 : rd;
  endfunction
  // faults: [0] no_rd [1] a7_never [2] keep_rd_on_unbalanced [3] no_balanced_flip
  function automatic [10:0] core(input [7:0] d, input bit k, input bit rd_in, input [3:0] f);
    reg [5:0] six; reg [3:0] four; reg rd0, r6, rd1, a7, kk; reg [4:0] x; reg [2:0] y; int o6, o4;
    x = d[4:0]; y = d[7:5]; kk = k && k_ok(d); rd0 = f[0] ? 1'b0 : rd_in;
    six = (kk && x == 5'd28) ? 6'b001111 : t6(x); o6 = n6(six);
    if (rd0 && (o6 != 3 || (six == 6'b111000 && !f[3]))) begin six = ~six; o6 = 6 - o6; end
    r6 = (o6 > 3) ? 1'b1 : (o6 < 3) ? 1'b0 : (six == 6'b000111) ? 1'b1 : (six == 6'b111000) ? 1'b0 : rd0;
    rd1 = f[2] ? rd0 : r6;
    if (kk) begin
      four = t4k(y); if (rd1) four = ~four;
    end else begin
      a7 = (y == 3'd7) && !f[1] && ((!rd1 && (x == 5'd17 || x == 5'd18 || x == 5'd20)) || (rd1 && (x == 5'd11 || x == 5'd13 || x == 5'd14)));
      four = a7 ? 4'b0111 : t4d(y);
      if (rd1 && (n4(four) != 2 || (four == 4'b1100 && !f[3]))) four = ~four;
    end
    o4 = n4(four);
    return {(o4 > 2) ? 1'b1 : (o4 < 2) ? 1'b0 : (four == 4'b0011) ? 1'b1 : (four == 4'b1100) ? 1'b0 : r6, six, four};
  endfunction
  function automatic [10:0] encode(input [7:0] d, input bit k, input bit rd_in);
    if (k && !k_ok(d)) bad_k++;
    return core(d, k, rd_in, {no_balanced_flip, keep_rd_on_unbalanced, a7_never, no_rd});
  endfunction
  function automatic void build();
    reg [10:0] c;
    for (int i = 0; i < 1024; i++) begin valid_m[i] = 0; valid_p[i] = 0; kd[i] = 9'd0; end
    for (int i = 0; i < 268; i++) begin
      reg [7:0] d; reg k;
      if (i < 256) begin d = i[7:0]; k = 0; end
      else begin k = 1; d = (i < 264) ? {3'(i - 256), 5'd28} : (i == 264) ? 8'hf7 : (i == 265) ? 8'hfb : (i == 266) ? 8'hfd : 8'hfe; end
      c = core(d, k, 1'b0, 4'd0); valid_m[c[9:0]] = 1; kd[c[9:0]] = {k, d};
      c = core(d, k, 1'b1, 4'd0); valid_p[c[9:0]] = 1; kd[c[9:0]] = {k, d};
    end
    built = 1;
  endfunction
  function automatic [11:0] decode(input [9:0] code, input bit rd_in);
    reg here, there, ce, de, r;
    if (!built) build();
    here = rd_in ? valid_p[code] : valid_m[code];
    there = rd_in ? valid_m[code] : valid_p[code];
    ce = !(here || there); de = !ce && !here && !dec_no_disp_check;
    r = rd4(code[3:0], rd6(code[9:4], rd_in));
    return {r, de, ce, ce ? 9'd0 : kd[code]};
  endfunction
  function automatic [9:0] enc(input [7:0] d, input bit k);
    reg [10:0] r; r = encode(d, k, rd_tx); rd_tx = r[10];
    if (trace) $display("s%0d TX %s%0d.%0d code=%b rd=%s", symbols, (k && k_ok(d)) ? "K" : "D", d[4:0], d[7:5], r[9:0], r[10] ? "+" : "-");
    symbols++;
    return r[9:0];
  endfunction
  function automatic [8:0] dec(input [9:0] code);
    reg [11:0] r; r = decode(code, rd_rx); rd_rx = r[11];
    last_disp_err = r[10]; last_code_err = r[9]; last_k = r[8];
    if (r[9]) code_errs++; if (r[10]) disp_errs++;
    if (trace && (r[9] || r[10])) $display("RX %b %s", code, r[9] ? "code error" : "disparity error");
    return r[8:0];
  endfunction
  function automatic bit comma7(input [6:0] w); return w == 7'b0011111 || w == 7'b1100000; endfunction
endmodule

// ---------------------------------------------------------------------------------------------
// hs_crc: a CRC of 1 to 32 bits with any polynomial, seed, bit order and final inversion.
// The register shifts left; the polynomial omits the x^width term. The field is sent register bit
// width-1 first (USB 2.0, USB 3.2 and Ethernet all send it this way).
//   use_crc32(), use_crc16_usb2(), use_crc5_usb2(), use_crc16_usb3(): parameter sets
//   reset(), crc_bit(b), crc_byte(v), crc_bits(v, n), field(), field_bit(i), check_value(), crc_residue_ok()
// Faults: msb_first (bytes enter MSB first), no_invert (the field is not complemented), seed_zero.
module hs_crc;
  int width = 32;
  bit [31:0] poly = 32'h04c11db7, seed = 32'hffffffff, residue = 32'hc704dd7b;
  bit lsb_first = 1, invert = 1;
  bit msb_first = 0, no_invert = 0, seed_zero = 0;
  bit [31:0] r = 32'hffffffff;
  function automatic [31:0] mask(); return (width >= 32) ? 32'hffffffff : ((32'd1 << width) - 32'd1); endfunction
  function automatic void reset(); r = seed_zero ? 32'd0 : (seed & mask()); endfunction
  function automatic void set(input int w, input [31:0] p, input [31:0] s, input [31:0] res, input bit lsb, input bit inv);
    width = w; poly = p; seed = s; residue = res; lsb_first = lsb; invert = inv; reset();
  endfunction
  function automatic void use_crc32();      set(32, 32'h04c11db7, 32'hffffffff, 32'hc704dd7b, 1, 1); endfunction
  function automatic void use_crc16_usb2(); set(16, 32'h8005, 32'hffff, 32'h800d, 1, 1); endfunction
  function automatic void use_crc5_usb2();  set(5, 32'h05, 32'h1f, 32'h0c, 1, 1); endfunction
  function automatic void use_crc16_usb3(); set(16, 32'h100b, 32'hffff, 32'hf6aa, 1, 1); endfunction
  function automatic void crc_bit(input bit b);
    reg fb; fb = b ^ r[width - 1];
    r = ((r << 1) ^ (fb ? poly : 32'd0)) & mask();
  endfunction
  function automatic void crc_byte(input [7:0] v);
    for (int i = 0; i < 8; i++) crc_bit(v[(lsb_first ^ msb_first) ? i : 7 - i]);
  endfunction
  function automatic void crc_bits(input [31:0] v, input int n);   // n bits of v, bit 0 first
    for (int i = 0; i < n; i++) crc_bit(v[i]);
  endfunction
  function automatic [31:0] field(); return (invert && !no_invert) ? (~r & mask()) : r; endfunction
  function automatic bit field_bit(input int i); reg [31:0] f; f = field(); return f[width - 1 - i]; endfunction
  // the usual published "check" number: the field with its first-sent bit read as bit 0
  function automatic [31:0] check_value();
    reg [31:0] f, o; f = field(); o = 32'd0;
    for (int i = 0; i < width; i++) o[i] = f[width - 1 - i];
    return lsb_first ? o : f;
  endfunction
  function automatic bit crc_residue_ok(); return r == (residue & mask()); endfunction
endmodule

// ---------------------------------------------------------------------------------------------
// hs_scr: additive (frame-synchronous) and multiplicative (self-synchronising) scramblers.
// poly holds the coefficients: bit k is x^k; the +1 term is always used (taps() sets bit 0); len is the degree.
// Additive: a Galois LFSR. The key bit is s[len-1]; each step shifts left and adds the low terms of
//   the polynomial when the key bit is 1. The data never enters the register.
// Multiplicative: the line bit is the data bit XOR the register bits at the polynomial's terms;
//   the scrambler shifts its own output in, the descrambler shifts the received line bit in.
//   scr_add(len, poly, seed), scr_mul(len, poly), use_usb3_gen1(), use_x58(), use_x23_usb3() (see its note)
//   scr_bit(b), dscr_bit(b), scr_byte(v), dscr_byte(v) (bit 0 first), scr_reset(), scr_hold() (a skip
//   symbol: no step), scr_unscrambled() (a symbol sent in the clear: 8 steps, data untouched)
// Faults: advance_on_skip (scr_hold steps the LFSR 8 times), no_reset (scr_reset does nothing),
//         wrong_tap (the lowest term x^k becomes x^(k+1)), seed_zero (scr_reset loads 0).
module hs_scr;
  bit mult = 0; int len = 16;
  bit [63:0] poly = 64'h10039, seed = 64'hffff;
  bit advance_on_skip = 0, no_reset = 0, wrong_tap = 0, seed_zero = 0;
  bit [63:0] s = 64'hffff;
  int steps = 0;
  function automatic [63:0] lmask(); return (len >= 64) ? 64'hffffffffffffffff : ((64'd1 << len) - 64'd1); endfunction
  function automatic [63:0] taps();
    reg [63:0] p; int k; p = poly | 64'd1; k = 1;
    if (wrong_tap) begin
      while (k < len && !p[k]) k++;
      if (k < len) begin p[k] = 1'b0; p[k + 1] = 1'b1; end
    end
    return p;
  endfunction
  function automatic void load(); s = (seed_zero ? 64'd0 : seed) & lmask(); endfunction
  function automatic void scr_add(input int n, input [63:0] p, input [63:0] sd); mult = 0; len = n; poly = p; seed = sd; s = sd & lmask(); endfunction
  function automatic void scr_mul(input int n, input [63:0] p); mult = 1; len = n; poly = p; seed = 64'd0; s = 64'd0; endfunction
  function automatic void use_usb3_gen1(); scr_add(16, 64'h10039, 64'hffff); endfunction   // x^16 + x^5 + x^4 + x^3 + 1, seed FFFFh
  function automatic void use_x58(); scr_mul(58, (64'd1 << 58) | (64'd1 << 39) | 64'd1); endfunction   // x^58 + x^39 + 1
  // USB 3.2 Gen 2 (§6.3.2.3) polynomial x^23 + x^21 + x^16 + x^8 + x^5 + x^2 + 1 with seed 1DBFBCh. Only the
  // polynomial and seed are the specification's: the register form here is this library's Galois form, and
  // the reset and bypass rules of §6.3.2.3 are not modelled, so do not quote its key stream as USB's.
  function automatic void use_x23_usb3(); scr_add(23, (64'd1 << 23) | (64'd1 << 21) | (64'd1 << 16) | (64'd1 << 8) | (64'd1 << 5) | (64'd1 << 2) | 64'd1, 64'h1dbfbc); endfunction
  function automatic void scr_reset(); if (!no_reset) load(); endfunction
  function automatic bit key(); return s[len - 1]; endfunction
  function automatic void step();
    reg kb; kb = s[len - 1];
    s = ((s << 1) & lmask()) ^ (kb ? (taps() & lmask()) : 64'd0);
    steps++;
  endfunction
  // the XOR of the register bits at the polynomial's terms x^1..x^len (bit k-1 of the register for x^k)
  function automatic bit fbx(input [63:0] st); return ^(st & (taps() >> 1) & lmask()); endfunction
  function automatic bit scr_bit(input bit b);
    reg o;
    if (!mult) begin o = b ^ s[len - 1]; step(); end
    else begin o = b ^ fbx(s); s = ((s << 1) | {63'd0, o}) & lmask(); steps++; end
    return o;
  endfunction
  function automatic bit dscr_bit(input bit b);
    reg o;
    if (!mult) begin o = b ^ s[len - 1]; step(); end
    else begin o = b ^ fbx(s); s = ((s << 1) | {63'd0, b}) & lmask(); steps++; end
    return o;
  endfunction
  function automatic [7:0] scr_byte(input [7:0] v);
    reg [7:0] o; for (int i = 0; i < 8; i++) o[i] = scr_bit(v[i]); return o;
  endfunction
  function automatic [7:0] dscr_byte(input [7:0] v);
    reg [7:0] o; for (int i = 0; i < 8; i++) o[i] = dscr_bit(v[i]); return o;
  endfunction
  // a skip symbol passes unscrambled and the LFSR holds
  function automatic void scr_hold(); if (advance_on_skip && !mult) for (int i = 0; i < 8; i++) step(); endfunction
  // another symbol that is sent unscrambled (a K code other than COM and SKP): the LFSR still steps 8 times
  function automatic void scr_unscrambled(); if (!mult) for (int i = 0; i < 8; i++) step(); endfunction
endmodule
Read included file: eth_kr.sv
`timescale 1ns/1ns
// eth_kr.sv: the training frame of 10GBASE-KR, sender side (read-only). A bench model: the line is a level, 0 or 1.

// eth_kr_fields: the two fields of the control channel, from their parts.
//   update(preset, init, p1, z0, m1)   the coefficient update field (Table 72-4).
//                                      p1, z0, m1: the request for c(+1), c(0), c(-1). 0 hold, 1 increment, 2 decrement
//   status(ready, p1, z0, m1)          the status report field (Table 72-5).
//                                      0 not_updated, 1 updated, 2 minimum, 3 maximum
module eth_kr_fields;
  function automatic [15:0] update(input bit preset, input bit init, input [1:0] p1, input [1:0] z0, input [1:0] m1);
    return {2'b00, preset, init, 6'd0, p1, z0, m1};
  endfunction
  function automatic [15:0] status(input bit ready, input [1:0] p1, input [1:0] z0, input [1:0] m1);
    return {ready, 9'd0, p1, z0, m1};
  endfunction
endmodule

// eth_kr_tx: one training frame, part by part (72.6.10.2). A frame is 548 octets: 4,384 UI.
//   marker()             the frame marker, 32 UI: FFFF0000h, the ones first. Bit 31 is sent first.
//   cells(prev, word)    a 16-bit field as 16 DME cells, cell 15 first. A cell is 8 UI: two halves of 4 UI.
//                        The result has one level for each half. Bit 31 is sent first. prev: the level before.
//   level                the line level after the last call of cells()
//   transitions          the transitions of the last call of cells()
//   pattern(seed)        runs the training pattern: 4,094 bits of PRBS11, then two zeros. Returns the number of ones.
//   prbs()               one bit of PRBS11, x^11 + x^9 + 1 (Figure 72-3)
module eth_kr_tx;
  bit level = 0;
  int transitions = 0;
  reg [10:0] s = 11'h7ff;                   // S0 is s[0], S10 is s[10]
  function automatic [31:0] marker();
    level = 0;
    return 32'hffff0000;
  endfunction
  function automatic [31:0] cells(input bit prev, input [15:0] word);
    reg [31:0] out;
    level = prev; transitions = 0;
    for (int k = 15; k >= 0; k--) begin
      level = !level; transitions++;                        // every cell starts with a transition
      out[2 * k + 1] = level;
      if (word[k]) begin level = !level; transitions++; end // a transition in the middle of the cell is a 1
      out[2 * k] = level;
    end
    return out;
  endfunction
  function automatic bit prbs();
    bit b;
    b = s[8] ^ s[10];
    s = {s[9:0], b};
    return b;
  endfunction
  function automatic int pattern(input [10:0] seed);
    int ones;
    s = seed; ones = 0;
    for (int i = 0; i < 4094; i++) if (prbs()) ones++;
    return ones;                                            // the two zeros that follow add nothing
  endfunction
endmodule

Check Yourself

Predict the outputThe bench sends the field 8001h as 16 DME cells. How many transitions does it print?
`timescale 1ns/1ns
module tb;
  eth_kr_tx tx(); reg [31:0] c;
  initial begin
    c = tx.cells(1'b0, 16'h8001);
    $display("%0d", tx.transitions);
    $finish;
  end
endmodule
Read 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_code.sv
`timescale 1ns/1ns
// hs_code.sv: line codes, CRCs and scramblers (read-only).

// ---------------------------------------------------------------------------------------------
// hs_8b10b: 8b/10b encoder and decoder with running disparity and the 12 K codes.
// code[9:0] = {a,b,c,d,e,i,f,g,h,j}; bit a (code[9]) goes on the wire first. rd: 0 = RD-, 1 = RD+.
//   encode(d, k, rd_in) -> {rd_out, code[9:0]}            (11 bits)
//   decode(code, rd_in) -> {rd_out, disp_err, code_err, k, d[7:0]}   (12 bits)
//   enc(d, k) / dec(code): the same, with the running disparity kept in rd_tx / rd_rx
// A K request for a byte that is not one of the 12 K codes is encoded as data and counted in bad_k.
// Decoder: code_err = the code is in neither column of the table; disp_err = it is a valid code
// only in the other column. rd_out follows the sub-block rule on the received bits.
// Faults: no_rd (always the RD- column), a7_never (never the alternate D.x.A7),
//         keep_rd_on_unbalanced (the 4b sub-block is chosen with the disparity from before the 6b one),
//         no_balanced_flip (D.07 and D.x.3 keep their RD- form at RD+), dec_no_disp_check.
module hs_8b10b;
  bit no_rd = 0, a7_never = 0, keep_rd_on_unbalanced = 0, no_balanced_flip = 0, dec_no_disp_check = 0;
  bit trace = 0;
  bit rd_tx = 0, rd_rx = 0;
  int bad_k = 0, symbols = 0, code_errs = 0, disp_errs = 0;
  bit last_k = 0, last_code_err = 0, last_disp_err = 0;
  bit valid_m [0:1023]; bit valid_p [0:1023]; bit [8:0] kd [0:1023]; bit built = 0;
  function automatic [5:0] t6(input [4:0] x);   // 5b/6b, RD- column, abcdei
    case (x)
      5'd0: return 6'b100111;  5'd1: return 6'b011101;  5'd2: return 6'b101101;  5'd3: return 6'b110001;
      5'd4: return 6'b110101;  5'd5: return 6'b101001;  5'd6: return 6'b011001;  5'd7: return 6'b111000;
      5'd8: return 6'b111001;  5'd9: return 6'b100101;  5'd10: return 6'b010101; 5'd11: return 6'b110100;
      5'd12: return 6'b001101; 5'd13: return 6'b101100; 5'd14: return 6'b011100; 5'd15: return 6'b010111;
      5'd16: return 6'b011011; 5'd17: return 6'b100011; 5'd18: return 6'b010011; 5'd19: return 6'b110010;
      5'd20: return 6'b001011; 5'd21: return 6'b101010; 5'd22: return 6'b011010; 5'd23: return 6'b111010;
      5'd24: return 6'b110011; 5'd25: return 6'b100110; 5'd26: return 6'b010110; 5'd27: return 6'b110110;
      5'd28: return 6'b001110; 5'd29: return 6'b101110; 5'd30: return 6'b011110; default: return 6'b101011;
    endcase
  endfunction
  function automatic [3:0] t4d(input [2:0] y);  // 3b/4b data, RD- column, fghj (y = 7 is P7)
    case (y)
      3'd0: return 4'b1011; 3'd1: return 4'b1001; 3'd2: return 4'b0101; 3'd3: return 4'b1100;
      3'd4: return 4'b1101; 3'd5: return 4'b1010; 3'd6: return 4'b0110; default: return 4'b1110;
    endcase
  endfunction
  function automatic [3:0] t4k(input [2:0] y);  // 3b/4b for K codes, RD- form before the flip
    case (y)
      3'd0: return 4'b1011; 3'd1: return 4'b0110; 3'd2: return 4'b1010; 3'd3: return 4'b1100;
      3'd4: return 4'b1101; 3'd5: return 4'b0101; 3'd6: return 4'b1001; default: return 4'b0111;
    endcase
  endfunction
  function automatic bit k_ok(input [7:0] d);
    return d[4:0] == 5'd28 || d == 8'hf7 || d == 8'hfb || d == 8'hfd || d == 8'hfe;
  endfunction
  function automatic int n6(input [5:0] v); return v[0] + v[1] + v[2] + v[3] + v[4] + v[5]; endfunction
  function automatic int n4(input [3:0] v); return v[0] + v[1] + v[2] + v[3]; endfunction
  // running disparity at the end of a sub-block (more ones: +; more zeros: -; 000111 and 0011: +; 111000 and 1100: -)
  function automatic bit rd6(input [5:0] v, input bit rd);
    return (n6(v) > 3) ? 1'b1 : (n6(v) < 3) ? 1'b0 : (v == 6'b000111) ? 1'b1 : (v == 6'b111000) ? 1'b0 : rd;
  endfunction
  function automatic bit rd4(input [3:0] v, input bit rd);
    return (n4(v) > 2) ? 1'b1 : (n4(v) < 2) ? 1'b0 : (v == 4'b0011) ? 1'b1 : (v == 4'b1100) ? 1'b0 : rd;
  endfunction
  // faults: [0] no_rd [1] a7_never [2] keep_rd_on_unbalanced [3] no_balanced_flip
  function automatic [10:0] core(input [7:0] d, input bit k, input bit rd_in, input [3:0] f);
    reg [5:0] six; reg [3:0] four; reg rd0, r6, rd1, a7, kk; reg [4:0] x; reg [2:0] y; int o6, o4;
    x = d[4:0]; y = d[7:5]; kk = k && k_ok(d); rd0 = f[0] ? 1'b0 : rd_in;
    six = (kk && x == 5'd28) ? 6'b001111 : t6(x); o6 = n6(six);
    if (rd0 && (o6 != 3 || (six == 6'b111000 && !f[3]))) begin six = ~six; o6 = 6 - o6; end
    r6 = (o6 > 3) ? 1'b1 : (o6 < 3) ? 1'b0 : (six == 6'b000111) ? 1'b1 : (six == 6'b111000) ? 1'b0 : rd0;
    rd1 = f[2] ? rd0 : r6;
    if (kk) begin
      four = t4k(y); if (rd1) four = ~four;
    end else begin
      a7 = (y == 3'd7) && !f[1] && ((!rd1 && (x == 5'd17 || x == 5'd18 || x == 5'd20)) || (rd1 && (x == 5'd11 || x == 5'd13 || x == 5'd14)));
      four = a7 ? 4'b0111 : t4d(y);
      if (rd1 && (n4(four) != 2 || (four == 4'b1100 && !f[3]))) four = ~four;
    end
    o4 = n4(four);
    return {(o4 > 2) ? 1'b1 : (o4 < 2) ? 1'b0 : (four == 4'b0011) ? 1'b1 : (four == 4'b1100) ? 1'b0 : r6, six, four};
  endfunction
  function automatic [10:0] encode(input [7:0] d, input bit k, input bit rd_in);
    if (k && !k_ok(d)) bad_k++;
    return core(d, k, rd_in, {no_balanced_flip, keep_rd_on_unbalanced, a7_never, no_rd});
  endfunction
  function automatic void build();
    reg [10:0] c;
    for (int i = 0; i < 1024; i++) begin valid_m[i] = 0; valid_p[i] = 0; kd[i] = 9'd0; end
    for (int i = 0; i < 268; i++) begin
      reg [7:0] d; reg k;
      if (i < 256) begin d = i[7:0]; k = 0; end
      else begin k = 1; d = (i < 264) ? {3'(i - 256), 5'd28} : (i == 264) ? 8'hf7 : (i == 265) ? 8'hfb : (i == 266) ? 8'hfd : 8'hfe; end
      c = core(d, k, 1'b0, 4'd0); valid_m[c[9:0]] = 1; kd[c[9:0]] = {k, d};
      c = core(d, k, 1'b1, 4'd0); valid_p[c[9:0]] = 1; kd[c[9:0]] = {k, d};
    end
    built = 1;
  endfunction
  function automatic [11:0] decode(input [9:0] code, input bit rd_in);
    reg here, there, ce, de, r;
    if (!built) build();
    here = rd_in ? valid_p[code] : valid_m[code];
    there = rd_in ? valid_m[code] : valid_p[code];
    ce = !(here || there); de = !ce && !here && !dec_no_disp_check;
    r = rd4(code[3:0], rd6(code[9:4], rd_in));
    return {r, de, ce, ce ? 9'd0 : kd[code]};
  endfunction
  function automatic [9:0] enc(input [7:0] d, input bit k);
    reg [10:0] r; r = encode(d, k, rd_tx); rd_tx = r[10];
    if (trace) $display("s%0d TX %s%0d.%0d code=%b rd=%s", symbols, (k && k_ok(d)) ? "K" : "D", d[4:0], d[7:5], r[9:0], r[10] ? "+" : "-");
    symbols++;
    return r[9:0];
  endfunction
  function automatic [8:0] dec(input [9:0] code);
    reg [11:0] r; r = decode(code, rd_rx); rd_rx = r[11];
    last_disp_err = r[10]; last_code_err = r[9]; last_k = r[8];
    if (r[9]) code_errs++; if (r[10]) disp_errs++;
    if (trace && (r[9] || r[10])) $display("RX %b %s", code, r[9] ? "code error" : "disparity error");
    return r[8:0];
  endfunction
  function automatic bit comma7(input [6:0] w); return w == 7'b0011111 || w == 7'b1100000; endfunction
endmodule

// ---------------------------------------------------------------------------------------------
// hs_crc: a CRC of 1 to 32 bits with any polynomial, seed, bit order and final inversion.
// The register shifts left; the polynomial omits the x^width term. The field is sent register bit
// width-1 first (USB 2.0, USB 3.2 and Ethernet all send it this way).
//   use_crc32(), use_crc16_usb2(), use_crc5_usb2(), use_crc16_usb3(): parameter sets
//   reset(), crc_bit(b), crc_byte(v), crc_bits(v, n), field(), field_bit(i), check_value(), crc_residue_ok()
// Faults: msb_first (bytes enter MSB first), no_invert (the field is not complemented), seed_zero.
module hs_crc;
  int width = 32;
  bit [31:0] poly = 32'h04c11db7, seed = 32'hffffffff, residue = 32'hc704dd7b;
  bit lsb_first = 1, invert = 1;
  bit msb_first = 0, no_invert = 0, seed_zero = 0;
  bit [31:0] r = 32'hffffffff;
  function automatic [31:0] mask(); return (width >= 32) ? 32'hffffffff : ((32'd1 << width) - 32'd1); endfunction
  function automatic void reset(); r = seed_zero ? 32'd0 : (seed & mask()); endfunction
  function automatic void set(input int w, input [31:0] p, input [31:0] s, input [31:0] res, input bit lsb, input bit inv);
    width = w; poly = p; seed = s; residue = res; lsb_first = lsb; invert = inv; reset();
  endfunction
  function automatic void use_crc32();      set(32, 32'h04c11db7, 32'hffffffff, 32'hc704dd7b, 1, 1); endfunction
  function automatic void use_crc16_usb2(); set(16, 32'h8005, 32'hffff, 32'h800d, 1, 1); endfunction
  function automatic void use_crc5_usb2();  set(5, 32'h05, 32'h1f, 32'h0c, 1, 1); endfunction
  function automatic void use_crc16_usb3(); set(16, 32'h100b, 32'hffff, 32'hf6aa, 1, 1); endfunction
  function automatic void crc_bit(input bit b);
    reg fb; fb = b ^ r[width - 1];
    r = ((r << 1) ^ (fb ? poly : 32'd0)) & mask();
  endfunction
  function automatic void crc_byte(input [7:0] v);
    for (int i = 0; i < 8; i++) crc_bit(v[(lsb_first ^ msb_first) ? i : 7 - i]);
  endfunction
  function automatic void crc_bits(input [31:0] v, input int n);   // n bits of v, bit 0 first
    for (int i = 0; i < n; i++) crc_bit(v[i]);
  endfunction
  function automatic [31:0] field(); return (invert && !no_invert) ? (~r & mask()) : r; endfunction
  function automatic bit field_bit(input int i); reg [31:0] f; f = field(); return f[width - 1 - i]; endfunction
  // the usual published "check" number: the field with its first-sent bit read as bit 0
  function automatic [31:0] check_value();
    reg [31:0] f, o; f = field(); o = 32'd0;
    for (int i = 0; i < width; i++) o[i] = f[width - 1 - i];
    return lsb_first ? o : f;
  endfunction
  function automatic bit crc_residue_ok(); return r == (residue & mask()); endfunction
endmodule

// ---------------------------------------------------------------------------------------------
// hs_scr: additive (frame-synchronous) and multiplicative (self-synchronising) scramblers.
// poly holds the coefficients: bit k is x^k; the +1 term is always used (taps() sets bit 0); len is the degree.
// Additive: a Galois LFSR. The key bit is s[len-1]; each step shifts left and adds the low terms of
//   the polynomial when the key bit is 1. The data never enters the register.
// Multiplicative: the line bit is the data bit XOR the register bits at the polynomial's terms;
//   the scrambler shifts its own output in, the descrambler shifts the received line bit in.
//   scr_add(len, poly, seed), scr_mul(len, poly), use_usb3_gen1(), use_x58(), use_x23_usb3() (see its note)
//   scr_bit(b), dscr_bit(b), scr_byte(v), dscr_byte(v) (bit 0 first), scr_reset(), scr_hold() (a skip
//   symbol: no step), scr_unscrambled() (a symbol sent in the clear: 8 steps, data untouched)
// Faults: advance_on_skip (scr_hold steps the LFSR 8 times), no_reset (scr_reset does nothing),
//         wrong_tap (the lowest term x^k becomes x^(k+1)), seed_zero (scr_reset loads 0).
module hs_scr;
  bit mult = 0; int len = 16;
  bit [63:0] poly = 64'h10039, seed = 64'hffff;
  bit advance_on_skip = 0, no_reset = 0, wrong_tap = 0, seed_zero = 0;
  bit [63:0] s = 64'hffff;
  int steps = 0;
  function automatic [63:0] lmask(); return (len >= 64) ? 64'hffffffffffffffff : ((64'd1 << len) - 64'd1); endfunction
  function automatic [63:0] taps();
    reg [63:0] p; int k; p = poly | 64'd1; k = 1;
    if (wrong_tap) begin
      while (k < len && !p[k]) k++;
      if (k < len) begin p[k] = 1'b0; p[k + 1] = 1'b1; end
    end
    return p;
  endfunction
  function automatic void load(); s = (seed_zero ? 64'd0 : seed) & lmask(); endfunction
  function automatic void scr_add(input int n, input [63:0] p, input [63:0] sd); mult = 0; len = n; poly = p; seed = sd; s = sd & lmask(); endfunction
  function automatic void scr_mul(input int n, input [63:0] p); mult = 1; len = n; poly = p; seed = 64'd0; s = 64'd0; endfunction
  function automatic void use_usb3_gen1(); scr_add(16, 64'h10039, 64'hffff); endfunction   // x^16 + x^5 + x^4 + x^3 + 1, seed FFFFh
  function automatic void use_x58(); scr_mul(58, (64'd1 << 58) | (64'd1 << 39) | 64'd1); endfunction   // x^58 + x^39 + 1
  // USB 3.2 Gen 2 (§6.3.2.3) polynomial x^23 + x^21 + x^16 + x^8 + x^5 + x^2 + 1 with seed 1DBFBCh. Only the
  // polynomial and seed are the specification's: the register form here is this library's Galois form, and
  // the reset and bypass rules of §6.3.2.3 are not modelled, so do not quote its key stream as USB's.
  function automatic void use_x23_usb3(); scr_add(23, (64'd1 << 23) | (64'd1 << 21) | (64'd1 << 16) | (64'd1 << 8) | (64'd1 << 5) | (64'd1 << 2) | 64'd1, 64'h1dbfbc); endfunction
  function automatic void scr_reset(); if (!no_reset) load(); endfunction
  function automatic bit key(); return s[len - 1]; endfunction
  function automatic void step();
    reg kb; kb = s[len - 1];
    s = ((s << 1) & lmask()) ^ (kb ? (taps() & lmask()) : 64'd0);
    steps++;
  endfunction
  // the XOR of the register bits at the polynomial's terms x^1..x^len (bit k-1 of the register for x^k)
  function automatic bit fbx(input [63:0] st); return ^(st & (taps() >> 1) & lmask()); endfunction
  function automatic bit scr_bit(input bit b);
    reg o;
    if (!mult) begin o = b ^ s[len - 1]; step(); end
    else begin o = b ^ fbx(s); s = ((s << 1) | {63'd0, o}) & lmask(); steps++; end
    return o;
  endfunction
  function automatic bit dscr_bit(input bit b);
    reg o;
    if (!mult) begin o = b ^ s[len - 1]; step(); end
    else begin o = b ^ fbx(s); s = ((s << 1) | {63'd0, b}) & lmask(); steps++; end
    return o;
  endfunction
  function automatic [7:0] scr_byte(input [7:0] v);
    reg [7:0] o; for (int i = 0; i < 8; i++) o[i] = scr_bit(v[i]); return o;
  endfunction
  function automatic [7:0] dscr_byte(input [7:0] v);
    reg [7:0] o; for (int i = 0; i < 8; i++) o[i] = dscr_bit(v[i]); return o;
  endfunction
  // a skip symbol passes unscrambled and the LFSR holds
  function automatic void scr_hold(); if (advance_on_skip && !mult) for (int i = 0; i < 8; i++) step(); endfunction
  // another symbol that is sent unscrambled (a K code other than COM and SKP): the LFSR still steps 8 times
  function automatic void scr_unscrambled(); if (!mult) for (int i = 0; i < 8; i++) step(); endfunction
endmodule
Read included file: eth_kr.sv
`timescale 1ns/1ns
// eth_kr.sv: the training frame of 10GBASE-KR, sender side (read-only). A bench model: the line is a level, 0 or 1.

// eth_kr_fields: the two fields of the control channel, from their parts.
//   update(preset, init, p1, z0, m1)   the coefficient update field (Table 72-4).
//                                      p1, z0, m1: the request for c(+1), c(0), c(-1). 0 hold, 1 increment, 2 decrement
//   status(ready, p1, z0, m1)          the status report field (Table 72-5).
//                                      0 not_updated, 1 updated, 2 minimum, 3 maximum
module eth_kr_fields;
  function automatic [15:0] update(input bit preset, input bit init, input [1:0] p1, input [1:0] z0, input [1:0] m1);
    return {2'b00, preset, init, 6'd0, p1, z0, m1};
  endfunction
  function automatic [15:0] status(input bit ready, input [1:0] p1, input [1:0] z0, input [1:0] m1);
    return {ready, 9'd0, p1, z0, m1};
  endfunction
endmodule

// eth_kr_tx: one training frame, part by part (72.6.10.2). A frame is 548 octets: 4,384 UI.
//   marker()             the frame marker, 32 UI: FFFF0000h, the ones first. Bit 31 is sent first.
//   cells(prev, word)    a 16-bit field as 16 DME cells, cell 15 first. A cell is 8 UI: two halves of 4 UI.
//                        The result has one level for each half. Bit 31 is sent first. prev: the level before.
//   level                the line level after the last call of cells()
//   transitions          the transitions of the last call of cells()
//   pattern(seed)        runs the training pattern: 4,094 bits of PRBS11, then two zeros. Returns the number of ones.
//   prbs()               one bit of PRBS11, x^11 + x^9 + 1 (Figure 72-3)
module eth_kr_tx;
  bit level = 0;
  int transitions = 0;
  reg [10:0] s = 11'h7ff;                   // S0 is s[0], S10 is s[10]
  function automatic [31:0] marker();
    level = 0;
    return 32'hffff0000;
  endfunction
  function automatic [31:0] cells(input bit prev, input [15:0] word);
    reg [31:0] out;
    level = prev; transitions = 0;
    for (int k = 15; k >= 0; k--) begin
      level = !level; transitions++;                        // every cell starts with a transition
      out[2 * k + 1] = level;
      if (word[k]) begin level = !level; transitions++; end // a transition in the middle of the cell is a 1
      out[2 * k] = level;
    end
    return out;
  endfunction
  function automatic bit prbs();
    bit b;
    b = s[8] ^ s[10];
    s = {s[9:0], b};
    return b;
  endfunction
  function automatic int pattern(input [10:0] seed);
    int ones;
    s = seed; ones = 0;
    for (int i = 0; i < 4094; i++) if (prbs()) ones++;
    return ones;                                            // the two zeros that follow add nothing
  endfunction
endmodule
ConceptWhy is the control channel sent at a quarter of the line rate?
Conceptc(+1) stands at its minimum. A decrement arrives. What does the status report?
ConceptWhen may a port treat its partner as ready?
ConceptTraining has run for 500 ms and a port is still in TRAIN_LOCAL. What happens?

Common Mistakes

Wrong Send a request in one frame and move on.

That frame may be ignored, and the tap may be busy.

Fix Hold the request until the status changes. Then hold until it is not_updated again.

Wrong Report nothing when a tap cannot move.

The partner would wait for an answer for ever.

Fix Report maximum or minimum, also when the tap already stood at the limit.

Wrong Stop sending frames as soon as both ready bits are seen.

The partner may not have counted three frames yet.

Fix Stay in LINK_READY for the wait_timer: 100 to 300 more frames.

Wrong Read the update field as a report on your own taps.

The two fields point in opposite directions.

Fix The update field asks the reader to change. The status field reports on the sender.

Remember

  • A training frame is 548 octets: marker, coefficient update, status report and a PRBS11 pattern.
  • The control channel is DME in cells of 8 UI. A violation makes the port ignore both fields.
  • A request stays until a status comes back. A hold brings the status back to not_updated.
  • A tap at its limit reports maximum or minimum. That is how the partner learns the limits.
  • Both ports send receiver ready, see it three times, linger for the wait_timer and switch to data.

Practice

Report a problem with this page