Clause 37 Auto-Negotiation and SGMII

Two gigabit fibre ports must agree on duplex and pause before a frame moves. Watch them trade one 16-bit word, acknowledge it and bring the link up.

You Will Be Able To

  • Split a Config_Reg base page into its fields.
  • Trace the arbitration states to LINK_OK, and explain why a zero word restarts the partner.
  • Resolve duplex and pause from two advertised pages.
  • Read an SGMII word, and say why it differs from a Clause 37 page.
Lesson
P11.21
Time
30 min
Runs on
Your browser
Check
5 questions

A 1000BASE-X port does not guess what its partner can do. Before any packet, the two ends exchange one word inside ordered sets.

Ordered setA is inA sendsB is inB sends
1AN_RESTART0000AN_RESTART0000
101ABILITY_DETECT00a0ABILITY_DETECT01e0
104ACKNOWLEDGE_DETECT40a0ACKNOWLEDGE_DETECT41e0
107COMPLETE_ACKNOWLEDGE40a0COMPLETE_ACKNOWLEDGE41e0
207IDLE_DETECTidleIDLE_DETECTidle
307LINK_OKidleLINK_OKidle

Bench run of the example: two ports reset together. Each row is a change of state. The bench timer is 100 ordered sets, not the standard's 10 ms. The match counts start again on each state entry (37.3.1.2).

One Word Inside /C/

Auto-negotiation lives in the PCS (37.1.3). It uses the configuration ordered sets of P11.20. Each set is K28.5, one data code-group, and the 16-bit word as two octets.

Code-groupKindOctetWhat it is
0KBChK28.5
1DB5hD21.5: this is /C1/
2DA0hword bits D7 to D0
3D41hword bits D15 to D8
4KBChK28.5
5D42hD2.2: this is /C2/
6DA0hword bits D7 to D0
7D41hword bits D15 to D8

Bench run: the word 41A0h as two configuration ordered sets. /C1/ and /C2/ alternate (36.2.4.10).

The low octet goes first. The sets repeat without a break while the ports negotiate (36.2.4.10).

Three values of xmit tell the transmitter what to send: CONFIGURATION, IDLE or DATA (37.3.1.1).

The Base Page

D15D14D13, D12D11 to D9D8D7D6D5D4 to D0
NPAckRFreservedASM_DIRPAUSEHDFDreserved
Next PageAcknowledgeRemote Fault0pause directionpausehalf duplexfull duplex0

The Config_Reg base page. IEEE Std 802.3-2022 37.2.1, Figure 37-2 (redrawn).

WordFDHDPAUSEASM_DIRRFAck
00A0h1010000
01E0h1111000
41A0h1011001
3020h1000110

Bench run: four words split into fields. RF 11 is Auto-Negotiation_Error (Table 37-3).

A port may hide an ability it has. It must not advertise one it lacks (37.2.2).

NP asks for Next Pages: more words after the base page. They are optional (37.2.4.3) and this page leaves them out.

Three in a Row

One corrupted word must not decide anything. So every step waits for three matching words in a row (37.3.1.2).

The Arbitration StatesA port sends zeros, then its page, then its page with Ack, then idle. Each step waits for three matching words from the partner, for the timer, or for both.
  • Control / FSM
  • Control
The arbitration statesA port sends zeros, then its page, then its page with Ack, then idle. Each step waits for three matching words from the partner, for the timer, or for both. control AN_RESTART sends the word 0000h for onetimer control ABILITY_DETECT sends its page, Ack = 0 control ACKNOWLEDGE_DETECT sends its page, Ack = 1 control COMPLETE_ACKNOWLEDGE stores the partner page; one timer control IDLE_DETECT sends idle; resolves priority; onetimer control LINK_OK packets may flow timer done3 matching words, notzero3 matching words withAcktimer done3 idles and timer done3 matching words
  1. control AN_RESTARTsends the word 0000h for one timer
    • timer done → ABILITY_DETECT
  2. control ABILITY_DETECTsends its page, Ack = 0
    • 3 matching words, not zero → ACKNOWLEDGE_DETECT
  3. control ACKNOWLEDGE_DETECTsends its page, Ack = 1
    • 3 matching words with Ack → COMPLETE_ACKNOWLEDGE
  4. control COMPLETE_ACKNOWLEDGEstores the partner page; one timer
    • timer done → IDLE_DETECT
  5. control IDLE_DETECTsends idle; resolves priority; one timer
    • 3 idles and timer done → LINK_OK
  6. control LINK_OKpackets may flow
    • 3 matching words → AN_RESTART
  1. Restart

    The port sends /C/ sets that carry 0000h for one link_timer. A partner past ABILITY_DETECT sees them and restarts too.

  2. Ability

    It sends its base page. Three matching words in a row from the partner, not zero, move it on.

  3. Acknowledge

    It sets Ack. Three matching words with Ack set, equal to the page seen before, complete the exchange.

  4. Idle

    After one more timer it sends idle and resolves what to enable. Three idles and a third timer bring the link up.

  5. Again

    A link that is up restarts when configuration words arrive.

Read the diagram as text
  • AN_RESTART: sends the word 0000h for one timer
  • ABILITY_DETECT: sends its page, Ack = 0
  • ACKNOWLEDGE_DETECT: sends its page, Ack = 1
  • COMPLETE_ACKNOWLEDGE: stores the partner page; one timer
  • IDLE_DETECT: sends idle; resolves priority; one timer
  • LINK_OK: packets may flow
  • AN_RESTART → ABILITY_DETECT: timer done
  • ABILITY_DETECT → ACKNOWLEDGE_DETECT: 3 matching words, not zero
  • ACKNOWLEDGE_DETECT → COMPLETE_ACKNOWLEDGE: 3 matching words with Ack
  • COMPLETE_ACKNOWLEDGE → IDLE_DETECT: timer done
  • IDLE_DETECT → LINK_OK: 3 idles and timer done
  • LINK_OK → AN_RESTART: 3 matching words

After IEEE Std 802.3-2022 Figure 37-6 (redrawn; AN_ENABLE, the Next Page states and the returns on a zero word are left out). The match counts start again on each state entry (37.3.1.2, NOTEs).

ability_match compares the words without the Ack bit. acknowledge_match needs the whole word to repeat with Ack set.

Each timed step lasts one link_timer: 10 ms, with up to 10 ms more allowed (37.3.1.4). That is 312,500 configuration sets.

The bench model used a timer of 100 ordered sets. Both ports were up at ordered set 307: three timers and a few sets of matching.

With real timers that is at least 30 ms from restart to the first packet.

The Zero Word Means Restart

A restarting port sends the word 0000h. Three of those in a row send a partner in ACKNOWLEDGE_DETECT, COMPLETE_ACKNOWLEDGE or IDLE_DETECT back to the start (Figure 37-6).

A partner still in ABILITY_DETECT just waits for a page that is not zero. A partner in LINK_OK restarts on any three matching words.

Ordered setA is inA sendsB is inB sends
401LINK_OKidleAN_RESTART0000
403AN_ENABLE0000AN_RESTART0000
404AN_RESTART0000AN_RESTART0000
501AN_RESTART0000ABILITY_DETECT01e0

Bench run of the example, second half: management restarts B at ordered set 400. A follows three words later.

In the bench run, A was back in AN_RESTART 4 ordered sets after B restarted.

If one port reset 60 sets after the other, both still came up together, at ordered set 367.

A page of all zeros cannot be told from a restart. With both ports advertising 0000h, both sat in ABILITY_DETECT for all 1000 ordered sets of the run.

With only A advertising 0000h, both links still came up, at ordered set 308. A's word with Ack set is 4000h, which is not zero.

Loss of synchronisation for a link_timer or more also restarts the port (37.3.1.1, an_sync_status).

What Both Ends Enable

In IDLE_DETECT each port compares its own page with the stored partner page. Both ends apply the same rules, so they reach matching answers (37.2.4.2).

Full duplex has priority over half duplex. Pause follows Table 37-4, which starts from what each port says:

PAUSE (D7)ASM_DIR (D8)The port says
00no pause
01asymmetric pause toward the partner: I may send PAUSE, I do not obey it
10symmetric pause
11symmetric pause, or asymmetric toward me: I obey PAUSE, and send it too if the partner has PAUSE

IEEE Std 802.3-2022 Table 37-2. Clause 28 uses the same encoding on twisted pair (Table 28B-2).

First port advertisesSecond port advertisesDuplexPause at the firstPause at the second
FD, PAUSEFD, HD, PAUSE, ASM_DIRfullboth waysboth ways
FDFD, PAUSEfulloffoff
FD, ASM_DIRFD, PAUSE, ASM_DIRfulltransmit onlyreceive only
FD, ASM_DIRFD, PAUSEfulloffoff
FD, ASM_DIRFD, ASM_DIRfulloffoff
FD, HDHDhalfoffoff
HD, PAUSEHD, PAUSEhalfoffoff
FDHDnone (error)offoff

Bench runs with a private resolution model (37.2.4.2, Table 37-4). "Transmit only" means the port may send PAUSE frames but ignores received ones. This course enables pause only in full duplex. Annex 31B makes PAUSE a full-duplex function, and 28B.3 says so for Clause 28. Clause 37 itself is silent.

With no common duplex the link cannot work. A port that supports Remote Fault reports that to the partner with the code 11 (37.2.4.2, 37.2.1.5.4).

On twisted pair, Clause 28 resolves pause with the same table (Annex 28B.3). P11.36 covers that page.

SGMII: Same Word, New Fields

SGMII (serial GMII) links a 10/100/1000 PHY to a MAC. It is Cisco's document ENG-46158, not part of IEEE 802.3.

Each way there is one data pair at 1.25 Gbaud and one 625 MHz clock pair, used on both edges (Overview).

The data uses the 1000BASE-X PCS of P11.20 unchanged. Auto-negotiation runs this page's machine, in the same /C/ ordered sets.

Only the meaning of the 16 bits changes (Table 1):

BitsClause 37 base pageSGMII: PHY to MACSGMII: MAC to PHY
D15NPlink: 1 up, 0 down0
D14AckAck, as in Clause 371
D13RF200
D12RF1duplex: 1 full, 0 half0
D11, D10reservedspeed: 10 = 1000, 01 = 100, 00 = 10 Mb/s0
D9reserved00
D8 to D5ASM_DIR, PAUSE, HD, FD00
D4 to D1reserved00
D0reserved11

One 16-bit word, two meanings. Clause 37: IEEE Std 802.3-2022 Figure 37-2. SGMII: Cisco ENG-46158 rev 1.7, Table 1 (both redrawn). Speed code 11 is reserved.

Clause 37 advertises what a port can do. The SGMII word reports what the PHY's copper link is doing now.

The PHY speaks first: whenever link, speed or duplex changes, it restarts and sends the new word. The MAC answers 4001h: Ack plus D0.

D0 is 1 both ways. Revision 1.4 set it to make auto-negotiation work. Without it the MAC's page would be 0000h, the restart word.

The link timer drops from 10 ms to 1.6 ms. The document expects a change to reach the MAC in about 3.4 ms: two timers and the acknowledge.

The line always runs at 1.25 Gbaud. At 100 Mb/s each octet is sent 10 times, and at 10 Mb/s 100 times.

The repeating happens above the PCS, so /S/ appears once per frame. The first preamble octet may come one time short (9 or 99).

So set both ends to the same mode first. An SGMII port and a 1000BASE-X port read each other's words wrongly.

Try It

Two eth_an37 ports are wired back to back. Each call of step hands a port the ordered set the other one sent.

Read the first six lines: restart, page, page with Ack, a timer, idle, link up. A stored 41E0h, which is B's page with Ack set.

At ordered set 400 management restarts B. Three zero words later, A restarts too.

Set both a.adv and b.adv to 16'h0000. Neither port leaves ABILITY_DETECT: each waits for a page that is not zero.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: ordered set 1: A AN_RESTART sends 0000 | B AN_RESTART sends 0000 ordered set 101: A ABILITY_DETECT sends 00a0 | B ABILITY_DETECT sends 01e0 ordered set 104: A ACKNOWLEDGE_DETECT sends 40a0 | B ACKNOWLEDGE_DETECT sends 41e0 ordered set 107: A COMPLETE_ACKNOWLEDGE sends 40a0 | B COMPLETE_ACKNOWLEDGE sends 41e0 ordered set 207: A IDLE_DETECT sends idle | B IDLE_DETECT sends idle ordered set 307: A LINK_OK sends idle | B LINK_OK sends idle A stored the partner page 41e0; B stored 40a0 ordered set 401: A LINK_OK sends idle | B AN_RESTART sends 0000 ordered set 403: A AN_ENABLE sends 0000 | B AN_RESTART sends 0000 ordered set 404: A AN_RESTART sends 0000 | B AN_RESTART sends 0000 ordered set 501: A AN_RESTART sends 0000 | B ABILITY_DETECT sends 01e0 ordered set 504: A ABILITY_DETECT sends 00a0 | B ABILITY_DETECT sends 01e0 ordered set 507: A ACKNOWLEDGE_DETECT sends 40a0 | B ACKNOWLEDGE_DETECT sends 41e0 ordered set 510: A COMPLETE_ACKNOWLEDGE sends 40a0 | B COMPLETE_ACKNOWLEDGE sends 41e0 ordered set 610: A IDLE_DETECT sends idle | B IDLE_DETECT sends idle ordered set 710: A LINK_OK sends idle | B LINK_OK sends idle A restarted 1 time(s); both links up: 1
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_pcs.sv
`timescale 1ns/1ns
// eth_pcs.sv: the 1000BASE-X PCS, transmit side and synchronization (read-only). It sits on hs_8b10b (hs_code.sv).

// eth_1000x: the transmit ordered-set layer (36.2.4). The stream is kept as {k, d} and as ten coded bits.
//   clear()            empty stream, running disparity negative
//   idle(k)            k idle ordered sets. Each tests the running disparity first (Figure 36-6):
//                      positive -> /I1/ (K28.5 D5.6), negative -> /I2/ (K28.5 D16.2)
//   cfg(word, k)       k configuration ordered sets, /C1/ and /C2/ in turn: K28.5, D21.5 or D2.2, word[7:0], word[15:8]
//   start_packet()     /S/ in place of the first preamble octet, then six 55h and D5h
//   data(d)            one data code-group
//   end_packet()       /T/ /R/, and one more /R/ when the first /R/ went out on an even position
//   err()              /V/
//   put(k, d)          any code-group
//   n                  code-groups so far; code-group i is even-numbered when i is even
//   sym[i] = {k, d};  code[i] = abcdei fghj, bit a (code[i][9]) is sent first;  rdb[i] = running disparity before i
//   is_k(i, d), comma_plus(), comma_minus()
// Fault: idle_wrong_disparity (every idle is /I2/, so a positive running disparity is never corrected).
module eth_1000x;
  bit idle_wrong_disparity = 0;
  hs_8b10b c8();
  bit [8:0] sym [0:8191]; bit [9:0] code [0:8191]; bit rdb [0:8191];
  int n = 0; bit c2 = 0;
  function automatic void clear(); n = 0; c2 = 0; c8.rd_tx = 0; endfunction
  function automatic void put(input bit k, input [7:0] d);
    sym[n] = {k, d}; rdb[n] = c8.rd_tx; code[n] = c8.enc(d, k); n++;
  endfunction
  function automatic void idle(input int k);
    bit positive;
    for (int i = 0; i < k; i++) begin
      positive = c8.rd_tx && !idle_wrong_disparity;
      put(1'b1, 8'hbc);                                // K28.5
      put(1'b0, positive ? 8'hc5 : 8'h50);             // D5.6 or D16.2
    end
  endfunction
  function automatic void cfg(input [15:0] word, input int k);
    for (int i = 0; i < k; i++) begin
      put(1'b1, 8'hbc);
      put(1'b0, c2 ? 8'h42 : 8'hb5);                   // D2.2 or D21.5
      put(1'b0, word[7:0]); put(1'b0, word[15:8]);
      c2 = !c2;
    end
  endfunction
  function automatic void data(input [7:0] d); put(1'b0, d); endfunction
  function automatic void start_packet();
    put(1'b1, 8'hfb);                                  // /S/ = K27.7
    for (int i = 0; i < 6; i++) put(1'b0, 8'h55);
    put(1'b0, 8'hd5);
  endfunction
  function automatic void end_packet();
    put(1'b1, 8'hfd);                                  // /T/ = K29.7
    put(1'b1, 8'hf7);                                  // /R/ = K23.7
    if (n % 2 != 0) put(1'b1, 8'hf7);                  // that /R/ was even-numbered: one more
  endfunction
  function automatic void err(); put(1'b1, 8'hfe); endfunction     // /V/ = K30.7
  function automatic bit is_k(input int i, input [7:0] d); return sym[i] == {1'b1, d}; endfunction
  function automatic int comma_plus();
    int c; c = 0;
    for (int i = 0; i < n; i++) if (code[i][9:3] == 7'b0011111) c++;
    return c;
  endfunction
  function automatic int comma_minus();
    int c; c = 0;
    for (int i = 0; i < n; i++) if (code[i][9:3] == 7'b1100000) c++;
    return c;
  endfunction
endmodule

// eth_1000x_sync: the synchronization process of Figure 36-9, one call of rx() per ten-bit code-group.
//   reset()            LOSS_OF_SYNC
//   rx(code)           takes one code-group; returns sync_status (1 = OK)
//   state              0 LOSS_OF_SYNC, 1 COMMA_DETECT_1, 2 ACQUIRE_SYNC_1, 3 COMMA_DETECT_2, 4 ACQUIRE_SYNC_2,
//                      5 COMMA_DETECT_3, 6 SYNC_ACQUIRED_1, 7 SYNC_ACQUIRED_2, 8 SYNC_ACQUIRED_2A,
//                      9 SYNC_ACQUIRED_3, 10 SYNC_ACQUIRED_3A, 11 SYNC_ACQUIRED_4, 12 SYNC_ACQUIRED_4A
//   even               the code-group just taken was even-numbered
//   good_cgs, bad_seen (every bad code-group since reset), k, d (the last decode)
// A code-group is bad when it is invalid, or when it holds a comma and is odd-numbered (36.2.5.1.3).
// Bench choices: in LOSS_OF_SYNC the decoder takes its running disparity from the comma it finds; an invalid
// code-group leaves the decoder's running disparity as the received bits set it.
module eth_1000x_sync;
  hs_8b10b c8();
  int state = 0, good_cgs = 0, bad_seen = 0;
  bit even = 0, sync = 0, rd = 0, k = 0; bit [7:0] d = 0;
  function automatic void reset(); state = 0; good_cgs = 0; bad_seen = 0; even = 0; sync = 0; rd = 0; endfunction
  function automatic bit rx(input [9:0] code);
    reg [11:0] r; bit invalid, comma, is_d, bad;
    comma = code[9:3] == 7'b0011111 || code[9:3] == 7'b1100000;
    if (state == 0 && comma) rd = (code[9:3] == 7'b1100000);
    r = c8.decode(code, rd);                           // {rd_out, disp_err, code_err, k, d}
    rd = r[11]; k = r[8]; d = r[7:0];
    invalid = r[10] || r[9];
    is_d = !invalid && !r[8];
    bad = invalid || (comma && even);                  // even: the one before was even, so this one is odd
    if (bad && state != 0) bad_seen++;
    case (state)
      0: begin if (comma) begin state = 1; even = 1; end else even = !even; end
      1, 3, 5: begin even = 0; state = is_d ? state + 1 : 0; end
      2, 4: begin
        if (bad) state = 0;
        else if (comma) begin state = state + 1; even = 1; end
        else even = !even;
      end
      6: begin even = !even; if (bad) begin state = 7; good_cgs = 0; end end
      7, 9, 11: begin
        even = !even;
        if (bad) begin state = (state == 11) ? 0 : state + 2; good_cgs = 0; end
        else begin state = state + 1; good_cgs = 1; end
      end
      default: begin                                   // 8, 10, 12: counting good code-groups
        even = !even;
        if (bad) begin state = (state == 12) ? 0 : state + 1; good_cgs = 0; end
        else if (good_cgs == 3) begin state = (state == 8) ? 6 : state - 3; good_cgs = 0; end
        else good_cgs++;
      end
    endcase
    sync = state >= 6;
    return sync;
  endfunction
endmodule

// ---- 10GBASE-R and 25GBASE-R: 64B/66B blocks (Clause 49; Clause 107 uses the same code) ----
// Eight XGMII characters are one vector raw[71:0] (49.2.13.2.2): raw[k] is the control flag of character k,
// raw[8 + 8*k +: 8] its octet. A block is blk[65:0]; bit 0 is sent first. blk[1:0] is the sync header,
// blk[9:2] the block type field of a control block, the rest the payload (Figure 49-7).

// eth_66: the control blocks that hold no Start, no Terminate and no frame data.
//   c_code(x)       Table 49-1: the 7-bit C code of XGMII control code x; 7Fh if x is not in the table
//   enc_ctrl(raw)   {ok, blk}: block type 1Eh (eight control characters), 2Dh (four, then an ordered set),
//                   4Bh (an ordered set, then four) or 55h (two ordered sets); ok = 0 if raw is none of these.
//                   It only lays out the fields. Whether the vector may be sent is the transmit process's
//                   decision (eth_66_tx).
//   on_wire(blk)    the 66 bits as text in the order they are sent: sync, block type, payload
//   ham(a, b)       how many bits differ between two block type values
// Fault: wrong_block_type (types 2Dh and 4Bh are swapped).
module eth_66;
  bit wrong_block_type = 0;
  function automatic [6:0] c_code(input [7:0] x);
    case (x)
      8'h07: return 7'h00;                             // idle
      8'h06: return 7'h06;                             // low power idle
      8'hfe: return 7'h1e;                             // error
      8'h1c: return 7'h2d;                             // the six reserved characters
      8'h3c: return 7'h33;
      8'h7c: return 7'h4b;
      8'hbc: return 7'h55;
      8'hdc: return 7'h66;
      8'hf7: return 7'h78;
      default: return 7'h7f;
    endcase
  endfunction
  function automatic [7:0] ch(input [71:0] raw, input int k); return raw[8 + 8*k +: 8]; endfunction
  // characters k to k+3 are a sequence ordered set: 9Ch with its flag, then three data octets
  function automatic bit is_q(input [71:0] raw, input int k);
    return raw[k] && ch(raw, k) == 8'h9c && !raw[k + 1] && !raw[k + 2] && !raw[k + 3];
  endfunction
  // characters k to k+3 are control characters with a C code
  function automatic bit is_c4(input [71:0] raw, input int k);
    for (int j = k; j < k + 4; j++) if (!raw[j] || c_code(ch(raw, j)) == 7'h7f) return 0;
    return 1;
  endfunction
  function automatic [66:0] enc_ctrl(input [71:0] raw);
    reg [65:0] b; bit q0, q4, c0, c4;
    b = 66'd0;
    b[1:0] = 2'b01;                                    // sync header "10": bit 0, sent first, is 1
    q0 = is_q(raw, 0); q4 = is_q(raw, 4); c0 = is_c4(raw, 0); c4 = is_c4(raw, 4);
    if (c0 && c4) b[9:2] = 8'h1e;
    else if (c0 && q4) b[9:2] = wrong_block_type ? 8'h4b : 8'h2d;
    else if (q0 && c4) b[9:2] = wrong_block_type ? 8'h2d : 8'h4b;
    else if (q0 && q4) b[9:2] = 8'h55;
    else return 67'd0;
    if (c0) for (int k = 0; k < 4; k++) b[10 + 7*k +: 7] = c_code(ch(raw, k));
    else begin b[33:10] = raw[39:16]; b[37:34] = 4'h0; end     // D1 to D3, then the O code of the sequence set
    if (c4) for (int k = 4; k < 8; k++) b[10 + 7*k +: 7] = c_code(ch(raw, k));
    else begin b[41:38] = 4'h0; b[65:42] = raw[71:48]; end     // the O code, then D5 to D7
    return {1'b1, b};
  endfunction
  function automatic string on_wire(input [65:0] blk);
    string s;
    s = "";
    for (int i = 0; i < 66; i++) begin
      if (i == 2 || i == 10) s = {s, " "};
      s = {s, blk[i] ? "1" : "0"};
    end
    return s;
  endfunction
  function automatic int ham(input [7:0] a, input [7:0] b);
    int n; reg [7:0] x;
    x = a ^ b; n = 0;
    for (int i = 0; i < 8; i++) if (x[i]) n++;
    return n;
  endfunction
endmodule

// eth_66_tx: the transmit state diagram (Figure 49-16) without the EEE state. One call per vector.
//   step(t)   t is the T_TYPE of the vector: 0 C (control), 1 S (start), 2 T (terminate), 3 D (data), 4 E (none of these).
//             Returns 1 if the vector is encoded and sent, 0 if the error block goes out in its place.
//   state     0 TX_INIT, 1 TX_C, 2 TX_D, 3 TX_T, 4 TX_E
module eth_66_tx;
  int state = 0;
  function automatic void reset(); state = 0; endfunction
  function automatic bit step(input int t);
    case (state)
      0, 1, 3: state = (t == 0) ? 1 : (t == 1) ? 2 : 4;                    // TX_INIT, TX_C, TX_T: only C or S may follow
      2: state = (t == 3) ? 2 : (t == 2) ? 3 : 4;                          // TX_D: only D or T may follow
      default: state = (t == 2) ? 3 : (t == 3) ? 2 : (t == 0) ? 1 : 4;     // TX_E: T, D or C leave it
    endcase
    return state != 4;
  endfunction
endmodule

// eth_66_comp: clock compensation on XGMII columns (49.2.4.7, 49.2.4.10). Call once per column, in order.
// A column is {c[3:0], d[31:0]}: lane k is flag c[k] and octet d[8k+7:8k].
//   can_delete(c, d)   1 if this column may be dropped: four idles that hold none of the first four characters
//                      after a Terminate, or the second of two consecutive sequence ordered sets
//   can_insert(c, d)   1 if an idle column may be added after this one: it is idle or an ordered set
module eth_66_comp;
  bit guard = 0, prev_seq = 0;
  function automatic void reset(); guard = 0; prev_seq = 0; endfunction
  function automatic bit is_seq(input [3:0] c, input [31:0] d); return c == 4'b0001 && d[7:0] == 8'h9c; endfunction
  function automatic bit is_idle(input [3:0] c, input [31:0] d); return c == 4'b1111 && d == 32'h07070707; endfunction
  function automatic bit can_delete(input [3:0] c, input [31:0] d);
    bit ok, has_t;
    has_t = 0;
    for (int k = 0; k < 4; k++) if (c[k] && d[8*k +: 8] == 8'hfd) has_t = 1;
    ok = (is_idle(c, d) && !guard) || (is_seq(c, d) && prev_seq);
    guard = has_t;                                     // the next column holds some of the four characters after /T/
    prev_seq = is_seq(c, d) && !ok;                    // only one of the two
    return ok;
  endfunction
  function automatic bit can_insert(input [3:0] c, input [31:0] d); return is_idle(c, d) || is_seq(c, d); endfunction
endmodule

// eth_66_scr: the scrambler and the descrambler of 10GBASE-R (49.2.6, 49.2.10; Figures 49-8 and 49-10).
// The register is s[57:0]: stage S0 is s[0] and holds the newest line bit. Use one instance to scramble and
// another to descramble.
//   scr_bit(b)       one payload bit in, one line bit out: b XOR S38 XOR S57. The line bit shifts into S0.
//   dscr_bit(b)      one line bit in, one payload bit out: the same XOR. The received bit shifts into S0.
//   scramble(blk)    a whole block: bits 1:0 (the sync header) pass, bits 2 to 65 are scrambled in that order
//   descramble(blk)  the reverse
//   load(v)          sets the register (the standard asks for no start value)
// Fault: scrambles_header (the two sync header bits go through the scrambler too).
module eth_66_scr;
  bit [57:0] s = 58'd0;
  bit scrambles_header = 0;
  function automatic void load(input [57:0] v); s = v; endfunction
  function automatic bit scr_bit(input bit b);
    bit o; o = b ^ s[38] ^ s[57]; s = {s[56:0], o}; return o;
  endfunction
  function automatic bit dscr_bit(input bit b);
    bit o; o = b ^ s[38] ^ s[57]; s = {s[56:0], b}; return o;
  endfunction
  function automatic [65:0] scramble(input [65:0] blk);
    reg [65:0] o; o = blk;
    for (int i = scrambles_header ? 0 : 2; i < 66; i++) o[i] = scr_bit(blk[i]);
    return o;
  endfunction
  function automatic [65:0] descramble(input [65:0] blk);
    reg [65:0] o; o = blk;
    for (int i = 2; i < 66; i++) o[i] = dscr_bit(blk[i]);
    return o;
  endfunction
endmodule

// eth_prbs31: the PRBS31 pattern generator (49.2.8, Figure 49-9). The register is s[30:0], stage S0 is s[0].
//   gen_bit()   the next pattern bit: S27 XOR S30 shifts into S0, and the output is that bit inverted
// The register must not be all zeros: it would stay there. The checker is not in this file.
module eth_prbs31;
  bit [30:0] s = 31'h7fffffff;
  function automatic bit gen_bit();
    bit f; f = s[27] ^ s[30]; s = {s[29:0], f}; return !f;
  endfunction
endmodule

// eth_66_test: the square wave of 49.2.8 and the two data patterns of the pseudo-random test pattern.
//   sq_bit()        square wave: sq_n ones, then sq_n zeros (sq_n may be 4 to 11)
//   pattern()       the 64-bit data pattern: zeros, or the payload of a block with two local fault sets (lf_pattern)
// The pseudo-random pattern generator and its checker (49.2.8, 49.2.12) are not in this file.
module eth_66_test;
  eth_66 code();
  bit lf_pattern = 0;
  int sq_n = 8, sq_k = 0;
  function automatic void restart(); sq_k = 0; endfunction
  function automatic bit sq_bit();
    bit b; b = (sq_k < sq_n); sq_k = (sq_k + 1) % (2 * sq_n); return b;
  endfunction
  function automatic [63:0] pattern();
    reg [66:0] r;
    if (!lf_pattern) return 64'd0;
    r = code.enc_ctrl({64'h0100009c_0100009c, 8'h11}); return r[65:2];
  endfunction
endmodule

// eth_66_loop: PCS loopback (49.2.14.4), switched by MDIO bit 3.0.14.
//   rx_block(from_tx, from_pma)   what the receive path decodes: its own transmit block when loopback is 1
//   pma_word(w)                   what goes to the PMA: the word 00FFh when loopback is 1, else w
module eth_66_loop;
  bit loopback = 0;
  function automatic [65:0] rx_block(input [65:0] from_tx, input [65:0] from_pma); return loopback ? from_tx : from_pma; endfunction
  function automatic [15:0] pma_word(input [15:0] w); return loopback ? 16'h00ff : w; endfunction
endmodule
Read included file: eth_link.sv
`timescale 1ns/1ns
// eth_link.sv: link bring-up models (read-only).

// eth_an37: the arbitration of Clause 37 auto-negotiation for one port (Figure 37-6, without Next Pages).
// One call of step() per received ordered set.
//   adv                the base page to advertise: D5 full duplex, D6 half duplex, D7 PAUSE, D8 ASM_DIR,
//                      D13 D12 remote fault. The model drives D14 (Acknowledge) itself and sends D15 as 0.
//   reset()            AN_ENABLE (power-on, or a restart asked by management)
//   step(kind, word)   kind 0: a /C/ ordered set carrying word; 1: an /I/; 2: anything else
//   xmit               what the port sends now: 0 = /C/ carrying tx_word, 1 = /I/, 2 = data (the link is up)
//   state              0 AN_ENABLE, 1 AN_RESTART, 2 ABILITY_DETECT, 3 ACKNOWLEDGE_DETECT,
//                      4 COMPLETE_ACKNOWLEDGE, 5 IDLE_DETECT, 6 LINK_OK
//   lp_adv, page_rx    the partner's base page, stored on entry to COMPLETE_ACKNOWLEDGE
//   an_complete, restarts
//   link_timer         in calls of step(). Bench value 100; the standard's timer is 10 ms (37.3.1.4).
// The match functions follow 37.3.1.2: three ordered sets in a row; the counts restart on each state entry.
// What the two ends then enable (duplex, pause) is not in this model.
module eth_an37;
  bit [15:0] adv = 16'h0020;
  int link_timer = 100;
  int state = 0, xmit = 0, t = 0, restarts = 0;
  bit [15:0] tx_word = 0, lp_adv = 0, rx_word = 0, am_word = 0, ab_word = 0, ak_word = 0;
  int am_cnt = 0, ak_cnt = 0, id_cnt = 0;
  bit page_rx = 0, an_complete = 0;
  function automatic void enter(input int s);
    state = s; t = 0; am_cnt = 0; ak_cnt = 0; id_cnt = 0;
    case (s)
      0: begin xmit = 0; tx_word = 16'h0000; page_rx = 0; an_complete = 0; restarts++; end
      1: begin xmit = 0; tx_word = 16'h0000; end
      2: begin xmit = 0; tx_word = adv & 16'h3fff; end
      3: begin xmit = 0; tx_word = (adv & 16'h3fff) | 16'h4000; end
      4: begin lp_adv = rx_word; page_rx = 1; end
      5: xmit = 1;
      default: begin xmit = 2; an_complete = 1; end
    endcase
  endfunction
  function automatic void reset(); enter(0); restarts = 0; endfunction
  function automatic void step(input int kind, input [15:0] word);
    bit ability, ack, consistent, idle3, zero, done;
    t++;
    if (kind == 0) begin
      rx_word = word; id_cnt = 0;
      // ability_match ignores the Acknowledge bit (D14)
      if (am_cnt > 0 && (word & 16'hbfff) == am_word) begin if (am_cnt < 3) am_cnt++; end
      else begin am_word = word & 16'hbfff; am_cnt = 1; end
      // acknowledge_match needs the whole word to repeat with D14 set
      if (!word[14]) ak_cnt = 0;
      else if (ak_cnt > 0 && word == ak_word) begin if (ak_cnt < 3) ak_cnt++; end
      else begin ak_word = word; ak_cnt = 1; end
    end
    else begin
      am_cnt = 0; ak_cnt = 0;
      if (kind == 1) begin if (id_cnt < 3) id_cnt++; end else id_cnt = 0;
    end
    ability = am_cnt == 3; ack = ak_cnt == 3; idle3 = id_cnt == 3;
    zero = ability && am_word == 16'h0000 && !rx_word[14];
    consistent = (ak_word & 16'hbfff) == ab_word;
    done = t >= link_timer;
    case (state)
      0: enter(1);
      1: if (done) enter(2);
      2: if (ability && !zero) begin ab_word = am_word; enter(3); end
      3: begin
        if (zero || (ack && !consistent)) enter(0);
        else if (ack) enter(4);
      end
      4: begin
        if (zero) enter(0);
        else if (done) enter(5);
      end
      5: begin
        if (zero) enter(0);
        else if (idle3 && done) enter(6);
      end
      default: if (ability) enter(0);
    endcase
  endfunction
endmodule

Check Yourself

Predict the outputPort A advertises 00A0h. The program runs until A enters ACKNOWLEDGE_DETECT and prints the word A sends. What does it print?
`timescale 1ns/1ns
module tb;
  eth_an37 a(), b();
  int ka, kb, sa, sb, now; reg [15:0] wa, wb;
  function automatic string sname(input int st);
    case (st) 0: return "AN_ENABLE"; 1: return "AN_RESTART"; 2: return "ABILITY_DETECT"; 3: return "ACKNOWLEDGE_DETECT";
      4: return "COMPLETE_ACKNOWLEDGE"; 5: return "IDLE_DETECT"; default: return "LINK_OK"; endcase
  endfunction
  function automatic string sent(input int xmit, input [15:0] w);
    if (xmit == 0) return $sformatf("%h", w);
    return "idle";
  endfunction
  // k ordered-set times. Each port takes what the other sent; a port whose link is up sends idle between packets.
  task automatic run(input int k, input bit quiet);
    for (int i = 0; i < k; i++) begin
      ka = (a.xmit == 0) ? 0 : 1; wa = a.tx_word; kb = (b.xmit == 0) ? 0 : 1; wb = b.tx_word;
      a.step(kb, wb); b.step(ka, wa); now++;
      if (!quiet && (a.state != sa || b.state != sb))
        $display("ordered set %0d: A %0s sends %0s | B %0s sends %0s", now, sname(a.state), sent(a.xmit, a.tx_word), sname(b.state), sent(b.xmit, b.tx_word));
      sa = a.state; sb = b.state;
    end
  endtask
  initial begin
    a.adv = 16'h00a0; b.adv = 16'h01e0;
    a.reset(); b.reset(); now = 0;
    while (a.state != 3) run(1, 1);
    $display("%h", a.tx_word);
    $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_pcs.sv
`timescale 1ns/1ns
// eth_pcs.sv: the 1000BASE-X PCS, transmit side and synchronization (read-only). It sits on hs_8b10b (hs_code.sv).

// eth_1000x: the transmit ordered-set layer (36.2.4). The stream is kept as {k, d} and as ten coded bits.
//   clear()            empty stream, running disparity negative
//   idle(k)            k idle ordered sets. Each tests the running disparity first (Figure 36-6):
//                      positive -> /I1/ (K28.5 D5.6), negative -> /I2/ (K28.5 D16.2)
//   cfg(word, k)       k configuration ordered sets, /C1/ and /C2/ in turn: K28.5, D21.5 or D2.2, word[7:0], word[15:8]
//   start_packet()     /S/ in place of the first preamble octet, then six 55h and D5h
//   data(d)            one data code-group
//   end_packet()       /T/ /R/, and one more /R/ when the first /R/ went out on an even position
//   err()              /V/
//   put(k, d)          any code-group
//   n                  code-groups so far; code-group i is even-numbered when i is even
//   sym[i] = {k, d};  code[i] = abcdei fghj, bit a (code[i][9]) is sent first;  rdb[i] = running disparity before i
//   is_k(i, d), comma_plus(), comma_minus()
// Fault: idle_wrong_disparity (every idle is /I2/, so a positive running disparity is never corrected).
module eth_1000x;
  bit idle_wrong_disparity = 0;
  hs_8b10b c8();
  bit [8:0] sym [0:8191]; bit [9:0] code [0:8191]; bit rdb [0:8191];
  int n = 0; bit c2 = 0;
  function automatic void clear(); n = 0; c2 = 0; c8.rd_tx = 0; endfunction
  function automatic void put(input bit k, input [7:0] d);
    sym[n] = {k, d}; rdb[n] = c8.rd_tx; code[n] = c8.enc(d, k); n++;
  endfunction
  function automatic void idle(input int k);
    bit positive;
    for (int i = 0; i < k; i++) begin
      positive = c8.rd_tx && !idle_wrong_disparity;
      put(1'b1, 8'hbc);                                // K28.5
      put(1'b0, positive ? 8'hc5 : 8'h50);             // D5.6 or D16.2
    end
  endfunction
  function automatic void cfg(input [15:0] word, input int k);
    for (int i = 0; i < k; i++) begin
      put(1'b1, 8'hbc);
      put(1'b0, c2 ? 8'h42 : 8'hb5);                   // D2.2 or D21.5
      put(1'b0, word[7:0]); put(1'b0, word[15:8]);
      c2 = !c2;
    end
  endfunction
  function automatic void data(input [7:0] d); put(1'b0, d); endfunction
  function automatic void start_packet();
    put(1'b1, 8'hfb);                                  // /S/ = K27.7
    for (int i = 0; i < 6; i++) put(1'b0, 8'h55);
    put(1'b0, 8'hd5);
  endfunction
  function automatic void end_packet();
    put(1'b1, 8'hfd);                                  // /T/ = K29.7
    put(1'b1, 8'hf7);                                  // /R/ = K23.7
    if (n % 2 != 0) put(1'b1, 8'hf7);                  // that /R/ was even-numbered: one more
  endfunction
  function automatic void err(); put(1'b1, 8'hfe); endfunction     // /V/ = K30.7
  function automatic bit is_k(input int i, input [7:0] d); return sym[i] == {1'b1, d}; endfunction
  function automatic int comma_plus();
    int c; c = 0;
    for (int i = 0; i < n; i++) if (code[i][9:3] == 7'b0011111) c++;
    return c;
  endfunction
  function automatic int comma_minus();
    int c; c = 0;
    for (int i = 0; i < n; i++) if (code[i][9:3] == 7'b1100000) c++;
    return c;
  endfunction
endmodule

// eth_1000x_sync: the synchronization process of Figure 36-9, one call of rx() per ten-bit code-group.
//   reset()            LOSS_OF_SYNC
//   rx(code)           takes one code-group; returns sync_status (1 = OK)
//   state              0 LOSS_OF_SYNC, 1 COMMA_DETECT_1, 2 ACQUIRE_SYNC_1, 3 COMMA_DETECT_2, 4 ACQUIRE_SYNC_2,
//                      5 COMMA_DETECT_3, 6 SYNC_ACQUIRED_1, 7 SYNC_ACQUIRED_2, 8 SYNC_ACQUIRED_2A,
//                      9 SYNC_ACQUIRED_3, 10 SYNC_ACQUIRED_3A, 11 SYNC_ACQUIRED_4, 12 SYNC_ACQUIRED_4A
//   even               the code-group just taken was even-numbered
//   good_cgs, bad_seen (every bad code-group since reset), k, d (the last decode)
// A code-group is bad when it is invalid, or when it holds a comma and is odd-numbered (36.2.5.1.3).
// Bench choices: in LOSS_OF_SYNC the decoder takes its running disparity from the comma it finds; an invalid
// code-group leaves the decoder's running disparity as the received bits set it.
module eth_1000x_sync;
  hs_8b10b c8();
  int state = 0, good_cgs = 0, bad_seen = 0;
  bit even = 0, sync = 0, rd = 0, k = 0; bit [7:0] d = 0;
  function automatic void reset(); state = 0; good_cgs = 0; bad_seen = 0; even = 0; sync = 0; rd = 0; endfunction
  function automatic bit rx(input [9:0] code);
    reg [11:0] r; bit invalid, comma, is_d, bad;
    comma = code[9:3] == 7'b0011111 || code[9:3] == 7'b1100000;
    if (state == 0 && comma) rd = (code[9:3] == 7'b1100000);
    r = c8.decode(code, rd);                           // {rd_out, disp_err, code_err, k, d}
    rd = r[11]; k = r[8]; d = r[7:0];
    invalid = r[10] || r[9];
    is_d = !invalid && !r[8];
    bad = invalid || (comma && even);                  // even: the one before was even, so this one is odd
    if (bad && state != 0) bad_seen++;
    case (state)
      0: begin if (comma) begin state = 1; even = 1; end else even = !even; end
      1, 3, 5: begin even = 0; state = is_d ? state + 1 : 0; end
      2, 4: begin
        if (bad) state = 0;
        else if (comma) begin state = state + 1; even = 1; end
        else even = !even;
      end
      6: begin even = !even; if (bad) begin state = 7; good_cgs = 0; end end
      7, 9, 11: begin
        even = !even;
        if (bad) begin state = (state == 11) ? 0 : state + 2; good_cgs = 0; end
        else begin state = state + 1; good_cgs = 1; end
      end
      default: begin                                   // 8, 10, 12: counting good code-groups
        even = !even;
        if (bad) begin state = (state == 12) ? 0 : state + 1; good_cgs = 0; end
        else if (good_cgs == 3) begin state = (state == 8) ? 6 : state - 3; good_cgs = 0; end
        else good_cgs++;
      end
    endcase
    sync = state >= 6;
    return sync;
  endfunction
endmodule

// ---- 10GBASE-R and 25GBASE-R: 64B/66B blocks (Clause 49; Clause 107 uses the same code) ----
// Eight XGMII characters are one vector raw[71:0] (49.2.13.2.2): raw[k] is the control flag of character k,
// raw[8 + 8*k +: 8] its octet. A block is blk[65:0]; bit 0 is sent first. blk[1:0] is the sync header,
// blk[9:2] the block type field of a control block, the rest the payload (Figure 49-7).

// eth_66: the control blocks that hold no Start, no Terminate and no frame data.
//   c_code(x)       Table 49-1: the 7-bit C code of XGMII control code x; 7Fh if x is not in the table
//   enc_ctrl(raw)   {ok, blk}: block type 1Eh (eight control characters), 2Dh (four, then an ordered set),
//                   4Bh (an ordered set, then four) or 55h (two ordered sets); ok = 0 if raw is none of these.
//                   It only lays out the fields. Whether the vector may be sent is the transmit process's
//                   decision (eth_66_tx).
//   on_wire(blk)    the 66 bits as text in the order they are sent: sync, block type, payload
//   ham(a, b)       how many bits differ between two block type values
// Fault: wrong_block_type (types 2Dh and 4Bh are swapped).
module eth_66;
  bit wrong_block_type = 0;
  function automatic [6:0] c_code(input [7:0] x);
    case (x)
      8'h07: return 7'h00;                             // idle
      8'h06: return 7'h06;                             // low power idle
      8'hfe: return 7'h1e;                             // error
      8'h1c: return 7'h2d;                             // the six reserved characters
      8'h3c: return 7'h33;
      8'h7c: return 7'h4b;
      8'hbc: return 7'h55;
      8'hdc: return 7'h66;
      8'hf7: return 7'h78;
      default: return 7'h7f;
    endcase
  endfunction
  function automatic [7:0] ch(input [71:0] raw, input int k); return raw[8 + 8*k +: 8]; endfunction
  // characters k to k+3 are a sequence ordered set: 9Ch with its flag, then three data octets
  function automatic bit is_q(input [71:0] raw, input int k);
    return raw[k] && ch(raw, k) == 8'h9c && !raw[k + 1] && !raw[k + 2] && !raw[k + 3];
  endfunction
  // characters k to k+3 are control characters with a C code
  function automatic bit is_c4(input [71:0] raw, input int k);
    for (int j = k; j < k + 4; j++) if (!raw[j] || c_code(ch(raw, j)) == 7'h7f) return 0;
    return 1;
  endfunction
  function automatic [66:0] enc_ctrl(input [71:0] raw);
    reg [65:0] b; bit q0, q4, c0, c4;
    b = 66'd0;
    b[1:0] = 2'b01;                                    // sync header "10": bit 0, sent first, is 1
    q0 = is_q(raw, 0); q4 = is_q(raw, 4); c0 = is_c4(raw, 0); c4 = is_c4(raw, 4);
    if (c0 && c4) b[9:2] = 8'h1e;
    else if (c0 && q4) b[9:2] = wrong_block_type ? 8'h4b : 8'h2d;
    else if (q0 && c4) b[9:2] = wrong_block_type ? 8'h2d : 8'h4b;
    else if (q0 && q4) b[9:2] = 8'h55;
    else return 67'd0;
    if (c0) for (int k = 0; k < 4; k++) b[10 + 7*k +: 7] = c_code(ch(raw, k));
    else begin b[33:10] = raw[39:16]; b[37:34] = 4'h0; end     // D1 to D3, then the O code of the sequence set
    if (c4) for (int k = 4; k < 8; k++) b[10 + 7*k +: 7] = c_code(ch(raw, k));
    else begin b[41:38] = 4'h0; b[65:42] = raw[71:48]; end     // the O code, then D5 to D7
    return {1'b1, b};
  endfunction
  function automatic string on_wire(input [65:0] blk);
    string s;
    s = "";
    for (int i = 0; i < 66; i++) begin
      if (i == 2 || i == 10) s = {s, " "};
      s = {s, blk[i] ? "1" : "0"};
    end
    return s;
  endfunction
  function automatic int ham(input [7:0] a, input [7:0] b);
    int n; reg [7:0] x;
    x = a ^ b; n = 0;
    for (int i = 0; i < 8; i++) if (x[i]) n++;
    return n;
  endfunction
endmodule

// eth_66_tx: the transmit state diagram (Figure 49-16) without the EEE state. One call per vector.
//   step(t)   t is the T_TYPE of the vector: 0 C (control), 1 S (start), 2 T (terminate), 3 D (data), 4 E (none of these).
//             Returns 1 if the vector is encoded and sent, 0 if the error block goes out in its place.
//   state     0 TX_INIT, 1 TX_C, 2 TX_D, 3 TX_T, 4 TX_E
module eth_66_tx;
  int state = 0;
  function automatic void reset(); state = 0; endfunction
  function automatic bit step(input int t);
    case (state)
      0, 1, 3: state = (t == 0) ? 1 : (t == 1) ? 2 : 4;                    // TX_INIT, TX_C, TX_T: only C or S may follow
      2: state = (t == 3) ? 2 : (t == 2) ? 3 : 4;                          // TX_D: only D or T may follow
      default: state = (t == 2) ? 3 : (t == 3) ? 2 : (t == 0) ? 1 : 4;     // TX_E: T, D or C leave it
    endcase
    return state != 4;
  endfunction
endmodule

// eth_66_comp: clock compensation on XGMII columns (49.2.4.7, 49.2.4.10). Call once per column, in order.
// A column is {c[3:0], d[31:0]}: lane k is flag c[k] and octet d[8k+7:8k].
//   can_delete(c, d)   1 if this column may be dropped: four idles that hold none of the first four characters
//                      after a Terminate, or the second of two consecutive sequence ordered sets
//   can_insert(c, d)   1 if an idle column may be added after this one: it is idle or an ordered set
module eth_66_comp;
  bit guard = 0, prev_seq = 0;
  function automatic void reset(); guard = 0; prev_seq = 0; endfunction
  function automatic bit is_seq(input [3:0] c, input [31:0] d); return c == 4'b0001 && d[7:0] == 8'h9c; endfunction
  function automatic bit is_idle(input [3:0] c, input [31:0] d); return c == 4'b1111 && d == 32'h07070707; endfunction
  function automatic bit can_delete(input [3:0] c, input [31:0] d);
    bit ok, has_t;
    has_t = 0;
    for (int k = 0; k < 4; k++) if (c[k] && d[8*k +: 8] == 8'hfd) has_t = 1;
    ok = (is_idle(c, d) && !guard) || (is_seq(c, d) && prev_seq);
    guard = has_t;                                     // the next column holds some of the four characters after /T/
    prev_seq = is_seq(c, d) && !ok;                    // only one of the two
    return ok;
  endfunction
  function automatic bit can_insert(input [3:0] c, input [31:0] d); return is_idle(c, d) || is_seq(c, d); endfunction
endmodule

// eth_66_scr: the scrambler and the descrambler of 10GBASE-R (49.2.6, 49.2.10; Figures 49-8 and 49-10).
// The register is s[57:0]: stage S0 is s[0] and holds the newest line bit. Use one instance to scramble and
// another to descramble.
//   scr_bit(b)       one payload bit in, one line bit out: b XOR S38 XOR S57. The line bit shifts into S0.
//   dscr_bit(b)      one line bit in, one payload bit out: the same XOR. The received bit shifts into S0.
//   scramble(blk)    a whole block: bits 1:0 (the sync header) pass, bits 2 to 65 are scrambled in that order
//   descramble(blk)  the reverse
//   load(v)          sets the register (the standard asks for no start value)
// Fault: scrambles_header (the two sync header bits go through the scrambler too).
module eth_66_scr;
  bit [57:0] s = 58'd0;
  bit scrambles_header = 0;
  function automatic void load(input [57:0] v); s = v; endfunction
  function automatic bit scr_bit(input bit b);
    bit o; o = b ^ s[38] ^ s[57]; s = {s[56:0], o}; return o;
  endfunction
  function automatic bit dscr_bit(input bit b);
    bit o; o = b ^ s[38] ^ s[57]; s = {s[56:0], b}; return o;
  endfunction
  function automatic [65:0] scramble(input [65:0] blk);
    reg [65:0] o; o = blk;
    for (int i = scrambles_header ? 0 : 2; i < 66; i++) o[i] = scr_bit(blk[i]);
    return o;
  endfunction
  function automatic [65:0] descramble(input [65:0] blk);
    reg [65:0] o; o = blk;
    for (int i = 2; i < 66; i++) o[i] = dscr_bit(blk[i]);
    return o;
  endfunction
endmodule

// eth_prbs31: the PRBS31 pattern generator (49.2.8, Figure 49-9). The register is s[30:0], stage S0 is s[0].
//   gen_bit()   the next pattern bit: S27 XOR S30 shifts into S0, and the output is that bit inverted
// The register must not be all zeros: it would stay there. The checker is not in this file.
module eth_prbs31;
  bit [30:0] s = 31'h7fffffff;
  function automatic bit gen_bit();
    bit f; f = s[27] ^ s[30]; s = {s[29:0], f}; return !f;
  endfunction
endmodule

// eth_66_test: the square wave of 49.2.8 and the two data patterns of the pseudo-random test pattern.
//   sq_bit()        square wave: sq_n ones, then sq_n zeros (sq_n may be 4 to 11)
//   pattern()       the 64-bit data pattern: zeros, or the payload of a block with two local fault sets (lf_pattern)
// The pseudo-random pattern generator and its checker (49.2.8, 49.2.12) are not in this file.
module eth_66_test;
  eth_66 code();
  bit lf_pattern = 0;
  int sq_n = 8, sq_k = 0;
  function automatic void restart(); sq_k = 0; endfunction
  function automatic bit sq_bit();
    bit b; b = (sq_k < sq_n); sq_k = (sq_k + 1) % (2 * sq_n); return b;
  endfunction
  function automatic [63:0] pattern();
    reg [66:0] r;
    if (!lf_pattern) return 64'd0;
    r = code.enc_ctrl({64'h0100009c_0100009c, 8'h11}); return r[65:2];
  endfunction
endmodule

// eth_66_loop: PCS loopback (49.2.14.4), switched by MDIO bit 3.0.14.
//   rx_block(from_tx, from_pma)   what the receive path decodes: its own transmit block when loopback is 1
//   pma_word(w)                   what goes to the PMA: the word 00FFh when loopback is 1, else w
module eth_66_loop;
  bit loopback = 0;
  function automatic [65:0] rx_block(input [65:0] from_tx, input [65:0] from_pma); return loopback ? from_tx : from_pma; endfunction
  function automatic [15:0] pma_word(input [15:0] w); return loopback ? 16'h00ff : w; endfunction
endmodule
Read included file: eth_link.sv
`timescale 1ns/1ns
// eth_link.sv: link bring-up models (read-only).

// eth_an37: the arbitration of Clause 37 auto-negotiation for one port (Figure 37-6, without Next Pages).
// One call of step() per received ordered set.
//   adv                the base page to advertise: D5 full duplex, D6 half duplex, D7 PAUSE, D8 ASM_DIR,
//                      D13 D12 remote fault. The model drives D14 (Acknowledge) itself and sends D15 as 0.
//   reset()            AN_ENABLE (power-on, or a restart asked by management)
//   step(kind, word)   kind 0: a /C/ ordered set carrying word; 1: an /I/; 2: anything else
//   xmit               what the port sends now: 0 = /C/ carrying tx_word, 1 = /I/, 2 = data (the link is up)
//   state              0 AN_ENABLE, 1 AN_RESTART, 2 ABILITY_DETECT, 3 ACKNOWLEDGE_DETECT,
//                      4 COMPLETE_ACKNOWLEDGE, 5 IDLE_DETECT, 6 LINK_OK
//   lp_adv, page_rx    the partner's base page, stored on entry to COMPLETE_ACKNOWLEDGE
//   an_complete, restarts
//   link_timer         in calls of step(). Bench value 100; the standard's timer is 10 ms (37.3.1.4).
// The match functions follow 37.3.1.2: three ordered sets in a row; the counts restart on each state entry.
// What the two ends then enable (duplex, pause) is not in this model.
module eth_an37;
  bit [15:0] adv = 16'h0020;
  int link_timer = 100;
  int state = 0, xmit = 0, t = 0, restarts = 0;
  bit [15:0] tx_word = 0, lp_adv = 0, rx_word = 0, am_word = 0, ab_word = 0, ak_word = 0;
  int am_cnt = 0, ak_cnt = 0, id_cnt = 0;
  bit page_rx = 0, an_complete = 0;
  function automatic void enter(input int s);
    state = s; t = 0; am_cnt = 0; ak_cnt = 0; id_cnt = 0;
    case (s)
      0: begin xmit = 0; tx_word = 16'h0000; page_rx = 0; an_complete = 0; restarts++; end
      1: begin xmit = 0; tx_word = 16'h0000; end
      2: begin xmit = 0; tx_word = adv & 16'h3fff; end
      3: begin xmit = 0; tx_word = (adv & 16'h3fff) | 16'h4000; end
      4: begin lp_adv = rx_word; page_rx = 1; end
      5: xmit = 1;
      default: begin xmit = 2; an_complete = 1; end
    endcase
  endfunction
  function automatic void reset(); enter(0); restarts = 0; endfunction
  function automatic void step(input int kind, input [15:0] word);
    bit ability, ack, consistent, idle3, zero, done;
    t++;
    if (kind == 0) begin
      rx_word = word; id_cnt = 0;
      // ability_match ignores the Acknowledge bit (D14)
      if (am_cnt > 0 && (word & 16'hbfff) == am_word) begin if (am_cnt < 3) am_cnt++; end
      else begin am_word = word & 16'hbfff; am_cnt = 1; end
      // acknowledge_match needs the whole word to repeat with D14 set
      if (!word[14]) ak_cnt = 0;
      else if (ak_cnt > 0 && word == ak_word) begin if (ak_cnt < 3) ak_cnt++; end
      else begin ak_word = word; ak_cnt = 1; end
    end
    else begin
      am_cnt = 0; ak_cnt = 0;
      if (kind == 1) begin if (id_cnt < 3) id_cnt++; end else id_cnt = 0;
    end
    ability = am_cnt == 3; ack = ak_cnt == 3; idle3 = id_cnt == 3;
    zero = ability && am_word == 16'h0000 && !rx_word[14];
    consistent = (ak_word & 16'hbfff) == ab_word;
    done = t >= link_timer;
    case (state)
      0: enter(1);
      1: if (done) enter(2);
      2: if (ability && !zero) begin ab_word = am_word; enter(3); end
      3: begin
        if (zero || (ack && !consistent)) enter(0);
        else if (ack) enter(4);
      end
      4: begin
        if (zero) enter(0);
        else if (done) enter(5);
      end
      5: begin
        if (zero) enter(0);
        else if (idle3 && done) enter(6);
      end
      default: if (ability) enter(0);
    endcase
  endfunction
endmodule
ConceptWhich bits of the base page carry Remote Fault?
ConceptHow long is link_timer?
ConceptBoth ports advertise FD and HD. Which duplex do they use?
ConceptA link is up. The port receives three matching configuration words. What happens?

Common Mistakes

Wrong Act on the first configuration word received.

One bit error would then set the duplex or pause mode.

Fix Wait for three matching words in a row.

Wrong Compare the Ack bit when testing ability_match.

The partner sets Ack halfway through; the match would break and restart.

Fix Ignore D14 for ability_match. Require it for acknowledge_match.

Wrong Enable pause because both ports set ASM_DIR.

ASM_DIR alone only offers a direction. Table 37-4 also needs PAUSE on at least one side.

Fix Apply the whole table. This course applies it only in full duplex (Annex 31B, 28B.3); Clause 37 is silent on that.

Wrong Advertise the page 0000h to mean "no abilities".

If both ends do it, neither leaves ABILITY_DETECT. If one does, the link comes up with no common duplex.

Fix Advertise at least one duplex mode the port really has.

Remember

  • The base page is 16 bits: FD, HD, PAUSE, ASM_DIR, two Remote Fault bits, Ack and NP.
  • It travels in /C1/ and /C2/ ordered sets, low octet first.
  • Every step needs three matching words; the timed steps each last one 10 ms link_timer.
  • A zero word means restart. Full duplex beats half; pause follows Table 37-4.
  • SGMII reuses the word: the PHY reports link, duplex and speed, the MAC answers 4001h, and link_timer is 1.6 ms.

Practice

Report a problem with this page