Precision Time Protocol

Two clocks on one cable never agree by themselves. The Precision Time Protocol lines them up with four timestamps. See where every nanosecond of the error goes.

You Will Be Able To

  • Name the four timestamps and the message that carries each.
  • Work out the mean path delay and the offset from the master.
  • Read the header of a PTP message and its correction field.
  • Explain why an asymmetric path leaves an error that PTP cannot see.
Lesson
P11.41
Time
45 min
Runs on
Your browser
Check
5 questions

A slave clock is 1.5 ms ahead of its master. Neither knows it.

One exchange of four timestamps finds the offset: 1,500,000 ns in the bench.

Four TimestampsTime runs down. The master is on the left and the slave on the right. Each clock stamps what it sends and what it receives.
  • Measure
  • Subordinate
  • Transaction / TLM
  • Structure
Four timestampsTime runs down. The master is on the left and the slave on the right. Each clock stamps what it sends and what it receives. measure t1 master: Sync leaves measure t2 slave: Sync arrives measure t3 slave: Delay_Reqleaves measure t4 master: Delay_Reqarrives subordinate Slave now holds all four Synca short waitDelay_ReqDelay_Resp carriest4
  1. measure t1master: Sync leaves
    • Sync → t2
  2. measure t2slave: Sync arrives
    • a short wait → t3
  3. measure t3slave: Delay_Req leaves
    • Delay_Req → t4
  4. measure t4master: Delay_Req arrives
    • Delay_Resp carries t4 → Slave
  5. subordinate Slavenow holds all four
  1. Sync

    The master sends a Sync and notes when it left: t1. The slave notes when it arrived: t2.

  2. Follow_Up

    The slave does not know t1 yet. A two-step master sends it in a second message, the Follow_Up.

  3. Delay_Req

    Now the other way. The slave sends a Delay_Req and notes t3. The master notes its arrival: t4.

  4. Delay_Resp

    The master sends t4 back in a Delay_Resp. The slave has four numbers and can do the sums.

Read the diagram as text
  • t1: master: Sync leaves
  • t2: slave: Sync arrives
  • t3: slave: Delay_Req leaves
  • t4: master: Delay_Req arrives
  • Slave: now holds all four
  • t1 → t2: Sync
  • t2 → t3: a short wait
  • t3 → t4: Delay_Req
  • t4 → Slave: Delay_Resp carries t4

Our own drawing after IEEE Std 1588-2019 Figure 41.

Two Clocks, Two Faults

A clock can be wrong in two ways. It can be off: it shows another time now.

And it can drift: its crystal runs a little fast or slow, so the error grows.

The bench slave starts 1,508,079 ns ahead. It gains 80 ns in every second: 80 parts per billion.

One second later it is 1,508,159 ns ahead.

The Precision Time Protocol (PTP) of IEEE Std 1588 measures the offset again and again. So the drift never gets far.

The clock that gives the time is the master. A clock that follows it is a slave.

Four Timestamps

One exchange gives the slave four timestamps (11.3).

TimestampClockReading
t1master100.999999700 s
t2slave101.001500200 s
t3slave101.001600200 s
t4master101.000100700 s

Bench run (p1141.ladder): the slave is 1.5 ms ahead and the cable takes 500 ns each way.

The master's clock makes t1 and t4. The slave's clock makes t2 and t3.

The slave already has t2 and t3. It gets t1 from the Sync or from the Follow_Up, and t4 from the Delay_Resp.

Offset and Delay from the Four

On the way down, the slave sees the path delay plus its own offset.

t2 − t1 = delay + offset. In the bench that is 1,500,500 ns.

On the way up, the offset counts the other way.

t4 − t3 = delay − offset. In the bench that is -1,499,500 ns.

Add the two and the offset cancels: twice the delay is 1,000 ns. So the mean path delay is 500 ns (11.3.2).

Take the delay off the way down: 1,500,500 − 500 = 1,500,000 ns. That is the offset from the master (11.2).

A positive offset means the slave is ahead.

A slave 250 ns behind gives 250 ns down and 750 ns up. The delay is again 500 ns, and the offset is -250 ns.

Time on the Wire

A PTP Timestamp has two fields: 48 bits of seconds and 32 bits of nanoseconds (5.3.3).

The nanoseconds are always below 1,000,000,000. So a difference needs a borrow from the seconds now and then.

In the bench t1 is 100.999999700 s and t2 is 101.001500200 s. The second has changed in between.

Small times use another type, the TimeInterval: nanoseconds times 65,536, as a signed 64-bit number (5.3.2).

So 2.5 ns is 28000h.

A value too large for the type is set to its largest value. One too negative is set to its most negative value.

The Messages

Every PTP message starts with the same header of 34 octets.

FieldOctetsOffset
majorSdoId and messageType10
minorVersionPTP and versionPTP11
messageLength22
domainNumber14
minorSdoId15
flagField26
correctionField88
messageTypeSpecific416
sourcePortIdentity1020
sequenceId230
controlField132
logMessageInterval133

IEEE Std 1588-2019 Table 35: the common header of every PTP message, 34 octets.

The low four bits of the first octet are the messageType. Fields go most significant octet first.

MessageTypeAfter the headerOctets
Sync0originTimestamp44
Delay_Req1originTimestamp44
Follow_Up8preciseOriginTimestamp44
Delay_Resp9receiveTimestamp, requestingPortIdentity54

IEEE Std 1588-2019 Tables 36 and 44 to 46. A timestamp is 10 octets at offset 34.

Sync and Delay_Req are event messages: they are stamped when they pass. The other two only carry numbers.

On Ethernet a PTP message is the client data of a frame with EtherType 88F7h (Annex E).

A Delay_Resp also names the port that asked, in requestingPortIdentity. Many slaves hear it, and only one uses it.

One Step or Two

The exact t1 is known only when the Sync is already leaving. Hardware can write it into the frame on the way out.

Such a port is one-step: the Sync itself carries t1 (9.5.9.4).

A two-step port cannot do that. Its Sync carries a rough time, or zero, and sets the twoStepFlag.

Then a Follow_Up brings the exact time, as the preciseOriginTimestamp (9.5.10).

The Follow_Up has the sequenceId of its Sync. That is how the slave pairs them (9.5.5).

Switches and the Correction Field

A switch holds a frame for a while, and not always for the same time. That delay is not cable.

A transparent clock is a switch that measures how long each event message stayed inside: the residence time (10.2.2).

It adds that time to the correctionField of the message, or of its Follow_Up.

The slave takes the correction fields off before it does its sums (11.2, 11.3.2).

The switch on the pathMean path delayError of the offset
a plain switch that says nothing2,100 ns1,400 ns
a transparent clock: residence time in the Sync500 ns0 ns
a transparent clock: residence time in the Follow_Up500 ns0 ns
the same with a one-step master500 ns0 ns

Bench run of a private model (p1141.tc). The switch holds the Sync for 3,000 ns and the Delay_Req for 200 ns. The cable takes 500 ns each way.

The plain switch makes the way down look 2,800 ns longer than the way up. Half of that ends up in the offset.

The correctionField is a TimeInterval, so it can also carry fractions of a nanosecond (13.3.2.9).

A Slave That Follows

What the slave does with the offset is its own business. The standard only asks that the offset be made small.

The bench does the simplest thing: after every exchange it steps the clock by the measured offset.

ExchangeSlave ahead byOffset it measuresLeft after the step
11,508,000 ns1,508,000 ns0 ns
210 ns10 ns0 ns
310 ns10 ns0 ns
410 ns10 ns0 ns
510 ns10 ns0 ns
610 ns10 ns0 ns

Bench run of a private model (p1141.servo). The slave gains 80 ns a second. Eight times a second it steps by the measured offset.

The first step takes away 1,508,000 ns. After that only the drift is left: 10 ns between two exchanges.

A real servo also trims the rate of the clock.

The Error PTP Cannot See

The sums assume that the path takes as long one way as the other. Often it does not.

The two directions differ byMean path delayError of the offset
0 ns500 ns0 ns
20 ns500 ns10 ns
80 ns500 ns40 ns
200 ns500 ns100 ns
1,000 ns500 ns500 ns

Bench run of a private model (p1141.asym). The mean of the two directions is 500 ns in every row. The way down is the longer one.

The mean path delay stays right. But the offset is wrong by half the difference, every time.

No message can show this.

So the difference must be measured once by other means and given to the port as its delayAsymmetry (7.4.2).

That value is half the difference. It is positive when the way down is the longer one.

The slave adds it to the correction of the Sync, and takes it off its Delay_Req (11.2, 11.3.2).

In the bench, 540 ns down and 460 ns up with a delayAsymmetry of 40 ns leave no error.

There is a second way to measure delay. It looks at one link only, between two neighbours (11.4).

Port A sends a Pdelay_Req and notes t1. Port B notes its arrival, t2, and the moment its answer leaves, t3.

Port A notes the arrival of the Pdelay_Resp: t4.

In the bench, t4 − t1 is 21,000 ns on the clock of A. The answer waited 20,000 ns inside B.

Take the wait off and halve: the mean link delay is 500 ns.

Each difference is taken on one clock. So it does not matter that B's clock is 7 ms ahead.

These messages go to the address 01-80-C2-00-00-0E, which a bridge does not pass on (Annex E).

Where the Stamp Is Taken

A timestamp is only as good as the moment it is taken.

The standard names that moment: the start of the first symbol after the start of frame delimiter (7.3.4.1).

A stamp taken in software, after the frame has been queued, is off by microseconds and never by the same amount.

So real ports stamp in hardware, close to the wire.

How often to send, and how good each clock must be, is set by a profile. ITU-T G.8275.1 is one, for telecom networks.

Try It

eth_ptp_clock is a clock with an offset and a drift. read gives its reading for a true time.

The slave starts 1,508,079 ns ahead. One second later it has gained 80 ns more.

ts turns a reading into a Timestamp: 64h seconds is 100, and 3B9AC8D4h is 999,999,700 ns.

eth_ptp_msg builds messages as octets. show reads four fields back by their offsets.

The Sync has flagField 0200h: bit 1 of the first octet is the twoStepFlag. Its own time is zero.

The Follow_Up has the same sequenceId, 7, and the exact time. Its correction field holds 2.5 ns.

The Delay_Resp is 10 octets longer: it also names the port that asked.

The sums for offset and delay are not in the readable library. They are the practice problems.

Change the drift to −200. Predict the second line.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: true time 100999999700 ns: master reads 100999999700, slave reads 101001507779 one second later the slave is 1508159 ns ahead the master's reading as a Timestamp: seconds 000000000064, nanoseconds 3b9ac8d4 Sync: type 0, 44 octets flagField at 6: 0200 correctionField at 8: 0000000000000000 sequenceId at 30: 7 timestamp at 34: seconds 0, nanoseconds 0 Follow_Up: type 8, 44 octets flagField at 6: 0000 correctionField at 8: 0000000000028000 sequenceId at 30: 7 timestamp at 34: seconds 100, nanoseconds 999999700 Delay_Resp: type 9, 54 octets flagField at 6: 0000 correctionField at 8: 0000000000000000 sequenceId at 30: 3 timestamp at 34: seconds 100, nanoseconds 999999700
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_ptp.sv
`timescale 1ns/1ns
// eth_ptp.sv: clocks and messages of the Precision Time Protocol (read-only). A bench model.

// eth_ptp_clock: a clock that starts off by some nanoseconds and runs a little fast or slow.
//   set(offset_ns, drift_ppb)    at true time 0 the clock is offset_ns ahead; it gains drift_ppb ns a second
//   read(true_ns)                what the clock shows at that true time, in nanoseconds
//   step(delta_ns)               move the clock by delta_ns
//   ts(ns)                       a reading as a PTP Timestamp: {seconds[47:0], nanoseconds[31:0]} (5.3.3)
module eth_ptp_clock;
  longint offset = 0; int drift = 0;
  function automatic void set(input longint offset_ns, input int drift_ppb);
    offset = offset_ns; drift = drift_ppb;
  endfunction
  function automatic longint read(input longint true_ns);
    return true_ns + offset + (true_ns / 1000) * drift / 1000000;
  endfunction
  function automatic void step(input longint delta_ns);
    offset = offset + delta_ns;
  endfunction
  function automatic [79:0] ts(input longint ns);
    reg [47:0] s; reg [31:0] n;
    s = ns / 1000000000; n = ns % 1000000000;
    return {s, n};
  endfunction
endmodule

// eth_ptp_msg: four PTP messages as octets (13.3, 13.6 to 13.8). A message is a vector of 54 octets. Octet 0 is
// bits 431:424 and goes first. A field goes most significant octet first. A message of 44 octets ends in zeros.
//   sync(two_step, seq, origin, corr, port)        Sync: originTimestamp at offset 34
//   follow_up(seq, precise, corr, port)            Follow_Up: preciseOriginTimestamp at offset 34
//   delay_req(seq, corr, port)                     Delay_Req: originTimestamp 0
//   delay_resp(seq, received, corr, port, asker)   Delay_Resp: receiveTimestamp at 34, requestingPortIdentity at 44
//   put(m, at, n, v) / get(m, at, n)               n octets (1 to 10) at offset at
//   mtype(m), len(m), name(type)                   messageType, messageLength, and the name of a type
// corr is the correctionField: nanoseconds times 65,536, signed (13.3.2.9). port is a PortIdentity: 10 octets.
module eth_ptp_msg;
  function automatic [431:0] put(input [431:0] m, input int at, input int n, input [79:0] v);
    reg [431:0] r;
    r = m;
    for (int i = 0; i < n; i++) r[431 - 8 * (at + i) -: 8] = v[8 * (n - 1 - i) +: 8];
    return r;
  endfunction
  function automatic [79:0] get(input [431:0] m, input int at, input int n);
    reg [79:0] v;
    v = 80'd0;
    for (int i = 0; i < n; i++) v = {v[71:0], m[431 - 8 * (at + i) -: 8]};
    return v;
  endfunction
  function automatic [431:0] header(input [3:0] t, input int octets, input bit two_step, input [63:0] corr, input [79:0] port, input [15:0] seq);
    reg [431:0] m;
    m = 432'd0;
    m = put(m, 0, 1, {76'd0, t});                  // majorSdoId 0, messageType
    m = put(m, 1, 1, 80'h12);                      // minorVersionPTP 1, versionPTP 2 (7.5.4)
    m = put(m, 2, 2, octets);                      // messageLength
    m = put(m, 6, 2, two_step ? 80'h0200 : 80'h0); // flagField: bit 1 of its first octet is twoStepFlag
    m = put(m, 8, 8, {16'd0, corr});               // correctionField
    m = put(m, 20, 10, port);                      // sourcePortIdentity
    m = put(m, 30, 2, {64'd0, seq});               // sequenceId
    return m;                                      // controlField 0; logMessageInterval is left at 0 here
  endfunction
  function automatic [431:0] sync(input bit two_step, input [15:0] seq, input [79:0] origin, input [63:0] corr, input [79:0] port);
    return put(header(4'h0, 44, two_step, corr, port, seq), 34, 10, origin);
  endfunction
  function automatic [431:0] follow_up(input [15:0] seq, input [79:0] precise, input [63:0] corr, input [79:0] port);
    return put(header(4'h8, 44, 1'b0, corr, port, seq), 34, 10, precise);
  endfunction
  function automatic [431:0] delay_req(input [15:0] seq, input [63:0] corr, input [79:0] port);
    return header(4'h1, 44, 1'b0, corr, port, seq);
  endfunction
  function automatic [431:0] delay_resp(input [15:0] seq, input [79:0] received, input [63:0] corr, input [79:0] port, input [79:0] asker);
    return put(put(header(4'h9, 54, 1'b0, corr, port, seq), 34, 10, received), 44, 10, asker);
  endfunction
  function automatic [3:0] mtype(input [431:0] m); return m[427:424]; endfunction
  function automatic int len(input [431:0] m); return int'(m[415:400]); endfunction
  function automatic string name(input [3:0] t);
    case (t)
      4'h0: return "Sync";
      4'h1: return "Delay_Req";
      4'h2: return "Pdelay_Req";
      4'h3: return "Pdelay_Resp";
      4'h8: return "Follow_Up";
      4'h9: return "Delay_Resp";
      4'ha: return "Pdelay_Resp_Follow_Up";
      4'hb: return "Announce";
      4'hc: return "Signaling";
      4'hd: return "Management";
      default: return "reserved";
    endcase
  endfunction
endmodule

Check Yourself

Predict the outputThe bench builds a Delay_Resp and prints the name of its type and its length. What does it print?
`timescale 1ns/1ns
module tb;
  eth_ptp_msg m(); reg [431:0] r;
  initial begin
    r = m.delay_resp(16'd9, 80'd0, 64'd0, 80'd1, 80'd2);
    $display("%s %0d", m.name(m.mtype(r)), m.len(r));
    $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_ptp.sv
`timescale 1ns/1ns
// eth_ptp.sv: clocks and messages of the Precision Time Protocol (read-only). A bench model.

// eth_ptp_clock: a clock that starts off by some nanoseconds and runs a little fast or slow.
//   set(offset_ns, drift_ppb)    at true time 0 the clock is offset_ns ahead; it gains drift_ppb ns a second
//   read(true_ns)                what the clock shows at that true time, in nanoseconds
//   step(delta_ns)               move the clock by delta_ns
//   ts(ns)                       a reading as a PTP Timestamp: {seconds[47:0], nanoseconds[31:0]} (5.3.3)
module eth_ptp_clock;
  longint offset = 0; int drift = 0;
  function automatic void set(input longint offset_ns, input int drift_ppb);
    offset = offset_ns; drift = drift_ppb;
  endfunction
  function automatic longint read(input longint true_ns);
    return true_ns + offset + (true_ns / 1000) * drift / 1000000;
  endfunction
  function automatic void step(input longint delta_ns);
    offset = offset + delta_ns;
  endfunction
  function automatic [79:0] ts(input longint ns);
    reg [47:0] s; reg [31:0] n;
    s = ns / 1000000000; n = ns % 1000000000;
    return {s, n};
  endfunction
endmodule

// eth_ptp_msg: four PTP messages as octets (13.3, 13.6 to 13.8). A message is a vector of 54 octets. Octet 0 is
// bits 431:424 and goes first. A field goes most significant octet first. A message of 44 octets ends in zeros.
//   sync(two_step, seq, origin, corr, port)        Sync: originTimestamp at offset 34
//   follow_up(seq, precise, corr, port)            Follow_Up: preciseOriginTimestamp at offset 34
//   delay_req(seq, corr, port)                     Delay_Req: originTimestamp 0
//   delay_resp(seq, received, corr, port, asker)   Delay_Resp: receiveTimestamp at 34, requestingPortIdentity at 44
//   put(m, at, n, v) / get(m, at, n)               n octets (1 to 10) at offset at
//   mtype(m), len(m), name(type)                   messageType, messageLength, and the name of a type
// corr is the correctionField: nanoseconds times 65,536, signed (13.3.2.9). port is a PortIdentity: 10 octets.
module eth_ptp_msg;
  function automatic [431:0] put(input [431:0] m, input int at, input int n, input [79:0] v);
    reg [431:0] r;
    r = m;
    for (int i = 0; i < n; i++) r[431 - 8 * (at + i) -: 8] = v[8 * (n - 1 - i) +: 8];
    return r;
  endfunction
  function automatic [79:0] get(input [431:0] m, input int at, input int n);
    reg [79:0] v;
    v = 80'd0;
    for (int i = 0; i < n; i++) v = {v[71:0], m[431 - 8 * (at + i) -: 8]};
    return v;
  endfunction
  function automatic [431:0] header(input [3:0] t, input int octets, input bit two_step, input [63:0] corr, input [79:0] port, input [15:0] seq);
    reg [431:0] m;
    m = 432'd0;
    m = put(m, 0, 1, {76'd0, t});                  // majorSdoId 0, messageType
    m = put(m, 1, 1, 80'h12);                      // minorVersionPTP 1, versionPTP 2 (7.5.4)
    m = put(m, 2, 2, octets);                      // messageLength
    m = put(m, 6, 2, two_step ? 80'h0200 : 80'h0); // flagField: bit 1 of its first octet is twoStepFlag
    m = put(m, 8, 8, {16'd0, corr});               // correctionField
    m = put(m, 20, 10, port);                      // sourcePortIdentity
    m = put(m, 30, 2, {64'd0, seq});               // sequenceId
    return m;                                      // controlField 0; logMessageInterval is left at 0 here
  endfunction
  function automatic [431:0] sync(input bit two_step, input [15:0] seq, input [79:0] origin, input [63:0] corr, input [79:0] port);
    return put(header(4'h0, 44, two_step, corr, port, seq), 34, 10, origin);
  endfunction
  function automatic [431:0] follow_up(input [15:0] seq, input [79:0] precise, input [63:0] corr, input [79:0] port);
    return put(header(4'h8, 44, 1'b0, corr, port, seq), 34, 10, precise);
  endfunction
  function automatic [431:0] delay_req(input [15:0] seq, input [63:0] corr, input [79:0] port);
    return header(4'h1, 44, 1'b0, corr, port, seq);
  endfunction
  function automatic [431:0] delay_resp(input [15:0] seq, input [79:0] received, input [63:0] corr, input [79:0] port, input [79:0] asker);
    return put(put(header(4'h9, 54, 1'b0, corr, port, seq), 34, 10, received), 44, 10, asker);
  endfunction
  function automatic [3:0] mtype(input [431:0] m); return m[427:424]; endfunction
  function automatic int len(input [431:0] m); return int'(m[415:400]); endfunction
  function automatic string name(input [3:0] t);
    case (t)
      4'h0: return "Sync";
      4'h1: return "Delay_Req";
      4'h2: return "Pdelay_Req";
      4'h3: return "Pdelay_Resp";
      4'h8: return "Follow_Up";
      4'h9: return "Delay_Resp";
      4'ha: return "Pdelay_Resp_Follow_Up";
      4'hb: return "Announce";
      4'hc: return "Signaling";
      4'hd: return "Management";
      default: return "reserved";
    endcase
  endfunction
endmodule
Conceptt2 − t1 is 100 ns and t4 − t3 is 700 ns. What is the offset from the master?
ConceptWhich message carries t4 to the slave?
ConceptA cable is 50 ns longer on the way down than on the way up. What must be set, and to which value?
ConceptWhat does a transparent clock write into a Sync that passes through it?

Common Mistakes

Wrong Take t1 from the Sync when its twoStepFlag is set.

A two-step Sync carries a rough time or zero.

Fix Use the preciseOriginTimestamp of the Follow_Up with the same sequenceId.

Wrong Subtract only the nanosecond fields of two timestamps.

The seconds may have changed in between.

Fix Turn each timestamp into one number first: seconds times 1,000,000,000 plus nanoseconds.

Wrong Treat the correction field as whole nanoseconds.

It counts in 1/65,536 of a nanosecond.

Fix Divide by 65,536, or keep everything in that unit.

Wrong Expect PTP to find an asymmetric path by itself.

The four timestamps look the same as for a clock that is off.

Fix Measure the asymmetry once and set the delayAsymmetry of the port.

Remember

  • Four timestamps: t1 and t4 from the master's clock, t2 and t3 from the slave's.
  • The delay is half of (t2 − t1) + (t4 − t3). The offset is t2 − t1 less the delay.
  • A Timestamp is 48 bits of seconds and 32 of nanoseconds. Corrections count in 1/65,536 ns.
  • A two-step master sends the exact t1 in a Follow_Up. Transparent clocks report their residence time in the correction field.
  • An asymmetric path leaves half the difference as an error. Only a configured delayAsymmetry removes it.

Practice

Report a problem with this page