Frame Preemption: The MAC Merge Sublayer

An urgent frame should not wait behind a long one. Frame preemption cuts the long frame, sends the urgent one, and then goes on. See how the pieces are marked and joined.

You Will Be Able To

  • Say what the eMAC, the pMAC and the MAC Merge sublayer do.
  • Read an mPacket: preamble, SMD, frag_count, mData and CRC.
  • Tell an mCRC from an FCS, and say what each one means.
  • Follow the receiver through a cut frame, and through each error.
Lesson
P11.44
Time
45 min
Runs on
Your browser
Check
5 questions

A frame of 1,518 octets holds a 100 Mb/s link for about 121 µs. An urgent frame behind it must wait.

In the bench, the wait falls from 1,530 octet times to at most 135.

An Express Frame Cuts InThree mPackets on the line, in the order they are sent. The long frame has 200 octets.
012mPacketfirstsecondthirdstarts withSMD-S0SMD-ESMD-C0, frag_count 0carriesits first 100 octetsexpress, 64 octetsits other 96 octetsends withmCRCits own FCSthe long frame's FCS
Scroll horizontally ↔
  1. mPacket 0

    The long frame starts. After 100 octets the sender stops and adds a check value that says: more will come.

  2. mPacket 1

    The express frame goes out. It looks like any Ethernet packet.

  3. mPacket 2

    The long frame goes on, and ends with its own FCS.

Bench run of the readable example (eth_mm_tx).

One Long Frame Blocks Everything

Ethernet sends a frame in one go. Once it has started, nothing else can use the link.

Frame preemption lets a MAC stop a long frame part way (99.1).

It is optional. It needs a full-duplex link from one port to one other, at 100 Mb/s or more.

Frame on the lineWait without preemptionWith it, before the first cutWith it, at worst
1,518 octets1,530 octet times76 octet times135 octet times
183 octets195 octet times76 octet times135 octet times
182 octets194 octet times76 octet times134 octet times
124 octets136 octet times76 octet times76 octet times
123 octets135 octet times135 octet times135 octet times
64 octets76 octet times76 octet times76 octet times

Bench arithmetic on the readable model: the longest wait of an express frame, with addFragSize 0. Counted from the first mData octet of a part.

The third column holds until the first cut.

After a cut, a part with 123 octets left cannot be cut again (IEEE 802.1Q Annex S.2).

So the worst wait is 123 octet times and a gap of 12.

The gain is largest on slow links. At 10 Gb/s a long frame lasts only about 1.2 µs.

Two MACs, One PHY

Two MACs Share One PHYThe transmit side on the left, the receive side on the right.
  • Storage
  • Datapath
  • Data
Two MACs share one PHYThe transmit side on the left, the receive side on the right. storage Express traffic urgent frames storage Preemptabletraffic everything else datapath eMAC a full MAC datapath pMAC a full MAC datapath MAC Merge cuts and joins datapath RS and PHY one link datapath MAC Merge at the partner framesframespacketspacketsmPacketsthe line
  1. storage Express trafficurgent frames
    • frames → eMAC
  2. storage Preemptable trafficeverything else
    • frames → pMAC
  3. datapath eMACa full MAC
    • packets → MAC Merge
  4. datapath pMACa full MAC
    • packets → MAC Merge
  5. datapath MAC Mergecuts and joins
    • mPackets → RS and PHY
  6. datapath RS and PHYone link
    • the line → MAC Merge
  7. datapath MAC Mergeat the partner
  1. Two MACs

    Each class has a MAC of its own, which builds whole packets.

  2. Merge

    The MAC Merge sublayer picks which one sends. It may cut a packet of the pMAC.

  3. One link

    The PHY sees ordinary packets. The partner sorts them by the octet after the preamble.

Read the diagram as text
  • Express traffic: urgent frames
  • Preemptable traffic: everything else
  • eMAC: a full MAC
  • pMAC: a full MAC
  • MAC Merge: cuts and joins
  • RS and PHY: one link
  • MAC Merge: at the partner
  • Express traffic → eMAC: frames
  • Preemptable traffic → pMAC: frames
  • eMAC → MAC Merge: packets
  • pMAC → MAC Merge: packets
  • MAC Merge → RS and PHY: mPackets
  • RS and PHY → MAC Merge: the line

Our own drawing after IEEE Std 802.3-2022 99.1 and Figure 99-2.

The port has two MACs. The eMAC carries express traffic. The pMAC carries preemptable traffic.

The MAC Merge sublayer sits below them and joins them to one RS (99.1).

IEEE 802.1Q says which priorities are express.

An express packet is not changed at all. A partner without the sublayer reads it as a normal packet.

Preemption is used only after the partner has said that it can receive it (99.4.2).

The mPacket

What the sublayer sends is called an mPacket (99.3).

FieldExpress, whole or first partA later part
Preamble7 octets of 55h6 octets of 55h
SMD1 octet1 octet
frag_countnone1 octet
mData60 octets or more60 octets or more
CRC4 octets4 octets

IEEE Std 802.3-2022 Figure 99-4. Both headers are eight octets long.

The SMD stands where the SFD used to be. It says what kind of mPacket this is.

A later piece has one preamble octet less and a frag_count octet more.

mData is the frame from its first octet up to, but not with, the FCS.

The SMD Says What Follows

mPacketNameFrame countSMD
VerifySMD-V07h
RespondSMD-R19h
Express packetSMD-ED5h
Start of a preemptable packetSMD-S00E6h
SMD-S114Ch
SMD-S227Fh
SMD-S33B3h
Continuation fragmentSMD-C0061h
SMD-C1152h
SMD-C229Eh
SMD-C332Ah

IEEE Std 802.3-2022 Table 99-1.

SMD-E is D5h, the normal SFD. So an express packet needs no change (99.3.3).

The start of a preemptable packet carries a frame count from 0 to 3. Its later pieces carry the same count.

That stops the receiver from joining pieces of two frames.

By our count, any two codes of the table differ in at least 4 bits.

So one wrong bit never turns a code into another one.

But SMD-E with its top bit wrong is 55h, a preamble octet.

frag_count: Which Piece Is This?

The frame count tells frames apart. The fragment count tells the pieces of one frame apart (99.3.4).

Fragment countfrag_count octet
0E6h
14Ch
27Fh
3B3h

IEEE Std 802.3-2022 Table 99-2.

The first continuation fragment carries 0. Each one after it carries one more, modulo 4.

With this count the receiver notices when up to three pieces in a row are lost.

mCRC: More Will Come

Every mPacket ends in four CRC octets (99.3.6).

In the last piece they are the FCS of the frame.

In every other piece they are an mCRC. It covers all data of the frame sent so far.

The mCRC is built like the FCS, but the last step differs (3.2.9).

The FCS inverts all 32 bits of the remainder. The mCRC inverts only its 16 low-order bits.

The first 100 octets of the frameOctet 1Octet 2Octet 3Octet 4
End of the frame: FCS of these octetsDB877523
More will come: mCRC of these octets24787523

Bench run of the readable example, in the order sent.

The CRC is sent high-order bits first. So the first two octets differ, and the last two are equal.

Where May the Transmitter Cut?

No piece may be shorter than the smallest Ethernet frame: 64 octets with its CRC.

A cut is allowed when two things hold (99.4.4).

The mPacket has carried 64 × (1 + addFragSize) − 4 octets of mData.

And 64 octets of the frame are still to come, the FCS among them.

addFragSizeA part holds at leastFirst cut afterSmallest frame that can be cut
064 octets60 octets of mData124 octets
1128 octets124 octets of mData188 octets
2192 octets188 octets of mData252 octets
3256 octets252 octets of mData316 octets

Bench run of may_cut in the readable model. A part is counted with its CRC.

addFragSize is the receiver's wish. It tells the sender in an LLDP TLV (79.3.7).

The Receiver Puts It Together

The Receiver, Between Two PiecesReceive Processing in five boxes.
  • Control / FSM
  • Control
The receiver, between two piecesReceive Processing in five boxes. control Idle next count: 0 control Receive data octets to the pMAC control Frame complete last four octets too control Wait for resume the mCRC is dropped control Assembly error the frame is spoilt SMD-Sends, not in the mCRCends in the mCRCright SMD-C, rightcountwrong SMD-C orcount
  1. control Idlenext count: 0
    • SMD-S → Receive data
  2. control Receive dataoctets to the pMAC
    • ends, not in the mCRC → Frame complete
    • ends in the mCRC → Wait for resume
  3. control Frame completelast four octets too
    • Idle
  4. control Wait for resumethe mCRC is dropped
    • right SMD-C, right count → Receive data
    • wrong SMD-C or count → Assembly error
  5. control Assembly errorthe frame is spoilt
    • Idle
  1. Start

    An SMD-S starts a frame. The receiver notes its frame count.

  2. Ends

    No mCRC: the frame is over. The last four octets go to the pMAC, which checks them as an FCS.

  3. Cut

    An mCRC: the frame was cut. The four octets are dropped, and the receiver waits.

  4. Resume

    The next piece must carry the same frame count and the next fragment count.

  5. Give up

    If not, the frame is spoilt, so that the pMAC throws it away.

Read the diagram as text
  • Idle: next count: 0
  • Receive data: octets to the pMAC
  • Frame complete: last four octets too
  • Wait for resume: the mCRC is dropped
  • Assembly error: the frame is spoilt
  • Idle → Receive data: SMD-S
  • Receive data → Frame complete: ends, not in the mCRC
  • Receive data → Wait for resume: ends in the mCRC
  • Wait for resume → Receive data: right SMD-C, right count
  • Wait for resume → Assembly error: wrong SMD-C or count
  • Frame complete → Idle
  • Assembly error → Idle

Our own drawing after IEEE Std 802.3-2022 Figure 99-6 and 99.4.5.

Two parts look at every mPacket. The express filter passes SMD-E packets to the eMAC (99.4.6).

Receive processing serves the pMAC. It hands on the data and hides the cuts (99.4.5).

An express packet between two pieces changes nothing for the frame that waits.

While a frame waits, this arrivesWhat Receive Processing doesCounter
SMD-Enothing: the express filter takes the packet
SMD-V or SMD-Rpasses it over (a course choice: the figure has no exit)
An octet that is no SMDpasses the mPacket over and waits onSMD errors
SMD-C, same frame countchecks the frag_countfragments received
then: the next fragment counttakes the data
then: any other frag_countspoils the frameassembly errors
SMD-C, other frame countspoils the frameassembly errors
SMD-S, and the receiver can keep itspoils the old frame and starts the new one
SMD-S, and it cannotspoils the old frame and drops the new mPacketassembly errors

IEEE Std 802.3-2022 Figure 99-6 and 30.14.1.8 to 30.14.1.11.

A spoilt frame reaches the pMAC with a wrong FCS.

An SMD-S in the middle of a frame means that the rest was lost.

Some receivers can take the new frame at once. The standard calls that ability keepSafterD.

When a Piece Goes Missing

What goes wrongGood frames at the pMACExpress frames at the eMACAssembly errorsSMD errorsAssembly OKFragments received
Nothing220023
The second part of A is lost121012
The last part of A is lost; the receiver can keep an SMD-S021002
The same; it cannot021101
One wrong bit in the SMD of A's second part121112
One wrong bit in the data of A's first part120211
One wrong bit in a frag_count of A121112

Bench run of a private model. Frame A has three parts with two express frames between them, then frame B has two.

In most rows one fault costs one frame. The two express frames arrive in every row.

A wrong bit in the first part spoils its mCRC. So the receiver takes that part for a whole frame.

The later parts then find no frame waiting. Each is counted as an SMD error.

Third row: frame B was complete on the line, yet it is lost too.

The reason is in Figure 99-6. The next fragment count is set to 0 in one state only, IDLE_RX_PROC.

A frame that starts while another waits skips that state. It inherits the old count, and its first continuation is refused.

This page follows the figure to the letter (99.4.7.1). The text of 99.3.4 would let you expect 0.

It looks like a gap in the standard: 99.4.7.3 does not even define this variable.

Six Counters

Management reads six counters from the sublayer (30.14).

AttributeCountsClause
aMACMergeFrameAssErrorCountentries to ASSEMBLY_ERROR30.14.1.8
aMACMergeFrameSmdErrorCountentries to BAD_FRAG, and no SMD while a frame waits30.14.1.9
aMACMergeFrameAssOkCountframes that were put together and handed on30.14.1.10
aMACMergeFragCountRxentries to CHECK_FRAG_CNT30.14.1.11
aMACMergeFragCountTxcontinuation mPackets sent30.14.1.12
aMACMergeHoldCounttimes that hold went from false to true30.14.1.13

IEEE Std 802.3-2022 30.14.1.8 to 30.14.1.13.

"Assembly OK" counts frames, not good frames. It asks only that the frame had been cut.

Read to the letter, 30.14.1.10 could also count a frame that started while another one waited. This course does not.

"Fragments received" goes up before the frag_count is checked. So it also counts pieces that are then refused.

Is the Partner Ready?

A cut frame would confuse a device in the path that does not expect it. So the link is tested first.

StepWhat happens
Discoverthe partner says in LLDP that it has the sublayer
Verifythis port sends an mPacket with SMD-V: 60 octets of 00h and an mCRC
Respondthe partner answers with SMD-R, built the same way
Verifiedthe answer arrives with a correct mCRC: preemption becomes active
No answertry again after verifyTime, 10 ms by default. After 3 tries: failed

IEEE Std 802.3-2022 99.4.2, 99.4.3 and Figure 99-8.

Verify and respond mPackets go to neither MAC. The express filter takes them out (99.4.6).

Verification can be switched off for a known network (99.4.3).

Hold and Release

The client can also clear the line in advance.

It asks with MM_CTL.request: hold or release (99.2).

Hold cuts the preemptable frame if the rules allow. No new one starts until release.

A hold takes effect within 1,240 + 512 × addFragSize bit times (99.4.8).

With addFragSize 0 that is 155 octet times.

A scheduler uses this to keep a time window free (P11.45).

Try It

eth_mm_tx is the transmit side as a model. load makes a frame of 200 octets with its FCS.

piece(100) sends the first 100 octets: preamble, SMD-S0, mData and the mCRC.

express sends a normal packet. Its SMD is D5h.

piece(96) sends the rest. The header is now six preamble octets, SMD-C0 and frag_count 0.

This piece reaches the end of the frame. So its last four octets are the frame's own FCS.

The bench then joins the mData of both pieces and the FCS. It gets the frame back.

The last line shows the two endings for the same 100 octets.

The receiver is not in the readable library. It is the practice problem.

Change piece(100) to piece(150) and piece(96) to piece(46). Which rule of this lesson does the new cut break?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: mPacket 0: 7 preamble, SMD-S0, 100 octets of mData, mCRC 24787523 mPacket 1: 7 preamble, SMD-E, an express frame of 64 octets mPacket 2: 6 preamble, SMD-C0, frag_count e6, 96 octets of mData, FCS dad800b6 joined: 200 octets, the frame as it was the first 100 octets: as a last part they would end in db 87 75 23, as a first part they end in 24 78 75 23
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_mm.sv
`timescale 1ns/1ns
// eth_mm.sv: the transmit side of the MAC Merge sublayer (read-only). A bench model in whole octets.

// eth_mm_tx: cuts a preemptable frame into mPackets and sends express frames between them (99.3, 99.4.4).
//   smd_s(fc), smd_c(fc), frag_code(n)   the codes of Tables 99-1 and 99-2
//   name(octet)                          "SMD-S0", "SMD-E", "preamble", ... or "no SMD"
//   load(len, seed)                      a new preemptable frame of len octets, DA to FCS; the FCS is worked out
//   may_cut(s)                           may the mPacket that is on its way stop after s octets of mData? (99.4.4)
//   piece(n)                             sends the next n octets of mData as one mPacket: SMD-S, or SMD-C and
//                                        frag_count, in front; the mCRC behind, or the FCS when the frame ends here
//   express(len, seed)                   sends an express frame of len octets
//   fcs(n)                               the FCS of frame[0 .. n-1], as it goes on the line: bits 7:0 first
//   line[], nline                        every octet sent. pk_at[k], pk_len[k], npk: where mPacket k lies
module eth_mm_tx;
  int add_frag_size = 0;             // addFragSize, 0 to 3, asked for by the link partner
  reg [7:0] frame [0:2047];          // the preemptable frame, DA to FCS
  int flen = 0, sent = 0;            // its length, and the octets of mData sent so far
  int tx_frame = 0, tx_frag = 0;     // txFrame and txFrag of Figure 99-5
  reg [7:0] line [0:8191];
  int nline = 0, npk = 0;
  int pk_at [0:63], pk_len [0:63];
  function automatic [7:0] smd_s(input int fc);
    case (fc & 3) 0: return 8'he6; 1: return 8'h4c; 2: return 8'h7f; default: return 8'hb3; endcase
  endfunction
  function automatic [7:0] smd_c(input int fc);
    case (fc & 3) 0: return 8'h61; 1: return 8'h52; 2: return 8'h9e; default: return 8'h2a; endcase
  endfunction
  function automatic [7:0] frag_code(input int n); return smd_s(n); endfunction
  function automatic string name(input [7:0] v);
    case (v)
      8'h55: return "preamble";
      8'h07: return "SMD-V";
      8'h19: return "SMD-R";
      8'hd5: return "SMD-E";
      8'he6: return "SMD-S0";
      8'h4c: return "SMD-S1";
      8'h7f: return "SMD-S2";
      8'hb3: return "SMD-S3";
      8'h61: return "SMD-C0";
      8'h52: return "SMD-C1";
      8'h9e: return "SMD-C2";
      8'h2a: return "SMD-C3";
      default: return "no SMD";
    endcase
  endfunction
  // CRC-32 of frame[0 .. n-1] (3.2.9), in the usual form: the first octet on the line is bits 7:0.
  function automatic [31:0] fcs(input int n);
    reg [31:0] c;
    c = 32'hffffffff;
    for (int i = 0; i < n; i++) begin
      c = c ^ {24'd0, frame[i]};
      for (int b = 0; b < 8; b++) c = c[0] ? ((c >> 1) ^ 32'hedb88320) : (c >> 1);
    end
    return ~c;
  endfunction
  // The mCRC of the first n octets (99.3.6): the remainder before its last inversion, with the 16 low-order
  // coefficients inverted. Beside the FCS of the same octets, the first two octets on the line are inverted.
  function automatic [31:0] mcrc(input int n); return fcs(n) ^ 32'h0000ffff; endfunction
  function automatic void load(input int len, input int seed);
    reg [31:0] c;
    flen = len; sent = 0; tx_frag = 0;
    for (int i = 0; i < len - 4; i++) frame[i] = 8'(i * 7 + seed * 29 + 3) ^ 8'(i >> 3);
    c = fcs(len - 4);
    for (int k = 0; k < 4; k++) frame[len - 4 + k] = c[8 * k +: 8];
  endfunction
  // 99.4.4: the mPacket has carried 64 x (1 + addFragSize) - 4 octets of mData, and 64 octets are left, FCS included.
  function automatic bit may_cut(input int s);
    return (s >= 64 * (1 + add_frag_size) - 4) && (flen - (sent + s) >= 64);
  endfunction
  function automatic void put(input [7:0] v); line[nline] = v; nline++; endfunction
  function automatic void piece(input int n);
    reg [31:0] c; bit last;
    pk_at[npk] = nline;
    last = (sent + n >= flen - 4);
    if (sent == 0) begin
      for (int i = 0; i < 7; i++) put(8'h55);
      put(smd_s(tx_frame));
    end else begin
      for (int i = 0; i < 6; i++) put(8'h55);
      put(smd_c(tx_frame)); put(frag_code(tx_frag));
      tx_frag = (tx_frag + 1) % 4;
    end
    for (int i = 0; i < n; i++) put(frame[sent + i]);
    sent += n;
    if (last) begin
      for (int k = 0; k < 4; k++) put(frame[flen - 4 + k]);
      tx_frame = (tx_frame + 1) % 4;
    end else begin
      c = mcrc(sent);
      for (int k = 0; k < 4; k++) put(c[8 * k +: 8]);
    end
    pk_len[npk] = nline - pk_at[npk]; npk++;
  endfunction
  function automatic void express(input int len, input int seed);
    reg [31:0] c; reg [7:0] v;
    pk_at[npk] = nline;
    for (int i = 0; i < 7; i++) put(8'h55);
    put(8'hd5);
    c = 32'hffffffff;                                  // an express frame has its own FCS
    for (int i = 0; i < len - 4; i++) begin
      v = 8'(i * 5 + seed * 17 + 1); put(v);
      c = c ^ {24'd0, v};
      for (int b = 0; b < 8; b++) c = c[0] ? ((c >> 1) ^ 32'hedb88320) : (c >> 1);
    end
    c = ~c;
    for (int k = 0; k < 4; k++) put(c[8 * k +: 8]);
    pk_len[npk] = nline - pk_at[npk]; npk++;
  endfunction
endmodule

Check Yourself

Predict the outputA frame of 300 octets is sent in pieces of 60 octets. The bench prints the SMD and the next octet of the third mPacket. What does it print?
`timescale 1ns/1ns
module tb;
  eth_mm_tx tx();
  initial begin
    tx.load(300, 2); tx.piece(60); tx.piece(60); tx.piece(60);
    $display("%s %h", tx.name(tx.line[tx.pk_at[2] + 6]), tx.line[tx.pk_at[2] + 7]);
    $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_mm.sv
`timescale 1ns/1ns
// eth_mm.sv: the transmit side of the MAC Merge sublayer (read-only). A bench model in whole octets.

// eth_mm_tx: cuts a preemptable frame into mPackets and sends express frames between them (99.3, 99.4.4).
//   smd_s(fc), smd_c(fc), frag_code(n)   the codes of Tables 99-1 and 99-2
//   name(octet)                          "SMD-S0", "SMD-E", "preamble", ... or "no SMD"
//   load(len, seed)                      a new preemptable frame of len octets, DA to FCS; the FCS is worked out
//   may_cut(s)                           may the mPacket that is on its way stop after s octets of mData? (99.4.4)
//   piece(n)                             sends the next n octets of mData as one mPacket: SMD-S, or SMD-C and
//                                        frag_count, in front; the mCRC behind, or the FCS when the frame ends here
//   express(len, seed)                   sends an express frame of len octets
//   fcs(n)                               the FCS of frame[0 .. n-1], as it goes on the line: bits 7:0 first
//   line[], nline                        every octet sent. pk_at[k], pk_len[k], npk: where mPacket k lies
module eth_mm_tx;
  int add_frag_size = 0;             // addFragSize, 0 to 3, asked for by the link partner
  reg [7:0] frame [0:2047];          // the preemptable frame, DA to FCS
  int flen = 0, sent = 0;            // its length, and the octets of mData sent so far
  int tx_frame = 0, tx_frag = 0;     // txFrame and txFrag of Figure 99-5
  reg [7:0] line [0:8191];
  int nline = 0, npk = 0;
  int pk_at [0:63], pk_len [0:63];
  function automatic [7:0] smd_s(input int fc);
    case (fc & 3) 0: return 8'he6; 1: return 8'h4c; 2: return 8'h7f; default: return 8'hb3; endcase
  endfunction
  function automatic [7:0] smd_c(input int fc);
    case (fc & 3) 0: return 8'h61; 1: return 8'h52; 2: return 8'h9e; default: return 8'h2a; endcase
  endfunction
  function automatic [7:0] frag_code(input int n); return smd_s(n); endfunction
  function automatic string name(input [7:0] v);
    case (v)
      8'h55: return "preamble";
      8'h07: return "SMD-V";
      8'h19: return "SMD-R";
      8'hd5: return "SMD-E";
      8'he6: return "SMD-S0";
      8'h4c: return "SMD-S1";
      8'h7f: return "SMD-S2";
      8'hb3: return "SMD-S3";
      8'h61: return "SMD-C0";
      8'h52: return "SMD-C1";
      8'h9e: return "SMD-C2";
      8'h2a: return "SMD-C3";
      default: return "no SMD";
    endcase
  endfunction
  // CRC-32 of frame[0 .. n-1] (3.2.9), in the usual form: the first octet on the line is bits 7:0.
  function automatic [31:0] fcs(input int n);
    reg [31:0] c;
    c = 32'hffffffff;
    for (int i = 0; i < n; i++) begin
      c = c ^ {24'd0, frame[i]};
      for (int b = 0; b < 8; b++) c = c[0] ? ((c >> 1) ^ 32'hedb88320) : (c >> 1);
    end
    return ~c;
  endfunction
  // The mCRC of the first n octets (99.3.6): the remainder before its last inversion, with the 16 low-order
  // coefficients inverted. Beside the FCS of the same octets, the first two octets on the line are inverted.
  function automatic [31:0] mcrc(input int n); return fcs(n) ^ 32'h0000ffff; endfunction
  function automatic void load(input int len, input int seed);
    reg [31:0] c;
    flen = len; sent = 0; tx_frag = 0;
    for (int i = 0; i < len - 4; i++) frame[i] = 8'(i * 7 + seed * 29 + 3) ^ 8'(i >> 3);
    c = fcs(len - 4);
    for (int k = 0; k < 4; k++) frame[len - 4 + k] = c[8 * k +: 8];
  endfunction
  // 99.4.4: the mPacket has carried 64 x (1 + addFragSize) - 4 octets of mData, and 64 octets are left, FCS included.
  function automatic bit may_cut(input int s);
    return (s >= 64 * (1 + add_frag_size) - 4) && (flen - (sent + s) >= 64);
  endfunction
  function automatic void put(input [7:0] v); line[nline] = v; nline++; endfunction
  function automatic void piece(input int n);
    reg [31:0] c; bit last;
    pk_at[npk] = nline;
    last = (sent + n >= flen - 4);
    if (sent == 0) begin
      for (int i = 0; i < 7; i++) put(8'h55);
      put(smd_s(tx_frame));
    end else begin
      for (int i = 0; i < 6; i++) put(8'h55);
      put(smd_c(tx_frame)); put(frag_code(tx_frag));
      tx_frag = (tx_frag + 1) % 4;
    end
    for (int i = 0; i < n; i++) put(frame[sent + i]);
    sent += n;
    if (last) begin
      for (int k = 0; k < 4; k++) put(frame[flen - 4 + k]);
      tx_frame = (tx_frame + 1) % 4;
    end else begin
      c = mcrc(sent);
      for (int k = 0; k < 4; k++) put(c[8 * k +: 8]);
    end
    pk_len[npk] = nline - pk_at[npk]; npk++;
  endfunction
  function automatic void express(input int len, input int seed);
    reg [31:0] c; reg [7:0] v;
    pk_at[npk] = nline;
    for (int i = 0; i < 7; i++) put(8'h55);
    put(8'hd5);
    c = 32'hffffffff;                                  // an express frame has its own FCS
    for (int i = 0; i < len - 4; i++) begin
      v = 8'(i * 5 + seed * 17 + 1); put(v);
      c = c ^ {24'd0, v};
      for (int b = 0; b < 8; b++) c = c[0] ? ((c >> 1) ^ 32'hedb88320) : (c >> 1);
    end
    c = ~c;
    for (int k = 0; k < 4; k++) put(c[8 * k +: 8]);
    pk_len[npk] = nline - pk_at[npk]; npk++;
  endfunction
endmodule
ConceptHow does a receiver know that a preemptable frame has ended?
ConceptBeside the FCS of the same octets, which octets of the mCRC differ?
ConceptA frame waits with frame count 1. An mPacket with SMD-C3 arrives. What does the receiver do?
ConceptaddFragSize is 1. What is the smallest frame that can be cut?

Common Mistakes

Wrong Correct an SMD that is one bit away from a valid code.

The standard treats every value outside the table as an error.

Fix Count an SMD error and pass the mPacket over.

Wrong Take the mCRC over the data of one mPacket.

It covers the frame from its first octet to the last octet sent so far.

Fix Keep one CRC running through all pieces of a frame.

Wrong Hand the mCRC octets to the pMAC.

They are not part of the frame. The frame's FCS would then fail.

Fix Drop the four octets when they match the mCRC.

Wrong Let an express packet reset the frame that waits.

Receive processing passes SMD-E over. The frame count and the fragment count stay.

Fix Keep every bit of state until the next SMD-C or SMD-S.

Remember

  • A port with preemption has an eMAC and a pMAC. The MAC Merge sublayer joins them to one PHY.
  • An mPacket starts with an SMD in the place of the SFD. A continuation adds a frag_count.
  • The last four octets are an mCRC when more will come, and the FCS when the frame ends.
  • The receiver checks the frame count and the fragment count of every continuation. A mismatch spoils the frame.
  • An octet that is no SMD is an error. Nothing is corrected.

Practice

Report a problem with this page